content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.dto.response import androidx.annotation.Keep import com.google.gson.annotations.SerializedName @Keep internal data class ItemResponseDto( @SerializedName("description") val description: String, @SerializedName("name") val name: String, @SerializedName("price") val price: String, @SerializedName("quantity") val quantity: String, @SerializedName("tax") val tax: String, )
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/data/datasource/remote/dto/response/ItemResponseDto.kt
2163649968
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.dto.response import androidx.annotation.Keep import com.google.gson.annotations.SerializedName @Keep internal data class AmountResponseDto( @SerializedName("details") val details: DetailsResponseDto, @SerializedName("total") val total: String, )
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/data/datasource/remote/dto/response/AmountResponseDto.kt
1119675824
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.dto.response import androidx.annotation.Keep import com.google.gson.annotations.SerializedName @Keep internal data class PaymentResponseDto( @SerializedName("amount") val amount: AmountResponseDto, @SerializedName("created_at") val createdAt: String, @SerializedName("currency") val currency: String, @SerializedName("description") val description: String, @SerializedName("invoice_number") val invoiceNumber: String, @SerializedName("items") val items: List<ItemResponseDto>, @SerializedName("links") val links: List<LinkResponseDto>, @SerializedName("merchant_op_id") val merchantOpId: String, @SerializedName("status_code") val statusCode: Int, @SerializedName("status_denom") val statusName: String, @SerializedName("terminal_id") val terminalId: String, @SerializedName("transaction_uuid") val transactionUuid: String, @SerializedName("updated_at") val updateAt: String, @SerializedName("commission") val commission: String, @SerializedName("transaction_signature") val transactionSignature: String, )
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/data/datasource/remote/dto/response/PaymentResponseDto.kt
2339856478
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.dto.response import androidx.annotation.Keep import com.google.gson.annotations.SerializedName @Keep internal data class LinkResponseDto( @SerializedName("href") val href: String, @SerializedName("method") val method: String, @SerializedName("rel") val rel: String, )
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/data/datasource/remote/dto/response/LinkResponseDto.kt
2763038677
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.dto.request import androidx.annotation.Keep import com.google.gson.annotations.SerializedName @Keep internal data class AmountDto( @SerializedName("details") val details: DetailsDto, @SerializedName("total") val total: String, )
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/data/datasource/remote/dto/request/AmountDto.kt
2702345263
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.dto.request import androidx.annotation.Keep import com.google.gson.annotations.SerializedName @Keep internal data class DetailsDto( @SerializedName("discount") val discount: String, @SerializedName("shipping") val shipping: String, @SerializedName("tax") val tax: String, @SerializedName("tip") val tip: String, )
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/data/datasource/remote/dto/request/DetailsDto.kt
82978808
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.dto.request import androidx.annotation.Keep import com.google.gson.annotations.SerializedName @Keep internal data class ItemDto( @SerializedName("description") val description: String, @SerializedName("name") val name: String, @SerializedName("price") val price: String, @SerializedName("quantity") val quantity: Int, @SerializedName("tax") val tax: String, )
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/data/datasource/remote/dto/request/ItemDto.kt
1637533702
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.dto.request.create import androidx.annotation.Keep import com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.dto.request.AmountDto import com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.dto.request.ItemDto import com.google.gson.annotations.SerializedName @Keep internal data class CreatePaymentDto( @SerializedName("amount") val amount: AmountDto, @SerializedName("buyer_identity_code") val buyerIdentityCode: String, @SerializedName("cancel_url") val cancelUrl: String, @SerializedName("currency") val currency: String, @SerializedName("description") val description: String, @SerializedName("invoice_number") val invoiceNumber: String, @SerializedName("items") val items: List<ItemDto>, @SerializedName("merchant_op_id") val merchantOpId: String, @SerializedName("merchant_uuid") val merchantUuid: String, @SerializedName("return_url") val returnUrl: String, @SerializedName("terminal_id") val terminalId: String, )
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/data/datasource/remote/dto/request/create/CreatePaymentDto.kt
2667656292
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.datasource.util import android.annotation.SuppressLint import okhttp3.MediaType import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response import java.security.SecureRandom import java.security.cert.X509Certificate import javax.net.ssl.SSLContext import javax.net.ssl.TrustManager import javax.net.ssl.X509TrustManager /** * Executes an HTTP POST request using OkHttpClient. * @param fullUrl The full URL for the POST request. * @param mediaTypeContent The media type of the request content (e.g., "application/json"). * @param content The content of the request. * @param headers A map of headers to be included in the request. * @return The response of the POST request. */ internal fun OkHttpClient.post( fullUrl: String, mediaTypeContent: String, content: String, headers: Map<String, String>, ): Response { val mediaType: MediaType? = mediaTypeContent.toMediaTypeOrNull() val body: RequestBody = content.toRequestBody(mediaType) val request: Request = Request.Builder() .url(fullUrl) .post(body) .apply { headers.forEach { addHeader(it.key, it.value) } } .build() return newCall(request).execute() } /** * Executes an HTTP GET request using OkHttpClient. * @param fullUrl The full URL for the GET request. * @param headers A map of headers to be included in the request. * @return The response of the GET request. */ internal fun OkHttpClient.get( fullUrl: String, headers: Map<String, String>, ): Response { val request: Request = Request.Builder() .url(fullUrl) .apply { headers.forEach { addHeader(it.key, it.value) } } .build() return newCall(request).execute() } /** * Configures OkHttpClient.Builder to ignore SSL/TLS certificates. * Use with caution and only in scenarios where certificate validation is not required. * @return The modified OkHttpClient.Builder. */ internal fun OkHttpClient.Builder.ignoreCertificates(): OkHttpClient.Builder { // Create a trust manager that does not validate certificate chains val trustAllCerts = arrayOf<TrustManager>( @SuppressLint("CustomX509TrustManager") object : X509TrustManager { @SuppressLint("TrustAllX509TrustManager") override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) = Unit @SuppressLint("TrustAllX509TrustManager") override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) = Unit override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf() } ) // Install the all-trusting trust manager val sslContext = SSLContext.getInstance("SSL") sslContext.init(null, trustAllCerts, SecureRandom()) // Create an SSL socket factory with our all-trusting manager val sslSocketFactory = sslContext.socketFactory sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager) hostnameVerifier { _, _ -> true } return this }
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/data/datasource/remote/datasource/util/Extensions.kt
771574022
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.datasource import com.github.jdsdhp.enzona.payment.embedded.Enzona import com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.datasource.util.get import com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.datasource.util.post import com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.dto.request.AmountDto import com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.dto.request.DetailsDto import com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.dto.request.create.CreatePaymentDto import com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.dto.response.PaymentResponseDto import com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.dto.response.cancel.CancelResponseDto import com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.mapper.asData import com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.mapper.asDomain import com.github.jdsdhp.enzona.payment.embedded.domain.datasource.PaymentRemoteDatasource import com.github.jdsdhp.enzona.payment.embedded.domain.datasource.RemoteDatasource import com.github.jdsdhp.enzona.payment.embedded.domain.model.CancelStatus import com.github.jdsdhp.enzona.payment.embedded.domain.model.Item import com.github.jdsdhp.enzona.payment.embedded.domain.model.Payment import com.github.jdsdhp.enzona.payment.embedded.util.ResultValue import com.google.gson.Gson import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext import okhttp3.OkHttpClient internal class PaymentRemoteDatasourceImpl( private val okHttpClient: OkHttpClient, private val dispatcher: CoroutineDispatcher, private val remoteDatasource: RemoteDatasource, ) : PaymentRemoteDatasource { /** * Enumeration representing different API endpoints. */ private enum class Endpoint(val path: String) { PAYMENTS("payment/v1.0.0/payments") } /** * Gson instance for JSON serialization and deserialization. */ private val gson: Gson = Gson() override suspend fun createPayment( apiUrl: Enzona.ApiUrl, token: String, discount: Double, shipping: Double, tip: Double, buyerIdentityCode: String, cancelUrl: String, currency: String, description: String, invoiceNumber: String, merchantOpId: Long, merchantUuid: String, returnUrl: String, terminalId: String, items: List<Item>, ): ResultValue<Payment> = withContext(dispatcher) { remoteDatasource.call { var totalPrice = 0.0 var totalTax = 0.0 items.forEach { totalPrice += it.price * it.quantity totalTax += it.tax } val details = DetailsDto( discount = "${discount}0", shipping = "${shipping}0", tax = "${totalTax}0", tip = "${tip}0", ) val amount = AmountDto( details = details, total = "${totalPrice + (shipping + totalTax + tip - discount)}0", ) val createPayment = CreatePaymentDto( amount = amount, buyerIdentityCode = buyerIdentityCode, cancelUrl = cancelUrl, currency = currency, description = description, invoiceNumber = invoiceNumber, items = items.map { it.asData() }, merchantOpId = merchantOpId.toString().padStart(12, '0'), merchantUuid = merchantUuid, returnUrl = returnUrl, terminalId = terminalId, ) val res = okHttpClient.post( fullUrl = "${apiUrl.url}/${Endpoint.PAYMENTS.path}", mediaTypeContent = "application/json", content = gson.toJson(createPayment), headers = mapOf("Authorization" to "Bearer $token"), ) gson.fromJson(res.body?.string(), PaymentResponseDto::class.java).asDomain() } } override suspend fun getPaymentDetails( apiUrl: Enzona.ApiUrl, token: String, transactionUuid: String, ): ResultValue<Payment> = withContext(dispatcher) { remoteDatasource.call { val res = okHttpClient.get( fullUrl = "${apiUrl.url}/${Endpoint.PAYMENTS.path}/$transactionUuid", headers = mapOf("Authorization" to "Bearer $token"), ) gson.fromJson(res.body?.string(), PaymentResponseDto::class.java).asDomain() } } override suspend fun cancelPayment( apiUrl: Enzona.ApiUrl, token: String, transactionUuid: String, ): ResultValue<CancelStatus> = withContext(dispatcher) { remoteDatasource.call { val res = okHttpClient.post( fullUrl = "${apiUrl.url}/${Endpoint.PAYMENTS.path}/$transactionUuid/cancel", mediaTypeContent = "application/json", content = "", headers = mapOf("Authorization" to "Bearer $token"), ) gson.fromJson(res.body?.string(), CancelResponseDto::class.java).asDomain() } } override suspend fun completePayment( apiUrl: Enzona.ApiUrl, token: String, transactionUuid: String, ): ResultValue<Payment> = withContext(dispatcher) { remoteDatasource.call { val res = okHttpClient.post( fullUrl = "${apiUrl.url}/${Endpoint.PAYMENTS.path}/$transactionUuid/complete", mediaTypeContent = "application/json", content = "", headers = mapOf("Authorization" to "Bearer $token"), ) gson.fromJson(res.body?.string(), PaymentResponseDto::class.java).asDomain() } } }
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/data/datasource/remote/datasource/PaymentRemoteDatasourceImpl.kt
4156641531
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.datasource import com.github.jdsdhp.enzona.payment.embedded.domain.datasource.RemoteDatasource import com.github.jdsdhp.enzona.payment.embedded.util.ResultValue /** * Internal class representing a remote data source abstraction. */ internal class RemoteDatasourceImpl : RemoteDatasource { override suspend fun <T> call(request: suspend () -> T): ResultValue<T> = safeApiCall(request = request) /** * Performs a safe API call without token handling, handling exceptions and returning a ResultValue. * @param request The suspended function performing the API call. * @return A [ResultValue] containing the API call result. */ private suspend fun <T> safeApiCall(request: suspend () -> T): ResultValue<T> = try { val res = request.invoke() ResultValue.Success(res) } catch (e: Exception) { ResultValue.Error(e) } }
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/data/datasource/remote/datasource/RemoteDatasourceImpl.kt
3206109335
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.datasource import com.github.jdsdhp.enzona.payment.embedded.Enzona import com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.datasource.util.post import com.github.jdsdhp.enzona.payment.embedded.domain.datasource.AuthRemoteDatasource import com.github.jdsdhp.enzona.payment.embedded.domain.datasource.RemoteDatasource import com.github.jdsdhp.enzona.payment.embedded.domain.model.Scope import com.github.jdsdhp.enzona.payment.embedded.domain.model.Token import com.github.jdsdhp.enzona.payment.embedded.util.ResultValue import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext import okhttp3.OkHttpClient import org.json.JSONException import org.json.JSONObject import kotlin.io.encoding.Base64 import kotlin.io.encoding.ExperimentalEncodingApi internal class AuthRemoteDatasourceImpl( private val okHttpClient: OkHttpClient, private val dispatcher: CoroutineDispatcher, private val remoteDatasource: RemoteDatasource, ) : AuthRemoteDatasource { @OptIn(ExperimentalEncodingApi::class) override suspend fun authenticate( apiUrl: Enzona.ApiUrl, consumerKey: String, consumerSecret: String, ): ResultValue<Token> = withContext(dispatcher) { remoteDatasource.call { val authHeader = "Basic ${Base64.encode("$consumerKey:$consumerSecret".toByteArray())}" val res = okHttpClient.post( fullUrl = "${apiUrl.url}/token", mediaTypeContent = "application/x-www-form-urlencoded", content = "grant_type=client_credentials&scope=${Scope.ENZONA_BUSINESS_PAYMENT.label}", headers = mapOf("Authorization" to authHeader), ) val json = JSONObject(res.body?.string() ?: throw JSONException("Token parsing error.")) val token = json.getString("access_token") val expiresIn = json.getInt("expires_in") val expireTime: Long = System.currentTimeMillis().plus(expiresIn) Token(accessToken = token, expireTime = expireTime) } } }
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/data/datasource/remote/datasource/AuthRemoteDatasourceImpl.kt
4223611519
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.mapper import com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.dto.request.AmountDto import com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.dto.request.DetailsDto import com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.dto.request.ItemDto import com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.dto.response.ItemResponseDto import com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.dto.response.LinkResponseDto import com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.dto.response.PaymentResponseDto import com.github.jdsdhp.enzona.payment.embedded.data.datasource.remote.dto.response.cancel.CancelResponseDto import com.github.jdsdhp.enzona.payment.embedded.domain.model.Amount import com.github.jdsdhp.enzona.payment.embedded.domain.model.CancelStatus import com.github.jdsdhp.enzona.payment.embedded.domain.model.Details import com.github.jdsdhp.enzona.payment.embedded.domain.model.Item import com.github.jdsdhp.enzona.payment.embedded.domain.model.Link import com.github.jdsdhp.enzona.payment.embedded.domain.model.Payment internal fun DetailsDto.asDomain(): Details = Details( discount = discount.toDouble(), shipping = shipping.toDouble(), tax = tax.toDouble(), tip = tip.toDouble(), ) internal fun Details.asData(): DetailsDto = DetailsDto( discount = "${discount}0", shipping = "${shipping}0", tax = "${tax}0", tip = "${tip}0", ) internal fun AmountDto.asDomain(): Amount = Amount(details = details.asDomain(), total = total.toDouble()) internal fun Amount.asData(): AmountDto = AmountDto(details = details.asData(), total = "${total}0") internal fun ItemDto.asDomain(): Item = Item( quantity = quantity, name = name, description = description, price = price.toDouble(), tax = tax.toDouble(), ) internal fun Item.asData(): ItemDto = ItemDto( quantity = quantity, name = name, description = description, price = "${price}0", tax = "${tax}0", ) internal fun ItemResponseDto.asDomain(): Item = Item( quantity = quantity.toInt(), name = name, description = description, price = price.toDouble(), tax = tax.toDouble(), ) internal fun LinkResponseDto.asDomain(): Link = Link(rel = rel, method = method, href = href) internal fun PaymentResponseDto.asDomain() = Payment( transactionUuid, createdAt, updateAt, statusCode, statusName, currency, description, totalPrice = amount.total.toDouble(), items = items.map { it.asDomain() }, links = links.map { it.asDomain() } ) internal fun CancelResponseDto.asDomain(): CancelStatus = CancelStatus( statusCode = statusCode.toInt(), statusName = statusName, transactionName = transactionName, transactionUuid = transactionUuid, updateAt = updateAt, )
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/data/datasource/remote/mapper/Mappers.kt
3162233493
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.domain.datasource import com.github.jdsdhp.enzona.payment.embedded.util.ResultValue /** * Interface representing a remote data source for making network calls. */ internal interface RemoteDatasource { /** * Executes a network call. * @param request The suspending lambda function that defines the network call. * @return A [ResultValue] containing the result of the network call. */ suspend fun <T> call(request: suspend () -> T): ResultValue<T> }
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/domain/datasource/RemoteDatasource.kt
614020979
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.domain.datasource import com.github.jdsdhp.enzona.payment.embedded.Enzona import com.github.jdsdhp.enzona.payment.embedded.domain.model.CancelStatus import com.github.jdsdhp.enzona.payment.embedded.domain.model.Item import com.github.jdsdhp.enzona.payment.embedded.domain.model.Payment import com.github.jdsdhp.enzona.payment.embedded.util.ResultValue /** * Interface representing a remote data source for payment creation. */ internal interface PaymentRemoteDatasource { /** * Suspend function to create a payment remotely. * @param apiUrl The Enzona API URL to be used (official or sandbox). * @param token The authentication token. * @param discount The discount amount for the payment. * @param shipping The shipping cost for the payment. * @param tip The tip amount for the payment. * @param buyerIdentityCode The identity code of the buyer. * @param cancelUrl The URL to redirect to when the payment is canceled. * @param currency The currency of the payment. * @param description The description of the payment. * @param invoiceNumber The invoice number associated with the payment. * @param merchantOpId The merchant operation ID. * @param merchantUuid The UUID of the merchant. * @param returnUrl The URL to return to after a successful payment. * @param terminalId The terminal ID associated with the payment. * @param items List of items included in the payment. * @return ResultValue containing the created payment information. */ suspend fun createPayment( apiUrl: Enzona.ApiUrl, token: String, discount: Double, shipping: Double, tip: Double, buyerIdentityCode: String, cancelUrl: String, currency: String, description: String, invoiceNumber: String, merchantOpId: Long, merchantUuid: String, returnUrl: String, terminalId: String, items: List<Item>, ): ResultValue<Payment> /** * Suspend function to get payment details remotely. * @param apiUrl The Enzona API URL to be used (official or sandbox). * @param token The authentication token. * @param transactionUuid The UUID of the transaction. * @return ResultValue containing the payment details. */ suspend fun getPaymentDetails( apiUrl: Enzona.ApiUrl, token: String, transactionUuid: String ): ResultValue<Payment> /** * Suspend function to cancel a payment remotely. * @param apiUrl The Enzona API URL to be used (official or sandbox). * @param token The authentication token. * @param transactionUuid The UUID of the transaction to be canceled. * @return ResultValue containing the cancellation status. */ suspend fun cancelPayment( apiUrl: Enzona.ApiUrl, token: String, transactionUuid: String ): ResultValue<CancelStatus> /** * Suspend function to complete a payment remotely. * @param apiUrl The Enzona API URL to be used (official or sandbox). * @param token The authentication token. * @param transactionUuid The UUID of the transaction to be completed. * @return ResultValue containing the payment details after completion. */ suspend fun completePayment( apiUrl: Enzona.ApiUrl, token: String, transactionUuid: String ): ResultValue<Payment> }
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/domain/datasource/PaymentRemoteDatasource.kt
2238279983
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.domain.datasource import com.github.jdsdhp.enzona.payment.embedded.Enzona import com.github.jdsdhp.enzona.payment.embedded.domain.model.Token import com.github.jdsdhp.enzona.payment.embedded.util.ResultValue /** * Interface representing a remote data source for authentication. */ internal interface AuthRemoteDatasource { /** * Suspend function to authenticate using consumer key and consumer secret. * @param apiUrl The Enzona API URL to be used (official or sandbox). * @param consumerKey The consumer key for authentication. * @param consumerSecret The consumer secret for authentication. * @return ResultValue containing the authentication token. */ suspend fun authenticate( apiUrl: Enzona.ApiUrl, consumerKey: String, consumerSecret: String, ): ResultValue<Token> }
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/domain/datasource/AuthRemoteDatasource.kt
871527240
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.domain.model /** * Data class representing details associated with an amount. * @property discount The discount amount. * @property shipping The shipping amount. * @property tax The tax amount. * @property tip The tip amount. */ data class Details( val discount: Double, val shipping: Double, val tax: Double, val tip: Double, )
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/domain/model/Details.kt
1521510632
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.domain.model /** * Data class representing a payment. * @property transactionUuid The unique identifier for the payment transaction. * @property createdAt The timestamp indicating when the payment was created. * @property updatedAt The timestamp indicating when the payment was last updated. * @property statusCode The numeric status code of the payment. * @property statusName The name of the payment status. * @property currency The currency used for the payment. * @property description A description associated with the payment. * @property totalPrice The total price of the payment. * @property items The list of items included in the payment. * @property links The list of links associated with the payment. */ data class Payment( val transactionUuid: String, val createdAt: String, val updatedAt: String, val statusCode: Int, val statusName: String, val currency: String, val description: String, val totalPrice: Double, val items: List<Item>, val links: List<Link>, )
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/domain/model/Payment.kt
665315115
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.domain.model /** * Enumeration representing different scopes. * @property label The label associated with the scope. */ internal enum class Scope(val label: String) { /** * Scope for Enzona business payment. */ ENZONA_BUSINESS_PAYMENT("enzona_business_payment") }
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/domain/model/Scope.kt
2803217830
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.domain.model /** * Data class representing an item. * @property quantity The quantity of the item. * @property name The name of the item. * @property description The description of the item. * @property price The price of the item. * @property tax The tax associated with the item. */ data class Item( val quantity: Int, val name: String, val description: String, val price: Double, val tax: Double, )
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/domain/model/Item.kt
576772748
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.domain.model /** * Data class representing the cancellation status of a payment. * @property statusCode The code indicating the cancellation status. * @property statusName The name describing the cancellation status. * @property transactionName The name of the transaction associated with the cancellation. * @property transactionUuid The UUID of the transaction associated with the cancellation. * @property updateAt The timestamp indicating when the cancellation status was last updated. */ data class CancelStatus( val statusCode: Int, val statusName: String, val transactionName: String, val transactionUuid: String, val updateAt: String, )
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/domain/model/CancelStatus.kt
1232995438
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.domain.model /** * Data class representing an authentication token. * @property accessToken The access token for authentication. * @property expireTime The expiration time of the access token. */ data class Token( val accessToken: String, val expireTime: Long, )
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/domain/model/Token.kt
2709095292
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.domain.model /** * Data class representing an amount, including details and total. * @property details The details associated with the amount. * @property total The total amount. */ internal data class Amount( val details: Details, val total: Double, )
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/domain/model/Amount.kt
4167335860
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.domain.model /** * Data class representing a link. * @property rel The relationship type of the link. * @property method The HTTP method associated with the link. * @property href The URL associated with the link. */ data class Link( val rel: String, val method: String, val href: String, )
enzona-payment-embedded/enzona-payment-embedded/src/main/java/com/github/jdsdhp/enzona/payment/embedded/domain/model/Link.kt
944525676
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.embedded import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import org.junit.Assert.* import org.junit.Test import org.junit.runner.RunWith /** * 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.github.jdsdhp.crashalytics", appContext.packageName) } }
enzona-payment-embedded/app/src/androidTest/java/com/github/jdsdhp/embedded/ExampleInstrumentedTest.kt
661987848
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.embedded import org.junit.Assert.assertEquals import org.junit.Test /** * 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) } }
enzona-payment-embedded/app/src/test/java/com/github/jdsdhp/embedded/ExampleUnitTest.kt
806984875
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.sample import android.util.Log import android.util.Patterns import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.github.jdsdhp.enzona.payment.embedded.Enzona import com.github.jdsdhp.enzona.payment.embedded.domain.model.Item import com.github.jdsdhp.enzona.payment.embedded.domain.model.Payment import com.github.jdsdhp.enzona.payment.embedded.util.ResultValue import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import java.util.regex.Pattern private const val TAG = "dev/tag" internal class MainViewModel : ViewModel() { private val enzona = Enzona.getInstance() data class UiState( val isLoading: Boolean = false, val error: String? = null, val textMessage: String? = null, val consumerKey: String = "", val consumerSecret: String = "", val merchantUUID: String = "", val items: List<Item> = emptyList(), val createPayment: CreatePayment = CreatePayment(), val payment: Payment? = null, ) private val _uiState: MutableStateFlow<UiState> = MutableStateFlow(UiState()) val uiState: StateFlow<UiState> = _uiState.asStateFlow() data class CreatePayment( val discount: Double = 0.0, val shipping: Double = 0.0, val tip: Double = 0.0, val buyerIdentityCode: String = "", val cancelUrl: String = "https://www.enzona.net/payment/cancel", val returnUrl: String = "https://www.enzona.net/payment/return", val currency: String = "CUP", val description: String = "", val invoiceNumber: String = "", val merchantOpId: String = "1", val terminalId: String = "", ) init { viewModelScope.launch { _uiState.update { it.copy( items = listOf( /*Item( quantity = 2, name = "Mango", description = "Product One Description", price = 5.0, tax = 1.0, ), Item( quantity = 3, name = "Orange", description = "Product Two Description", price = 2.0, tax = 2.0, ),*/ Item( quantity = 1, name = "Guava", description = "Product Three Description", price = 1.0, tax = 0.0, ), ), ) } } } fun onConsumerKeyChanged(value: String) { viewModelScope.launch { _uiState.update { it.copy(consumerKey = value) } } } fun onConsumerSecretChanged(value: String) { viewModelScope.launch { _uiState.update { it.copy(consumerSecret = value) } } } fun onMerchantUUIDChanged(value: String) { viewModelScope.launch { _uiState.update { it.copy(merchantUUID = value) } } } fun onDiscountChanged(value: String) { value.toDoubleOrNull()?.let { v -> if (v >= 0.0) { viewModelScope.launch { val createPayment = _uiState.value.createPayment _uiState.update { state -> state.copy(createPayment = createPayment.copy(discount = v)) } } } } } fun onShippingChanged(value: String) { value.toDoubleOrNull()?.let { v -> if (v >= 0.0) { viewModelScope.launch { val createPayment = _uiState.value.createPayment _uiState.update { state -> state.copy(createPayment = createPayment.copy(shipping = v)) } } } } } fun onTipChanged(value: String) { value.toDoubleOrNull()?.let { v -> if (v >= 0.0) { viewModelScope.launch { val createPayment = _uiState.value.createPayment _uiState.update { state -> state.copy(createPayment = createPayment.copy(tip = v)) } } } } } fun onBuyerIdentityCodeChanged(value: String) { viewModelScope.launch { val createPayment = _uiState.value.createPayment _uiState.update { state -> state.copy(createPayment = createPayment.copy(buyerIdentityCode = value)) } } } fun onCancelUrlChanged(value: String) { if (Pattern.matches(Patterns.WEB_URL.pattern(), value)) { viewModelScope.launch { val createPayment = _uiState.value.createPayment _uiState.update { state -> state.copy(createPayment = createPayment.copy(cancelUrl = value)) } } } } fun onReturnUrlChanged(value: String) { if (Pattern.matches(Patterns.WEB_URL.pattern(), value)) { viewModelScope.launch { val createPayment = _uiState.value.createPayment _uiState.update { state -> state.copy(createPayment = createPayment.copy(returnUrl = value)) } } } } fun onCurrencyChanged(value: String) { viewModelScope.launch { val createPayment = _uiState.value.createPayment _uiState.update { state -> state.copy(createPayment = createPayment.copy(currency = value)) } } } fun onDescriptionChanged(value: String) { viewModelScope.launch { val createPayment = _uiState.value.createPayment _uiState.update { state -> state.copy(createPayment = createPayment.copy(description = value)) } } } fun onInvoiceNumberChanged(value: String) { viewModelScope.launch { val createPayment = _uiState.value.createPayment _uiState.update { state -> state.copy(createPayment = createPayment.copy(invoiceNumber = value)) } } } fun onMerchantOpIdChanged(value: String) { if (value.length <= 12) { value.toLongOrNull()?.let { viewModelScope.launch { val createPayment = _uiState.value.createPayment _uiState.update { state -> state.copy(createPayment = createPayment.copy(merchantOpId = value)) } } } } } fun onTerminalIdChanged(value: String) { viewModelScope.launch { val createPayment = _uiState.value.createPayment _uiState.update { state -> state.copy(createPayment = createPayment.copy(terminalId = value)) } } } fun onDialogClose() { viewModelScope.launch { _uiState.update { it.copy(textMessage = null, error = null) } } } fun onAuthButtonClick() { viewModelScope.launch { _uiState.update { it.copy(isLoading = true, textMessage = null, error = null) } enzona.initialize( apiUrl = Enzona.ApiUrl.OFFICIAL, merchantConsumerKey = _uiState.value.consumerKey, merchantConsumerSecret = _uiState.value.consumerSecret, merchantUUID = _uiState.value.merchantUUID, ) when (val res = enzona.authenticate()) { is ResultValue.Success -> { Log.d(TAG, "onAuthButtonClick: Success = $res") _uiState.update { it.copy( isLoading = false, textMessage = "Authenticated Successfully!", ) } } is ResultValue.Error -> { Log.d(TAG, "onAuthButtonClick: Error = $res") _uiState.update { it.copy( isLoading = false, error = res.exception.toString(), ) } } } } } fun onCreatePaymentClick() { viewModelScope.launch { _uiState.update { it.copy(isLoading = true, textMessage = null, error = null) } val createPayment: CreatePayment = _uiState.value.createPayment when (val res = enzona.createPayment( discount = createPayment.discount, shipping = createPayment.shipping, tip = createPayment.tip, buyerIdentityCode = createPayment.buyerIdentityCode, cancelUrl = createPayment.cancelUrl, currency = createPayment.currency, description = createPayment.description, invoiceNumber = createPayment.invoiceNumber, merchantOpId = createPayment.merchantOpId.toLong(), returnUrl = createPayment.returnUrl, terminalId = createPayment.terminalId, items = _uiState.value.items, )) { is ResultValue.Success -> { Log.d(TAG, "onCreatePaymentClick: Success = $res") _uiState.update { it.copy( payment = res.data, isLoading = false, textMessage = "Payment created successfully!", ) } } is ResultValue.Error -> { Log.d(TAG, "onCreatePaymentClick: Error = $res") _uiState.update { it.copy( isLoading = false, error = res.exception.toString(), ) } } } } } fun onGetPaymentDetailClick() { viewModelScope.launch { _uiState.update { it.copy(isLoading = true, textMessage = null, error = null) } when (val res = enzona.getPaymentDetails( transactionUuid = _uiState.value.payment?.transactionUuid ?: "", )) { is ResultValue.Success -> { Log.d(TAG, "onGetPaymentDetailClick: Success = $res") _uiState.update { it.copy( payment = res.data.copy( links = _uiState.value.payment?.links ?: emptyList() ), isLoading = false, textMessage = "Payment details updated!", ) } } is ResultValue.Error -> { Log.d(TAG, "onGetPaymentDetailClick: Error = $res") _uiState.update { it.copy( isLoading = false, error = res.exception.toString(), ) } } } } } fun onCancelPaymentClick() { viewModelScope.launch { _uiState.update { it.copy(isLoading = true, textMessage = null, error = null) } when (val res = enzona.cancelPayment( transactionUuid = _uiState.value.payment?.transactionUuid ?: "", )) { is ResultValue.Success -> { Log.d(TAG, "oCancelPaymentClick: Success = $res") _uiState.update { it.copy( payment = it.payment?.copy( updatedAt = res.data.updateAt, statusCode = res.data.statusCode, statusName = res.data.statusName, ), isLoading = false, textMessage = "Payment canceled successfully!", ) } } is ResultValue.Error -> { Log.d(TAG, "oCancelPaymentClick: Error = $res") _uiState.update { it.copy( isLoading = false, error = res.exception.toString(), ) } } } } } fun onCompletePaymentClick() { viewModelScope.launch { _uiState.update { it.copy(isLoading = true, textMessage = null, error = null) } when (val res = enzona.completePayment( transactionUuid = _uiState.value.payment?.transactionUuid ?: "", )) { is ResultValue.Success -> { Log.d(TAG, "onCompletePaymentClick: Success = $res") _uiState.update { it.copy( payment = res.data.copy( links = _uiState.value.payment?.links ?: emptyList() ), isLoading = false, textMessage = "Payment completed successfully!", ) } } is ResultValue.Error -> { Log.d(TAG, "onCompletePaymentClick: Error = $res") _uiState.update { it.copy( isLoading = false, error = res.exception.toString(), ) } } } } } }
enzona-payment-embedded/app/src/main/java/com/github/jdsdhp/enzona/payment/embedded/sample/MainViewModel.kt
3485728706
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.sample.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)
enzona-payment-embedded/app/src/main/java/com/github/jdsdhp/enzona/payment/embedded/sample/ui/theme/Color.kt
1713671135
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.sample.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 AppTheme( 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 ) }
enzona-payment-embedded/app/src/main/java/com/github/jdsdhp/enzona/payment/embedded/sample/ui/theme/Theme.kt
4184474374
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.sample.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 ) */ )
enzona-payment-embedded/app/src/main/java/com/github/jdsdhp/enzona/payment/embedded/sample/ui/theme/Type.kt
557994264
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.sample import android.app.Application class App : Application()
enzona-payment-embedded/app/src/main/java/com/github/jdsdhp/enzona/payment/embedded/sample/App.kt
3460381742
/* * Copyright (c) 2024 jesusd0897. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jdsdhp.enzona.payment.embedded.sample import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.github.jdsdhp.enzona.payment.embedded.sample.ui.theme.AppTheme class MainActivity : ComponentActivity() { private val viewModel: MainViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AppTheme { // A surface container using the 'background' color from the theme Surface(modifier = Modifier.fillMaxSize()) { MainScreen(viewModel = viewModel) } } } } } @Composable internal fun MainScreen( modifier: Modifier = Modifier, viewModel: MainViewModel, ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() Column( modifier = modifier .padding(16.dp) .verticalScroll(rememberScrollState()), horizontalAlignment = Alignment.CenterHorizontally, ) { Spacer(modifier = Modifier.height(16.dp)) Text( text = stringResource(id = R.string.authenticate), style = MaterialTheme.typography.titleLarge, ) Spacer(modifier = Modifier.height(16.dp)) TextField( modifier = Modifier.fillMaxWidth(), label = { Text(text = stringResource(R.string.consumer_key)) }, value = uiState.consumerKey, onValueChange = { viewModel.onConsumerKeyChanged(it) }, ) Spacer(modifier = Modifier.height(8.dp)) TextField( modifier = Modifier.fillMaxWidth(), label = { Text(text = stringResource(R.string.consumer_secret)) }, value = uiState.consumerSecret, onValueChange = { viewModel.onConsumerSecretChanged(it) }, ) Spacer(modifier = Modifier.height(8.dp)) TextField( modifier = Modifier.fillMaxWidth(), label = { Text(text = stringResource(R.string.merchant_uuid)) }, value = uiState.merchantUUID, onValueChange = { viewModel.onMerchantUUIDChanged(it) }, ) Spacer(modifier = Modifier.height(16.dp)) Button(onClick = { viewModel.onAuthButtonClick() }) { Text(text = stringResource(R.string.authenticate)) } Spacer(modifier = Modifier.height(16.dp)) HorizontalDivider() Spacer(modifier = Modifier.height(16.dp)) Text( text = stringResource(id = R.string.create_payment), style = MaterialTheme.typography.titleLarge, ) Spacer(modifier = Modifier.height(16.dp)) TextField( modifier = Modifier.fillMaxWidth(), label = { Text(text = stringResource(R.string.currency)) }, value = uiState.createPayment.currency, onValueChange = { viewModel.onCurrencyChanged(it) }, ) Spacer(modifier = Modifier.height(8.dp)) TextField( modifier = Modifier.fillMaxWidth(), label = { Text(text = stringResource(R.string.cancel_url)) }, value = uiState.createPayment.cancelUrl, onValueChange = { viewModel.onCancelUrlChanged(it) }, ) Spacer(modifier = Modifier.height(8.dp)) TextField( modifier = Modifier.fillMaxWidth(), label = { Text(text = stringResource(R.string.return_url)) }, value = uiState.createPayment.returnUrl, onValueChange = { viewModel.onReturnUrlChanged(it) }, ) Spacer(modifier = Modifier.height(8.dp)) TextField( modifier = Modifier.fillMaxWidth(), label = { Text(text = stringResource(R.string.merchant_op_id_12_digits_max)) }, value = uiState.createPayment.merchantOpId, onValueChange = { viewModel.onMerchantOpIdChanged(it) }, ) Spacer(modifier = Modifier.height(8.dp)) TextField( modifier = Modifier.fillMaxWidth(), label = { Text(text = stringResource(R.string.description_optional)) }, value = uiState.createPayment.description, onValueChange = { viewModel.onDescriptionChanged(it) }, ) Spacer(modifier = Modifier.height(8.dp)) TextField( modifier = Modifier.fillMaxWidth(), label = { Text(text = stringResource(R.string.invoice_number_optional)) }, value = uiState.createPayment.invoiceNumber, onValueChange = { viewModel.onInvoiceNumberChanged(it) }, ) Spacer(modifier = Modifier.height(8.dp)) TextField( modifier = Modifier.fillMaxWidth(), label = { Text(text = stringResource(R.string.discount_optional)) }, value = uiState.createPayment.discount.toString(), onValueChange = { viewModel.onDiscountChanged(it) }, ) Spacer(modifier = Modifier.height(8.dp)) TextField( modifier = Modifier.fillMaxWidth(), label = { Text(text = stringResource(R.string.tip_optional)) }, value = uiState.createPayment.tip.toString(), onValueChange = { viewModel.onTipChanged(it) }, ) Spacer(modifier = Modifier.height(8.dp)) TextField( modifier = Modifier.fillMaxWidth(), label = { Text(text = stringResource(R.string.shipping_optional)) }, value = uiState.createPayment.shipping.toString(), onValueChange = { viewModel.onShippingChanged(it) }, ) Spacer(modifier = Modifier.height(8.dp)) TextField( modifier = Modifier.fillMaxWidth(), label = { Text(text = stringResource(R.string.buyer_identity_code_optional)) }, value = uiState.createPayment.buyerIdentityCode, onValueChange = { viewModel.onBuyerIdentityCodeChanged(it) }, ) Spacer(modifier = Modifier.height(8.dp)) TextField( modifier = Modifier.fillMaxWidth(), label = { Text(text = stringResource(R.string.terminal_id_optional)) }, value = uiState.createPayment.terminalId, onValueChange = { viewModel.onTerminalIdChanged(it) }, ) Spacer(modifier = Modifier.height(8.dp)) Column(modifier = Modifier.fillMaxWidth()) { uiState.items.forEach { Card(modifier = Modifier.fillMaxWidth()) { Column(modifier = Modifier.padding(8.dp)) { Text(text = it.name + " (${it.quantity})") Text(text = it.description) Text(text = "$${it.price}") Text(text = stringResource(R.string.tax_dots, it.tax)) } } Spacer(modifier = Modifier.height(4.dp)) } } Spacer(modifier = Modifier.height(16.dp)) Button(onClick = { viewModel.onCreatePaymentClick() }) { Text(text = stringResource(R.string.create_payment)) } Spacer(modifier = Modifier.height(16.dp)) HorizontalDivider() Spacer(modifier = Modifier.height(16.dp)) Text( text = stringResource(R.string.payment_details), style = MaterialTheme.typography.titleLarge, ) Spacer(modifier = Modifier.height(16.dp)) Card(modifier = Modifier.fillMaxWidth()) { Column(modifier = Modifier.padding(8.dp)) { uiState.payment?.let { payment -> Text( text = stringResource( R.string.transaction_uuid_dots, payment.transactionUuid ) ) Text(text = stringResource(R.string.status_code_dots, payment.statusCode)) Text(text = stringResource(R.string.status_name_dots, payment.statusName)) Text(text = stringResource(R.string.description_dots, payment.description)) Text(text = stringResource(R.string.currency_dots, payment.currency)) Text(text = stringResource(R.string.created_at_dots, payment.createdAt)) Text(text = stringResource(R.string.updated_at_dots, payment.updatedAt)) Text(text = stringResource(R.string.total_price_dots, payment.totalPrice)) payment.links.forEach { Spacer(modifier = Modifier.height(4.dp)) Text(text = "${it.rel} - ${it.method} - ${it.href}") } Spacer(modifier = Modifier.height(4.dp)) } } } Spacer(modifier = Modifier.height(16.dp)) Button(onClick = { viewModel.onGetPaymentDetailClick() }) { Text(text = stringResource(R.string.get_payment_details)) } Spacer(modifier = Modifier.height(16.dp)) HorizontalDivider() Spacer(modifier = Modifier.height(16.dp)) Text( text = stringResource(R.string.cancel_payment), style = MaterialTheme.typography.titleLarge, ) Spacer(modifier = Modifier.height(16.dp)) Button(onClick = { viewModel.onCancelPaymentClick() }) { Text(text = stringResource(R.string.cancel_payment)) } Spacer(modifier = Modifier.height(16.dp)) HorizontalDivider() Spacer(modifier = Modifier.height(16.dp)) Text( text = stringResource(R.string.complete_payment), style = MaterialTheme.typography.titleLarge, ) Spacer(modifier = Modifier.height(16.dp)) Button(onClick = { viewModel.onCompletePaymentClick() }) { Text(text = stringResource(R.string.complete_payment)) } Spacer(modifier = Modifier.height(16.dp)) } if (uiState.isLoading) { Box( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colorScheme.background), contentAlignment = Alignment.Center, ) { CircularProgressIndicator() } } uiState.textMessage?.let { AlertDialog( text = { Text(text = it) }, onDismissRequest = { viewModel.onDialogClose() }, confirmButton = { Button(onClick = { viewModel.onDialogClose() }) { Text(text = stringResource(R.string.accept)) } }, ) } uiState.error?.let { AlertDialog( text = { Text(text = it) }, onDismissRequest = { viewModel.onDialogClose() }, confirmButton = { Button(onClick = { viewModel.onDialogClose() }) { Text(text = stringResource(R.string.accept)) } }, ) } }
enzona-payment-embedded/app/src/main/java/com/github/jdsdhp/enzona/payment/embedded/sample/MainActivity.kt
524666449
import de.kevinboeckler.dojo.Feld import de.kevinboeckler.dojo.solve import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test class MainKtTest{ @Test fun cannotSee() { assertTrue(Feld(1, 1).cannotSee(Feld(2, 3))) assertFalse(Feld(1, 1).cannotSee(Feld(2, 2))) assertFalse(Feld(2, 3).cannotSee(Feld(3, 2))) } @Test fun solveOne() { assertNotNull(solve(setOf(Feld(1, 1)), 1)) } }
achtdamen/src/test/kotlin/MainKtTest.kt
872210192
package de.kevinboeckler.dojo import kotlin.math.abs import kotlin.system.measureTimeMillis fun main() { val millis = measureTimeMillis { val n = 8 val loesungen = solve(initFelder(n), n) println(loesungen.size) println(loesungen[0]) } print("$millis ms passed") } fun initFelder(n: Int): Set<Feld> { val felder = mutableSetOf<Feld>() for (i in 0..<n) { for (j in 0..<n) { felder.add(Feld(i, j)) } } return felder } fun solve(felder: Set<Feld>, damen: Int): List<Loesung> { if (damen == 0) { return listOf(Loesung(setOf())) } val loesungen = mutableListOf<Loesung>() val queue = felder.toMutableList() while (queue.isNotEmpty()) { val damenFeld = queue.removeAt(0) val neueFelder = streicheFelder(felder, damenFeld) val loesung = solve(neueFelder, damen - 1) for (unterLoesung in loesung) { val neueLoesung = unterLoesung.felder.toMutableSet() neueLoesung.add(damenFeld) loesungen.add(Loesung(neueLoesung)) neueLoesung.forEach { queue.remove(it) } } } return loesungen } fun streicheFelder(felder: Set<Feld>, dame: Feld): Set<Feld> = felder.filter { dame.cannotSee(it) }.toSet() data class Feld(val x: Int, val y: Int) { fun cannotSee(feld: Feld) = !(x == feld.x || y == feld.y || abs(feld.x - x) == abs(feld.y - y)) } data class Loesung(val felder: Set<Feld>)
achtdamen/src/main/kotlin/Main.kt
564579677
package com.example.flashcard 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.flashcard", appContext.packageName) } }
FlashCard1/app/src/androidTest/java/com/example/flashcard/ExampleInstrumentedTest.kt
1172248016
package com.example.flashcard 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) } }
FlashCard1/app/src/test/java/com/example/flashcard/ExampleUnitTest.kt
2300790270
package com.example.flashcard import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.ImageView import android.widget.RelativeLayout import android.widget.TextView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val flashcardQuestion = findViewById<TextView>(R.id.flashcard_question) val flashcardAnswer = findViewById<TextView>(R.id.flashcard_answer) val textView1 = findViewById<TextView>(R.id.textView1) val textView2 = findViewById<TextView>(R.id.textView2) val textView3 = findViewById<TextView>(R.id.textView3) val mainLayout = findViewById<RelativeLayout>(R.id.main_layout) flashcardAnswer.visibility = View.INVISIBLE flashcardQuestion.setOnClickListener { flashcardQuestion.visibility = View.INVISIBLE flashcardAnswer.visibility = View.VISIBLE } flashcardAnswer.setOnClickListener { flashcardAnswer.visibility = View.INVISIBLE flashcardQuestion.visibility = View.VISIBLE } val isShowingAnswers = findViewById<ImageView>(R.id.eyeoff) val showAnswers = findViewById<ImageView>(R.id.eye) flashcardQuestion.visibility = View.VISIBLE isShowingAnswers.setOnClickListener { if (textView1.visibility == View.VISIBLE) { textView1.visibility = View.INVISIBLE textView2.visibility = View.INVISIBLE textView3.visibility = View.INVISIBLE resetTextViewBackgrounds(textView1, textView2, textView3) isShowingAnswers.visibility = View.INVISIBLE showAnswers.visibility = View.VISIBLE } else { textView1.visibility = View.VISIBLE textView2.visibility = View.VISIBLE textView3.visibility = View.VISIBLE } } showAnswers.setOnClickListener { if (textView1.visibility == View.INVISIBLE) { isShowingAnswers.visibility = View.VISIBLE textView1.visibility = View.VISIBLE textView2.visibility = View.VISIBLE textView3.visibility = View.VISIBLE resetTextViewBackgrounds(textView1, textView2, textView3) isShowingAnswers.visibility = View.VISIBLE showAnswers.visibility = View.INVISIBLE } else { textView1.visibility = View.INVISIBLE textView2.visibility = View.INVISIBLE textView3.visibility = View.INVISIBLE } } textView1.setOnClickListener { textView1.setBackgroundColor(resources.getColor(R.color.red)) textView3.setBackgroundColor(resources.getColor(R.color.green)) } textView2.setOnClickListener { textView2.setBackgroundColor(resources.getColor(R.color.red)) textView3.setBackgroundColor(resources.getColor(R.color.green)) } textView3.setOnClickListener { textView3.setBackgroundColor(resources.getColor(R.color.green)) } mainLayout.setOnClickListener { resetTextViewBackgrounds(textView1, textView2, textView3) } } private fun resetTextViewBackgrounds(vararg textViews: TextView) { for (textView in textViews) { textView.setBackgroundColor(resources.getColor(R.color.beige_clair)) } } }
FlashCard1/app/src/main/java/com/example/flashcard/MainActivity.kt
95410900
package pt.isel.ls.webApi import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.http4k.core.Method import org.http4k.core.Request import org.http4k.core.RequestContexts import org.http4k.core.Status import org.http4k.core.then import org.http4k.routing.bind import org.http4k.routing.routes import org.junit.jupiter.api.Test import pt.isel.ls.data.entities.BoardList import pt.isel.ls.data.mem.MemBoardsData import pt.isel.ls.data.mem.MemCardsData import pt.isel.ls.data.mem.MemDataContext import pt.isel.ls.data.mem.MemDataSource import pt.isel.ls.data.mem.MemListsData import pt.isel.ls.data.mem.MemUsersData import pt.isel.ls.tasksServices.TasksServices import pt.isel.ls.tasksServices.dtos.ErrorDto import pt.isel.ls.tasksServices.dtos.InputBoardListDto import pt.isel.ls.tasksServices.dtos.OutputIdDto import pt.isel.ls.utils.ErrorCodes import kotlin.test.BeforeTest import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull class ListsTest { private val services = TasksServices(MemDataContext, MemBoardsData, MemUsersData, MemListsData, MemCardsData) private val filters = Filters(services) private val boardsApi = BoardsApi(services) private val usersApi = UsersApi(services) private val unitApi = ListsApi(services) private val context = RequestContexts() private val prepare = ApiTestUtils(filters, boardsApi, usersApi, unitApi, context) private val app = filters.logRequest( filters.authFilter.then( routes( "boards/{id}/lists" bind Method.GET to unitApi::getLists, "boards/{id}/lists" bind Method.POST to unitApi::createList, "boards/{id}/lists/{lid}" bind Method.GET to unitApi::getList, "boards/{id}/lists/{lid}" bind Method.DELETE to unitApi::deleteList ) ) ) @BeforeTest fun resetStorage() { MemDataSource.resetStorage() } @Test fun createList() { val user = prepare.createUser() val board = prepare.createBoard(user.token) val createDto = InputBoardListDto("Test Board") val responseCreateList = app( Request( Method.POST, "boards/${board.id}/lists" ) .body(Json.encodeToString(createDto)) .header("content-type", "application/json") .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.CREATED, responseCreateList.status) assertEquals("application/json", responseCreateList.header("content-type")) val createdList = Json.decodeFromString<OutputIdDto>(responseCreateList.bodyString()) assert(createdList.id > 0) } @Test fun getList() { val user = prepare.createUser() val board = prepare.createBoard(user.token) val createDto = InputBoardListDto("Test List") val responseCreateList = app( Request( Method.POST, "boards/${board.id}/lists" ) .body(Json.encodeToString(createDto)) .header("content-type", "application/json") .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.CREATED, responseCreateList.status) assertEquals("application/json", responseCreateList.header("content-type")) val createdList = Json.decodeFromString<OutputIdDto>(responseCreateList.bodyString()) assert(createdList.id > 0) val responseGetList = app( Request( Method.GET, "boards/${board.id}/lists/${createdList.id}" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseGetList.status) assertEquals("application/json", responseGetList.header("content-type")) val listResult = Json.decodeFromString<BoardList>(responseGetList.bodyString()) assertEquals(createDto.name, listResult.name) } private fun simpleCreateBoard(listData: InputBoardListDto, boardId: Int, token: String) { app( Request( Method.POST, "boards/$boardId/lists" ) .body(Json.encodeToString(listData)) .header("content-type", "application/json") .header("Authorization", "Bearer $token") ).let { assertEquals(Status.CREATED, it.status) assertEquals("application/json", it.header("content-type")) } } @Test fun getBoardLists() { val user = prepare.createUser() val board = prepare.createBoard(user.token) simpleCreateBoard(InputBoardListDto("Test List"), board.id, user.token) simpleCreateBoard(InputBoardListDto("Test List 2"), board.id, user.token) val responseGetLists = app( Request( Method.GET, "boards/${board.id}/lists" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseGetLists.status) assertEquals("application/json", responseGetLists.header("content-type")) val gottenLists = Json.decodeFromString<List<BoardList>>(responseGetLists.bodyString()) assertEquals(2, gottenLists.size) } @Test fun getBoardListsWithOptionalLimit1() { val user = prepare.createUser() val board = prepare.createBoard(user.token) val createDto1 = InputBoardListDto("Test List") val createDto2 = InputBoardListDto("Test List 2") val createDto3 = InputBoardListDto("Test List 3") simpleCreateBoard(createDto1, board.id, user.token) simpleCreateBoard(createDto2, board.id, user.token) simpleCreateBoard(createDto3, board.id, user.token) val responseGetLists = app( Request( Method.GET, "boards/${board.id}/lists?limit=1" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseGetLists.status) assertEquals("application/json", responseGetLists.header("content-type")) val gottenLists = Json.decodeFromString<List<BoardList>>(responseGetLists.bodyString()) assertEquals(1, gottenLists.size) assertNotNull(gottenLists.firstOrNull { it.name == createDto1.name }) assertNull(gottenLists.firstOrNull { it.name == createDto2.name }) assertNull(gottenLists.firstOrNull { it.name == createDto3.name }) } @Test fun getBoardListsWithOptionalLimitOverSize() { val user = prepare.createUser() val board = prepare.createBoard(user.token) val createDto1 = InputBoardListDto("Test List") val createDto2 = InputBoardListDto("Test List 2") val createDto3 = InputBoardListDto("Test List 3") simpleCreateBoard(createDto1, board.id, user.token) simpleCreateBoard(createDto2, board.id, user.token) simpleCreateBoard(createDto3, board.id, user.token) val responseGetLists = app( Request( Method.GET, "boards/${board.id}/lists?limit=5" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseGetLists.status) assertEquals("application/json", responseGetLists.header("content-type")) val gottenLists = Json.decodeFromString<List<BoardList>>(responseGetLists.bodyString()) assertEquals(3, gottenLists.size) assertNotNull(gottenLists.firstOrNull { it.name == createDto1.name }) assertNotNull(gottenLists.firstOrNull { it.name == createDto2.name }) assertNotNull(gottenLists.firstOrNull { it.name == createDto3.name }) } @Test fun getBoardListsWithOptionalSkip1() { val user = prepare.createUser() val board = prepare.createBoard(user.token) val createDto1 = InputBoardListDto("Test List") val createDto2 = InputBoardListDto("Test List 2") val createDto3 = InputBoardListDto("Test List 3") simpleCreateBoard(createDto1, board.id, user.token) simpleCreateBoard(createDto2, board.id, user.token) simpleCreateBoard(createDto3, board.id, user.token) val responseGetLists = app( Request( Method.GET, "boards/${board.id}/lists?skip=1" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseGetLists.status) assertEquals("application/json", responseGetLists.header("content-type")) val gottenLists = Json.decodeFromString<List<BoardList>>(responseGetLists.bodyString()) assertEquals(2, gottenLists.size) assertNull(gottenLists.firstOrNull { it.name == createDto1.name }) assertNotNull(gottenLists.firstOrNull { it.name == createDto2.name }) assertNotNull(gottenLists.firstOrNull { it.name == createDto3.name }) } @Test fun getBoardListsWithOptionalSkipOverSize() { val user = prepare.createUser() val board = prepare.createBoard(user.token) val createDto1 = InputBoardListDto("Test List") val createDto2 = InputBoardListDto("Test List 2") val createDto3 = InputBoardListDto("Test List 3") simpleCreateBoard(createDto1, board.id, user.token) simpleCreateBoard(createDto2, board.id, user.token) simpleCreateBoard(createDto3, board.id, user.token) val responseGetLists = app( Request( Method.GET, "boards/${board.id}/lists?skip=5" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseGetLists.status) assertEquals("application/json", responseGetLists.header("content-type")) val gottenLists = Json.decodeFromString<List<BoardList>>(responseGetLists.bodyString()) assertEquals(0, gottenLists.size) } @Test fun getBoardListsWithOptionalParameters() { val user = prepare.createUser() val board = prepare.createBoard(user.token) val createDto1 = InputBoardListDto("Test List") val createDto2 = InputBoardListDto("Test List 2") val createDto3 = InputBoardListDto("Test List 3") simpleCreateBoard(createDto1, board.id, user.token) simpleCreateBoard(createDto2, board.id, user.token) simpleCreateBoard(createDto3, board.id, user.token) val responseGetLists = app( Request( Method.GET, "boards/${board.id}/lists?skip=1&limit=1" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseGetLists.status) assertEquals("application/json", responseGetLists.header("content-type")) val gottenLists = Json.decodeFromString<List<BoardList>>(responseGetLists.bodyString()) assertEquals(1, gottenLists.size) assertNull(gottenLists.firstOrNull { it.name == createDto1.name }) assertNotNull(gottenLists.firstOrNull { it.name == createDto2.name }) assertNull(gottenLists.firstOrNull { it.name == createDto3.name }) } @Test fun deleteBoardList() { val user = prepare.createUser() val board = prepare.createBoard(user.token) val createDto = InputBoardListDto("Test List") val responseCreateList = app( Request( Method.POST, "boards/${board.id}/lists" ) .body(Json.encodeToString(createDto)) .header("content-type", "application/json") .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.CREATED, responseCreateList.status) assertEquals("application/json", responseCreateList.header("content-type")) val createdList = Json.decodeFromString<OutputIdDto>(responseCreateList.bodyString()) app( Request( Method.DELETE, "boards/${board.id}/lists/${createdList.id}" ) .header("Authorization", "Bearer ${user.token}") ).let { assertEquals(Status.OK, it.status) } } @Test fun deleteNonExistentBoardList() { val user = prepare.createUser() val board = prepare.createBoard(user.token) val createDto = InputBoardListDto("Test List") app( Request( Method.POST, "boards/${board.id}/lists" ) .body(Json.encodeToString(createDto)) .header("content-type", "application/json") .header("Authorization", "Bearer ${user.token}") ).let { assertEquals(Status.CREATED, it.status) assertEquals("application/json", it.header("content-type")) } val res = app( Request( Method.DELETE, "boards/${board.id}/lists/-1" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.NOT_FOUND, res.status) assertEquals("application/json", res.header("content-type")) val expectedCode = ErrorCodes.LIST_READ_FAIL assertEquals(ErrorDto(expectedCode.message, expectedCode.code), Json.decodeFromString(res.bodyString())) } }
isel-ls/src/test/kotlin/pt/isel/ls/webApi/ListsTest.kt
45127552
package pt.isel.ls.webApi import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.http4k.core.Method import org.http4k.core.Request import org.http4k.core.RequestContexts import org.http4k.core.then import org.http4k.filter.ServerFilters import org.http4k.routing.RoutingHttpHandler import org.http4k.routing.bind import org.http4k.routing.routes import pt.isel.ls.tasksServices.dtos.InputBoardDto import pt.isel.ls.tasksServices.dtos.InputBoardListDto import pt.isel.ls.tasksServices.dtos.InputUserDto import pt.isel.ls.tasksServices.dtos.OutputIdDto import pt.isel.ls.tasksServices.dtos.OutputUserDto class ApiTestUtils(filters: Filters, boardsApi: BoardsApi, usersApi: UsersApi, listsApi: ListsApi, context: RequestContexts) { private val app: RoutingHttpHandler private val createUserDto: InputUserDto private val createBoardDto: InputBoardDto private val createListDto: InputBoardListDto fun createUser(dto: InputUserDto = createUserDto): OutputUserDto { val response = app( Request( Method.POST, "users" ).body(Json.encodeToString(dto)) ) return Json.decodeFromString(response.bodyString()) } fun createBoard(token: String, dto: InputBoardDto = createBoardDto): OutputIdDto { val response = app( Request( Method.POST, "boards" ) .body(Json.encodeToString(dto)) .header("Authorization", "Bearer $token") ) return Json.decodeFromString(response.bodyString()) } fun createList(token: String, boardId: Int, dto: InputBoardListDto = createListDto): OutputIdDto { val response = app( Request( Method.POST, "boards/$boardId/lists" ) .body(Json.encodeToString(dto)) .header("Authorization", "Bearer $token") ) return Json.decodeFromString(response.bodyString()) } init { this.app = routes( ServerFilters.InitialiseRequestContext(context).then(filters.filterUser(context)).then( routes( "boards/" bind Method.POST to boardsApi.createBoard(context), "boards/{id}/lists" bind Method.POST to listsApi::createList ) ), "users" bind Method.POST to usersApi::createUser ) this.createUserDto = InputUserDto("Maria", "maria@example.org", "olamundo") this.createBoardDto = InputBoardDto("New Board", "A really cool new board") this.createListDto = InputBoardListDto("Cool List") } }
isel-ls/src/test/kotlin/pt/isel/ls/webApi/ApiTestUtils.kt
2463373950
package pt.isel.ls.webApi import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.http4k.core.Method import org.http4k.core.Request import org.http4k.core.RequestContexts import org.http4k.core.Status import org.http4k.core.then import org.http4k.routing.bind import org.http4k.routing.routes import org.junit.jupiter.api.Test import pt.isel.ls.data.entities.Card import pt.isel.ls.data.mem.MemBoardsData import pt.isel.ls.data.mem.MemCardsData import pt.isel.ls.data.mem.MemDataContext import pt.isel.ls.data.mem.MemDataSource import pt.isel.ls.data.mem.MemListsData import pt.isel.ls.data.mem.MemUsersData import pt.isel.ls.tasksServices.TasksServices import pt.isel.ls.tasksServices.dtos.ErrorDto import pt.isel.ls.tasksServices.dtos.InputBoardListDto import pt.isel.ls.tasksServices.dtos.InputCardDto import pt.isel.ls.tasksServices.dtos.InputMoveCardDto import pt.isel.ls.tasksServices.dtos.OutputIdDto import pt.isel.ls.utils.ErrorCodes import kotlin.test.BeforeTest import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull class CardsTest { private val services = TasksServices(MemDataContext, MemBoardsData, MemUsersData, MemListsData, MemCardsData) private val filters = Filters(services) private val boardsApi = BoardsApi(services) private val usersApi = UsersApi(services) private val listsApi = ListsApi(services) private val unitApi = CardsApi(services) private val context = RequestContexts() private val prepare = ApiTestUtils(filters, boardsApi, usersApi, listsApi, context) private val app = filters.logRequest( filters.authFilter.then( routes( "boards/{id}/lists/{lid}/cards" bind Method.POST to unitApi::createCard, "boards/{id}/lists/{lid}/cards" bind Method.GET to unitApi::getCardsFromList, "boards/{id}/cards/{cid}" bind Method.GET to unitApi::getCard, "boards/{id}/cards/{cid}/move" bind Method.GET to unitApi::alterCardListPosition, "boards/{id}/cards/{cid}" bind Method.DELETE to unitApi::deleteCard ) ) ) @BeforeTest fun resetStorage() { MemDataSource.resetStorage() } @Test fun createCard() { val user = prepare.createUser() val board = prepare.createBoard(user.token) val boardList = prepare.createList(user.token, board.id) val createDto = InputCardDto( "Test Card", "Card used for integration testing" ) val response = app( Request( Method.POST, "boards/${board.id}/lists/${boardList.id}/cards" ) .body(Json.encodeToString(createDto)) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.CREATED, response.status) assertEquals("application/json", response.header("content-type")) val createdCard = Json.decodeFromString<OutputIdDto>(response.bodyString()) assert(createdCard.id > 0) } @Test fun getCard() { val user = prepare.createUser() val board = prepare.createBoard(user.token) val boardList = prepare.createList(user.token, board.id) val createDto = InputCardDto( "Test Card", "Card used for integration testing" ) val response = app( Request( Method.POST, "boards/${board.id}/lists/${boardList.id}/cards" ) .body(Json.encodeToString(createDto)) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.CREATED, response.status) assertEquals("application/json", response.header("content-type")) val createdCard = Json.decodeFromString<OutputIdDto>(response.bodyString()) val responseGet = app( Request( Method.GET, "boards/${board.id}/cards/${createdCard.id}" ) .body(Json.encodeToString(createDto)) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseGet.status) assertEquals("application/json", responseGet.header("content-type")) val gottenCard = Json.decodeFromString<Card>(responseGet.bodyString()) assertEquals(createDto.name, gottenCard.name) assertEquals(createDto.description, gottenCard.description) assertEquals(createDto.dueDate, gottenCard.dueDate) } private fun simpleCreateCard(createDto: InputCardDto, boardId: Int, listId: Int, token: String) { app( Request( Method.POST, "boards/$boardId/lists/$listId/cards" ) .body(Json.encodeToString(createDto)) .header("Authorization", "Bearer $token") ).let { assertEquals(Status.CREATED, it.status) assertEquals("application/json", it.header("content-type")) } } @Test fun getListCards() { val user = prepare.createUser() val board = prepare.createBoard(user.token) val boardList = prepare.createList(user.token, board.id) val createDto = InputCardDto( "Test Card", "Card used for integration testing" ) val response = app( Request( Method.POST, "boards/${board.id}/lists/${boardList.id}/cards" ) .body(Json.encodeToString(createDto)) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.CREATED, response.status) assertEquals("application/json", response.header("content-type")) val responseGetListCards = app( Request( Method.GET, "boards/${board.id}/lists/${boardList.id}/cards" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseGetListCards.status) assertEquals("application/json", responseGetListCards.header("content-type")) val gottenListCards = Json.decodeFromString<List<Card>>(responseGetListCards.bodyString()) assertEquals(1, gottenListCards.size) } @Test fun getListCardsWithOptionalLimit1() { val user = prepare.createUser() val board = prepare.createBoard(user.token) val boardList = prepare.createList(user.token, board.id) val createDto1 = InputCardDto( "Test Card", "Card used for integration testing" ) val createDto2 = createDto1.copy(name = "Test Card 2") val createDto3 = createDto1.copy(name = "Test Card 3") simpleCreateCard(createDto1, board.id, boardList.id, user.token) simpleCreateCard(createDto2, board.id, boardList.id, user.token) simpleCreateCard(createDto3, board.id, boardList.id, user.token) val response = app( Request( Method.GET, "boards/${board.id}/lists/${boardList.id}/cards?limit=1" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, response.status) assertEquals("application/json", response.header("content-type")) val gottenListCards = Json.decodeFromString<List<Card>>(response.bodyString()) assertEquals(1, gottenListCards.size) assertNotNull(gottenListCards.firstOrNull { it.name == createDto1.name }) assertNull(gottenListCards.firstOrNull { it.name == createDto2.name }) assertNull(gottenListCards.firstOrNull { it.name == createDto3.name }) } @Test fun getListCardsWithOptionalLimitOverSize() { val user = prepare.createUser() val board = prepare.createBoard(user.token) val boardList = prepare.createList(user.token, board.id) val createDto1 = InputCardDto( "Test Card", "Card used for integration testing" ) val createDto2 = createDto1.copy(name = "Test Card 2") val createDto3 = createDto1.copy(name = "Test Card 3") simpleCreateCard(createDto1, board.id, boardList.id, user.token) simpleCreateCard(createDto2, board.id, boardList.id, user.token) simpleCreateCard(createDto3, board.id, boardList.id, user.token) val response = app( Request( Method.GET, "boards/${board.id}/lists/${boardList.id}/cards?limit=5" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, response.status) assertEquals("application/json", response.header("content-type")) val gottenListCards = Json.decodeFromString<List<Card>>(response.bodyString()) assertEquals(3, gottenListCards.size) assertNotNull(gottenListCards.firstOrNull { it.name == createDto1.name }) assertNotNull(gottenListCards.firstOrNull { it.name == createDto2.name }) assertNotNull(gottenListCards.firstOrNull { it.name == createDto3.name }) } @Test fun getListCardsWithOptionalSkip1() { val user = prepare.createUser() val board = prepare.createBoard(user.token) val boardList = prepare.createList(user.token, board.id) val createDto1 = InputCardDto( "Test Card", "Card used for integration testing" ) val createDto2 = createDto1.copy(name = "Test Card 2") val createDto3 = createDto1.copy(name = "Test Card 3") simpleCreateCard(createDto1, board.id, boardList.id, user.token) simpleCreateCard(createDto2, board.id, boardList.id, user.token) simpleCreateCard(createDto3, board.id, boardList.id, user.token) val response = app( Request( Method.GET, "boards/${board.id}/lists/${boardList.id}/cards?skip=1" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, response.status) assertEquals("application/json", response.header("content-type")) val gottenListCards = Json.decodeFromString<List<Card>>(response.bodyString()) assertEquals(2, gottenListCards.size) assertNull(gottenListCards.firstOrNull { it.name == createDto1.name }) assertNotNull(gottenListCards.firstOrNull { it.name == createDto2.name }) assertNotNull(gottenListCards.firstOrNull { it.name == createDto3.name }) } @Test fun getListCardsWithOptionalSkipOverSize() { val user = prepare.createUser() val board = prepare.createBoard(user.token) val boardList = prepare.createList(user.token, board.id) val createDto1 = InputCardDto( "Test Card", "Card used for integration testing" ) val createDto2 = createDto1.copy(name = "Test Card 2") val createDto3 = createDto1.copy(name = "Test Card 3") simpleCreateCard(createDto1, board.id, boardList.id, user.token) simpleCreateCard(createDto2, board.id, boardList.id, user.token) simpleCreateCard(createDto3, board.id, boardList.id, user.token) val response = app( Request( Method.GET, "boards/${board.id}/lists/${boardList.id}/cards?skip=5" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, response.status) assertEquals("application/json", response.header("content-type")) val gottenListCards = Json.decodeFromString<List<Card>>(response.bodyString()) assertEquals(0, gottenListCards.size) } @Test fun getListCardsWithOptionalParameters() { val user = prepare.createUser() val board = prepare.createBoard(user.token) val boardList = prepare.createList(user.token, board.id) val createDto1 = InputCardDto( "Test Card", "Card used for integration testing" ) val createDto2 = createDto1.copy(name = "Test Card 2") val createDto3 = createDto1.copy(name = "Test Card 3") simpleCreateCard(createDto1, board.id, boardList.id, user.token) simpleCreateCard(createDto2, board.id, boardList.id, user.token) simpleCreateCard(createDto3, board.id, boardList.id, user.token) val response = app( Request( Method.GET, "boards/${board.id}/lists/${boardList.id}/cards?limit=1&skip=1" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, response.status) assertEquals("application/json", response.header("content-type")) val gottenListCards = Json.decodeFromString<List<Card>>(response.bodyString()) assertEquals(1, gottenListCards.size) assertNull(gottenListCards.firstOrNull { it.name == createDto1.name }) assertNotNull(gottenListCards.firstOrNull { it.name == createDto2.name }) assertNull(gottenListCards.firstOrNull { it.name == createDto3.name }) } @Test fun moveCard() { val user = prepare.createUser() val board = prepare.createBoard(user.token) val originBoardList = prepare.createList(user.token, board.id) val destinationBoardList = prepare.createList(user.token, board.id, InputBoardListDto("Cooler List")) val createDto = InputCardDto( "Test Card", "Card used for integration testing" ) val responseCreate = app( Request( Method.POST, "boards/${board.id}/lists/${originBoardList.id}/cards" ) .body(Json.encodeToString(createDto)) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.CREATED, responseCreate.status) assertEquals("application/json", responseCreate.header("content-type")) val createdCard = Json.decodeFromString<OutputIdDto>(responseCreate.bodyString()) val request = InputMoveCardDto(destinationBoardList.id, 0) app( Request( Method.GET, "boards/${board.id}/cards/${createdCard.id}/move" ) .body(Json.encodeToString(request)) .header("Authorization", "Bearer ${user.token}") ).let { assertEquals(Status.OK, it.status) } app( Request( Method.GET, "boards/${board.id}/cards/${createdCard.id}" ) .body(Json.encodeToString(createDto)) .header("Authorization", "Bearer ${user.token}") ).let { assertEquals(Status.OK, it.status) assertEquals("application/json", it.header("content-type")) val gottenCard = Json.decodeFromString<Card>(it.bodyString()) assertEquals(destinationBoardList.id, gottenCard.listId) } } @Test fun deleteCard() { val user = prepare.createUser() val board = prepare.createBoard(user.token) val boardList = prepare.createList(user.token, board.id) val createDto = InputCardDto( "Test Card", "Card used for integration testing" ) val response = app( Request( Method.POST, "boards/${board.id}/lists/${boardList.id}/cards" ) .body(Json.encodeToString(createDto)) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.CREATED, response.status) assertEquals("application/json", response.header("content-type")) val createdCard = Json.decodeFromString<OutputIdDto>(response.bodyString()) app( Request( Method.DELETE, "boards/${board.id}/cards/${createdCard.id}" ) .body(Json.encodeToString(createDto)) .header("Authorization", "Bearer ${user.token}") ).let { assertEquals(Status.OK, it.status) } } @Test fun deleteNonExistentCard() { val user = prepare.createUser() val board = prepare.createBoard(user.token) val boardList = prepare.createList(user.token, board.id) val createDto = InputCardDto( "Test Card", "Card used for integration testing" ) app( Request( Method.POST, "boards/${board.id}/lists/${boardList.id}/cards" ) .body(Json.encodeToString(createDto)) .header("Authorization", "Bearer ${user.token}") ).let { assertEquals(Status.CREATED, it.status) assertEquals("application/json", it.header("content-type")) } app( Request( Method.DELETE, "boards/${board.id}/cards/-1" ) .body(Json.encodeToString(createDto)) .header("Authorization", "Bearer ${user.token}") ).let { val expectedError = ErrorCodes.CARD_READ_FAIL assertEquals(expectedError.http4kStatus(), it.status) assertEquals("application/json", it.header("content-type")) assertEquals(ErrorDto(expectedError.message, expectedError.code), Json.decodeFromString(it.bodyString())) } } }
isel-ls/src/test/kotlin/pt/isel/ls/webApi/CardsTest.kt
1880788859
package pt.isel.ls.webApi import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.http4k.core.Method import org.http4k.core.Request import org.http4k.core.Status import org.http4k.routing.bind import org.http4k.routing.routes import org.junit.jupiter.api.Test import pt.isel.ls.data.mem.MemBoardsData import pt.isel.ls.data.mem.MemCardsData import pt.isel.ls.data.mem.MemDataContext import pt.isel.ls.data.mem.MemDataSource import pt.isel.ls.data.mem.MemListsData import pt.isel.ls.data.mem.MemUsersData import pt.isel.ls.tasksServices.TasksServices import pt.isel.ls.tasksServices.dtos.InputUserDto import pt.isel.ls.tasksServices.dtos.OutputUserDto import pt.isel.ls.tasksServices.dtos.SecureOutputUserDto import java.util.* import kotlin.test.BeforeTest import kotlin.test.assertEquals class UsersTest { private val services = TasksServices(MemDataContext, MemBoardsData, MemUsersData, MemListsData, MemCardsData) private val filters = Filters(services) private val unitApi = UsersApi(services) private val app = filters.logRequest( routes( "users/{id}" bind Method.GET to unitApi::getUser, "users" bind Method.POST to unitApi::createUser ) ) @BeforeTest fun clearStorage() { MemDataSource.clearStorage() } @Test fun createUser() { val createDto = InputUserDto("Maria", "maria@example.org", "helloworld") val response = app( Request( Method.POST, "users" ).body(Json.encodeToString(createDto)) ) assertEquals(Status.CREATED, response.status) assertEquals("application/json", response.header("content-type")) val createdUser = Json.decodeFromString<OutputUserDto>(response.bodyString()) assertEquals(UUID::class, UUID.fromString(createdUser.token)::class) } @Test fun getUserData() { val createDto = InputUserDto("Maria", "maria@example.org", "helloworld") val response = app( Request( Method.POST, "users" ).body(Json.encodeToString(createDto)) ) assertEquals(Status.CREATED, response.status) assertEquals("application/json", response.header("content-type")) val createdUser = Json.decodeFromString<OutputUserDto>(response.bodyString()) val responseGet = app( Request( Method.GET, "users/${createdUser.id}" ) ) assertEquals(Status.OK, responseGet.status) assertEquals("application/json", responseGet.header("content-type")) val returnedUser = Json.decodeFromString<SecureOutputUserDto>(responseGet.bodyString()) assertEquals(createDto.name, returnedUser.name) assertEquals(createDto.email, returnedUser.email) } }
isel-ls/src/test/kotlin/pt/isel/ls/webApi/UsersTest.kt
3344526491
package pt.isel.ls.webApi import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.http4k.core.Method import org.http4k.core.Request import org.http4k.core.RequestContexts import org.http4k.core.Status import org.http4k.core.then import org.http4k.filter.ServerFilters import org.http4k.routing.bind import org.http4k.routing.routes import org.junit.jupiter.api.Test import pt.isel.ls.data.entities.Board import pt.isel.ls.data.entities.User import pt.isel.ls.data.mem.MemBoardsData import pt.isel.ls.data.mem.MemCardsData import pt.isel.ls.data.mem.MemDataContext import pt.isel.ls.data.mem.MemDataSource import pt.isel.ls.data.mem.MemListsData import pt.isel.ls.data.mem.MemUsersData import pt.isel.ls.tasksServices.TasksServices import pt.isel.ls.tasksServices.dtos.InputBoardDto import pt.isel.ls.tasksServices.dtos.InputUserDto import pt.isel.ls.tasksServices.dtos.OutputIdDto import pt.isel.ls.tasksServices.dtos.SecureOutputUserDto import kotlin.test.BeforeTest import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull class BoardsTest { private val services = TasksServices(MemDataContext, MemBoardsData, MemUsersData, MemListsData, MemCardsData) private val filters = Filters(services) private val unitApi = BoardsApi(services) private val usersApi = UsersApi(services) private val listsApi = ListsApi(services) private val context = RequestContexts() private val prepare = ApiTestUtils(filters, unitApi, usersApi, listsApi, context) private val app = routes( ServerFilters.InitialiseRequestContext(context).then(filters.filterUser(context)).then( routes( "boards/{id}" bind Method.GET to unitApi.getBoard(context), "boards/" bind Method.GET to unitApi.getBoards(context), "boards/" bind Method.POST to unitApi.createBoard(context), "boards/{id}/user-list" bind Method.GET to unitApi.getBoardUsers(context) ) ), filters.authFilter.then( routes( "boards/{id}/user-list/{uid}" bind Method.PUT to unitApi::addUsersOnBoard, "boards/{id}/user-list/{uid}" bind Method.DELETE to unitApi::deleteUserFromBoard ) ) ) @BeforeTest fun clearStorage() { MemDataSource.clearStorage() } @Test fun createBoard() { val user = prepare.createUser() val createDto = InputBoardDto("New Board", "A really cool new board") val response = app( Request( Method.POST, "boards" ) .body(Json.encodeToString(createDto)) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.CREATED, response.status) assertEquals("application/json", response.header("content-type")) val createdBoard = Json.decodeFromString<OutputIdDto>(response.bodyString()) assert(createdBoard.id > 0) } @Test fun getBoard() { val user = prepare.createUser() val createDto = InputBoardDto("New Board", "A really cool new board") val response = app( Request( Method.POST, "boards" ) .body(Json.encodeToString(createDto)) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.CREATED, response.status) assertEquals("application/json", response.header("content-type")) val createdBoard = Json.decodeFromString<OutputIdDto>(response.bodyString()) val responseGetBoard = app( Request( Method.GET, "boards/${createdBoard.id}" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseGetBoard.status) assertEquals("application/json", responseGetBoard.header("content-type")) val gottenBoard = Json.decodeFromString<Board>(responseGetBoard.bodyString()) assertEquals(createDto.name, gottenBoard.name) assertEquals(createDto.description, gottenBoard.description) } private fun simpleCreateBoard(createData: InputBoardDto, token: String) { app( Request( Method.POST, "boards" ) .body(Json.encodeToString(createData)) .header("Authorization", "Bearer $token") ).let { assertEquals(Status.CREATED, it.status) } } @Test fun getUserBoards() { val user = prepare.createUser() val createDto1 = InputBoardDto("New Board", "A really cool new board") val createDto2 = InputBoardDto("New Board 2", "Derivative work actually") simpleCreateBoard(createDto1, user.token) simpleCreateBoard(createDto2, user.token) val responseGetBoards = app( Request( Method.GET, "boards" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseGetBoards.status) assertEquals("application/json", responseGetBoards.header("content-type")) val boards = Json.decodeFromString<List<Board>>(responseGetBoards.bodyString()) assertEquals(2, boards.size) assertNotNull(boards.firstOrNull { it.name == createDto1.name }) assertNotNull(boards.firstOrNull { it.name == createDto2.name }) } @Test fun getUserBoardsWithOptionalLimit1() { val user = prepare.createUser() val createDto1 = InputBoardDto("New Board", "A really cool new board") val createDto2 = InputBoardDto("New Board 2", "Derivative work actually") val createDto3 = InputBoardDto("New Board 3", "Ditto") simpleCreateBoard(createDto1, user.token) simpleCreateBoard(createDto2, user.token) simpleCreateBoard(createDto3, user.token) val responseGetBoards = app( Request( Method.GET, "boards?limit=1" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseGetBoards.status) assertEquals("application/json", responseGetBoards.header("content-type")) val boards = Json.decodeFromString<List<Board>>(responseGetBoards.bodyString()) assertEquals(1, boards.size) assertNotNull(boards.firstOrNull { it.name == createDto1.name }) assertNull(boards.firstOrNull { it.name == createDto2.name }) assertNull(boards.firstOrNull { it.name == createDto3.name }) } @Test fun getUserBoardsWithOptionalLimitOverSize() { val user = prepare.createUser() val createDto1 = InputBoardDto("New Board", "A really cool new board") val createDto2 = InputBoardDto("New Board 2", "Derivative work actually") val createDto3 = InputBoardDto("New Board 3", "Ditto") simpleCreateBoard(createDto1, user.token) simpleCreateBoard(createDto2, user.token) simpleCreateBoard(createDto3, user.token) val responseGetBoards = app( Request( Method.GET, "boards?limit=5" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseGetBoards.status) assertEquals("application/json", responseGetBoards.header("content-type")) val boards = Json.decodeFromString<List<Board>>(responseGetBoards.bodyString()) assertEquals(3, boards.size) assertNotNull(boards.firstOrNull { it.name == createDto1.name }) assertNotNull(boards.firstOrNull { it.name == createDto2.name }) assertNotNull(boards.firstOrNull { it.name == createDto3.name }) } @Test fun getUserBoardsWithOptionalSkip1() { val user = prepare.createUser() val createDto1 = InputBoardDto("New Board", "A really cool new board") val createDto2 = InputBoardDto("New Board 2", "Derivative work actually") val createDto3 = InputBoardDto("New Board 3", "Ditto") simpleCreateBoard(createDto1, user.token) simpleCreateBoard(createDto2, user.token) simpleCreateBoard(createDto3, user.token) val responseGetBoards = app( Request( Method.GET, "boards?skip=1" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseGetBoards.status) assertEquals("application/json", responseGetBoards.header("content-type")) val boards = Json.decodeFromString<List<Board>>(responseGetBoards.bodyString()) assertEquals(2, boards.size) assertNull(boards.firstOrNull { it.name == createDto1.name }) assertNotNull(boards.firstOrNull { it.name == createDto2.name }) assertNotNull(boards.firstOrNull { it.name == createDto3.name }) } @Test fun getUserBoardsWithOptionalSkipOverSize() { val user = prepare.createUser() val createDto1 = InputBoardDto("New Board", "A really cool new board") val createDto2 = InputBoardDto("New Board 2", "Derivative work actually") val createDto3 = InputBoardDto("New Board 3", "Ditto") simpleCreateBoard(createDto1, user.token) simpleCreateBoard(createDto2, user.token) simpleCreateBoard(createDto3, user.token) val responseGetBoards = app( Request( Method.GET, "boards?skip=5" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseGetBoards.status) assertEquals("application/json", responseGetBoards.header("content-type")) val boards = Json.decodeFromString<List<Board>>(responseGetBoards.bodyString()) assertEquals(0, boards.size) } @Test fun getUserBoardsWithOptionalParameters() { val user = prepare.createUser() val createDto1 = InputBoardDto("New Board", "A really cool new board") val createDto2 = InputBoardDto("New Board 2", "Derivative work actually") val createDto3 = InputBoardDto("New Board 3", "Ditto") simpleCreateBoard(createDto1, user.token) simpleCreateBoard(createDto2, user.token) simpleCreateBoard(createDto3, user.token) val responseGetBoards = app( Request( Method.GET, "boards?skip=1&limit=1" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseGetBoards.status) assertEquals("application/json", responseGetBoards.header("content-type")) val boards = Json.decodeFromString<List<Board>>(responseGetBoards.bodyString()) assertEquals(1, boards.size) assertNull(boards.firstOrNull { it.name == createDto1.name }) assertNotNull(boards.firstOrNull { it.name == createDto2.name }) assertNull(boards.firstOrNull { it.name == createDto3.name }) } @Test fun getBoardUserList() { val user = prepare.createUser() val createDto = InputBoardDto("New Board", "A really cool new board") val response = app( Request( Method.POST, "boards" ) .body(Json.encodeToString(createDto)) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.CREATED, response.status) val createdBoard = Json.decodeFromString<OutputIdDto>(response.bodyString()) val responseGetBoard = app( Request( Method.GET, "boards/${createdBoard.id}/user-list" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseGetBoard.status) assertEquals("application/json", responseGetBoard.header("content-type")) val boardUsers = Json.decodeFromString<List<SecureOutputUserDto>>(responseGetBoard.bodyString()) assertEquals(1, boardUsers.size) assertEquals(user.id, boardUsers.first().id) } private fun simpleAddUserToBoard(token: String, userId: Int, boardId: Int) { app( Request( Method.PUT, "boards/$boardId/user-list/$userId" ) .header("Authorization", "Bearer $token") ).let { assertEquals(Status.OK, it.status) } } @Test fun getBoardUserListWithOptionalLimit1() { val user = prepare.createUser() val user1 = prepare.createUser(InputUserDto("Josephine", "josephine@example.org", "helloworld")) val user2 = prepare.createUser(InputUserDto("Jonathan", "jonathan@example.org", "helloworld")) val createDto = InputBoardDto("New Board", "A really cool new board") val response = app( Request( Method.POST, "boards" ) .body(Json.encodeToString(createDto)) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.CREATED, response.status) val createdBoard = Json.decodeFromString<OutputIdDto>(response.bodyString()) simpleAddUserToBoard(user.token, user1.id, createdBoard.id) simpleAddUserToBoard(user.token, user2.id, createdBoard.id) val responseGetBoard = app( Request( Method.GET, "boards/${createdBoard.id}/user-list?limit=1" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseGetBoard.status) assertEquals("application/json", responseGetBoard.header("content-type")) val boardUsers = Json.decodeFromString<List<SecureOutputUserDto>>(responseGetBoard.bodyString()) assertEquals(1, boardUsers.size) assertNotNull(boardUsers.firstOrNull { it.id == user.id }) assertNull(boardUsers.firstOrNull { it.id == user1.id }) assertNull(boardUsers.firstOrNull { it.id == user2.id }) } @Test fun getBoardUserListWithOptionalLimitOverSize() { val user = prepare.createUser() val user1 = prepare.createUser(InputUserDto("Josephine", "josephine@example.org", "helloworld")) val user2 = prepare.createUser(InputUserDto("Jonathan", "jonathan@example.org", "helloworld")) val createDto = InputBoardDto("New Board", "A really cool new board") val response = app( Request( Method.POST, "boards" ) .body(Json.encodeToString(createDto)) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.CREATED, response.status) val createdBoard = Json.decodeFromString<OutputIdDto>(response.bodyString()) simpleAddUserToBoard(user.token, user1.id, createdBoard.id) simpleAddUserToBoard(user.token, user2.id, createdBoard.id) val responseGetBoard = app( Request( Method.GET, "boards/${createdBoard.id}/user-list?limit=5" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseGetBoard.status) assertEquals("application/json", responseGetBoard.header("content-type")) val boardUsers = Json.decodeFromString<List<SecureOutputUserDto>>(responseGetBoard.bodyString()) assertEquals(3, boardUsers.size) assertNotNull(boardUsers.firstOrNull { it.id == user.id }) assertNotNull(boardUsers.firstOrNull { it.id == user1.id }) assertNotNull(boardUsers.firstOrNull { it.id == user2.id }) } @Test fun getBoardUserListWithOptionalSkip1() { val user = prepare.createUser() val user1 = prepare.createUser(InputUserDto("Josephine", "josephine@example.org", "helloworld")) val user2 = prepare.createUser(InputUserDto("Jonathan", "jonathan@example.org", "helloworld")) val createDto = InputBoardDto("New Board", "A really cool new board") val response = app( Request( Method.POST, "boards" ) .body(Json.encodeToString(createDto)) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.CREATED, response.status) val createdBoard = Json.decodeFromString<OutputIdDto>(response.bodyString()) simpleAddUserToBoard(user.token, user1.id, createdBoard.id) simpleAddUserToBoard(user.token, user2.id, createdBoard.id) val responseGetBoard = app( Request( Method.GET, "boards/${createdBoard.id}/user-list?skip=1" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseGetBoard.status) assertEquals("application/json", responseGetBoard.header("content-type")) val boardUsers = Json.decodeFromString<List<SecureOutputUserDto>>(responseGetBoard.bodyString()) assertEquals(2, boardUsers.size) assertNull(boardUsers.firstOrNull { it.id == user.id }) assertNotNull(boardUsers.firstOrNull { it.id == user1.id }) assertNotNull(boardUsers.firstOrNull { it.id == user2.id }) } @Test fun getBoardUserListWithOptionalSkipOverSize() { val user = prepare.createUser() val user1 = prepare.createUser(InputUserDto("Josephine", "josephine@example.org", "helloworld")) val user2 = prepare.createUser(InputUserDto("Jonathan", "jonathan@example.org", "helloworld")) val createDto = InputBoardDto("New Board", "A really cool new board") val response = app( Request( Method.POST, "boards" ) .body(Json.encodeToString(createDto)) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.CREATED, response.status) val createdBoard = Json.decodeFromString<OutputIdDto>(response.bodyString()) simpleAddUserToBoard(user.token, user1.id, createdBoard.id) simpleAddUserToBoard(user.token, user2.id, createdBoard.id) val responseGetBoard = app( Request( Method.GET, "boards/${createdBoard.id}/user-list?skip=5" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseGetBoard.status) assertEquals("application/json", responseGetBoard.header("content-type")) val boardUsers = Json.decodeFromString<List<User>>(responseGetBoard.bodyString()) assertEquals(0, boardUsers.size) } @Test fun getBoardUserListWithOptionalParameters() { val user = prepare.createUser() val user1 = prepare.createUser(InputUserDto("Josephine", "josephine@example.org", "helloworld")) val user2 = prepare.createUser(InputUserDto("Jonathan", "jonathan@example.org", "helloworld")) val createDto = InputBoardDto("New Board", "A really cool new board") val response = app( Request( Method.POST, "boards" ) .body(Json.encodeToString(createDto)) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.CREATED, response.status) val createdBoard = Json.decodeFromString<OutputIdDto>(response.bodyString()) simpleAddUserToBoard(user.token, user1.id, createdBoard.id) simpleAddUserToBoard(user.token, user2.id, createdBoard.id) val responseGetBoard = app( Request( Method.GET, "boards/${createdBoard.id}/user-list?skip=1&limit=1" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseGetBoard.status) assertEquals("application/json", responseGetBoard.header("content-type")) val boardUsers = Json.decodeFromString<List<SecureOutputUserDto>>(responseGetBoard.bodyString()) assertEquals(1, boardUsers.size) assertNull(boardUsers.firstOrNull { it.id == user.id }) assertNotNull(boardUsers.firstOrNull { it.id == user1.id }) assertNull(boardUsers.firstOrNull { it.id == user2.id }) } @Test fun addBoardUser() { val user = prepare.createUser() val user2 = prepare.createUser(InputUserDto("Jose", "jose@example.org", "helloworld")) val createDto = InputBoardDto("New Board", "A really cool new board") val response = app( Request( Method.POST, "boards" ) .body(Json.encodeToString(createDto)) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.CREATED, response.status) val createdBoard = Json.decodeFromString<OutputIdDto>(response.bodyString()) val responseAddUser = app( Request( Method.PUT, "boards/${createdBoard.id}/user-list/${user2.id}" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseAddUser.status) val responseGetBoardUsers = app( Request( Method.GET, "boards/${createdBoard.id}/user-list" ) .header("Authorization", "Bearer ${user.token}") ) val boardUsers = Json.decodeFromString<List<SecureOutputUserDto>>(responseGetBoardUsers.bodyString()) assertNotNull(boardUsers.firstOrNull { it.id == user.id }) assertNotNull(boardUsers.firstOrNull { it.id == user2.id }) } @Test fun removeBoardUser() { val user = prepare.createUser() val user2 = prepare.createUser(InputUserDto("Jose", "jose@example.org", "helloworld")) val createDto = InputBoardDto("New Board", "A really cool new board") val response = app( Request( Method.POST, "boards" ) .body(Json.encodeToString(createDto)) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.CREATED, response.status) val createdBoard = Json.decodeFromString<OutputIdDto>(response.bodyString()) val responseAddUser = app( Request( Method.PUT, "boards/${createdBoard.id}/user-list/${user2.id}" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseAddUser.status) val responseGetBoardUsers = app( Request( Method.GET, "boards/${createdBoard.id}/user-list" ) .header("Authorization", "Bearer ${user.token}") ) val boardUsers = Json.decodeFromString<List<SecureOutputUserDto>>(responseGetBoardUsers.bodyString()) assertNotNull(boardUsers.firstOrNull { it.id == user.id }) assertNotNull(boardUsers.firstOrNull { it.id == user2.id }) val responseRemoveUser = app( Request( Method.DELETE, "boards/${createdBoard.id}/user-list/${user2.id}" ) .header("Authorization", "Bearer ${user.token}") ) assertEquals(Status.OK, responseRemoveUser.status) val responseGetBoardUsersRemoved = app( Request( Method.GET, "boards/${createdBoard.id}/user-list" ) .header("Authorization", "Bearer ${user.token}") ) val boardUser = Json.decodeFromString<List<SecureOutputUserDto>>(responseGetBoardUsersRemoved.bodyString()) assertNotNull(boardUser.firstOrNull { it.id == user.id }) assertNull(boardUser.firstOrNull { it.id == user2.id }) } }
isel-ls/src/test/kotlin/pt/isel/ls/webApi/BoardsTest.kt
2643353849
package pt.isel.ls.data.mem import pt.isel.ls.TaskAppException import pt.isel.ls.tasksServices.dtos.CreateUserDto import pt.isel.ls.tasksServices.dtos.EditUserDto import pt.isel.ls.utils.PasswordUtils import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNotEquals import kotlin.test.assertTrue class MemUsersDataTest { @BeforeTest fun clearStorage() { MemDataSource.clearStorage() } @Test fun addUser() { assertFailsWith<TaskAppException> { MemUsersData.getById(1) } val salt = PasswordUtils.generateSalt() val newUser = CreateUserDto( "Alberto", "alberto@example.org", PasswordUtils.hashPassword("olamundo", salt), salt ) val insertedUser = MemUsersData.add(newUser) assertEquals(newUser.email, insertedUser.email) } @Test fun getUserByEmail() { val salt1 = PasswordUtils.generateSalt() val newUser1 = CreateUserDto( "Alberto", "alberto@example.org", PasswordUtils.hashPassword("olamundo", salt1), salt1 ) val salt2 = PasswordUtils.generateSalt() val newUser2 = CreateUserDto( "Mariana", "mariana@example.org", PasswordUtils.hashPassword("olamundo", salt2), salt2 ) val insertedUser1 = MemUsersData.add(newUser1) val insertedUser2 = MemUsersData.add(newUser2) val emailUser1 = MemUsersData.getByEmail(newUser1.email) val emailUser2 = MemUsersData.getByEmail(newUser2.email) assertEquals(insertedUser1.email, emailUser1.email) assertEquals(insertedUser2.email, emailUser2.email) } @Test fun getUserByToken() { val salt = PasswordUtils.generateSalt() val newUser = CreateUserDto( "Alberto", "alberto@example.org", PasswordUtils.hashPassword("olamundo", salt), salt ) val insertedUser = MemUsersData.add(newUser) val token = MemUsersData.createToken(insertedUser) val tokenUser = MemUsersData.getByToken(token) assertEquals(insertedUser, tokenUser) } @Test fun existsUser() { val salt = PasswordUtils.generateSalt() val newUser = CreateUserDto( "Alberto", "alberto@example.org", PasswordUtils.hashPassword("olamundo", salt), salt ) val insertedUser = MemUsersData.add(newUser) assertTrue(MemUsersData.exists(insertedUser.id)) assertFalse(MemUsersData.exists(insertedUser.id + 1)) } @Test fun updateUser() { val salt = PasswordUtils.generateSalt() val newUser = CreateUserDto( "Alberto", "alberto@example.org", PasswordUtils.hashPassword("olamundo", salt), salt ) val insertedUser = MemUsersData.add(newUser) val requestEditUser = EditUserDto(insertedUser.id, "Mariana") MemUsersData.edit(requestEditUser) val edittedUser = MemUsersData.getById(insertedUser.id) assertNotEquals(edittedUser.name, insertedUser.name) assertEquals(edittedUser.name, "Mariana") } @Test fun deleteUser() { val salt = PasswordUtils.generateSalt() val newUser = CreateUserDto( "Alberto", "alberto@example.org", PasswordUtils.hashPassword("olamundo", salt), salt ) val insertedUser = MemUsersData.add(newUser) val gottenUser = MemUsersData.getById(insertedUser.id) assertEquals(insertedUser, gottenUser) MemUsersData.delete(insertedUser.id) assertFailsWith<TaskAppException> { MemUsersData.delete(insertedUser.id) } } }
isel-ls/src/test/kotlin/pt/isel/ls/data/mem/MemUsersDataTest.kt
1011562437
package pt.isel.ls.server enum class HeaderTypes(val field: String) { CONTENT_TYPE("content-type"), USER("User"), APP_JSON("application/json"), TEXT_PLAIN("text/plain"), ACCEPT("accept") }
isel-ls/src/main/kotlin/pt/isel/ls/HeaderTypes.kt
236508729
package pt.isel.ls.utils import java.security.MessageDigest import java.security.SecureRandom import java.util.* object PasswordUtils { fun generateSalt(): String { val bytes = ByteArray(8) SecureRandom.getInstanceStrong().nextBytes(bytes) return Base64.getEncoder().encodeToString(bytes) } fun hashPassword(password: String, salt: String): String { val saltedPassword = password + salt val hashedBytes = MessageDigest.getInstance("SHA-256").digest(saltedPassword.toByteArray(Charsets.UTF_8)) // Convert to a string // Source: https://gist.github.com/lovubuntu/164b6b9021f5ba54cefc67f60f7a1a25 return hashedBytes.fold(StringBuilder()) { sb, it -> sb.append("%02x".format(it)) }.toString() } }
isel-ls/src/main/kotlin/pt/isel/ls/utils/PasswordUtils.kt
917587543
package pt.isel.ls.utils import org.http4k.core.Request import org.http4k.routing.path import pt.isel.ls.TaskAppException import java.lang.IllegalStateException import java.lang.NumberFormatException object UrlUtils { const val LIMIT_NAME = "limit" const val SKIP_NAME = "skip" const val LIMIT_DEFAULT = 25 const val SKIP_DEFAULT = 0 private fun Request.getQueryInt(name: String, defaultValue: Int): Int { val query = this.query(name) return if (query != null) { try { val result = query.toInt() if (result >= 0) result else defaultValue } catch (_: NumberFormatException) { defaultValue } } else { defaultValue } } fun getLimit(request: Request): Int = request.getQueryInt(LIMIT_NAME, LIMIT_DEFAULT) fun getSkip(request: Request): Int = request.getQueryInt(SKIP_NAME, SKIP_DEFAULT) fun getPathInt(request: Request, name: String, fragmentName: String = name): Int { return try { val result = request.path(name)?.toInt() checkNotNull(result) { "$fragmentName not provided in URL." } } catch (ex: IllegalStateException) { throw TaskAppException(ErrorCodes.URL_PATH_ERROR, issue = ex.message) } catch (ex: NumberFormatException) { throw TaskAppException(ErrorCodes.URL_PATH_TYPE_ERROR, issue = "$fragmentName is of incorrect type.") } } }
isel-ls/src/main/kotlin/pt/isel/ls/utils/UrlUtils.kt
2970890359
package pt.isel.ls.utils import org.http4k.core.Status import org.http4k.core.Status.Companion.BAD_REQUEST import org.http4k.core.Status.Companion.CONFLICT import org.http4k.core.Status.Companion.INTERNAL_SERVER_ERROR import org.http4k.core.Status.Companion.NOT_FOUND import org.http4k.core.Status.Companion.UNAUTHORIZED import org.http4k.core.Status.Companion.UNPROCESSABLE_ENTITY enum class ErrorCodes(val code: Int, val message: String) { UNDEFINED(500, "An error has occurred, please try again later."), URL_PATH_ERROR(600, "There was an issue with one of the given parameters."), URL_QUERY_ERROR(601, "There was an issue with one of the given query parameters."), JSON_BODY_ERROR(602, "There was an issue with the supplied body."), URL_PATH_TYPE_ERROR(603, "There was an issue with the type of one of the given parameters."), PGSQL_CONN_NULL(700, "An error has occurred, please try again later."), PGSQL_UNEXPECTED(701, "An error has occurred, please try again later."), BOARD_READ_FAIL(1000, "Board not found."), BOARD_CREATE_FAIL(1001, "Board could not be created."), BOARD_DELETE_FAIL(1002, "Board could not be deleted."), BOARD_UPDATE_FAIL(1003, "Board could not be updated."), BOARD_NAME_IN_USE(1004, "Board name not unique."), ADD_USER_FAIL(1005, "Could not add the specified user to the specified board."), LIST_READ_FAIL(2000, "List not found."), LIST_CREATE_FAIL(2001, "List could not be created."), LIST_DELETE_FAIL(2002, "List could not be deleted."), LIST_UPDATE_FAIL(2003, "List could not be updated."), LIST_CREATE_FOREIGN_KEY_FAIL(2004, "List could not be created due to a failed reference."), AUTHENTICATION_CHALLENGE_FAILED(3000, "Authentication challenge failed."), NO_EMAIL_MATCH(3001, "Invalid email."), NO_TOKEN_MATCH(3002, "Invalid token."), EMAIL_ALREADY_IN_USE(3003, "Specified email is already in use."), EMAIL_FAILED_CHECK(3004, "Specified email format is incorrect."), NOT_AUTHENTICATED(3005, "Client is not correctly authenticated."), USER_READ_FAIL(3006, "User not found."), USER_CREATE_FAIL(3007, "User could not be created."), USER_DELETE_FAIL(3008, "User could not be deleted."), USER_UPDATE_FAIL(3009, "User edit failed."), TOKEN_GENERATION_FAILED(3010, "Token could not be generated at this moment."), AUTH_HEADER_MISSING(3011, "Missing or invalid Authorization header."), CARD_READ_FAIL(4000, "Card not found."), CARD_CREATE_FAIL(4001, "Card could not be created."), CARD_DELETE_FAIL(4002, "Card could not be deleted."), CARD_MOVE_FAIL(4003, "Card could not be moved."), CARD_UPDATE_FAIL(4004, "Card could not be updated."), CARD_MOVE_NEGATIVE(4005, "Card position cannot be negative."), CARD_CREATE_FOREIGN_KEY_FAIL(4006, "Card could not be created due to a failed reference."); fun http4kStatus(): Status = when (this) { URL_PATH_ERROR, URL_QUERY_ERROR, JSON_BODY_ERROR, EMAIL_FAILED_CHECK, URL_PATH_TYPE_ERROR -> BAD_REQUEST BOARD_READ_FAIL, LIST_READ_FAIL, USER_READ_FAIL, CARD_READ_FAIL -> NOT_FOUND EMAIL_ALREADY_IN_USE, BOARD_NAME_IN_USE -> CONFLICT ADD_USER_FAIL, LIST_CREATE_FOREIGN_KEY_FAIL, CARD_CREATE_FOREIGN_KEY_FAIL -> UNPROCESSABLE_ENTITY AUTHENTICATION_CHALLENGE_FAILED, NO_EMAIL_MATCH, NO_TOKEN_MATCH, NOT_AUTHENTICATED, AUTH_HEADER_MISSING -> UNAUTHORIZED else -> INTERNAL_SERVER_ERROR } }
isel-ls/src/main/kotlin/pt/isel/ls/utils/ErrorCodes.kt
2127003181
package pt.isel.ls.utils class EmailValidator { companion object { val EMAIL_REGEX = "^[A-Za-z](.*)([@]{1})(.{1,})(\\.)(.{1,})" fun isEmailValid(email: String): Boolean { return EMAIL_REGEX.toRegex().matches(email) } } }
isel-ls/src/main/kotlin/pt/isel/ls/utils/EmailValidator.kt
1367622688
package pt.isel.ls.tasksServices import pt.isel.ls.data.CardsData import pt.isel.ls.data.DataContext import pt.isel.ls.data.entities.Card import pt.isel.ls.tasksServices.dtos.EditCardDto import pt.isel.ls.tasksServices.dtos.InputCardDto import pt.isel.ls.tasksServices.dtos.InputMoveCardDto class ServiceCards(private val context: DataContext, private val cardsRepo: CardsData) { fun createCard(newCard: InputCardDto, boardId: Int, boardListId: Int): Card { lateinit var card: Card context.handleData { con -> card = cardsRepo.add(newCard, boardId, boardListId, con) } return card } fun getCardsOnList(boardId: Int, boardListId: Int, limit: Int = 25, skip: Int = 0): List<Card> { lateinit var cards: List<Card> context.handleData { con -> cards = cardsRepo.getByList(boardId, boardListId, limit, skip, con) } return cards } fun getCard(boardId: Int, cardId: Int): Card { lateinit var card: Card context.handleData { con -> card = cardsRepo.getById(cardId, con) } return card } fun editCard(editCard: EditCardDto, boardId: Int, cardId: Int) { context.handleData { con -> cardsRepo.edit(editCard, boardId, cardId, con) } } fun moveCard(moveList: InputMoveCardDto, boardId: Int, cardId: Int) { context.handleData { con -> cardsRepo.move(moveList, boardId, cardId, con) } } fun removeCard(boardId: Int, cardId: Int) { context.handleData { con -> cardsRepo.delete(cardId, con) } } }
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/ServiceCards.kt
3238534721
package pt.isel.ls.tasksServices import pt.isel.ls.data.BoardsData import pt.isel.ls.data.CardsData import pt.isel.ls.data.DataContext import pt.isel.ls.data.ListsData import pt.isel.ls.data.UsersData class TasksServices( context: DataContext, boardsRepo: BoardsData, usersRepo: UsersData, listsRepo: ListsData, cardsRepo: CardsData ) { val users = ServiceUsers(context, usersRepo) val boards = ServiceBoards(context, boardsRepo) val lists = ServiceLists(context, listsRepo) val cards = ServiceCards(context, cardsRepo) }
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/TasksServices.kt
2216537931
package pt.isel.ls.tasksServices import pt.isel.ls.data.DataContext import pt.isel.ls.data.ListsData import pt.isel.ls.data.entities.BoardList import pt.isel.ls.tasksServices.dtos.EditBoardListDto import pt.isel.ls.tasksServices.dtos.InputBoardListDto class ServiceLists(private val context: DataContext, private val listsRepo: ListsData) { fun createBoardList(boardId: Int, newBoardList: InputBoardListDto): BoardList { lateinit var boardList: BoardList context.handleData { con -> boardList = listsRepo.add(newBoardList, boardId, con) } return boardList } fun getBoardLists(boardId: Int, limit: Int = 25, skip: Int = 0): List<BoardList> { lateinit var boardLists: List<BoardList> context.handleData { con -> boardLists = listsRepo.getListsByBoard(boardId, limit, skip, con) } return boardLists } fun getBoardList(boardId: Int, boardListId: Int): BoardList { lateinit var boardList: BoardList context.handleData { con -> boardList = listsRepo.getById(boardListId, con) } return boardList } fun editBoardList(editList: EditBoardListDto, boardListId: Int, boardId: Int, ncards: Int) { context.handleData { con -> listsRepo.edit(editList.name, boardListId, boardId, ncards, con) } } fun removeList(boardId: Int, listId: Int) { context.handleData { con -> listsRepo.delete(listId, con) } } }
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/ServiceLists.kt
561723997
package pt.isel.ls.tasksServices import pt.isel.ls.TaskAppException import pt.isel.ls.data.DataContext import pt.isel.ls.data.UsersData import pt.isel.ls.data.entities.User import pt.isel.ls.tasksServices.dtos.CreateUserDto import pt.isel.ls.tasksServices.dtos.InputUserDto import pt.isel.ls.tasksServices.dtos.LoginUserDto import pt.isel.ls.tasksServices.dtos.OutputUserDto import pt.isel.ls.tasksServices.dtos.SecureOutputUserDto import pt.isel.ls.tasksServices.users.ChallengeFailureException import pt.isel.ls.utils.EmailValidator import pt.isel.ls.utils.ErrorCodes import pt.isel.ls.utils.PasswordUtils class ServiceUsers(private val context: DataContext, private val userRepository: UsersData) { fun createUser(newUser: InputUserDto): OutputUserDto { lateinit var user: User lateinit var token: String if (!EmailValidator.isEmailValid(newUser.email)) throw TaskAppException(ErrorCodes.EMAIL_FAILED_CHECK) val salt = PasswordUtils.generateSalt() val passwordHash = PasswordUtils.hashPassword(newUser.password, salt) val hashedNewUser = CreateUserDto(newUser.name, newUser.email, passwordHash, salt) context.handleData { con -> user = userRepository.add(hashedNewUser, con) token = userRepository.createToken(user, con) } return OutputUserDto(token, user.id, user.name) } fun getUser(userId: Int): SecureOutputUserDto { lateinit var user: User context.handleData { con -> user = userRepository.getById(userId, con) } // Wipe out mentions of password and salt return SecureOutputUserDto(user.id, user.name, user.email) } fun getUserByToken(token: String): User { lateinit var user: User context.handleData { con -> user = userRepository.getByToken(token, con) } return user } fun authenticateUser(credentials: LoginUserDto): OutputUserDto { lateinit var user: User try { context.handleData { user = userRepository.getByEmail(credentials.email, it) } } catch (ex: TaskAppException) { throw if (ex.errorCode == ErrorCodes.NO_EMAIL_MATCH) { ChallengeFailureException() } else { ex } } val hashedPasswordAttempt = PasswordUtils.hashPassword(credentials.password, user.salt) if (hashedPasswordAttempt == user.passwordHash) { lateinit var token: String context.handleData { token = userRepository.createToken(user, it) } return OutputUserDto(token, user.id, user.name) } throw ChallengeFailureException() } }
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/ServiceUsers.kt
3888443521
package pt.isel.ls.tasksServices.dtos import kotlinx.serialization.Serializable @Serializable data class InputMoveCardDto(val lid: Int, val cix: Int) : Dto
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/dtos/InputMoveCardDto.kt
1618325927
package pt.isel.ls.tasksServices.dtos import kotlinx.serialization.Serializable @Serializable data class EditBoardDto(val id: Int, val description: String) : Dto
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/dtos/EditBoardDto.kt
2204742875
package pt.isel.ls.tasksServices.dtos import kotlinx.serialization.Serializable @Serializable data class ErrorDto(val message: String, val code: Int)
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/dtos/ErrorDto.kt
2516645001
package pt.isel.ls.tasksServices.dtos import kotlinx.serialization.Serializable @Serializable data class EditBoardListDto(val name: String) : Dto
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/dtos/EditBoardListDto.kt
3166227444
package pt.isel.ls.tasksServices.dtos import kotlinx.serialization.Serializable @Serializable data class LoginUserDto(val email: String, val password: String)
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/dtos/LoginUserDto.kt
2412495739
package pt.isel.ls.tasksServices.dtos data class CreateUserDto(val name: String, val email: String, val passwordHash: String, val salt: String)
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/dtos/CreateUserDto.kt
235132658
package pt.isel.ls.tasksServices.dtos import kotlinx.serialization.Serializable @Serializable data class SecureOutputUserDto(val id: Int, val name: String, val email: String)
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/dtos/SecureOutputUserDto.kt
3330609134
package pt.isel.ls.tasksServices.dtos import kotlinx.serialization.Serializable @Serializable data class OutputIdDto(val id: Int) : Dto
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/dtos/OutputIdDto.kt
78740394
package pt.isel.ls.tasksServices.dtos import kotlinx.serialization.Serializable @Serializable data class OutputUserDto(val token: String, val id: Int, val name: String) : Dto
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/dtos/OutputUserDto.kt
2608407035
package pt.isel.ls.tasksServices.dtos interface Dto
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/dtos/Dto.kt
4269085499
package pt.isel.ls.tasksServices.dtos import kotlinx.serialization.Serializable import pt.isel.ls.data.utils.TimestampAsLongSerializer import java.security.Timestamp @Serializable data class InputCardDto( val name: String, val description: String, @Serializable(with = TimestampAsLongSerializer::class) val dueDate: java.sql.Timestamp? = null ) : Dto
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/dtos/InputCardDto.kt
3215880305
package pt.isel.ls.tasksServices.dtos import kotlinx.serialization.Serializable @Serializable data class EditUserDto(val id: Int, val name: String) : Dto
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/dtos/EditUserDto.kt
188022923
package pt.isel.ls.tasksServices.dtos import kotlinx.serialization.Serializable @Serializable data class InputUserDto(val name: String, val email: String, val password: String) : Dto
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/dtos/InputUserDto.kt
2243777288
package pt.isel.ls.tasksServices.dtos import kotlinx.serialization.Serializable import pt.isel.ls.data.utils.TimestampAsLongSerializer import java.sql.Timestamp @Serializable data class EditCardDto( val name: String, val description: String, @Serializable(with = TimestampAsLongSerializer::class) val dueDate: Timestamp? = null )
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/dtos/EditCardDto.kt
2216423891
package pt.isel.ls.tasksServices.dtos data class UserCredentialsDto( val passwordHash: String, val salt: String )
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/dtos/UserCredentialsDto.kt
1508912890
package pt.isel.ls.tasksServices.dtos import kotlinx.serialization.Serializable import pt.isel.ls.data.entities.Entity @Serializable data class OutputEntitiesDto<T : Entity>(val list: List<T>)
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/dtos/OutputEntitiesDto.kt
11233516
package pt.isel.ls.tasksServices.dtos import kotlinx.serialization.Serializable @Serializable data class InputBoardDto(val name: String, val description: String) : Dto
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/dtos/InputBoardDto.kt
756179760
package pt.isel.ls.tasksServices.dtos import kotlinx.serialization.Serializable @Serializable data class InputBoardListDto(val name: String) : Dto
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/dtos/InputBoardListDto.kt
754097737
package pt.isel.ls.tasksServices.users import pt.isel.ls.TaskAppException import pt.isel.ls.utils.ErrorCodes class ChallengeFailureException : TaskAppException(ErrorCodes.AUTHENTICATION_CHALLENGE_FAILED)
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/users/ChallengeFailureException.kt
4229444674
package pt.isel.ls.tasksServices import pt.isel.ls.data.BoardsData import pt.isel.ls.data.DataContext import pt.isel.ls.data.entities.Board import pt.isel.ls.data.entities.User import pt.isel.ls.tasksServices.dtos.InputBoardDto import pt.isel.ls.tasksServices.dtos.SecureOutputUserDto class ServiceBoards(private val context: DataContext, private val boardRepository: BoardsData) { fun getBoard(boardId: Int, user: User): Board { lateinit var board: Board context.handleData { con -> board = boardRepository.getById(boardId, con) } return board } fun getBoard(boardName: String, user: User): Board { lateinit var board: Board context.handleData { con -> board = boardRepository.getByName(boardName, con) } return board } fun getUserBoards(user: User, searchField: String?, limit: Int = 25, skip: Int = 0): List<Board> { lateinit var boards: List<Board> if (searchField.isNullOrBlank()) { context.handleData { con -> boards = boardRepository.getUserBoards(user, limit, skip, con) } } else { context.handleData { con -> boards = boardRepository.filterByName(user, searchField, con) } } return boards } fun createBoard(newBoard: InputBoardDto, user: User): Board { lateinit var board: Board context.handleData { board = boardRepository.add(newBoard, it) boardRepository.addUserToBoard(user.id, board.id, it) } return board } fun getUsersOnBoard(boardId: Int, user: User, limit: Int = 25, skip: Int = 0): List<SecureOutputUserDto> { lateinit var users: List<SecureOutputUserDto> context.handleData { con -> users = boardRepository.getUsers(boardId, user, limit, skip, con) } return users } fun addUserOnBoard(boardId: Int, userId: Int) { context.handleData { con -> boardRepository.addUserToBoard(userId, boardId, con) } } fun deleteUserOnBoard(boardId: Int, userId: Int) { context.handleData { con -> boardRepository.deleteUserFromBoard(userId, boardId, con) } } }
isel-ls/src/main/kotlin/pt/isel/ls/tasksServices/ServiceBoards.kt
716531559
package pt.isel.ls.webApi import kotlinx.serialization.SerializationException import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.http4k.core.ContentType import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status import pt.isel.ls.TaskAppException import pt.isel.ls.server.HeaderTypes import pt.isel.ls.tasksServices.TasksServices import pt.isel.ls.tasksServices.dtos.InputUserDto import pt.isel.ls.tasksServices.dtos.LoginUserDto import pt.isel.ls.utils.ErrorCodes import pt.isel.ls.utils.UrlUtils class UsersApi( private val services: TasksServices ) { fun loginUser(request: Request): Response { return try { val credentials = Json.decodeFromString<LoginUserDto>(request.bodyString()) val result = services.users.authenticateUser(credentials) Response(Status.OK) .header(HeaderTypes.CONTENT_TYPE.field, ContentType.APPLICATION_JSON.value) .body(Json.encodeToString(result)) } catch (ex: SerializationException) { throw TaskAppException(ErrorCodes.JSON_BODY_ERROR, ex.message) } } fun getUser(request: Request): Response { val userId = UrlUtils.getPathInt(request, "id", "User") val user = services.users.getUser(userId) return Response(Status.OK).header(HeaderTypes.CONTENT_TYPE.field, ContentType.APPLICATION_JSON.value) .body(Json.encodeToString(user)) } fun createUser(request: Request): Response { return try { val newUser = Json.decodeFromString<InputUserDto>(request.bodyString()) val user = services.users.createUser(newUser) Response(Status.CREATED) .header(HeaderTypes.CONTENT_TYPE.field, ContentType.APPLICATION_JSON.value) .body(Json.encodeToString(user)) } catch (ex: SerializationException) { throw TaskAppException(ErrorCodes.JSON_BODY_ERROR, ex.message) } } }
isel-ls/src/main/kotlin/pt/isel/ls/webApi/UsersApi.kt
3164718358
package pt.isel.ls.webApi import kotlinx.serialization.SerializationException import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.http4k.core.ContentType import org.http4k.core.HttpHandler import org.http4k.core.Request import org.http4k.core.RequestContexts import org.http4k.core.Response import org.http4k.core.Status.Companion.CREATED import org.http4k.core.Status.Companion.OK import org.http4k.routing.path import pt.isel.ls.TaskAppException import pt.isel.ls.data.entities.User import pt.isel.ls.server.HeaderTypes import pt.isel.ls.tasksServices.TasksServices import pt.isel.ls.tasksServices.dtos.InputBoardDto import pt.isel.ls.tasksServices.dtos.OutputIdDto import pt.isel.ls.utils.ErrorCodes import pt.isel.ls.utils.UrlUtils import java.lang.IllegalStateException import java.lang.NumberFormatException class BoardsApi( private val services: TasksServices ) { fun getBoard(contexts: RequestContexts): HttpHandler = { val boardId = try { val boardId = it.path("id")?.toInt() checkNotNull(boardId) { "Board ID not provided in URL." } } catch (ex: IllegalStateException) { throw TaskAppException(ErrorCodes.URL_PATH_ERROR, issue = ex.message) } catch (ex: NumberFormatException) { throw TaskAppException(ErrorCodes.URL_PATH_TYPE_ERROR) } val user: User = contexts[it]["user"] ?: throw TaskAppException(ErrorCodes.NOT_AUTHENTICATED) val board = services.boards.getBoard(boardId, user) Response(OK) .header(HeaderTypes.CONTENT_TYPE.field, ContentType.APPLICATION_JSON.value) .body(Json.encodeToString(board)) } fun createBoard(contexts: RequestContexts): HttpHandler = { val user: User = contexts[it]["user"] ?: throw TaskAppException(ErrorCodes.NOT_AUTHENTICATED) try { val board = Json.decodeFromString<InputBoardDto>(it.bodyString()) if (board.name.isEmpty()) throw TaskAppException(ErrorCodes.JSON_BODY_ERROR, "Name is mandatory.") val rsp = services.boards.createBoard(board, user) val returnValue = OutputIdDto(rsp.id) Response(CREATED).header(HeaderTypes.CONTENT_TYPE.field, ContentType.APPLICATION_JSON.value) .body(Json.encodeToString(returnValue)) } catch (ex: SerializationException) { throw TaskAppException(ErrorCodes.JSON_BODY_ERROR, ex.message) } } fun getBoards(contexts: RequestContexts): HttpHandler = { val user: User = contexts[it]["user"] ?: throw TaskAppException(ErrorCodes.NOT_AUTHENTICATED) val search = it.query("search") val boards = services.boards.getUserBoards(user, search, UrlUtils.getLimit(it), UrlUtils.getSkip(it)) Response(OK) .header(HeaderTypes.CONTENT_TYPE.field, ContentType.APPLICATION_JSON.value) .body(Json.encodeToString(boards)) } fun getBoardUsers(contexts: RequestContexts): HttpHandler = { val boardId = UrlUtils.getPathInt(it, "id", "Board") val user: User = contexts[it]["user"] ?: throw TaskAppException(ErrorCodes.NOT_AUTHENTICATED) val users = services.boards.getUsersOnBoard(boardId, user, UrlUtils.getLimit(it), UrlUtils.getSkip(it)) Response(OK) .header(HeaderTypes.CONTENT_TYPE.field, ContentType.APPLICATION_JSON.value) .body(Json.encodeToString(users)) } fun deleteUserFromBoard(request: Request): Response { val boardId = UrlUtils.getPathInt(request, "id", "Board") val userId = UrlUtils.getPathInt(request, "uid", "User") services.boards.deleteUserOnBoard(boardId, userId) return Response(OK) .header(HeaderTypes.CONTENT_TYPE.field, ContentType.APPLICATION_JSON.value) } fun addUsersOnBoard(request: Request): Response { val boardId = UrlUtils.getPathInt(request, "id", "Board") val userId = UrlUtils.getPathInt(request, "uid", "User") services.boards.addUserOnBoard(boardId, userId) return Response(OK) .header(HeaderTypes.CONTENT_TYPE.field, ContentType.APPLICATION_JSON.value) } }
isel-ls/src/main/kotlin/pt/isel/ls/webApi/BoardsApi.kt
2776739061
package pt.isel.ls.webApi import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.http4k.core.ContentType import org.http4k.core.Filter import org.http4k.core.Request import org.http4k.core.RequestContexts import org.http4k.core.Response import org.slf4j.LoggerFactory import pt.isel.ls.TaskAppException import pt.isel.ls.server.HeaderTypes import pt.isel.ls.tasksServices.TasksServices import pt.isel.ls.tasksServices.dtos.ErrorDto import pt.isel.ls.utils.ErrorCodes.AUTH_HEADER_MISSING class Filters( private val services: TasksServices ) { private val logger = LoggerFactory.getLogger("pt.isel.ls.TaskServer") private fun logRequest(request: Request) { logger.info( "incoming request: method={}, uri={}, content-type={} accept={}", request.method, request.uri, request.header("content-type"), request.header("accept") ) } val logRequest = Filter { next -> { logRequest(it) try { next(it) } catch (ex: TaskAppException) { if (ex.message != null) logger.error(ex.message) if (ex.issue != null) logger.error(ex.issue) Response(ex.errorCode.http4kStatus()) .header(HeaderTypes.CONTENT_TYPE.field, ContentType.APPLICATION_JSON.value) .body( Json.encodeToString( ErrorDto( ex.issue ?: ex.errorCode.message, ex.errorCode.code ) ) ) } } } fun filterUser(contexts: RequestContexts) = Filter { next -> { request -> val authHeader = request.header("Authorization") if (authHeader != null && authHeader.startsWith("Bearer ")) { val token = authHeader.substring(7) val user = services.users.getUserByToken(token) contexts[request]["user"] = user next(request) } else { throw TaskAppException(AUTH_HEADER_MISSING) } } } val authFilter = Filter { next -> { request -> val authHeader = request.header("Authorization") if (authHeader != null && authHeader.startsWith("Bearer ")) { val token = authHeader.substring(7) services.users.getUserByToken(token) next(request) } else { throw TaskAppException(AUTH_HEADER_MISSING) } } } }
isel-ls/src/main/kotlin/pt/isel/ls/webApi/Filters.kt
4112406557
package pt.isel.ls.webApi import kotlinx.serialization.SerializationException import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.http4k.core.ContentType import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status import org.http4k.core.Status.Companion.OK import pt.isel.ls.TaskAppException import pt.isel.ls.server.HeaderTypes import pt.isel.ls.tasksServices.TasksServices import pt.isel.ls.tasksServices.dtos.EditCardDto import pt.isel.ls.tasksServices.dtos.InputCardDto import pt.isel.ls.tasksServices.dtos.InputMoveCardDto import pt.isel.ls.tasksServices.dtos.OutputIdDto import pt.isel.ls.utils.ErrorCodes import pt.isel.ls.utils.UrlUtils class CardsApi( private val services: TasksServices ) { fun deleteCard(request: Request): Response { val boardId = UrlUtils.getPathInt(request, "id", "Board") val cardId = UrlUtils.getPathInt(request, "cid", "Card") services.cards.removeCard(boardId, cardId) return Response(OK) } fun alterCardListPosition(request: Request): Response { val boardId = UrlUtils.getPathInt(request, "id", "Board") val cardId = UrlUtils.getPathInt(request, "cid", "Card") return try { val inputList = Json.decodeFromString<InputMoveCardDto>(request.bodyString()) services.cards.moveCard(inputList, boardId, cardId) Response(OK).header(HeaderTypes.CONTENT_TYPE.field, ContentType.APPLICATION_JSON.value) } catch (ex: SerializationException) { throw TaskAppException(ErrorCodes.JSON_BODY_ERROR, ex.message) } } fun getCardsFromList(request: Request): Response { val boardId = UrlUtils.getPathInt(request, "id", "Board") val boardListId = UrlUtils.getPathInt(request, "lid", "List") val cards = services.cards.getCardsOnList(boardId, boardListId, UrlUtils.getLimit(request), UrlUtils.getSkip(request)) return Response(OK) .header(HeaderTypes.CONTENT_TYPE.field, ContentType.APPLICATION_JSON.value) .body(Json.encodeToString(cards)) } fun createCard(request: Request): Response { val boardId = UrlUtils.getPathInt(request, "id", "Board") val boardListId = UrlUtils.getPathInt(request, "lid", "List") return try { val newCard = Json.decodeFromString<InputCardDto>(request.bodyString()) val card = services.cards.createCard(newCard, boardId, boardListId) Response(Status.CREATED) .header(HeaderTypes.CONTENT_TYPE.field, ContentType.APPLICATION_JSON.value) .body(Json.encodeToString(OutputIdDto(card.id))) } catch (ex: SerializationException) { throw TaskAppException(ErrorCodes.JSON_BODY_ERROR, ex.message) } } fun getCard(request: Request): Response { val boardId = UrlUtils.getPathInt(request, "id", "Board") val cardId = UrlUtils.getPathInt(request, "cid", "Card") val card = services.cards.getCard(boardId, cardId) return Response(OK) .header(HeaderTypes.CONTENT_TYPE.field, ContentType.APPLICATION_JSON.value) .body(Json.encodeToString(card)) } fun editCard(request: Request): Response { val boardId = UrlUtils.getPathInt(request, "id", "Board") val cardId = UrlUtils.getPathInt(request, "cid", "Card") return try { val editCard = Json.decodeFromString<EditCardDto>(request.bodyString()) services.cards.editCard(editCard, boardId, cardId) Response(OK).header(HeaderTypes.CONTENT_TYPE.field, ContentType.APPLICATION_JSON.value) } catch (ex: SerializationException) { throw TaskAppException(ErrorCodes.JSON_BODY_ERROR, ex.message) } } }
isel-ls/src/main/kotlin/pt/isel/ls/webApi/CardsApi.kt
1694200437
package pt.isel.ls.webApi import kotlinx.serialization.SerializationException import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.http4k.core.ContentType import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status import org.http4k.routing.path import pt.isel.ls.TaskAppException import pt.isel.ls.server.HeaderTypes import pt.isel.ls.tasksServices.TasksServices import pt.isel.ls.tasksServices.dtos.EditBoardListDto import pt.isel.ls.tasksServices.dtos.InputBoardListDto import pt.isel.ls.tasksServices.dtos.OutputIdDto import pt.isel.ls.utils.ErrorCodes import pt.isel.ls.utils.UrlUtils class ListsApi( private val services: TasksServices ) { fun deleteList(request: Request): Response { val boardId = UrlUtils.getPathInt(request, "id", "Board") val listId = UrlUtils.getPathInt(request, "lid", "List") services.lists.removeList(boardId, listId) return Response(Status.OK) } fun editList(request: Request): Response { val boardId = UrlUtils.getPathInt(request, "id", "Board") val boardListId = UrlUtils.getPathInt(request, "lid", "List") val ncards = request.path("ncards")?.toInt() ?: 0 return try { val editList = Json.decodeFromString<EditBoardListDto>(request.bodyString()) services.lists.editBoardList(editList, boardListId, boardId, ncards) Response(Status.OK) } catch (ex: SerializationException) { throw TaskAppException(ErrorCodes.JSON_BODY_ERROR, ex.message) } } fun getList(request: Request): Response { val boardId = UrlUtils.getPathInt(request, "id", "Board") val boardListId = UrlUtils.getPathInt(request, "lid", "List") val list = services.lists.getBoardList(boardId, boardListId) return Response(Status.OK) .header(HeaderTypes.CONTENT_TYPE.field, ContentType.APPLICATION_JSON.value) .body(Json.encodeToString(list)) } fun getLists(request: Request): Response { val boardId = UrlUtils.getPathInt(request, "id", "Board") val boardLists = services.lists.getBoardLists(boardId, UrlUtils.getLimit(request), UrlUtils.getSkip(request)) return Response(Status.OK).header(HeaderTypes.CONTENT_TYPE.field, ContentType.APPLICATION_JSON.value) .body(Json.encodeToString(boardLists)) } fun createList(request: Request): Response { val boardId = UrlUtils.getPathInt(request, "id", "Board") return try { val listInput = Json.decodeFromString<InputBoardListDto>(request.bodyString()) val boardList = services.lists.createBoardList(boardId, listInput) Response(Status.CREATED) .header(HeaderTypes.CONTENT_TYPE.field, ContentType.APPLICATION_JSON.value) .body(Json.encodeToString(OutputIdDto(boardList.id))) } catch (ex: SerializationException) { throw TaskAppException(ErrorCodes.JSON_BODY_ERROR, ex.message) } } }
isel-ls/src/main/kotlin/pt/isel/ls/webApi/ListsApi.kt
102183469
package pt.isel.ls.data import java.sql.Connection interface DataContext { fun handleData(block: (Connection?) -> Unit) }
isel-ls/src/main/kotlin/pt/isel/ls/data/DataContext.kt
1554031856
package pt.isel.ls.data import pt.isel.ls.data.entities.User import pt.isel.ls.tasksServices.dtos.CreateUserDto import pt.isel.ls.tasksServices.dtos.EditUserDto import java.sql.Connection interface UsersData : Data<User> { fun createToken(user: User, connection: Connection? = null): String fun getByToken(token: String, connection: Connection? = null): User fun getByEmail(email: String, connection: Connection? = null): User fun add(newUser: CreateUserDto, connection: Connection? = null): User fun edit(editUser: EditUserDto, connection: Connection? = null) }
isel-ls/src/main/kotlin/pt/isel/ls/data/UsersData.kt
295942694
package pt.isel.ls.data import pt.isel.ls.data.entities.Board import pt.isel.ls.data.entities.User import pt.isel.ls.tasksServices.dtos.EditBoardDto import pt.isel.ls.tasksServices.dtos.InputBoardDto import pt.isel.ls.tasksServices.dtos.SecureOutputUserDto import java.sql.Connection interface BoardsData : Data<Board> { fun getByName(name: String, connection: Connection? = null): Board fun getUserBoards(user: User, limit: Int = 25, skip: Int = 0, connection: Connection? = null): List<Board> fun edit(editBoard: EditBoardDto, connection: Connection? = null) fun add(newBoard: InputBoardDto, connection: Connection? = null): Board fun addUserToBoard(userId: Int, boardId: Int, connection: Connection? = null) fun deleteUserFromBoard(userId: Int, boardId: Int, connection: Connection? = null) fun getUsers(boardId: Int, user: User, limit: Int = 25, skip: Int = 0, connection: Connection? = null): List<SecureOutputUserDto> fun filterByName(user: User, searchField: String, con: Connection?): List<Board> }
isel-ls/src/main/kotlin/pt/isel/ls/data/BoardsData.kt
3961598050
package pt.isel.ls.data import pt.isel.ls.data.entities.Entity import java.sql.Connection interface Data<K : Entity> { fun getById(id: Int, connection: Connection? = null): K fun delete(id: Int, connection: Connection? = null) fun exists(id: Int, connection: Connection? = null): Boolean }
isel-ls/src/main/kotlin/pt/isel/ls/data/Data.kt
3755082733
package pt.isel.ls.data.utils import kotlinx.serialization.KSerializer import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import java.sql.Timestamp /* java.sql.Timestamp can be used for Postgres Timestamp, but cannot be serialized with Kotlinx oob. Thankfully this seems to be a way around it. https://github.com/Kotlin/kotlinx.serialization/issues/23#issuecomment-1141089814 https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#specifying-serializer-on-a-property https://github.com/Kotlin/kotlinx.serialization/blob/master/guide/example/example-serializer-15.kt */ object TimestampAsLongSerializer : KSerializer<Timestamp> { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Timestamp", PrimitiveKind.LONG) override fun serialize(encoder: Encoder, value: Timestamp) = encoder.encodeLong(value.time) override fun deserialize(decoder: Decoder): Timestamp = Timestamp(decoder.decodeLong()) }
isel-ls/src/main/kotlin/pt/isel/ls/data/utils/TimestampAsLongSerializer.kt
2204363184
package pt.isel.ls.data import pt.isel.ls.data.entities.BoardList import pt.isel.ls.tasksServices.dtos.InputBoardListDto import java.sql.Connection interface ListsData : Data<BoardList> { fun getListsByBoard(boardId: Int, limit: Int = 25, skip: Int = 0, connection: Connection? = null): List<BoardList> fun edit(editName: String, listId: Int, boardId: Int, ncards: Int = 0, connection: Connection? = null) fun add(newBoardList: InputBoardListDto, boardId: Int, connection: Connection? = null): BoardList }
isel-ls/src/main/kotlin/pt/isel/ls/data/ListsData.kt
750805691
package pt.isel.ls.data.pgsql import pt.isel.ls.TaskAppException import pt.isel.ls.utils.ErrorCodes class IllegalConnException : TaskAppException(ErrorCodes.PGSQL_CONN_NULL, message = "A null PgSql Connection use was attempted.")
isel-ls/src/main/kotlin/pt/isel/ls/data/pgsql/IllegalConnException.kt
3625806389
package pt.isel.ls.data.pgsql import org.postgresql.util.PSQLState import pt.isel.ls.TaskAppException import pt.isel.ls.data.BoardsData import pt.isel.ls.data.entities.Board import pt.isel.ls.data.entities.User import pt.isel.ls.tasksServices.dtos.EditBoardDto import pt.isel.ls.tasksServices.dtos.InputBoardDto import pt.isel.ls.tasksServices.dtos.SecureOutputUserDto import pt.isel.ls.utils.ErrorCodes import java.sql.Connection import java.sql.SQLException object PgSqlBoardsData : BoardsData { override fun getByName(name: String, connection: Connection?): Board { connection ?: throw IllegalConnException() val statement = connection.prepareStatement( "select * from Boards where name = ?;" ) statement.setString(1, name) val rs = statement.executeQuery() while (rs.next()) { return Board( rs.getInt("id"), rs.getString("name"), rs.getString("description") ) } throw TaskAppException(ErrorCodes.BOARD_READ_FAIL) } override fun getUserBoards(user: User, limit: Int, skip: Int, connection: Connection?): List<Board> { connection ?: throw IllegalConnException() val statement = connection.prepareStatement( "select id, name, description from Boards b join UsersBoards ub on b.id = ub.boardId where ub.userId = ? offset ? limit ?;" ) statement.setInt(1, user.id) statement.setInt(2, skip) statement.setInt(3, limit) val rs = statement.executeQuery() val results = mutableListOf<Board>() while (rs.next()) { results += Board( rs.getInt("id"), rs.getString("name"), rs.getString("description") ) } return results } override fun getById(id: Int, connection: Connection?): Board { connection ?: throw IllegalConnException() val statement = connection.prepareStatement( "select * from Boards where id = ?;" ) statement.setInt(1, id) val rs = statement.executeQuery() while (rs.next()) { return Board( rs.getInt("id"), rs.getString("name"), rs.getString("description") ) } throw TaskAppException(ErrorCodes.BOARD_READ_FAIL) } override fun add(newBoard: InputBoardDto, connection: Connection?): Board { connection ?: throw IllegalConnException() val statement = connection.prepareStatement( "insert into Boards (name, description) values (?, ?) returning id;" ) statement.setString(1, newBoard.name) statement.setString(2, newBoard.description) val rs = try { statement.executeQuery() } catch (ex: SQLException) { throw if (ex.sqlState == PSQLState.UNIQUE_VIOLATION.state) { TaskAppException(ErrorCodes.BOARD_NAME_IN_USE) } else { ex } } while (rs.next()) { val id = rs.getInt("id") return Board(id, newBoard.name, newBoard.description) } throw TaskAppException(ErrorCodes.BOARD_CREATE_FAIL) } override fun delete(id: Int, connection: Connection?) { connection ?: throw IllegalConnException() val statement = connection.prepareStatement( "delete from Boards where id = ?;" ) statement.setInt(1, id) val count = statement.executeUpdate() if (count == 0) throw TaskAppException(ErrorCodes.BOARD_DELETE_FAIL) } override fun edit(editBoard: EditBoardDto, connection: Connection?) { connection ?: throw IllegalConnException() val statement = connection.prepareStatement( "update Boards set description = ? where id = ?;" ) statement.setString(1, editBoard.description) statement.setInt(2, editBoard.id) val count = statement.executeUpdate() if (count == 0) throw TaskAppException(ErrorCodes.BOARD_UPDATE_FAIL) } override fun exists(id: Int, connection: Connection?): Boolean { connection ?: throw IllegalConnException() val statement = connection.prepareStatement( "select count(*) exists from Boards where id = ?;" ) statement.setInt(1, id) val rs = statement.executeQuery() while (rs.next()) { return rs.getInt("exists") == 1 } return false } override fun addUserToBoard(userId: Int, boardId: Int, connection: Connection?) { connection ?: throw IllegalConnException() val statement = connection.prepareStatement( "insert into usersboards (userid, boardid) values (?,?);" ) statement.setInt(1, userId) statement.setInt(2, boardId) try { statement.execute() } catch (ex: SQLException) { when (ex.sqlState) { PSQLState.FOREIGN_KEY_VIOLATION.state -> throw TaskAppException(ErrorCodes.ADD_USER_FAIL) PSQLState.UNIQUE_VIOLATION.state -> return // It's already there, so no harm done. else -> throw ex } } } override fun getUsers(boardId: Int, user: User, limit: Int, skip: Int, connection: Connection?): List<SecureOutputUserDto> { connection ?: throw IllegalConnException() val statement = connection.prepareStatement( "select u.id, u.name, u.email from Users u join UsersBoards ub on u.id = ub.userid where ub.boardid = ? offset ? limit ?;" ) statement.setInt(1, boardId) statement.setInt(2, skip) statement.setInt(3, limit) val rs = statement.executeQuery() val results = mutableListOf<SecureOutputUserDto>() while (rs.next()) { results += SecureOutputUserDto( rs.getInt("id"), rs.getString("name"), rs.getString("email") ) } return results } override fun filterByName(user: User, searchField: String, con: Connection?): List<Board> { con ?: throw IllegalConnException() val statement = con.prepareStatement( "select b.* from Boards b join usersboards ub on b.id = ub.boardid where ub.userid = ? and LOWER(b.name) like LOWER(?) ;" ) statement.setInt(1, user.id) statement.setString(2, "%${searchField.lowercase()}%") val boards = mutableListOf<Board>() val rs = statement.executeQuery() while (rs.next()) { boards.add( Board( rs.getInt("id"), rs.getString("name"), rs.getString("description") ) ) } return boards } override fun deleteUserFromBoard(userId: Int, boardId: Int, connection: Connection?) { connection ?: throw IllegalConnException() val statement = connection.prepareStatement( "delete from usersboards where userid=? and boardid=?;" ) statement.setInt(1, userId) statement.setInt(2, boardId) statement.execute() } }
isel-ls/src/main/kotlin/pt/isel/ls/data/pgsql/PgSqlBoardsData.kt
4243119250
package pt.isel.ls.data.pgsql import org.postgresql.ds.PGSimpleDataSource import pt.isel.ls.TaskAppException import pt.isel.ls.data.DataContext import pt.isel.ls.utils.ErrorCodes import java.sql.Connection import java.sql.SQLException object PgDataContext : DataContext { private val dataSource: PGSimpleDataSource = PGSimpleDataSource() init { dataSource.setUrl(System.getenv("JDBC_DATABASE_URL")) } fun getConnection() = dataSource.connection override fun handleData(block: (Connection?) -> Unit) { getConnection().use { con -> con.autoCommit = false try { block(con).also { con.commit() } } catch (e: TaskAppException) { con.rollback() throw e } catch (e: SQLException) { con.rollback() throw UnexpectedSQLException(e.message) } catch (e: Exception) { con.rollback() throw TaskAppException(ErrorCodes.UNDEFINED, ErrorCodes.UNDEFINED.message, e.message) } } } }
isel-ls/src/main/kotlin/pt/isel/ls/data/pgsql/PgDataContext.kt
2673951419
package pt.isel.ls.data.pgsql import org.postgresql.util.PSQLException import org.postgresql.util.PSQLState import pt.isel.ls.TaskAppException import pt.isel.ls.data.UsersData import pt.isel.ls.data.entities.User import pt.isel.ls.tasksServices.dtos.CreateUserDto import pt.isel.ls.tasksServices.dtos.EditUserDto import pt.isel.ls.utils.ErrorCodes import java.sql.Connection import java.sql.SQLException import java.sql.Timestamp import java.util.UUID object PgSqlUsersData : UsersData { override fun createToken(user: User, connection: Connection?): String { checkNotNull(connection) { "Connection is need to use DB" } val statement = connection.prepareStatement( "insert into UsersTokens (token, userId, creationDate) values (?,?,?);" ) val token = UUID.randomUUID() statement.setObject(1, token) statement.setInt(2, user.id) statement.setTimestamp(3, Timestamp(System.currentTimeMillis())) val count = try { statement.executeUpdate() } catch (ex: SQLException) { throw if (ex.sqlState == PSQLState.FOREIGN_KEY_VIOLATION.state) { TaskAppException(ErrorCodes.TOKEN_GENERATION_FAILED) } else { ex } } if (count == 0) throw TaskAppException(ErrorCodes.TOKEN_GENERATION_FAILED) return token.toString() } override fun getByToken(token: String, connection: Connection?): User { checkNotNull(connection) { "Connection is need to use DB" } val statement = connection.prepareStatement( "select u.id, u.name, u.email, u.passwordHash, u.salt from Users u join UsersTokens ut on u.id = ut.userId where token = ?;" ) statement.setString(1, token) val rs = statement.executeQuery() while (rs.next()) { return User( rs.getInt("id"), rs.getString("name"), rs.getString("email"), rs.getString("passwordHash"), rs.getString("salt") ) } throw TaskAppException(ErrorCodes.NO_TOKEN_MATCH) } override fun getByEmail(email: String, connection: Connection?): User { checkNotNull(connection) { "Connection is need to use DB" } val statement = connection.prepareStatement( "select * from Users where email = ?;" ) statement.setString(1, email) val rs = statement.executeQuery() while (rs.next()) { return User( rs.getInt("id"), rs.getString("name"), rs.getString("email"), rs.getString("passwordHash"), rs.getString("salt") ) } throw TaskAppException(ErrorCodes.NO_EMAIL_MATCH) } override fun getById(id: Int, connection: Connection?): User { checkNotNull(connection) { "Connection is need to use DB" } val statement = connection.prepareStatement( "select * from Users where id = ?;" ) statement.setInt(1, id) val rs = statement.executeQuery() while (rs.next()) { return User( rs.getInt("id"), rs.getString("name"), rs.getString("email"), rs.getString("passwordHash"), rs.getString("salt") ) } throw TaskAppException(ErrorCodes.USER_READ_FAIL) } override fun add(newUser: CreateUserDto, connection: Connection?): User { checkNotNull(connection) { "Connection is need to use DB" } val statement = connection.prepareStatement( "insert into Users (name, email, passwordHash, salt) values (?, ?, ?, ?) returning id,name,email;" ) statement.setString(1, newUser.name) statement.setString(2, newUser.email) statement.setString(3, newUser.passwordHash) statement.setString(4, newUser.salt) val rs = try { statement.executeQuery() } catch (ex: PSQLException) { throw if (ex.sqlState == PSQLState.UNIQUE_VIOLATION.state) { TaskAppException(ErrorCodes.EMAIL_ALREADY_IN_USE) } else { ex } } while (rs.next()) { val id = rs.getInt("id") return User(id, newUser.name, newUser.email, newUser.passwordHash, newUser.salt) } throw TaskAppException(ErrorCodes.USER_CREATE_FAIL) } override fun delete(id: Int, connection: Connection?) { checkNotNull(connection) { "Connection is need to use DB" } val statement = connection.prepareStatement( "delete from Users where id = ?;" ) statement.setInt(1, id) val count = statement.executeUpdate() if (count == 0) throw TaskAppException(ErrorCodes.USER_DELETE_FAIL) } override fun edit(editUser: EditUserDto, connection: Connection?) { checkNotNull(connection) { "Connection is need to use DB" } val statement = connection.prepareStatement( "update Users set name = ? where id = ?;" ) statement.setString(1, editUser.name) statement.setInt(2, editUser.id) val count = statement.executeUpdate() if (count == 0) throw TaskAppException(ErrorCodes.USER_UPDATE_FAIL) } override fun exists(id: Int, connection: Connection?): Boolean { checkNotNull(connection) { "Connection is need to use DB" } val statement = connection.prepareStatement( "select count(*) exists from Users where id = ?;" ) statement.setInt(1, id) val rs = statement.executeQuery() while (rs.next()) { return rs.getInt("exists") == 1 } return false } }
isel-ls/src/main/kotlin/pt/isel/ls/data/pgsql/PgSqlUsersData.kt
408985644
package pt.isel.ls.data.pgsql import org.postgresql.util.PSQLState import pt.isel.ls.TaskAppException import pt.isel.ls.data.ListsData import pt.isel.ls.data.entities.BoardList import pt.isel.ls.tasksServices.dtos.InputBoardListDto import pt.isel.ls.utils.ErrorCodes import java.sql.Connection import java.sql.SQLException object PgSqlListsData : ListsData { override fun getListsByBoard(boardId: Int, limit: Int, skip: Int, connection: Connection?): List<BoardList> { connection ?: throw IllegalConnException() val statement = connection.prepareStatement( "select l.id , l.name , l.boardId, l.ncards from Lists l join Boards b on l.boardId = b.id where b.id = ? offset ? limit ?;" ) statement.setInt(1, boardId) statement.setInt(2, skip) statement.setInt(3, limit) val rs = statement.executeQuery() val results = mutableListOf<BoardList>() while (rs.next()) { results += BoardList( rs.getInt("id"), rs.getString("name"), rs.getInt("boardId"), rs.getInt("ncards") ) } return results } override fun getById(id: Int, connection: Connection?): BoardList { connection ?: throw IllegalConnException() val statement = connection.prepareStatement( "select * from Lists where id = ?;" ) statement.setInt(1, id) val rs = statement.executeQuery() while (rs.next()) { return BoardList( rs.getInt("id"), rs.getString("name"), rs.getInt("boardId"), rs.getInt("ncards") ) } throw TaskAppException(ErrorCodes.LIST_READ_FAIL) } override fun add(newBoardList: InputBoardListDto, boardId: Int, connection: Connection?): BoardList { connection ?: throw IllegalConnException() val statement = connection.prepareStatement( "insert into Lists (name, boardId,ncards) values (?, ?,?) returning id, name, boardId, ncards;" ) statement.setString(1, newBoardList.name) statement.setInt(2, boardId) statement.setInt(3, 0) val rs = try { statement.executeQuery() } catch (ex: SQLException) { throw if (ex.sqlState == PSQLState.FOREIGN_KEY_VIOLATION.state) { TaskAppException(ErrorCodes.LIST_CREATE_FOREIGN_KEY_FAIL) } else { ex } } while (rs.next()) { val id = rs.getInt("id") val name = rs.getString("name") val bId = rs.getInt("boardId") val ncards = rs.getInt("ncards") return BoardList( id, name, bId, ncards ) } throw TaskAppException(ErrorCodes.LIST_CREATE_FAIL) } override fun delete(id: Int, connection: Connection?) { connection ?: throw IllegalConnException() val statement = connection.prepareStatement( "delete from Lists where id = ?;" ) statement.setInt(1, id) val count = statement.executeUpdate() if (count == 0) throw TaskAppException(ErrorCodes.LIST_DELETE_FAIL) } override fun edit(editName: String, listId: Int, boardId: Int, ncards: Int, connection: Connection?) { connection ?: throw IllegalConnException() val statement = connection.prepareStatement( "update Lists set name = ?,ncards = ? where id = ? and boardid = ?;" ) statement.setString(1, editName) statement.setInt(2, ncards) statement.setInt(3, listId) statement.setInt(4, boardId) val count = statement.executeUpdate() if (count == 0) throw TaskAppException(ErrorCodes.LIST_UPDATE_FAIL) } override fun exists(id: Int, connection: Connection?): Boolean { connection ?: throw IllegalConnException() val statement = connection.prepareStatement( "select count(*) exists from Boards where id = ?;" ) statement.setInt(1, id) val rs = statement.executeQuery() while (rs.next()) { return rs.getInt("exists") == 1 } return false } }
isel-ls/src/main/kotlin/pt/isel/ls/data/pgsql/PgSqlListsData.kt
1184716665
package pt.isel.ls.data.pgsql import pt.isel.ls.TaskAppException import pt.isel.ls.utils.ErrorCodes class UnexpectedSQLException(message: String?) : TaskAppException(ErrorCodes.PGSQL_UNEXPECTED, message = message)
isel-ls/src/main/kotlin/pt/isel/ls/data/pgsql/UnexpectedSQLException.kt
1412572624
package pt.isel.ls.data.pgsql import org.postgresql.util.PSQLState import pt.isel.ls.TaskAppException import pt.isel.ls.data.CardsData import pt.isel.ls.data.entities.Board import pt.isel.ls.data.entities.Card import pt.isel.ls.tasksServices.dtos.EditCardDto import pt.isel.ls.tasksServices.dtos.InputCardDto import pt.isel.ls.tasksServices.dtos.InputMoveCardDto import pt.isel.ls.utils.ErrorCodes import java.sql.Connection import java.sql.SQLException import java.sql.Types object PgSqlCardsData : CardsData { override fun getByList(boardId: Int, listId: Int, limit: Int, skip: Int, connection: Connection?): List<Card> { connection ?: throw IllegalConnException() val statement = connection.prepareStatement( "select * from Cards where listId = ? and boardid = ? offset ? limit ?;" ) statement.setInt(1, listId) statement.setInt(2, boardId) statement.setInt(3, skip) statement.setInt(4, limit) val rs = statement.executeQuery() val results = mutableListOf<Card>() while (rs.next()) { results += Card( rs.getInt("id"), rs.getString("name"), rs.getString("description"), rs.getTimestamp("dueDate"), if (rs.getInt("listId") == 0 && rs.wasNull()) null else rs.getInt("listId"), rs.getInt("boardId"), rs.getInt("cidx") ) } return results } override fun getByBoard(board: Board, connection: Connection?): List<Card> { connection ?: throw IllegalConnException() val statement = connection.prepareStatement( "select * from Cards where boardId = ?;" ) statement.setInt(1, board.id) val rs = statement.executeQuery() val results = mutableListOf<Card>() while (rs.next()) { results += Card( rs.getInt("id"), rs.getString("name"), rs.getString("description"), rs.getTimestamp("dueDate"), if (rs.getInt("listId") == 0 && rs.wasNull()) null else rs.getInt("listId"), rs.getInt("boardId"), rs.getInt("cIdx") ) } return results } internal fun getListCount(lid: Int?, boardId: Int, connection: Connection): Int { val statement = connection.prepareStatement("select nCards from lists where id = ? and boardid = ?;") if (lid != null) { statement.setInt(1, lid) } else { statement.setNull(1, Types.INTEGER) } statement.setInt(2, boardId) val rs = statement.executeQuery() while (rs.next()) { return rs.getInt("nCards") } throw TaskAppException(ErrorCodes.LIST_READ_FAIL) } internal fun getCardInfo(cardId: Int, connection: Connection): Card { val statement = connection.prepareStatement("select * from cards where id = ?;") statement.setInt(1, cardId) val rs = statement.executeQuery() while (rs.next()) { return Card( rs.getInt("id"), rs.getString("name"), rs.getString("description"), rs.getTimestamp("dueDate"), if (rs.getInt("listId") == 0 && rs.wasNull()) null else rs.getInt("listId"), rs.getInt("boardId"), rs.getInt("cidx") ) } throw TaskAppException(ErrorCodes.CARD_READ_FAIL) } private fun updateCardLid(cardId: Int, lid: Int, bid: Int, connection: Connection) { val statement = connection.prepareStatement( "update Cards set listid = ? where id = ? and boardid = ?;" ) /* * update whatever set pos = pos + 1 where pos between 2 and 3; * update whatever set pos = 2 where id = 4;*/ statement.setInt(1, lid) statement.setInt(2, cardId) statement.setInt(3, bid) val count = statement.executeUpdate() if (count == 0) throw TaskAppException(ErrorCodes.CARD_UPDATE_FAIL) } private fun updateCardIdx(cardId: Int, cIdx: Int, bid: Int, connection: Connection) { val statement = connection.prepareStatement( "update Cards set cIdx = ? where id = ? and boardid = ?;" ) /* * update whatever set pos = pos + 1 where pos between 2 and 3; * update whatever set pos = 2 where id = 4;*/ statement.setInt(1, cIdx) statement.setInt(2, cardId) statement.setInt(3, bid) val count = statement.executeUpdate() if (count == 0) throw TaskAppException(ErrorCodes.CARD_UPDATE_FAIL) } private fun updateList(updatedCards: List<Card>, connection: Connection) { val sql = "UPDATE Cards SET cIdx = ?, listid = ? WHERE id = ?" val statement = connection.prepareStatement(sql) for (card in updatedCards) { statement.setInt(1, card.cIdx) if (card.listId != null) { statement.setInt(2, card.listId) } else { statement.setNull(2, Types.INTEGER) } statement.setInt(3, card.id) statement.executeUpdate() } statement.close() } override fun move(inputList: InputMoveCardDto, boardId: Int, cardId: Int, connection: Connection?) { connection ?: throw IllegalConnException() val cardInfo = getCardInfo(cardId, connection) if (inputList.cix < 0) throw TaskAppException(ErrorCodes.CARD_MOVE_NEGATIVE) val cardOldPosition = cardInfo.cIdx val newPosition = inputList.cix val startIndex = minOf(cardOldPosition, newPosition) val endIndex = maxOf(cardOldPosition, newPosition) if (inputList.lid == cardInfo.listId) { if (newPosition == cardOldPosition) return val oldListOfCards = getByList(boardId, cardInfo.listId, connection = connection) val updatedCards = oldListOfCards.toMutableList() updatedCards[updatedCards.indexOf(cardInfo)] = cardInfo.copy(cIdx = newPosition) val cardWithSamePosition = oldListOfCards.find { it.cIdx == newPosition } if (cardWithSamePosition != null) { if (newPosition > cardOldPosition) { updatedCards[updatedCards.indexOf(cardWithSamePosition)] = cardWithSamePosition.copy(cIdx = newPosition - 1) } else { updatedCards[updatedCards.indexOf(cardWithSamePosition)] = cardWithSamePosition.copy(cIdx = newPosition + 1) } } updatedCards.sortBy { it.cIdx } for (i in startIndex..endIndex) { val obj = updatedCards[i] updatedCards[i] = obj.copy(cIdx = i) } updateList(updatedCards, connection) } else { if (cardInfo.listId != null) { // delete(cardInfo.id,connection) val updatedCards = getByList(boardId, cardInfo.listId, connection = connection).toMutableList() updatedCards.remove(cardInfo) updatedCards.sortBy { it.cIdx } if ((updatedCards.size != 0) and (newPosition != updatedCards.size - 1)) { for (i in startIndex..endIndex) { val obj = updatedCards[i] updatedCards[i] = obj.copy(cIdx = i) } updateList(updatedCards, connection) } } val oldListOfCardsNewList = getByList(boardId, inputList.lid, connection = connection) val updatedCardsNewList = oldListOfCardsNewList.toMutableList() val cardWithSamePosition = oldListOfCardsNewList.find { it.cIdx == newPosition } if (newPosition <= updatedCardsNewList.size) { updatedCardsNewList.add(cardInfo.copy(listId = inputList.lid, cIdx = newPosition)) if (cardWithSamePosition != null) { updatedCardsNewList[updatedCardsNewList.indexOf(cardWithSamePosition)] = cardWithSamePosition.copy(cIdx = newPosition + 1) } updatedCardsNewList.sortBy { it.cIdx } if ((updatedCardsNewList.size != 0) and (newPosition != updatedCardsNewList.size - 1)) { for (i in newPosition until updatedCardsNewList.size) { val obj = updatedCardsNewList[i] updatedCardsNewList[i] = obj.copy(cIdx = i) } } } else { updatedCardsNewList.add(cardInfo.copy(listId = inputList.lid, cIdx = newPosition)) } updateList(updatedCardsNewList, connection) } } override fun getById(id: Int, connection: Connection?): Card { connection ?: throw IllegalConnException() return getCardInfo(id, connection) } private fun changeCardCount(id: Int, connection: Connection, delta: Int = 1) { val statement = connection.prepareStatement( "update Lists set nCards = nCards + 1 * ? where id = ?;" ) statement.setInt(1, delta) statement.setInt(2, id) statement.executeUpdate() } override fun add(newCard: InputCardDto, boardId: Int, listId: Int?, connection: Connection?): Card { connection ?: throw IllegalConnException() val statement = if (listId != null) { connection.prepareStatement( "insert into Cards (name, description, dueDate, listId, boardId, cidx) values (?, ?, ?, ?, ?, (select l.nCards from lists l where l.id = ? and l.boardid = ?)) returning id, name, description, dueDate, listId, boardId, cidx;" ) } else { connection.prepareStatement( "insert into Cards (name, description, dueDate, listId, boardId, cidx) values (?, ?, ?, ?, ?, -1) returning id, name, description, dueDate, listId, boardId, cidx;" ) } statement.setString(1, newCard.name) statement.setString(2, newCard.description) if (newCard.dueDate == null) { statement.setNull(3, Types.TIMESTAMP) } else { statement.setTimestamp(3, newCard.dueDate) } if (listId != null) { statement.setInt(4, listId) statement.setInt(6, listId) statement.setInt(7, boardId) } else { statement.setNull(4, Types.INTEGER) } statement.setInt(5, boardId) val rs = try { statement.executeQuery() } catch (ex: SQLException) { throw if (ex.sqlState == PSQLState.FOREIGN_KEY_VIOLATION.state) { TaskAppException(ErrorCodes.CARD_CREATE_FOREIGN_KEY_FAIL) } else { ex } } if (listId != null) changeCardCount(listId, connection) while (rs.next()) { val id = rs.getInt("id") val name = rs.getString("name") val description = rs.getString("description") val dueDate = rs.getTimestamp("dueDate") val lId = if (rs.getInt("listId") == 0 && rs.wasNull()) null else rs.getInt("listId") val bId = rs.getInt("boardId") val cIdx = rs.getInt("cidx") return Card( id, name, description, dueDate, lId, bId, cIdx ) } throw TaskAppException(ErrorCodes.CARD_CREATE_FAIL) } override fun delete(id: Int, connection: Connection?) { connection ?: throw IllegalConnException() val statement = connection.prepareStatement( "delete from Cards where id = ?;" ) statement.setInt(1, id) val count = statement.executeUpdate() if (count == 0) throw TaskAppException(ErrorCodes.CARD_DELETE_FAIL) } override fun edit(editCardDto: EditCardDto, boardId: Int, cardId: Int, connection: Connection?) { connection ?: throw IllegalConnException() val statement = connection.prepareStatement( "update Cards set name = ? where id = ?;" + "update Cards set description = ? where id = ?;" + "update Cards set dueDate = ? where id = ?;" ) statement.setString(1, editCardDto.name) statement.setString(3, editCardDto.description) if (editCardDto.dueDate == null) { statement.setNull(5, Types.TIMESTAMP) } else { statement.setTimestamp(5, editCardDto.dueDate) } statement.setInt(2, cardId) statement.setInt(4, cardId) statement.setInt(6, cardId) statement.setInt(8, cardId) val count = statement.executeUpdate() if (count == 0) throw TaskAppException(ErrorCodes.CARD_UPDATE_FAIL) } override fun exists(id: Int, connection: Connection?): Boolean { connection ?: throw IllegalConnException() val statement = connection.prepareStatement( "select count(*) exists from Cards where id = ?;" ) statement.setInt(1, id) val rs = statement.executeQuery() while (rs.next()) { return rs.getInt("exists") == 1 } return false } }
isel-ls/src/main/kotlin/pt/isel/ls/data/pgsql/PgSqlCardsData.kt
712297128
package pt.isel.ls.data import pt.isel.ls.data.entities.Board import pt.isel.ls.data.entities.Card import pt.isel.ls.tasksServices.dtos.EditCardDto import pt.isel.ls.tasksServices.dtos.InputCardDto import pt.isel.ls.tasksServices.dtos.InputMoveCardDto import java.sql.Connection interface CardsData : Data<Card> { fun getByList(boardId: Int, listId: Int, limit: Int = 25, skip: Int = 0, connection: Connection? = null): List<Card> fun add(newCard: InputCardDto, boardId: Int, listId: Int?, connection: Connection? = null): Card fun edit(editCardDto: EditCardDto, boardId: Int, cardId: Int, connection: Connection? = null) fun getByBoard(board: Board, connection: Connection? = null): List<Card> fun move(inputList: InputMoveCardDto, boardId: Int, cardId: Int, connection: Connection? = null) }
isel-ls/src/main/kotlin/pt/isel/ls/data/CardsData.kt
3393265679
package pt.isel.ls.data.entities import java.sql.Timestamp import java.util.UUID data class UserToken( val token: UUID, val userId: Int, val creationDate: Timestamp )
isel-ls/src/main/kotlin/pt/isel/ls/data/entities/UserToken.kt
437105812
package pt.isel.ls.data.entities import kotlinx.serialization.Serializable @Serializable sealed interface Entity { val id: Int fun clone(id: Int): Entity }
isel-ls/src/main/kotlin/pt/isel/ls/data/entities/Entity.kt
2938283913
package pt.isel.ls.data.entities import kotlinx.serialization.Serializable import pt.isel.ls.data.utils.TimestampAsLongSerializer import java.sql.Timestamp @Serializable data class Card( override val id: Int, val name: String, val description: String, @Serializable(with = TimestampAsLongSerializer::class) val dueDate: Timestamp?, val listId: Int?, val boardId: Int, val cIdx: Int ) : Entity { override fun clone(id: Int): Card = this.copy(id = id) }
isel-ls/src/main/kotlin/pt/isel/ls/data/entities/Card.kt
122213832
package pt.isel.ls.data.entities data class UserBoard( val userId: Int, val boardId: Int )
isel-ls/src/main/kotlin/pt/isel/ls/data/entities/UserBoard.kt
4069142678
package pt.isel.ls.data.entities import kotlinx.serialization.Serializable @Serializable data class Board( override val id: Int, var name: String, var description: String ) : Entity { override fun clone(id: Int): Board = this.copy(id = id) }
isel-ls/src/main/kotlin/pt/isel/ls/data/entities/Board.kt
1463970917
package pt.isel.ls.data.entities import kotlinx.serialization.Serializable @Serializable data class User( override val id: Int, var name: String, var email: String, val passwordHash: String, val salt: String ) : Entity { override fun clone(id: Int): User = copy(id = id) }
isel-ls/src/main/kotlin/pt/isel/ls/data/entities/User.kt
3580110440
package pt.isel.ls.data.entities import kotlinx.serialization.Serializable @Serializable data class BoardList( override val id: Int, var name: String, val boardId: Int, var ncards: Int ) : Entity { override fun clone(id: Int): BoardList = this.copy(id = id) }
isel-ls/src/main/kotlin/pt/isel/ls/data/entities/BoardList.kt
3364194567
package pt.isel.ls.data.mem import pt.isel.ls.TaskAppException import pt.isel.ls.data.ListsData import pt.isel.ls.data.entities.BoardList import pt.isel.ls.tasksServices.dtos.InputBoardListDto import pt.isel.ls.utils.ErrorCodes import java.sql.Connection object MemListsData : ListsData { private val CASCADE_DELETE = true override fun getListsByBoard(boardId: Int, limit: Int, skip: Int, connection: Connection?): List<BoardList> { val lists = MemDataSource.lists.filter { it.boardId == boardId } if (skip > lists.lastIndex) return emptyList() return lists.subList( skip, if (skip + limit <= lists.lastIndex) skip + limit else lists.lastIndex + 1 ) } override fun edit(editName: String, listId: Int, boardId: Int, ncards: Int, connection: Connection?) { val oldList = MemDataSource.lists.firstOrNull { it.id == listId && it.boardId == boardId } ?: throw TaskAppException(ErrorCodes.LIST_UPDATE_FAIL) val newList = BoardList(oldList.id, editName, oldList.boardId, ncards) MemDataSource.lists.remove(oldList) MemDataSource.lists.add(newList) } override fun add(newBoardList: InputBoardListDto, boardId: Int, connection: Connection?): BoardList { if (!MemDataSource.boards.any { it.id == boardId }) { throw TaskAppException(ErrorCodes.BOARD_READ_FAIL) } val newId = if (MemDataSource.lists.isEmpty()) 1 else MemDataSource.lists.maxOf { it.id } + 1 val list = BoardList(newId, newBoardList.name, boardId, 0) MemDataSource.lists.add(list) return list } override fun getById(id: Int, connection: Connection?): BoardList = MemDataSource.lists.firstOrNull { it.id == id } ?: throw TaskAppException(ErrorCodes.LIST_READ_FAIL) override fun delete(id: Int, connection: Connection?) { val list = MemDataSource.lists.firstOrNull { it.id == id } ?: throw TaskAppException(ErrorCodes.LIST_READ_FAIL) if (MemDataSource.cards.any { it.listId == id }) { if (CASCADE_DELETE) { MemDataSource.cards.removeAll { it.listId == id } } else { // Should never happen due to cascade being used in live, thus doesn't have a specific code throw TaskAppException(message = "Cannot delete a list that has cards.") } } MemDataSource.lists.remove(list) } override fun exists(id: Int, connection: Connection?): Boolean = MemDataSource.lists.any { it.id == id } }
isel-ls/src/main/kotlin/pt/isel/ls/data/mem/MemListsData.kt
2451150196
package pt.isel.ls.data.mem import pt.isel.ls.TaskAppException import pt.isel.ls.data.CardsData import pt.isel.ls.data.entities.Board import pt.isel.ls.data.entities.Card import pt.isel.ls.tasksServices.dtos.EditCardDto import pt.isel.ls.tasksServices.dtos.InputCardDto import pt.isel.ls.tasksServices.dtos.InputMoveCardDto import pt.isel.ls.utils.ErrorCodes import java.sql.Connection object MemCardsData : CardsData { override fun getByList(boardId: Int, listId: Int, limit: Int, skip: Int, connection: Connection?): List<Card> { val cards = MemDataSource.cards.filter { it.listId == listId && it.boardId == boardId } if (skip > cards.lastIndex) return emptyList() return cards.subList( skip, if (skip + limit <= cards.lastIndex) skip + limit else cards.lastIndex + 1 ) } override fun add(newCard: InputCardDto, boardId: Int, listId: Int?, connection: Connection?): Card { if (!MemDataSource.boards.any { it.id == boardId }) { throw TaskAppException(ErrorCodes.BOARD_READ_FAIL) } if (listId != null) { if (!MemDataSource.lists.any { it.id == listId }) { throw TaskAppException(ErrorCodes.LIST_READ_FAIL) } } val newId = if (MemDataSource.cards.isEmpty()) 1 else MemDataSource.cards.maxOf { it.id } + 1 val ts = newCard.dueDate val card = Card( newId, newCard.name, newCard.description, ts, listId, boardId, 0 ) MemDataSource.cards.add(card) return card } override fun edit(editCardDto: EditCardDto, boardId: Int, cardId: Int, connection: Connection?) { val oldCard = MemDataSource.cards.firstOrNull { it.id == cardId } ?: throw TaskAppException(ErrorCodes.CARD_READ_FAIL) val newCard = Card( oldCard.id, editCardDto.name, editCardDto.description, editCardDto.dueDate ?: oldCard.dueDate, oldCard.listId, boardId, 0 ) MemDataSource.cards.remove(oldCard) MemDataSource.cards.add(newCard) } override fun getByBoard(board: Board, connection: Connection?): List<Card> = MemDataSource.cards.filter { it.boardId == board.id } override fun move(inputList: InputMoveCardDto, boardId: Int, cardId: Int, connection: Connection?) { if (inputList.cix < 0) throw TaskAppException(ErrorCodes.CARD_MOVE_NEGATIVE) val oldCard = MemDataSource.cards.firstOrNull { it.id == cardId && it.boardId == boardId } ?: throw TaskAppException(ErrorCodes.CARD_READ_FAIL) val newCard = oldCard.copy(listId = inputList.lid) MemDataSource.cards.remove(oldCard) MemDataSource.cards.add(newCard) } override fun getById(id: Int, connection: Connection?): Card = MemDataSource.cards.firstOrNull { it.id == id } ?: throw TaskAppException(ErrorCodes.CARD_READ_FAIL) override fun delete(id: Int, connection: Connection?) { val card = MemDataSource.cards.firstOrNull { it.id == id } ?: throw TaskAppException(ErrorCodes.CARD_READ_FAIL) MemDataSource.cards.remove(card) } override fun exists(id: Int, connection: Connection?): Boolean = MemDataSource.cards.any { it.id == id } }
isel-ls/src/main/kotlin/pt/isel/ls/data/mem/MemCardsData.kt
3948191987