content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.vanlam.furnitureshop.data
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import kotlin.random.Random.Default.nextLong
data class Order(
val orderStatus: String = "",
val address: Address = Address(),
val products: List<CartProduct> = emptyList(),
val totalPrice: Float = 0f,
val dateOrder: String = SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH).format(Date()),
val orderId: Long = nextLong(0, 100_000_000_000) + totalPrice.toLong()
) | Furniture_Shop/app/src/main/java/com/vanlam/furnitureshop/data/Order.kt | 607044777 |
package com.vanlam.furnitureshop.helper
fun Float?.getProductPrice(price: Float): Float {
// this --> offerPercent
if (this == null) {
return price
}
val remainingPricePercentage = 1f - this
return remainingPricePercentage * price
} | Furniture_Shop/app/src/main/java/com/vanlam/furnitureshop/helper/PriceCalculator.kt | 118499241 |
package com.vanlam.furnitureadder
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.vanlam.furnitureadder", appContext.packageName)
}
} | Furniture_Shop/furnitureadder/src/androidTest/java/com/vanlam/furnitureadder/ExampleInstrumentedTest.kt | 3961787226 |
package com.vanlam.furnitureadder
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | Furniture_Shop/furnitureadder/src/test/java/com/vanlam/furnitureadder/ExampleUnitTest.kt | 2989879786 |
package com.vanlam.furnitureadder
data class Product(
val id: String,
val name: String,
val category: String,
val price: Float,
val offerPercentage: Float? = null,
val description: String? = null,
val colors: List<Int>? = null,
val sizes: List<String>? = null,
val images: List<String>
)
| Furniture_Shop/furnitureadder/src/main/java/com/vanlam/furnitureadder/Product.kt | 1097007688 |
package com.vanlam.furnitureadder
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Bitmap
import android.icu.number.IntegerWidth
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.lifecycleScope
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import com.google.firebase.storage.ktx.storage
import com.skydoves.colorpickerview.ColorEnvelope
import com.skydoves.colorpickerview.ColorPickerDialog
import com.skydoves.colorpickerview.listeners.ColorEnvelopeListener
import com.vanlam.furnitureadder.databinding.ActivityMainBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
import java.util.UUID
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private var selectedImages = mutableListOf<Uri>()
private var selectedColors = mutableListOf<Int>()
private val productStorage = Firebase.storage.reference
private val firestore = Firebase.firestore
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.buttonColorPicker.setOnClickListener {
ColorPickerDialog.Builder(this)
.setTitle("Product Color")
.setPositiveButton("Select", object : ColorEnvelopeListener {
override fun onColorSelected(envelope: ColorEnvelope?, fromUser: Boolean) {
envelope?.let {
selectedColors.add(it.color)
updateStringColors()
}
}
})
.setNegativeButton("Cancel") { colorPicker, _ ->
colorPicker.dismiss()
}.show()
}
val selectImagesActivityResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == RESULT_OK) {
val intent = result.data
if (intent?.clipData != null) { // Multiple images selected
val count = intent.clipData?.itemCount ?: 0
(0 until count).forEach {
val imageUri = intent.clipData?.getItemAt(it)?.uri
imageUri?.let {
selectedImages.add(it)
}
}
}
else { // Single image selected
val imageUri = intent?.data
imageUri?.let { selectedImages.add(it) }
}
updateStringImages()
}
}
binding.buttonImagesPicker.setOnClickListener {
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
intent.type = "image/*"
selectImagesActivityResult.launch(intent)
}
}
private fun updateStringImages() {
binding.tvSelectedImages.text = selectedImages.size.toString()
}
private fun updateStringColors() {
var colorString = ""
selectedColors.forEach {
colorString = "$colorString ${Integer.toHexString(it)}"
}
binding.tvSelectedColors.text = colorString
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.toolbar_menu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.saveProduct) {
val dataValidation = validateInformation()
if (!dataValidation) {
Toast.makeText(this, "Please check your input information", Toast.LENGTH_SHORT).show()
return false
}
saveProduct()
}
return super.onOptionsItemSelected(item)
}
private fun saveProduct() {
val name = binding.edName.text.trim().toString()
val category = binding.edCategory.text.trim().toString()
val description = binding.edDescription.text.trim().toString()
val price = binding.edPrice.text.toString().toFloat()
val offer = binding.offerPercentage.text.toString().toFloat()
val sizes = getSizeList(binding.edSizes.text.trim().toString())
val imagesByteArray = getImagesByteArray()
val images = mutableListOf<String>()
lifecycleScope.launch(Dispatchers.IO) {
withContext(Dispatchers.Main) {
showLoading()
}
try {
async {
imagesByteArray.forEach {
val id = UUID.randomUUID().toString()
launch {
val imageStorage = productStorage.child("products/images/$id")
val result = imageStorage.putBytes(it).await()
val downloadUrl = result.storage.downloadUrl.await().toString()
images.add(downloadUrl)
}
}
}.await()
} catch (e: Exception) {
e.printStackTrace()
withContext(Dispatchers.Main) {
hideLoading()
}
}
val product = Product(
UUID.randomUUID().toString(),
name, category, price,
if (binding.offerPercentage.text.isEmpty()) null else offer,
if (binding.edDescription.text.isEmpty()) null else description,
if (selectedColors.isEmpty()) null else selectedColors,
sizes, images
)
firestore.collection("products").add(product)
.addOnSuccessListener {
hideLoading()
}
.addOnFailureListener {
hideLoading()
Log.e("MainActivity", it.message.toString())
}
}
}
private fun hideLoading() {
binding.progressBar.visibility = View.INVISIBLE
}
private fun showLoading() {
binding.progressBar.visibility = View.VISIBLE
}
private fun getImagesByteArray(): List<ByteArray> {
val imagesByteArray = mutableListOf<ByteArray>()
selectedImages.forEach {
val stream = ByteArrayOutputStream()
val imageBmp = MediaStore.Images.Media.getBitmap(contentResolver, it)
if (imageBmp.compress(Bitmap.CompressFormat.JPEG, 100, stream)) {
imagesByteArray.add(stream.toByteArray())
}
}
return imagesByteArray
}
private fun getSizeList(stringSize: String): List<String>? {
if (stringSize.isEmpty())
return null
return stringSize.split(",")
}
private fun validateInformation(): Boolean {
if (binding.edName.text.isEmpty())
return false
if (binding.edCategory.text.isEmpty())
return false
if (binding.edPrice.text.isEmpty())
return false
if (selectedImages.isEmpty())
return false
return true
}
} | Furniture_Shop/furnitureadder/src/main/java/com/vanlam/furnitureadder/MainActivity.kt | 2339640316 |
package dev.thecodebuffet.zcash.zip321
import MemoBytes
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import java.util.*
class MemoBytesTests : FunSpec({
test("InitWithString") {
val expectedBase64 = "VGhpcyBpcyBhIHNpbXBsZSBtZW1vLg"
val memoBytes = MemoBytes("This is a simple memo.")
memoBytes.toBase64URL() shouldBe expectedBase64
}
test("InitWithBytes") {
val bytes = byteArrayOf(
0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, 0x20, 0x73, 0x69, 0x6d, 0x70,
0x6c, 0x65, 0x20, 0x6d, 0x65, 0x6d, 0x6f, 0x2e
)
val expectedBase64 = "VGhpcyBpcyBhIHNpbXBsZSBtZW1vLg"
val memo = MemoBytes(bytes)
memo.toBase64URL() shouldBe expectedBase64
}
test("UnicodeMemo") {
val memoUTF8Text = "This is a unicode memo ✨🦄🏆🎉"
val expectedBase64 = "VGhpcyBpcyBhIHVuaWNvZGUgbWVtbyDinKjwn6aE8J-PhvCfjok"
val memo = MemoBytes(memoUTF8Text)
memo.toBase64URL() shouldBe expectedBase64
MemoBytes.fromBase64URL(expectedBase64).data.contentEquals(memo.data) shouldBe true
MemoBytes.fromBase64URL(expectedBase64).equals(memo) shouldBe true
}
test("InitWithStringThrows") {
shouldThrow<MemoBytes.MemoError.MemoEmpty> {
MemoBytes("")
}
shouldThrow<MemoBytes.MemoError.MemoTooLong> {
MemoBytes("a".repeat(513))
}
}
test("InitWithBytesThrows") {
shouldThrow<MemoBytes.MemoError.MemoEmpty> {
MemoBytes(byteArrayOf())
}
shouldThrow<MemoBytes.MemoError.MemoTooLong> {
MemoBytes(ByteArray(MemoBytes.maxLength + 1))
}
}
})
| zcash-kotlin-payment-uri/lib/src/test/kotlin/dev/thecodebuffet/zcash/zip321/MemoBytesTests.kt | 2873032305 |
package dev.thecodebuffet.zcash.zip321
import dev.thecodebuffet.zcash.zip321.extensions.qcharDecode
import dev.thecodebuffet.zcash.zip321.extensions.qcharEncoded
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.should
import io.kotest.matchers.shouldBe
class EncodingTests : FunSpec({
test("qcharEncoded string contains allowed characters only") {
val message = "sk8:forever@!"
message.qcharEncoded() shouldBe message
}
test("qcharEncoded string has percent-encoded disallowed characters") {
mapOf(
"Thank you for your purchase" to "Thank%20you%20for%20your%20purchase",
"Use Coupon [ZEC4LIFE] to get a 20% discount on your next purchase!!" to
"Use%20Coupon%20%5BZEC4LIFE%5D%20to%20get%20a%2020%25%20discount%20on%20your%20next%20purchase!!",
"Order #321" to "Order%20%23321",
"Your Ben & Jerry's Order" to "Your%20Ben%20%26%20Jerry's%20Order",
" " to "%20",
"\"" to "%22",
"#" to "%23",
"%" to "%25",
"&" to "%26",
"/" to "%2F",
"<" to "%3C",
"=" to "%3D",
">" to "%3E",
"?" to "%3F",
"[" to "%5B",
"\\" to "%5C",
"]" to "%5D",
"^" to "%5E",
"`" to "%60",
"{" to "%7B",
"|" to "%7C",
"}" to "%7D"
).forEach { (input, expected) ->
input.qcharEncoded() shouldBe expected
}
}
test("unallowed characters are escaped") {
val unallowedCharacters = listOf(
" ", "\"", "#", "%", "&", "/", "<", "=", ">", "?", "[", "\\", "]", "^", "`", "{", "|", "}"
)
unallowedCharacters.forEach { unallowed ->
val qcharEncoded = unallowed.qcharEncoded()
qcharEncoded should {
it != null && it.contains("%")
}
}
(0x00..0x1F).map { it.toChar().toString() }.forEach { controlChar ->
val qcharEncoded = controlChar.qcharEncoded()
qcharEncoded should {
it != null && it.contains("%")
}
}
}
test("qcharEncodedText decodes properly") {
mapOf(
"Thank%20you%20for%20your%20purchase" to "Thank you for your purchase",
"Use%20Coupon%20%5BZEC4LIFE%5D%20to%20get%20a%2020%25%20discount%20on%20your%20next%20purchase!!" to
"Use Coupon [ZEC4LIFE] to get a 20% discount on your next purchase!!",
"Order%20%23321" to "Order #321",
"Your%20Ben%20%26%20Jerry's%20Order" to "Your Ben & Jerry's Order",
"%20" to " ",
"%22" to "\"",
"%23" to "#",
"%25" to "%",
"%26" to "&",
"%2F" to "/",
"%3C" to "<",
"%3D" to "=",
"%3E" to ">",
"%3F" to "?",
"%5B" to "[",
"%5C" to "\\",
"%5D" to "]",
"%5E" to "^",
"%60" to "`",
"%7B" to "{",
"%7C" to "|",
"%7D" to "}"
).forEach { (input, expected) ->
input.qcharDecode() shouldBe expected
}
}
})
| zcash-kotlin-payment-uri/lib/src/test/kotlin/dev/thecodebuffet/zcash/zip321/EncodingTests.kt | 2615517456 |
package dev.thecodebuffet.zcash.zip321
import NonNegativeAmount
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FreeSpec
import io.kotest.matchers.shouldBe
import java.math.BigDecimal
class AmountTests : FreeSpec({
"Amount tests" - {
"testAmountStringDecimals" {
NonNegativeAmount(BigDecimal("123.456")).toString() shouldBe "123.456"
"${NonNegativeAmount(BigDecimal("123.456"))}" shouldBe "123.456"
}
"testAmountTrailing" {
NonNegativeAmount(BigDecimal("50.000")).toString() shouldBe "50"
}
"testAmountLeadingZeros" {
NonNegativeAmount(BigDecimal("0000.5")).toString() shouldBe "0.5"
}
"testAmountMaxDecimals" {
NonNegativeAmount(BigDecimal("0.12345678")).toString() shouldBe "0.12345678"
}
"testAmountThrowsIfMaxSupply" {
shouldThrow<NonNegativeAmount.AmountError> {
NonNegativeAmount(BigDecimal("21000000.00000001")).toString()
}
}
"testAmountThrowsIfNegativeAmount" {
shouldThrow<NonNegativeAmount.AmountError> {
NonNegativeAmount(BigDecimal("-1")).toString()
}
}
// Text Conversion Tests
"testAmountThrowsIfTooManyFractionalDigits" {
shouldThrow<NonNegativeAmount.AmountError.TooManyFractionalDigits> {
NonNegativeAmount("0.123456789")
}
}
"testAmountParsesMaxFractionalDigits" {
NonNegativeAmount("0.12345678").toString() shouldBe NonNegativeAmount(BigDecimal("0.12345678")).toString()
}
"testAmountParsesMaxAmount" {
NonNegativeAmount("21000000").toString() shouldBe NonNegativeAmount(BigDecimal("21000000")).toString()
}
}
})
| zcash-kotlin-payment-uri/lib/src/test/kotlin/dev/thecodebuffet/zcash/zip321/AmountTests.kt | 687036456 |
package dev.thecodebuffet.zcash.zip321.parser
import MemoBytes
import NonNegativeAmount
import OtherParam
import Payment
import RecipientAddress
import com.copperleaf.kudzu.parser.ParserContext
import dev.thecodebuffet.zcash.zip321.ZIP321
import dev.thecodebuffet.zcash.zip321.extensions.qcharDecode
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.assertions.throwables.shouldThrowAny
import io.kotest.core.spec.style.FreeSpec
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import java.math.BigDecimal
class SubParserTests : FreeSpec({
"paramindex subparser" - {
"parses non-zero single digit" {
Parser(null).parameterIndexParser
.parse(ParserContext.fromString("1")).first.value shouldBe 1u
Parser(null).parameterIndexParser
.parse(ParserContext.fromString("9")).first.value shouldBe 9u
}
"fails on zero single digit" {
shouldThrowAny {
Parser(null).parameterIndexParser
.parse(ParserContext.fromString("0"))
}
}
"parses many digits" {
Parser(null).parameterIndexParser
.parse(ParserContext.fromString("12")).first.value shouldBe 12u
Parser(null).parameterIndexParser
.parse(ParserContext.fromString("123")).first.value shouldBe 123u
}
"fails on leading zero many digits" - {
shouldThrowAny {
Parser(null).parameterIndexParser
.parse(ParserContext.fromString("090"))
}
}
"fails on too many digits" - {
shouldThrowAny {
Parser(null).parameterIndexParser
.parse(ParserContext.fromString("19999"))
}
}
}
"Optionally IndexedParameter Name parsing" - {
"parses a non-indexed parameter" {
Parser(null).optionallyIndexedParamName
.parse(
ParserContext.fromString("address")
)
.first
.value shouldBe Pair<String, UInt?>("address", null)
}
"parses a indexed parameter" {
Parser(null).optionallyIndexedParamName
.parse(
ParserContext.fromString("address.123")
)
.first
.value shouldBe Pair<String, UInt?>("address", 123u)
}
"fails to parse a zero-index parameter" {
shouldThrowAny {
Parser(null).optionallyIndexedParamName
.parse(
ParserContext.fromString("address.0")
)
}
}
"fails to parse leading zero parameter" {
shouldThrowAny {
Parser(null).optionallyIndexedParamName
.parse(
ParserContext.fromString("address.023")
)
}
}
"fails to parse a parameter with an index greater than 9999" {
shouldThrowAny {
Parser(null).optionallyIndexedParamName
.parse(
ParserContext.fromString("address.19999")
)
}
}
"fails to parse a paramname with invalid characters" {
shouldThrowAny {
Parser(null).optionallyIndexedParamName
.parse(
ParserContext.fromString("add[ress[1].1")
)
}
}
}
"Query and Key parser" - {
"parses a query key with no index" {
val parsedQueryParam = Parser(null).queryKeyAndValueParser
.parse(
ParserContext.fromString(
"address=tmEZhbWHTpdKMw5it8YDspUXSMGQyFwovpU"
)
).first.value
parsedQueryParam.first.first shouldBe "address"
parsedQueryParam.first.second shouldBe null
parsedQueryParam.second shouldBe "tmEZhbWHTpdKMw5it8YDspUXSMGQyFwovpU"
}
"parses a query key with a valid index" {
val parsedQueryParam = Parser(null).queryKeyAndValueParser
.parse(
ParserContext.fromString(
"address.123=tmEZhbWHTpdKMw5it8YDspUXSMGQyFwovpU"
)
).first.value
parsedQueryParam.first.first shouldBe "address"
parsedQueryParam.first.second shouldBe 123u
parsedQueryParam.second shouldBe "tmEZhbWHTpdKMw5it8YDspUXSMGQyFwovpU"
}
"fails to parse a query key with invalid index" {
shouldThrowAny {
Parser(null).queryKeyAndValueParser
.parse(
ParserContext.fromString(
"address.00123=tmEZhbWHTpdKMw5it8YDspUXSMGQyFwovpU"
)
)
}
}
}
"query key parsing tests" - {
"parser catches query qcharencoded values" {
Parser(null).queryKeyAndValueParser
.parse(
ParserContext.fromString("message.1=Thank%20You%20For%20Your%20Purchase")
)
.first
.value shouldBe Pair(Pair("message", 1u), "Thank%20You%20For%20Your%20Purchase")
}
"Zcash parameter creates valid amount" {
val query = "amount"
val value = "1.00020112"
val index = 1u
val input = Pair<Pair<String, UInt?>, String>(Pair(query, index), value)
Parser(null).zcashParameter(input) shouldBe
IndexedParameter(1u, Param.Amount(amount = NonNegativeAmount(value)))
}
"Zcash parameter creates valid message" {
val query = "message"
val index = 1u
val value = "Thank%20You%20For%20Your%20Purchase"
val input = Pair<Pair<String, UInt?>, String>(Pair(query, index), value)
val qcharDecodedValue = value.qcharDecode() ?: ""
qcharDecodedValue shouldNotBe ""
Parser(null).zcashParameter(input) shouldBe
IndexedParameter(1u, Param.Message(qcharDecodedValue))
}
"Zcash parameter creates valid label" {
val query = "label"
val index = 1u
val value = "Thank%20You%20For%20Your%20Purchase"
val input = Pair<Pair<String, UInt?>, String>(Pair(query, index), value)
val qcharDecodedValue = value.qcharDecode() ?: ""
qcharDecodedValue shouldNotBe ""
Parser(null).zcashParameter(input) shouldBe
IndexedParameter(1u, Param.Label(qcharDecodedValue))
}
"Zcash parameter creates valid memo" {
val query = "memo"
val index = 99u
val value = "VGhpcyBpcyBhIHNpbXBsZSBtZW1vLg"
val input = Pair<Pair<String, UInt?>, String>(Pair(query, index), value)
val memo = MemoBytes.fromBase64URL(value)
Parser(null).zcashParameter(input) shouldBe
IndexedParameter(99u, Param.Memo(memo))
}
"Zcash parameter creates valid memo that contains UTF-8 characters" {
val query = "memo"
val index = 99u
val value = "VGhpcyBpcyBhIHVuaWNvZGUgbWVtbyDinKjwn6aE8J-PhvCfjok"
val input = Pair<Pair<String, UInt?>, String>(Pair(query, index), value)
Parser(null).queryKeyAndValueParser.parse(
ParserContext.fromString("memo.99=VGhpcyBpcyBhIHVuaWNvZGUgbWVtbyDinKjwn6aE8J-PhvCfjok")
).first.value shouldBe input
}
"Zcash parameter creates safely ignored other parameter" {
val query = "future-binary-format"
val value = "VGhpcyBpcyBhIHNpbXBsZSBtZW1vLg"
val input = Pair<Pair<String, UInt?>, String>(Pair(query, null), value)
Parser(null).zcashParameter(input) shouldBe
IndexedParameter(0u, Param.Other(query, value))
}
}
"Parses many parameters in a row" - {
"Index parameters are parsed with no leading address" {
val remainingString = "?address=ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez&amount=1&memo=VGhpcyBpcyBhIHNpbXBsZSBtZW1vLg&message=Thank%20you%20for%20your%20purchase"
val recipient =
RecipientAddress("ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez")
val expected = listOf(
IndexedParameter(0u, Param.Address(recipient)),
IndexedParameter(0u, Param.Amount(NonNegativeAmount("1"))),
IndexedParameter(0u, Param.Memo(MemoBytes.fromBase64URL("VGhpcyBpcyBhIHNpbXBsZSBtZW1vLg"))),
IndexedParameter(0u, Param.Message("Thank you for your purchase"))
)
Parser(null).parseParameters(ParserContext.fromString(remainingString), null) shouldBe expected
}
}
"Index parameters are parsed with leading address" {
val remainingString = "?amount=1&memo=VGhpcyBpcyBhIHNpbXBsZSBtZW1vLg&message=Thank%20you%20for%20your%20purchase"
val recipient =
RecipientAddress("ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez")
val expected = listOf(
IndexedParameter(0u, Param.Address(recipient)),
IndexedParameter(0u, Param.Amount(NonNegativeAmount("1"))),
IndexedParameter(0u, Param.Memo(MemoBytes.fromBase64URL("VGhpcyBpcyBhIHNpbXBsZSBtZW1vLg"))),
IndexedParameter(0u, Param.Message("Thank you for your purchase"))
)
val leadingAddress = IndexedParameter(0u, Param.Address(recipient))
Parser(null).parseParameters(ParserContext.fromString(remainingString), leadingAddress) shouldBe expected
}
"Duplicate Params are caught" - {
"Duplicate other params are detected" {
val params = listOf(
Param.Address(RecipientAddress("ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez")),
Param.Amount(NonNegativeAmount("1")),
Param.Message("Thanks"),
Param.Label("payment"),
Param.Other("future", "is awesome")
)
params.hasDuplicateParam(Param.Other("future", "is dystopic")) shouldBe true
}
"Duplicate address params are detected" {
val params = listOf(
Param.Address(RecipientAddress("ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez")),
Param.Amount(NonNegativeAmount("1")),
Param.Message("Thanks"),
Param.Label("payment"),
Param.Other("future", "is awesome")
)
params.hasDuplicateParam(Param.Address(RecipientAddress("ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez"))) shouldBe true
}
}
"Payment can be created from uniquely indexed Params" - {
"Payment is created from indexed parameters" {
val recipient = RecipientAddress("ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez")
?: error("Failed to create recipient")
val params = listOf(
Param.Address(recipient),
Param.Amount(NonNegativeAmount("1")),
Param.Message("Thanks"),
Param.Label("payment"),
Param.Other("future", "is awesome")
)
val payment = Payment.fromUniqueIndexedParameters(index = 1u, parameters = params)
payment shouldBe Payment(
recipientAddress = recipient,
nonNegativeAmount = NonNegativeAmount("1"),
memo = null,
label = "payment",
message = "Thanks",
otherParams = listOf(OtherParam("future", "is awesome"))
)
}
"duplicate addresses are detected" {
val shieldedRecipient =
RecipientAddress("ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez")
val duplicateAddressParams: List<IndexedParameter> = listOf(
IndexedParameter(index = 0u, param = Param.Address(shieldedRecipient)),
IndexedParameter(index = 0u, param = Param.Amount(NonNegativeAmount(value = BigDecimal(1)))),
IndexedParameter(index = 0u, param = Param.Message("Thanks")),
IndexedParameter(index = 0u, param = Param.Memo(MemoBytes.fromBase64URL("VGhpcyBpcyBhIHNpbXBsZSBtZW1vLg"))),
IndexedParameter(index = 0u, param = Param.Label("payment")),
IndexedParameter(index = 0u, param = Param.Address(shieldedRecipient)),
IndexedParameter(index = 0u, param = Param.Other("future", "is awesome"))
)
shouldThrow<ZIP321.Errors> {
Parser(null).mapToPayments(duplicateAddressParams)
} shouldBe ZIP321.Errors.DuplicateParameter("address", null)
}
"duplicate amounts are detected" {
val shieldedRecipient =
RecipientAddress("ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez")
val duplicateAmountParams: List<IndexedParameter> = listOf(
IndexedParameter(index = 0u, param = Param.Address(shieldedRecipient)),
IndexedParameter(index = 0u, param = Param.Amount(NonNegativeAmount(value = BigDecimal(1)))),
IndexedParameter(index = 0u, param = Param.Message("Thanks")),
IndexedParameter(index = 0u, param = Param.Memo(MemoBytes.fromBase64URL("VGhpcyBpcyBhIHNpbXBsZSBtZW1vLg"))),
IndexedParameter(index = 0u, param = Param.Label("payment")),
IndexedParameter(index = 0u, param = Param.Amount(NonNegativeAmount(value = BigDecimal(2)))),
IndexedParameter(index = 0u, param = Param.Other("future", "is awesome"))
)
shouldThrow<ZIP321.Errors> {
Parser(null).mapToPayments(duplicateAmountParams)
} shouldBe ZIP321.Errors.DuplicateParameter("amount", null)
}
"duplicate message are detected" {
val shieldedRecipient =
RecipientAddress("ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez")
val duplicateParams: List<IndexedParameter> = listOf(
IndexedParameter(index = 0u, param = Param.Address(shieldedRecipient)),
IndexedParameter(index = 0u, param = Param.Amount(NonNegativeAmount(value = BigDecimal(1)))),
IndexedParameter(index = 0u, param = Param.Message("Thanks")),
IndexedParameter(index = 0u, param = Param.Memo(MemoBytes.fromBase64URL("VGhpcyBpcyBhIHNpbXBsZSBtZW1vLg"))),
IndexedParameter(index = 0u, param = Param.Message("Thanks")),
IndexedParameter(index = 0u, param = Param.Label("payment")),
IndexedParameter(index = 0u, param = Param.Amount(NonNegativeAmount(value = BigDecimal(2)))),
IndexedParameter(index = 0u, param = Param.Other("future", "is awesome"))
)
shouldThrow<ZIP321.Errors> {
Parser(null).mapToPayments(duplicateParams)
} shouldBe ZIP321.Errors.DuplicateParameter("message", null)
}
"duplicate memos are detected" {
val shieldedRecipient =
RecipientAddress("ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez")
val duplicateParams: List<IndexedParameter> = listOf(
IndexedParameter(index = 0u, param = Param.Address(shieldedRecipient)),
IndexedParameter(index = 0u, param = Param.Memo(MemoBytes.fromBase64URL("VGhpcyBpcyBhIHNpbXBsZSBtZW1vLg"))),
IndexedParameter(index = 0u, param = Param.Amount(NonNegativeAmount(value = BigDecimal(1)))),
IndexedParameter(index = 0u, param = Param.Message("Thanks")),
IndexedParameter(index = 0u, param = Param.Memo(MemoBytes.fromBase64URL("VGhpcyBpcyBhIHNpbXBsZSBtZW1vLg"))),
IndexedParameter(index = 0u, param = Param.Label("payment")),
IndexedParameter(index = 0u, param = Param.Other("future", "is awesome"))
)
shouldThrow<ZIP321.Errors> {
Parser(null).mapToPayments(duplicateParams)
} shouldBe ZIP321.Errors.DuplicateParameter("memo", null)
}
"duplicate other params are detected" {
val shieldedRecipient =
RecipientAddress("ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez")
val duplicateParams: List<IndexedParameter> = listOf(
IndexedParameter(index = 0u, param = Param.Address(shieldedRecipient)),
IndexedParameter(index = 0u, param = Param.Label("payment")),
IndexedParameter(index = 0u, param = Param.Amount(NonNegativeAmount(value = BigDecimal(1)))),
IndexedParameter(index = 0u, param = Param.Message("Thanks")),
IndexedParameter(index = 0u, param = Param.Other("future", "is dystopian")),
IndexedParameter(index = 0u, param = Param.Memo(MemoBytes.fromBase64URL("VGhpcyBpcyBhIHNpbXBsZSBtZW1vLg"))),
IndexedParameter(index = 0u, param = Param.Other("future", "is awesome"))
)
shouldThrow<ZIP321.Errors> {
Parser(null).mapToPayments(duplicateParams)
} shouldBe ZIP321.Errors.DuplicateParameter("future", null)
}
}
})
| zcash-kotlin-payment-uri/lib/src/test/kotlin/dev/thecodebuffet/zcash/zip321/parser/SubParserTests.kt | 4061379704 |
package dev.thecodebuffet.zcash.zip321.parser
import RecipientAddress
import com.copperleaf.kudzu.parser.ParserContext
import io.kotest.core.spec.style.FreeSpec
import io.kotest.matchers.shouldBe
class ParserTests : FreeSpec({
"Parser detects leading addresses" - {
"detects single recipient with leading address" {
val validURI = "zcash:ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez"
val (node, remainingText) = Parser(null).maybeLeadingAddressParse.parse(
ParserContext.fromString(validURI)
)
val recipient =
RecipientAddress("ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez", null)
remainingText.isEmpty() shouldBe true
node.value shouldBe IndexedParameter(0u, Param.Address(recipient))
}
"detects leading address with other params" {
val validURI = "zcash:ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez?amount=1.0001"
val (node, remainingText) = Parser(null).maybeLeadingAddressParse.parse(
ParserContext.fromString(validURI)
)
val recipient =
RecipientAddress("ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez", null)
remainingText.isEmpty() shouldBe false
node.value shouldBe IndexedParameter(0u, Param.Address(recipient))
}
"returns null when no leading address is present" {
val validURI = "zcash:?amount=1.0001&address=ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez"
val (node, remainingText) = Parser(null).maybeLeadingAddressParse.parse(
ParserContext.fromString(validURI)
)
remainingText.isEmpty() shouldBe false
node.value shouldBe null
}
}
})
| zcash-kotlin-payment-uri/lib/src/test/kotlin/dev/thecodebuffet/zcash/zip321/parser/ParserTests.kt | 3307937808 |
package dev.thecodebuffet.zcash.zip321
import MemoBytes
import NonNegativeAmount
import Payment
import RecipientAddress
import io.kotest.core.spec.style.FreeSpec
import io.kotest.matchers.shouldBe
class RendererTests : FreeSpec({
"Amount Tests" - {
"Amount parameter is rendered with no `paramIndex`" {
val expected = "amount=123.456"
val nonNegativeAmount = NonNegativeAmount(123.456.toBigDecimal())
Render.parameter(nonNegativeAmount, null) shouldBe expected
}
"Amount parameter is rendered with `paramIndex`" {
val expected = "amount.1=123.456"
val nonNegativeAmount = NonNegativeAmount(123.456.toBigDecimal())
Render.parameter(nonNegativeAmount, 1u) shouldBe expected
}
"Address parameter is rendered with no `paramIndex`" {
val expected = "address=tmEZhbWHTpdKMw5it8YDspUXSMGQyFwovpU"
val address0 = "tmEZhbWHTpdKMw5it8YDspUXSMGQyFwovpU"
val recipient0 = RecipientAddress(value = address0)
Render.parameter(recipient0, null) shouldBe expected
}
"Address parameter is rendered with `paramIndex`" {
val expected = "address.1=tmEZhbWHTpdKMw5it8YDspUXSMGQyFwovpU"
val address0 = "tmEZhbWHTpdKMw5it8YDspUXSMGQyFwovpU"
val recipient0 = RecipientAddress(value = address0)
Render.parameter(recipient0, 1u) shouldBe expected
}
"Message parameter is rendered with no `paramIndex`" {
val expected = "message=Thank%20you%20for%20your%20purchase"
Render.parameterMessage(message = "Thank you for your purchase", index = null) shouldBe expected
}
"Message parameter is rendered with `paramIndex`" {
val expected = "message.10=Thank%20you%20for%20your%20purchase"
Render.parameterMessage(message = "Thank you for your purchase", index = 10u) shouldBe expected
}
"Label parameter is rendered with no `paramIndex`" {
val expected = "label=Lunch%20Tab"
Render.parameterLabel(label = "Lunch Tab", index = null) shouldBe expected
}
"Label parameter is rendered with `paramIndex`" {
val expected = "label.1=Lunch%20Tab"
Render.parameterLabel(label = "Lunch Tab", index = 1u) shouldBe expected
}
"required future parameter is rendered with no `paramIndex`" {
val expected = "req-futureParam=Future%20is%20Z"
Render.parameter(label = "req-futureParam", value = "Future is Z", index = null) shouldBe expected
}
"required future parameter is rendered with `paramIndex" {
val expected = "req-futureParam.1=Future%20is%20Z"
Render.parameter(label = "req-futureParam", value = "Future is Z", index = 1u) shouldBe expected
}
"Memo parameter is rendered with no `paramIndex`" {
val expected = "memo=VGhpcyBpcyBhIHVuaWNvZGUgbWVtbyDinKjwn6aE8J-PhvCfjok"
val memo = MemoBytes("This is a unicode memo ✨🦄🏆🎉")
Render.parameter(memo, null) shouldBe expected
}
"Memo parameter is rendered with `paramIndex`" {
val expected = "memo.10=VGhpcyBpcyBhIHVuaWNvZGUgbWVtbyDinKjwn6aE8J-PhvCfjok"
val memo = MemoBytes("This is a unicode memo ✨🦄🏆🎉")
Render.parameter(memo, 10u) shouldBe expected
}
// MARK: Payment
"Payment is rendered with no `paramIndex`" {
val expected = "address=tmEZhbWHTpdKMw5it8YDspUXSMGQyFwovpU&amount=123.456"
val address0 = "tmEZhbWHTpdKMw5it8YDspUXSMGQyFwovpU"
val recipient0 = RecipientAddress(value = address0)
val payment0 = Payment(
recipientAddress = recipient0,
nonNegativeAmount = NonNegativeAmount(123.456.toBigDecimal()),
memo = null,
label = null,
message = null,
otherParams = null
)
Render.payment(payment0, null) shouldBe expected
}
"Payment is rendered with `paramIndex`" {
val expected =
"address.1=ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez&amount.1=0.789&memo.1=VGhpcyBpcyBhIHVuaWNvZGUgbWVtbyDinKjwn6aE8J-PhvCfjok"
val address1 = "ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez"
val recipient1 = RecipientAddress(value = address1)
val payment1 = Payment(
recipientAddress = recipient1,
nonNegativeAmount = NonNegativeAmount(0.789.toBigDecimal()),
memo = MemoBytes("This is a unicode memo ✨🦄🏆🎉"),
label = null,
message = null,
otherParams = null
)
Render.payment(payment1, 1u) shouldBe expected
}
"Payment renders with no `paramIndex` and no address label" {
val expected = "tmEZhbWHTpdKMw5it8YDspUXSMGQyFwovpU?amount=123.456"
val address0 = "tmEZhbWHTpdKMw5it8YDspUXSMGQyFwovpU"
val recipient0 = RecipientAddress(value = address0)
val payment0 = Payment(
recipientAddress = recipient0,
nonNegativeAmount = NonNegativeAmount(123.456.toBigDecimal()),
memo = null,
label = null,
message = null,
otherParams = null
)
Render.payment(payment0, null, omittingAddressLabel = true) shouldBe expected
}
"Payment renderer ignores label omission when index is provided" {
val expected =
"address.1=ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez&amount.1=0.789&memo.1=VGhpcyBpcyBhIHVuaWNvZGUgbWVtbyDinKjwn6aE8J-PhvCfjok"
val address1 = "ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez"
val recipient1 = RecipientAddress(value = address1)
val payment1 = Payment(
recipientAddress = recipient1,
nonNegativeAmount = NonNegativeAmount(0.789.toBigDecimal()),
memo = MemoBytes("This is a unicode memo ✨🦄🏆🎉"),
label = null,
message = null,
otherParams = null
)
Render.payment(payment1, 1u, omittingAddressLabel = true) shouldBe expected
}
}
})
| zcash-kotlin-payment-uri/lib/src/test/kotlin/dev/thecodebuffet/zcash/zip321/RendererTests.kt | 3312392837 |
package dev.thecodebuffet.zcash.zip321
import RecipientAddress
import io.kotest.assertions.throwables.shouldNotThrow
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
class RecipientTests : FunSpec({
test("Recipient init throws when validation fails") {
shouldThrow<RecipientAddress.RecipientAddressError.InvalidRecipient> {
RecipientAddress("asdf") { _ -> false }
}
}
test("Recipient init does not throw when validation does not fail") {
shouldNotThrow<RecipientAddress.RecipientAddressError.InvalidRecipient> {
val expected = "asdf"
val recipient = RecipientAddress(expected) { _ -> true }
recipient.value shouldBe expected
}
}
test("Recipient init should not throw when no validation provided") {
shouldNotThrow<RecipientAddress.RecipientAddressError.InvalidRecipient> {
val expected = "asdf"
val recipient: RecipientAddress = RecipientAddress(expected)
recipient.value shouldBe expected
}
}
})
| zcash-kotlin-payment-uri/lib/src/test/kotlin/dev/thecodebuffet/zcash/zip321/RecipientTests.kt | 2739142968 |
package dev.thecodebuffet.zcash.zip321
import MemoBytes
import NonNegativeAmount
import Payment
import PaymentRequest
import RecipientAddress
import io.kotest.assertions.fail
import io.kotest.core.spec.style.FreeSpec
import io.kotest.matchers.shouldBe
import java.math.BigDecimal
/* ktlint-disable line-length */
class ZcashSwiftPaymentUriTests : FreeSpec({
"test that a single recipient payment request is generated" {
val expected =
"zcash:ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez"
val recipient =
RecipientAddress("ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez")
ZIP321.request(recipient) shouldBe expected
}
"test that a single payment request is generated" {
val expected =
"zcash:ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez?amount=1&memo=VGhpcyBpcyBhIHNpbXBsZSBtZW1vLg&message=Thank%20you%20for%20your%20purchase"
val recipient =
RecipientAddress("ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez")
val payment = Payment(
recipientAddress = recipient,
nonNegativeAmount = NonNegativeAmount(BigDecimal(1)),
memo = MemoBytes("This is a simple memo."),
label = null,
message = "Thank you for your purchase",
otherParams = null
)
val paymentRequest = PaymentRequest(payments = listOf(payment))
ZIP321.uriString(
paymentRequest,
ZIP321.FormattingOptions.UseEmptyParamIndex(omitAddressLabel = true)
) shouldBe expected
ZIP321.request(
payment,
ZIP321.FormattingOptions.UseEmptyParamIndex(omitAddressLabel = true)
) shouldBe expected
}
"test that multiple payments can be put in one request starting with no paramIndex" {
val expected =
"zcash:?address=tmEZhbWHTpdKMw5it8YDspUXSMGQyFwovpU&amount=123.456&address.1=ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez&amount.1=0.789&memo.1=VGhpcyBpcyBhIHVuaWNvZGUgbWVtbyDinKjwn6aE8J-PhvCfjok"
val recipient0 = RecipientAddress("tmEZhbWHTpdKMw5it8YDspUXSMGQyFwovpU")
val payment0 = Payment(
recipientAddress = recipient0,
nonNegativeAmount = NonNegativeAmount.create(BigDecimal(123.456)),
memo = null,
label = null,
message = null,
otherParams = null
)
val recipient1 =
RecipientAddress("ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez")
val payment1 = Payment(
recipientAddress = recipient1,
nonNegativeAmount = NonNegativeAmount.create(BigDecimal(0.789)),
memo = MemoBytes("This is a unicode memo ✨🦄🏆🎉"),
label = null,
message = null,
otherParams = null
)
val paymentRequest = PaymentRequest(payments = listOf(payment0, payment1))
ZIP321.uriString(paymentRequest, ZIP321.FormattingOptions.UseEmptyParamIndex(omitAddressLabel = false)) shouldBe expected
}
"test that multiple payments can be parsed" {
val validURI =
"zcash:?address=tmEZhbWHTpdKMw5it8YDspUXSMGQyFwovpU&amount=123.456&address.1=ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez&amount.1=0.789&memo.1=VGhpcyBpcyBhIHVuaWNvZGUgbWVtbyDinKjwn6aE8J-PhvCfjok"
val recipient0 = RecipientAddress("tmEZhbWHTpdKMw5it8YDspUXSMGQyFwovpU")
val payment0 = Payment(
recipientAddress = recipient0,
nonNegativeAmount = NonNegativeAmount.create(BigDecimal(123.456)),
memo = null,
label = null,
message = null,
otherParams = null
)
val recipient1 =
RecipientAddress("ztestsapling10yy2ex5dcqkclhc7z7yrnjq2z6feyjad56ptwlfgmy77dmaqqrl9gyhprdx59qgmsnyfska2kez")
val payment1 = Payment(
recipientAddress = recipient1,
nonNegativeAmount = NonNegativeAmount.create(BigDecimal(0.789)),
memo = MemoBytes("This is a unicode memo ✨🦄🏆🎉"),
label = null,
message = null,
otherParams = null
)
val paymentRequest = PaymentRequest(payments = listOf(payment0, payment1))
when (val parsedRequest = ZIP321.request(validURI, null)) {
is ZIP321.ParserResult.SingleAddress -> fail("expected Request. got $parsedRequest")
is ZIP321.ParserResult.Request -> {
parsedRequest.paymentRequest shouldBe paymentRequest
}
}
}
})
| zcash-kotlin-payment-uri/lib/src/test/kotlin/dev/thecodebuffet/zcash/zip321/ZcashSwiftPaymentUriTests.kt | 1274427992 |
/*
* This Kotlin source file was generated by the Gradle 'init' task.
*/
package dev.thecodebuffet.zcash.zip321
import Payment
import PaymentRequest
import RecipientAddress
import dev.thecodebuffet.zcash.zip321.parser.Parser
/**
* ZIP-321 object for handling formatting options.
*/
object ZIP321 {
sealed class Errors : Exception() {
/**
* There's a payment exceeding the max supply as [ZIP-321](https://zips.z.cash/zip-0321) forbids.
*/
data class AmountExceededSupply(val value: UInt) : Errors()
/**
* There's a payment that is less than a decimal zatoshi as [ZIP-321](https://zips.z.cash/zip-0321) forbids.
*/
data class AmountTooSmall(val value: UInt) : Errors()
/**
* Parsing encountered a duplicate [ZIP-321](https://zips.z.cash/zip-0321) URI parameter for the returned payment index.
*/
data class DuplicateParameter(val parameter: String, val index: UInt?) : Errors()
/**
* An invalid address query parameter was found. paramIndex is provided in the associated value.
*/
data class InvalidAddress(val index: UInt?) : Errors()
/**
* A memo field in the ZIP 321 URI was not properly base-64 encoded according to [ZIP-321](https://zips.z.cash/zip-0321)
*/
object InvalidBase64 : Errors()
/**
* not even a Zcash URI
*/
object InvalidURI : Errors()
/**
* A memo value exceeded 512 bytes in length or could not be interpreted as a UTF-8 string
* when using a valid UTF-8 lead byte
*/
data class MemoBytesError(val error: Throwable, val index: UInt?) : Errors()
/**
* The [ZIP-321](https://zips.z.cash/zip-0321) request included more payments than can be created within a single Zcash transaction.
* The associated value is the number of payments in the request.
*/
data class TooManyPayments(val value: Long) : Errors()
/**
* The payment at the associated value attempted to include a memo when sending to a transparent recipient address,
* which is not supported by the [Zcash protocol](https://zips.z.cash/protocol/protocol.pdf).
*/
data class TransparentMemoNotAllowed(val index: UInt?) : Errors()
/**
* The payment which index is included in the associated value did not include a recipient address.
*/
data class RecipientMissing(val index: UInt?) : Errors()
/**
* The payment request includes a `paramIndex` that is invalid according to [ZIP-321](https://zips.z.cash/zip-0321) specs
*/
data class InvalidParamIndex(val value: String) : Errors()
/**
* Some invalid value was found at a query parameter that a specific index
*/
data class InvalidParamValue(val param: String, val index: UInt?) : Errors()
/**
* The [ZIP-321](https://zips.z.cash/zip-0321) URI was malformed and failed to parse.
*/
data class ParseError(val value: String) : Errors()
/**
* A value was expected to be qchar-encoded but its decoding failed.
* Associated type has the value that failed.
*/
data class QcharDecodeFailed(val index: UInt?, val key: String, val value: String) : Errors()
/**
* The parser found a required parameter it does not recognize.
* Associated string contains the unrecognized input.
* See [Forward compatibilty](https://zips.z.cash/zip-0321#forward-compatibility)
* Variables which are prefixed with a req- are considered required. If a parser does not recognize any
* variables which are prefixed with req-, it MUST consider the entire URI invalid. Any other variables that
* are not recognized, but that are not prefixed with a req-, SHOULD be ignored.)
*/
data class UnknownRequiredParameter(val value: String) : Errors()
}
sealed class ParserResult {
data class SingleAddress(val singleRecipient: RecipientAddress) : ParserResult()
data class Request(val paymentRequest: PaymentRequest) : ParserResult()
}
/**
* Enumerates formatting options for URI strings.
*/
sealed class FormattingOptions {
/** Enumerates all payments. */
object EnumerateAllPayments : FormattingOptions()
/** Uses an empty parameter index. */
data class UseEmptyParamIndex(val omitAddressLabel: Boolean) : FormattingOptions()
}
/**
* Transforms a [PaymentRequest] into a ZIP-321 payment request [String].
*
* @param request The payment request.
* @param formattingOptions The formatting options.
* @return The ZIP-321 payment request [String].
*/
fun uriString(
from: PaymentRequest,
formattingOptions: FormattingOptions = FormattingOptions.EnumerateAllPayments
): String {
return when (formattingOptions) {
is FormattingOptions.EnumerateAllPayments -> Render.request(from, 1u, false)
is FormattingOptions.UseEmptyParamIndex -> Render.request(
from,
startIndex = null,
omittingFirstAddressLabel = formattingOptions.omitAddressLabel
)
}
}
/**
* Convenience function to generate a ZIP-321 payment URI for a single recipient with no amount.
*
* @param recipient A recipient address.
* @param formattingOptions The formatting options.
* @return The ZIP-321 payment URI [String].
*/
fun request(
recipient: RecipientAddress,
formattingOptions: FormattingOptions = FormattingOptions.UseEmptyParamIndex(
omitAddressLabel = true
)
): String {
return when (formattingOptions) {
is FormattingOptions.UseEmptyParamIndex -> "zcash:".plus(
Render.parameter(recipient, index = null, omittingAddressLabel = formattingOptions.omitAddressLabel)
)
else -> "zcash:".plus(Render.parameter(recipient, index = null, omittingAddressLabel = false))
}
}
/**
* Generates a ZIP-321 payment request [String] from a [Payment].
*
* @param payment The payment.
* @param formattingOptions The formatting options.
* @return The ZIP-321 payment request [String].
*/
fun request(
payment: Payment,
formattingOptions: FormattingOptions = FormattingOptions.EnumerateAllPayments
): String {
return uriString(PaymentRequest(payments = listOf(payment)), formattingOptions = formattingOptions)
}
/**
* Parses a ZIP-321 payment request from [String]
*
* @param uriString The payment request String.
* @param validatingRecipients a lambda that validates all found recipients
* @return The ZIP-321 payment request result [ParserResult].
*/
fun request(uriString: String, validatingRecipients: ((String) -> Boolean)?): ParserResult {
return Parser(validatingRecipients).parse(uriString)
}
}
| zcash-kotlin-payment-uri/lib/src/main/kotlin/dev/thecodebuffet/zcash/zip321/ZIP321.kt | 4026955064 |
package dev.thecodebuffet.zcash.zip321.parser
import com.copperleaf.kudzu.parser.text.BaseTextParser
class AddressTextParser : BaseTextParser(
isValidChar = { _, char -> char.isLetterOrDigit() },
isValidText = { it.isNotEmpty() },
allowEmptyInput = false,
invalidTextErrorMessage = { "Expected bech32 or Base58 text, got '$it'" }
)
| zcash-kotlin-payment-uri/lib/src/main/kotlin/dev/thecodebuffet/zcash/zip321/parser/AddressParser.kt | 4119502269 |
package dev.thecodebuffet.zcash.zip321.parser
import MemoBytes
import NonNegativeAmount
import OtherParam
import Payment
import PaymentRequest
import RecipientAddress
import com.copperleaf.kudzu.parser.ParserContext
import com.copperleaf.kudzu.parser.chars.AnyCharParser
import com.copperleaf.kudzu.parser.chars.CharInParser
import com.copperleaf.kudzu.parser.chars.DigitParser
import com.copperleaf.kudzu.parser.choice.PredictiveChoiceParser
import com.copperleaf.kudzu.parser.many.ManyParser
import com.copperleaf.kudzu.parser.many.SeparatedByParser
import com.copperleaf.kudzu.parser.many.UntilParser
import com.copperleaf.kudzu.parser.mapped.MappedParser
import com.copperleaf.kudzu.parser.maybe.MaybeParser
import com.copperleaf.kudzu.parser.sequence.SequenceParser
import com.copperleaf.kudzu.parser.text.LiteralTokenParser
import dev.thecodebuffet.zcash.zip321.ZIP321
import dev.thecodebuffet.zcash.zip321.ZIP321.ParserResult
import java.math.BigDecimal
class Parser(private val addressValidation: ((String) -> Boolean)?) {
val maybeLeadingAddressParse = MappedParser(
SequenceParser(
LiteralTokenParser("zcash:"),
MaybeParser(
AddressTextParser()
)
)
) {
val addressValue: IndexedParameter? = it.node2.node?.let { textNode ->
IndexedParameter(
index = 0u,
param = Param.Address(
RecipientAddress(
textNode.text,
validating = addressValidation
)
)
)
}
addressValue
}
val parameterIndexParser = MappedParser(
SequenceParser(
CharInParser(CharRange('1', '9')),
MaybeParser(
ManyParser(
DigitParser()
)
)
)
) {
val firstDigit = it.node1.text
(
firstDigit + it.node2.let { node ->
if (node.text.length > 3) {
throw ZIP321.Errors.InvalidParamIndex(firstDigit + node.text)
} else {
node.text
}
}
).toUInt()
}
val optionallyIndexedParamName = MappedParser(
SequenceParser(
UntilParser(
AnyCharParser(),
PredictiveChoiceParser(
LiteralTokenParser("."),
LiteralTokenParser("=")
)
),
MaybeParser(
SequenceParser(
LiteralTokenParser("."),
parameterIndexParser
)
)
)
) {
val paramName = it.node1.text
if (!paramName.all { c -> CharsetValidations.isValidParamNameChar(c) }) {
throw ZIP321.Errors.ParseError("Invalid paramname $paramName")
} else {
Pair<String, UInt?>(
it.node1.text,
it.node2.node?.node2?.value
)
}
}
val queryKeyAndValueParser = MappedParser(
SequenceParser(
optionallyIndexedParamName,
LiteralTokenParser("="),
ManyParser(
CharInParser(CharsetValidations.Companion.QcharCharacterSet.characters.toList())
)
)
) {
Pair(it.node1.value, it.node3.text)
}
/**
* parses a sequence of query parameters lead by query separator char (?)
*/
private val queryParamsParser = MappedParser(
SequenceParser(
LiteralTokenParser("?"),
SeparatedByParser(
queryKeyAndValueParser,
LiteralTokenParser("&")
)
)
) {
it.node2.nodeList.map { node -> node.value }
}
/**
* maps a parsed Query Parameter key and value into an `IndexedParameter`
* providing validation of Query keys and values. An address validation can be provided.
*/
fun zcashParameter(
parsedQueryKeyValue: Pair<Pair<String, UInt?>, String>,
validatingAddress: ((String) -> Boolean)? = null
): IndexedParameter {
val queryKey = parsedQueryKeyValue.first.first
val queryKeyIndex = parsedQueryKeyValue.first.second?.let {
if (it == 0u) {
throw ZIP321.Errors.InvalidParamIndex("$queryKey.0")
} else {
it
}
} ?: 0u
val queryValue = parsedQueryKeyValue.second
val param = Param.from(
queryKey,
queryValue,
queryKeyIndex,
validatingAddress
)
return IndexedParameter(queryKeyIndex, param)
}
/**
* Parses the rest of the URI after the `zcash:` and possible
* leading address have been captured, validating the found addresses
* if validation is provided
*/
fun parseParameters(
remainingString: ParserContext,
leadingAddress: IndexedParameter?,
validatingAddress: ((String) -> Boolean)? = null
): List<IndexedParameter> {
val list = ArrayList<IndexedParameter>()
leadingAddress?.let { list.add(it) }
list.addAll(
queryParamsParser.parse(remainingString)
.first
.value
.map { zcashParameter(it, validatingAddress) }
)
if (list.isEmpty()) {
throw ZIP321.Errors.RecipientMissing(null)
}
return list
}
/**
* Maps a list of `IndexedParameter` into a list of validated `Payment`
*/
@Throws(ZIP321.Errors::class)
fun mapToPayments(indexedParameters: List<IndexedParameter>): List<Payment> {
if (indexedParameters.isEmpty()) {
throw ZIP321.Errors.RecipientMissing(null)
}
val paramsByIndex: MutableMap<UInt, MutableList<Param>> = mutableMapOf()
for (idxParam in indexedParameters) {
val paramVecByIndex = paramsByIndex[idxParam.index]
if (paramVecByIndex != null) {
if (paramVecByIndex.hasDuplicateParam(idxParam.param)) {
throw ZIP321.Errors.DuplicateParameter(
idxParam.param.name,
idxParam.index.mapToParamIndex()
)
} else {
paramVecByIndex.add(idxParam.param)
}
} else {
paramsByIndex[idxParam.index] = mutableListOf(idxParam.param)
}
}
return paramsByIndex
.map { (index, parameters) ->
Payment.fromUniqueIndexedParameters(index, parameters)
}
}
@Throws(ZIP321.Errors::class)
fun parse(uriString: String): ParserResult {
val (node, remainingText) = maybeLeadingAddressParse.parse(
ParserContext.fromString(uriString)
)
val leadingAddress = node.value
// no remaining text to parse and no address found. Not a valid URI
if (remainingText.isEmpty() && leadingAddress == null) {
throw ZIP321.Errors.InvalidURI
}
if (remainingText.isEmpty() && leadingAddress != null) {
leadingAddress?.let {
when (val param = it.param) {
is Param.Address -> return ParserResult.SingleAddress(param.recipientAddress)
else ->
throw ZIP321.Errors.ParseError(
"leading parameter after `zcash:` that is not an address"
)
}
}
}
// remaining text is not empty there's still work to do
return ParserResult.Request(
PaymentRequest(
mapToPayments(
parseParameters(remainingText, node.value, addressValidation)
)
)
)
}
}
@Suppress("detekt:CyclomaticComplexMethod")
fun Payment.Companion.fromUniqueIndexedParameters(index: UInt, parameters: List<Param>): Payment {
val recipient = parameters.firstOrNull { param ->
when (param) {
is Param.Address -> true
else -> false
}
}?.let { address ->
when (address) {
is Param.Address -> address.recipientAddress
else -> null
}
} ?: throw ZIP321.Errors.RecipientMissing(index.mapToParamIndex())
var amount: NonNegativeAmount? = null
var memo: MemoBytes? = null
var label: String? = null
var message: String? = null
val other = ArrayList<OtherParam>()
for (param in parameters) {
when (param) {
is Param.Address -> continue
is Param.Amount -> amount = param.amount
is Param.Label -> label = param.label
is Param.Memo -> {
if (recipient.isTransparent()) {
throw ZIP321.Errors.TransparentMemoNotAllowed(index.mapToParamIndex())
}
memo = param.memoBytes
}
is Param.Message -> message = param.message
is Param.Other -> other.add(OtherParam(param.paramName, param.value))
}
}
return Payment(
recipient,
amount ?: NonNegativeAmount(BigDecimal(0)),
memo,
label,
message,
when (other.isEmpty()) {
true -> null
false -> other
}
)
}
fun UInt.mapToParamIndex(): UInt? {
return when (this == 0u) {
false -> this
true -> null
}
}
| zcash-kotlin-payment-uri/lib/src/main/kotlin/dev/thecodebuffet/zcash/zip321/parser/Parser.kt | 2456993910 |
package dev.thecodebuffet.zcash.zip321.parser
data class IndexedParameter(
val index: UInt,
val param: Param
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as IndexedParameter
if (index != other.index) return false
if (param != other.param) return false
return true
}
override fun hashCode(): Int {
var result = index.hashCode()
result = 31 * result + param.hashCode()
return result
}
}
| zcash-kotlin-payment-uri/lib/src/main/kotlin/dev/thecodebuffet/zcash/zip321/parser/IndexedParameter.kt | 220374445 |
package dev.thecodebuffet.zcash.zip321.parser
import MemoBytes
import NonNegativeAmount
import RecipientAddress
import dev.thecodebuffet.zcash.zip321.ParamName
import dev.thecodebuffet.zcash.zip321.ZIP321
import dev.thecodebuffet.zcash.zip321.extensions.qcharDecode
sealed class Param {
companion object {
fun from(
queryKey: String,
value: String,
index: UInt,
validatingAddress: ((String) -> Boolean)? = null
): Param {
return when (queryKey) {
ParamName.ADDRESS.value -> {
try {
Param.Address(RecipientAddress(value, validatingAddress))
} catch (error: RecipientAddress.RecipientAddressError.InvalidRecipient) {
throw ZIP321.Errors.InvalidAddress(if (index > 0u) index else null)
}
}
ParamName.AMOUNT.value -> {
try {
Param.Amount(NonNegativeAmount(decimalString = value))
} catch (error: NonNegativeAmount.AmountError.NegativeAmount) {
throw ZIP321.Errors.AmountTooSmall(index)
} catch (error: NonNegativeAmount.AmountError.GreaterThanSupply) {
throw ZIP321.Errors.AmountExceededSupply(index)
} catch (error: NonNegativeAmount.AmountError.InvalidTextInput) {
throw ZIP321.Errors.ParseError("Invalid text input $value")
} catch (error: NonNegativeAmount.AmountError.TooManyFractionalDigits) {
throw ZIP321.Errors.AmountTooSmall(index)
}
}
ParamName.LABEL.value -> {
when (val qcharDecoded = value.qcharDecode()) {
null -> throw ZIP321.Errors.QcharDecodeFailed(index.mapToParamIndex(), queryKey, value)
else -> Param.Label(qcharDecoded)
}
}
ParamName.MESSAGE.value -> {
when (val qcharDecoded = value.qcharDecode()) {
null -> throw ZIP321.Errors.QcharDecodeFailed(index.mapToParamIndex(), queryKey, value)
else -> Param.Message(qcharDecoded)
}
}
ParamName.MEMO.value -> {
try {
Param.Memo(MemoBytes.fromBase64URL(value))
} catch (error: MemoBytes.MemoError) {
throw ZIP321.Errors.MemoBytesError(error, index)
}
}
else -> {
if (queryKey.startsWith("req-")) {
throw ZIP321.Errors.UnknownRequiredParameter(queryKey)
}
when (val qcharDecoded = value.qcharDecode()) {
null -> throw ZIP321.Errors.InvalidParamValue("message", index)
else -> Param.Other(queryKey, qcharDecoded)
}
}
}
}
}
data class Address(val recipientAddress: RecipientAddress) : Param()
data class Amount(val amount: NonNegativeAmount) : Param()
data class Memo(val memoBytes: MemoBytes) : Param()
data class Label(val label: String) : Param()
data class Message(val message: String) : Param()
data class Other(val paramName: String, val value: String) : Param()
val name: String
get() = when (this) {
is Address -> ParamName.ADDRESS.name.lowercase()
is Amount -> ParamName.AMOUNT.name.lowercase()
is Memo -> ParamName.MEMO.name.lowercase()
is Label -> ParamName.LABEL.name.lowercase()
is Message -> ParamName.MESSAGE.name.lowercase()
is Other -> paramName
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Param
if (name != other.name) return false
return when (this) {
is Address -> recipientAddress == (other as? Address)?.recipientAddress
is Amount -> amount == (other as? Amount)?.amount
is Memo -> memoBytes == (other as? Memo)?.memoBytes
is Label -> label == (other as? Label)?.label
is Message -> message == (other as? Message)?.message
is Other -> (other as? Other)?.let {
p ->
p.paramName == paramName && p.value == value
} ?: false
}
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + when (this) {
is Address -> recipientAddress.hashCode()
is Amount -> amount.hashCode()
is Memo -> memoBytes.hashCode()
is Label -> label.hashCode()
is Message -> message.hashCode()
is Other -> {
result = 31 * result + paramName.hashCode()
result = 31 * result + value.hashCode()
result
}
}
return result
}
/**
* Checks if this `Param` is the same kind of
* the other given regardless of the value.
* this is useful to check if a list of `Param`
* conforming a `Payment` has duplicate query keys
* telling the porser to fail.
*/
fun partiallyEqual(other: Param): Boolean {
if (this === other) return true
if (name != other.name) return false
return when (this) {
is Address -> (other as? Address) != null
is Amount -> (other as? Amount) != null
is Memo -> (other as? Memo) != null
is Label -> (other as? Label) != null
is Message -> (other as? Message) != null
is Other -> (other as? Other)?.let {
p ->
p.paramName == paramName
} ?: false
}
}
}
fun List<Param>.hasDuplicateParam(param: Param): Boolean {
for (i in this) {
if (i.partiallyEqual(param)) return true else continue
}
return false
}
| zcash-kotlin-payment-uri/lib/src/main/kotlin/dev/thecodebuffet/zcash/zip321/parser/Param.kt | 1307496004 |
package dev.thecodebuffet.zcash.zip321.parser
class CharsetValidations {
companion object {
object Base58CharacterSet {
val characters: Set<Char> = setOf(
'1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K',
'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
)
}
object Bech32CharacterSet {
val characters: Set<Char> = setOf(
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
)
}
object ParamNameCharacterSet {
val characters: Set<Char> = setOf(
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '+', '-'
)
}
object UnreservedCharacterSet {
val characters = setOf(
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '.', '_', '~', '!'
)
}
object PctEncodedCharacterSet {
val characters = setOf(
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F',
'a', 'b', 'c', 'd', 'e', 'f', '%'
)
}
object AllowedDelimsCharacterSet {
val characters = setOf('!', '$', '\'', '(', ')', '*', '+', ',', ';')
}
object QcharCharacterSet {
val characters = UnreservedCharacterSet.characters.union(
PctEncodedCharacterSet.characters
)
.union(
AllowedDelimsCharacterSet.characters
)
.union(
setOf(':', '@')
)
}
val isValidBase58OrBech32Char: (Char) -> Boolean = { char ->
isValidBase58Char(char) || isValidBech32Char(char)
}
val isValidBase58Char: (Char) -> Boolean = { it in Base58CharacterSet.characters }
val isValidBech32Char: (Char) -> Boolean = { it in Bech32CharacterSet.characters }
val isValidParamNameChar: (Char) -> Boolean = { it in ParamNameCharacterSet.characters }
}
}
| zcash-kotlin-payment-uri/lib/src/main/kotlin/dev/thecodebuffet/zcash/zip321/parser/CharsetValidations.kt | 796549956 |
package dev.thecodebuffet.zcash.zip321.parser
import com.copperleaf.kudzu.parser.text.BaseTextParser
class ParameterNameParser : BaseTextParser(
isValidChar = { _, char -> CharsetValidations.isValidParamNameChar(char) },
isValidText = {
it.isNotEmpty() &&
it.all {
c ->
CharsetValidations.isValidParamNameChar(c)
}
},
allowEmptyInput = false,
invalidTextErrorMessage = { "Expected [A-Za-z0-9+-], got '$it'" }
)
| zcash-kotlin-payment-uri/lib/src/main/kotlin/dev/thecodebuffet/zcash/zip321/parser/ParameterNameParser.kt | 3808203729 |
package dev.thecodebuffet.zcash.zip321.extensions
fun String.qcharEncoded(): String? {
val qcharEncodeAllowed = setOf(
'-', '.', '_', '~', '!', '$', '\'', '(', ')', '*', '+', ',', ';', '@', ':'
)
.map { it.toString() }
return this.replace(Regex("[^A-Za-z0-9\\-._~!$'()*+,;@:]")) { matched ->
if (matched.value in qcharEncodeAllowed) {
matched.value
} else {
"%" + matched.value.toCharArray().joinToString("%") { byte ->
"%02X".format(byte.code.toByte())
}
}
}
}
fun String.qcharDecode(): String? {
return java.net.URLDecoder.decode(this, "UTF-8")
}
| zcash-kotlin-payment-uri/lib/src/main/kotlin/dev/thecodebuffet/zcash/zip321/extensions/StringEncodings.kt | 1975807890 |
package dev.thecodebuffet.zcash.zip321
import MemoBytes
import NonNegativeAmount
import Payment
import PaymentRequest
import RecipientAddress
import dev.thecodebuffet.zcash.zip321.extensions.qcharEncoded
enum class ParamName(val value: String) {
ADDRESS("address"),
AMOUNT("amount"),
LABEL("label"),
MEMO("memo"),
MESSAGE("message")
}
object Render {
private fun parameterIndex(idx: UInt?): String {
return idx?.let { ".$it" } ?: ""
}
fun parameter(label: String, value: String, index: UInt?): String? {
val qcharValue = value.qcharEncoded() ?: return null
return "$label${parameterIndex(index)}=$qcharValue"
}
fun parameter(nonNegativeAmount: NonNegativeAmount, index: UInt?): String {
return "${ParamName.AMOUNT.value}${parameterIndex(index)}=$nonNegativeAmount"
}
fun parameter(memo: MemoBytes, index: UInt?): String {
return "${ParamName.MEMO.value}${parameterIndex(index)}=${memo.toBase64URL()}"
}
fun parameter(address: RecipientAddress, index: UInt?, omittingAddressLabel: Boolean = false): String {
return if (index == null && omittingAddressLabel) {
address.value
} else {
"${ParamName.ADDRESS.value}${parameterIndex(index)}=${address.value}"
}
}
fun parameterLabel(label: String, index: UInt?): String {
return parameter(ParamName.LABEL.value, label, index) ?: ""
}
fun parameterMessage(message: String, index: UInt?): String {
return parameter(ParamName.MESSAGE.value, message, index) ?: ""
}
fun payment(payment: Payment, index: UInt?, omittingAddressLabel: Boolean = false): String {
var result = ""
result += parameter(payment.recipientAddress, index, omittingAddressLabel)
if (index == null && omittingAddressLabel) {
result += "?"
} else {
result += "&"
}
result += "${parameter(payment.nonNegativeAmount, index)}"
payment.memo?.let { result += "&${parameter(it, index)}" }
payment.label?.let { result += "&${parameterLabel(label = it, index)}" }
payment.message?.let { result += "&${parameterMessage(message = it, index)}" }
return result
}
fun request(paymentRequest: PaymentRequest, startIndex: UInt?, omittingFirstAddressLabel: Boolean = false): String {
var result = "zcash:"
val payments = paymentRequest.payments.toMutableList()
val paramIndexOffset: UInt = startIndex ?: 1u
if (startIndex == null) {
result += if (omittingFirstAddressLabel) "" else "?"
result += payment(payments[0], startIndex, omittingFirstAddressLabel)
payments.removeFirst()
if (payments.isNotEmpty()) {
result += "&"
}
}
val count = payments.size
for ((elementIndex, element) in payments.withIndex()) {
val paramIndex = elementIndex.toUInt() + paramIndexOffset
result += payment(element, paramIndex)
if (paramIndex < count.toUInt()) {
result += "&"
}
}
return result
}
}
| zcash-kotlin-payment-uri/lib/src/main/kotlin/dev/thecodebuffet/zcash/zip321/Render.kt | 3855310776 |
data class Payment(
val recipientAddress: RecipientAddress,
val nonNegativeAmount: NonNegativeAmount,
val memo: MemoBytes?,
val label: String?,
val message: String?,
val otherParams: List<OtherParam>?
) {
@Suppress("EmptyClassBlock")
companion object {}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Payment) return false
if (recipientAddress != other.recipientAddress) return false
if (nonNegativeAmount != other.nonNegativeAmount) return false
if (memo != other.memo) return false
if (label != other.label) return false
if (message != other.message) return false
if (otherParams != other.otherParams) return false
return true
}
override fun hashCode(): Int {
var result = recipientAddress.hashCode()
result = 31 * result + nonNegativeAmount.hashCode()
result = 31 * result + (memo?.hashCode() ?: 0)
result = 31 * result + (label?.hashCode() ?: 0)
result = 31 * result + (message?.hashCode() ?: 0)
result = 31 * result + (otherParams?.hashCode() ?: 0)
return result
}
}
data class OtherParam(val key: String, val value: String)
| zcash-kotlin-payment-uri/lib/src/main/kotlin/dev/thecodebuffet/zcash/zip321/model/Payment.kt | 1337686875 |
import java.nio.charset.Charset
import java.util.Base64
class MemoBytes {
companion object {
const val maxLength: Int = 512
fun fromBase64URL(string: String): MemoBytes {
return string.decodeBase64URL()?.let { MemoBytes(it) } ?: throw MemoError.InvalidBase64URL
}
}
val data: ByteArray
sealed class MemoError(message: String) : RuntimeException(message) {
object MemoTooLong : MemoError("MemoBytes exceeds max length of 512 bytes")
object MemoEmpty : MemoError("MemoBytes can't be initialized with empty bytes")
object InvalidBase64URL : MemoError("MemoBytes can't be initialized with invalid Base64URL")
}
@Throws(MemoError::class)
constructor(data: ByteArray) {
require(data.isNotEmpty()) { throw MemoError.MemoEmpty }
require(data.size <= maxLength) { throw MemoError.MemoTooLong }
this.data = data
}
@Throws(MemoError::class)
constructor(string: String) {
require(string.isNotEmpty()) { throw MemoError.MemoEmpty }
require(string.length <= maxLength) { throw MemoError.MemoTooLong }
this.data = string.encodeToByteArray()
}
fun toBase64URL(): String {
return Base64.getUrlEncoder().encodeToString(data)
.replace("/", "_")
.replace("+", "-")
.replace("=", "")
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as MemoBytes
if (!data.contentEquals(other.data)) return false
return true
}
override fun hashCode(): Int {
return 31 * data.contentHashCode()
}
}
fun String.decodeBase64URL(): ByteArray? {
return try {
// Replace Base64URL specific characters
val base64URL = replace('-', '+').replace('_', '/')
// Pad the string with '=' characters to make the length a multiple of 4
val paddedBase64 = base64URL + "=".repeat((4 - base64URL.length % 4) % 4)
// Decode the Base64 string into a byte array
Base64.getDecoder().decode(paddedBase64.toByteArray(Charset.defaultCharset()))
} catch (e: IllegalArgumentException) {
// Handle decoding failure and return null
null
}
}
| zcash-kotlin-payment-uri/lib/src/main/kotlin/dev/thecodebuffet/zcash/zip321/model/MemoBytes.kt | 1885992271 |
typealias RequestParams = Pair<String, String>
class RecipientAddress private constructor(val value: String) {
sealed class RecipientAddressError(message: String) : Exception(message) {
object InvalidRecipient : RecipientAddressError("The provided recipient is invalid")
}
/**
* Initialize an opaque Recipient address that's convertible to a String with or without a
* validating function.
* @param value the string representing the recipient
* @param validating a closure that validates the given input.
* @throws `null` if the validating function resolves the input as invalid,
* or a [RecipientAddress] if the input is valid or no validating closure is passed.
*/
@Throws(RecipientAddressError::class)
constructor(value: String, validating: ((String) -> Boolean)? = null) : this(
when (validating?.invoke(value)) {
null, true -> value
false -> throw RecipientAddressError.InvalidRecipient
}
)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is RecipientAddress) return false
return value == other.value
}
override fun hashCode(): Int {
return value.hashCode()
}
fun isTransparent(): Boolean {
return value.startsWith("t")
}
}
| zcash-kotlin-payment-uri/lib/src/main/kotlin/dev/thecodebuffet/zcash/zip321/model/RecipientAddress.kt | 2702529544 |
data class PaymentRequest(val payments: List<Payment>)
| zcash-kotlin-payment-uri/lib/src/main/kotlin/dev/thecodebuffet/zcash/zip321/model/PaymentRequest.kt | 528618922 |
import java.math.BigDecimal
import java.math.RoundingMode
/**
* An non-negative decimal ZEC amount represented as specified in ZIP-321.
* Amount can be from 1 zatoshi (0.00000001) to the maxSupply of 21M ZEC (21_000_000)
*
* @property value The decimal value of the ZEC amount.
*/
class NonNegativeAmount {
private val value: BigDecimal
/**
* Initializes an Amount from a `BigDecimal` number.
*
* @param value Decimal representation of the desired amount. Important: `BigDecimal` values
* with more than 8 fractional digits will be rounded using bankers rounding.
* @throws AmountError if the provided value can't represent or can't be rounded to a
* non-negative non-zero ZEC decimal amount.
*/
@Throws(AmountError::class)
constructor(value: BigDecimal) {
validateDecimal(value)
this.value = value
}
@Throws(AmountError::class)
constructor(decimalString: String) {
val decimal = decimalFromString(decimalString)
validateDecimal(decimal)
this.value = decimal
}
/**
* Enum representing errors that can occur during Amount operations.
*/
sealed class AmountError(message: String) : Exception(message) {
object NegativeAmount : AmountError("Amount cannot be negative")
object GreaterThanSupply : AmountError("Amount cannot be greater than the maximum supply")
object TooManyFractionalDigits : AmountError("Amount has too many fractional digits")
object InvalidTextInput : AmountError("Invalid text input for amount")
}
companion object {
private const val maxFractionalDecimalDigits: Int = 8
private val maxSupply: BigDecimal = BigDecimal("21000000")
@Throws(AmountError::class)
private fun validateDecimal(value: BigDecimal) {
require(value > BigDecimal.ZERO) { throw AmountError.NegativeAmount }
require(value <= maxSupply) { throw AmountError.GreaterThanSupply }
requireFractionalDigits(value)
}
/**
* Rounds the given `BigDecimal` value according to bankers rounding.
*
* @return The rounded value.
*/
private fun BigDecimal.round(): BigDecimal {
return this.setScale(maxFractionalDecimalDigits, RoundingMode.HALF_EVEN)
}
/**
* Creates an Amount from a `BigDecimal` value.
*
* @param value The decimal representation of the desired amount.
* @return A valid ZEC amount.
* @throws AmountError if the provided value cannot represent or cannot be rounded to a
* non-negative non-zero ZEC decimal amount.
*/
@Throws(AmountError::class)
fun create(value: BigDecimal): NonNegativeAmount {
return NonNegativeAmount(value.round())
}
/**
* Creates an Amount from a string representation.
*
* @param string String representation of the ZEC amount.
* @return A valid ZEC amount.
* @throws AmountError if the string cannot be parsed or if the parsed value violates ZEC
* amount constraints.
*/
@Throws(AmountError::class)
fun createFromString(string: String): NonNegativeAmount {
return create(decimalFromString(string))
}
@Throws(AmountError::class)
fun decimalFromString(string: String): BigDecimal {
try {
val decimal = BigDecimal(string)
requireFractionalDigits(decimal)
return decimal
} catch (e: NumberFormatException) {
throw AmountError.InvalidTextInput
}
}
private fun requireFractionalDigits(value: BigDecimal) {
require(value.scale() <= maxFractionalDecimalDigits) {
throw AmountError.TooManyFractionalDigits
}
}
}
/**
* Converts the amount to a string representation.
*
* @return The string representation of the amount.
*/
override fun toString(): String {
return value.setScale(maxFractionalDecimalDigits, RoundingMode.HALF_EVEN).stripTrailingZeros().toPlainString()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as NonNegativeAmount
// NOTE: comparing with == operator provides false negatives.
// apparently this is a JDK issue.
return this.value.compareTo(other.value) == 0
}
override fun hashCode(): Int {
return 31 * this.value.hashCode()
}
}
| zcash-kotlin-payment-uri/lib/src/main/kotlin/dev/thecodebuffet/zcash/zip321/model/NonNegativeAmount.kt | 3582848352 |
package com.ac
import com.ac.io.HttpMethod
import com.ac.io.KHttpServer
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class HttpServerTest {
@Test
fun testHttpServerOK() {
val server = KHttpServer(8080)
.addRoute(HttpMethod.GET, "/") {
HttpResponse.ok("works")
}
server.start()
val response = khttp.get("http://localhost:8080")
assertEquals(200, response.statusCode)
assertEquals("works", response.text)
assertEquals("KotlinServer", response.headers["Server"])
assertEquals("5", response.headers["Content-Length"])
assertNotNull(response.headers["Date"])
server.stop()
}
@Test
fun testHttpServerNotFound() {
val server = KHttpServer(8080)
server.start()
val response = khttp.get("http://localhost:8080")
assertEquals(404, response.statusCode)
assertEquals("Route Not Found...", response.text)
assertEquals("KotlinServer", response.headers["Server"])
assertEquals("18", response.headers["Content-Length"])
assertNotNull(response.headers["Date"])
server.stop()
}
} | khttp-server/src/test/kotlin/com/ac/HttpServerTest.kt | 2952715829 |
package com.ac
import com.ac.io.HttpMethod
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.net.URI
import java.nio.ByteBuffer
import java.nio.channels.ReadableByteChannel
data class HttpRequest(val httpMethod: HttpMethod, val uri: URI, val requestHeaders: Map<String, List<String>>) {
companion object {
fun decode(inputStream: InputStream): HttpRequest {
return buildRequest(readMessage(inputStream))
}
fun decode(channel: ReadableByteChannel): HttpRequest {
return buildRequest(readMessage(channel))
}
}
}
private fun buildRequest(message: List<String>): HttpRequest {
if (message.isEmpty()) {
throw RuntimeException("invalid request")
}
val firstLine = message[0]
val httpInfo = firstLine.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (httpInfo.size != 3) {
throw RuntimeException("httpInfo invalid")
}
val protocolVersion = httpInfo[2]
return if (protocolVersion != "HTTP/1.1") {
throw RuntimeException("protocolVersion not supported")
} else {
HttpRequest(HttpMethod.valueOf(httpInfo[0]), URI(httpInfo[1]), addRequestHeaders(message))
}
}
private fun readMessage(inputStream: InputStream): List<String> {
return try {
if (inputStream.available() <= 0) {
throw RuntimeException("empty")
}
val inBuffer = CharArray(inputStream.available())
val inReader = InputStreamReader(inputStream)
inReader.read(inBuffer)
String(inBuffer).lines()
} catch (e: Exception) {
throw RuntimeException(e)
}
}
private fun readMessage(channel: ReadableByteChannel): List<String> {
val readBuffer: ByteBuffer = ByteBuffer.allocate(10240)
val sb = StringBuilder()
readBuffer.clear()
var read: Int
var totalRead = 0
while (channel.read(readBuffer).also { read = it } > 0) {
totalRead += read
if (totalRead > 8192) {
throw IOException("Request data limit exceeded")
}
readBuffer.flip()
val bytes = ByteArray(readBuffer.limit())
readBuffer.get(bytes)
sb.append(String(bytes))
readBuffer.clear()
}
if (read < 0) {
throw IOException("End of input stream. Connection is closed by the client")
}
return sb.toString().lines()
}
private fun addRequestHeaders(message: List<String>): MutableMap<String, List<String>> {
val requestHeaders: MutableMap<String, List<String>> = mutableMapOf()
if (message.size > 1) {
for (i in 1..< message.size) {
val header = message[i]
val colonIndex = header.indexOf(':')
if (!(colonIndex > 0 && header.length > colonIndex + 1)) {
break
}
val headerName = header.substring(0, colonIndex)
val headerValue = header.substring(colonIndex + 1)
requestHeaders[headerName] = headerValue.split(",")
}
}
return requestHeaders
} | khttp-server/src/main/kotlin/com/ac/HttpRequest.kt | 4183820841 |
package com.ac.io.handler
import com.ac.io.HttpRequestHandler
import java.io.IOException
import java.net.Socket
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
class ThreadPoolHttpServerWorker(
private val executor: ExecutorService = Executors.newFixedThreadPool(100)) : HttpServerWorker {
override fun stop() {
executor.shutdownNow()
}
override fun handleConnection(socket: Socket, httpRequestHandler: HttpRequestHandler) {
val httpRequestRunner = Runnable {
try {
httpRequestHandler.handleConnection(socket)
} catch (e: IOException) {
e.printStackTrace()
}
}
executor.execute(httpRequestRunner)
}
} | khttp-server/src/main/kotlin/com/ac/io/handler/ThreadPoolHttpServerWorker.kt | 1145921609 |
package com.ac.io.handler
import com.ac.io.HttpRequestHandler
import java.net.Socket
interface HttpServerWorker {
fun stop();
fun handleConnection(socket: Socket, httpRequestHandler: HttpRequestHandler);
} | khttp-server/src/main/kotlin/com/ac/io/handler/HttpServerWorker.kt | 2058227700 |
package com.ac.io
import com.ac.RequestRunner
import com.ac.io.handler.HttpServerWorker
import com.ac.io.handler.ThreadPoolHttpServerWorker
import java.net.ServerSocket
import java.net.Socket
class KHttpServer (private val port: Int, private val worker: HttpServerWorker = ThreadPoolHttpServerWorker()) {
private val routes: MutableMap<String, RequestRunner> = mutableMapOf()
private val socket = ServerSocket(port)
private val handler: HttpRequestHandler = HttpRequestHandler(routes)
private lateinit var mainThread: Thread
fun start () {
mainThread = Thread {
println("Server started on port: $port")
while (true) {
val socket = socket.accept()
handleConnection(socket)
}
}
mainThread.start();
}
fun stop () {
mainThread.interrupt()
worker.stop()
socket.close()
}
private fun handleConnection(clientConnection: Socket) {
worker.handleConnection(clientConnection, handler)
}
fun addRoute(opCode: HttpMethod, route: String, runner: RequestRunner) : KHttpServer {
routes[opCode.name.plus(route)] = runner
return this
}
}
enum class HttpMethod {
GET,
PUT,
POST,
PATCH
}
enum class HttpStatusCode(val code: Int, val statusMessage: String) {
OK(200, "OK"),
BAD_REQUEST(400, "Bad Request"),
NOT_FOUND(404, "Not Found"),
INTERNAL_SERVER_ERROR(500, "Internal Server Error")
}
| khttp-server/src/main/kotlin/com/ac/io/KHttpServer.kt | 4247276742 |
package com.ac.io
import com.ac.HttpRequest
import com.ac.HttpResponse
import java.io.BufferedWriter
import java.io.OutputStreamWriter
import java.net.Socket
import java.util.function.Function
typealias RequestRunner = Function<HttpRequest, HttpResponse>
class HttpRequestHandler (private val routes: Map<String, RequestRunner>) {
fun handleConnection(socket: Socket) {
val inputStream = socket.getInputStream()
val outputStream = socket.getOutputStream()
val bufferedWriter = BufferedWriter(OutputStreamWriter(outputStream))
val request: HttpRequest = HttpRequest.decode(inputStream)
handleRequest(request, bufferedWriter)
bufferedWriter.close()
inputStream.close()
}
private fun handleRequest(request: HttpRequest, bufferedWriter: BufferedWriter) {
val routeKey: String = request.httpMethod.name.plus(request.uri.rawPath)
if (routes.containsKey(routeKey)) {
val httpResponse = routes[routeKey]!!.apply(request)
httpResponse.writeTo(bufferedWriter)
} else {
HttpResponse(HttpStatusCode.NOT_FOUND, "Route Not Found...", mutableMapOf())
.writeTo(bufferedWriter)
}
}
} | khttp-server/src/main/kotlin/com/ac/io/HttpRequestHandler.kt | 2828256453 |
package com.ac
import com.ac.io.HttpStatusCode
import java.io.BufferedWriter
import java.nio.ByteBuffer
import java.nio.channels.WritableByteChannel
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.util.*
data class HttpResponse (val status : HttpStatusCode, val entity: Any?, val responseHeaders: MutableMap<String, List<String>> = mutableMapOf()) {
companion object {
fun ok(entity: Any?) : HttpResponse = HttpResponse(HttpStatusCode.OK, entity)
}
init {
responseHeaders["Date"] = listOf(DateTimeFormatter.RFC_1123_DATE_TIME.format(ZonedDateTime.now(ZoneOffset.UTC)))
responseHeaders["Server"] = listOf("KotlinServer")
}
fun writeTo(outputStream: BufferedWriter) {
writeResponse(outputStream, this)
}
fun writeTo(channel: WritableByteChannel) {
writeResponse(channel, this)
}
}
private fun writeResponse(channel: WritableByteChannel, response: HttpResponse) {
try {
val breadLine = "\r\n"
channel.write(("HTTP/1.1 ${response.status.code} ${response.status.statusMessage} $breadLine").toByteBuffer())
writeHeaders(channel, response.responseHeaders)
val entityString = response.entity?.toString();
if (entityString.isNullOrEmpty()) {
channel.write(breadLine.toByteBuffer())
} else {
channel.write(("Content-Length: " + entityString.length + breadLine).toByteBuffer())
channel.write(breadLine.toByteBuffer())
channel.write(entityString.toByteBuffer())
}
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun writeHeaders(channel: WritableByteChannel, responseHeaders: Map<String, List<String?>>) {
responseHeaders.forEach { (name: String, values: List<String?>) ->
val valuesCombined = StringJoiner(";")
values.forEach{ str: String? -> valuesCombined.add(str) }
channel.write("$name: $valuesCombined\r\n".toByteBuffer())
}
}
fun String.toByteBuffer(): ByteBuffer = ByteBuffer.wrap(this.encodeToByteArray())
private fun writeResponse(outputStream: BufferedWriter, response: HttpResponse) {
try {
val breadLine = "\r\n"
outputStream.write("HTTP/1.1 ${response.status.code} ${response.status.statusMessage} $breadLine")
writeHeaders(outputStream, response.responseHeaders)
val entityString = response.entity?.toString();
if (entityString.isNullOrEmpty()) {
outputStream.write(breadLine)
} else {
outputStream.write("Content-Length: " + entityString.length + breadLine)
outputStream.write(breadLine)
outputStream.write(entityString)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun writeHeaders(outputStream: BufferedWriter, responseHeaders: Map<String, List<String?>>) {
responseHeaders.forEach { (name: String, values: List<String?>) ->
val valuesCombined = StringJoiner(";")
values.forEach{ str: String? -> valuesCombined.add(str) }
outputStream.write("$name: $valuesCombined\r\n")
}
}
| khttp-server/src/main/kotlin/com/ac/HttpResponse.kt | 1442685898 |
package com.ac
import com.ac.io.handler.ThreadPoolHttpServerWorker
import com.ac.io.HttpMethod
import com.ac.io.KHttpServer
import com.ac.nio.KHttpServerNIO
import java.util.*
import java.util.concurrent.Executors
fun main() {
ioThreadPoolServer()
ioVirtualThreadPool()
nioServer()
}
fun ioThreadPoolServer() {
val server = KHttpServer(8080, ThreadPoolHttpServerWorker())
.addRoute(HttpMethod.GET, "/") {
HttpResponse.ok(UUID.randomUUID().toString())
}
server.start()
}
fun ioVirtualThreadPool() {
val server = KHttpServer(8081, ThreadPoolHttpServerWorker(Executors.newVirtualThreadPerTaskExecutor()))
.addRoute(HttpMethod.GET, "/") {
HttpResponse.ok(UUID.randomUUID().toString())
}
server.start()
}
fun nioServer() {
val server = KHttpServerNIO(8082)
.addRoute(HttpMethod.GET, "/") {
HttpResponse.ok(UUID.randomUUID().toString())
}
.addRoute(HttpMethod.GET, "/hello") {
HttpResponse.ok("hello")
}
server.start()
} | khttp-server/src/main/kotlin/com/ac/Main.kt | 2199725600 |
package com.ac.nio
import com.ac.*
import com.ac.io.HttpMethod
import com.ac.io.HttpStatusCode
import java.net.InetSocketAddress
import java.nio.channels.SelectionKey
import java.nio.channels.Selector
import java.nio.channels.ServerSocketChannel
import java.nio.channels.SocketChannel
import java.util.function.Function
typealias RequestRunner = Function<HttpRequest, HttpResponse>
class KHttpServerNIO(private val port: Int) {
private lateinit var serverChannel: ServerSocketChannel
private lateinit var selector: Selector
private val routes: MutableMap<String, RequestRunner> = mutableMapOf()
fun start() {
init()
startLoop()
}
private fun init() {
selector = Selector.open()
serverChannel = ServerSocketChannel.open()
serverChannel.configureBlocking(false)
serverChannel.socket().bind(InetSocketAddress(port))
serverChannel.register(selector, SelectionKey.OP_ACCEPT)
println("Server started on port: $port")
}
private fun stop() {
selector.close()
serverChannel.close()
}
fun addRoute(opCode: HttpMethod, route: String, runner: RequestRunner) : KHttpServerNIO {
routes[opCode.name.plus(route)] = runner
return this
}
private fun startLoop() {
while (true) {
selector.select()
val keys = selector.selectedKeys()
val keyIterator = keys.iterator()
while (keyIterator.hasNext()) {
val key = keyIterator.next()
keyIterator.remove()
try {
if (!key.isValid) {
continue
}
if (key.isAcceptable) {
accept()
} else if (key.isReadable) {
read(key)
} else if (key.isWritable) {
write(key)
}
} catch (e: Exception) {
e.printStackTrace()
closeChannelSilently(key)
}
}
}
}
private fun accept() {
val clientChannel = serverChannel.accept()
if (clientChannel == null) {
println("No connection is available. Skipping selection key")
return
}
clientChannel.configureBlocking(false)
clientChannel.register(selector, SelectionKey.OP_READ)
}
private fun read(key: SelectionKey) {
val clientChannel = key.channel() as SocketChannel
val request = HttpRequest.decode(clientChannel)
key.attach(request)
println("Parsed incoming HTTP request: $request")
key.interestOps(SelectionKey.OP_WRITE)
}
private fun write(key: SelectionKey) {
val clientChannel = key.channel() as SocketChannel
val request = key.attachment() as HttpRequest
val routeKey: String = request.httpMethod.name.plus(request.uri.rawPath)
if (routes.containsKey(routeKey)) {
val httpResponse = routes[routeKey]!!.apply(request)
httpResponse.writeTo(clientChannel)
} else {
HttpResponse(HttpStatusCode.NOT_FOUND, "Route Not Found...", mutableMapOf())
.writeTo(clientChannel)
}
closeChannelSilently(key)
}
private fun closeChannelSilently(key: SelectionKey) {
val channel = key.channel()
key.cancel()
println("Closing connection for channel: $channel")
channel.close()
}
} | khttp-server/src/main/kotlin/com/ac/nio/KHttpServerNIO.kt | 3601494302 |
package com.register.currencyexrate
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.register.currencyexrate", appContext.packageName)
}
} | CurrencyExRate/app/src/androidTest/java/com/register/currencyexrate/ExampleInstrumentedTest.kt | 3050030666 |
package com.register.currencyexrate
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | CurrencyExRate/app/src/test/java/com/register/currencyexrate/ExampleUnitTest.kt | 4270100736 |
package com.register.currencyexrate.di
import android.app.Application
import com.register.currencyexrate.presentation.CurrencyApp
import com.register.currencyexrate.presentation.CurrencyInfoFragment
import com.register.currencyexrate.presentation.ListOfCurrencyFragment
import com.register.currencyexrate.presentation.MainActivity
import com.register.currencyexrate.presentation.SplashFragment
import dagger.BindsInstance
import dagger.Component
@ApplicationScope
@Component(
modules = [
DataModule::class,
ViewModelModule::class,
]
)
interface ApplicationComponent {
fun inject(fragment: SplashFragment)
fun inject(fragment: ListOfCurrencyFragment)
fun inject(fragment: CurrencyInfoFragment)
fun inject(application: CurrencyApp)
@Component.Factory
interface Factory {
fun create(
@BindsInstance application: Application
): ApplicationComponent
}
} | CurrencyExRate/app/src/main/java/com/register/currencyexrate/di/ApplicationComponent.kt | 2822266791 |
package com.register.currencyexrate.di
import android.app.Application
import com.register.currencyexrate.data.database.AppDatabase
import com.register.currencyexrate.data.database.CurrencyInfoDao
import com.register.currencyexrate.data.network.ApiFactory
import com.register.currencyexrate.data.network.ApiService
import com.register.currencyexrate.data.repository.CurrencyRepositoryImpl
import com.register.currencyexrate.domain.repository.CurrencyRepository
import dagger.Binds
import dagger.Module
import dagger.Provides
@Module
interface DataModule {
@Binds
@ApplicationScope
fun bindRepository(impl: CurrencyRepositoryImpl): CurrencyRepository
companion object {
@Provides
@ApplicationScope
fun provideCurrencyDao(
application: Application
): CurrencyInfoDao {
return AppDatabase.getInstance(application).currencyInfoDao()
}
@Provides
@ApplicationScope
fun provideApiService(): ApiService {
return ApiFactory.apiService
}
}
} | CurrencyExRate/app/src/main/java/com/register/currencyexrate/di/DataModule.kt | 2107940566 |
package com.register.currencyexrate.di
import androidx.lifecycle.ViewModel
import com.register.currencyexrate.presentation.MainViewModel
import dagger.Binds
import dagger.Module
import dagger.multibindings.IntoMap
@Module
interface ViewModelModule {
@Binds
@IntoMap
@ViewModelKey(MainViewModel::class)
fun bindCoinViewModel(viewModel: MainViewModel): ViewModel
} | CurrencyExRate/app/src/main/java/com/register/currencyexrate/di/ViewModelModule.kt | 2721404731 |
package com.register.currencyexrate.di
import javax.inject.Scope
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class ApplicationScope
| CurrencyExRate/app/src/main/java/com/register/currencyexrate/di/ApplicationScope.kt | 723585956 |
package com.register.currencyexrate.di
import androidx.lifecycle.ViewModel
import dagger.MapKey
import kotlin.reflect.KClass
@MapKey
@Retention(AnnotationRetention.RUNTIME)
annotation class ViewModelKey(val value: KClass<out ViewModel>) | CurrencyExRate/app/src/main/java/com/register/currencyexrate/di/ViewModelKey.kt | 2244892954 |
package com.register.currencyexrate.data.database
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "currency_table")
data class CurrencyInfoDbModel(
@PrimaryKey
val id: String,
val numCode: String,
val charCode: String,
val nominal: Int,
val name: String,
val value: Double,
val previous: Double
) | CurrencyExRate/app/src/main/java/com/register/currencyexrate/data/database/CurrencyInfoDbModel.kt | 3666238852 |
package com.register.currencyexrate.data.database
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(entities = [CurrencyInfoDbModel::class], version = 2, exportSchema = false)
abstract class AppDatabase: RoomDatabase() {
companion object {
private var db: AppDatabase? = null
private const val DB_NAME = "main.db"
private val LOCK = Any()
fun getInstance(context: Context): AppDatabase {
synchronized(LOCK) {
db?.let { return it }
val instance =
Room.databaseBuilder(
context,
AppDatabase::class.java,
DB_NAME
)
.fallbackToDestructiveMigration()
.build()
db = instance
return instance
}
}
}
abstract fun currencyInfoDao(): CurrencyInfoDao
} | CurrencyExRate/app/src/main/java/com/register/currencyexrate/data/database/AppDatabase.kt | 1312095769 |
package com.register.currencyexrate.data.database
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import kotlinx.coroutines.flow.Flow
@Dao
interface CurrencyInfoDao {
@Query("SELECT * FROM currency_table")
fun getCurrencyInfo(): List<CurrencyInfoDbModel>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertCurrencyInfo(currencyList: List<CurrencyInfoDbModel>)
} | CurrencyExRate/app/src/main/java/com/register/currencyexrate/data/database/CurrencyInfoDao.kt | 965375726 |
package com.register.currencyexrate.data.repository
import com.register.currencyexrate.data.database.CurrencyInfoDao
import com.register.currencyexrate.data.mapper.CurrencyMapper
import com.register.currencyexrate.data.network.ApiService
import com.register.currencyexrate.domain.entities.CurrencyInfo
import com.register.currencyexrate.domain.repository.CurrencyRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject
class CurrencyRepositoryImpl @Inject constructor(
private val currencyDao: CurrencyInfoDao,
private val mapper: CurrencyMapper,
private val apiService: ApiService
): CurrencyRepository {
override suspend fun getCurrencyInfo(): List<CurrencyInfo> {
return withContext(Dispatchers.IO) {
val response = apiService.getCurrencyData()
when (response.code()) {
in 200..300 -> {
val list = mapper.mapJsonContainerToListCurrencyInfo(response.body()!!)
val dbModelList = list.map(mapper::mapDtoToDbModel)
currencyDao.insertCurrencyInfo(dbModelList)
val entityList = currencyDao.getCurrencyInfo()
val result = entityList.map(mapper::mapDbModelToEntity)
result
}
in 400..500 -> emptyList()
else -> emptyList()
}
}
}
override suspend fun getCurrencyInfoWithDate(
year: String,
month: String,
day: String
): List<CurrencyInfo> {
return withContext(Dispatchers.IO) {
val response = apiService.getCurrencyWithDate(year, month, day)
when (response.code()) {
in 200..300 -> {
val list = mapper.mapJsonContainerToListCurrencyInfo(response.body()!!)
val dbModelList = list.map(mapper::mapDtoToDbModel)
currencyDao.insertCurrencyInfo(dbModelList)
val entityList = currencyDao.getCurrencyInfo()
val result = entityList.map(mapper::mapDbModelToEntity)
result
}
in 400..500 -> emptyList()
else -> emptyList()
}
}
}
} | CurrencyExRate/app/src/main/java/com/register/currencyexrate/data/repository/CurrencyRepositoryImpl.kt | 254821114 |
package com.register.currencyexrate.data.network
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object ApiFactory {
private const val BASE_URL = "https://www.cbr-xml-daily.ru/"
private fun setupInterceptor(): OkHttpClient {
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
return OkHttpClient.Builder()
.addInterceptor(interceptor)
.build()
}
private val client = setupInterceptor()
private val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL).client(client)
.build()
val apiService = retrofit.create(ApiService::class.java)
} | CurrencyExRate/app/src/main/java/com/register/currencyexrate/data/network/ApiFactory.kt | 3746144596 |
package com.register.currencyexrate.data.network.model
import com.google.gson.JsonObject
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
data class CurrencyInfoJsonContainer(
@SerializedName("Valute")
@Expose
val json: JsonObject? = null
) | CurrencyExRate/app/src/main/java/com/register/currencyexrate/data/network/model/CurrencyInfoJsonContainer.kt | 2054890934 |
package com.register.currencyexrate.data.network.model
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
data class CurrencyInfoDto(
@SerializedName("ID")
@Expose
val id: String,
@SerializedName("NumCode")
@Expose
val numCode: String,
@SerializedName("CharCode")
@Expose
val charCode: String,
@SerializedName("Nominal")
@Expose
val nominal: Int,
@SerializedName("Name")
@Expose
val name: String,
@SerializedName("Value")
@Expose
val value: Double,
@SerializedName("Previous")
@Expose
val previous: Double
) | CurrencyExRate/app/src/main/java/com/register/currencyexrate/data/network/model/CurrencyInfoDto.kt | 3495219089 |
package com.register.currencyexrate.data.network
import com.register.currencyexrate.data.network.model.CurrencyInfoJsonContainer
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Path
interface ApiService {
@GET("daily_json.js")
suspend fun getCurrencyData(): Response<CurrencyInfoJsonContainer>
@GET("archive/{year}/{month}/{day}/daily_json.js")
suspend fun getCurrencyWithDate(
@Path("year") year: String,
@Path("month") month: String,
@Path("day") day: String
): Response<CurrencyInfoJsonContainer>
} | CurrencyExRate/app/src/main/java/com/register/currencyexrate/data/network/ApiService.kt | 2118055475 |
package com.register.currencyexrate.data.mapper
import android.util.Log
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParseException
import com.register.currencyexrate.data.database.CurrencyInfoDao
import com.register.currencyexrate.data.database.CurrencyInfoDbModel
import com.register.currencyexrate.data.network.model.CurrencyInfoDto
import com.register.currencyexrate.data.network.model.CurrencyInfoJsonContainer
import com.register.currencyexrate.domain.entities.CurrencyInfo
import javax.inject.Inject
class CurrencyMapper @Inject constructor() {
fun mapDtoToDbModel(dto: CurrencyInfoDto) = CurrencyInfoDbModel(
id = dto.id,
numCode = dto.numCode,
charCode = dto.charCode,
nominal = dto.nominal,
name = dto.name,
value = dto.value,
previous = dto.previous
)
fun mapJsonContainerToListCurrencyInfo(jsonContainer: CurrencyInfoJsonContainer): List<CurrencyInfoDto> {
Log.d("MapperTagCurr", "$jsonContainer")
val result = mutableListOf<CurrencyInfoDto>()
val jsonObject = jsonContainer.json ?: return result
Log.d("MapperTagCurr", "$jsonObject")
val currencyKeySet = jsonObject.keySet()
Log.d("MapperTagCurr", "$currencyKeySet")
for (currencyKey in currencyKeySet) {
val currencyJson = jsonObject.getAsJsonObject(currencyKey)
Log.d("MapperTagCurr", "$currencyJson")
try {
val currencyInfo = Gson().fromJson(currencyJson, CurrencyInfoDto::class.java)
Log.d("MapperTagCurr", "$currencyInfo")
result.add(currencyInfo)
} catch (e: JsonParseException) {
Log.e("MapperError", "Error parsing currency JSON", e)
}
Log.d("MapperTagCurr", " $result")
}
Log.d("MapperTagCurr", "$result")
return result
}
fun mapDbModelToEntity(dbModel: CurrencyInfoDbModel) = CurrencyInfo(
id = dbModel.id,
numCode = dbModel.numCode,
charCode = dbModel.charCode,
nominal = dbModel.nominal,
name = dbModel.name,
value = dbModel.value,
previous = dbModel.previous
)
} | CurrencyExRate/app/src/main/java/com/register/currencyexrate/data/mapper/CurrencyMapper.kt | 2853395485 |
package com.register.currencyexrate.domain.repository
import androidx.lifecycle.LiveData
import com.register.currencyexrate.domain.entities.CurrencyInfo
import kotlinx.coroutines.flow.Flow
interface CurrencyRepository {
suspend fun getCurrencyInfo(): List<CurrencyInfo>
suspend fun getCurrencyInfoWithDate(
year: String,
month: String,
day: String
): List<CurrencyInfo>
} | CurrencyExRate/app/src/main/java/com/register/currencyexrate/domain/repository/CurrencyRepository.kt | 2795012530 |
package com.register.currencyexrate.domain.useCases
import com.register.currencyexrate.domain.repository.CurrencyRepository
import javax.inject.Inject
class GetCurrencyWithDateUseCase @Inject constructor(
private val repository: CurrencyRepository
) {
suspend fun getCurrencyInfoWithDate(
year: String,
month: String,
day: String
) = repository.getCurrencyInfoWithDate(year, month, day)
} | CurrencyExRate/app/src/main/java/com/register/currencyexrate/domain/useCases/GetCurrencyWithDateUseCase.kt | 3398308476 |
package com.register.currencyexrate.domain.useCases
import com.register.currencyexrate.domain.repository.CurrencyRepository
import javax.inject.Inject
class GetCurrencyInfoUseCase @Inject constructor(
private val repository: CurrencyRepository
) {
suspend fun getCurrency() = repository.getCurrencyInfo()
} | CurrencyExRate/app/src/main/java/com/register/currencyexrate/domain/useCases/GetCurrencyInfoUseCase.kt | 1224308375 |
package com.register.currencyexrate.domain.entities
data class CurrencyInfo(
val id: String,
val numCode: String,
val charCode: String,
val nominal: Int,
val name: String,
val value: Double,
val previous: Double
) | CurrencyExRate/app/src/main/java/com/register/currencyexrate/domain/entities/CurrencyInfo.kt | 1669983884 |
package com.register.currencyexrate.presentation
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.register.currencyexrate.domain.entities.CurrencyInfo
import com.register.currencyexrate.domain.useCases.GetCurrencyInfoUseCase
import com.register.currencyexrate.domain.useCases.GetCurrencyWithDateUseCase
import kotlinx.coroutines.launch
import javax.inject.Inject
class MainViewModel @Inject constructor(
private val getCurrencyInfoUseCase: GetCurrencyInfoUseCase,
private val getCurrencyWithDateUseCase: GetCurrencyWithDateUseCase,
): ViewModel() {
private val _currentCharCode = MutableLiveData<String>()
val currentCharCode: LiveData<String> = _currentCharCode
private val _currentCount = MutableLiveData<Double>()
val currentCount: LiveData<Double> = _currentCount
private val _currentName = MutableLiveData<String>()
val currentName: LiveData<String> = _currentName
private val _currencyListDate = MutableLiveData<List<CurrencyInfo>>()
val currencyListDate: LiveData<List<CurrencyInfo>> = _currencyListDate
private val _errorMessage = MutableLiveData<Boolean>()
val errorMessage: LiveData<Boolean> = _errorMessage
fun getCurrencyInfoNow() {
viewModelScope.launch {
val response = getCurrencyInfoUseCase.getCurrency()
_currencyListDate.value = response
if(response.isEmpty()) {
_errorMessage.value = true
} else {
_errorMessage.value = false
Log.d("ViewModelTag", "$response")
}
}
}
fun getCurrencyWithDate(
year: String,
month: String,
day: String,
) {
viewModelScope.launch {
val currencyInfoLiveData = getCurrencyWithDateUseCase.getCurrencyInfoWithDate(year, month, day)
_currencyListDate.value = currencyInfoLiveData
if(currencyInfoLiveData.isEmpty()) {
_errorMessage.value = true
} else {
_errorMessage.value = false
Log.d("ViewModelTag", "$currencyInfoLiveData")
}
}
}
fun getClickedItemName(name: String) {
_currentName.value = name
}
fun getClickedItemCharCode(charCode: String) {
_currentCharCode.value = charCode
}
fun getClickedItemCount(count: Double) {
_currentCount.value = count
}
override fun onCleared() {
super.onCleared()
_currencyListDate.value = emptyList()
_currentCount.value = 0.0
_currentName.value = ""
_currentCharCode.value = ""
_errorMessage.value = false
}
} | CurrencyExRate/app/src/main/java/com/register/currencyexrate/presentation/MainViewModel.kt | 944429484 |
package com.register.currencyexrate.presentation
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.asLiveData
import androidx.navigation.fragment.findNavController
import com.register.currencyexrate.R
import com.register.currencyexrate.databinding.FragmentSplashBinding
import com.register.currencyexrate.domain.entities.CurrencyInfo
import com.register.currencyexrate.presentation.adapters.CurrencyListAdapter
import kotlinx.coroutines.flow.collect
import javax.inject.Inject
class SplashFragment : Fragment() {
private lateinit var viewModel: MainViewModel
@Inject
lateinit var viewModelFactory: ViewModelFactory
private val component by lazy {
(requireActivity().application as CurrencyApp).component
}
private var _binding: FragmentSplashBinding? = null
private val binding: FragmentSplashBinding
get() = _binding ?: throw RuntimeException("FragmentSplashBinding == null")
override fun onAttach(context: Context) {
component.inject(this)
super.onAttach(context)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentSplashBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = ViewModelProvider(requireActivity(), viewModelFactory)[MainViewModel::class.java]
viewModel.getCurrencyInfoNow()
viewModel.currencyListDate.observe(viewLifecycleOwner) { data ->
Log.d("CurrencyFragment", "currencyList has been observed with data: $data")
if(data == null) {
Toast.makeText(
requireActivity().applicationContext,
"Нет данных",
Toast.LENGTH_LONG
).show()
Log.d("CurrencyFragment", "Showed Toast: Нет данных")
} else {
Log.d("CurrencyFragment", "Launching CurrencyListFragment")
launchCurrencyListFragment()
}
}
animateLogo()
}
private fun animateLogo() {
val scaleX = ObjectAnimator.ofFloat(binding.textView, "scaleX", 1f, 1.2f, 1f)
scaleX.repeatCount = Animation.INFINITE
val scaleY = ObjectAnimator.ofFloat(binding.textView, "scaleY", 1f, 1.2f, 1f)
scaleY.repeatCount = Animation.INFINITE
val animatorSet = AnimatorSet()
animatorSet.playTogether(scaleY, scaleX)
animatorSet.duration = 1000
animatorSet.start()
}
private fun launchCurrencyListFragment() {
findNavController().navigate(R.id.action_splashFragment_to_listOfCurrencyFragment)
}
} | CurrencyExRate/app/src/main/java/com/register/currencyexrate/presentation/SplashFragment.kt | 1314518622 |
package com.register.currencyexrate.presentation
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import com.register.currencyexrate.R
import com.register.currencyexrate.data.database.AppDatabase
import javax.inject.Inject
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | CurrencyExRate/app/src/main/java/com/register/currencyexrate/presentation/MainActivity.kt | 1541052739 |
package com.register.currencyexrate.presentation
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import javax.inject.Inject
import javax.inject.Provider
import kotlin.reflect.KClass
class ViewModelFactory @Inject constructor(
private val viewModelProviders: @JvmSuppressWildcards Map<Class<out ViewModel>, Provider<ViewModel>>
): ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return viewModelProviders[modelClass]?.get() as T
}
} | CurrencyExRate/app/src/main/java/com/register/currencyexrate/presentation/ViewModelFactory.kt | 824023535 |
package com.register.currencyexrate.presentation
import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.google.android.material.snackbar.Snackbar
import com.register.currencyexrate.R
import com.register.currencyexrate.databinding.FragmentCurrencyInfoBinding
import com.register.currencyexrate.databinding.FragmentListOfCurrencyBinding
import javax.inject.Inject
class CurrencyInfoFragment : Fragment() {
private lateinit var viewModel: MainViewModel
@Inject
lateinit var viewModelFactory: ViewModelFactory
private val component by lazy {
(requireActivity().application as CurrencyApp).component
}
private var _binding: FragmentCurrencyInfoBinding? = null
private val binding: FragmentCurrencyInfoBinding
get() = _binding ?: throw RuntimeException("FragmentCurrencyInfoBinding == null")
override fun onAttach(context: Context) {
component.inject(this)
super.onAttach(context)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentCurrencyInfoBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = ViewModelProvider(requireActivity(), viewModelFactory)[MainViewModel::class.java]
viewModel.currentName.observe(viewLifecycleOwner) {
binding.currencyInfoName.text = it
}
viewModel.currentCharCode.observe(viewLifecycleOwner) {
binding.currencyInfoCharcode.text = it
binding.textInputCharcode.hint = it
}
viewModel.currentCount.observe(viewLifecycleOwner) {
binding.currencyInfoCount.text = it.toString()
}
binding.imageArrowBack.setOnClickListener {
goBack()
}
binding.textEtCharcode.addTextChangedListener(object: TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
// Не используется
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
val inputText = s.toString()
if (inputText.isBlank()) {
binding.textEtRub.setText("0")
} else if (inputText == "-") {
Toast.makeText(
requireContext(),
"Отрицательные числа недопустимы",
Toast.LENGTH_LONG
).show()
binding.textEtCharcode.setText("")
} else if (!inputText.matches(Regex("-?\\d*"))) {
binding.textEtCharcode.setText(inputText.filter { it.isDigit() })
} else {
val sum = inputText.toLong()
val rate = viewModel.currentCount.value
val modifiedText = (rate?.times(sum)).toString()
if (modifiedText.contains('.')) {
val splitText = modifiedText.split(".")
if (splitText.size == 2 && splitText[1].length > 3) {
val newText = "${splitText[0]}.${splitText[1].substring(0, 3)}"
binding.textEtRub.setText(newText)
}
} else {
binding.textEtRub.setText(modifiedText)
}
}
}
override fun afterTextChanged(s: Editable?) {
// Не используется
}
})
}
private fun goBack() {
findNavController().navigate(R.id.action_currencyInfoFragment_to_listOfCurrencyFragment)
}
override fun onDestroy() {
_binding = null
super.onDestroy()
}
} | CurrencyExRate/app/src/main/java/com/register/currencyexrate/presentation/CurrencyInfoFragment.kt | 3112915269 |
package com.register.currencyexrate.presentation
import android.app.Application
import androidx.work.Configuration
import com.register.currencyexrate.di.DaggerApplicationComponent
import javax.inject.Inject
class CurrencyApp: Application() {
val component by lazy {
DaggerApplicationComponent.factory()
.create(this)
}
override fun onCreate() {
component.inject(this)
super.onCreate()
}
} | CurrencyExRate/app/src/main/java/com/register/currencyexrate/presentation/CurrencyApp.kt | 2496835756 |
package com.register.currencyexrate.presentation
import android.app.DatePickerDialog
import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.AdapterView.OnItemClickListener
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.register.currencyexrate.R
import com.register.currencyexrate.databinding.FragmentListOfCurrencyBinding
import com.register.currencyexrate.databinding.FragmentSplashBinding
import com.register.currencyexrate.domain.entities.CurrencyInfo
import com.register.currencyexrate.presentation.adapters.CurrencyListAdapter
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import javax.inject.Inject
class ListOfCurrencyFragment : Fragment() {
private lateinit var viewModel: MainViewModel
@Inject
lateinit var viewModelFactory: ViewModelFactory
private val component by lazy {
(requireActivity().application as CurrencyApp).component
}
private var _binding: FragmentListOfCurrencyBinding? = null
private val binding: FragmentListOfCurrencyBinding
get() = _binding ?: throw RuntimeException("FragmentListOfCurrencyBinding == null")
override fun onAttach(context: Context) {
component.inject(this)
super.onAttach(context)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentListOfCurrencyBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val calendar = Calendar.getInstance()
viewModel = ViewModelProvider(requireActivity(), viewModelFactory)[MainViewModel::class.java]
val adapter = CurrencyListAdapter()
binding.rvCurrency.adapter = adapter
binding.rvCurrency.layoutManager = GridLayoutManager(requireContext(), 3)
viewModel.currencyListDate.observe(viewLifecycleOwner) {
adapter.submitList(it)
}
adapter.setOnItemClickListener(object: CurrencyListAdapter.OnItemClickListener {
override fun onItemClick(position: Int) {
val currentList = adapter.currentList
val clickedItem = currentList[position]
viewModel.getClickedItemName(clickedItem.name)
viewModel.getClickedItemCount(clickedItem.value)
viewModel.getClickedItemCharCode(clickedItem.charCode)
launchCurrencyInfoFragment()
}
})
binding.textInputEtData.setOnClickListener {
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH)
val day = calendar.get(Calendar.DAY_OF_MONTH)
val datePickerDialog = DatePickerDialog(requireContext(), DatePickerDialog.OnDateSetListener { view, selectedYear, selectedMonth, selectedDay ->
val selectedDateCalendar = Calendar.getInstance().apply {
set(selectedYear, selectedMonth, selectedDay)
}
val selectedDate = SimpleDateFormat("d MMMM yyyy", Locale("ru")).format(selectedDateCalendar.time)
binding.textInputEtData.setText(selectedDate)
val currentDate = Calendar.getInstance()
if (selectedYear == currentDate.get(Calendar.YEAR) &&
selectedMonth == currentDate.get(Calendar.MONTH) &&
selectedDay == currentDate.get(Calendar.DAY_OF_MONTH)
) {
viewModel.getCurrencyInfoNow()
} else {
val yearStr = selectedYear.toString()
val monthStr = (selectedMonth + 1).toString().padStart(2, '0')
val dayStr = selectedDay.toString().padStart(2, '0')
viewModel.getCurrencyWithDate(yearStr, monthStr, dayStr)
}
}, year, month, day)
datePickerDialog.show()
}
viewModel.errorMessage.observe(viewLifecycleOwner) {
if(it) {
binding.errorText.visibility = View.VISIBLE
} else {
binding.errorText.visibility = View.GONE
}
}
}
private fun launchCurrencyInfoFragment() {
findNavController().navigate(R.id.action_listOfCurrencyFragment_to_currencyInfoFragment)
}
override fun onDestroy() {
_binding = null
super.onDestroy()
}
} | CurrencyExRate/app/src/main/java/com/register/currencyexrate/presentation/ListOfCurrencyFragment.kt | 3705000852 |
package com.register.currencyexrate.presentation.adapters
import androidx.recyclerview.widget.DiffUtil
import com.register.currencyexrate.domain.entities.CurrencyInfo
object CurrencyItemDiffCallback: DiffUtil.ItemCallback<CurrencyInfo>() {
override fun areItemsTheSame(oldItem: CurrencyInfo, newItem: CurrencyInfo): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: CurrencyInfo, newItem: CurrencyInfo): Boolean {
return oldItem == newItem
}
} | CurrencyExRate/app/src/main/java/com/register/currencyexrate/presentation/adapters/CurrencyItemDiffCallback.kt | 3207174325 |
package com.register.currencyexrate.presentation.adapters
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.AdapterView.OnItemClickListener
import androidx.recyclerview.widget.ListAdapter
import com.register.currencyexrate.databinding.CurrencyItemBinding
import com.register.currencyexrate.domain.entities.CurrencyInfo
class CurrencyListAdapter: ListAdapter<CurrencyInfo, CurrencyItemViewHolder>(CurrencyItemDiffCallback) {
private var clickListener: OnItemClickListener? = null
fun setOnItemClickListener(listener: OnItemClickListener) {
clickListener = listener
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CurrencyItemViewHolder {
val binding = CurrencyItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
return CurrencyItemViewHolder(binding)
}
override fun onBindViewHolder(holder: CurrencyItemViewHolder, position: Int) {
val currency = getItem(position)
with(holder.binding) {
currencyName.text = currency.charCode
currencyValue.text = currency.value.toString()
}
holder.itemView.setOnClickListener {
clickListener?.onItemClick(position)
}
}
interface OnItemClickListener {
fun onItemClick(position: Int)
}
} | CurrencyExRate/app/src/main/java/com/register/currencyexrate/presentation/adapters/CurrencyListAdapter.kt | 1254207304 |
package com.register.currencyexrate.presentation.adapters
import androidx.recyclerview.widget.RecyclerView
import com.register.currencyexrate.databinding.CurrencyItemBinding
class CurrencyItemViewHolder(
val binding: CurrencyItemBinding
): RecyclerView.ViewHolder(binding.root) | CurrencyExRate/app/src/main/java/com/register/currencyexrate/presentation/adapters/CurrencyItemViewHolder.kt | 329434427 |
package com.suzy.lifemaster
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.suzy.lifemaster", appContext.packageName)
}
} | LifeMaster/app/src/androidTest/java/com/suzy/lifemaster/ExampleInstrumentedTest.kt | 3112643373 |
package com.suzy.lifemaster
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | LifeMaster/app/src/test/java/com/suzy/lifemaster/ExampleUnitTest.kt | 585433727 |
package com.suzy.lifemaster.ui.home
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class HomeViewModel : ViewModel() {
private val _text = MutableLiveData<String>().apply {
value = "This is home Fragment"
}
val text: LiveData<String> = _text
} | LifeMaster/app/src/main/java/com/suzy/lifemaster/ui/home/HomeViewModel.kt | 1703925906 |
package com.suzy.lifemaster.ui.home
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.suzy.lifemaster.databinding.FragmentHomeBinding
class HomeFragment : Fragment() {
private var _binding: FragmentHomeBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val homeViewModel =
ViewModelProvider(this).get(HomeViewModel::class.java)
_binding = FragmentHomeBinding.inflate(inflater, container, false)
val root: View = binding.root
val textView: TextView = binding.textHome
homeViewModel.text.observe(viewLifecycleOwner) {
textView.text = it
}
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | LifeMaster/app/src/main/java/com/suzy/lifemaster/ui/home/HomeFragment.kt | 750407017 |
package com.suzy.lifemaster.ui.dashboard
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.suzy.lifemaster.databinding.FragmentDashboardBinding
class DashboardFragment : Fragment() {
private var _binding: FragmentDashboardBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val dashboardViewModel =
ViewModelProvider(this).get(DashboardViewModel::class.java)
_binding = FragmentDashboardBinding.inflate(inflater, container, false)
val root: View = binding.root
val textView: TextView = binding.textDashboard
dashboardViewModel.text.observe(viewLifecycleOwner) {
textView.text = it
}
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | LifeMaster/app/src/main/java/com/suzy/lifemaster/ui/dashboard/DashboardFragment.kt | 3735132239 |
package com.suzy.lifemaster.ui.dashboard
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class DashboardViewModel : ViewModel() {
private val _text = MutableLiveData<String>().apply {
value = "This is dashboard Fragment"
}
val text: LiveData<String> = _text
} | LifeMaster/app/src/main/java/com/suzy/lifemaster/ui/dashboard/DashboardViewModel.kt | 227188333 |
package com.suzy.lifemaster.ui.notifications
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class NotificationsViewModel : ViewModel() {
private val _text = MutableLiveData<String>().apply {
value = "This is notifications Fragment"
}
val text: LiveData<String> = _text
} | LifeMaster/app/src/main/java/com/suzy/lifemaster/ui/notifications/NotificationsViewModel.kt | 3775618492 |
package com.suzy.lifemaster.ui.notifications
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.suzy.lifemaster.databinding.FragmentNotificationsBinding
class NotificationsFragment : Fragment() {
private var _binding: FragmentNotificationsBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val notificationsViewModel =
ViewModelProvider(this).get(NotificationsViewModel::class.java)
_binding = FragmentNotificationsBinding.inflate(inflater, container, false)
val root: View = binding.root
val textView: TextView = binding.textNotifications
notificationsViewModel.text.observe(viewLifecycleOwner) {
textView.text = it
}
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | LifeMaster/app/src/main/java/com/suzy/lifemaster/ui/notifications/NotificationsFragment.kt | 313908411 |
package com.suzy.lifemaster
import android.os.Bundle
import com.google.android.material.bottomnavigation.BottomNavigationView
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.suzy.lifemaster.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val navView: BottomNavigationView = binding.navView
val navController = findNavController(R.id.nav_host_fragment_activity_main)
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
val appBarConfiguration = AppBarConfiguration(
setOf(
R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications
)
)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
}
} | LifeMaster/app/src/main/java/com/suzy/lifemaster/MainActivity.kt | 1466911052 |
package com.cs.umu.dv22cen.trees
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.cs.umu.dv22cen.trees", appContext.packageName)
}
} | Trees/app/src/androidTest/java/com/cs/umu/dv22cen/trees/ExampleInstrumentedTest.kt | 168797720 |
package com.cs.umu.dv22cen.trees
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | Trees/app/src/test/java/com/cs/umu/dv22cen/trees/ExampleUnitTest.kt | 3677054621 |
package com.cs.umu.dv22cen.trees.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | Trees/app/src/main/java/com/cs/umu/dv22cen/trees/ui/theme/Color.kt | 3990283943 |
package com.cs.umu.dv22cen.trees.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun TreesTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | Trees/app/src/main/java/com/cs/umu/dv22cen/trees/ui/theme/Theme.kt | 2243574649 |
package com.cs.umu.dv22cen.trees.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | Trees/app/src/main/java/com/cs/umu/dv22cen/trees/ui/theme/Type.kt | 1206321533 |
package com.cs.umu.dv22cen.trees
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
/**
* Tree database class.
* @author Christoffer Eriksson dv22cen
* @since 2024-03-19
*/
@Database(entities = [TreeDB::class], version = 2)
abstract class TreeDatabase : RoomDatabase() {
/**
* Gets the treeDao
* @return TreeDao
*/
abstract fun treeDao(): TreeDao
companion object {
@Volatile
private var INSTANCE: TreeDatabase? = null
/**
* Gets database instance.
* @param context Context
* @return Database instance.
*/
fun getInstance(context: Context): TreeDatabase =
INSTANCE ?: synchronized(this) {
INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
}
/**
* Builds the database.
* @param context Context
*/
private fun buildDatabase(context: Context) =
Room.databaseBuilder(
context.applicationContext,
TreeDatabase::class.java, "tree_database.db"
).fallbackToDestructiveMigration().build()
}
} | Trees/app/src/main/java/com/cs/umu/dv22cen/trees/treeDatabase.kt | 3791491692 |
package com.cs.umu.dv22cen.trees
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.room.Room
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* Awards activity for Umeå Trees.
* @author Christoffer Eriksson dv22cen
* @since 2024-03-19
*/
class awards: AppCompatActivity() {
private lateinit var database:TreeDatabase
private lateinit var treeDao: TreeDao
private var treeTotal: Int = 0
private var treeFound: Int = 0
private var amounts = arrayOf(10, 100, 500, 1000, 2500, 5000, 10000, 20000, 30878)//default max to current max
private var drawables = arrayOf(R.drawable.dirt, R.drawable.seed, R.drawable.firts,
R.drawable.second, R.drawable.tree1, R.drawable.tree2, R.drawable.tree3, R.drawable.tree4,
R.drawable.finaltree)
private lateinit var imageViews: List<ImageView>
/**
* Runs when activity is created.
* @param savedInstanceState Possible bundle of saved data
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.awards)
setSupportActionBar(findViewById(R.id.my_toolbar))
supportActionBar?.title = "Umeå Träd"
imageViews = listOf(findViewById(R.id.imageView10), findViewById(R.id.imageView100),
findViewById(R.id.imageView500), findViewById(R.id.imageView1000),
findViewById(R.id.imageView2500), findViewById(R.id.imageView5000),
findViewById(R.id.imageView10000), findViewById(R.id.imageView20000),
findViewById(R.id.imageViewAll))
database = Room.databaseBuilder(
this,
TreeDatabase::class.java, "tree_database.db"
).fallbackToDestructiveMigration().build()
treeTotal = intent.getIntExtra("com.cs.umu.dv22cen.trees.total", 0)
amounts[8] = treeTotal
treeDao = database.treeDao()
lifecycleScope.launch {
getTrees()
}
}
/**
* Gets trees and writes amounts found and amount left.
*/
private suspend fun getTrees(){
treeFound = treeDao.getRowCount()
withContext (Dispatchers.Main) {
for (i in 0..8){
if(treeFound >= amounts[i]){
imageViews[i].setImageResource(drawables[i])
}
}
}
}
/**
* Creates the APPbar.
* @param menu1 The menu.
* @return true
*/
override fun onCreateOptionsMenu(menu1: Menu?): Boolean {
val inflater: MenuInflater = menuInflater
inflater.inflate(R.menu.toolbar, menu1)
return true
}
/**
* Runs when an item in appbar is pressed.
* @param item the Item.
* @return true/false if item identified and handled.
*/
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
R.id.treeDex -> {
val myIntent: Intent = Intent(
this,
listDataBase::class.java
)
myIntent.putExtra("com.cs.umu.dv22cen.trees.total", treeTotal)
finish()
this.startActivity(myIntent)
true
}
R.id.action_settings -> {
val myIntent: Intent = Intent(
this,
settings::class.java
)
myIntent.putExtra("com.cs.umu.dv22cen.trees.total", treeTotal)
finish()
this.startActivity(myIntent)
true
}
R.id.help ->{
val myIntent: Intent = Intent(
this,
help::class.java
)
myIntent.putExtra("com.cs.umu.dv22cen.trees.total", treeTotal)
finish()
this.startActivity(myIntent)
true
}
R.id.award ->{
val intent = intent
finish()
this.startActivity(intent)
true
}
else -> {
false
}
}
} | Trees/app/src/main/java/com/cs/umu/dv22cen/trees/awards.kt | 1951790226 |
package com.cs.umu.dv22cen.trees
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.widget.Button
import android.widget.SeekBar
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
/**
* Settings activity fro Umeå Träd.
* Sätter radien för att hitta träd och mängden träd på kartan.
* @author Christoffer Eriksson dv22cen
* @since 2024-03-19
*/
class settings : AppCompatActivity() {
private lateinit var radius: SeekBar
private lateinit var amountTrees: SeekBar
private lateinit var choose: Button
private var distance: Int = 50
private var amount: Int = 20
private var total: Int = 0
/**
* Runs when activity is created.
* @param savedInstanceState Possible bundle of saved data
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.settings)
radius = findViewById(R.id.seekBar)
amountTrees = findViewById(R.id.seekBar2)
choose = findViewById(R.id.button)
setSupportActionBar(findViewById(R.id.my_toolbar))
supportActionBar?.title = "Umeå Träd"
total = intent.getIntExtra("com.cs.umu.dv22cen.trees.total", 0)
choose.setOnClickListener{
val myIntent: Intent = Intent(
this,
MainActivity::class.java
)
myIntent.putExtra("com.cs.umu.dv22cen.trees.radius", distance)
myIntent.putExtra("com.cs.umu.dv22cen.trees.amount", amount)
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
finish()
this.startActivity(myIntent)
}
radius.setOnSeekBarChangeListener(object :
SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seek: SeekBar,
progress: Int, fromUser: Boolean) {
}
override fun onStartTrackingTouch(seek: SeekBar) {
// write custom code for progress is started
}
override fun onStopTrackingTouch(seek: SeekBar) {
// write custom code for progress is stopped
Toast.makeText(this@settings,
"Valt värde: " + seek.progress*10 + "m",
Toast.LENGTH_SHORT).show()
distance = seek.progress*10
}
})
amountTrees.setOnSeekBarChangeListener(object :
SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seek: SeekBar,
progress: Int, fromUser: Boolean) {
}
override fun onStartTrackingTouch(seek: SeekBar) {
// write custom code for progress is started
}
override fun onStopTrackingTouch(seek: SeekBar) {
// write custom code for progress is stopped
Toast.makeText(this@settings,
"Valt värde: " + seek.progress*4 + "st",
Toast.LENGTH_SHORT).show()
amount = seek.progress*4
}
})
}
/**
* Creates the APPbar.
* @param menu1 The menu.
* @return true
*/
override fun onCreateOptionsMenu(menu1: Menu?): Boolean {
val inflater: MenuInflater = menuInflater
inflater.inflate(R.menu.toolbar, menu1)
return true
}
/**
* Runs when an item in appbar is pressed.
* @param item the Item.
* @return true/false if item identified and handled.
*/
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
R.id.treeDex -> {
val myIntent: Intent = Intent(
this,
listDataBase::class.java
)
myIntent.putExtra("com.cs.umu.dv22cen.trees.total", total)
finish()
this.startActivity(myIntent)
true
}
R.id.action_settings -> {
val intent = intent
finish()
startActivity(intent)
true
}
R.id.help ->{
val myIntent: Intent = Intent(
this,
help::class.java
)
myIntent.putExtra("com.cs.umu.dv22cen.trees.total", total)
finish()
this.startActivity(myIntent)
true
}
R.id.award ->{
val myIntent: Intent = Intent(
this,
awards::class.java
)
myIntent.putExtra("com.cs.umu.dv22cen.trees.total", total)
finish()
this.startActivity(myIntent)
true
}
else -> {
false
}
}
} | Trees/app/src/main/java/com/cs/umu/dv22cen/trees/settings.kt | 1430652546 |
package com.cs.umu.dv22cen.trees
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.IntentSender
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.Color.TRANSPARENT
import android.location.Location
import android.os.Bundle
import android.os.Looper
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.widget.Button
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.lifecycle.lifecycleScope
import androidx.room.Room
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import com.google.android.gms.common.api.ResolvableApiException
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationResult
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.LocationSettingsRequest
import com.google.android.gms.location.LocationSettingsResponse
import com.google.android.gms.location.Priority
import com.google.android.gms.location.SettingsClient
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.CircleOptions
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
import com.google.android.gms.maps.model.PolylineOptions
import com.google.android.gms.tasks.CancellationTokenSource
import com.google.android.gms.tasks.Task
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject
/**
* Main activity of android app for Umeå municipality trees
* Handles the GUI with Map and AppBar.
* When pressing back the app always quits.
* Owns an instance of the database where trees are stored.
* Does API:requests using volley.
* @author Christoffer Eriksson dv22cen
* @since 2024-03-19
*/
class MainActivity : AppCompatActivity(), OnMapReadyCallback{
private val LOCATION_PERMISSION_REQUEST_CODE = 1
private lateinit var fusedLocationClient: FusedLocationProviderClient
private lateinit var currentLocation: Location
private lateinit var map: GoogleMap
private lateinit var locationCallback: LocationCallback
private lateinit var catchButton: Button
private val viewModel: treeViewModel by viewModels()
protected val REQUEST_CHECK_SETTINGS = 0x1
private lateinit var database:TreeDatabase
private lateinit var treeDao: TreeDao
private lateinit var queue: RequestQueue
/**
* Runs when the activity is created
* Creates all local variables for GUI Views and sets onClickListener.
* Creates the database and map.
* @param savedInstanceState The possible saved data since the activity last ran
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_layout)
viewModel.createEdge()
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
catchButton = findViewById(R.id.catch_button)
catchButton.visibility = INVISIBLE
setSupportActionBar(findViewById(R.id.my_toolbar))
supportActionBar?.title = "Umeå Träd"
queue = Volley.newRequestQueue(this)
val intent = intent
if(intent.hasExtra("com.cs.umu.dv22cen.trees.radius") && intent.hasExtra("com.cs.umu.dv22cen.trees.amount"))
{
viewModel.setRadius(intent.getIntExtra("com.cs.umu.dv22cen.trees.radius", 50))
viewModel.setAmount(intent.getIntExtra("com.cs.umu.dv22cen.trees.amount", 20))
}
database = Room.databaseBuilder(
this,
TreeDatabase::class.java, "tree_database.db"
).fallbackToDestructiveMigration().build()
treeDao = database.treeDao()
setLocationCallback()
mapFragment.getMapAsync(this)
setCatchListener()
}
/**
* Runs when the activity is paused.
*/
override fun onPause() {
super.onPause()
stopLocationUpdates()
}
/**
* Runs when the activity is resumed.
*/
override fun onResume() {
super.onResume()
if (viewModel.isRequesting()) checkLocationSettings()
}
/**
* Sets the callback which is run when a new location is collected.
*/
private fun setLocationCallback() {
locationCallback = object : LocationCallback() {
override fun onLocationResult(p0: LocationResult) {
catchButton.visibility = INVISIBLE
for (location in p0.locations) {
map.clear()
val polylineOptions = PolylineOptions()
.add(viewModel.getEdge(0))
.add(viewModel.getEdge(1))
.add(viewModel.getEdge(2))
.add(viewModel.getEdge(3))
.add(viewModel.getEdge(4))
.add(viewModel.getEdge(0))
map.addPolyline(polylineOptions)
currentLocation = location
val current = LatLng(location.latitude, location.longitude)
map.addMarker(
MarkerOptions()
.position(current)
.title("Du")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
)
map.addCircle(
CircleOptions()
.center(LatLng(location.latitude, location.longitude))
.radius(viewModel.getRadius().toDouble())
.strokeColor(Color.YELLOW)
.fillColor(TRANSPARENT)
)
getTrees(location.latitude, location.longitude)
}
}
}
}
/**
* Sets the onClickListener of the catchButton.
*/
private fun setCatchListener(){
catchButton.setOnClickListener {
val trees = viewModel.getCurrentTreeArray()
val treesCaught = ArrayList<responseObject>()
for (x in trees){
val treeCoordinates = x.coordinate
val treeLocation = Location("")
treeLocation.latitude = treeCoordinates.latitude
treeLocation.longitude = treeCoordinates.longitude
if(treeLocation.distanceTo(currentLocation) < viewModel.getRadius()){
treesCaught.add(x)
}
}
lifecycleScope.launch {
insertDb(treesCaught)
}
}
}
/**
* Runs when the AppBar is created.
* @param menu1 The menu
* @return true if success
*/
override fun onCreateOptionsMenu(menu1: Menu?): Boolean {
val inflater: MenuInflater = menuInflater
inflater.inflate(R.menu.toolbar, menu1)
return true
}
/**
* Runs when an item in the menu is pressed.
* @param item The pressed item
* @return boolean True if success reading what clicked/else false
*/
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
R.id.treeDex -> {
val myIntent: Intent = Intent(
this,
listDataBase::class.java
)
myIntent.putExtra("com.cs.umu.dv22cen.trees.total", viewModel.getTotalTrees())
this.startActivity(myIntent)
true
}
R.id.action_settings -> {
val myIntent: Intent = Intent(
this,
settings::class.java
)
myIntent.putExtra("com.cs.umu.dv22cen.trees.total", viewModel.getTotalTrees())
this.startActivity(myIntent)
true
}
R.id.help ->{
val myIntent: Intent = Intent(
this,
help::class.java
)
myIntent.putExtra("com.cs.umu.dv22cen.trees.total", viewModel.getTotalTrees())
this.startActivity(myIntent)
true
}
R.id.award ->{
val myIntent: Intent = Intent(
this,
awards::class.java
)
myIntent.putExtra("com.cs.umu.dv22cen.trees.total", viewModel.getTotalTrees())
this.startActivity(myIntent)
true
}
else -> {
false
}
}
/**
* Runs when the map is ready
* @param googleMap The map.
*/
override fun onMapReady(googleMap: GoogleMap) {
map = googleMap
map.setInfoWindowAdapter(MyInfoWindowAdapter(this))
startLocation(map)
}
/**
* Gets the starting location of the phone.
* Adds a marker at current position.
* @param googleMap The map
*/
private fun startLocation(googleMap: GoogleMap){
var lat = 0.0
var long = 0.0
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION), LOCATION_PERMISSION_REQUEST_CODE)
}
fusedLocationClient.getCurrentLocation(Priority.PRIORITY_BALANCED_POWER_ACCURACY, CancellationTokenSource().token)
.addOnSuccessListener { location : Location? ->
if (location != null) {
currentLocation = location
}
val current = location?.let { LatLng(location.latitude, it.longitude) }
current?.let {
moveToCurrentLocation(current)
lat = location.latitude
long = location.longitude
MarkerOptions()
.position(it)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
.title("Du")
}?.let {
googleMap.addMarker(
it
)
}
if(!viewModel.isRequesting()){
checkLocationSettings()
}
}
}
/**
* Runs when permissions are requested.
*/
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startLocation(map)
} else {
Toast.makeText(this@MainActivity,
"Applikationen fungerar inte utan platstjänster",
Toast.LENGTH_SHORT).show()
}
}
}
/**
* Pans the camera on map to current location.
* @param currentLocation Current coordinates.
*/
private fun moveToCurrentLocation(currentLocation: LatLng) {
map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 15f))
map.animateCamera(CameraUpdateFactory.zoomIn())
map.animateCamera(CameraUpdateFactory.zoomTo(15f), 2000, null)
}
/**
* Gets trees from API.
* @param lat The latitude currently
* @param long The longitude currently
*/
private fun getTrees(lat: Double, long: Double){
viewModel.clearTrees()
viewModel.clearMarkers()
val url1 = "https://opendata.umea.se/api/explore/v2.1/catalog/datasets/trad-som-forvaltas-av-gator-och-parker/records?order_by=distance(geo_point_2d%2C%20geom%27POINT("
val url2 = "%20"
val url3 = ")%27)Asc&limit="
val url4 = viewModel.getAmount().toString()
val url = url1 + long + url2 + lat + url3 + url4
val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null,
{ response ->
val total = response.getInt("total_count")
viewModel.setTotalTrees(total)
val array = response.getJSONArray("results")
if(array.length() > 0){
for(index in 0..< array.length()){
val responseApi: JSONObject = array.getJSONObject(index)
insertTrees(responseApi, index)
}
}
if(viewModel.isRequesting()){
//My understanding of this is that the job will complete and be collected
// but the scope will exist for future jobs to be put on it until the
// activity dies
lifecycleScope.launch {
checkDbMarkers(map)
}
}
},
{ error ->
Toast.makeText(this@MainActivity,
error.toString(),
Toast.LENGTH_SHORT).show()
}
)
// Access the RequestQueue through your singleton class.
queue.add(jsonObjectRequest)
}
/**
* Inserts trees into viewModel
* @param responseApi The tree info response.
* @param index The index of tree.
*/
private fun insertTrees(responseApi: JSONObject, index: Int){
val coords = responseApi.getJSONObject("geo_point_2d")
val longitude = coords.optDouble("lon")
val latitude = coords.optDouble("lat")
val treeType = responseApi.optString("lov_eller_barrtrad_1_1_1")
val treeSpecies = responseApi.optString("tradart_vetenskap_namn_1_1_2")
val treeName = responseApi.optString("tradart_svenskt_namn_1_1_3")
val treePlacement = responseApi.optString("gatu_eller_parktrad_1_4_4")
val date = responseApi.optString("planteringsdatum_6_1_1")
val info = "$treeType,$treeSpecies,$treeName,$treePlacement,$date"
viewModel.insertTree(LatLng(latitude, longitude), treeType, treeSpecies, treeName, treePlacement, date, info, index)
}
/**
* Inserts trees into database.
* @param treesCaught ArrayList of trees being added.
*/
private suspend fun insertDb(treesCaught: ArrayList<responseObject>) {
val markers = ArrayList<Marker>()
for(x in treesCaught){
val treeInsert = TreeDB(x.coordinate.latitude, x.coordinate.longitude, x.treeType,
x.treeSpecies, x.treeName, x.treePlacement, x.date, x.info)
treeDao.insert(treeInsert)
markers.add(viewModel.getMarker(x.index))
}
withContext (Dispatchers.Main) {
colourMarker(map, markers)
}
}
/**
* Checks if trees of markers are in database.
* @param googleMap The map.
*/
private suspend fun checkDbMarkers(googleMap: GoogleMap){
val size = viewModel.getAmountTrees()
for (index in 0..<size){
val tree = viewModel.getTree(index)
val lat = tree.coordinate.latitude
val lon = tree.coordinate.longitude
val treeFromDB = treeDao.findByCoord(lat,lon)
var treeMarker: Marker?
withContext (Dispatchers.Main) {
if(treeFromDB == null){
treeMarker = googleMap.addMarker(
MarkerOptions()
.position(tree.coordinate)
.title("Tree $index")
.snippet(tree.info)
)
}
else{
treeMarker = googleMap.addMarker(
MarkerOptions()
.position(LatLng(treeFromDB.lat, treeFromDB.lon))
.title("Tree $index")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.snippet(treeFromDB.info)
)
}
if (treeMarker != null) {
viewModel.insertMarker(index, treeMarker!!)
}
catchButton.visibility = VISIBLE
}
}
}
/**
* Changes colour of marker.
* @param map The map.
* @param markers ArrayList of markers being coloured.
*/
private fun colourMarker(map: GoogleMap, markers: ArrayList<Marker>){
for(x in 0..<markers.size){
markers[x].remove()
val tree = viewModel.getTree(x)
val info = tree.info
val treeMarker = map.addMarker(
MarkerOptions()
.position(tree.coordinate)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.title("Tree $x")
.snippet(info)
)
viewModel.removeMarker(x)
if (treeMarker != null) {
viewModel.insertMarker(x, treeMarker)
}
}
}
/**
* Checks the settings of phone.
*/
private fun checkLocationSettings(){
val locationRequest = LocationRequest.Builder(10000)
.setMinUpdateDistanceMeters(20F)
.setPriority(Priority.PRIORITY_HIGH_ACCURACY)
.setMinUpdateIntervalMillis(10000)
.build()
val builder = LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest)
val client: SettingsClient = LocationServices.getSettingsClient(this)
val task: Task<LocationSettingsResponse> = client.checkLocationSettings(builder.build())
task.addOnSuccessListener {
viewModel.setIsRequesting(true)
startLocationUpdates(locationRequest)
}
task.addOnFailureListener { exception ->
if (exception is ResolvableApiException){
try {
exception.startResolutionForResult(this@MainActivity,
REQUEST_CHECK_SETTINGS)
} catch (sendEx: IntentSender.SendIntentException) {
Toast.makeText(this@MainActivity,
sendEx.toString(),
Toast.LENGTH_SHORT).show()
}
}
}
}
/**
* Starts Location updates.
* @param locationRequest The request being run.
*/
@SuppressLint("MissingPermission")
private fun startLocationUpdates(locationRequest: LocationRequest) {
fusedLocationClient.requestLocationUpdates(locationRequest,
locationCallback,
Looper.getMainLooper())
}
/**
* Stops location requests.
*/
private fun stopLocationUpdates() {
fusedLocationClient.removeLocationUpdates(locationCallback)
viewModel.setIsRequesting(false)
}
}
| Trees/app/src/main/java/com/cs/umu/dv22cen/trees/MainActivity.kt | 263159692 |
package com.cs.umu.dv22cen.trees
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
/**
* Help activity for Umeå Trees.
* @author Christoffer Eriksson dv22cen
* @since 2024-03-19
*/
class help: AppCompatActivity() {
private var total: Int = 0
/**
* Runs when activity is created.
* @param savedInstanceState Possible bundle of saved data
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.help)
setSupportActionBar(findViewById(R.id.my_toolbar))
supportActionBar?.title = "Umeå Träd"
total = intent.getIntExtra("com.cs.umu.dv22cen.trees.total", 0)
}
/**
* Creates the APPbar.
* @param menu1 The menu.
* @return true
*/
override fun onCreateOptionsMenu(menu1: Menu?): Boolean {
val inflater: MenuInflater = menuInflater
inflater.inflate(R.menu.toolbar, menu1)
return true
}
/**
* Runs when an item in appbar is pressed.
* @param item the Item.
* @return true/false if item identified and handled.
*/
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
R.id.treeDex -> {
val myIntent: Intent = Intent(
this,
listDataBase::class.java
)
myIntent.putExtra("com.cs.umu.dv22cen.trees.total", total)
finish()
this.startActivity(myIntent)
true
}
R.id.action_settings -> {
val myIntent: Intent = Intent(
this,
settings::class.java
)
myIntent.putExtra("com.cs.umu.dv22cen.trees.total", total)
finish()
startActivity(myIntent)
true
}
R.id.help ->{
val intent = intent
finish()
startActivity(intent)
true
}
else -> {
false
}
}
} | Trees/app/src/main/java/com/cs/umu/dv22cen/trees/help.kt | 882396484 |
package com.cs.umu.dv22cen.trees
import android.annotation.SuppressLint
import android.content.Context
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.model.Marker
/**
* InfoWindow for makrers clicked in google map.
* @author Christoffer Eriksson dv22cen
* @since 2024-03-19
*/
class MyInfoWindowAdapter(mContext: Context) : GoogleMap.InfoWindowAdapter {
private var mWindow: View = LayoutInflater.from(mContext).inflate(R.layout.info_window, null)
/**
* Sets the text of info window.
* @param marker The marker pressed.
*/
@SuppressLint("SetTextI18n")
private fun setInfoWindowText(marker: Marker) {
val title = marker.title
val snippet = marker.snippet
val titleLayout = mWindow.findViewById<TextView>(R.id.title)
val type = mWindow.findViewById<TextView>(R.id.type)
val species = mWindow.findViewById<TextView>(R.id.species)
val namn = mWindow.findViewById<TextView>(R.id.namn)
val placement = mWindow.findViewById<TextView>(R.id.placement)
val date = mWindow.findViewById<TextView>(R.id.date)
val valuesList: List<String> = snippet!!.split(",")
if (!TextUtils.isEmpty(title)) {
titleLayout.text = title
type.text = "Typ: " + valuesList[0]
species.text = "Art: " + valuesList[1]
namn.text = "Namn: " + valuesList[2]
placement.text = "Placering: " + valuesList[3]
date.text = "Planterades: " + valuesList[4]
}
}
/**
* Returns the info window.
* @param p0 The marker pressed.
* @return View info window.
*/
override fun getInfoWindow(p0: Marker): View? {
if(p0.title != "Du"){
setInfoWindowText(p0)
return mWindow
}
return null
}
/**
* Returns the info window contents.
* @param p0 The marker pressed.
* @return View info window.
*/
override fun getInfoContents(p0: Marker): View? {
if(p0.title != "Du"){
setInfoWindowText(p0)
return mWindow
}
return null
}
} | Trees/app/src/main/java/com/cs/umu/dv22cen/trees/InfoWindowClass.kt | 507677420 |
package com.cs.umu.dv22cen.trees
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
/**
* TreeDao interface for interacting with database.
* @author Christoffer Eriksson dv22cen
* @since 2024-03-19
*/
@Dao
interface TreeDao {
/**
* Gets all trees from database.
*/
@Query("SELECT * FROM treedb")
suspend fun getAll(): List<TreeDB>
/**
* Gets a tree based on coordinates.
*/
@Query("SELECT * FROM treedb WHERE lat LIKE :lat AND lon LIKE :lon")
suspend fun findByCoord(lat: Double, lon: Double): TreeDB?
/**
* Gets amount of trees in database.
*/
@Query("SELECT COUNT(*) FROM treedb")
suspend fun getRowCount(): Int
/**
* Removes all rows in database.
*/
//Should not be used unless testing
@Query("DELETE FROM treedb")
suspend fun nukeTable()
/**
* Inserts all trees in list.
*/
@Insert
suspend fun insertAll(vararg trees: TreeDB)
/**
* Inserts a tree.
*/
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(tree: TreeDB)
/**
* Deletes a tree.
*/
@Delete
suspend fun delete(tree: TreeDB)
} | Trees/app/src/main/java/com/cs/umu/dv22cen/trees/TreeDao.kt | 2129553997 |
package com.cs.umu.dv22cen.trees
import com.google.android.gms.maps.model.LatLng
/**
* Dataclass for trees as responseObjects from Umeå Kommun API.
* @author Christoffer Eriksson dv22cen
* @since 2024-03-19
*/
data class responseObject(var coordinate : LatLng, val treeType: String, var treeSpecies: String,
var treeName: String, var treePlacement: String, var date: String, var info: String, var index:Int) {
} | Trees/app/src/main/java/com/cs/umu/dv22cen/trees/responseObject.kt | 3770670361 |
package com.cs.umu.dv22cen.trees
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.google.android.gms.maps.model.LatLng
import io.reactivex.annotations.NonNull
/**
* Tree relation class
* @author Christoffer Eriksson dv22cen
* @since 2024-03-19
*/
@Entity(primaryKeys = ["lat", "lon"])
data class TreeDB(
@ColumnInfo(name = "lat") val lat: Double,
@ColumnInfo(name = "lon") val lon: Double,
@ColumnInfo(name = "type") val type: String?,
@ColumnInfo(name = "species") val species: String?,
@ColumnInfo(name = "name") val name: String?,
@ColumnInfo(name = "placement") val placement: String?,
@ColumnInfo(name = "date") val date: String?,
@ColumnInfo(name = "info") val info: String?
)
| Trees/app/src/main/java/com/cs/umu/dv22cen/trees/TreeDB.kt | 369523012 |
package com.cs.umu.dv22cen.trees
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.room.Room
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.properties.Delegates
/**
* Statistics of found trees activity.
* @author Christoffer Eriksson dv22cen
* @since 2024-03-19
*/
class listDataBase: AppCompatActivity() {
private lateinit var database:TreeDatabase
private lateinit var treeDao: TreeDao
private lateinit var amountText: TextView
private lateinit var amountLeft: TextView
private var treeFound: Int = 0
private var treeTotal: Int = 0
/**
* Runs when activity is created.
* @param savedInstanceState Possible bundle of saved data
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.listdatabase)
val intent = intent
setSupportActionBar(findViewById(R.id.my_toolbar))
supportActionBar?.title = "Umeå Träd"
database = Room.databaseBuilder(
this,
TreeDatabase::class.java, "tree_database.db"
).fallbackToDestructiveMigration().build()
treeTotal = intent.getIntExtra("com.cs.umu.dv22cen.trees.total", 0)
treeDao = database.treeDao()
amountText = findViewById(R.id.treeAmount)
amountLeft = findViewById(R.id.treeAmountLeft)
lifecycleScope.launch {
getTrees()
}
}
/**
* Gets trees and writes amounts found and amount left.
*/
private suspend fun getTrees(){
treeFound = treeDao.getRowCount()
val treesLeft = treeFound
withContext (Dispatchers.Main) {
amountText.text = treesLeft.toString()
amountLeft.text = (treeTotal - treeFound).toString()
}
}
/**
* Creates the APPbar.
* @param menu1 The menu.
* @return true
*/
override fun onCreateOptionsMenu(menu1: Menu?): Boolean {
val inflater: MenuInflater = menuInflater
inflater.inflate(R.menu.toolbar, menu1)
return true
}
/**
* Runs when an item in appbar is pressed.
* @param item the Item.
* @return true/false if item identified and handled.
*/
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
R.id.treeDex -> {
val intent = intent
finish()
startActivity(intent)
true
}
R.id.action_settings -> {
val myIntent: Intent = Intent(
this,
settings::class.java
)
myIntent.putExtra("com.cs.umu.dv22cen.trees.total", treeTotal)
finish()
this.startActivity(myIntent)
true
}
R.id.help ->{
val myIntent: Intent = Intent(
this,
help::class.java
)
myIntent.putExtra("com.cs.umu.dv22cen.trees.total", treeTotal)
finish()
this.startActivity(myIntent)
true
}
R.id.award ->{
val myIntent: Intent = Intent(
this,
awards::class.java
)
myIntent.putExtra("com.cs.umu.dv22cen.trees.total", treeTotal)
finish()
this.startActivity(myIntent)
true
}
else -> {
false
}
}
} | Trees/app/src/main/java/com/cs/umu/dv22cen/trees/listDataBase.kt | 983052658 |
package com.cs.umu.dv22cen.trees
import androidx.lifecycle.ViewModel
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Marker
/**
* ViewModel for Umeå Trees.
* Holds data for business logic.
* @author Christoffer Eriksson dv22cen
* @since 2024-03-19
*/
class treeViewModel : ViewModel(){
private var currentTreeArray = ArrayList<responseObject>()
private var currentMarkers = ArrayList<Marker>()
private var edgeCoords = ArrayList<LatLng>()
private var isRequesting = false
private var totalTrees: Int = 0
private var radius: Int = 50
private var amount: Int = 20
/**
* Sets the amount of trees shown on map.
* @param value New amount.
*/
fun setAmount(value: Int){
amount = value
}
/**
* Gets the amount of trees shown on map.
* @return amount in Int
*/
fun getAmount(): Int {
return amount
}
/**
* Sets the radius where trees can be caught.
* @param value New radius.
*/
fun setRadius(value: Int){
radius = value
}
/**
* Gets the radius trees can get caught in.
* @return radius in Int
*/
fun getRadius(): Int {
return radius
}
/**
* Sets the amount of total trees.
* @param value New total.
*/
fun setTotalTrees(value: Int){
totalTrees = value
}
/**
* Gets amount of total trees.
* @return Total trees INT
*/
fun getTotalTrees(): Int {
return totalTrees
}
/**
* Sets isRequesting or not.
* @param value true/false
*/
fun setIsRequesting(value: Boolean){
isRequesting = value
}
/**
* Checks if isRequesting.
* @return true if requesting/false.
*/
fun isRequesting(): Boolean {
return isRequesting
}
/**
* Creates edges for area where trees are.
*/
fun createEdge(){
edgeCoords.add(LatLng(63.60058801627824, 19.90512209328035))
edgeCoords.add(LatLng(63.637458984908186, 19.87140091076691))
edgeCoords.add(LatLng(63.884630136196584, 20.032408116193817))
edgeCoords.add(LatLng(63.90963719553976, 20.56794576006403))
edgeCoords.add(LatLng(63.814108255731824, 20.516780194224896))
}
/**
* Gets the edge of area where trees ares.
* @param index Index of edge.
* @return Coordinates of start for edge.
*/
fun getEdge(index: Int): LatLng {
return edgeCoords[index]
}
/**
* Inserts marker.
* @param index Index where inserted is placed.
* @param marker The marker.
*/
fun insertMarker(index: Int,marker: Marker){
currentMarkers.add(index,marker)
}
/**
* Gets a marker.
* @param index Index of marker.
* @return The marker.
*/
fun getMarker(index: Int): Marker {
return currentMarkers[index]
}
/**
* Removes a marker.
* @param index Index of marker.
*/
fun removeMarker(index: Int){
currentMarkers.removeAt(index)
}
/**
* Removes all markers.
*/
fun clearMarkers(){
currentMarkers.clear()
}
/**
* Inserts a tree.
* @param coordinate Coordinates of tree.
* @param treeType Type of tree string.
* @param treeName Name of tree string.
* @param treeSpecies Species of tree string.
* @param treePlacement Placement of tree string.
* @param date Date of plantation string.
* @param info Info about tree string.
* @param index Index of tree.
*/
fun insertTree(coordinate: LatLng, treeType: String, treeSpecies: String, treeName: String, treePlacement: String, date: String, info: String, index:Int) {
currentTreeArray.add(responseObject(coordinate, treeType, treeName, treeSpecies, treePlacement, date, info, index))
}
/**
* Removes all trees.
*/
fun clearTrees(){
currentTreeArray.clear()
}
/**
* Gets currentTreeArray.
* @return CurrentTreeArray.
*/
fun getCurrentTreeArray(): ArrayList<responseObject> {
return currentTreeArray
}
/**
* Gets a tree.
* @param index Index of tree.
* @return Tree as responseObject.
*/
fun getTree(index: Int): responseObject {
return currentTreeArray[index]
}
/**
* Gets the amount of trees.
* @return amount as Int.
*/
fun getAmountTrees(): Int {
return currentTreeArray.size
}
} | Trees/app/src/main/java/com/cs/umu/dv22cen/trees/treeViewModel.kt | 1802146270 |
import com.elbekd.bot.Bot
import com.elbekd.bot.feature.chain.chain
import com.elbekd.bot.model.toChatId
class RabbitRedBot {
val profileService = ProfileService()
val token = System.getenv("BOT_TOKEN")
val bot = Bot.createPolling(token)
fun bot() {
var email = ""
var password = ""
var chatId = ""
bot.onCommand("/start") { (msg, _) ->
chatId = msg.chat.id.toString()
println(chatId)
val isChatIdExits = profileService.isChatIdExists(chatId)
if (isChatIdExits == "false") {
bot.sendMessage(msg.chat.id.toChatId(), "For registration pleas send /registration")
} else {
bot.sendMessage(msg.chat.id.toChatId(), "For login pleas send /login")
}
}
bot.chain("/registration") { msg ->
chatId = msg.chat.id.toString()
println(chatId)
val isChatIdExits = profileService.isChatIdExists(chatId)
if (isChatIdExits == "false") {
bot.sendMessage(msg.chat.id.toChatId(), "Hi! Pleas send me your email")
}
}
.then { msg ->
email = msg.text.toString()
bot.sendMessage(msg.chat.id.toChatId(), "Thank you! Pleas send me your password")
}
.then { msg ->
password = msg.text.toString()
chatId = msg.chat.id.toChatId().toString()
val response = profileService.registration(email, password, chatId)
bot.sendMessage(msg.chat.id.toChatId(), "Fine! $response")
}
.build()
bot.chain("/login") { msg ->
bot.sendMessage(msg.chat.id.toChatId(), "Hi! Pleas send me your email")
}
.then { msg ->
email = msg.text.toString()
bot.sendMessage(msg.chat.id.toChatId(), "Thank you! Pleas send me your password")
}
.then { msg ->
password = msg.text.toString()
val response = profileService.login(email, password)
bot.sendMessage(msg.chat.id.toChatId(), "Fine! $response")
}
.build()
bot.start()
}
} | rabbit-bot/src/main/kotlin/RabbitRedBot.kt | 40212333 |
fun main() {
RabbitRedBot().bot()
} | rabbit-bot/src/main/kotlin/Main.kt | 1926244259 |
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.serialization.json.Json
val host = "http://localhost:8080/"
class ProfileService {
suspend fun registration(email: String, password: String, chatId: String): String {
val client = HttpClient(CIO) {
install(ContentNegotiation) {
json(Json {
prettyPrint = true
isLenient = true
})
}
}
val response: HttpResponse = client.post("${host}auth/registration") {
contentType(ContentType.Application.Json)
setBody(Profile(email, password, chatId))
}
// val response: HttpResponse = client.get("${host}habits") {
// headers {
// append(HttpHeaders.Authorization,
// "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJyZWQucmFiYml0IiwiZW1haWwiOiJsb2dpbkBnbS5jb20iLCJleHAiOjE3MDcwNzQzMjJ9.yDokwKDq6_FoxB2XlaALr_auNueCkcMEC0yqMB8CwNE")
// }
// }
return response.body()
}
suspend fun isChatIdExists(chatId: String): String {
val client = HttpClient(CIO) {
install(ContentNegotiation) {
json(Json {
prettyPrint = true
isLenient = true
})
}
}
val response: HttpResponse = client.get("${host}auth/isChatIdExists") {
parameter("chatId", chatId)
}
return response.body()
}
suspend fun login(email: String, password: String): String {
val client = HttpClient(CIO) {
install(ContentNegotiation) {
json(Json {
prettyPrint = true
isLenient = true
})
}
}
val response: HttpResponse = client.post("${host}auth/login") {
contentType(ContentType.Application.Json)
setBody(Profile(email, password, null))
}
return response.body()
}
} | rabbit-bot/src/main/kotlin/ProfileService.kt | 1679192208 |
import kotlinx.serialization.Serializable
@Serializable
data class Profile(
val email: String,
val password: String,
val chatId: String?
)
| rabbit-bot/src/main/kotlin/BotDataClass.kt | 1860988633 |
package com.example.myapplication
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.myapplication", appContext.packageName)
}
} | AndroidSonarCloudIntegration/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt | 1188990709 |
package com.example.myapplication
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | AndroidSonarCloudIntegration/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt | 2019423820 |
package com.example.myapplication.ui.home
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class HomeViewModel : ViewModel() {
private val _text = MutableLiveData<String>().apply {
value = "This is home Fragment"
}
val text: LiveData<String> = _text
} | AndroidSonarCloudIntegration/app/src/main/java/com/example/myapplication/ui/home/HomeViewModel.kt | 3600328474 |
package com.example.myapplication.ui.home
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.myapplication.databinding.FragmentHomeBinding
class HomeFragment : Fragment() {
private var _binding: FragmentHomeBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val homeViewModel =
ViewModelProvider(this).get(HomeViewModel::class.java)
_binding = FragmentHomeBinding.inflate(inflater, container, false)
val root: View = binding.root
val textView: TextView = binding.textHome
homeViewModel.text.observe(viewLifecycleOwner) {
textView.text = it
}
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | AndroidSonarCloudIntegration/app/src/main/java/com/example/myapplication/ui/home/HomeFragment.kt | 3141711831 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.