path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
leetcode-kotlin/{{cookiecutter.slug}}/src/test/kotlin/solution/SolutionTest.kt | petr-korobeinikov | 675,327,458 | false | null | package solution
import kotlin.test.Test
import kotlin.test.assertTrue
class SolutionTest {
@Test
fun solution() {
val classUnderTest = Solution()
assertTrue(classUnderTest.solution(), "someLibraryMethod should return 'true'")
}
}
| 0 | Kotlin | 0 | 0 | edfc5cada3fd4e419f8b8911abd9a403e5119d01 | 247 | cookiecutters | MIT License |
ij/src/main/kotlin/org/jetbrains/academy/test/system/ij/formatting/FormattingUtil.kt | jetbrains-academy | 632,174,674 | false | null | @file:Suppress("ForbiddenComment")
package org.jetbrains.academy.test.system.ij.formatting
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.psi.PsiFile
import com.intellij.psi.codeStyle.CodeStyleManager
import org.junit.jupiter.api.Assertions
// TODO: make it possible to check different aspects of formatting
fun PsiFile.checkIfFormattingRulesWereApplied() {
val originalCode = ApplicationManager.getApplication().runReadAction<String> { text }
val codeStyleManager = CodeStyleManager.getInstance(project)
WriteCommandAction.runWriteCommandAction(project) {
codeStyleManager.reformat(this)
}
val formattedCode = ApplicationManager.getApplication().runReadAction<String> { text }
Assertions.assertEquals(
originalCode.trimIndent(),
formattedCode.trimIndent(),
"The code after formatting should be:${System.lineSeparator()}$formattedCode${System.lineSeparator()}Please, apply code formatting refactoring to the code."
)
}
fun PsiFile.formatting(): String? {
val codeStyleManager = CodeStyleManager.getInstance(project)
WriteCommandAction.runWriteCommandAction(project) {
codeStyleManager.reformat(this)
}
return ApplicationManager.getApplication().runReadAction<String> { text }
}
| 1 | Kotlin | 0 | 0 | f852ad145edaeb67c27da58a0222d2d9950e9a70 | 1,353 | kotlin-test-framework | MIT License |
engine/camunda-engine-client/src/main/kotlin/CamundaEngineClientConfiguration.kt | lbilger | 250,224,382 | true | {"Kotlin": 435719} | package io.holunda.camunda.client
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration
@Configuration
@ComponentScan
class CamundaEngineClientConfiguration
| 0 | null | 0 | 0 | 7a6e818e74debe3d9c4f285c841202c73673c0a3 | 226 | camunda-bpm-taskpool | Apache License 2.0 |
app-compose/src/main/kotlin/com/ave/vastgui/appcompose/example/informationget/AppInfo.kt | SakurajimaMaii | 353,212,367 | false | null | /*
* Copyright 2022 VastGui [email protected]
*
* 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.ave.vastgui.appcompose.example.informationget
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.ListItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.unit.dp
import com.ave.vastgui.tools.utils.AppUtils
// Author: Vast Gui
// Email: [email protected]
// Date: 2023/5/31
// Documentation: https://ave.entropy2020.cn/documents/VastTools/core-topics/information-get/app-utils/
@Composable
fun AppInfo() {
val appInfo = mapOf(
"getPackageName" to AppUtils.getPackageName(),
"getAppName" to AppUtils.getAppName(),
"getVersionName" to AppUtils.getVersionName(),
"getVersionCode" to AppUtils.getVersionCode().toString(),
"getAppDebug" to AppUtils.getAppDebug().toString()
).toList()
Column {
Text(
text = "Function name: getAppBitmap",
modifier = Modifier.padding(15.dp)
)
Image(
bitmap = AppUtils.getAppBitmap().asImageBitmap(),
contentDescription = null,
modifier = Modifier.padding(15.dp)
)
LazyColumn(modifier = Modifier.fillMaxSize()) {
items(appInfo) { item ->
ListItem(
headlineContent = {
Text(text = "Function name: ${item.first}")
},
supportingContent = {
Text(text = item.second)
}
)
}
}
}
} | 8 | null | 7 | 64 | 81c5ca59680143d9523c01852d9587a8d926c1c3 | 2,495 | Android-Vast-Extension | Apache License 2.0 |
idea/src/org/jetbrains/jet/plugin/intentions/MakeTypeExplicitInLambdaIntention.kt | chashnikov | 14,658,474 | false | null | /*
* Copyright 2010-2014 JetBrains s.r.o.
*
* 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 org.jetbrains.jet.plugin.intentions
import org.jetbrains.jet.lang.psi.JetFunctionLiteralExpression
import com.intellij.openapi.editor.Editor
import org.jetbrains.jet.plugin.project.AnalyzerFacadeWithCache
import org.jetbrains.jet.lang.resolve.BindingContext
import org.jetbrains.jet.renderer.DescriptorRenderer
import org.jetbrains.jet.lang.types.ErrorUtils
import org.jetbrains.jet.lang.psi.JetPsiFactory
import com.intellij.psi.PsiWhiteSpace
import org.jetbrains.jet.plugin.codeInsight.ShortenReferences
public class MakeTypeExplicitInLambdaIntention : JetSelfTargetingIntention<JetFunctionLiteralExpression>(
"make.type.explicit.in.lambda", javaClass()) {
override fun isApplicableTo(element: JetFunctionLiteralExpression): Boolean {
throw IllegalStateException("isApplicableTo(JetExpressionImpl, Editor) should be called instead")
}
override fun isApplicableTo(element: JetFunctionLiteralExpression, editor: Editor): Boolean {
val openBraceOffset = element.getLeftCurlyBrace().getStartOffset()
val closeBraceOffset = element.getRightCurlyBrace()?.getStartOffset()
val caretLocation = editor.getCaretModel().getOffset()
val arrow = element.getFunctionLiteral().getArrowNode()
if (arrow != null && !(openBraceOffset < caretLocation && caretLocation < arrow.getStartOffset() + 2) &&
caretLocation != closeBraceOffset) return false
else if (arrow == null && caretLocation != openBraceOffset + 1 && caretLocation != closeBraceOffset) return false
val context = AnalyzerFacadeWithCache.getContextForElement(element)
val func = context[BindingContext.FUNCTION, element.getFunctionLiteral()]
if (func == null || ErrorUtils.containsErrorType(func)) return false
if (hasImplicitReturnType(element) && func.getReturnType() != null) return true
if (hasImplicitReceiverType(element) && func.getReceiverParameter()?.getType() != null) return true
val params = element.getValueParameters()
return params.any { it.getTypeReference() == null }
}
override fun applyTo(element: JetFunctionLiteralExpression, editor: Editor) {
val functionLiteral = element.getFunctionLiteral()
val context = AnalyzerFacadeWithCache.getContextForElement(element)
val func = context[BindingContext.FUNCTION, functionLiteral]!!
// Step 1: make the parameters types explicit
val valueParameters = func.getValueParameters()
val parameterString = valueParameters.map({descriptor -> "" + descriptor.getName() +
": " + DescriptorRenderer.SOURCE_CODE.renderType(descriptor.getType())
}).makeString(", ", "(", ")")
val psiFactory = JetPsiFactory(element)
val newParameterList = psiFactory.createParameterList(parameterString)
val oldParameterList = functionLiteral.getValueParameterList()
if (oldParameterList != null) {
oldParameterList.replace(newParameterList)
}
else {
val openBraceElement = functionLiteral.getOpenBraceNode().getPsi()
val nextSibling = openBraceElement?.getNextSibling()
val addNewline = nextSibling is PsiWhiteSpace && nextSibling.getText()?.contains("\n") ?: false
val (whitespace, arrow) = psiFactory.createWhitespaceAndArrow()
functionLiteral.addRangeAfter(whitespace, arrow, openBraceElement)
functionLiteral.addAfter(newParameterList, openBraceElement)
if (addNewline) {
functionLiteral.addAfter(psiFactory.createNewLine(), openBraceElement)
}
}
ShortenReferences.process(element.getValueParameters())
// Step 2: make the return type explicit
val expectedReturnType = func.getReturnType()
if (hasImplicitReturnType(element) && expectedReturnType != null) {
val paramList = functionLiteral.getValueParameterList()
val returnTypeColon = psiFactory.createColon()
val returnTypeExpr = psiFactory.createType(DescriptorRenderer.SOURCE_CODE.renderType(expectedReturnType))
functionLiteral.addAfter(returnTypeExpr, paramList)
functionLiteral.addAfter(returnTypeColon, paramList)
ShortenReferences.process(functionLiteral.getReturnTypeRef()!!)
}
// Step 3: make the receiver type explicit
val expectedReceiverType = func.getReceiverParameter()?.getType()
if (hasImplicitReceiverType(element) && expectedReceiverType != null) {
val receiverTypeString = DescriptorRenderer.SOURCE_CODE.renderType(expectedReceiverType)
val dot = functionLiteral.addBefore(psiFactory.createDot(), functionLiteral.getValueParameterList())
functionLiteral.addBefore(psiFactory.createType(receiverTypeString), dot)
ShortenReferences.process(functionLiteral.getReceiverTypeRef()!!)
}
}
private fun hasImplicitReturnType(element: JetFunctionLiteralExpression): Boolean {
return !element.hasDeclaredReturnType()
}
private fun hasImplicitReceiverType(element: JetFunctionLiteralExpression): Boolean {
return element.getFunctionLiteral().getReceiverTypeRef() == null
}
} | 1 | null | 1 | 1 | 88a261234860ff0014e3c2dd8e64072c685d442d | 5,953 | kotlin | Apache License 2.0 |
android/src/main/kotlin/com/notifierlistener/notifier_listener/NotificationListener.kt | zetsu01 | 366,304,374 | false | null | package com.emilecode.android_notification_listener2
import android.app.Notification
import android.content.Intent
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import org.json.JSONException
import org.json.JSONObject
import android.os.Bundle
import android.util.Log
/**
* Notification listening service. Intercepts notifications if permission is given to do so.
*/
class NotificationListener : NotificationListenerService() {
override fun onNotificationPosted(sbn: StatusBarNotification) {
try
{
// Retrieve package name to set as title.
val packageName = sbn.packageName
// Retrieve extra object from notification to extract payload.
val extras = sbn.notification.extras
val packageMessage = extras?.getCharSequence(Notification.EXTRA_TEXT).toString()
val packageText = extras?.getCharSequence("android.title").toString()
val packageExtra = convertBumbleToJsonString(sbn.notification.extras)
var category = "no-category-notification"
if(sbn.notification.category != "null")
{
category = sbn.notification.category
}
// Pass data from one activity to another.
val intent = Intent(NOTIFICATION_INTENT)
intent.putExtra(NOTIFICATION_PACKAGE_NAME, packageName)
intent.putExtra(NOTIFICATION_PACKAGE_MESSAGE, packageMessage)
intent.putExtra(NOTIFICATION_PACKAGE_TEXT, packageText)
intent.putExtra(NOTIFICATION_PACKAGE_EXTRA, packageExtra)
intent.putExtra(NOTIFICATION_PACKAGE_CATEGORY,category)
sendBroadcast(intent)
}
catch (error :Exception ){
Log.w( "Crashing aborded ", "An exception occured, I do not know yet what causes that error\nIt seams that a bundle is null on a notification received or it is just a bug\nIf you did not receive the notification please raise a complain on my github" );
}
}
companion object {
const val NOTIFICATION_INTENT = "notification_event"
const val NOTIFICATION_PACKAGE_NAME = "package_name"
const val NOTIFICATION_PACKAGE_MESSAGE = "package_message"
const val NOTIFICATION_PACKAGE_TEXT = "package_text";
const val NOTIFICATION_PACKAGE_EXTRA = "package_extra";
const val NOTIFICATION_PACKAGE_CATEGORY = "category";
}
private fun convertBumbleToJsonString(extra: Bundle): String {
val json = JSONObject()
val keys = extra.keySet()
for (key in keys) {
try {
json.put(key, JSONObject.wrap(extra.get(key)))
} catch (e: JSONException) {
//Handle exception here
}
}
return json.toString()
}
} | 7 | null | 13 | 2 | d827073026e62a113ff04a888f0a641763252567 | 2,830 | flutter_androidnotificationlistener_plugin | MIT License |
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/quicksight/CfnTemplateWordCloudVisualPropertyDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.quicksight
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.Any
import kotlin.String
import kotlin.collections.Collection
import kotlin.collections.MutableList
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.quicksight.CfnTemplate
/**
* A word cloud.
*
* For more information, see [Using word
* clouds](https://docs.aws.amazon.com/quicksight/latest/user/word-cloud.html) in the *Amazon
* QuickSight User Guide* .
*
* Example:
*
* ```
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-quicksight-template-wordcloudvisual.html)
*/
@CdkDslMarker
public class CfnTemplateWordCloudVisualPropertyDsl {
private val cdkBuilder: CfnTemplate.WordCloudVisualProperty.Builder =
CfnTemplate.WordCloudVisualProperty.builder()
private val _actions: MutableList<Any> = mutableListOf()
private val _columnHierarchies: MutableList<Any> = mutableListOf()
/**
* @param actions The list of custom actions that are configured for a visual.
*/
public fun actions(vararg actions: Any) {
_actions.addAll(listOf(*actions))
}
/**
* @param actions The list of custom actions that are configured for a visual.
*/
public fun actions(actions: Collection<Any>) {
_actions.addAll(actions)
}
/**
* @param actions The list of custom actions that are configured for a visual.
*/
public fun actions(actions: IResolvable) {
cdkBuilder.actions(actions)
}
/**
* @param chartConfiguration The configuration settings of the visual.
*/
public fun chartConfiguration(chartConfiguration: IResolvable) {
cdkBuilder.chartConfiguration(chartConfiguration)
}
/**
* @param chartConfiguration The configuration settings of the visual.
*/
public
fun chartConfiguration(chartConfiguration: CfnTemplate.WordCloudChartConfigurationProperty) {
cdkBuilder.chartConfiguration(chartConfiguration)
}
/**
* @param columnHierarchies The column hierarchy that is used during drill-downs and drill-ups.
*/
public fun columnHierarchies(vararg columnHierarchies: Any) {
_columnHierarchies.addAll(listOf(*columnHierarchies))
}
/**
* @param columnHierarchies The column hierarchy that is used during drill-downs and drill-ups.
*/
public fun columnHierarchies(columnHierarchies: Collection<Any>) {
_columnHierarchies.addAll(columnHierarchies)
}
/**
* @param columnHierarchies The column hierarchy that is used during drill-downs and drill-ups.
*/
public fun columnHierarchies(columnHierarchies: IResolvable) {
cdkBuilder.columnHierarchies(columnHierarchies)
}
/**
* @param subtitle The subtitle that is displayed on the visual.
*/
public fun subtitle(subtitle: IResolvable) {
cdkBuilder.subtitle(subtitle)
}
/**
* @param subtitle The subtitle that is displayed on the visual.
*/
public fun subtitle(subtitle: CfnTemplate.VisualSubtitleLabelOptionsProperty) {
cdkBuilder.subtitle(subtitle)
}
/**
* @param title The title that is displayed on the visual.
*/
public fun title(title: IResolvable) {
cdkBuilder.title(title)
}
/**
* @param title The title that is displayed on the visual.
*/
public fun title(title: CfnTemplate.VisualTitleLabelOptionsProperty) {
cdkBuilder.title(title)
}
/**
* @param visualId The unique identifier of a visual.
* This identifier must be unique within the context of a dashboard, template, or analysis. Two
* dashboards, analyses, or templates can have visuals with the same identifiers..
*/
public fun visualId(visualId: String) {
cdkBuilder.visualId(visualId)
}
public fun build(): CfnTemplate.WordCloudVisualProperty {
if(_actions.isNotEmpty()) cdkBuilder.actions(_actions)
if(_columnHierarchies.isNotEmpty()) cdkBuilder.columnHierarchies(_columnHierarchies)
return cdkBuilder.build()
}
}
| 1 | Kotlin | 0 | 0 | 17c41bdaffb2e10d31b32eb2282b73dd18be09fa | 4,143 | awscdk-dsl-kotlin | Apache License 2.0 |
app/src/main/java/de/berlindroid/zeaapp/emails/EmailAdapter.kt | gdg-berlin-android | 194,500,509 | false | {"Java": 87997, "Kotlin": 48857, "GLSL": 8098, "HTML": 678} | package de.berlindroid.zeaapp.emails
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.navigation.findNavController
import androidx.navigation.fragment.FragmentNavigatorExtras
import androidx.recyclerview.widget.RecyclerView
import de.berlindroid.zeaapp.R
import kotlinx.android.synthetic.main.email_item.view.*
class EmailAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return EmailViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.email_item, parent, false))
}
override fun getItemCount() = 20
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is EmailViewHolder) {
val text = "Email $position"
holder.email.text = text
holder.itemView.transitionName = text
holder.itemView.setOnClickListener {
val args = FragmentNavigatorExtras(
holder.itemView to text
)
val bundle = bundleOf(
"email" to text
)
it.findNavController().navigate(R.id.action_emailFragments_to_details, bundle, null, args)
}
}
}
inner class EmailViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
val email = itemView.email!!
}
} | 4 | Java | 1 | 6 | 9f8ad45717faeab0eaa461eb2ae164667619dbaa | 1,508 | ze-appp | Apache License 2.0 |
lib/src/main/kotlin/com/dbflow5/database/DatabaseHelper.kt | agrosner | 24,161,015 | false | null | package com.dbflow5.database
import com.dbflow5.adapter.createIfNotExists
import com.dbflow5.config.DBFlowDatabase
import com.dbflow5.config.FlowLog
import com.dbflow5.config.NaturalOrderComparator
import java.io.IOException
/**
* Description: Manages creation, updating, and migrating ac [DBFlowDatabase]. It performs View creations.
*/
open class DatabaseHelper(private val migrationFileHelper: MigrationFileHelper,
val databaseDefinition: DBFlowDatabase) {
// path to migration for the database.
private val dbMigrationPath
get() = "$MIGRATION_PATH/${databaseDefinition.databaseName}"
open fun onConfigure(db: DatabaseWrapper) {
checkForeignKeySupport(db)
}
open fun onCreate(db: DatabaseWrapper) {
// table creations done first to get tables in db.
executeTableCreations(db)
// execute any initial migrations when DB is first created.
// use the databaseversion of the definition, since onupgrade is not called oncreate on a version 0
// then SQLCipher and Android set the DB to that version you choose.
executeMigrations(db, -1, databaseDefinition.databaseVersion)
// views reflect current db state.
executeViewCreations(db)
}
open fun onUpgrade(db: DatabaseWrapper, oldVersion: Int, newVersion: Int) {
// create new tables if not previously created
executeTableCreations(db)
// migrations run to get to DB newest version. adjusting any existing tables to new version
executeMigrations(db, oldVersion, newVersion)
// views reflect current db state.
executeViewCreations(db)
}
open fun onOpen(db: DatabaseWrapper) {
}
open fun onDowngrade(db: DatabaseWrapper, oldVersion: Int, newVersion: Int) {
}
/**
* If foreign keys are supported, we turn it on the DB specified.
*/
protected fun checkForeignKeySupport(database: DatabaseWrapper) {
if (databaseDefinition.isForeignKeysSupported) {
database.execSQL("PRAGMA foreign_keys=ON;")
FlowLog.log(FlowLog.Level.I, "Foreign Keys supported. Enabling foreign key features.")
}
}
protected fun executeTableCreations(database: DatabaseWrapper) {
database.executeTransaction {
databaseDefinition.modelAdapters
.asSequence()
.filter { it.createWithDatabase() }
.forEach {
try {
it.createIfNotExists(this)
} catch (e: SQLiteException) {
FlowLog.logError(e)
}
}
}
}
/**
* This method executes CREATE TABLE statements as well as CREATE VIEW on the database passed.
*/
protected fun executeViewCreations(database: DatabaseWrapper) {
database.executeTransaction {
databaseDefinition.modelViewAdapters
.asSequence()
.filter { it.createWithDatabase() }
.forEach {
try {
it.createIfNotExists(this)
} catch (e: SQLiteException) {
FlowLog.logError(e)
}
}
}
}
protected fun executeMigrations(db: DatabaseWrapper,
oldVersion: Int, newVersion: Int) {
// will try migrations file or execute migrations from code
try {
val files: List<String> = migrationFileHelper.getListFiles(dbMigrationPath)
.sortedWith(NaturalOrderComparator())
val migrationFileMap = hashMapOf<Int, MutableList<String>>()
for (file in files) {
try {
val version = Integer.valueOf(file.replace(".sql", ""))
val fileList = migrationFileMap.getOrPut(version) { arrayListOf() }
fileList.add(file)
} catch (e: NumberFormatException) {
FlowLog.log(FlowLog.Level.W, "Skipping invalidly named file: $file", e)
}
}
val migrationMap = databaseDefinition.migrations
val curVersion = oldVersion + 1
try {
db.beginTransaction()
// execute migrations in order, migration file first before wrapped migration classes.
for (i in curVersion..newVersion) {
val migrationFiles = migrationFileMap[i]
if (migrationFiles != null) {
for (migrationFile in migrationFiles) {
executeSqlScript(db, migrationFile)
FlowLog.log(FlowLog.Level.I, "$migrationFile executed successfully.")
}
}
val migrationsList = migrationMap[i]
if (migrationsList != null) {
for (migration in migrationsList) {
// before migration
migration.onPreMigrate()
// migrate
migration.migrate(db)
// after migration cleanup
migration.onPostMigrate()
FlowLog.log(FlowLog.Level.I, "${migration.javaClass} executed successfully.")
}
}
}
db.setTransactionSuccessful()
} finally {
db.endTransaction()
}
} catch (e: IOException) {
FlowLog.log(FlowLog.Level.E, "Failed to execute migrations. App might be in an inconsistent state.", e)
}
}
/**
* Supports multiline sql statements with ended with the standard ";"
*
* @param db The database to run it on
* @param file the file name in assets/migrations that we read from
*/
private fun executeSqlScript(db: DatabaseWrapper, file: String) {
migrationFileHelper.executeMigration("$dbMigrationPath/$file") { queryString -> db.execSQL(queryString) }
}
companion object {
/**
* Location where the migration files should exist.
*/
@JvmStatic
val MIGRATION_PATH = "migrations"
}
}
| 38 | null | 613 | 4,865 | e1b6211dac6ddc0aa0c1c9a76a116478ccf92b86 | 6,385 | DBFlow | MIT License |
core/domain/src/main/java/com/niyaj/domain/expense/ValidateExpenseAmountUseCase.kt | skniyajali | 644,752,474 | false | {"Kotlin": 4922890, "Shell": 4104, "Batchfile": 1397, "Java": 232} | /*
* Copyright 2024 Sk Niyaj Ali
*
* 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
*
* https://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.niyaj.domain.expense
import com.niyaj.common.result.ValidationResult
import com.niyaj.common.tags.ExpenseTestTags.EXPENSE_PRICE_EMPTY_ERROR
import com.niyaj.common.tags.ExpenseTestTags.EXPENSE_PRICE_LESS_THAN_TEN_ERROR
import javax.inject.Inject
class ValidateExpenseAmountUseCase @Inject constructor() {
operator fun invoke(expenseAmount: String): ValidationResult {
if (expenseAmount.isEmpty()) {
return ValidationResult(
successful = false,
errorMessage = EXPENSE_PRICE_EMPTY_ERROR,
)
}
try {
if (expenseAmount.toInt() < 10) {
return ValidationResult(
successful = false,
errorMessage = EXPENSE_PRICE_LESS_THAN_TEN_ERROR,
)
}
} catch (e: NumberFormatException) {
return ValidationResult(
successful = false,
errorMessage = "Expenses amount is not valid.",
)
}
return ValidationResult(true)
}
}
| 39 | Kotlin | 0 | 1 | 49485fe344b9345cd0cce0e0961742226dbd8ea1 | 1,678 | PoposRoom | Apache License 2.0 |
src/calls/request/ta/scoring/ScorerAllocator.kt | DiSSCo | 517,633,705 | false | null | package org.synthesis.calls.request.ta.scoring
import io.vertx.sqlclient.Row
import io.vertx.sqlclient.SqlClient
import org.synthesis.account.UserAccountId
import org.synthesis.country.CountryCode
import org.synthesis.infrastructure.persistence.*
import org.synthesis.infrastructure.persistence.querybuilder.fetchOne
import org.synthesis.infrastructure.persistence.querybuilder.select
import org.synthesis.institution.ScorerData
interface ScorerAllocator {
/**
* @throws [StorageException.InteractingFailed]
*/
suspend fun find(id: UserAccountId, countryCode: CountryCode): ScorerData?
}
class PostgresScorerAllocator(
private val sqlClient: SqlClient
) : ScorerAllocator {
override suspend fun find(id: UserAccountId, countryCode: CountryCode): ScorerData? = sqlClient.fetchOne(
select(
from = "scorers as s",
columns = listOf(
"s.user_id as id",
"s.country_code as country_code",
"a.email as email",
"a.first_name as first_name",
"a.last_name as last_name"
)
) {
"accounts a" innerJoin "s.user_id = a.id"
where {
"s.user_id" eq id.uuid
"s.country_code" eq countryCode.id.uppercase()
}
}
)?.hydrate()
private fun Row.hydrate(): ScorerData = ScorerData(
id = UserAccountId(getUUID("id")),
email = getString("email"),
firstName = getString("first_name"),
lastName = getString("last_name"),
country = CountryCode(getString("country_code"))
)
}
| 0 | Kotlin | 0 | 0 | a2277d627647d1669c3714da455f37fe6c2e93ae | 1,635 | elvis-backend | Apache License 2.0 |
app/src/main/kotlin/kr/ac/snu/hcil/omnitrack/core/system/OTMeasureFactoryManager.kt | yghokim | 62,933,149 | false | null | package kr.ac.snu.hcil.omnitrack.core.system
import kr.ac.snu.hcil.omnitrack.core.connection.OTMeasureFactory
import kr.ac.snu.hcil.omnitrack.core.database.models.OTFieldDAO
import kr.ac.snu.hcil.omnitrack.core.externals.OTExternalServiceManager
class OTMeasureFactoryManager(val serviceManager: OTExternalServiceManager, private val itemMeasureFactoryManager: OTItemDynamicMeasureFactoryManager) {
fun getAttachableMeasureFactories(field: OTFieldDAO): List<OTMeasureFactory> {
return serviceManager.getFilteredMeasureFactories { it.getAttributeType() == field.type } + itemMeasureFactoryManager.getAttachableMeasureFactories(field)
}
fun getMeasureFactoryByCode(typeCode: String): OTMeasureFactory? {
return serviceManager.getMeasureFactoryByCode(typeCode)
?: itemMeasureFactoryManager.getMeasureFactoryByCode(typeCode)
}
} | 9 | Kotlin | 4 | 8 | f13e5c157d5646c3f9493c4fdc25ed3b1fc2e296 | 876 | omnitrack_android | MIT License |
android/schedule/appwidget/src/main/java/com/edugma/features/schedule/appwidget/currentLessons/UpdateActionCallback.kt | Edugma | 474,423,768 | false | {"Kotlin": 1050092, "Swift": 1255, "Shell": 331, "HTML": 299} | package com.edugma.features.schedule.appwidget.currentLessons
import android.content.Context
import androidx.glance.GlanceId
import androidx.glance.action.ActionParameters
import androidx.glance.appwidget.action.ActionCallback
class UpdateActionCallback : ActionCallback {
override suspend fun onAction(
context: Context,
glanceId: GlanceId,
parameters: ActionParameters,
) {
CurrentLessonAppWidget().update(context, glanceId)
}
}
| 1 | Kotlin | 0 | 3 | d9149728b9dee61606d7c46d80bc474a77f46362 | 477 | app | MIT License |
core/common/src/serializers/MonthSerializers.kt | Kotlin | 215,849,579 | false | null | /*
* Copyright 2019-2021 JetBrains s.r.o.
* Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file.
*/
package kotlinx.datetime.serializers
import kotlinx.datetime.Month
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.internal.*
@Suppress("INVISIBLE_MEMBER")
public object MonthSerializer: KSerializer<Month> {
private val impl = EnumSerializer("Month", Month.values())
override val descriptor: SerialDescriptor
get() = impl.descriptor
override fun deserialize(decoder: Decoder): Month = impl.deserialize(decoder)
override fun serialize(encoder: Encoder, value: Month): Unit = impl.serialize(encoder, value)
}
| 44 | Kotlin | 38 | 1,190 | e3642e689496e2c87de3e995068cd815f91ee03e | 787 | kotlinx-datetime | Apache License 2.0 |
app/src/main/java/com/coding/zxm/wanandroid/home/HomeViewModel.kt | ZhangXinmin528 | 283,199,248 | false | null | package com.coding.zxm.wanandroid.home
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.coding.zxm.network.RetrofitClient
import com.coding.zxm.network.common.CommonResult
import com.coding.zxm.wanandroid.app.WanApp
import com.coding.zxm.wanandroid.home.model.BannerEntity
import com.coding.zxm.wanandroid.home.model.NewsEntity
import com.coding.zxm.wanandroid.util.ToastUtil
import kotlinx.coroutines.launch
/**
* Created by ZhangXinmin on 2020/8/12.
* Copyright (c) 2020 . All rights reserved.
*/
class HomeViewModel(private val homeRepository: HomeRepository) : ViewModel() {
fun getBannerData(): MutableLiveData<MutableList<BannerEntity>> {
val liveData = MutableLiveData<MutableList<BannerEntity>>()
viewModelScope.launch {
val result = homeRepository.getBannerData()
if (result is CommonResult.Success) {
liveData.postValue(result.data)
} else if (result is CommonResult.Error) {
ToastUtil.showToast(result.exception.message)
liveData.postValue(null)
}
}
return liveData
}
fun getNewsData(pageIndex: Int): MutableLiveData<NewsEntity> {
val liveData = MutableLiveData<NewsEntity>()
viewModelScope.launch {
val result = homeRepository.getHomeNews(pageIndex)
if (result is CommonResult.Success) {
liveData.postValue(result.data)
} else if (result is CommonResult.Error) {
ToastUtil.showToast(result.exception.message)
liveData.postValue(null)
}
}
return liveData
}
object HomeViewModelFactory : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return HomeViewModel(HomeRepository(RetrofitClient.getInstance(WanApp.getApplicationContext())!!)) as T
}
}
} | 0 | Kotlin | 1 | 3 | 226f612382444b8853651590d6ef019363f536f1 | 2,084 | WanAndroid | Apache License 2.0 |
app/src/main/java/de/kauker/unofficial/sdk/grocy/models/GrocyProduct.kt | aimok04 | 556,343,801 | false | null | package de.kauker.unofficial.sdk.grocy.models
import de.kauker.unofficial.sdk.grocy.GrocyClient
import de.kauker.unofficial.sdk.grocy.GrocyRequest
import org.json.JSONObject
class GrocyProduct(
val grocyClient: GrocyClient,
data: JSONObject
) {
lateinit var id: String
lateinit var name: String
lateinit var description: String
lateinit var timestamp: String
var productGroup: GrocyProductGroup? = null
lateinit var _productGroupId: String
var active: Boolean = false
var location: GrocyLocation? = null
lateinit var _locationId: String
var shoppingLocation: GrocyLocation? = null
lateinit var _shoppingLocationId: String
var quantityUnitPurchase: GrocyQuantityUnit? = null
lateinit var _quantityUnitPurchaseId: String
var quantityUnitStock: GrocyQuantityUnit? = null
lateinit var _quantityUnitStockId: String
init {
parse(data)
}
fun parse(json: JSONObject) {
id = json.getString("id")
name = json.getString("name")
description = json.getString("description")
_productGroupId = json.getString("product_group_id")
active = json.getString("active").equals("1")
_locationId = json.getString("location_id")
_shoppingLocationId = json.getString("shopping_location_id")
_quantityUnitPurchaseId = json.getString("qu_id_purchase")
_quantityUnitStockId = json.getString("qu_id_stock")
timestamp = json.getString("row_created_timestamp")
}
override fun toString(): String {
return "GrocyProduct(id='$id', name='$name', description='$description', timestamp='$timestamp', productGroup=$productGroup, _productGroupId='$_productGroupId', active=$active, location=$location, _locationId='$_locationId', shoppingLocation=$shoppingLocation, _shoppingLocationId='$_shoppingLocationId', quantityUnitPurchase=$quantityUnitPurchase, _quantityUnitPurchaseId='$_quantityUnitPurchaseId', quantityUnitStock=$quantityUnitStock, _quantityUnitStockId='$_quantityUnitStockId')"
}
/* api calls */
fun addToShoppingList(shoppingListId: Int, amount: Int): Boolean {
val post = JSONObject()
post.put("product_id", this.id)
post.put("amount", amount)
post.put("shopping_list_id", shoppingListId)
try {
return GrocyRequest(grocyClient).post(
"/api/objects/shopping_list",
post.toString()
).isSuccessful
} catch (throwable: Throwable) {
throwable.printStackTrace()
}
return false
}
}
| 0 | null | 0 | 3 | 9cb18de0d0750801a70f7a92bac51afcfd6f5106 | 2,598 | grocy-for-wear-os | Apache License 2.0 |
PineLib/src/main/java/com/blueberrysolution/pinelib19/addone/diff_brand/miui/MIUIUtils.kt | leaptochina | 228,527,202 | false | null | package com.blueberrysolution.pinelib19.addone.diff_brand.miui
import android.os.Environment
import com.blueberrysolution.pinelib19.addone.share_preferences.Sp
import java.io.File
import java.io.FileInputStream
import java.lang.Exception
import java.util.*
object MIUIUtils {
// 检测MIUI
val KEY_MIUI_VERSION_CODE = "ro.miui.ui.version.code";
val KEY_MIUI_VERSION_NAME = "ro.miui.ui.version.name";
val KEY_MIUI_INTERNAL_STORAGE = "ro.miui.internal.storage";
fun isMIUI(): Boolean {
//获取缓存状态
if(Sp.i.contain("isMIUI"))
{
return Sp.i.get("isMIUI", false);
}
val prop= Properties();
var isMIUI: Boolean = false;
try {
prop.load(FileInputStream(File(Environment.getRootDirectory(), "build.prop")));
} catch (e: Exception)
{
//e.printStackTrace();
return false;
}
isMIUI = prop.getProperty(KEY_MIUI_VERSION_CODE, null) != null
|| prop.getProperty(KEY_MIUI_VERSION_NAME, null) != null
|| prop.getProperty(KEY_MIUI_INTERNAL_STORAGE, null) != null;
Sp.i.put("isMIUI", isMIUI);
return isMIUI;
}
} | 0 | Kotlin | 0 | 0 | b7ccb0b4259c3e17f71a677bdbc6388bb92d9841 | 1,201 | celo_test | Apache License 2.0 |
base/src/main/kotlin/com/github/fsbarata/functional/control/reader/Reader.kt | fsbarata | 388,747,693 | false | null | package com.github.fsbarata.functional.control.reader
import com.github.fsbarata.functional.Context
import com.github.fsbarata.functional.control.Monad
import com.github.fsbarata.functional.control.arrow.kleisli
import com.github.fsbarata.functional.data.Functor
import com.github.fsbarata.functional.data.id
/**
* Reader Monad
*
* This type models a set of dependencies D, required to generate the value A.
*/
class Reader<D, out A>(val runReader: (D) -> A):
Monad<ReaderContext<D>, A> {
override val scope get() = Scope<D>()
override fun <B> map(f: (A) -> B): Reader<D, B> =
Reader { f(runReader(it)) }
override infix fun <B> ap(ff: Functor<ReaderContext<D>, (A) -> B>): Reader<D, B> =
Reader { d -> ff.map { it(runReader(d)) }.asReader.runReader(d) }
override infix fun <B> bind(f: (A) -> Context<ReaderContext<D>, B>): Reader<D, B> =
flatMap { f(it).asReader }
fun <B> flatMap(f: (A) -> Reader<in D, B>) =
Reader<D, B> { f(runReader(it)).runReader(it) }
fun <B> using(f: (B) -> D) = Reader<B, A> { b -> runReader(f(b)) }
operator fun invoke(d: D) = runReader(d)
class Scope<D>: Monad.Scope<ReaderContext<D>> {
override fun <A> just(a: A) = just<D, A>(a)
}
companion object {
fun <D, A> just(a: A): Reader<D, A> = Reader { a }
fun <D> ask(): Reader<D, D> = Reader(::id)
fun <D, A, B> kleisli(f: (A) -> Reader<D, B>) = Scope<D>().kleisli(f)
}
}
internal typealias ReaderContext<D> = Reader<D, *>
val <D, A> Context<ReaderContext<D>, A>.asReader
get() = this as Reader<D, A>
| 0 | Kotlin | 1 | 0 | ce4b63f6326efcc92fcc9a2c69dcda1e45b1e4be | 1,523 | kotlin-functional | Apache License 2.0 |
src/main/java/com/algorithmlx/tenytech/init/TTClientStartup.kt | 0mods | 412,780,565 | false | {"Kotlin": 33432} | package com.algorithmlx.tenytech.init
import com.algorithmlx.tenytech.ModId
import net.minecraft.item.Item
import net.minecraft.item.ItemModelsProperties
import net.minecraft.util.ResourceLocation
import mcp.MethodsReturnNonnullByDefault
object TTClientStartup {
fun flyRingRenderer(item: Item) {
ItemModelsProperties.register(
item,
ResourceLocation(ModId, "damage")
) { pStack, _, _ ->
if (pStack.isDamaged) {
val fullDur = 7200000
val state1 = fullDur % 20
val state2 = fullDur % 50
val state3 = fullDur % 80
val damageValue = pStack.damageValue
if (damageValue < state1)
return@register 0F
else if (damageValue in state1 downTo state2)
return@register 1F
else if (damageValue in state2 downTo state3) return@register 2F
else return@register 3F
} else return@register 0F
}
}
} | 0 | Kotlin | 1 | 3 | b7e1211acb5795e719aa179a85e2d753f9f18fe6 | 1,046 | TenyTech-Mod | MIT License |
app/src/main/java/org/fossasia/susi/ai/login/LoginPresenter.kt | fragm3 | 189,690,148 | false | null | package org.fossasia.susi.ai.login
import android.graphics.Color
import org.fossasia.susi.ai.R
import org.fossasia.susi.ai.data.ForgotPasswordModel
import org.fossasia.susi.ai.data.contract.ILoginModel
import org.fossasia.susi.ai.data.contract.IForgotPasswordModel
import org.fossasia.susi.ai.data.LoginModel
import org.fossasia.susi.ai.data.UtilModel
import org.fossasia.susi.ai.data.db.DatabaseRepository
import org.fossasia.susi.ai.data.db.contract.IDatabaseRepository
import org.fossasia.susi.ai.helper.Constant
import org.fossasia.susi.ai.helper.CredentialHelper
import org.fossasia.susi.ai.helper.NetworkUtils
import org.fossasia.susi.ai.login.contract.ILoginPresenter
import org.fossasia.susi.ai.login.contract.ILoginView
import org.fossasia.susi.ai.rest.responses.susi.ForgotPasswordResponse
import org.fossasia.susi.ai.rest.responses.susi.LoginResponse
import org.fossasia.susi.ai.rest.responses.susi.Settings
import org.fossasia.susi.ai.rest.responses.susi.UserSetting
import retrofit2.Response
import timber.log.Timber
import java.net.UnknownHostException
/**
* Presenter for Login
* The P in MVP
*
* Created by chiragw15 on 4/7/17.
*/
class LoginPresenter(loginActivity: LoginActivity) : ILoginPresenter, ILoginModel.OnLoginFinishedListener, IForgotPasswordModel.OnFinishListener {
private var loginModel: LoginModel = LoginModel()
private var utilModel: UtilModel = UtilModel(loginActivity)
private var databaseRepository: IDatabaseRepository = DatabaseRepository()
private var loginView: ILoginView? = null
var forgotPasswordModel: ForgotPasswordModel = ForgotPasswordModel()
lateinit var email: String
lateinit var message: String
override fun onAttach(loginView: ILoginView) {
this.loginView = loginView
if (utilModel.getAnonymity()) {
loginView.skipLogin()
return
}
if (utilModel.isLoggedIn()) {
loginView.skipLogin()
return
}
loginView.attachEmails(utilModel.getSavedEmails())
}
override fun skipLogin() {
utilModel.clearToken()
utilModel.saveAnonymity(true)
loginView?.skipLogin()
}
override fun login(email: String, password: String, isSusiServerSelected: Boolean, url: String) {
if (email.isEmpty()) {
loginView?.invalidCredentials(true, Constant.EMAIL)
return
}
if (password.isEmpty()) {
loginView?.invalidCredentials(true, Constant.PASSWORD)
return
}
if (!CredentialHelper.isEmailValid(email)) {
loginView?.invalidCredentials(false, Constant.EMAIL)
return
}
if (!isSusiServerSelected) {
if (url.isEmpty()) {
loginView?.invalidCredentials(true, Constant.INPUT_URL)
return
}
if (CredentialHelper.isURLValid(url)) {
if (CredentialHelper.getValidURL(url) != null) {
utilModel.setServer(false)
utilModel.setCustomURL(url)
} else {
loginView?.invalidCredentials(false, Constant.INPUT_URL)
return
}
} else {
loginView?.invalidCredentials(false, Constant.INPUT_URL)
return
}
} else {
utilModel.setServer(true)
}
this.email = email
loginView?.showProgress(true)
loginModel.login(email.trim({ it <= ' ' }).toLowerCase(), password, this)
}
override fun cancelLogin() {
loginModel.cancelLogin()
}
override fun onError(throwable: Throwable) {
loginView?.showProgress(false)
if (throwable is UnknownHostException) {
if (NetworkUtils.isNetworkConnected()) {
Timber.e(throwable.toString())
loginView?.onLoginError(utilModel.getString(R.string.unknown_host_exception), throwable.message.toString())
} else {
loginView?.onLoginError(utilModel.getString(R.string.error_internet_connectivity),
utilModel.getString(R.string.no_internet_connection))
}
} else {
loginView?.onLoginError(utilModel.getString(R.string.error_internet_connectivity),
utilModel.getString(R.string.no_internet_connection))
}
}
override fun onLoginModelSuccess(response: Response<LoginResponse>) {
if (response.isSuccessful && response.body() != null) {
utilModel.saveToken(response)
databaseRepository.deleteAllMessages()
utilModel.saveEmail(email)
utilModel.saveAnonymity(false)
loginModel.getUserSetting(this)
message = response.body().message.toString()
} else if (response.code() == 422) {
loginView?.showProgress(false)
loginView?.onLoginError(utilModel.getString(R.string.password_invalid_title),
utilModel.getString(R.string.password_invalid))
} else {
loginView?.showProgress(false)
loginView?.onLoginError("${response.code()} " + utilModel.getString(R.string.error),
"${response.message()} \n" + utilModel.getString(R.string.error_custom_server))
}
}
override fun onSuccessSetting(response: Response<UserSetting>) {
loginView?.showProgress(false)
if (response.isSuccessful && response.body() != null) {
val settings: Settings? = response.body().settings
if (settings != null) {
utilModel.putBooleanPref(Constant.ENTER_SEND, settings.enterSend)
utilModel.putBooleanPref(Constant.SPEECH_ALWAYS, settings.speechAlways)
utilModel.putBooleanPref(Constant.SPEECH_OUTPUT, settings.speechOutput)
if (settings.language == "default") {
utilModel.setLanguage("en")
} else {
utilModel.setLanguage(settings.language)
}
}
loginView?.onLoginSuccess(message)
}
}
override fun onErrorSetting() {
loginView?.showProgress(false)
loginView?.onLoginSuccess(message)
}
override fun onDetach() {
loginView = null
}
override fun requestPassword(email: String, url: String, isPersonalServerChecked: Boolean) {
if (email.isEmpty()) {
loginView?.invalidCredentials(true, Constant.EMAIL)
return
}
if (!CredentialHelper.isEmailValid(email)) {
loginView?.invalidCredentials(false, Constant.EMAIL)
return
}
if (isPersonalServerChecked) {
if (url.isEmpty()) {
loginView?.invalidCredentials(true, Constant.INPUT_URL)
return
}
if (CredentialHelper.isURLValid(url)) {
if (CredentialHelper.getValidURL(url) != null) {
utilModel.setServer(false)
utilModel.setCustomURL(CredentialHelper.getValidURL(url) as String)
} else {
loginView?.invalidCredentials(false, Constant.INPUT_URL)
return
}
} else {
loginView?.invalidCredentials(false, Constant.INPUT_URL)
return
}
} else {
utilModel.setServer(true)
}
this.email = email
loginView?.showForgotPasswordProgress(true)
forgotPasswordModel.requestPassword(email.trim({ it <= ' ' }), this)
}
override fun onForgotPasswordModelSuccess(response: Response<ForgotPasswordResponse>) {
loginView?.showForgotPasswordProgress(false)
if (response.isSuccessful && response.body() != null) {
loginView?.resetPasswordSuccess()
} else if (response.code() == 422) {
loginView?.resetPasswordFailure(utilModel.getString(R.string.email_invalid_title), utilModel.getString(R.string.email_invalid), utilModel.getString(R.string.retry), Color.RED)
} else {
loginView?.resetPasswordFailure("${response.code()} " + utilModel.getString(R.string.error), response.message(), utilModel.getString(R.string.ok), Color.BLUE)
}
}
override fun cancelSignup() {
forgotPasswordModel.cancelSignup()
}
}
| 1 | null | 1 | 1 | bd42eb2289fa96da51bc634a29b36c3952ae1dc0 | 8,456 | susi_android | Apache License 2.0 |
plugin/src/main/kotlin/net/bnb1/kradle/KradleExtension.kt | mrkuz | 400,078,467 | false | null | package net.bnb1.kradle
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.model.ObjectFactory
import javax.inject.Inject
open class KradleExtension @Inject constructor(factory: ObjectFactory) {
private val _mainClass = factory.empty<String>()
fun mainClass(name: String, jvmName: Boolean = false) {
if (jvmName) {
_mainClass.set(name)
} else {
_mainClass.set(name + "Kt")
}
}
val mainClass
get() = _mainClass.getOrElse("")
val targetJvm = factory.property("17")
fun targetJvm(version: String) = targetJvm.set(version)
val kotlinxCoroutinesVersion = factory.property("1.5.2")
fun kotlinxCoroutinesVersion(version: String) = kotlinxCoroutinesVersion.set(version)
val tests = TestsExtension(factory)
fun tests(configure: TestsExtension.() -> Unit) = configure(tests)
val uberJar = UberJarExtension(factory)
fun uberJar(configure: UberJarExtension.() -> Unit) = configure(uberJar)
val image = ImageExtension(factory)
fun image(configure: ImageExtension.() -> Unit) = configure(image)
// Backward compatibility
val jacocoVersion = tests.jacocoVersion
fun jacocoVersion(version: String) = tests.jacocoVersion.set(version)
val jmhVersion = factory.property("1.33")
fun jmhVersion(version: String) = jmhVersion.set(version)
val ktlintVersion = factory.property("0.43.0")
fun ktlintVersion(version: String) = ktlintVersion.set(version)
val detektConfigFile = factory.property("detekt-config.yml")
fun detektConfigFile(name: String) = detektConfigFile.set(name)
val detektVersion = factory.property("1.18.1")
fun detektVersion(version: String) = detektVersion.set(version)
private val disabledBlueprints = factory.setProperty(Class::class.java)
fun disable(blueprint: Class<out PluginBlueprint<Plugin<Project>>>) = disabledBlueprints.add(blueprint)
fun isDisabled(blueprint: PluginBlueprint<Plugin<Project>>) =
disabledBlueprints.get().contains(blueprint::class.java)
open class UberJarExtension(factory: ObjectFactory) {
val minimize = factory.property(false)
fun minimize(enabled: Boolean) = minimize.set(enabled)
}
open class ImageExtension(factory: ObjectFactory) {
val baseImage = factory.property("bellsoft/liberica-openjdk-alpine:17")
fun baseImage(name: String) = baseImage.set(name)
val ports = factory.setProperty(Int::class.java)
val jvmKillVersion = factory.empty<String>()
fun withJvmKill(version: String = "1.16.0") = jvmKillVersion.set(version)
val withAppSh = factory.property(false)
fun withAppSh() = withAppSh.set(true)
val javaOpts = factory.empty<String>()
fun javaOpts(opts: String) = javaOpts.set(opts)
}
open class TestsExtension(factory: ObjectFactory) {
val junitJupiterVersion = factory.property("5.8.1")
fun junitJupiterVersion(version: String) = junitJupiterVersion.set(version)
val jacocoVersion = factory.property("0.8.7")
fun jacocoVersion(version: String) = jacocoVersion.set(version)
val kotestVersion = factory.empty<String>()
fun useKotest(version: String = "4.6.3") = kotestVersion.set(version)
val mockkVersion = factory.empty<String>()
fun useMockk(version: String = "1.12.1") = mockkVersion.set(version)
}
} | 0 | Kotlin | 0 | 1 | 29c7ffa5bb7ce8e22c3f052cd99145fa8e089302 | 3,446 | kradle | MIT License |
src/main/kotlin/org/cdb/labwitch/controller/TagController.kt | CodeDrillBrigade | 714,769,385 | false | {"Kotlin": 68833} | package org.cdb.labwitch.controller
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.coroutines.flow.toList
import org.cdb.labwitch.logic.TagLogic
import org.cdb.labwitch.models.embed.Tag
import org.cdb.labwitch.models.identifiers.EntityId
import org.cdb.labwitch.models.security.Permissions
import org.cdb.labwitch.requests.authenticatedGet
import org.cdb.labwitch.requests.authenticatedPost
import org.koin.ktor.ext.inject
fun Routing.tagController() =
route("/tag") {
val tagLogic by inject<TagLogic>()
authenticatedGet("") {
call.respond(tagLogic.getAll().toList())
}
authenticatedGet("/{tagId}") {
val materialId = checkNotNull(call.parameters["tagId"]) { "Tag Id must not be null" }
call.respond(tagLogic.get(EntityId(materialId)))
}
authenticatedPost("", permissions = setOf(Permissions.MANAGE_METADATA)) {
val tagToCreate = call.receive<Tag>()
call.respond(tagLogic.create(tagToCreate))
}
}
| 2 | Kotlin | 0 | 0 | d61c00de00a28ea260ca3b5efbfc6c2a7b56d6fc | 1,034 | LabWitchery-backend | MIT License |
app/src/main/java/co/orangesoft/authmanager/auth/SimpleProfile.kt | Orangesoft-Development | 301,754,025 | false | null | package co.orangesoft.authmanager.auth
import com.google.gson.annotations.SerializedName
class SimpleProfile(
var id: String,
var providerId: String? = null,
var name: String? = null,
var phoneNumber: String? = null,
@SerializedName("avatar_url")
var avatarUrl: String? = null,
var birthday: String? = null
) | 0 | Kotlin | 0 | 0 | 7d35474f23d1f577662ebbe45642f74901bfe410 | 338 | auth_manager | Apache License 2.0 |
compiler/fir/checkers/src/org/jetbrains/kotlin/fir/analysis/checkers/declaration/FirOperatorModifierChecker.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
/*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.analysis.checkers.declaration
import javaslang.Function2
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext
import org.jetbrains.kotlin.fir.analysis.checkers.declaration.Checks.Returns
import org.jetbrains.kotlin.fir.analysis.checkers.declaration.Checks.ValueParametersCount
import org.jetbrains.kotlin.fir.analysis.checkers.declaration.Checks.isKProperty
import org.jetbrains.kotlin.fir.analysis.checkers.declaration.Checks.member
import org.jetbrains.kotlin.fir.analysis.checkers.declaration.Checks.memberOrExtension
import org.jetbrains.kotlin.fir.analysis.checkers.declaration.Checks.noDefaultAndVarargs
import org.jetbrains.kotlin.fir.analysis.checkers.hasModifier
import org.jetbrains.kotlin.fir.analysis.checkers.isSubtypeOf
import org.jetbrains.kotlin.fir.analysis.checkers.isSupertypeOf
import org.jetbrains.kotlin.fir.analysis.checkers.overriddenFunctions
import org.jetbrains.kotlin.fir.analysis.diagnostics.DiagnosticReporter
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors
import org.jetbrains.kotlin.fir.analysis.diagnostics.reportOn
import org.jetbrains.kotlin.fir.containingClass
import org.jetbrains.kotlin.fir.declarations.FirSimpleFunction
import org.jetbrains.kotlin.fir.declarations.utils.isOperator
import org.jetbrains.kotlin.fir.resolve.toFirRegularClass
import org.jetbrains.kotlin.fir.symbols.impl.ConeClassLikeLookupTagImpl
import org.jetbrains.kotlin.fir.typeContext
import org.jetbrains.kotlin.fir.types.*
import org.jetbrains.kotlin.fir.types.impl.ConeClassLikeTypeImpl
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.util.OperatorNameConventions.ASSIGNMENT_OPERATIONS
import org.jetbrains.kotlin.util.OperatorNameConventions.BINARY_OPERATION_NAMES
import org.jetbrains.kotlin.util.OperatorNameConventions.COMPARE_TO
import org.jetbrains.kotlin.util.OperatorNameConventions.COMPONENT_REGEX
import org.jetbrains.kotlin.util.OperatorNameConventions.CONTAINS
import org.jetbrains.kotlin.util.OperatorNameConventions.DEC
import org.jetbrains.kotlin.util.OperatorNameConventions.EQUALS
import org.jetbrains.kotlin.util.OperatorNameConventions.GET
import org.jetbrains.kotlin.util.OperatorNameConventions.GET_VALUE
import org.jetbrains.kotlin.util.OperatorNameConventions.HAS_NEXT
import org.jetbrains.kotlin.util.OperatorNameConventions.INC
import org.jetbrains.kotlin.util.OperatorNameConventions.INVOKE
import org.jetbrains.kotlin.util.OperatorNameConventions.ITERATOR
import org.jetbrains.kotlin.util.OperatorNameConventions.NEXT
import org.jetbrains.kotlin.util.OperatorNameConventions.PROVIDE_DELEGATE
import org.jetbrains.kotlin.util.OperatorNameConventions.RANGE_TO
import org.jetbrains.kotlin.util.OperatorNameConventions.SET
import org.jetbrains.kotlin.util.OperatorNameConventions.SET_VALUE
import org.jetbrains.kotlin.util.OperatorNameConventions.SIMPLE_UNARY_OPERATION_NAMES
object FirOperatorModifierChecker : FirSimpleFunctionChecker() {
override fun check(declaration: FirSimpleFunction, context: CheckerContext, reporter: DiagnosticReporter) {
if (!declaration.isOperator) return
//we are not interested in implicit operators from override
if (!declaration.hasModifier(KtTokens.OPERATOR_KEYWORD)) return
val checks = OperatorFunctionChecks.checksByName.getOrElse(declaration.name) {
OperatorFunctionChecks.regexChecks.find { it.first.matches(declaration.name.asString()) }?.second
}
if (checks == null) {
reporter.reportOn(declaration.source, FirErrors.INAPPLICABLE_OPERATOR_MODIFIER, "illegal function name", context)
return
}
for (check in checks) {
check.check(context, declaration)?.let { error ->
reporter.reportOn(declaration.source, FirErrors.INAPPLICABLE_OPERATOR_MODIFIER, error, context)
return
}
}
}
}
interface Check : Function2<CheckerContext, FirSimpleFunction, String?> {
override fun apply(t1: CheckerContext, t2: FirSimpleFunction): String? = check(t1, t2)
fun check(context: CheckerContext, function: FirSimpleFunction): String?
}
object Checks {
fun simple(message: String, predicate: (FirSimpleFunction) -> Boolean) = object : Check {
override fun check(context: CheckerContext, function: FirSimpleFunction): String? = message.takeIf { !predicate(function) }
}
fun full(message: String, predicate: (CheckerContext, FirSimpleFunction) -> Boolean) = object : Check {
override fun check(context: CheckerContext, function: FirSimpleFunction): String? = message.takeIf { !predicate(context, function) }
}
val memberOrExtension = simple("must be a member or an extension function") {
it.dispatchReceiverType != null || it.receiverTypeRef != null
}
val member = simple("must be a member function") {
it.dispatchReceiverType != null
}
object ValueParametersCount {
fun atLeast(n: Int) = simple("must have at least $n value parameter" + (if (n > 1) "s" else "")) {
it.valueParameters.size >= n
}
fun exactly(n: Int) = simple("must have exactly $n value parameters") {
it.valueParameters.size == n
}
val single = simple("must have a single value parameter") {
it.valueParameters.size == 1
}
val none = simple("must have no value parameters") {
it.valueParameters.isEmpty()
}
}
object Returns {
val boolean = simple("must return Boolean") {
it.returnTypeRef.isBoolean
}
val int = simple("must return Int") {
it.returnTypeRef.isInt
}
val unit = simple("must return Unit") {
it.returnTypeRef.isUnit
}
}
val noDefaultAndVarargs = simple("should not have varargs or parameters with default values") {
it.valueParameters.all { param ->
param.defaultValue == null && !param.isVararg
}
}
private val kPropertyType = ConeClassLikeTypeImpl(
ConeClassLikeLookupTagImpl(StandardNames.FqNames.kProperty),
arrayOf(ConeStarProjection),
isNullable = false
)
val isKProperty = full("second parameter must be of type KProperty<*> or its supertype") { ctx, function ->
val paramType = function.valueParameters[1].returnTypeRef.coneType
paramType.isSupertypeOf(ctx.session.typeContext, kPropertyType)
}
}
@OptIn(ExperimentalStdlibApi::class)
object OperatorFunctionChecks {
//reimplementation of org.jetbrains.kotlin.util.OperatorChecks for FIR
val checksByName: Map<Name, List<Check>> = buildMap<Name, List<Check>> {
checkFor(GET, memberOrExtension, ValueParametersCount.atLeast(1))
checkFor(
SET,
memberOrExtension, ValueParametersCount.atLeast(2),
Checks.simple("last parameter should not have a default value or be a vararg") {
it.valueParameters.lastOrNull()?.let { param ->
param.defaultValue == null && !param.isVararg
} == true
}
)
checkFor(GET_VALUE, memberOrExtension, noDefaultAndVarargs, ValueParametersCount.atLeast(2), isKProperty)
checkFor(SET_VALUE, memberOrExtension, noDefaultAndVarargs, ValueParametersCount.atLeast(3), isKProperty)
checkFor(PROVIDE_DELEGATE, memberOrExtension, noDefaultAndVarargs, ValueParametersCount.exactly(2), isKProperty)
checkFor(INVOKE, memberOrExtension)
checkFor(CONTAINS, memberOrExtension, ValueParametersCount.single, noDefaultAndVarargs, Returns.boolean)
checkFor(ITERATOR, memberOrExtension, ValueParametersCount.none)
checkFor(NEXT, memberOrExtension, ValueParametersCount.none)
checkFor(HAS_NEXT, memberOrExtension, ValueParametersCount.none, Returns.boolean)
checkFor(RANGE_TO, memberOrExtension, ValueParametersCount.single, noDefaultAndVarargs)
checkFor(
EQUALS,
member,
Checks.full("must override ''equals()'' in Any") { ctx, function ->
val containingClass = function.containingClass()?.toFirRegularClass(ctx.session) ?: return@full true
function.overriddenFunctions(containingClass, ctx).any {
it.containingClass()?.classId?.asSingleFqName() == StandardNames.FqNames.any.toSafe()
}
}
)
checkFor(COMPARE_TO, memberOrExtension, Returns.int, ValueParametersCount.single, noDefaultAndVarargs)
checkFor(BINARY_OPERATION_NAMES, memberOrExtension, ValueParametersCount.single, noDefaultAndVarargs)
checkFor(SIMPLE_UNARY_OPERATION_NAMES, memberOrExtension, ValueParametersCount.none)
checkFor(
setOf(INC, DEC),
memberOrExtension,
Checks.full("receiver must be a supertype of the return type") { ctx, function ->
val receiver = function.dispatchReceiverType ?: function.receiverTypeRef?.coneType ?: return@full false
function.returnTypeRef.coneType.isSubtypeOf(ctx.session.typeContext, receiver)
}
)
checkFor(ASSIGNMENT_OPERATIONS, memberOrExtension, Returns.unit, ValueParametersCount.single, noDefaultAndVarargs)
}
val regexChecks: List<Pair<Regex, List<Check>>> = buildList {
checkFor(COMPONENT_REGEX, memberOrExtension, ValueParametersCount.none)
}
private fun MutableMap<Name, List<Check>>.checkFor(name: Name, vararg checks: Check) {
put(name, checks.asList())
}
private fun MutableMap<Name, List<Check>>.checkFor(names: Set<Name>, vararg checks: Check) {
names.forEach { put(it, checks.asList()) }
}
private fun MutableList<Pair<Regex, List<Check>>>.checkFor(regex: Regex, vararg checks: Check) {
add(regex to checks.asList())
}
} | 4 | null | 5411 | 43,797 | a8f547d080724fae3a45d675a16c5b3fc2f13b17 | 10,438 | kotlin | Apache License 2.0 |
bezier/src/main/java/io/channel/bezier/icon/Exclusive.kt | channel-io | 736,533,981 | false | {"Kotlin": 2421787, "Python": 12500} | @file:Suppress("ObjectPropertyName", "UnusedReceiverParameter")
// Auto-generated by script/generate_compose_bezier_icon.py
package io.channel.bezier.icon
import androidx.compose.foundation.layout.size
import androidx.compose.material.Icon
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import io.channel.bezier.BezierIcon
import io.channel.bezier.BezierIcons
val BezierIcons.Exclusive: BezierIcon
get() = object : BezierIcon {
override val imageVector: ImageVector
get() = _exclusive ?: ImageVector.Builder(
name = "Exclusive",
defaultWidth = 24.dp,
defaultHeight = 24.dp,
viewportWidth = 24f,
viewportHeight = 24f,
).apply {
path(
fill = SolidColor(Color(0xFF313234)),
strokeLineWidth = 1f,
pathFillType = PathFillType.EvenOdd,
) {
moveTo(8.366f, 11.505f)
lineTo(11.293f, 8.577000000000002f)
arcTo(1.0f, 1.0f, 44.991348337162f, isMoreThanHalf = false, isPositiveArc = false, 11.293f, 7.163000000000002f)
lineTo(8.366f, 4.236f)
arcTo(0.8f, 0.8f, 315.0318958890256f, isMoreThanHalf = false, isPositiveArc = false, 7.0f, 4.802f)
lineTo(7.0f, 7.0f)
arcTo(6.0f, 6.0f, 270.0f, isMoreThanHalf = true, isPositiveArc = false, 7.0f, 19.0f)
lineTo(9.0f, 19.0f)
arcTo(1.0f, 1.0f, 90.0f, isMoreThanHalf = true, isPositiveArc = false, 9.0f, 17.0f)
lineTo(7.0f, 17.0f)
arcTo(4.0f, 4.0f, 90.0f, isMoreThanHalf = false, isPositiveArc = true, 7.0f, 9.0f)
lineTo(7.0f, 10.939f)
arcTo(0.8f, 0.8f, 180.0450898590568f, isMoreThanHalf = false, isPositiveArc = false, 8.366f, 11.505f)
moveTo(13.016f, 7.0f)
arcTo(1.0f, 1.0f, 180.0f, isMoreThanHalf = false, isPositiveArc = false, 14.016f, 8.0f)
lineTo(22.016f, 8.0f)
arcTo(1.0f, 1.0f, 90.0f, isMoreThanHalf = true, isPositiveArc = false, 22.016f, 6.0f)
lineTo(14.015999999999998f, 6.0f)
arcTo(1.0f, 1.0f, 270.0f, isMoreThanHalf = false, isPositiveArc = false, 13.015999999999998f, 7.0f)
moveTo(13.0f, 12.5f)
arcTo(1.0f, 1.0f, 180.0f, isMoreThanHalf = false, isPositiveArc = false, 14.0f, 13.5f)
lineTo(22.0f, 13.5f)
arcTo(1.0f, 1.0f, 90.0f, isMoreThanHalf = true, isPositiveArc = false, 22.0f, 11.5f)
lineTo(14.0f, 11.5f)
arcTo(1.0f, 1.0f, 270.0f, isMoreThanHalf = false, isPositiveArc = false, 13.0f, 12.5f)
moveTo(22.016f, 19.0f)
arcTo(1.0f, 1.0f, 90.0f, isMoreThanHalf = true, isPositiveArc = false, 22.016f, 17.0f)
lineTo(14.015999999999998f, 17.0f)
arcTo(1.0f, 1.0f, 270.0f, isMoreThanHalf = true, isPositiveArc = false, 14.015999999999998f, 19.0f)
close()
}
}.build().also {
_exclusive = it
}
}
private var _exclusive: ImageVector? = null
@Preview(showBackground = true)
@Composable
private fun ExclusiveIconPreview() {
Icon(
modifier = Modifier.size(128.dp),
imageVector = BezierIcons.Exclusive.imageVector,
contentDescription = null,
)
}
| 7 | Kotlin | 3 | 6 | 39cd58b0dd4a1543d54f0c1ce7c605f33ce135c6 | 3,984 | bezier-compose | MIT License |
navigation/src/main/java/com/beetlestance/androidextensions/navigation/util/LiveEvent.kt | beetlestance | 282,616,603 | false | null | package com.bubelov.coins.util
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.Observer
import androidx.annotation.MainThread
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
class LiveEvent<T> : MediatorLiveData<T>() {
private val observers = ConcurrentHashMap<LifecycleOwner, MutableSet<ObserverWrapper<in T>>>()
@MainThread
override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
val wrapper = ObserverWrapper(observer)
val set = observers[owner]
if (set != null) {
set.add(wrapper)
} else {
val newSet = Collections.newSetFromMap(ConcurrentHashMap<ObserverWrapper<in T>, Boolean>())
newSet.add(wrapper)
observers[owner] = newSet
}
super.observe(owner, wrapper)
}
override fun removeObservers(owner: LifecycleOwner) {
observers.remove(owner)
super.removeObservers(owner)
}
override fun removeObserver(observer: Observer<in T>) {
observers.forEach {
if (it.value.remove(observer)) {
if (it.value.isEmpty()) {
observers.remove(it.key)
}
return@forEach
}
}
super.removeObserver(observer)
}
@MainThread
override fun setValue(t: T?) {
observers.forEach { it.value.forEach { wrapper -> wrapper.newValue() } }
super.setValue(t)
}
/**
* Used for cases where T is Void, to make calls cleaner.
*/
@MainThread
fun call() {
value = null
}
private class ObserverWrapper<T>(private val observer: Observer<T>) : Observer<T> {
private val pending = AtomicBoolean(false)
override fun onChanged(t: T?) {
if (pending.compareAndSet(true, false)) {
observer.onChanged(t)
}
}
fun newValue() {
pending.set(true)
}
}
} | 2 | null | 3 | 9 | 52514231c13695292826b2872792349590234197 | 2,076 | android-extensions | Apache License 2.0 |
app/src/main/java/com/github/satoshun/coroutine/autodispose/sample/MainActivity.kt | mohammadt3anii | 163,180,984 | true | {"Kotlin": 21469} | package com.github.satoshun.coroutine.autodispose.sample
import android.os.Bundle
import android.util.Log
import android.view.ViewGroup
import androidx.fragment.app.commit
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class MainActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_act)
// auto dispose when onDestroy
val childJob = launch {
while (true) {
delay(1200)
Log.d("activity", "onCreate")
}
}
childJob.invokeOnCompletion {
Log.d("activity", "onCreate job completed")
}
supportFragmentManager.commit {
add(R.id.frame, MainFragment())
}
findViewById<ViewGroup>(R.id.root).addView(MainView(this))
}
override fun onResume() {
super.onResume()
// auto dispose when onPause
val childJob = launch {
while (true) {
delay(3000)
Log.d("activity", "onResume")
}
}
childJob.invokeOnCompletion {
Log.d("activity", "onResume job completed")
}
}
}
| 0 | Kotlin | 0 | 0 | 6c0d298372df297fe72af9d4a9a97eb411332edc | 1,105 | CoroutineAutoDispose | Apache License 2.0 |
gooddata-server-oauth2-autoconfigure/src/main/kotlin/AuthenticationStoreClient.kt | gooddata | 373,135,413 | false | {"Kotlin": 449683} | /*
* Copyright 2021 GoodData Corporation
*
* 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
*
* https://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.gooddata.oauth2.server
import com.nimbusds.jose.jwk.JWK
import java.time.Instant
import java.time.LocalDateTime
import org.springframework.http.HttpStatus
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException
import org.springframework.web.server.ResponseStatusException
/**
* `AuthenticationStoreClient` defines methods for retrieving identity objects from persistent storage.
*/
interface AuthenticationStoreClient {
/**
* Retrieves [Organization] that corresponds to provided `hostname`. [ResponseStatusException]
* with [HttpStatus.NOT_FOUND] status code is thrown in case no [Organization] can be found.
*
* @param hostname of the organization
* @return `Organization` corresponding to `hostname`
* @throws ResponseStatusException in case `Organization` is not found
*/
suspend fun getOrganizationByHostname(hostname: String): Organization
/**
* Retrieves [User] that corresponds to provided `organizationId` and `authenticationId` retrieved from
* OIDC ID token.
*
* Returns `null` in case no [User] can be found.
*
* @param organizationId ID identifying the organization
* @param authenticationId ID identifying the user in OIDC provider
* @return found [User] or `null` in case no [User] is found
*/
suspend fun getUserByAuthenticationId(organizationId: String, authenticationId: String): User?
/**
*
* Retrieves [User] that belongs to given `organizationId`
*
* @param organizationId ID of the organization that the user belongs to
* @param token API token to be searched
* @return `User` corresponding to `hostname`
* TODO exception should be handled directly in the library
* @throws InvalidBearerTokenException in case no [User] is found
*/
suspend fun getUserByApiToken(organizationId: String, token: String): User
/**
*
* Retrieves [User] that belongs to given `organizationId`
*
* @param organizationId ID of the organization that the user belongs to
* @param userId id of the user to be searched
* @return `User` corresponding to userId
* TODO should an exception be thrown if the user is not found?
*/
suspend fun getUserById(organizationId: String, userId: String): User?
/**
*
* Retrieves [List<JWK>] that belongs to given `organizationId`
*
* @param organizationId ID of the organization that the JWKs belongs to
* @return list of JWKs corresponding to organizationId
*/
suspend fun getJwks(organizationId: String): List<JWK>
/**
* Checks whether JWT, that belongs to organization `organizationId` and user `userId` specified by `jwtHash`
* (optionally also by `jwtId` for faster processing) is valid
*
* @param organizationId ID of the organization that the JWTs belongs to
* @param userId ID of the user that the JWTs belongs to
* @param jwtHash md5 hash of the JWT token
* @param jwtId ID of the JWT (optional)
* @return true if the JWT is valid, false otherwise
*/
suspend fun isValidJwt(organizationId: String, userId: String, jwtHash: String, jwtId: String?): Boolean
/**
* Invalidates JWT, that belongs to organization `organizationId` and user `userId` specified by `jwtHash`
* (optionally also by `jwtId` for faster processing) is valid
*
* @param organizationId ID of the organization that the JWTs belongs to
* @param userId ID of the user that the JWTs belongs to
* @param jwtHash md5 hash of the JWT token
* @param jwtId ID of the JWT (optional)
* @param validTo UTC time of JWT expiration
*/
suspend fun invalidateJwt(
organizationId: String,
userId: String,
jwtHash: String,
jwtId: String?,
validTo: LocalDateTime
)
/**
* Marks the [User] belonging to the [Organization] for global logout. Any OIDC tokens which were issued before that
* actions are to be considered as expired.
*
* @param userId ID identifying the user
* @param organizationId ID identifying the organization
*/
suspend fun logoutAll(userId: String, organizationId: String)
/**
* Retrieve [CookieSecurityProperties] for given organization.
*
* @param organizationId ID identifying the organization
* @return [CookieSecurityProperties] for given organization
*/
suspend fun getCookieSecurityProperties(organizationId: String): CookieSecurityProperties
}
/**
* Represents the single organization stored in the persistent storage and having its hostname and own specific OAuth
* settings.
*
* @property id the ID of this organization within the persistent storage
* @property oauthIssuerLocation the location URL of the OAuth issuer
* @property oauthClientId the identifier of the application registered in the OAuth issuer
* @property oauthClientSecret the secret of the application registered in the OAuth issuer
* @property allowedOrigins the list of hosts (origins) for which
* * the successful application login is allowed to redirect
* * the CORS requests are allowed
* @property oauthIssuerId the ID of the OAuth issuer. This value is used as suffix for OAuth callback (redirect) URL.
* If not defined (`null` value), the standard callback URL is used. Defaults to `null`.
* * callback URL with this value: `<hostUrl>/<action>/oauth2/code/<oauthIssuerId>`
* * standard callback URL: `<hostUrl>/<action>/oauth2/code/<registrationId>` (see
* [org.springframework.security.oauth2.client.registration.ClientRegistration])
* @property oauthSubjectIdClaim name of the claim in ID token that will be used for finding the user in organization.
* Defaults to `null` and it means that `sub` claim will be used.
*
* @see AuthenticationStoreClient
*/
data class Organization(
val id: String,
val oauthIssuerLocation: String? = null,
val oauthClientId: String? = null,
val oauthClientSecret: String? = null,
val allowedOrigins: List<String>? = null,
val oauthIssuerId: String? = null,
val oauthSubjectIdClaim: String? = null,
)
/**
* Represents authenticated end-user (principal) stored in the persistent storage.
*
* @property id the ID of this end-user within the persistent storage
* @property lastLogoutAllTimestamp timestamp, when this end-user hit "Logout From All Sessions" last time
*
* @see AuthenticationStoreClient
*/
data class User(
val id: String,
val lastLogoutAllTimestamp: Instant? = null,
)
| 0 | Kotlin | 5 | 2 | e11e40fe2ba8500135061e64d9e2b3480ed25125 | 7,188 | gooddata-server-oauth2 | Apache License 2.0 |
app/src/main/java/com/oxapps/materialcountdown/util/TimeHelper.kt | Flozzo | 46,596,362 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Text": 1, "Markdown": 1, "Proguard": 1, "Java": 4, "XML": 35, "Kotlin": 13} | /*
* Copyright 2018 <NAME>
*
* 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.oxapps.materialcountdown.util
import com.oxapps.materialcountdown.R
import java.util.concurrent.TimeUnit
data class RemainingTimeValue(val unitsLeft: Int, val unitText: Int)
internal fun getRemainingTimeValues(remainingMillis: Long): RemainingTimeValue {
val timeUnit: Int
val timeValue: Int
when {
remainingMillis >= TimeUnit.DAYS.toMillis(2) -> {
timeValue = TimeUnit.MILLISECONDS.toDays(remainingMillis).toInt()
timeUnit = R.string.days_remaining
}
remainingMillis >= TimeUnit.DAYS.toMillis(1) -> {
timeValue = 1
timeUnit = R.string.day_remaining
}
remainingMillis >= TimeUnit.HOURS.toMillis(2) -> {
timeValue = TimeUnit.MILLISECONDS.toHours(remainingMillis).toInt()
timeUnit = R.string.hours_remaining
}
remainingMillis >= TimeUnit.HOURS.toMillis(1) -> {
timeValue = 1
timeUnit = R.string.hour_remaining
}
remainingMillis >= TimeUnit.MINUTES.toMillis(2) -> {
timeValue = TimeUnit.MILLISECONDS.toMinutes(remainingMillis).toInt()
timeUnit = R.string.minutes_remaining
}
else -> {
timeValue = 1
timeUnit = R.string.minute_remaining
}
}
return RemainingTimeValue(timeValue, timeUnit)
}
| 1 | null | 1 | 1 | 3eb52ad33004f6c76b45afdb9f2911afc0e6b805 | 1,953 | MaterialCountdown | Apache License 2.0 |
app/src/main/java/bry1337/github/io/creditnotebook/presentation/persontransaction/TransactionListAdapter.kt | Bry1337 | 196,964,188 | false | null | package bry1337.github.io.creditnotebook.presentation.persontransaction
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import bry1337.github.io.creditnotebook.R
import bry1337.github.io.creditnotebook.databinding.ItemPersonTransactionBinding
import bry1337.github.io.creditnotebook.model.Finance
import bry1337.github.io.creditnotebook.util.OnBindViewHolder
/**
* Created by edwardbryan.abergas on 07/24/2019.
*
* @author [email protected]
*/
class TransactionListAdapter : RecyclerView.Adapter<TransactionListAdapter.TransactionViewHolder>() {
private lateinit var financeList: List<Finance>
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TransactionViewHolder {
val binding: ItemPersonTransactionBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.context),
R.layout.item_person_transaction, parent, false)
return TransactionViewHolder(binding)
}
override fun getItemCount(): Int {
return if(::financeList.isInitialized) financeList.size else 0
}
override fun onBindViewHolder(holder: TransactionViewHolder, position: Int) {
holder.onBind(financeList[position])
}
fun updateFinanceList(financeList: List<Finance>){
this.financeList = financeList
notifyDataSetChanged()
}
inner class TransactionViewHolder(private val binding: ItemPersonTransactionBinding) : RecyclerView.ViewHolder(
binding.root), OnBindViewHolder<Finance> {
private val viewModel = TransactionViewModel()
override fun onBind(obj: Finance) {
viewModel.bind(obj)
binding.viewModel = viewModel
}
}
} | 0 | Kotlin | 0 | 1 | 7f486a4097aac180504751b67b2e0bbea63eb0cd | 1,715 | super-duper-giggle | MIT License |
app/src/main/java/org/simple/clinic/facility/alertchange/AlertFacilityChangeSheet.kt | simpledotorg | 132,515,649 | false | null | package org.simple.clinic.facility.alertchange
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.f2prateek.rx.preferences2.Preference
import kotlinx.parcelize.Parcelize
import org.simple.clinic.R
import org.simple.clinic.databinding.SheetAlertFacilityChangeBinding
import org.simple.clinic.di.injector
import org.simple.clinic.facility.alertchange.Continuation.ContinueToActivity
import org.simple.clinic.facility.alertchange.Continuation.ContinueToScreen_Old
import org.simple.clinic.facility.change.FacilityChangeScreen
import org.simple.clinic.feature.Features
import org.simple.clinic.mobius.ViewRenderer
import org.simple.clinic.navigation.v2.ExpectsResult
import org.simple.clinic.navigation.v2.Router
import org.simple.clinic.navigation.v2.ScreenKey
import org.simple.clinic.navigation.v2.ScreenResult
import org.simple.clinic.navigation.v2.Succeeded
import org.simple.clinic.navigation.v2.compat.wrap
import org.simple.clinic.navigation.v2.fragments.BaseBottomSheet
import org.simple.clinic.router.ScreenResultBus
import org.simple.clinic.router.screen.FullScreenKey
import org.simple.clinic.router.util.resolveFloat
import java.util.Locale
import javax.inject.Inject
import javax.inject.Named
class AlertFacilityChangeSheet :
BaseBottomSheet<
AlertFacilityChangeSheet.Key,
SheetAlertFacilityChangeBinding,
AlertFacilityChangeModel,
AlertFacilityChangeEvent,
AlertFacilityChangeEffect,
Unit>(),
ExpectsResult {
@Inject
lateinit var locale: Locale
@Inject
@Named("is_facility_switched")
lateinit var isFacilitySwitchedPreference: Preference<Boolean>
@Inject
lateinit var features: Features
@Inject
lateinit var screenResults: ScreenResultBus
@Inject
lateinit var router: Router
override fun defaultModel() = AlertFacilityChangeModel()
override fun uiRenderer(): ViewRenderer<AlertFacilityChangeModel> {
return object : ViewRenderer<AlertFacilityChangeModel> {
override fun render(model: AlertFacilityChangeModel) {
// Nothing to render here
}
}
}
override fun bindView(inflater: LayoutInflater, container: ViewGroup?) =
SheetAlertFacilityChangeBinding.inflate(inflater, container, false)
private val currentFacilityName
get() = screenKey.currentFacilityName
private val continuation
get() = screenKey.continuation
private val facilityName
get() = binding.facilityName
private val yesButton
get() = binding.yesButton
private val changeButton
get() = binding.changeButton
override fun onAttach(context: Context) {
super.onAttach(context)
context.injector<Injector>().inject(this)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return super.onCreateDialog(savedInstanceState).apply {
window!!.setDimAmount(0F)
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (isFacilitySwitchedPreference.get().not()) {
view.postDelayed(::closeSheetWithContinuation, 100)
} else {
showDialogUi()
facilityName.text = getString(R.string.alertfacilitychange_facility_name, currentFacilityName)
yesButton.setOnClickListener {
proceedToNextScreen()
}
changeButton.setOnClickListener {
openFacilityChangeScreen()
}
}
}
private fun showDialogUi() {
val backgroundDimAmount = requireContext().resolveFloat(android.R.attr.backgroundDimAmount)
requireDialog().window!!.setDimAmount(backgroundDimAmount)
binding.root.visibility = View.VISIBLE
}
override fun onScreenResult(requestType: Parcelable, result: ScreenResult) {
if (requestType == ChangeCurrentFacility && result is Succeeded) {
proceedToNextScreen()
}
}
private fun proceedToNextScreen() {
isFacilitySwitchedPreference.set(false)
closeSheetWithContinuation()
}
private fun closeSheetWithContinuation() {
when (continuation) {
is ContinueToScreen_Old -> {
val screenKey = (continuation as ContinueToScreen_Old).screenKey
router.replaceTop(screenKey.wrap())
}
is ContinueToActivity -> {
val (intent, requestCode) = (continuation as ContinueToActivity).run {
intent to requestCode
}
requireActivity().startActivityForResult(intent, requestCode)
router.pop()
}
is Continuation.ContinueToScreen -> {
val screenKey = (continuation as Continuation.ContinueToScreen).screenKey
router.replaceTop(screenKey)
}
is Continuation.ContinueToScreenExpectingResult -> {
val screenKey = (continuation as Continuation.ContinueToScreenExpectingResult).screenKey
val requestType = (continuation as Continuation.ContinueToScreenExpectingResult).requestType
router.replaceTopExpectingResult(requestType, screenKey)
}
}
}
private fun openFacilityChangeScreen() {
router.pushExpectingResult(ChangeCurrentFacility, FacilityChangeScreen.Key())
}
@Parcelize
data class Key(
val currentFacilityName: String,
val continuation: Continuation
) : ScreenKey() {
override val analyticsName = "Alert Facility Change"
override val type = ScreenType.Modal
override fun instantiateFragment() = AlertFacilityChangeSheet()
}
interface Injector {
fun inject(target: AlertFacilityChangeSheet)
}
@Parcelize
object ChangeCurrentFacility : Parcelable
}
sealed class Continuation : Parcelable {
@Parcelize
data class ContinueToScreen_Old(val screenKey: FullScreenKey) : Continuation()
@Parcelize
data class ContinueToScreen(val screenKey: ScreenKey) : Continuation()
@Parcelize
data class ContinueToScreenExpectingResult(
val requestType: Parcelable,
val screenKey: ScreenKey
) : Continuation()
@Parcelize
data class ContinueToActivity(val intent: Intent, val requestCode: Int) : Continuation()
}
| 4 | null | 72 | 220 | 1a0bb8c0cfcec3988a0d6864d73786d0099c2286 | 6,158 | simple-android | MIT License |
playerFeature/src/main/java/com/yes/player/presentation/ui/EqualizerViewTest.kt | Yeroshin | 561,680,210 | false | {"Kotlin": 372924} | package com.yes.player.presentation.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.ui.unit.times
@Preview
@Composable
fun EqualizerViewTest(/*value1: Int, value2: Int, value3: Int, value4: Int, value5: Int*/) {
val value1 = 80
val value2 = 40
val value3 =25
val value4 = 20
val value5 = 2
val columnCount = 5
val columnSpacing = 4.dp
val maxColumnHeight = listOf(value1, value2, value3, value4, value5).maxOrNull() ?: 0
val screenWidth = LocalConfiguration.current.screenWidthDp.dp
val squareSize = (screenWidth / columnCount )
val columnHeights = listOf(value1, value2, value3, value4, value5)
.map { (it / 100f) * maxColumnHeight }
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Bottom
) {
repeat(maxColumnHeight) { heightIndex ->
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(columnSpacing)
) {
repeat(columnCount) { columnIndex ->
val columnHeight = columnHeights[columnIndex]
val squareColor = if (heightIndex < columnHeight) Color.White else Color.Black
Box(
modifier = Modifier
.size(squareSize)
.offset(y = -(heightIndex * (squareSize / 2)))
.background(squareColor)
)
}
}
}
}
} | 0 | Kotlin | 1 | 3 | f64f02e058d4db19444bcb19ea0ac093c91a96de | 2,234 | YES_MusicPlayer | MIT License |
tree-leaf/src/main/kotlin/org/hchery/treeleaf/service/crypto/KeyManage.kt | hchery | 799,787,264 | false | {"Kotlin": 60401, "Java": 11448} | package org.hchery.treeleaf.service.crypto
import org.hchery.treeleaf.dao.AesKeyDao
import org.hchery.treeleaf.dao.CryptoKeyDao
import org.hchery.treeleaf.db.key.AesKeyDbModel
import org.hchery.treeleaf.db.key.KeyDbModel
import org.springframework.stereotype.Service
import javax.crypto.KeyGenerator
/**
* DATE: 2024/5/29
* AUTHOR: hchery
* URL: https://github.com/hchery
* EMAIL: <EMAIL>
*/
interface KeyResolve<T : KeyDbModel> {
operator fun invoke(keyName: String, func: () -> T): T
}
abstract class AbstractKeyService<T : KeyDbModel>(private val dao: CryptoKeyDao<T>) : KeyResolve<T> {
private val keyMap = dao.findAll().associateBy { it.name }.toMutableMap()
override fun invoke(keyName: String, func: () -> T): T {
return keyMap[keyName] ?: func().also { keyMap[keyName] = dao.save(it) }
}
}
internal fun makeNewAesKey(): ByteArray {
val keyGenerator = KeyGenerator.getInstance("AES").apply { init(256) }
return keyGenerator.generateKey().encoded
}
interface AesKeyResolve : KeyResolve<AesKeyDbModel>
@Service
class AesKeyService(dao: AesKeyDao): AbstractKeyService<AesKeyDbModel>(dao), AesKeyResolve
| 0 | Kotlin | 0 | 0 | 5a1467c90ac14937a8f3cdbcb5403c264363daa7 | 1,153 | TreeLeaf | MIT License |
app/src/main/java/com/handysparksoft/ainimations/ui/theme/Color.kt | davidasensio | 637,809,073 | false | null | package com.handysparksoft.ainimations.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)
val Lime = Color(0xFFC6F16D)
val DarkBackground = Color(0xBE293545)
| 0 | Kotlin | 0 | 0 | 951b84af1d5d0cfab4800433ee699e4cbe7803bd | 364 | AiNimations | MIT License |
src/test/kotlin/com/github/cramer/gradle/jasperreports/utils/CompilationUtilsTest.kt | f-cramer | 769,405,116 | false | {"Kotlin": 27536} | package com.github.cramer.gradle.jasperreports.utils
import assertk.assertThat
import assertk.assertions.isNotNull
import assertk.assertions.isTrue
import com.github.fcramer.gradle.jasperreports.commons.CompilationTask
import com.github.fcramer.gradle.jasperreports.commons.TaskConfiguration
import com.github.fcramer.gradle.jasperreports.utils.compileReport
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.io.File
import java.nio.file.Files
class CompilationUtilsTest {
@Test
fun testCompilation(@TempDir directory: File?) {
val fileName = "Blank"
val input = File(directory, "$fileName.jrxml")
writeFile("/" + input.name, input)
val output = File(directory, "$fileName.jasper")
val tmp = File(directory, "tmp")
assertThat(tmp.mkdirs(), name = "temporary directory was created or did already exists").isTrue()
val configuration = TaskConfiguration(compiler = null, isValidateXml = true, isKeepJava = false, tmpDir = tmp)
compileReport(CompilationTask(input, output, configuration))
}
private fun writeFile(resource: String, file: File) {
CompilationUtilsTest::class.java.getResourceAsStream(resource)!!.use { input ->
assertThat(input, name = "resource").isNotNull()
Files.newOutputStream(file.toPath()).use { output ->
input.copyTo(output)
}
}
}
}
| 2 | Kotlin | 0 | 1 | 71d9050d1554c0ee87eb32994640c141ea9201cc | 1,444 | jasperreports-gradle-plugin | Apache License 2.0 |
app/src/main/java/com/ucsm/tylersai/amsteacher/model/SectionClass.kt | hanlinag | 290,556,091 | false | null | package com.ucsm.tylersai.amsteacher.model
data class SectionClass(
var teachingsubject :String,
var year: String,
var sectionname: String
){
constructor():this("","","")
} | 0 | null | 2 | 4 | 2ea4e1408c3b74d89f4a9594a6e81994715f958b | 189 | ams-teacher | MIT License |
beagle/src/test/kotlin/br/com/zup/beagle/android/logger/BeagleMessageLogsTest.kt | ZupIT | 391,144,851 | false | null | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* 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 br.com.zup.beagle.android.logger
import br.com.zup.beagle.android.mockdata.makeRequestData
import br.com.zup.beagle.android.mockdata.makeResponseData
import br.com.zup.beagle.android.setup.BeagleEnvironment
import br.com.zup.beagle.android.testutil.RandomData
import br.com.zup.beagle.core.ServerDrivenComponent
import io.mockk.Runs
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.slot
import io.mockk.unmockkAll
import io.mockk.verify
import org.junit.Assert.assertEquals
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
@DisplayName("Given a BeagleMessageLogs")
internal class BeagleMessageLogsTest {
private val beagleLoggerInfoSlot = slot<String>()
val exception = mockk<java.lang.Exception>()
@BeforeEach
fun setUp() {
mockkObject(BeagleEnvironment)
every { BeagleEnvironment.beagleSdk.logger } returns null
every { BeagleEnvironment.beagleSdk.config.isLoggingEnabled } returns true
mockkObject(BeagleLoggerProxy)
every { BeagleLoggerProxy.info(capture(beagleLoggerInfoSlot)) } just Runs
every { BeagleLoggerProxy.warning(any()) } just Runs
every { BeagleLoggerProxy.error(any()) } just Runs
every { BeagleLoggerProxy.error(any(), any()) } just Runs
}
@AfterEach
fun tearDown() {
unmockkAll()
}
@DisplayName("When trying to receive or pass invalid data")
@Nested
inner class Exception {
@Test
@DisplayName("Then the log Http RequestData should call BeagleLogger info")
fun `check message log for RequestData`() {
// Given
val requestData = makeRequestData()
// When
BeagleMessageLogs.logHttpRequestData(requestData)
// Then
assertEquals("""
*** HTTP REQUEST ***
Uri=${requestData.uri}
Method=${requestData.method}
Headers=${requestData.headers}
Body=${requestData.body}
""".trimIndent(), beagleLoggerInfoSlot.captured)
}
@Test
@DisplayName("Then the log Http ResponseData should call BeagleLogger info")
fun `check message log for ResponseData`() {
// Given
val responseData = makeResponseData()
// When
BeagleMessageLogs.logHttpResponseData(responseData)
// Then
assertEquals("""
*** HTTP RESPONSE ***
StatusCode=${responseData.statusCode}
Body=${String(responseData.data)}
Headers=${responseData.headers}
""".trimIndent(), beagleLoggerInfoSlot.captured)
}
@Test
@DisplayName("Then the log to invalid http client should call BeagleLogger info")
fun `check message log for http client`() {
// Given
val throwable = mockk<Throwable>()
// When
BeagleMessageLogs.logUnknownHttpError(throwable)
// Then
verify(exactly = 1) {
BeagleLoggerProxy.error(
"Exception thrown while trying to call http client.", throwable)
}
}
@Test
@DisplayName("Then the log to invalid deserialization should call BeagleLogger info")
fun `check message log for invalid deserialization`() {
// Given
val json = RandomData.string()
// When
BeagleMessageLogs.logDeserializationError(json, exception)
// Then
verify(exactly = 1) {
BeagleLoggerProxy.error(
"Exception thrown while trying to deserialize the following json: $json", exception)
}
}
@Test
@DisplayName("Then the log to WidgetViewFactory not found should call BeagleLogger info")
fun `check message log for WidgetViewFactory not found`() {
// Given
val widget = mockk<ServerDrivenComponent>()
// When
BeagleMessageLogs.logViewFactoryNotFound(widget)
// Then
val message = """
Did you miss to create a WidgetViewFactory for Widget ${widget::class.java.simpleName}
""".trimIndent()
verify(exactly = 1) { BeagleLoggerProxy.warning(message) }
}
@Test
@DisplayName("Then the log of support for action bar should call BeagleLogger info")
fun `check message log for support action bar`() {
// When
BeagleMessageLogs.logActionBarAlreadyPresentOnView(exception)
// Then
verify(exactly = 1) { BeagleLoggerProxy.error("SupportActionBar is already present", exception) }
}
@Test
@DisplayName("Then the form validation log should call BeagleLogger info")
fun `check message log for form not found`() {
// Given
val validator = RandomData.string()
// When
BeagleMessageLogs.logFormValidatorNotFound(validator)
// Then
verify(exactly = 1) { BeagleLoggerProxy.warning("Validation with name '$validator' were not found!") }
}
@Test
@DisplayName("Then the log to form input not found should call BeagleLogger info")
fun `check log for form input not found`() {
// Given
val formActionName = RandomData.string()
// When
BeagleMessageLogs.logFormInputsNotFound(formActionName)
// Then
verify(exactly = 1) {
BeagleLoggerProxy.warning("Are you missing to declare your FormInput for " +
"form action '$formActionName'?")
}
}
@Test
@DisplayName("Then form submission not found log should call BeagleLogger information")
fun `check the log for attempting to submit a form`() {
// Given
val formActionName = RandomData.string()
// When
BeagleMessageLogs.logFormSubmitNotFound(formActionName)
// Then
verify(exactly = 1) {
BeagleLoggerProxy.warning("Are you missing to declare your FormSubmit component for " +
"form action '$formActionName'?")
}
}
@Test
@DisplayName("Then the context access log should call BeagleLogger info")
fun `check log for context access`() {
// When
BeagleMessageLogs.errorWhileTryingToAccessContext(exception)
// Then
verify(exactly = 1) {
BeagleLoggerProxy.error(
"Error while evaluating expression bindings.", exception)
}
}
@Test
@DisplayName("Then the context change log should call BeagleLogger info")
fun `check the log for change context`() {
// When
BeagleMessageLogs.errorWhileTryingToChangeContext(exception)
// Then
verify(exactly = 1) { BeagleLoggerProxy.error("Error while trying to change context.", exception) }
}
}
@Test
@DisplayName("Then the log to attempt to notify the change of context should call BeagleLogger info")
fun `check the message log to context change attempt`() {
// When
BeagleMessageLogs.errorWhileTryingToNotifyContextChanges(exception)
// Then
verify(exactly = 1) {
BeagleLoggerProxy.error("Error while trying to notify context changes.", exception)
}
}
@Test
@DisplayName("Then the log to attempt to evaluate binding should call BeagleLogger info")
fun `check the evaluate binding attempt log`() {
// When
BeagleMessageLogs.errorWhileTryingToEvaluateBinding(exception)
// Then
verify(exactly = 1) {
BeagleLoggerProxy.error("Error while trying to evaluate binding.", exception)
}
}
@Test
@DisplayName("Then the log to attempt to multiple expressions should call BeagleLogger info")
fun `check the attempt log to use multiple expressions in a type that is not string`() {
// When
BeagleMessageLogs.multipleExpressionsInValueThatIsNotString()
// Then
verify(exactly = 1) {
BeagleLoggerProxy.warning(
"You are trying to use multiple expressions in a type that is not string!")
}
}
@Test
@DisplayName("Then the color parses log should call Beagle Logger info")
fun `check the message log for attempted parses color`() {
val color = RandomData.string()
// When
BeagleMessageLogs.errorWhenMalformedColorIsProvided(color, exception)
// Then
verify(exactly = 1) {
BeagleLoggerProxy.error(
"Could not parses color $color", exception)
}
}
@Test
@DisplayName("Then the message log to not found value should call BeagleLogger info")
fun `check the message log to not found value`() {
val value = RandomData.string()
// When
BeagleMessageLogs.errorWhenExpressionEvaluateNullValue(value)
// Then
verify(exactly = 1) {
BeagleLoggerProxy.error("Could not found value for $value")
}
}
@Test
@DisplayName("Then the message log for the invalid simple form should call BeagleLogger info")
fun `check the attempt message log found simple form not found`() {
// When
BeagleMessageLogs.logNotFoundSimpleForm()
// Then
verify(exactly = 1) {
BeagleLoggerProxy.error("Not found simple form in the parents")
}
}
@Test
@DisplayName("Then in an attempt to set an invalid image the log should call BeagleLogger info")
fun `check the message log when an invalid image is set`() {
val image = RandomData.string()
// When
BeagleMessageLogs.errorWhileTryingToSetInvalidImage(image, exception)
// Then
verify(exactly = 1) {
BeagleLoggerProxy.error("Could not find image $image", exception)
}
}
@Test
@DisplayName("Then in an attempt to use a reserved keyword in a Global Context the log " +
"should call BeagleLogger info")
fun `check the message log to global keyword reserved in a global context`() {
// When
BeagleMessageLogs.globalKeywordIsReservedForGlobalContext()
// Then
verify(exactly = 1) {
BeagleLoggerProxy.warning("Context name global is a reserved keyword for Global Context only")
}
}
@Test
@DisplayName("Then in an attempt to parse an expression")
fun `check the message log to parse an expression`() {
val expression = RandomData.string()
// When
BeagleMessageLogs.errorWhileTryingParseExpressionFunction(expression, exception)
// Then
verify(exactly = 1) {
BeagleLoggerProxy.error("Error while trying to parse expression: $expression", exception)
}
}
@Test
@DisplayName("Then in an attempt to execute an expression function")
fun `check the message log to execute an expression function`() {
// When
BeagleMessageLogs.errorWhileTryingExecuteExpressionFunction(exception)
// Then
verify(exactly = 1) {
BeagleLoggerProxy.error("Error while trying to execute expression function.", exception)
}
}
@Test
@DisplayName("Then in an attempt to found a nonexistent function")
fun `check the log to found a nonexistent function`() {
val functionName = RandomData.string()
// When
BeagleMessageLogs.functionWithNameDoesNotExist(functionName)
// Then
verify(exactly = 1) {
BeagleLoggerProxy.warning("Function with named $functionName does not exist.")
}
}
@Test
@DisplayName("Then in an attempt to put a child in a view with a specific id")
fun `check the log to put a child in a view with a specific id`() {
val id = RandomData.string()
// When
BeagleMessageLogs.errorWhileTryingToAddViewWithAddChildrenAction(id)
// Then
verify(exactly = 1) {
BeagleLoggerProxy.error("The view with id:$id cannot receive children")
}
}
@Test
@DisplayName("Then in an attempt to add a prefetch in an expression")
fun `check the log to add a prefetch in an expression`() {
// When
BeagleMessageLogs.expressionNotSupportInPreFetch()
// Then
verify(exactly = 1) {
BeagleLoggerProxy.warning("Expression is not support in prefetch")
}
}
@DisplayName("When cannot get property value")
@Nested
inner class CanNotGetPropertyValue {
@DisplayName("Then should call BeagleLoggerProxy warning")
@Test
fun testCanNotGetPropertyValue() {
//given
val propertyName = "property"
val expectedMessage = "Cannot get some attributes of property $propertyName."
//when
BeagleMessageLogs.cannotGetPropertyValue(propertyName)
//then
verify(exactly = 1) { BeagleLoggerProxy.warning(expectedMessage) }
}
}
}
| 1 | null | 2 | 9 | 812a330777edd79a123495e9f678dc8f25a019f7 | 14,113 | beagle-android | Apache License 2.0 |
kase-gradle-dsl/src/main/kotlin/com/rickbusarow/kase/gradle/dsl/model/FunctionCall.kt | rickbusarow | 692,975,358 | false | {"Kotlin": 896283, "Shell": 4226} | /*
* Copyright (C) 2023 Rick Busarow
* 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.rickbusarow.kase.gradle.dsl.model
import com.rickbusarow.kase.gradle.DslLanguage
import com.rickbusarow.kase.gradle.DslLanguage.GroovyDsl
import com.rickbusarow.kase.gradle.DslLanguageSettings.InfixSupport
import com.rickbusarow.kase.gradle.DslLanguageSettings.InfixSupport.NoInfix
import com.rickbusarow.kase.gradle.DslLanguageSettings.LabelSupport
import com.rickbusarow.kase.gradle.DslLanguageSettings.LabelSupport.NoLabels
import com.rickbusarow.kase.gradle.DslLanguageSettings.PropertyAccessSupport
import dev.drewhamilton.poko.Poko
/**
* *Attempts to* model the special behaviors around how Kotlin and
* Groovy handle `set___(...)` functions that were defined in Java.
*
* ### In Kotlin
* - You can always still use `setFoo(...)` in Kotlin
* - a `setFoo(T t)` function will be rewritten to support
* property access (`foo = t`) if `t` is assignable to `foo`
* - a `setFoo(T t)` function will stay `setFoo(t: T)` if `t` is not assignable to `foo` (if it
* needs some sort of transformation before setting, like setting an `Int` to a `String`)
*
* ### In Groovy
* - You can always still use `setFoo(...)` in Groovy
* - You can use `foo = t` in Groovy if `t` is directly assignable to `foo`
* - You can use the infix `foo t` function in Groovy if `t` is directly assignable to `foo`
* - This also supports labels, e.g. `foo bar: t`
*
* @property propertyName the name of the "property" if property
* access is used, like "foo" for a `setFoo(...)` function
* @property propertyAccessSupport whether to use property
* access in the function call, such as `foo = t`
* @property labelSupport whether to use labels in the function call, such as `group = "com.acme"`
* @property infixSupport whether to use infix in the function call, such as `foo t`
* @property parameter the new value to be set
* @since 0.1.0
*/
@Poko
public class SetterFunctionCall public constructor(
public val propertyName: String,
public val propertyAccessSupport: PropertyAccessSupport,
public val labelSupport: LabelSupport,
public val infixSupport: InfixSupport,
public val parameter: ValueParameter
) : DslElement {
override fun write(language: DslLanguage): String {
return when {
language.useInfix &&
language.supports(infixSupport) &&
language.supports(propertyAccessSupport) -> FunctionCall(
name = propertyName,
labelSupport = NoLabels,
infixSupport = infixSupport,
parameterList = ParameterList(parameter)
).write(language)
language.supports(propertyAccessSupport) -> ValueAssignment.SetterAssignment(
name = propertyName,
dslStringFactory = parameter
).write(language)
else -> FunctionCall(
name = "set$propertyName",
labelSupport = labelSupport,
infixSupport = infixSupport,
parameterList = ParameterList(parameter)
).write(language)
}
}
}
/**
* A function call
*
* @property name the name of the function, such as `exclude`
* @property labelSupport whether to use labels in the function call, such as `group = "com.acme"`
* @property infixSupport whether to use infix in the function call, such as `foo t`
* @property parameterList the list of parameters to pass to the function
* @since 0.1.0
*/
@Poko
public class FunctionCall(
public val name: String,
public val labelSupport: LabelSupport,
public val infixSupport: InfixSupport,
public val parameterList: ParameterList
) : DslElement {
public constructor(
name: String,
labelSupport: LabelSupport,
infixSupport: InfixSupport,
vararg parameters: Parameter?
) : this(
name = name,
labelSupport = labelSupport,
infixSupport = infixSupport,
parameterList = ParameterList(parameters.filterNotNull())
)
public constructor(
name: String,
parameters: List<Parameter>
) : this(
name = name,
labelSupport = NoLabels,
infixSupport = NoInfix,
parameterList = ParameterList(parameters)
)
public constructor(
name: String,
labelSupport: LabelSupport,
infixSupport: InfixSupport,
parameters: List<Parameter>
) : this(
name = name,
labelSupport = labelSupport,
infixSupport = infixSupport,
parameterList = ParameterList(parameters)
)
public constructor(
name: String,
vararg parameters: Parameter?
) : this(
name = name,
labelSupport = NoLabels,
infixSupport = NoInfix,
parameters = parameters.filterNotNull()
)
public constructor(
name: String,
vararg parameters: String
) : this(
name = name,
parameters = parameters.map { Parameter(it) },
labelSupport = NoLabels,
infixSupport = NoInfix
)
override fun write(language: DslLanguage): String {
return language.write { "$name${parameterList.write(language, labelSupport, infixSupport)}" }
}
}
/**
* Wraps [content] in parentheses if it's necessary for this syntax, or
* if this language is [GroovyDsl] and [GroovyDsl.useInfix] is `true`.
*
* @param content the content to parenthesize, e.g. `exclude group: "com.acme", module: "rocket"`
* @param infixSupport overrides the default behavior of
* the language's [useInfix][DslLanguage.useInfix] setting
* @return the parenthesized content, e.g. `(exclude group: "com.acme", module: "rocket")`
* @since 0.1.0
*/
public fun DslLanguage.parens(content: DslElement, infixSupport: InfixSupport? = null): String {
return parens(content.write(this), infixSupport)
}
| 3 | Kotlin | 0 | 0 | 75805a3d47b246b247f2d98ec4514b0c4385b06e | 6,095 | kase | Apache License 2.0 |
linea/src/commonMain/kotlin/compose/icons/lineaicons/arrows/SquareDown.kt | DevSrSouza | 311,134,756 | false | {"Kotlin": 36719092} | package compose.icons.lineaicons.arrows
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Bevel
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.lineaicons.ArrowsGroup
public val ArrowsGroup.SquareDown: ImageVector
get() {
if (_squareDown != null) {
return _squareDown!!
}
_squareDown = Builder(name = "SquareDown", defaultWidth = 64.0.dp, defaultHeight = 64.0.dp,
viewportWidth = 64.0f, viewportHeight = 64.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Bevel,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(15.0f, 24.0f)
lineToRelative(17.0f, 17.0f)
lineToRelative(17.0f, -17.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(1.0f, 1.0f)
horizontalLineToRelative(62.0f)
verticalLineToRelative(62.0f)
horizontalLineToRelative(-62.0f)
close()
}
}
.build()
return _squareDown!!
}
private var _squareDown: ImageVector? = null
| 17 | Kotlin | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 2,009 | compose-icons | MIT License |
ktor-io/wasmJs/src/io/ktor/utils/io/ByteChannelWasm.kt | ktorio | 40,136,600 | false | {"Kotlin": 6826990, "C": 453568, "Python": 948, "JavaScript": 775, "HTML": 336, "Mustache": 77, "Handlebars": 9} | /*
* Copyright 2014-2023 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.utils.io
import io.ktor.utils.io.core.*
import io.ktor.utils.io.core.internal.*
import io.ktor.utils.io.internal.*
import kotlinx.coroutines.*
/**
* Creates buffered channel for asynchronous reading and writing of sequences of bytes.
*/
@Suppress("DEPRECATION")
public actual fun ByteChannel(autoFlush: Boolean): ByteChannel {
return ByteChannelJS(ChunkBuffer.Empty, autoFlush)
}
/**
* Creates channel for reading from the specified byte array.
*/
public actual fun ByteReadChannel(content: ByteArray, offset: Int, length: Int): ByteReadChannel {
if (content.isEmpty()) return ByteReadChannel.Empty
@Suppress("DEPRECATION")
val head = ChunkBuffer.Pool.borrow()
var tail = head
var start = offset
val end = start + length
while (true) {
tail.reserveEndGap(8)
val size = minOf(end - start, tail.writeRemaining)
@Suppress("DEPRECATION")
(tail as Buffer).writeFully(content, start, size)
start += size
if (start == end) break
val current = tail
@Suppress("DEPRECATION")
tail = ChunkBuffer.Pool.borrow()
current.next = tail
}
return ByteChannelJS(head, false).apply { close() }
}
public actual suspend fun ByteReadChannel.joinTo(dst: ByteWriteChannel, closeOnEnd: Boolean) {
(this as ByteChannelSequentialBase).joinToImpl((dst as ByteChannelSequentialBase), closeOnEnd)
}
/**
* Reads up to [limit] bytes from receiver channel and writes them to [dst] channel.
* Closes [dst] channel if fails to read or write with cause exception.
* @return a number of copied bytes
*/
public actual suspend fun ByteReadChannel.copyTo(dst: ByteWriteChannel, limit: Long): Long {
return (this as ByteChannelSequentialBase).copyToSequentialImpl((dst as ByteChannelSequentialBase), limit)
}
@Suppress("DEPRECATION")
internal class ByteChannelJS(initial: ChunkBuffer, autoFlush: Boolean) : ByteChannelSequentialBase(initial, autoFlush) {
private var attachedJob: Job? = null
@OptIn(InternalCoroutinesApi::class)
@Deprecated(IO_DEPRECATION_MESSAGE)
override fun attachJob(job: Job) {
attachedJob?.cancel()
attachedJob = job
job.invokeOnCompletion(onCancelling = true) { cause ->
attachedJob = null
if (cause != null) {
cancel(cause.unwrapCancellationException())
}
}
}
override fun toString(): String = "ByteChannel[$attachedJob, ${hashCode()}]"
}
| 162 | Kotlin | 1017 | 12,440 | 1bc44e0715d4b7ffd9669a03a3fe02314c0b11b6 | 2,618 | ktor | Apache License 2.0 |
net.akehurst.kaf/common/realisation/src/jvm8Test/kotlin/common/test_ApplicationWithPortsAndActor.kt | dhakehurst | 166,023,488 | false | null | /**
* Copyright (C) 2019 Dr. <NAME> (http://dr.david.h.akehurst.net)
*
* 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 net.akehurst.kaf.common.realisation
import net.akehurst.kaf.common.api.*
import net.akehurst.kaf.service.commandLineHandler.api.CommandLineHandlerService
import net.akehurst.kaf.service.commandLineHandler.api.commandLineValue
import net.akehurst.kaf.service.commandLineHandler.simple.CommandLineHandlerSimple
import net.akehurst.kaf.service.configuration.api.ConfigurationService
import net.akehurst.kaf.service.configuration.api.configuredValue
import net.akehurst.kaf.service.configuration.map.ConfigurationMap
import net.akehurst.kaf.service.logging.api.LogLevel
import net.akehurst.kaf.service.logging.api.LoggingService
import net.akehurst.kaf.service.logging.console.LoggingServiceConsole
import kotlin.test.Test
class test_ApplicationWithPortsAndActor {
interface Output {
suspend fun writeln(text: String?)
}
class component_Greeter() : Component {
lateinit var port_display: Port
val handler = actor_Greeter()
override val af = afComponent {
port_display = port("display") { requires(Output::class) }
initialise = {
port_display.connectInternal(handler)
}
}
}
class actor_Greeter() : Actor {
interface Shutdown {
fun shutdown()
}
val output: Output by externalConnection()
val confGreeting: String by configuredValue("greeting") { "unknown" }
val greeting: String? by commandLineValue() { confGreeting }
override val af = afActor {
preExecute = { self ->
output.writeln(greeting)
self.af.receive(Shutdown::shutdown, asyncCallContext()) {
self.af.framework.shutdown()
}
}
}
}
class component_Console() : Component {
lateinit var port_output: Port
val handler = actor_Console()
override val af = afComponent {
port_output = port("output") { provides(Output::class) }
initialise = {
port_output.connectInternal(handler)
}
}
}
class actor_Console() : Actor, Output {
override val af = afActor()
override suspend fun writeln(text: String?) {
println(text)
}
}
class TestApplication(afId: String) : Application {
val greeter = component_Greeter()
val console = component_Console()
override val af = afApplication(this,afId) {
defineService(ConfigurationService::class) {
ConfigurationMap(mutableMapOf(
"sut.greeter.handler.greeting" to "Hello World!"
))
}
defineService(LoggingService::class) { LoggingServiceConsole(LogLevel.ALL) }
defineService(CommandLineHandlerService::class) { commandLineArgs -> CommandLineHandlerSimple(commandLineArgs) }
initialise = {
greeter.port_display.connectPort(console.port_output)
}
}
}
@Test
fun test() {
val sut = TestApplication("sut")
sut.af.startBlocking(listOf())
}
}
| 0 | Kotlin | 0 | 0 | f74c333396998ad2ead9e5cdd964f88ac4af44d4 | 3,806 | net.akehurst.kaf | Apache License 2.0 |
core/src/main/kotlin/com/huskerdev/openglfx/effects/GLShaderEffectPeer.kt | husker-dev | 393,363,130 | false | {"Kotlin": 114168, "C": 39584, "C++": 17027, "CMake": 1781} | package com.huskerdev.openglfx.effects
import com.sun.scenario.effect.Crop
class GLShaderEffectPeer: Crop(null) {
} | 6 | Kotlin | 7 | 52 | 6cc02edbb639101c08a9e9fc6bb796bc55c991a8 | 118 | openglfx | Apache License 2.0 |
ClienteApiRest/app/src/main/java/Api/MainActivityViewModel.kt | aranzabe | 405,328,026 | false | null | package Api
import Modelo.User
import Modelo.Usuario
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
class MainActivityViewModel : ViewModel() {
val myResponse: MutableLiveData<Usuario> = MutableLiveData()
val myResponseList: MutableLiveData<List<Usuario>> = MutableLiveData()
fun getPost(id:Int) {
viewModelScope.launch {
myResponse.value = UserNetwork.retrofit.getUsuario(id)
}
}
fun getPosts() {
viewModelScope.launch {
myResponseList.value = UserNetwork.retrofit.getUsuarios()
}
}
} | 0 | null | 0 | 1 | aa74da85a1893ee45dc0852bb15b664fe09edb78 | 676 | android | MIT License |
src/main/kotlin/TextUtils.kt | uk-gov-mirror | 356,709,418 | false | null | class TextUtils {
private val qualifiedTablePattern = Regex(Config.Hbase.qualifiedTablePattern)
private val coalescedNames = mapOf("agent_core:agentToDoArchive" to "agent_core:agentToDo")
fun topicNameTableMatcher(topicName: String) = qualifiedTablePattern.find(topicName)
fun coalescedName(tableName: String) =
if (coalescedNames[tableName] != null) coalescedNames[tableName] else tableName
}
| 0 | null | 0 | 0 | 9015c4827e4599ba44ee96735d929d456df4f4cd | 421 | dwp.streaming-data-importer | MIT License |
event-aggregator/src/main/kotlin/io/kommons/designpatterns/event/aggregator/emitters/Scout.kt | debop | 235,066,649 | false | null | package io.kommons.designpatterns.event.aggregator.emitters
import io.kommons.designpatterns.event.aggregator.Event.WARSHIPS_APPROACHING
import io.kommons.designpatterns.event.aggregator.EventEmitter
import io.kommons.designpatterns.event.aggregator.EventObserver
import io.kommons.designpatterns.event.aggregator.Weekday
import io.kommons.designpatterns.event.aggregator.Weekday.TUESDAY
/**
* Scout produces events
*/
class Scout(vararg obs: EventObserver): EventEmitter(*obs) {
override fun timePasses(day: Weekday) {
if (day == TUESDAY) {
notifyObservers(WARSHIPS_APPROACHING)
}
}
} | 0 | Kotlin | 11 | 53 | c00bcc0542985bbcfc4652d0045f31e5c1304a70 | 626 | kotlin-design-patterns | Apache License 2.0 |
app/src/main/java/software/ehsan/newsfeed/data/exception/BaseException.kt | EhsanMashhadi | 587,488,394 | false | null | package software.ehsan.newsfeed.data.exception
open class BaseException: Exception() | 0 | Kotlin | 0 | 0 | 4eca40b718f31f58e63c3d5e0f5cce32ec41a372 | 85 | NewsFeed | Apache License 2.0 |
gradle-plugin/devkit/src/main/kotlin/com/dailystudio/devbricksx/DevKitPlugin.kt | dailystudio | 264,874,323 | false | {"Java": 1002565, "Kotlin": 855589, "Shell": 6356, "HTML": 1286} | package com.dailystudio.devbricksx
import com.android.build.api.dsl.CommonExtension
import com.android.build.api.variant.AndroidComponentsExtension
import com.google.devtools.ksp.gradle.KspExtension
import org.gradle.api.*
import org.gradle.kotlin.dsl.create
import org.gradle.kotlin.dsl.getByType
import org.gradle.kotlin.dsl.project
import kotlin.reflect.KClass
class DevKitPlugin: Plugin<Project> {
companion object {
const val EXTENSION_NAME = "devKit"
}
override fun apply(project: Project) {
val config = project.extensions.create<DevKitExtension>(EXTENSION_NAME)
val kspPluginApplied = project.plugins.hasPlugin("com.google.devtools.ksp")
val isApplication = project.plugins.hasPlugin("com.android.application")
val androidComponentsExtension = project.extensionByType(
AndroidComponentsExtension::class) ?: return
androidComponentsExtension.onVariants { variant ->
val useAnnotation = config.useAnnotations.get()
val compileType = try {
CompileType.valueOf(config.compileType.get())
} catch (e: Exception) {
println("failed to parse compile type [error: $e], use default [${CompileType.Library}]")
CompileType.Library
}
val devKitComps = config.devKitComps.get().mapNotNull {
try {
Components.valueOf(it)
} catch (e: Exception) {
println("failed to parse component from [$it, error: $e], skip")
null
}
}
val roomVersion = Dependencies.ROOM_VERSION
val devBricksXVersion = Dependencies.DEV_BRICKS_X_VERSION
val targetName = "${project.name}.${variant.name}"
println(separatorLineToWrap(targetName))
println("DevKit configuration: [${targetName}]")
println(separatorLineToWrap(targetName))
println("|- Project type: [${if (isApplication) "Application" else "Library"}]")
println("|- Compile type: [$compileType]")
println("|- Use annotation: [$useAnnotation]")
println("|- Components: $devKitComps")
println("`- Dependencies:")
println(" |- Room: [$roomVersion]")
println(" `- DevBricksX: [$devBricksXVersion]")
println()
if (useAnnotation && !kspPluginApplied) {
println("applying KSP(Kotlin Symbol Processing) plug-in")
with(project) {
plugins.apply("com.google.devtools.ksp")
}
}
val nameOfConfig = if (isApplication) {
"implementation"
} else {
"api"
}
project.dependencies.apply {
if (compileType == CompileType.Project) {
add(nameOfConfig, project(":devbricksx"))
} else {
add(nameOfConfig,"cn.dailystudio:devbricksx:${devBricksXVersion}")
}
}
for (comp in devKitComps) {
val artifactName = comp.toString().toLowerCase()
project.dependencies.apply {
if (compileType == CompileType.Project) {
add(nameOfConfig, project(":devbricksx-${artifactName}"))
} else {
add(nameOfConfig,"cn.dailystudio:devbricksx-${artifactName}:${devBricksXVersion}")
}
}
}
if (useAnnotation) {
val commonExtension = project.extensionByType(CommonExtension::class)
commonExtension?.sourceSets?.configureEach {
kotlin.srcDir("${project.buildDir}/generated/ksp/$name/kotlin/")
}
val kspExtension = project.extensionByType(KspExtension::class)
kspExtension?.arg("room.schemaLocation", "${project.projectDir}/schemas")
project.dependencies.apply {
if (compileType == CompileType.Project) {
add("ksp", project(":devbricksx-compiler"))
} else {
add("ksp","cn.dailystudio:devbricksx-compiler:${devBricksXVersion}")
}
add("ksp", "androidx.room:room-compiler:${roomVersion}")
}
}
}
}
}
fun separatorLineToWrap(artifactName: String): String {
return buildString {
for (i in 0 until artifactName.length + 25) {
append('-')
}
}
}
fun <T : Any> Project.extensionByType(
klass: KClass<T>): T? {
return try {
extensions.getByType(klass)
} catch (e: UnknownDomainObjectException) {
println("unable to get extension for type [$klass]: $e")
null
}
}
| 1 | Java | 6 | 63 | 942f967e5451ac9c67717c074ebebf8d0be33d73 | 4,937 | devbricksx-android | Apache License 2.0 |
src/main/kotlin/me/branchpanic/mods/stockpile/StockpileClient.kt | BernardoGrigiastro | 375,697,481 | true | {"Kotlin": 102549, "Java": 1098} | package me.branchpanic.mods.stockpile
import me.branchpanic.mods.stockpile.content.blockentity.ItemBarrelBlockEntity
import me.branchpanic.mods.stockpile.content.client.BarrelHatKeyListener
import me.branchpanic.mods.stockpile.content.client.gui.OverlayRenderer
import me.branchpanic.mods.stockpile.content.client.gui.UpgradeOverlayRenderer
import me.branchpanic.mods.stockpile.content.client.gui.UpgradeRemoverOverlayRenderer
import me.branchpanic.mods.stockpile.content.client.renderer.ItemBarrelRenderer
import net.fabricmc.api.ClientModInitializer
import net.fabricmc.api.EnvType
import net.fabricmc.api.Environment
import net.fabricmc.fabric.api.client.keybinding.FabricKeyBinding
import net.fabricmc.fabric.api.client.keybinding.KeyBindingRegistry
import net.fabricmc.fabric.api.client.rendereregistry.v1.BlockEntityRendererRegistry
import net.fabricmc.fabric.api.event.client.ClientTickCallback
import net.minecraft.client.MinecraftClient
import net.minecraft.client.util.InputUtil
import net.minecraft.util.hit.HitResult
import net.minecraft.world.RayTraceContext
import org.lwjgl.glfw.GLFW
@Environment(EnvType.CLIENT)
object StockpileClient : ClientModInitializer {
val BARREL_HAT_KEY: FabricKeyBinding = FabricKeyBinding.Builder.create(
Stockpile.id("barrel_hat"),
InputUtil.Type.KEYSYM,
GLFW.GLFW_KEY_G,
"controls.stockpile"
).build()
private val overlays: List<OverlayRenderer> = listOf(
UpgradeOverlayRenderer(),
UpgradeRemoverOverlayRenderer()
)
override fun onInitializeClient() {
BlockEntityRendererRegistry.INSTANCE.register(ItemBarrelBlockEntity.TYPE, ::ItemBarrelRenderer)
KeyBindingRegistry.INSTANCE.addCategory("controls.stockpile")
KeyBindingRegistry.INSTANCE.register(BARREL_HAT_KEY)
ClientTickCallback.EVENT.register(BarrelHatKeyListener)
}
fun drawOverlays(partialTicks: Float) {
// Adapted from HWYLA:
// https://github.com/TehNut/HWYLA/blob/9d83ceb1d36733f11f9502378426626de246a7bf/src/main/java/mcp/mobius/waila/overlay/RayTracing.java#L62
val mc = MinecraftClient.getInstance()
val interactionManager = mc.interactionManager ?: return
val player = mc.player ?: return
val world = mc.world ?: return
val playerReach = interactionManager.reachDistance
val eyePosition = player.getCameraPosVec(partialTicks)
val lookVector = player.getRotationVec(partialTicks)
val traceEnd =
eyePosition.add(lookVector.x * playerReach, lookVector.y * playerReach, lookVector.z * playerReach)
val context = RayTraceContext(
eyePosition,
traceEnd,
RayTraceContext.ShapeType.OUTLINE,
RayTraceContext.FluidHandling.NONE,
player
)
val result = world.rayTrace(context)
if (result.type != HitResult.Type.BLOCK) {
return
}
overlays.forEach { o ->
o.draw(world, player.mainHandStack, result.blockPos)
}
}
}
| 0 | null | 0 | 0 | eea85a487ebe3c33566f5244d83e28a5ced3e400 | 3,068 | stockpile | MIT License |
app/src/main/java/com/rosi/masts/mvc/view/ViewManager.kt | sr01 | 387,141,087 | false | null | package com.rosi.masts.mvc.view
import com.rosi.masts.base.actor.*
import com.rosi.masts.di.DependencyProvider
import com.rosi.masts.mvc.*
import com.rosi.masts.mvc.control.Controller
import com.rosi.masts.mvc.model.media.MediaController
import com.rosi.masts.mvc.view.android.activity.keybinding.KeyBindingActivityActor
import com.rosi.masts.mvc.view.android.activity.main.MainActivityActor
import com.rosi.masts.utils.Logger
import com.rosi.masts.mvc.view.stt.JavaToJni
import com.rosi.masts.mvc.view.stt.JniToJava
import com.rosi.masts.mvc.view.stt.JniToJavaActor
class ViewManager(controller: Controller, override val name: String, deps: DependencyProvider) : Actor(name, deps.logger, deps.generalScope) {
private val tag = "ViewManager"
override val logger: Logger = deps.logger
private var isServiceRunning = false
val jniToJavaActor = JniToJavaActor(controller, deps.settings, "view-manager/jni-to-java-actor", logger, deps.generalScope)
private val appController: MediaController = deps.mediaController
private val jniToJava: JniToJava = deps.jniToJava
private val javaToJni: JavaToJni = deps.javaToJni
val keyBindingActivityActor = KeyBindingActivityActor(controller, "view-manager/key-binding-activity-actor", logger, deps.mainScope)
val mainActivityActor = MainActivityActor(controller, this, deps.stringsProvider, "view-manager/main-activity-actor", logger, deps.mainScope)
init {
initJavaToJni()
}
override suspend fun receive(message: Message) {
super.receive(message)
when (message) {
is GetServiceStatus -> {
logger.testPrint(tag, "receive, GetServiceStatus")
this send message.withServiceStatus(isServiceRunning) to message.recipient
}
is ServiceStatusChanged -> {
this.isServiceRunning = message.isRunning
this send message to mainActivityActor
}
is KeyDetectedMessage -> this send message to keyBindingActivityActor
is InputKeyMessage -> this send message to appController
is SelectActionMessage -> this send message to keyBindingActivityActor
is SelectKeyMessage -> this send message to keyBindingActivityActor
is BindSuccessMessage -> this send message to keyBindingActivityActor
is GetAvailableActionsMessage -> this send message to keyBindingActivityActor
is RemoveKeyActionBindingMessage -> this send message to mainActivityActor
is ImportKeyBindingsMessage -> this send message to mainActivityActor
is ShareKeyBindingsMessage -> this send message to mainActivityActor
else -> printUnknownMessage(message)
}
}
private fun initJavaToJni() {
try {
println("[SR.Test] =================== JavaToJniInit ===================")
jniToJava.init(jniToJavaActor, logger)
javaToJni.JavaToJniInit()
javaToJni.InitArmMcuCom()
println("[SR.Test] JniControl loaded successfully")
logger.i(tag, "JniControl.isArmMcuComOpen: " + javaToJni.isArmMcuComOpen())
} catch (t: Throwable) {
println("[SR.Test] Failed to load JniControl, $t")
}
}
}
| 0 | Kotlin | 0 | 0 | 01f998fefea75370bb9f00535cb8ccee31700c4d | 3,298 | FineSTT | Apache License 2.0 |
SearchNBlogWithoutAds/app/src/main/java/kr/esens/searchnblogwithoutads/LoadingDialog.kt | ESENS12 | 275,990,883 | false | null | package kr.esens.searchnblogwithoutads
import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
class LoadingDialog(context: Context) : Dialog(context) {
init {
setCanceledOnTouchOutside(false)
window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
setContentView(R.layout.dialog_loading)
}
} | 0 | Kotlin | 0 | 0 | 82268e856a0bda1024bc3a3aa29fafa855dbee40 | 415 | Kotlin | MIT License |
src/main/kotlin/icu/windea/pls/lang/util/CwtConfigManager.kt | DragonKnightOfBreeze | 328,104,626 | false | {"Kotlin": 3434785, "Java": 164698, "Lex": 42127, "HTML": 23578, "Shell": 2822} | package icu.windea.pls.lang.util
import com.intellij.psi.*
import com.intellij.psi.util.*
import icu.windea.pls.*
import icu.windea.pls.config.*
import icu.windea.pls.config.config.*
import icu.windea.pls.config.config.internal.*
import icu.windea.pls.config.configGroup.*
import icu.windea.pls.config.expression.internal.*
import icu.windea.pls.core.*
import icu.windea.pls.cwt.*
import icu.windea.pls.cwt.psi.*
import icu.windea.pls.ep.configGroup.*
import icu.windea.pls.lang.*
import icu.windea.pls.model.*
import java.util.*
object CwtConfigManager {
/**
* @param forRepo 是否兼容插件或者规则仓库中的CWT文件(此时将其视为规则文件)。
*/
fun getContainingConfigGroup(element: PsiElement, forRepo: Boolean = false): CwtConfigGroup? {
if(element.language != CwtLanguage) return null
val file = element.containingFile ?: return null
val vFile = file.virtualFile ?: return null
val project = file.project
val fileProviders = CwtConfigGroupFileProvider.EP_NAME.extensionList
val configGroup = fileProviders.firstNotNullOfOrNull { fileProvider ->
fileProvider.getContainingConfigGroup(vFile, project)
}
if(configGroup != null) return configGroup
runCatchingCancelable r@{
if(!forRepo) return@r
val workDirectory = vFile.toNioPath().toFile().parentFile ?: return@r
val command = "git remote -v"
val commandResult = executeCommand(command, CommandType.POWER_SHELL, null, workDirectory)
val gameTypeId = commandResult.lines()
.mapNotNull { it.splitByBlank(3).getOrNull(1) }
.firstNotNullOfOrNull t@{
if(it.contains("Paradox-Language-Support")) return@t "core"
val s = it.substringInLast("cwtools-", "-config", "")
if(s.isNotEmpty()) return@t s
null
} ?: return@r
val gameType = ParadoxGameType.resolve(gameTypeId)
return getConfigGroup(project, gameType)
}
return null
}
fun getConfigPath(element: PsiElement): CwtConfigPath? {
if(element is CwtFile || element is CwtRootBlock) return CwtConfigPath.Empty
if(element !is CwtMemberElement) return null
return doGetConfigPathFromCache(element)
}
private fun doGetConfigPathFromCache(element: CwtMemberElement): CwtConfigPath? {
//invalidated on file modification
return CachedValuesManager.getCachedValue(element, PlsKeys.cachedConfigPath) {
val file = element.containingFile ?: return@getCachedValue null
val value = doGetConfigPath(element)
CachedValueProvider.Result.create(value, file)
}
}
private fun doGetConfigPath(element: CwtMemberElement): CwtConfigPath? {
var current: PsiElement = element
var depth = 0
val subPaths = LinkedList<String>()
while(current !is PsiFile) {
when {
current is CwtProperty -> {
subPaths.addFirst(current.name)
depth++
}
current is CwtValue && current.isBlockValue() -> {
subPaths.addFirst("-")
depth++
}
}
current = current.parent ?: break
}
if(current !is CwtFile) return null //unexpected
return CwtConfigPath.resolve(subPaths)
}
fun getConfigType(element: PsiElement): CwtConfigType? {
if(element !is CwtMemberElement) return null
return doGetConfigTypeFromCache(element)
}
private fun doGetConfigTypeFromCache(element: CwtMemberElement): CwtConfigType? {
//invalidated on file modification
return CachedValuesManager.getCachedValue(element, PlsKeys.cachedConfigType) {
val file = element.containingFile ?: return@getCachedValue null
val value = when(element) {
is CwtProperty -> doGetConfigType(element)
is CwtValue -> doGetConfigType(element)
else -> null
}
CachedValueProvider.Result.create(value, file)
}
}
private fun doGetConfigType(element: CwtMemberElement): CwtConfigType? {
val configPath = element.configPath
if(configPath == null || configPath.isEmpty()) return null
val path = configPath.path
return when {
element is CwtProperty && path.matchesAntPattern("types/type[*]") -> {
CwtConfigType.Type
}
element is CwtProperty && path.matchesAntPattern("types/type[*]/subtype[*]") -> {
CwtConfigType.Subtype
}
element is CwtProperty && path.matchesAntPattern("types/type[*]/modifiers/**") -> {
when {
configPath.get(3).surroundsWith("subtype[", "]") -> {
if(configPath.length == 5) return CwtConfigType.Modifier
}
else -> {
if(configPath.length == 4) return CwtConfigType.Modifier
}
}
null
}
element is CwtProperty && path.matchesAntPattern("enums/enum[*]") -> {
CwtConfigType.Enum
}
element is CwtValue && path.matchesAntPattern("enums/enum[*]/*") -> {
CwtConfigType.EnumValue
}
element is CwtProperty && path.matchesAntPattern("enums/complex_enum[*]") -> {
CwtConfigType.ComplexEnum
}
element is CwtProperty && path.matchesAntPattern("values/value[*]") -> {
CwtConfigType.DynamicValueType
}
element is CwtValue && path.matchesAntPattern("values/value[*]/*") -> {
CwtConfigType.DynamicValue
}
element is CwtProperty && path.matchesAntPattern("inline[*]") -> {
CwtConfigType.Inline
}
element is CwtProperty && path.matchesAntPattern("single_alias[*]") -> {
CwtConfigType.SingleAlias
}
element is CwtProperty && path.matchesAntPattern("alias[*]") -> {
val aliasName = configPath.get(0).substringIn('[', ']', "").substringBefore(':', "")
when {
aliasName == "modifier" -> return CwtConfigType.Modifier
aliasName == "trigger" -> return CwtConfigType.Trigger
aliasName == "effect" -> return CwtConfigType.Effect
}
CwtConfigType.Alias
}
element is CwtProperty && path.matchesAntPattern("links/*") -> {
CwtConfigType.Link
}
element is CwtProperty && path.matchesAntPattern("localisation_links/*") -> {
CwtConfigType.LocalisationLink
}
element is CwtProperty && path.matchesAntPattern("localisation_commands/*") -> {
CwtConfigType.LocalisationCommand
}
element is CwtProperty && path.matchesAntPattern("modifier_categories/*") -> {
CwtConfigType.ModifierCategory
}
element is CwtProperty && path.matchesAntPattern("modifiers/*") -> {
CwtConfigType.Modifier
}
element is CwtProperty && path.matchesAntPattern("scopes/*") -> {
CwtConfigType.Scope
}
element is CwtProperty && path.matchesAntPattern("scope_groups/*") -> {
CwtConfigType.ScopeGroup
}
element is CwtProperty && path.matchesAntPattern("database_object_types/*") -> {
CwtConfigType.DatabaseObjectType
}
element is CwtProperty && path.matchesAntPattern("system_scopes/*") -> {
CwtConfigType.SystemScope
}
element is CwtProperty && path.matchesAntPattern("localisation_locales/*") -> {
CwtConfigType.LocalisationLocale
}
path.matchesAntPattern("scripted_variables/*") -> {
CwtConfigType.ExtendedScriptedVariable
}
path.matchesAntPattern("definitions/*") -> {
CwtConfigType.ExtendedDefinition
}
path.matchesAntPattern("game_rules/*") -> {
CwtConfigType.ExtendedGameRule
}
path.matchesAntPattern("on_actions/*") -> {
CwtConfigType.ExtendedOnAction
}
path.matchesAntPattern("inline_scripts/*") -> {
CwtConfigType.ExtendedInlineScript
}
path.matchesAntPattern("parameters/*") -> {
CwtConfigType.ExtendedParameter
}
path.matchesAntPattern("complex_enum_values/*/*") -> {
CwtConfigType.ExtendedComplexEnumValue
}
path.matchesAntPattern("dynamic_values/*/*") -> {
CwtConfigType.ExtendedDynamicValue
}
else -> null
}
}
fun getPathPatterns(configs: Collection<CwtConfig<*>>): Set<String> {
val patterns = sortedSetOf<String>()
configs.forEach { config -> collectPathPatterns(config, patterns) }
return patterns
}
fun collectPathPatterns(config: CwtConfig<*>, patterns: MutableCollection<String>) {
val path = when(config) {
is CwtTypeConfig -> config.path
is CwtComplexEnumConfig -> config.path
else -> null
}
val pathFile = when(config) {
is CwtTypeConfig -> config.pathFile
is CwtComplexEnumConfig -> config.pathFile
else -> null
}
val pathExtension = when(config) {
is CwtTypeConfig -> config.pathExtension
is CwtComplexEnumConfig -> config.pathExtension
else -> null
}
val pathStrict = when(config) {
is CwtTypeConfig -> config.pathStrict
is CwtComplexEnumConfig -> config.pathStrict
else -> false
}
val pattern = buildString {
if(path != null) {
append(path)
if(pathStrict) append("/") else append("/**")
}
if(pathFile!= null) {
if(path != null) append("/")
append(pathFile)
} else if(pathExtension != null) {
if(path != null) append("/")
append("*.").append(pathExtension)
}
}
if(pattern.isNotEmpty()) patterns += pattern
//TODO 1.3.20
}
fun matchesPath(config: CwtConfig<*>, path: ParadoxPath): Boolean {
TODO() //TODO 1.3.20
}
fun getConfigByPathExpression(configGroup: CwtConfigGroup, pathExpression: String): List<CwtMemberConfig<*>> {
val separatorIndex = pathExpression.indexOf('#')
if(separatorIndex == -1) return emptyList()
val filePath = pathExpression.substring(0, separatorIndex)
if(filePath.isEmpty()) return emptyList()
val fileConfig = configGroup.files[filePath] ?: return emptyList()
val configPath = pathExpression.substring(separatorIndex + 1)
if(configPath.isEmpty()) return emptyList()
val pathList = configPath.split('/')
var r: List<CwtMemberConfig<*>> = emptyList()
pathList.forEach { p ->
if(p == "-") {
if(r.isEmpty()) {
r = fileConfig.values
} else {
r = buildList {
r.forEach { c1 ->
c1.configs?.forEach { c2 ->
if(c2 is CwtValueConfig) this += c2
}
}
}
}
} else {
if(r.isEmpty()) {
r = fileConfig.properties.filter { c -> c.key == p }
} else {
r = buildList {
r.forEach { c1 ->
c1.configs?.forEach { c2 ->
if(c2 is CwtPropertyConfig && c2.key == p) this += c2
}
}
}
}
}
if(r.isEmpty()) return emptyList()
}
return r
}
fun getContextConfigs(element: PsiElement, containerElement: PsiElement, schema: CwtSchemaConfig): List<CwtMemberConfig<*>> {
val configPath = getConfigPath(containerElement) ?: return emptyList()
var contextConfigs = mutableListOf<CwtMemberConfig<*>>()
contextConfigs += schema.properties
configPath.forEachIndexed f1@{ i, path ->
val flatten = i != configPath.length - 1 || !(element is CwtString && element.isPropertyValue())
val nextContextConfigs = mutableListOf<CwtMemberConfig<*>>()
contextConfigs.forEach f2@{ config ->
when(config) {
is CwtPropertyConfig -> {
val schemaExpression = CwtSchemaExpression.resolve(config.key)
if(!matchesSchemaExpression(path, schemaExpression, schema)) return@f2
nextContextConfigs += config
}
is CwtValueConfig -> {
if(path != "-") return@f2
nextContextConfigs += config
}
}
}
contextConfigs = nextContextConfigs
if(flatten) contextConfigs = contextConfigs.flatMapTo(mutableListOf()) { it.configs.orEmpty() }
}
return contextConfigs
}
fun matchesSchemaExpression(value: String, schemaExpression: CwtSchemaExpression, schema: CwtSchemaConfig): Boolean {
return when(schemaExpression) {
is CwtSchemaExpression.Constant -> {
schemaExpression.expressionString == value
}
is CwtSchemaExpression.Enum -> {
schema.enums[schemaExpression.name]?.values?.any { it.stringValue == value } ?: false
}
is CwtSchemaExpression.Template -> {
value.matchesPattern(schemaExpression.pattern)
}
is CwtSchemaExpression.Type -> {
true //fast check
}
is CwtSchemaExpression.Constraint -> {
false //fast check
}
}
}
}
| 9 | Kotlin | 4 | 37 | 4b3531109f2428f6f7e6be5abc9b5b27547950e8 | 14,691 | Paradox-Language-Support | MIT License |
serenity-asciidoc/src/test/kotlin/net/serenitybdd/reports/asciidoc/WhenGeneratingAnAsciidocReport.kt | cliviu | 219,955,490 | false | {"Gradle": 23, "Java Properties": 17, "INI": 24, "Markdown": 128, "Shell": 22, "Ignore List": 7, "Batchfile": 20, "Groovy": 282, "Git Attributes": 2, "Text": 99, "XML": 176, "HTML": 1249, "JSON": 584, "CSS": 324, "JavaScript": 737, "Gherkin": 58, "SCSS": 233, "SVG": 1377, "Less": 120, "Kotlin": 62, "Fluent": 32, "Java": 1786, "Maven POM": 6, "AsciiDoc": 3, "FreeMarker": 15, "XSLT": 1, "YAML": 18, "Gemfile.lock": 1, "EditorConfig": 1, "Browserslist": 1, "Ruby": 1, "JSON with Comments": 5, "robots.txt": 1, "PowerShell": 1, "Ant Build System": 1} | package net.serenitybdd.reports.asciidoc
import net.thucydides.model.util.EnvironmentVariables
import net.thucydides.model.util.MockEnvironmentVariables
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import java.io.File
import java.nio.file.Paths
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class WhenGeneratingAnAsciidocReport {
val TEST_OUTCOMES_WITH_A_SINGLE_TEST = ClassLoader.getSystemResource("test_outcomes/with_a_single_test").path
@Nested
inner class AllReports {
private val generatedReport : File
private val reportContents : String
private val environmentVariables : EnvironmentVariables = MockEnvironmentVariables()
init {
environmentVariables.setProperty("serenity.project.name","A Simple Cucumber Report")
environmentVariables.setProperty("project.version","1.2.3")
generatedReport = AsciidocReporter(environmentVariables).generateReportFrom(Paths.get(TEST_OUTCOMES_WITH_A_SINGLE_TEST))
reportContents = generatedReport.readText()
}
@Test
fun `should have a correct title`() {
assertThat(reportContents).contains("= A Simple Cucumber Report")
}
@Test
fun `should display the date the report was generated`() {
val expectedDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd-MMM-yyyy"))
assertThat(reportContents).contains(":revdate: ${expectedDate}")
}
@Test
fun `should include the current project version number`() {
assertThat(reportContents).contains(":revnumber: 1.2.3")
}
}
@Nested
inner class ReportsWithNarratives {
private val generatedReport : File
private val reportContents : String
private val environmentVariables : EnvironmentVariables = MockEnvironmentVariables()
init {
environmentVariables.setProperty("serenity.project.name","A Simple Cucumber Report")
environmentVariables.setProperty("project.version","1.2.3")
environmentVariables.setProperty("serenity.requirements.dir","src/test/resources/test_outcomes/with_a_single_test/features")
generatedReport = AsciidocReporter(environmentVariables).generateReportFrom(Paths.get(TEST_OUTCOMES_WITH_A_SINGLE_TEST))
reportContents = generatedReport.readText()
}
@Test
fun `should include the top level narrative`() {
assertThat(reportContents).contains("A Simple Cucumber Report")
}
@Test
fun `should convert markdown narratives to asciidoc`() {
assertThat(reportContents).contains("== Some details")
}
}
@Nested
inner class ReportsWithCapabilitiesAndFeatures {
private val generatedReport : File
private val reportContents : String
private val environmentVariables : EnvironmentVariables = MockEnvironmentVariables()
init {
environmentVariables.setProperty("serenity.project.name","A Simple Cucumber Report")
environmentVariables.setProperty("project.version","1.2.3")
environmentVariables.setProperty("serenity.requirements.dir","src/test/resources/test_outcomes/with_a_single_test/features")
generatedReport = AsciidocReporter(environmentVariables).generateReportFrom(Paths.get(TEST_OUTCOMES_WITH_A_SINGLE_TEST))
reportContents = generatedReport.readText()
}
@Test
fun `should include level 2 headings for each capability`() {
assertThat(reportContents).contains("== Capability: Application")
.contains("== Capability: Compliance")
.contains("== Capability: Monitoring")
}
@Test
fun `should include narrative texts for each capability`() {
assertThat(reportContents).contains("Client onboarding and vetting")
println(reportContents)
}
}
@Nested
inner class YouCanUseYourOwnTemplateBy {
private val environmentVariables : EnvironmentVariables = MockEnvironmentVariables()
private val customTemplatePath = File(ClassLoader.getSystemResource("custom_template/my_template.adoc").path)
@Test
fun `providing a custom asciidoc template using the asciidoc-dot-template system property and a full path`() {
environmentVariables.setProperty("asciidoc.template", customTemplatePath.path)
val generatedReport = AsciidocReporter(environmentVariables).generateReportFrom(Paths.get(TEST_OUTCOMES_WITH_A_SINGLE_TEST))
val reportContents = generatedReport.readText()
assertThat(reportContents).contains("My Custom Asciidoc Template")
}
@Test
fun `providing a custom asciidoc template using a relative path`() {
environmentVariables.setProperty("asciidoc.template", "src/test/resources/custom_template/my_template.adoc")
val generatedReport = AsciidocReporter(environmentVariables).generateReportFrom(Paths.get(TEST_OUTCOMES_WITH_A_SINGLE_TEST))
val reportContents = generatedReport.readText()
assertThat(reportContents).contains("My Custom Asciidoc Template")
}
}
}
| 1 | null | 1 | 1 | e7a9e9c6654a5e9a86cdb9cf88fbb063fcefad5c | 5,516 | serenity-core | Apache License 2.0 |
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/CreativeCommonsSa.kt | DevSrSouza | 311,134,756 | false | null | package compose.icons.lineawesomeicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Butt
import androidx.compose.ui.graphics.StrokeJoin.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.LineAwesomeIcons
public val LineAwesomeIcons.CreativeCommonsSa: ImageVector
get() {
if (_creativeCommonsSa != null) {
return _creativeCommonsSa!!
}
_creativeCommonsSa = Builder(name = "CreativeCommonsSa", defaultWidth = 32.0.dp,
defaultHeight = 32.0.dp, viewportWidth = 32.0f, viewportHeight = 32.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(16.0f, 3.0f)
curveTo(8.832f, 3.0f, 3.0f, 8.832f, 3.0f, 16.0f)
curveTo(3.0f, 23.168f, 8.832f, 29.0f, 16.0f, 29.0f)
curveTo(23.168f, 29.0f, 29.0f, 23.168f, 29.0f, 16.0f)
curveTo(29.0f, 8.832f, 23.168f, 3.0f, 16.0f, 3.0f)
close()
moveTo(16.0f, 5.0f)
curveTo(22.065f, 5.0f, 27.0f, 9.935f, 27.0f, 16.0f)
curveTo(27.0f, 22.065f, 22.065f, 27.0f, 16.0f, 27.0f)
curveTo(9.935f, 27.0f, 5.0f, 22.065f, 5.0f, 16.0f)
curveTo(5.0f, 9.935f, 9.935f, 5.0f, 16.0f, 5.0f)
close()
moveTo(16.0f, 10.0f)
curveTo(13.794f, 10.0f, 12.0f, 11.794f, 12.0f, 14.0f)
lineTo(10.0f, 14.0f)
lineTo(13.0f, 17.0f)
lineTo(16.0f, 14.0f)
lineTo(14.0f, 14.0f)
curveTo(14.0f, 12.897f, 14.897f, 12.0f, 16.0f, 12.0f)
curveTo(17.103f, 12.0f, 18.0f, 12.897f, 18.0f, 14.0f)
lineTo(18.0f, 18.0f)
curveTo(18.0f, 19.103f, 17.103f, 20.0f, 16.0f, 20.0f)
curveTo(15.263f, 20.0f, 14.6243f, 19.595f, 14.2773f, 19.0f)
lineTo(12.1426f, 19.0f)
curveTo(12.5896f, 20.721f, 14.141f, 22.0f, 16.0f, 22.0f)
curveTo(18.206f, 22.0f, 20.0f, 20.206f, 20.0f, 18.0f)
lineTo(20.0f, 14.0f)
curveTo(20.0f, 11.794f, 18.206f, 10.0f, 16.0f, 10.0f)
close()
}
}
.build()
return _creativeCommonsSa!!
}
private var _creativeCommonsSa: ImageVector? = null
| 17 | null | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 2,796 | compose-icons | MIT License |
app/src/main/java/com/xxxxx/myparking/models/AvailableCarsResponse.kt | carlosiniesta7 | 221,419,594 | false | null | package com.xxxxx.myparking.models
data class AvailableCarsResponse (
val success: Boolean,
val cars: List<Cars>
) | 0 | Kotlin | 0 | 0 | 364d574e7b4cd6dc3a6864bfc59522fb0b1883eb | 123 | Car2Reserve | Apache License 2.0 |
mobile/src/main/java/be/mygod/vpnhotspot/SettingsActivity.kt | snyiu100 | 116,776,835 | true | {"Kotlin": 38604} | package be.mygod.vpnhotspot
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import be.mygod.vpnhotspot.databinding.ActivitySettingsBinding
class SettingsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
DataBindingUtil.setContentView<ActivitySettingsBinding>(this, R.layout.activity_settings)
.toolbar.setNavigationOnClickListener({ navigateUp() })
}
}
| 0 | Kotlin | 0 | 0 | f341bf409e764fe91cb782e8d5f337c697f8397d | 534 | VPNHotspot | Apache License 2.0 |
src/main/java/com/cplusedition/bot/dsl/html/impl/Empty.kt | cplusedition | 412,142,025 | false | {"TypeScript": 3121002, "Java": 3005697, "JavaScript": 2745438, "HTML": 2273206, "Kotlin": 2011043, "CSS": 236922, "PureBasic": 147886, "LLVM": 117819, "Shell": 4832, "C": 4368, "M4": 603, "Makefile": 321} | /*!
C+edition for Desktop, Community Edition.
Copyright (C) 2021 Cplusedition Limited. All rights reserved.
The author licenses this file to You 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.cplusedition.bot.dsl.html.impl
import com.cplusedition.bot.core.bot
import com.cplusedition.bot.dsl.html.api.ICData
class CData(vararg content: String) : Text(*content), ICData {
override fun toString(): String {
return "<![CDATA[" + content.bot.joinln() + "]]>"
}
companion object {
private const val serialVersionUID = 1L
}
} | 0 | TypeScript | 0 | 0 | 801e52da05ab50b56df4a1a7fbeacb09f6b4fa2e | 1,108 | cplusedition-desktop-ce | Apache License 2.0 |
app/src/main/java/com/example/test/api/AsinProductResponse.kt | mohilcode | 636,133,705 | false | null | package com.example.test.api
data class AsinProductResponse(
val product: Product
)
data class Product(
val title: String,
val description: String
)
| 0 | Kotlin | 0 | 0 | d59733ae686612f6a96f48986ba3a06485d8d1bb | 164 | shopsmartscan | MIT License |
kotlin/akka-actor-model/src/main/kotlin/com/example/akkaactormodel/AkkaActorModelApplication.kt | fmuhic | 202,541,972 | false | {"Lua": 34751, "JavaScript": 9514, "Kotlin": 8168, "Assembly": 6979, "C++": 5790, "Shell": 5618, "C": 2124, "Python": 1709, "Go": 1404, "CMake": 1251, "Rust": 942, "Dockerfile": 691, "HTML": 477, "Makefile": 122, "CSS": 90} | package com.example.akkaactormodel
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class AkkaActorModelApplication
fun main(args: Array<String>) {
runApplication<AkkaActorModelApplication>(*args)
}
| 0 | Lua | 1 | 0 | c26a22d5b6e42320f308cd24d4ba1035b96463cf | 295 | junkyard | MIT License |
src/commonMain/kotlin/org/tix/serialize/TixSerializers.kt | ncipollo | 336,920,234 | false | {"Kotlin": 601503} | package org.tix.serialize
import kotlinx.serialization.json.Json
import kotlinx.serialization.modules.SerializersModule
import kotlinx.serialization.modules.contextual
import net.mamoe.yamlkt.Yaml
import org.tix.integrations.jira.issue.json.IssueFieldSerializer
import org.tix.serialize.dynamic.DynamicElement
import org.tix.serialize.dynamic.DynamicElementJsonSerializer
import org.tix.serialize.dynamic.DynamicElementYamlSerializer
object TixSerializers {
fun json() = Json {
encodeDefaults = false
prettyPrint = true
serializersModule = SerializersModule {
contextual(DynamicElementJsonSerializer)
contextual(IssueFieldSerializer)
}
}
fun yaml() = Yaml {
encodeDefaultValues = false
serializersModule = SerializersModule {
contextual(DynamicElementYamlSerializer)
}
}
}
fun Json.decodeDynamicElement(text: String) = decodeFromString(DynamicElementJsonSerializer, text)
fun Json.encodeDynamicElement(element: DynamicElement) = encodeToString(DynamicElementJsonSerializer, element)
fun Yaml.decodeDynamicElement(text: String) = decodeFromString(DynamicElementYamlSerializer, text)
fun Yaml.encodeDynamicElement(element: DynamicElement) = encodeToString(DynamicElementYamlSerializer, element) | 8 | Kotlin | 0 | 3 | 02f87c827c1159af055f5afc5481afd45c013703 | 1,307 | tix-core | MIT License |
app/src/main/java/vn/loitp/app/activity/customviews/layout/transformationlayout/single/TransformationSingleActivity.kt | tplloi | 126,578,283 | false | null | /*
* Designed and developed by 2020 skydoves (<NAME>)
*
* 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 vn.loitp.app.activity.customviews.layout.transformationlayout.single
import android.os.Bundle
import com.annotation.IsFullScreen
import com.annotation.LogTag
import com.core.base.BaseFontActivity
import vn.loitp.app.R
@LogTag("MainSingleActivity")
@IsFullScreen(false)
class TransformationSingleActivity : BaseFontActivity() {
override fun setLayoutResourceId(): Int {
return R.layout.activity_layout_transformation_single_main
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportFragmentManager
.beginTransaction()
.replace(R.id.layoutContainer, TransformationSingleFragment(), TransformationSingleFragment.TAG)
.commit()
}
}
| 0 | Kotlin | 0 | 6 | 4fe4c945e89819d77aaf6cb76f1de6bbff7868a5 | 1,386 | basemaster | Apache License 2.0 |
controls-opcua/src/main/kotlin/ru/mipt/npm/controls/opcua/client/MiloDevice.kt | mipt-npm | 240,888,288 | false | null | package space.kscience.controls.opcua.client
import kotlinx.coroutines.future.await
import kotlinx.serialization.json.Json
import org.eclipse.milo.opcua.sdk.client.OpcUaClient
import org.eclipse.milo.opcua.stack.core.types.builtin.*
import org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn
import space.kscience.controls.api.Device
import space.kscience.dataforge.meta.Meta
import space.kscience.dataforge.meta.MetaSerializer
import space.kscience.dataforge.meta.transformations.MetaConverter
/**
* An OPC-UA device backed by Eclipse Milo client
*/
public interface MiloDevice : Device {
/**
* The OPC-UA client initialized on first use
*/
public val client: OpcUaClient
override fun close() {
client.disconnect()
super.close()
}
}
/**
* Read OPC-UA value with timestamp
* @param T the type of property to read. The value is coerced to it.
*/
public suspend inline fun <reified T: Any> MiloDevice.readOpcWithTime(
nodeId: NodeId,
converter: MetaConverter<T>,
magAge: Double = 500.0
): Pair<T, DateTime> {
val data = client.readValue(magAge, TimestampsToReturn.Server, nodeId).await()
val time = data.serverTime ?: error("No server time provided")
val meta: Meta = when (val content = data.value.value) {
is T -> return content to time
is Meta -> content
is ExtensionObject -> content.decode(client.dynamicSerializationContext) as Meta
else -> error("Incompatible OPC property value $content")
}
val res: T = converter.metaToObject(meta) ?: error("Meta $meta could not be converted to ${T::class}")
return res to time
}
/**
* Read and coerce value from OPC-UA
*/
public suspend inline fun <reified T> MiloDevice.readOpc(
nodeId: NodeId,
converter: MetaConverter<T>,
magAge: Double = 500.0
): T {
val data: DataValue = client.readValue(magAge, TimestampsToReturn.Neither, nodeId).await()
val content = data.value.value
if(content is T) return content
val meta: Meta = when (content) {
is Meta -> content
//Always decode string as Json meta
is String -> Json.decodeFromString(MetaSerializer, content)
is Number -> Meta(content)
is Boolean -> Meta(content)
//content is ExtensionObject -> (content as ExtensionObject).decode(client.dynamicSerializationContext) as Meta
else -> error("Incompatible OPC property value $content")
}
return converter.metaToObject(meta) ?: error("Meta $meta could not be converted to ${T::class}")
}
public suspend inline fun <reified T> MiloDevice.writeOpc(
nodeId: NodeId,
converter: MetaConverter<T>,
value: T
): StatusCode {
val meta = converter.objectToMeta(value)
return client.writeValue(nodeId, DataValue(Variant(meta))).await()
} | 4 | Kotlin | 2 | 9 | a20fb97c02f6394fe49436f97373991bed2f8f6f | 2,822 | controls.kt | Apache License 2.0 |
app/src/main/java/com/yenaly/han1meviewer/ui/fragment/search/HMultiChoicesDialog.kt | YenalyLiew | 524,046,895 | false | null | package com.yenaly.han1meviewer.ui.fragment.search
import android.annotation.SuppressLint
import android.content.Context
import android.util.SparseArray
import android.view.View
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import androidx.core.util.size
import androidx.core.util.valueIterator
import androidx.core.view.isVisible
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.yenaly.han1meviewer.R
import com.yenaly.han1meviewer.logic.model.SearchOption
import com.yenaly.han1meviewer.ui.adapter.HSearchTagAdapter
import com.yenaly.han1meviewer.util.createAlertDialog
import com.yenaly.yenaly_libs.utils.findActivity
import com.yenaly.yenaly_libs.utils.view.SimpleFragmentStateAdapter
import com.yenaly.yenaly_libs.utils.view.attach
class HMultiChoicesDialog(
val context: Context,
@StringRes private val titleRes: Int,
private val hasSingleItem: Boolean = false
) {
companion object {
const val UNKNOWN_ADAPTER = -1
}
private val pageAdapter = SimpleFragmentStateAdapter(context.findActivity())
private val coreView = View.inflate(context, R.layout.pop_up_hanime_search_tag, null)
private val tab = coreView.findViewById<TabLayout>(R.id.tl_tag)
private val page = coreView.findViewById<ViewPager2>(R.id.vp_tag)
private val adapterMap: SparseArray<HSearchTagAdapter> = SparseArray()
private val nameResList = mutableListOf<Int>()
private var onSave: ((AlertDialog) -> Unit)? = null
private var onReset: ((AlertDialog) -> Unit)? = null
private var isAdded = false
private val dialog = context.createAlertDialog {
setTitle(titleRes)
setPositiveButton(R.string.save, null)
setNeutralButton(R.string.reset, null)
setView(coreView)
}
init {
page.adapter = pageAdapter
page.offscreenPageLimit = ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT
dialog.setOnShowListener { di ->
page.requestLayout()
val ad = di as AlertDialog
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
onSave?.invoke(ad)
}
dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener {
onReset?.invoke(ad)
}
}
}
private fun getTagScope(@StringRes scopeNameRes: Int): HSearchTagAdapter? =
adapterMap[scopeNameRes]
fun addTagScope(@StringRes scopeNameRes: Int?, items: List<SearchOption>?, spanCount: Int = 3) {
if (items.isNullOrEmpty() || isAdded) return
if (hasSingleItem) {
tab.isVisible = false
page.isUserInputEnabled = false
isAdded = true
}
val tagAdapter = HSearchTagAdapter()
adapterMap[scopeNameRes ?: UNKNOWN_ADAPTER] = tagAdapter
nameResList += scopeNameRes ?: UNKNOWN_ADAPTER
pageAdapter.addFragment { HCheckBoxFragment(tagAdapter, items, spanCount) }
}
fun setOnSaveListener(action: (AlertDialog) -> Unit) {
onSave = action
}
fun setOnResetListener(action: (AlertDialog) -> Unit) {
onReset = action
}
fun loadSavedTags(saved: SparseArray<Set<SearchOption>>) {
for (i in 0..<saved.size) {
val key = saved.keyAt(i)
val value = saved.valueAt(i)
getTagScope(key)?.let { adapter ->
adapter.checkedSet.clear()
adapter.checkedSet += value
}
}
}
@SuppressLint("NotifyDataSetChanged")
fun clearAllChecks() {
adapterMap.valueIterator().forEach { adapter ->
if (adapter.checkedSet.isNotEmpty()) {
adapter.checkedSet.clear()
adapter.notifyDataSetChanged()
}
}
}
fun collectCheckedTags(): SparseArray<Set<SearchOption>> {
return SparseArray<Set<SearchOption>>().apply {
for (i in 0..<adapterMap.size) {
val key = adapterMap.keyAt(i)
val value = adapterMap.valueAt(i)
if (value.checkedSet.isNotEmpty()) {
this[key] = value.checkedSet
}
}
}
}
fun show() {
if (!hasSingleItem) {
tab.attach(page) { tab, pos ->
tab.setText(nameResList[pos])
}
}
dialog.show()
}
} | 37 | null | 130 | 1,745 | ba816ad86628c3bf5e9b8af0987ddf2cb741fca8 | 4,433 | Han1meViewer | Apache License 2.0 |
src/main/kotlin/dev/turingcomplete/kotlinonetimepassword/OtpAuthUriBuilder.kt | marcelkliemannel | 119,086,726 | false | null | package dev.turingcomplete.kotlinonetimepassword
import dev.turingcomplete.kotlinonetimepassword.OtpAuthUriBuilder.Companion.forHotp
import dev.turingcomplete.kotlinonetimepassword.OtpAuthUriBuilder.Companion.forTotp
import java.io.ByteArrayOutputStream
import java.net.URI
import java.net.URLEncoder
import java.nio.ByteBuffer
import java.nio.CharBuffer
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
import java.util.*
import java.util.concurrent.TimeUnit
/**
* A builder to create an OTP Auth URI as defined in
* [Key Uri Format](https://github.com/google/google-authenticator/wiki/Key-Uri-Format).
* This URI contains all necessary information for a TOTP/HOTP client to set up
* the code generation.
*
* This URI can be used, for example, to be encoded into a QR code.
*
* An example OTP Auth URI would be:
* ```text
* otpauth://totp/Company:<EMAIL>?secret=SGWY3DPESRKFPHH&issuer=Company&digits=8&algorithm=SHA1
* ```
*
* Use the factory methods [forTotp]/[TimeBasedOneTimePasswordGenerator.otpAuthUriBuilder]
* or [forHotp]/[HmacOneTimePasswordGenerator.otpAuthUriBuilder] to create a/an
* TOTP/HOTP specific instance of an [OtpAuthUriBuilder].
*
* @param removePaddingFromBase32Secret if set to `true`, the Base32 padding
* character `=` will be removed from the `secret` URI parameter (e.g.,
* `MFQWC===` will be transformed to `MFQWC`.), this is required by the
* specification.
* @property charset the [Charset] to be used at various places inside this
* builder, for example, for the URL encoding.
*
* @see OtpAuthUriBuilder.Totp
* @see OtpAuthUriBuilder.Hotp
*/
open class OtpAuthUriBuilder<S : OtpAuthUriBuilder<S>>(private val type: String,
base32Secret: ByteArray,
removePaddingFromBase32Secret: Boolean = true,
private val charset: Charset = StandardCharsets.UTF_8) {
// -- Companion Object -------------------------------------------------------------------------------------------- //
companion object {
/**
* Creates a new [OtpAuthUriBuilder] for a __TOTP__ OTP Auth URI.
*
* @param base32Secret the secret as a Base32 encoded [ByteArray].
*
* @see TimeBasedOneTimePasswordGenerator.otpAuthUriBuilder
*/
fun forTotp(base32Secret: ByteArray): Totp {
return Totp(base32Secret)
}
/**
* Creates a new [OtpAuthUriBuilder] for a __HOTP__ OTP Auth URI.
*
* @param base32Secret the secret as a Base32 encoded [ByteArray].
*
* @see HmacOneTimePasswordGenerator.otpAuthUriBuilder
*/
fun forHotp(initialCounter: Long, base32Secret: ByteArray): Hotp {
return Hotp(initialCounter, base32Secret)
}
}
// -- Properties -------------------------------------------------------------------------------------------------- //
private val base32Secret: ByteArray
private var label: String? = null
protected var parameters = mutableMapOf<String, String>()
// -- Initialization ---------------------------------------------------------------------------------------------- //
init {
this.base32Secret = if (removePaddingFromBase32Secret) removePaddingFromBase32Secret(base32Secret) else base32Secret
}
// -- Exposed Methods --------------------------------------------------------------------------------------------- //
/**
* Sets the label path part of the URI, which consist of an account name
* and an optional issuer. Both values will be separated by a colon (`:`),
* which can be URL encoded by setting the parameter [encodeSeparator].
*
* The issuer is a provider or service to which the account name (for
* which the OTP code gets used) belongs to.
*
* The issuer and account name will be URL encoded.
*
* The OTP Auth URI specification recommends to always set this path part
* with both values. And if it is set, the [issuer] parameter should also be
* set.
*
* This is an _optional_ path part.
*/
fun label(accountName: String, issuer: String?, encodeSeparator: Boolean = false): S {
if (accountName.contains(":")
|| accountName.contains("%3A")
|| issuer?.contains(":") == true
|| issuer?.contains("%3A") == true) {
throw IllegalArgumentException("Neither the account name nor the issuer are allowed to contain a colon.")
}
val encodedAccountName = URLEncoder.encode(accountName, charset.name())
label = if (issuer != null) {
val colon = if (encodeSeparator) "%3A" else ":"
URLEncoder.encode(issuer, charset.name()) + colon + encodedAccountName
}
else {
encodedAccountName
}
@Suppress("UNCHECKED_CAST")
return this as S
}
/**
* Sets the `issuer` query parameter, which indicates the provider or service
* the account (for which the OTP code gets used) belongs to.
*
* The OTP Auth URI specification recommends to always set this parameter. And
* if it is set, the [label] path part should also be set.
*
* The value will be URL encoded.
*
* This is an _optional_ parameter.
*/
fun issuer(issuer: String): S {
parameters["issuer"] = URLEncoder.encode(issuer, StandardCharsets.UTF_8.name())
@Suppress("UNCHECKED_CAST")
return this as S
}
/**
* Sets the `algorithm` query parameter, which is the uppercase name of the
* HMAC algorithms defined in [HmacAlgorithm].
*
* This value is equivalent to the [TimeBasedOneTimePasswordConfig.hmacAlgorithm]
* and [HmacOneTimePasswordConfig.hmacAlgorithm] configuration.
*
* The Google Authenticator may ignore this value and always uses `SHA1`.
*
* This is an _optional_ parameter.
*/
fun algorithm(algorithm: HmacAlgorithm): S {
parameters["algorithm"] = algorithm.name
@Suppress("UNCHECKED_CAST")
return this as S
}
/**
* Sets the `digits` query parameter, which is the length of the generated
* code.
*
* This value is equivalent to the [TimeBasedOneTimePasswordConfig.codeDigits] and
* [HmacOneTimePasswordConfig.codeDigits] configuration.
*
* The Google Authenticator may ignore this value and always uses `6`.
*
* This is an _optional_ parameter.
*/
fun digits(digits: Int): S {
parameters["digits"] = digits.toString()
@Suppress("UNCHECKED_CAST")
return this as S
}
/**
* Builds the final OTP Auth URI as a [String].
*
* Warning: Handling the URI as a string may leak the secret into the String
* pool of the JVM. Consider using [buildToByteArray] instead.
*/
fun buildToString(): String {
return buildUriWithoutSecret(mapOf(Pair("secret", base32Secret.toString(charset))))
}
/**
* Builds the final OTP Auth URI as a [URI].
*
* Warning: Handling the URI as a string may leak the secret into the String
* pool of the JVM. Consider using [buildToByteArray] instead.
*/
fun buildToUri(): URI {
return URI(buildToString())
}
/**
* Builds the final OTP Auth URI as a [ByteArray].
*/
fun buildToByteArray(): ByteArray {
return ByteArrayOutputStream().apply {
write(buildUriWithoutSecret().toByteArray(charset))
write(if (parameters.isNotEmpty()) '&'.code else '?'.code)
write("secret=".toByteArray(charset))
write(base32Secret)
}.toByteArray()
}
// -- Private Methods --------------------------------------------------------------------------------------------- //
private fun buildUriWithoutSecret(additionalParameters: Map<String, String> = emptyMap()): String {
val query = parameters.plus(additionalParameters).map { "${it.key}=${it.value}" }.joinToString(separator = "&", prefix = "?")
return "otpauth://$type/${if (label != null) label else ""}$query"
}
private fun removePaddingFromBase32Secret(base32Secret: ByteArray): ByteArray {
val base32SecretByteBuffer = ByteBuffer.wrap(base32Secret)
val base32SecretCharBuffer: CharBuffer = charset.decode(base32SecretByteBuffer)
var cleanedBase32SecretLength = 0
val cleanedBase32SecretCharBuffer = CharBuffer.allocate(base32SecretCharBuffer.length)
for(i in base32SecretCharBuffer.indices) {
if (base32SecretCharBuffer[i] != '=') {
cleanedBase32SecretLength++
cleanedBase32SecretCharBuffer.put(i, base32SecretCharBuffer[i])
}
}
val cleanedBase32SecretByteBuffer = charset.encode(cleanedBase32SecretCharBuffer.subSequence(0, cleanedBase32SecretLength))
val cleanedBase32Secret = Arrays.copyOfRange(cleanedBase32SecretByteBuffer.array(),
cleanedBase32SecretByteBuffer.position(),
cleanedBase32SecretByteBuffer.limit())
// Clean up
// `base32SecretByteBuffer` holds a reference to the original array
Arrays.fill(base32SecretCharBuffer.array(), '-')
Arrays.fill(cleanedBase32SecretCharBuffer.array(), '-')
Arrays.fill(cleanedBase32SecretByteBuffer.array(), 0.toByte())
return cleanedBase32Secret
}
// -- Inner Type -------------------------------------------------------------------------------------------------- //
/**
* A builder for a TOTP OTP Auth URI.
*
* An instance should be created via [forTotp]
* or [TimeBasedOneTimePasswordGenerator.otpAuthUriBuilder].
*/
class Totp(base32Secret: ByteArray) : OtpAuthUriBuilder<Totp>("totp", base32Secret) {
/**
* Sets the `period` query parameter, which defines the validity of a TOTP
* code in seconds.
*
* This value is equivalent to the [TimeBasedOneTimePasswordConfig.timeStep] and
* [TimeBasedOneTimePasswordConfig.timeStepUnit] configuration.
*
* This is an _optional_ parameter.
*/
fun period(timeStep: Long, timeStepUnit: TimeUnit): Totp {
parameters["period"] = timeStepUnit.toSeconds(timeStep).toString()
return this
}
}
// -- Inner Type -------------------------------------------------------------------------------------------------- //
/**
* A builder for an HOTP OTP Auth URI.
*
* An instance should be created via [forHotp]
* or [HmacOneTimePasswordGenerator.otpAuthUriBuilder].
*
* @param initialCounter the initial [counter] value.
*/
class Hotp(initialCounter: Long, base32Secret: ByteArray) : OtpAuthUriBuilder<Hotp>("hotp", base32Secret) {
init {
counter(initialCounter)
}
/**
* Sets the `counter` parameter, which defines the initial counter value.
*
* This is a _required_ parameter and will be initially set by the
* constructor parameter `initialCounter`. Calling this method will
* overwrite the initial value from the constructor.
*/
fun counter(initialCounter: Long): Hotp {
parameters["counter"] = initialCounter.toString()
return this
}
}
}
| 0 | null | 22 | 96 | 946719e50ba6ddbaacec6522f9b5131e0fd9143d | 10,934 | kotlin-onetimepassword | Apache License 2.0 |
src/main/java/com/elpassion/genealogical/kotlinimpl/FatherNameDisplayer.kt | elpassion | 53,936,336 | false | null | package com.elpassion.genealogical.kotlinimpl
interface Person {
val father: Person?
val name: String?
}
class FatherNameDisplayer {
fun display(person: Person) = person.father?.name ?: "Name not known"
}
| 1 | null | 1 | 1 | c60eb5f62841e373e7607b110468fbca6ee2a915 | 221 | livecoding-kotlin-grandpa-and-grandson | The Unlicense |
src/test/kotlin/com/melowetty/hsepermhelper/util/ScheduleUtilsTest.kt | HSE-Perm-Helper | 682,010,195 | false | {"Kotlin": 146961, "Dockerfile": 102} | package com.melowetty.hsepermhelper.util
import com.melowetty.hsepermhelper.model.Lesson
import com.melowetty.hsepermhelper.model.LessonType
import com.melowetty.hsepermhelper.model.Schedule
import com.melowetty.hsepermhelper.model.ScheduleType
import com.melowetty.hsepermhelper.model.ScheduledTime
import com.melowetty.hsepermhelper.util.ScheduleUtils.Companion.filterWeekSchedules
import org.hibernate.validator.internal.util.Contracts.assertTrue
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Test
import java.time.LocalDate
class ScheduleUtilsTest {
@Test
fun `test merge session schedule`() {
val lessons = listOf(getLesson(), getLesson(), getLesson(), getLesson(), getLesson())
val start = LocalDate.now()
val end = LocalDate.now()
val actual = ScheduleUtils.mergeSessionSchedules(
listOf(
Schedule(
start = start,
end = end,
scheduleType = ScheduleType.SESSION_SCHEDULE,
lessons = lessons.subList(0, 3),
number = 1,
),
Schedule(
start = end,
end = end,
scheduleType = ScheduleType.SESSION_SCHEDULE,
lessons = lessons.subList(3, 5),
number = 2,
)
)
)
val expected = Schedule(
start = start,
end = end,
scheduleType = ScheduleType.SESSION_SCHEDULE,
lessons = lessons,
number = 1,
)
assertEquals(expected, actual, "Расписания после мёржа не равны!")
}
@Test
fun `test normalize schedules when do not contains session schedule`() {
val schedules = listOf(getSchedule(), getSchedule())
val actual = ScheduleUtils.normalizeSchedules(schedules)
assertEquals(schedules, actual, "Расписания после нормализации не равны!")
}
@Test
fun `test normalize schedules when contains session schedule`() {
val schedules = listOf(
getSchedule(), getSchedule(),
getSchedule().copy(scheduleType = ScheduleType.SESSION_SCHEDULE),
getSchedule().copy(scheduleType = ScheduleType.SESSION_SCHEDULE)
)
val actual = ScheduleUtils.normalizeSchedules(schedules)
assertTrue(actual.size == 3, "Расписания после нормализации содержит больше чем три расписания!")
}
@Test
fun getWeekScheduleByDate_returnsCorrectSchedule() {
val schedules = listOf(getSchedule(), getSchedule(), getSchedule())
val date = LocalDate.now()
val actual = ScheduleUtils.getWeekScheduleByDate(schedules, date)
assertEquals(schedules[0], actual, "Returned schedule does not match the expected schedule!")
}
@Test
fun getWeekScheduleByDate_handlesNoMatchingSchedule() {
val schedules = listOf(getSchedule(), getSchedule(), getSchedule())
val date = LocalDate.now().plusDays(10)
assertNull(ScheduleUtils.getWeekScheduleByDate(schedules, date))
}
@Test
fun getLessonsAtDateInWeekSchedule_returnsCorrectLessons() {
val schedule = getSchedule()
val date = LocalDate.now()
val actual = ScheduleUtils.getLessonsAtDateInWeekSchedule(schedule, date)
assertEquals(schedule.lessons, actual, "Returned lessons do not match the expected lessons!")
}
@Test
fun getLessonsAtDateInWeekSchedule_handlesNoLessonsOnDate() {
val schedule = getSchedule()
val date = LocalDate.now().plusDays(10)
val actual = ScheduleUtils.getLessonsAtDateInWeekSchedule(schedule, date)
assertTrue(actual.isEmpty(), "Expected no lessons on the given date!")
}
@Test
fun filterWeekSchedules_returnsOnlyWeekAndSessionSchedules() {
val schedules = listOf(
getSchedule().copy(scheduleType = ScheduleType.WEEK_SCHEDULE),
getSchedule().copy(scheduleType = ScheduleType.SESSION_SCHEDULE),
getSchedule().copy(scheduleType = ScheduleType.QUARTER_SCHEDULE)
)
val actual = schedules.filterWeekSchedules()
assertEquals(2, actual.size, "Expected only week and session schedules!")
assertTrue(
actual.all { it.scheduleType == ScheduleType.WEEK_SCHEDULE || it.scheduleType == ScheduleType.SESSION_SCHEDULE },
"Expected only week and session schedules!"
)
}
@Test
fun filterWeekSchedules_handlesEmptyList() {
val schedules = emptyList<Schedule>()
val actual = schedules.filterWeekSchedules()
assertTrue(actual.isEmpty(), "Expected no schedules in the result!")
}
@Test
fun filterWeekSchedules_handlesNoMatchingSchedules() {
val schedules = listOf(
getSchedule().copy(scheduleType = ScheduleType.QUARTER_SCHEDULE),
getSchedule().copy(scheduleType = ScheduleType.QUARTER_SCHEDULE)
)
val actual = schedules.filterWeekSchedules()
assertTrue(actual.isEmpty(), "Expected no schedules in the result!")
}
@Test
fun getCourseFromGroup() {
val actual = ScheduleUtils.getCourseFromGroup("РИС-22-3")
val expected = 3
assertEquals(expected, actual)
}
@Test
fun getShortGroupFromGroup() {
val actual = ScheduleUtils.getShortGroupFromGroup("ИЯ-22-1")
val expected = "ИЯ"
assertEquals(expected, actual)
}
private fun getLesson(): Lesson {
return Lesson(
course = 1,
group = "test",
lecturer = "test",
lessonType = LessonType.TEST,
parentScheduleType = ScheduleType.SESSION_SCHEDULE,
programme = "test",
subject = "test",
subGroup = null,
time = ScheduledTime(
date = LocalDate.now(),
startTime = "9:40",
endTime = "11:00"
)
)
}
private fun getSchedule(): Schedule {
return Schedule(
start = LocalDate.now(),
end = LocalDate.now(),
scheduleType = ScheduleType.WEEK_SCHEDULE,
lessons = listOf(getLesson(), getLesson(), getLesson(), getLesson()),
number = 1,
)
}
} | 3 | Kotlin | 0 | 0 | dbe744d3e4ff060d5d5781222930922b34df96bf | 6,425 | main-backend | MIT License |
reflekt-plugin/src/test/resources/io/reflekt/plugin/analysis/util/data/base_test_no_reflekt/project/test/Main.kt | vovakfake | 352,456,214 | true | {"Kotlin": 154061} | package io.reflekt.test
import io.reflekt.Reflekt
fun main() {
val classes = Reflekt.classes().withSubType<B1>().withAnnotations<B1>(FirstAnnotationTest::class)
}
| 0 | null | 0 | 0 | 791e5370f4d8e57225f873ccc0f0d3b39d883de9 | 169 | reflekt | Apache License 2.0 |
app/src/main/java/tw/com/deathhit/taipei_tour/MainActivityViewModel.kt | Deathhit | 748,190,483 | false | {"Kotlin": 197443} | package tw.com.deathhit.taipei_tour
import android.os.Parcelable
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.parcelize.Parcelize
import tw.com.deathhit.taipei_tour.model.MainScreen
import javax.inject.Inject
@HiltViewModel
class MainActivityViewModel @Inject constructor(private val savedStateHandle: SavedStateHandle) :
ViewModel() {
private var state: State
get() = savedStateHandle[KEY_STATE] ?: State()
set(value) {
savedStateHandle[KEY_STATE] = value
}
val stateFlow = savedStateHandle.getStateFlow(KEY_STATE, state)
fun goBack(isWebViewCanGoBack: Boolean = false) {
state =
state.copy(actions = state.actions + State.Action.GoBack(isWebViewCanGoBack = isWebViewCanGoBack))
}
fun goToAttractionDetailScreen(attractionId: String) {
state = state.copy(
actions = state.actions + State.Action.GoToScreen(
screen = MainScreen.AttractionDetail(
attractionId = attractionId
)
)
)
}
fun goToGalleryScreen(attractionId: String) {
state = state.copy(
actions = state.actions + State.Action.GoToScreen(
screen = MainScreen.Gallery(
attractionId = attractionId
)
)
)
}
fun goToImageViewer(imageUrl: String) {
state = state.copy(
actions = state.actions + State.Action.GoToScreen(
MainScreen.ImageViewer(imageUrl)
)
)
}
fun goToWebsite(startUrl: String, title: String) {
state = state.copy(
actions = state.actions + State.Action.GoToScreen(
screen = MainScreen.WebView(
startUrl = startUrl,
title = title
)
)
)
}
fun onAction(action: State.Action) {
state = state.copy(actions = state.actions - action)
}
companion object {
private const val TAG = "MainActivityViewModel"
private const val KEY_STATE = "$TAG.KEY_STATE"
}
@Parcelize
data class State(val actions: List<Action> = emptyList()) : Parcelable {
sealed interface Action : Parcelable {
@Parcelize
data class GoBack(val isWebViewCanGoBack: Boolean) : Action
@Parcelize
data class GoToScreen(val screen: MainScreen) : Action
}
}
} | 0 | Kotlin | 0 | 0 | d76f4a3f3d3f0310e3a8b551efa11f46c3c54a30 | 2,568 | TaipeiTour | Apache License 2.0 |
stocks/src/main/java/com/pyamsoft/tickertape/stocks/JsonParser.kt | pyamsoft | 371,196,339 | false | null | package com.pyamsoft.tickertape.stocks
import androidx.annotation.CheckResult
interface JsonParser {
@CheckResult fun <T : Any> toJson(data: T): String
@CheckResult
fun <T : Any> fromJson(
json: String,
type: Class<T>,
): T?
}
@CheckResult
inline fun <reified T : Any> JsonParser.fromJson(json: String): T? {
return this.fromJson(json, T::class.java)
}
| 1 | Kotlin | 0 | 6 | c5309984f17de290ce2fb82120b4699cc8227b65 | 380 | tickertape | Apache License 2.0 |
compottie/src/commonMain/kotlin/io/github/alexzhirkevich/compottie/internal/animation/expressions/operations/js/number/JsToPrecision.kt | alexzhirkevich | 730,724,501 | false | {"Kotlin": 820392, "Swift": 601, "HTML": 572} | package io.github.alexzhirkevich.compottie.internal.animation.expressions.operations.js.number
import io.github.alexzhirkevich.compottie.internal.animation.expressions.Expression
import io.github.alexzhirkevich.compottie.internal.animation.expressions.operations.unresolvedReference
import kotlin.math.pow
import kotlin.math.roundToInt
internal fun JsToPrecision(
number : Expression,
digits : Expression? = null
) = Expression { property, context, state ->
val number = (number(property, context, state) as? Number?)?.toFloat()
?: unresolvedReference("toFixed")
val digits = (digits?.invoke(property, context, state) as Number?)?.toInt()
?.takeIf { it > 0 }
?: return@Expression number
number.roundTo(digits-1)
}
internal fun JsToFixed(
number : Expression,
digits : Expression?
) = Expression { property, context, state ->
val number = (number(property, context, state) as? Number?)?.toFloat()
?: unresolvedReference("toFixed")
val digits = (digits?.invoke(property, context, state) as Number?)?.toInt() ?: 0
if (digits == 0) {
return@Expression number.roundToInt().toString()
}
val stringNumber = number.roundTo(digits).toString()
val intPart = stringNumber.substringBefore(".")
val floatPart = stringNumber.substringAfter(".", "").take(digits)
if (floatPart.isBlank()) {
return@Expression intPart
}
(intPart + "." + floatPart.padEnd(digits, '0'))
}
private val pow10 by lazy {
(1..10).mapIndexed { i, it -> i to 10f.pow(it) }.toMap()
}
internal fun Float.roundTo(digit : Int) : Float {
if(digit <= 0)
return roundToInt().toFloat()
val pow = pow10[digit-1] ?: return this
return ((this * pow).roundToInt() / pow)
} | 2 | Kotlin | 2 | 135 | 426ee74342a86ecebc8118ef71e02597290faa4c | 1,772 | compottie | MIT License |
flowredux/src/commonMain/kotlin/com/freeletics/flowredux/dsl/ExecutionPolicy.kt | freeletics | 184,753,749 | false | {"Kotlin": 142269, "Shell": 2723, "CSS": 1258} | package com.freeletics.flowredux.dsl
/**
* Defines which behavior a DSL Block such as `on<Action>` should have whenever
* a new action or value is emitted.
*/
public enum class ExecutionPolicy {
/**
* Cancels the previous execution.
* By applying this [ExecutionPolicy] the previous execution of the
* same DSL block will be canceled.
*
* Example:
*
* ```
* inState<SomeState> {
* on<Action1>(executionPolicy = CANCEL_PREVIOUS_EXECUTION) { action, stateSnapshot ->
* delay(1000)
* OverrideState(...)
* }
* }
* ```
* Dispatching Action1 two times right after each other means that with this policy the first
* dispatching of Action1 will be canceled as soon as the second dispatching of Action1
* is happening. That is what [CANCEL_PREVIOUS] means.
*
* (uses flatMapLatest under the hood)
*/
CANCEL_PREVIOUS,
/**
* Keeps all previous execution of the DSL block running.
* Whichever DSL block result is first is the first to execute also `ChangeState`.
* In other words, the order of execution is not guaranteed at all.
*
* Example: Let's assume we have the following DSL definition and dispatch two times
* very short after each other Action1.
*
* ```
* var invocations = 0
*
* inState<SomeState> {
* on<Action1>(executionPolicy = UNORDERED) { action, stateSnapshot ->
* invocations++
* delay( 1000/invocations )
* OverrideState(...)
* }
* }
* ```
*
* By applying [UNORDERED] policy then there are no guarantees that dispatching two times Action1
* will result in the same order calling OverrideState.
* In the example above the delay decreases with each Action1 execution.
* That means that for example the second dispatching of Action1 actually return OverrideState()
* before the OverrideState caused by the first dispatching of Action1.
*
* With [UNORDERED] this is explicitly permitted.
*
* If you need guarantees that first dispatching of Action1 means also corresponding OverrideState
* should be executed in the same order as Action being dispatched, then you need [ORDERED] as
* [ExecutionPolicy].
*
* (uses flatMapMerge under the hood)
*/
UNORDERED,
/**
* See example of [UNORDERED].
*
* (uses flatMapConcat under the hood)
*/
ORDERED
}
| 19 | Kotlin | 27 | 707 | eecee7caf3bba31fca8d8f2a8ed66a60839310ca | 2,506 | FlowRedux | Apache License 2.0 |
core/data/src/main/java/com/msg/data/mapper/post/WritePostMapper.kt | School-of-Company | 700,744,250 | false | {"Kotlin": 917283} | package com.msg.data.mapper.post
import com.msg.model.param.post.WritePostParam
import com.msg.network.request.post.WritePostRequest
fun WritePostParam.toRequest() = WritePostRequest(
title = title,
content = content,
links = links,
feedType = feedType,
) | 5 | Kotlin | 0 | 20 | e1e0c6e5a187f5b010a65eb824f9612a2bb118a8 | 273 | Bitgoeul-Android | MIT License |
src/main/kotlin/io/ashdavies/extensions/Fragment.kt | ashdavies | 177,180,130 | false | null | package io.ashdavies.extensions
import android.view.View
import androidx.fragment.app.Fragment
fun Fragment.requireView(): View = view ?: throw IllegalStateException("Fragment $this has no layout")
| 0 | Kotlin | 1 | 4 | 09739852177e5e28600ba7c3dcfe9d63314c9dd9 | 200 | lifecycle-flow | Apache License 2.0 |
SKIE/compiler/kotlin-plugin/src/kgp_common/kotlin/co/touchlab/skie/sir/element/SirFile.kt | touchlab | 685,579,240 | false | null | package co.touchlab.skie.sir.element
import io.outfoxx.swiftpoet.FileSpec
import java.nio.file.Path
// File can only be created from SirProvider
class SirFile(
val namespace: String,
val name: String,
override val module: SirModule.Skie,
) : SirElement, SirTopLevelDeclarationParent {
// Relative to generated swift directory
val relativePath: Path
get() = relativePath(namespace, name)
var content: String = ""
override val parent: SirModule
get() = module
init {
module.files.add(this)
}
override val declarations: MutableList<SirDeclaration> = mutableListOf()
// TODO Replace SwiftPoet with Sir
val swiftPoetBuilderModifications = mutableListOf<FileSpec.Builder.() -> Unit>()
override fun toString(): String = "${this::class.simpleName}: $name"
companion object {
fun relativePath(namespace: String, name: String): Path =
Path.of("$namespace/$namespace.$name.swift")
const val skieNamespace: String = "Skie"
}
}
| 8 | null | 8 | 519 | a9a31608ac24935dd8853d9ec9e6f66e9a424f34 | 1,039 | SKIE | Apache License 2.0 |
app/src/main/java/com/nanamare/movie/ui/screen/UpcomingScreen.kt | Nanamare | 441,159,715 | false | null | package com.nanamare.movie.ui.screen
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells.Fixed
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.paging.LoadState
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.items
import coil.compose.AsyncImage
import coil.compose.SubcomposeAsyncImage
import coil.compose.rememberAsyncImagePainter
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
import com.nanamare.base.ui.compose.*
import com.nanamare.base.util.rememberFlowWithLifecycle
import com.nanamare.base.util.toast
import com.nanamare.data.BuildConfig
import com.nanamare.movie.R
import com.nanamare.movie.model.Movie
import com.nanamare.movie.ui.MainActivityViewModel
import com.nanamare.movie.ui.base.NavigationViewModel
import com.nanamare.movie.ui.base.getActivityViewModel
import com.nanamare.movie.ui.screen.Mode.NORMAL
import com.nanamare.movie.ui.screen.Mode.SEARCH
@Composable
fun UpcomingScreen(
modifier: Modifier,
viewModel: MainActivityViewModel = getActivityViewModel()
) {
val context = LocalContext.current
val error = rememberFlowWithLifecycle(viewModel.error)
LaunchedEffect(error) {
error.collect { context.toast("network is lost") }
}
val currentType by viewModel.currentMode.collectAsState()
if (currentType == SEARCH) {
BackHandler {
viewModel.changeMode(NORMAL)
}
}
Scaffold(
topBar = {
SearchAppBar(
title = stringResource(R.string.toolbar_title_search),
currentType = currentType,
onSymbolClick = {
// TODO Change Theme
},
onChangeType = viewModel::changeMode
) { query ->
viewModel.setQuery(query)
}
}) { innerPadding ->
when (currentType) {
NORMAL -> {
val movies = viewModel.upcomingMovie.collectAsLazyPagingItems()
val refresh by viewModel.isRefresh.collectAsState()
SwipeRefresh(
state = rememberSwipeRefreshState(refresh),
onRefresh = { viewModel.refresh(true) }
) {
UpcomingMovieList(
modifier = modifier
.padding(innerPadding)
.fillMaxSize(),
movies = movies,
isRefresh = refresh,
loadingFinish = { viewModel.refresh(false) },
block = viewModel::navigate
)
}
}
SEARCH -> {
val searchMovie = viewModel.searchMovie.collectAsLazyPagingItems()
val keyboardTrigger by viewModel.keyboardTrigger.collectAsState(0L)
SearchMovieList(
modifier = modifier.padding(innerPadding),
movies = searchMovie,
isNotEmptyQuery = { viewModel.queryFlow.value.isNotEmpty() },
keyboardTrigger = keyboardTrigger,
block = viewModel::navigate
)
}
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun UpcomingMovieList(
modifier: Modifier,
movies: LazyPagingItems<Movie>,
isRefresh: Boolean,
loadingFinish: () -> Unit,
block: (NavigationViewModel.Screen) -> Unit
) {
movies.apply {
if (isRefresh) {
refresh()
}
LazyVerticalGrid(
columns = Fixed(2),
modifier = modifier,
verticalArrangement = Arrangement.Center,
horizontalArrangement = Arrangement.Center
) {
itemsIndexed(movies) { movie, position ->
MovieThumbnail(movie, position, block)
}
when {
loadState.append is LoadState.Loading -> {
item { LoadingItem() }
item { LoadingItem() }
}
loadState.refresh is LoadState.NotLoading && loadState.prepend.endOfPaginationReached -> {
loadingFinish()
}
loadState.refresh is LoadState.Loading || isRefresh -> {
item(span = { GridItemSpan(2) }) {
LoadingView(Modifier.fillMaxSize())
}
}
loadState.refresh is LoadState.Error -> {
val error = movies.loadState.refresh as LoadState.Error
item {
ErrorItem(
message = error.error.localizedMessage.orEmpty(),
modifier = Modifier.fillMaxSize(),
onClickRetry = { retry() }
)
}
}
loadState.append is LoadState.Error -> {
val error = movies.loadState.append as LoadState.Error
item {
ErrorItem(
message = error.error.localizedMessage.orEmpty(),
onClickRetry = { retry() }
)
}
}
}
}
}
}
@OptIn(ExperimentalComposeUiApi::class)
@Composable
private fun SearchMovieList(
modifier: Modifier,
movies: LazyPagingItems<Movie>,
isNotEmptyQuery: () -> Boolean,
keyboardTrigger: Long,
block: (NavigationViewModel.Screen) -> Unit
) {
val scaffoldState = LocalScaffoldState.current
LazyColumn(modifier = modifier) {
movies.apply {
when {
loadState.append is LoadState.Loading -> item { LoadingItem() }
loadState.append is LoadState.NotLoading && loadState.append.endOfPaginationReached && itemCount == 0 && isNotEmptyQuery() -> {
item {
EmptySnackBar(scaffoldState)
EmptyPlaceHolder(Modifier.fillParentMaxSize())
}
}
loadState.refresh is LoadState.Loading && keyboardTrigger != 0L -> {
item {
LoadingView(Modifier.fillParentMaxSize())
}
}
loadState.refresh is LoadState.Error -> {
val error = movies.loadState.refresh as LoadState.Error
item {
ErrorItem(
message = error.error.localizedMessage.orEmpty(),
modifier = Modifier.fillParentMaxSize(),
onClickRetry = { retry() }
)
}
return@LazyColumn
}
loadState.append is LoadState.Error -> {
val error = movies.loadState.append as LoadState.Error
item {
ErrorItem(
message = error.error.localizedMessage.orEmpty(),
onClickRetry = { retry() }
)
}
return@LazyColumn
}
}
}
items(movies, Movie::id) { movie ->
if (movie == null) return@items
MovieCard(movie, block)
}
}
val keyboardController = LocalSoftwareKeyboardController.current
val focusManager = LocalFocusManager.current
LaunchedEffect(keyboardTrigger) {
if (keyboardTrigger == 0L) return@LaunchedEffect
keyboardController?.hide()
focusManager.clearFocus()
}
}
@Composable
private fun MovieCard(movie: Movie, block: (NavigationViewModel.Screen) -> Unit) {
val configuration = LocalConfiguration.current
val screenHeight = configuration.screenHeightDp.dp
val screenWidth = configuration.screenWidthDp.dp
val imageRatio = screenWidth / screenHeight
SubcomposeAsyncImage(
modifier = Modifier
.aspectRatio(imageRatio)
.fillMaxWidth()
.throttleSingleClick(
interactionSource = remember { MutableInteractionSource() },
indication = rememberRipple(bounded = false),
onClick = { block(NavigationViewModel.Screen.DetailMovie(movie)) }
),
model = "${BuildConfig.TMDB_IMAGE_URL}${movie.posterPath}",
loading = {
Box(contentAlignment = Alignment.Center) {
CircularProgressIndicator(modifier = Modifier.size(52.dp))
}
},
contentDescription = "MovieThumbnail",
contentScale = ContentScale.FillHeight,
alignment = Alignment.Center
)
}
@OptIn(ExperimentalComposeUiApi::class)
@Composable
private fun SearchAppBar(
title: String,
currentType: Mode,
onSymbolClick: () -> Unit,
onChangeType: (Mode) -> Unit,
block: (searchQuery: String) -> Unit
) {
val keyboardController = LocalSoftwareKeyboardController.current
// Move to another screen and when you return restore it
var searchText by rememberSaveable(stateSaver = TextFieldValue.Saver) {
mutableStateOf(TextFieldValue())
}
val focusManager = LocalFocusManager.current
val focusRequester = remember { FocusRequester() }
// when restore searchText, move cursor to text.length
searchText = if (currentType == NORMAL) {
TextFieldValue()
} else {
block(searchText.text)
TextFieldValue(searchText.text, TextRange(searchText.text.length))
}
SimpleTopBar(
navigationIcon = {
IconButton(onClick = onSymbolClick) {
Icon(painter = painterResource(id = R.drawable.ic_sketch_symbol), null)
}
},
actions = {
if (currentType == SEARCH) {
IconButton(
onClick = { onChangeType(NORMAL) },
modifier = Modifier
.fillMaxHeight()
.align(Alignment.CenterVertically)
) {
Icon(
imageVector = Icons.Filled.Close,
contentDescription = "CloseButton",
tint = Color.White
)
}
} else {
keyboardController?.hide()
IconButton(
onClick = { onChangeType(SEARCH) },
modifier = Modifier
.fillMaxHeight()
.align(Alignment.CenterVertically)
) {
Icon(
imageVector = Icons.Filled.Search,
contentDescription = "SearchButton",
tint = Color.White
)
}
}
}
) {
if (currentType == SEARCH) {
Surface {
TextField(
textStyle = MaterialTheme.typography.subtitle1,
modifier = Modifier
.focusRequester(focusRequester)
.fillMaxSize(),
value = searchText,
onValueChange = {
searchText = it
block(searchText.text)
},
placeholder = {
Text(
text = stringResource(R.string.search),
color = Color.White
)
},
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Text,
imeAction = ImeAction.Search,
),
keyboardActions = KeyboardActions(
onSearch = {
block(searchText.text)
keyboardController?.hide()
focusManager.clearFocus()
},
),
colors = TextFieldDefaults.textFieldColors(
cursorColor = Color.White,
backgroundColor = MaterialTheme.colors.primary,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent
),
singleLine = true
)
}
SideEffect {
if (searchText.text.isEmpty()) {
focusRequester.requestFocus()
}
}
} else {
Text(text = title)
}
}
}
@Composable
private fun MovieThumbnail(
movie: Movie,
index: Int,
block: (NavigationViewModel.Screen) -> Unit
) {
val bottomPadding = if (index % 2 == 1) 8.dp else 0.dp
val moviePosterRatio = 1f / 1.3f
Box(
modifier = Modifier
.fillMaxWidth()
.padding(bottom = bottomPadding),
contentAlignment = Alignment.Center
) {
AsyncImage(
contentScale = ContentScale.FillHeight,
modifier = Modifier
.aspectRatio(moviePosterRatio)
.fillMaxWidth()
.align(Alignment.Center)
.throttleSingleClick(
interactionSource = remember { MutableInteractionSource() },
indication = rememberRipple(bounded = false),
onClick = { block(NavigationViewModel.Screen.DetailMovie(movie)) }
),
model = "${BuildConfig.TMDB_IMAGE_URL}${movie.posterPath}",
placeholder = rememberAsyncImagePainter(
model = Image(
painter = painterResource(id = R.drawable.outline_movie_24),
contentDescription = null,
modifier = Modifier.size(50.dp)
)
),
contentDescription = "MovieThumbnail",
alignment = Alignment.Center
)
}
}
enum class Mode {
NORMAL, SEARCH
}
| 12 | null | 0 | 22 | 4ddde2be616aeec4ac7f04b33a3b577c34bf2d91 | 16,079 | MovieCompose | MIT License |
browser-kotlin/src/jsMain/kotlin/web/errors/ErrorEvent.types.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6891970} | // Automatically generated - do not modify!
package web.errors
import seskar.js.JsValue
import seskar.js.JsVirtual
import web.events.EventTarget
import web.events.EventType
@JsVirtual
sealed external class ErrorEventTypes :
ErrorEventTypes_deprecated {
@JsValue("error")
fun <C : EventTarget> error(): EventType<ErrorEvent<C>>
@JsValue("processorerror")
fun <C : EventTarget> processorError(): EventType<ErrorEvent<C>>
}
| 0 | Kotlin | 7 | 28 | 8b3f4024ebb4f67e752274e75265afba423a8c38 | 446 | types-kotlin | Apache License 2.0 |
app/src/main/java/com/example/android/common/logger/LogWrapper.kt | Grestomaniac | 251,610,955 | false | {"Kotlin": 22275} | /*
* Copyright (C) 2012 The Android Open Source Project
*
* 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.example.android.common.logger
import android.util.Log
class LogWrapper : LogNode {
var next: LogNode? = null
override fun println(priority: Int, tag: String?, msg: String?, tr: Throwable?) {
var msg = msg
var useMsg: String? = msg
if (useMsg == null) {
useMsg = ""
}
if (tr != null) {
msg += "\n$Log.getStackTraceString(tr)"
}
Log.println(priority, tag, useMsg)
next?.println(priority, tag, msg, tr)
}
}
| 0 | null | 0 | 0 | ffd1946b72e6d42242c1462d0de1ed53bd17c638 | 1,144 | Metcast_app | MIT License |
src/main/kotlin/me/fzzyhmstrs/fzzymapz/theme/impl/BiomeTheme.kt | fzzyhmstrs | 642,181,261 | false | null | package me.fzzyhmstrs.fzzymapz.theme.impl
import me.fzzyhmstrs.fzzymapz.FM
import me.fzzyhmstrs.fzzymapz.registry.RegisterTheme
import me.fzzyhmstrs.fzzymapz.theme.Theme
import net.minecraft.util.Identifier
class BiomeTheme(private val map: MutableMap<Identifier, Identifier>): Theme(RegisterTheme.BIOME){
override fun provide(inputId: Identifier): Identifier{
return map[inputId] ?: FALLBACK
}
companion object{
private val FALLBACK = Identifier(FM.MOD_ID,"")
}
} | 0 | Kotlin | 0 | 0 | fd1caab1a9134f580ad036a5af35cb530532e156 | 500 | fzzymapz | MIT License |
projects/android/eyeonit/src/main/java/io/eyeonit/eyeonit/ui/theme/Shape.kt | AzureAD | 448,733,315 | false | {"HTML": 5728885, "Kotlin": 53219, "JavaScript": 39484, "CSS": 34202, "Java": 24432, "TypeScript": 23817} | package com.sample.hackathon.declaredaccessandroid.ui.theme
import androidx.compose.foundation.shape.CutCornerShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Shapes
import androidx.compose.ui.unit.dp
val EyeonitShapes = Shapes(
small = CutCornerShape(topStart = 10.dp),
medium = CutCornerShape(topStart = 20.dp),
large = RoundedCornerShape(10.dp)
)
| 3 | HTML | 3 | 2 | ea8b89c3867de2af13f73331e4c410e756fe2c3e | 414 | declaredaccess | MIT License |
server/zally-server/src/main/kotlin/org/zalando/zally/dto/ApiDefinitionResponse.kt | zalando | 76,853,145 | false | null | package org.zalando.zally.dto
import java.util.UUID
data class ApiDefinitionResponse(
val externalId: UUID? = null,
val message: String? = null,
val score: Float,
val violations: List<ViolationDTO> = emptyList(),
val violationsCount: Map<String, Int> = emptyMap(),
val apiDefinition: String?
)
| 62 | null | 2 | 882 | 8c7407db2be39041f61b6baa3ee74012ebdb26ad | 320 | zally | MIT License |
app/src/main/java/com/codelab/basiclayouts/feature_account/presentation/homepage/HomepageViewModel.kt | RexHsu09 | 502,902,254 | false | {"Kotlin": 232883} | package com.codelab.basiclayouts.feature_account.presentation.homepage
import androidx.compose.runtime.*
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.codelab.basiclayouts.R
import com.codelab.basiclayouts.core.domain.use_case.AccountingUseCases
import com.codelab.basiclayouts.feature_account.domain.model.FriendInfo
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class HomepageViewModel @Inject constructor(
private val accountingUseCases: AccountingUseCases
) : ViewModel() {
private val _friendList = getFriendData().toMutableStateList()
val friendList: List<FriendInfo>
get() = _friendList
init {
viewModelScope.launch {
accountingUseCases.cardInit()
}
}
// 下面這是展示用 到時候要移到初始頁面initialize卡片
// fun addCards(){
// viewModelScope.launch {
// accountingUseCases.cardInit()
// }
// }
}
private fun getFriendData(): List<FriendInfo>{
return friendsList
} | 0 | Kotlin | 0 | 0 | 1422ed591972d731b544ff34b58eb1c9eac3e172 | 1,074 | Friendly_UI_Improved | Apache License 2.0 |
korim/src/commonMain/kotlin/com/soywiz/korim/bitmap/BitmapIndexed.kt | hegdepranav001 | 257,100,686 | true | {"Kotlin": 457938, "Shell": 1396, "Batchfile": 698} | package com.soywiz.korim.bitmap
import com.soywiz.kmem.*
import com.soywiz.korim.color.*
import kotlin.math.*
abstract class BitmapIndexed(
bpp: Int,
width: Int, height: Int,
var data: ByteArray = ByteArray(width * height / (8 / bpp)),
var palette: RgbaArray = RgbaArray(1 shl bpp)
) : Bitmap(width, height, bpp, false, data) {
init {
if (data.size < width * height / (8 / bpp)) throw RuntimeException("Bitmap data is too short: width=$width, height=$height, data=ByteArray(${data.size}), area=${width * height}")
}
override fun toString() = "BitmapIndexed(bpp=$bpp, width=$width, height=$height, clut=${palette.size})"
protected val temp = ByteArray(max(width, height))
val datau = UByteArrayInt(data)
val n8_dbpp: Int = 8 / bpp
val mask = ((1 shl bpp) - 1)
inline operator fun get(x: Int, y: Int): Int = getInt(x, y)
inline operator fun set(x: Int, y: Int, color: Int): Unit = setInt(x, y, color)
override fun getInt(x: Int, y: Int): Int = (datau[index_d(x, y)] ushr (bpp * index_m(x, y))) and mask
override fun setInt(x: Int, y: Int, color: Int): Unit {
val i = index_d(x, y)
datau[i] = datau[i].insert(color, bpp * index_m(x, y), bpp)
}
override fun getRgba(x: Int, y: Int): RGBA = palette[this[x, y]]
fun index_d(x: Int, y: Int) = index(x, y) / n8_dbpp
fun index_m(x: Int, y: Int) = index(x, y) % n8_dbpp
fun setRow(y: Int, row: UByteArray) {
arraycopy(row.asByteArray(), 0, data, index(0, y), stride)
}
fun setRow(y: Int, row: ByteArray) {
arraycopy(row, 0, data, index(0, y), stride)
}
fun setWhitescalePalette() = this.apply {
for (n in 0 until palette.size) {
val col = ((n.toFloat() / palette.size.toFloat()) * 255).toInt()
palette[n] = RGBA(col, col, col, 0xFF)
}
return this
}
override fun swapRows(y0: Int, y1: Int) {
val s0 = index_d(0, y0)
val s1 = index_d(0, y1)
arraycopy(data, s0, temp, 0, stride)
arraycopy(data, s1, data, s0, stride)
arraycopy(temp, 0, data, s1, stride)
}
fun toLines(palette: String): List<String> {
return (0 until height).map { y -> (0 until height).map { x -> palette[this[x, y]] }.joinToString("") }
}
fun setRowChunk(x: Int, y: Int, data: ByteArray, width: Int, increment: Int) {
if (increment == 1) {
arraycopy(data, 0, this.data, index(x, y), width / n8_dbpp)
} else {
var m = index(x, y)
for (n in 0 until width / n8_dbpp) {
this.data[m] = data[n]
m += increment
}
}
}
override fun toBMP32(): Bitmap32 = Bitmap32(width, height, premultiplied = premultiplied).also { outBmp ->
val out = outBmp.data.ints
val pal = [email protected]
for (x in 0 until width)
for (y in 0 until height)
out[y*width+x] = pal[get(x, y)]
}
}
| 0 | Kotlin | 0 | 0 | 546a07834d4126fd56632790e7fd336d3a1b4e02 | 2,738 | korim | Apache License 2.0 |
app/src/test/java/com/puntogris/brubankchallenge/SearchViewModelTest.kt | puntogris | 817,276,560 | false | {"Kotlin": 73081} | package com.puntogris.brubankchallenge
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.puntogris.brubankchallenge.domain.IRepository
import com.puntogris.brubankchallenge.domain.models.Movie
import com.puntogris.brubankchallenge.ui.search.SearchViewModel
import com.puntogris.brubankchallenge.utils.Resource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.cancel
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.MockitoAnnotations
@ExperimentalCoroutinesApi
class SearchViewModelTest {
@get:Rule
val rule = InstantTaskExecutorRule()
@Mock
private lateinit var repository: IRepository
private val testDispatcher = UnconfinedTestDispatcher()
private lateinit var viewModel: SearchViewModel
@Before
fun setUp() {
MockitoAnnotations.openMocks(this)
Dispatchers.setMain(testDispatcher)
viewModel = SearchViewModel(repository)
}
@After
fun tearDown() {
Dispatchers.resetMain()
testDispatcher.cancel()
}
@Test
fun `updateQuery should update the query state`() = runBlockingTest {
val query = "Test Query"
viewModel.updateQuery(query)
assertEquals(query, viewModel.query.value)
}
@Test
fun `search results should update correctly`() = runTest {
val query = "Movie"
val expectedMovies = listOf(
Movie(
id = 1,
title = "Movie 1",
backdropUrl = "",
posterUrl = "",
overview = "",
releaseDate = "",
primaryGenre = "",
isFavorite = false
),
Movie(
id = 2,
title = "Movie 2",
backdropUrl = "",
posterUrl = "",
overview = "",
releaseDate = "",
primaryGenre = "",
isFavorite = true
)
)
val expectedResults = Resource.Success(expectedMovies)
`when`(repository.searchMovies(query)).thenReturn(expectedResults)
viewModel.updateQuery(query)
advanceUntilIdle()
assertEquals(expectedMovies, viewModel.searchResults.value)
}
@Test
fun `toggleFavoriteState should update favourite movie state and search results`() = runTest {
val movie = Movie(
id = 1,
title = "Movie 1",
backdropUrl = "",
posterUrl = "",
overview = "",
releaseDate = "",
primaryGenre = "",
isFavorite = false
)
val expectedUpdatedMovie = movie.copy(isFavorite = true)
`when`(repository.searchMovies("")).thenReturn(Resource.Success(listOf(movie)))
`when`(repository.addMovieToFavorites(movie)).then { movie.copy(isFavorite = true) }
`when`(repository.removeMovieFromFavorites(movie)).then { movie.copy(isFavorite = false) }
advanceUntilIdle()
viewModel.toggleFavoriteState(movie)
advanceUntilIdle()
assertEquals(
expectedUpdatedMovie.isFavorite,
viewModel.searchResults.value.first().isFavorite
)
}
}
| 0 | Kotlin | 0 | 0 | 977edeb4b96d9ed3d620838561b9cc18b1611fe2 | 3,713 | brubank-challenge | MIT License |
compiler/fir/tree/tree-generator/src/org/jetbrains/kotlin/fir/tree/generator/printer/implementation.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.tree.generator.printer
import org.jetbrains.kotlin.fir.tree.generator.model.*
import org.jetbrains.kotlin.generators.tree.ImplementationKind
import org.jetbrains.kotlin.fir.tree.generator.pureAbstractElementType
import org.jetbrains.kotlin.generators.tree.Importable
import org.jetbrains.kotlin.generators.tree.typeWithArguments
import org.jetbrains.kotlin.utils.SmartPrinter
import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty
import org.jetbrains.kotlin.utils.withIndent
import java.io.File
fun Implementation.generateCode(generationPath: File): GeneratedFile {
val dir = generationPath.resolve(packageName.replace(".", "/"))
val file = File(dir, "$type.kt")
val stringBuilder = StringBuilder()
SmartPrinter(stringBuilder).apply {
printCopyright()
println("@file:Suppress(\"DuplicatedCode\", \"unused\")")
println()
println("package $packageName")
println()
val imports = collectImports()
imports.forEach { println("import $it") }
if (imports.isNotEmpty()) {
println()
}
printGeneratedMessage()
printImplementation(this@generateCode)
}
return GeneratedFile(file, stringBuilder.toString())
}
fun SmartPrinter.printImplementation(implementation: Implementation) {
fun Field.transform() {
when (this) {
is FieldWithDefault -> origin.transform()
is FirField ->
println("$name = ${name}${call()}transform(transformer, data)")
is FieldList -> {
println("${name}.transformInplace(transformer, data)")
}
else -> throw IllegalStateException()
}
}
with(implementation) {
buildSet {
if (requiresOptIn) {
add("FirImplementationDetail")
}
for (field in fieldsWithoutDefault) {
field.optInAnnotation?.let { add(it.type) }
}
}.ifNotEmpty {
println("@OptIn(${joinToString { "$it::class" }})")
}
if (!isPublic) {
print("internal ")
}
print("${kind!!.title} $type")
print(element.typeParameters)
val isInterface = kind == ImplementationKind.Interface || kind == ImplementationKind.SealedInterface
val isAbstract = kind == ImplementationKind.AbstractClass || kind == ImplementationKind.SealedClass
fun abstract() {
if (isAbstract) {
print("abstract ")
}
}
if (!isInterface && !isAbstract && fieldsWithoutDefault.isNotEmpty()) {
if (isPublic) {
print(" @FirImplementationDetail constructor")
}
println("(")
withIndent {
fieldsWithoutDefault.forEachIndexed { _, field ->
if (field.isParameter) {
println("${field.name}: ${field.typeWithArguments},")
} else if (!field.isFinal) {
printField(field, isImplementation = true, override = true, inConstructor = true, notNull = field.notNull)
}
}
}
print(")")
}
print(" : ")
if (!isInterface && !allParents.any { it.kind == ImplementationKind.AbstractClass || it.kind == ImplementationKind.SealedClass }) {
print("${pureAbstractElementType.type}(), ")
}
print(allParents.joinToString { "${it.typeWithArguments}${it.kind.braces()}" })
println(" {")
withIndent {
if (isInterface || isAbstract) {
allFields.forEach {
abstract()
printField(it, isImplementation = true, override = true, notNull = it.notNull)
}
} else {
fieldsWithDefault.forEach {
printFieldWithDefaultInImplementation(it)
}
if (fieldsWithDefault.isNotEmpty()) {
println()
}
}
val bindingCalls = element.allFields.filter {
it.withBindThis && it.type.contains("Symbol") && it !is FieldList && it.name != "companionObjectSymbol"
}.takeIf {
it.isNotEmpty() && !isInterface && !isAbstract &&
!element.type.contains("Reference")
&& !element.type.contains("ResolvedQualifier")
&& !element.type.endsWith("Ref")
&& !element.type.endsWith("AnnotationsContainer")
}.orEmpty()
val customCalls = fieldsWithoutDefault.filter { it.customInitializationCall != null }
if (bindingCalls.isNotEmpty() || customCalls.isNotEmpty()) {
println("init {")
withIndent {
for (symbolField in bindingCalls) {
println("${symbolField.name}${symbolField.call()}bind(this)")
}
for (customCall in customCalls) {
println("${customCall.name} = ${customCall.customInitializationCall}")
}
}
println("}")
println()
}
fun Field.acceptString(): String = "${name}${call()}accept(visitor, data)"
if (!isInterface && !isAbstract) {
print("override fun <R, D> acceptChildren(visitor: FirVisitor<R, D>, data: D) {")
if (element.allFirFields.isNotEmpty()) {
println()
withIndent {
for (field in allFields.filter { it.isFirType }) {
if (field.withGetter || !field.needAcceptAndTransform) continue
when (field.name) {
"explicitReceiver" -> {
val explicitReceiver = implementation["explicitReceiver"]!!
val dispatchReceiver = implementation["dispatchReceiver"]!!
val extensionReceiver = implementation["extensionReceiver"]!!
println(
"""
|${explicitReceiver.acceptString()}
| if (dispatchReceiver !== explicitReceiver) {
| ${dispatchReceiver.acceptString()}
| }
| if (extensionReceiver !== explicitReceiver && extensionReceiver !== dispatchReceiver) {
| ${extensionReceiver.acceptString()}
| }
""".trimMargin(),
)
}
"dispatchReceiver", "extensionReceiver", "subjectVariable", "companionObject" -> {
}
else -> {
if (type == "FirWhenExpressionImpl" && field.name == "subject") {
println(
"""
|val subjectVariable_ = subjectVariable
| if (subjectVariable_ != null) {
| subjectVariable_.accept(visitor, data)
| } else {
| subject?.accept(visitor, data)
| }
""".trimMargin(),
)
} else {
when (field.origin) {
is FirField -> {
println(field.acceptString())
}
is FieldList -> {
println("${field.name}.forEach { it.accept(visitor, data) }")
}
else -> throw IllegalStateException()
}
}
}
}
}
}
}
println("}")
println()
}
abstract()
print("override fun <D> transformChildren(transformer: FirTransformer<D>, data: D): $typeWithArguments")
if (!isInterface && !isAbstract) {
println(" {")
withIndent {
for (field in allFields) {
when {
!field.isMutable || !field.isFirType || field.withGetter || !field.needAcceptAndTransform -> {}
field.name == "explicitReceiver" -> {
val explicitReceiver = implementation["explicitReceiver"]!!
val dispatchReceiver = implementation["dispatchReceiver"]!!
val extensionReceiver = implementation["extensionReceiver"]!!
if (explicitReceiver.isMutable) {
println("explicitReceiver = explicitReceiver${explicitReceiver.call()}transform(transformer, data)")
}
if (dispatchReceiver.isMutable) {
println(
"""
|if (dispatchReceiver !== explicitReceiver) {
| dispatchReceiver = dispatchReceiver?.transform(transformer, data)
| }
""".trimMargin(),
)
}
if (extensionReceiver.isMutable) {
println(
"""
|if (extensionReceiver !== explicitReceiver && extensionReceiver !== dispatchReceiver) {
| extensionReceiver = extensionReceiver?.transform(transformer, data)
| }
""".trimMargin(),
)
}
}
field.name in setOf("dispatchReceiver", "extensionReceiver") -> {}
field.needsSeparateTransform -> {
if (!(element.needTransformOtherChildren && field.needTransformInOtherChildren)) {
println("transform${field.name.replaceFirstChar(Char::uppercaseChar)}(transformer, data)")
}
}
!element.needTransformOtherChildren -> {
field.transform()
}
else -> {}
}
}
if (element.needTransformOtherChildren) {
println("transformOtherChildren(transformer, data)")
}
println("return this")
}
println("}")
} else {
println()
}
for (field in allFields) {
if (!field.needsSeparateTransform) continue
println()
abstract()
print("override ${field.transformFunctionDeclaration(typeWithArguments)}")
if (isInterface || isAbstract) {
println()
continue
}
println(" {")
withIndent {
if (field.isMutable && field.isFirType) {
// TODO: replace with smth normal
if (type == "FirWhenExpressionImpl" && field.name == "subject") {
println(
"""
|if (subjectVariable != null) {
| subjectVariable = subjectVariable?.transform(transformer, data)
| subject = subjectVariable?.initializer
| } else {
| subject = subject?.transform(transformer, data)
| }
""".trimMargin(),
)
} else {
field.transform()
}
}
println("return this")
}
println("}")
}
if (element.needTransformOtherChildren) {
println()
abstract()
print("override fun <D> transformOtherChildren(transformer: FirTransformer<D>, data: D): $typeWithArguments")
if (isInterface || isAbstract) {
println()
} else {
println(" {")
withIndent {
for (field in allFields) {
if (!field.isMutable || !field.isFirType || field.name == "subjectVariable") continue
if (!field.needsSeparateTransform) {
field.transform()
}
if (field.needTransformInOtherChildren) {
println("transform${field.name.replaceFirstChar(Char::uppercaseChar)}(transformer, data)")
}
}
println("return this")
}
println("}")
}
}
fun generateReplace(
field: Field,
overridenType: Importable? = null,
forceNullable: Boolean = false,
body: () -> Unit,
) {
println()
if (field.name == "source") {
println("@FirImplementationDetail")
}
abstract()
print("override ${field.replaceFunctionDeclaration(overridenType, forceNullable)}")
if (isInterface || isAbstract) {
println()
return
}
print(" {")
if (!field.isMutable) {
println("}")
return
}
println()
withIndent {
body()
}
println("}")
}
for (field in allFields.filter { it.withReplace }) {
val capitalizedFieldName = field.name.replaceFirstChar(Char::uppercaseChar)
val newValue = "new$capitalizedFieldName"
generateReplace(field, forceNullable = field.useNullableForReplace) {
when {
field.withGetter -> {}
field.origin is FieldList && !field.isMutableOrEmpty -> {
println("${field.name}.clear()")
println("${field.name}.addAll($newValue)")
}
else -> {
if (field.useNullableForReplace) {
println("require($newValue != null)")
}
print("${field.name} = $newValue")
if (field.origin is FieldList && field.isMutableOrEmpty) {
print(".toMutableOrEmpty()")
}
println()
}
}
}
for (overridenType in field.overridenTypes) {
generateReplace(field, overridenType) {
println("require($newValue is ${field.typeWithArguments})")
println("replace$capitalizedFieldName($newValue)")
}
}
}
}
println("}")
}
}
| 3 | null | 5686 | 46,039 | f98451e38169a833f60b87618db4602133e02cf2 | 17,204 | kotlin | Apache License 2.0 |
Browser/src/jvmMain/kotlin/io/nacular/doodle/dom/WASMTypes.kt | nacular | 108,631,782 | false | {"Kotlin": 3150677} | package io.nacular.doodle.dom
/** @suppress */
public actual interface JsAny
/** @suppress */
public actual class JsString: JsAny
/** @suppress */
public actual fun String.toJsString(): JsString = JsString()
/** @suppress */
public actual class JsNumber: JsAny
internal actual fun JsNumber.toDouble(): Double = 0.0
/** @suppress */
public actual class JsArray<T: JsAny?>: JsAny {
internal actual val length: Int = 0
}
internal actual operator fun <T: JsAny?> JsArray<T>.get(index: Int): T? = null
internal actual operator fun <T : JsAny?> JsArray<T>.set(index: Int, value: T) {}
internal actual fun <T: JsAny?> JsArray<T>.push(value: T) {}
internal actual fun JsArray<out JsString>.contains(value: JsString): Boolean {
(0..this.length).forEach {
if (this[it] == value) return true
}
return false
}
internal actual fun <T : JsAny> jsArrayOf(vararg values: T): JsArray<T> = JsArray() | 3 | Kotlin | 26 | 613 | f7414d4c30cdd7632992071234223653e52b978c | 915 | doodle | MIT License |
src/main/kotlin/no/nav/pensjon/opptjening/omsorgsopptjening/start/innlesning/barnetrygd/external/pdl/ParallelleSannheter.kt | navikt | 585,136,142 | false | {"Kotlin": 254799, "HTML": 6035, "Shell": 806, "Dockerfile": 605} | package no.nav.pensjon.opptjening.omsorgsopptjening.start.innlesning.barnetrygd.external.pdl
private const val FOLKEREGISTERET = "FREG"
private infix fun Metadata.harMaster(antattMaster: String) = master.uppercase() == antattMaster
| 0 | Kotlin | 0 | 0 | 86bab024a1d95e8809f3c2d13f3e1251db783cbd | 234 | omsorgsopptjening-start-innlesning | MIT License |
src/Day06.kt | PascalHonegger | 573,052,507 | false | {"Kotlin": 66208} | fun main() {
fun solve(input: String, size: Int) = input
.windowedSequence(size)
.indexOfFirst { it.toSet().size == size } + size
fun part1(input: String) = solve(input, size = 4)
fun part2(input: String) = solve(input, size = 14)
check(part1("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 7)
check(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5)
check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6)
check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10)
check(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11)
check(part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 19)
check(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23)
check(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23)
check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29)
check(part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26)
val input = readTextInput("Day06")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2215ea22a87912012cf2b3e2da600a65b2ad55fc | 926 | advent-of-code-2022 | Apache License 2.0 |
platform/vcs-impl/src/com/intellij/codeInsight/completion/ml/VcsFeatureProvider.kt | hieuprogrammer | 284,920,751 | false | null | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.completion.ml
import com.intellij.codeInsight.actions.FormatChangedTextUtil
import com.intellij.codeInsight.completion.CompletionLocation
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.psi.*
class VcsFeatureProvider : ElementFeatureProvider {
override fun getName(): String = "vcs"
override fun calculateFeatures(element: LookupElement,
location: CompletionLocation,
contextFeatures: ContextFeatures): Map<String, MLFeatureValue> {
val features = mutableMapOf<String, MLFeatureValue>()
val psi = element.psiElement
val psiFile = psi?.containingFile
psiFile?.viewProvider?.virtualFile?.let { file ->
val changeListManager = ChangeListManager.getInstance(location.project)
changeListManager.getChange(file)?.let { change ->
features["file_state"] = MLFeatureValue.categorical(change.type)
if (change.type == Change.Type.MODIFICATION && psi is PsiNameIdentifierOwner) {
val changedRanges = FormatChangedTextUtil.getInstance().getChangedTextRanges(location.project, psiFile)
if (changedRanges.any { psi.textRange.intersects(it) }) {
features["declaration_is_changed"] = MLFeatureValue.binary(true)
}
}
}
}
return features
}
} | 1 | null | 1 | 2 | dc846ecb926c9d9589c1ed8a40fdb20e47874db9 | 1,611 | intellij-community | Apache License 2.0 |
app/src/main/java/br/com/astradev/mathreferenceapp/ui/screens/FormulaScreen.kt | MalcolnLMR | 877,896,069 | false | {"Kotlin": 38784} | package br.com.astradev.mathreferenceapp.ui.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
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.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import br.com.astradev.mathreferenceapp.model.geometry.objects.FormulaNames
import br.com.astradev.mathreferenceapp.model.getGeometryComponent
import br.com.astradev.mathreferenceapp.ui.components.HomeBackground
import br.com.astradev.mathreferenceapp.ui.components.HomeTopBar
import br.com.astradev.mathreferenceapp.ui.components.NormalTextField
import br.com.astradev.mathreferenceapp.ui.screens.objects.Routes
import br.com.astradev.mathreferenceapp.ui.theme.AccentLight
import br.com.astradev.mathreferenceapp.ui.theme.BaseLight
import br.com.astradev.mathreferenceapp.ui.theme.Black
import br.com.astradev.mathreferenceapp.ui.theme.White
import br.com.astradev.mathreferenceapp.ui.theme.mathreferenceappTheme
@Composable
fun FormulaScreen(navController: NavController) {
HomeBackground()
val component = getGeometryComponent("Cubóide")
if (component == null) navController.navigate(Routes.HOME_SCREEN)
HomeTopBar(component!!.name, component.icon)
Column (
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 15.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.End
) {
for (key in component.map.invoke().keys){
NormalTextField(key)
Spacer(Modifier.size(5.dp))
}
Spacer(Modifier.size(40.dp))
for (mathComponent in component.formulas){
Row(
Modifier
.fillMaxWidth()
.background(BaseLight, RoundedCornerShape(5.dp))
.padding(10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = mathComponent.nome + ": ",
modifier = Modifier
.background(AccentLight, RoundedCornerShape(5.dp))
.padding(horizontal = 3.dp),
color = Black
)
/*
Text(
text = mathComponent.formulaText + " = ",
modifier = Modifier
.background(AccentLight, RoundedCornerShape(5.dp))
)*/
Spacer(Modifier.weight(1f))
Text(
text = mathComponent.formula.invoke(
// TODO fazer com que isso aqui receba os valores digitados pelo usuário
mapOf(
FormulaNames.WIDTH to 1.0,
FormulaNames.HEIGHT to 1.0,
FormulaNames.LENGTH to 1.0
)
).toString(),
modifier = Modifier
.background(White, RoundedCornerShape(5.dp))
.padding(horizontal = 3.dp),
color = Black
)
}
Spacer(Modifier.fillMaxWidth().height(5.dp))
}
}
}
@Preview
@Composable
fun FormulaScreenPreview(){
mathreferenceappTheme {
FormulaScreen(rememberNavController())
}
} | 0 | Kotlin | 0 | 0 | b381cbfefb7644f418b55fab4b26e52afacbd6e1 | 4,068 | geometry-android-app | MIT License |
stripe/src/test/java/com/stripe/android/view/StripeEditTextTest.kt | Yog8482 | 320,415,601 | true | {"Kotlin": 2159772, "Java": 64814, "Ruby": 6208, "Shell": 321} | package com.stripe.android.view
import android.content.Context
import androidx.annotation.ColorInt
import androidx.core.content.ContextCompat
import androidx.test.core.app.ApplicationProvider
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions
import com.stripe.android.R
import com.stripe.android.testharness.ViewTestUtils
import kotlin.test.Test
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestCoroutineDispatcher
import org.junit.runner.RunWith
import org.mockito.Mockito.reset
import org.mockito.Mockito.verify
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
@ExperimentalCoroutinesApi
class StripeEditTextTest {
private val context: Context = ApplicationProvider.getApplicationContext()
private val afterTextChangedListener: StripeEditText.AfterTextChangedListener = mock()
private val deleteEmptyListener: StripeEditText.DeleteEmptyListener = mock()
private val testDispatcher = TestCoroutineDispatcher()
private val editText = StripeEditText(
context,
workDispatcher = testDispatcher
).also {
it.setDeleteEmptyListener(deleteEmptyListener)
it.setAfterTextChangedListener(afterTextChangedListener)
}
@Test
fun deleteText_whenZeroLength_callsDeleteListener() {
ViewTestUtils.sendDeleteKeyEvent(editText)
verify(deleteEmptyListener).onDeleteEmpty()
verifyNoMoreInteractions(afterTextChangedListener)
}
@Test
fun addText_callsAppropriateListeners() {
editText.append("1")
verifyNoMoreInteractions(deleteEmptyListener)
verify(afterTextChangedListener)
.onTextChanged("1")
}
@Test
fun deleteText_whenNonZeroLength_callsAppropriateListeners() {
editText.append("1")
reset(afterTextChangedListener)
ViewTestUtils.sendDeleteKeyEvent(editText)
verifyNoMoreInteractions(deleteEmptyListener)
verify(afterTextChangedListener)
.onTextChanged("")
}
@Test
fun deleteText_whenSelectionAtBeginningButLengthNonZero_doesNotCallListener() {
editText.append("12")
verify(afterTextChangedListener)
.onTextChanged("12")
editText.setSelection(0)
ViewTestUtils.sendDeleteKeyEvent(editText)
verifyNoMoreInteractions(deleteEmptyListener)
verifyNoMoreInteractions(afterTextChangedListener)
}
@Test
fun deleteText_whenDeletingMultipleItems_onlyCallsListenerOneTime() {
editText.append("123")
// Doing this four times because we need to delete all three items, then jump back.
repeat(4) {
ViewTestUtils.sendDeleteKeyEvent(editText)
}
verify(deleteEmptyListener).onDeleteEmpty()
}
@Test
fun getDefaultErrorColorInt_onDarkTheme_returnsDarkError() {
editText.setTextColor(ContextCompat.getColor(context, android.R.color.primary_text_dark))
assertThat(editText.defaultErrorColorInt)
.isEqualTo(ContextCompat.getColor(context, R.color.stripe_error_text_dark_theme))
}
@Test
fun getDefaultErrorColorInt_onLightTheme_returnsLightError() {
editText.setTextColor(ContextCompat.getColor(context, android.R.color.primary_text_light))
assertThat(editText.defaultErrorColorInt)
.isEqualTo(ContextCompat.getColor(context, R.color.stripe_error_text_light_theme))
}
@Test
fun setErrorColor_whenInError_overridesDefault() {
// By default, the text color in this test activity is a light theme
@ColorInt val blueError = 0x0000ff
editText.setErrorColor(blueError)
editText.shouldShowError = true
val currentColorInt = editText.textColors.defaultColor
assertThat(currentColorInt)
.isEqualTo(blueError)
}
@Test
fun getCachedColorStateList_afterInit_returnsNotNull() {
assertThat(editText.cachedColorStateList)
.isNotNull()
}
@Test
fun setShouldShowError_whenErrorColorNotSet_shouldUseDefaultErrorColor() {
editText.shouldShowError = true
assertThat(editText.textColors.defaultColor)
.isEqualTo(ContextCompat.getColor(context, R.color.stripe_error_text_light_theme))
}
@Test
fun shouldShowError_whenChanged_changesTextColor() {
editText.errorMessage = "There was an error!"
editText.shouldShowError = true
assertThat(editText.currentTextColor)
.isEqualTo(-1369050)
editText.shouldShowError = false
assertThat(editText.currentTextColor)
.isEqualTo(-570425344)
}
@Test
fun `setHintDelayed should set hint after delay`() {
assertThat(editText.hint)
.isNull()
editText.setHintDelayed("Here's a hint", DELAY)
testDispatcher.advanceTimeBy(DELAY + 10)
assertThat(editText.hint)
.isEqualTo("Here's a hint")
}
@Test
fun `setHintDelayed when Job is canceled before delay should not set hint`() {
assertThat(editText.hint)
.isNull()
editText.setHintDelayed("Here's a hint", DELAY)
testDispatcher.advanceTimeBy(DELAY - 10)
editText.job.cancel()
assertThat(editText.hint)
.isNull()
}
private companion object {
private const val DELAY = 100L
}
}
| 0 | null | 0 | 1 | ec4b7553eab234075a1e8fce75fdcecc73635eb2 | 5,487 | stripe-android | MIT License |
app/src/main/java/com/andreasgift/edisco/MainActivity.kt | andrea-liu87 | 198,418,230 | false | null | package com.andreasgift.edisco
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import android.Manifest
import android.annotation.TargetApi
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.speech.tts.TextToSpeech
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.AdView
import com.google.android.gms.ads.MobileAds
import com.google.android.gms.tasks.OnFailureListener
import com.google.android.gms.tasks.OnSuccessListener
import com.google.firebase.ml.vision.FirebaseVision
import com.google.firebase.ml.vision.common.FirebaseVisionImage
import com.google.firebase.ml.vision.document.FirebaseVisionCloudDocumentRecognizerOptions
import com.google.firebase.ml.vision.document.FirebaseVisionDocumentText
import com.google.firebase.ml.vision.document.FirebaseVisionDocumentTextRecognizer
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Arrays
import java.util.Date
import java.util.Locale
class MainActivity : AppCompatActivity() {
private var image: ImageView? = null
private var textView: TextView? = null
lateinit var mAdView: AdView
private val freeQuota = 50
private var unitRead: Int = 0
private var sharedPref: SharedPreferences? = null
private val KEY_PREFS = "unit read shared preferences"
private val language = Locale.ENGLISH
private val REQUEST_IMAGE_CAPTURE = 1
private val TAG = "MainActivity"
private var tts: TextToSpeech? = null
private var imagePath: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
MobileAds.initialize(this)
mAdView = findViewById(R.id.adView)
val adRequest = AdRequest.Builder().build()
mAdView.loadAd(adRequest)
sharedPref = this.getPreferences(Context.MODE_PRIVATE)
unitRead = sharedPref!!.getInt(KEY_PREFS, 0)
requestPermission(Manifest.permission.CAMERA)
image = findViewById(R.id.image_view)
textView = findViewById(R.id.text_view)
}
/**
* The sequence of method happen when README button is pressed
* consist of method:
* getPicture() extractText() textToSpeech()
* @param v button view parents
*/
fun OnClick(v: View) {
if (unitRead <= freeQuota) {
try {
getPicture()
} catch (e: IOException) {
e.printStackTrace()
}
} else {
textView!!.text = resources.getText(R.string.quota_message)
textToSpeech(getString(R.string.quota_message), getString(R.string.error_message))
}
}
/**
* This method will called intent to take picture
* Upon success, it will call extractText() to process the image and read any text from it
*/
@Throws(IOException::class)
private fun getPicture() {
Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
takePictureIntent.resolveActivity(packageManager)?.also {
// Create the File where the photo should go
val photoFile: File? = try {
createImageFile()
} catch (e: IOException) {
e.printStackTrace()
null
}
// Continue only if the File was successfully created
photoFile?.also {
val photoURI: Uri = FileProvider.getUriForFile(
this,
"com.andreasgift.edisco",
it
)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
}
}
}
}
@Throws(IOException::class)
private fun createImageFile(): File {
val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile(
"JPEG_${timeStamp}_", /* prefix */
".jpg", /* suffix */
storageDir /* directory */
).apply {
// Save a file: path for use with ACTION_VIEW intents
imagePath = absolutePath
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
val bitmap = BitmapFactory.decodeFile(imagePath)
image!!.setImageBitmap(bitmap)
extractText(bitmap)
}
}
/**
* This method will extract any text from bitmap
* Upon success, it will called textToSpeech() to read the text
* @param input bitmap as input
*/
private fun extractText(input: Bitmap) {
val image = FirebaseVisionImage.fromBitmap(input)
val options = FirebaseVisionCloudDocumentRecognizerOptions.Builder()
.setLanguageHints(Arrays.asList("en", "id"))
.build()
val recognizer = FirebaseVision.getInstance().getCloudDocumentTextRecognizer(options)
recognizer.processImage(image)
.addOnSuccessListener { firebaseVisionDocumentText ->
val resultText = firebaseVisionDocumentText.text
Log.d(TAG, "Text : $resultText")
textToSpeech(resultText, getString(R.string.no_text_message))
}
.addOnFailureListener { e -> Log.e(TAG, e.toString()) }
}
/**
* This method will read input text
* @param text text that will be read by device
* @param errorMssg error message wil be read by device when onInit fail
*/
private fun textToSpeech(text: String?, errorMssg: String) {
tts = TextToSpeech(this, TextToSpeech.OnInitListener { status ->
if (status == TextToSpeech.SUCCESS) {
tts!!.language = language
tts!!.setSpeechRate(0.6f)
if (text != null) {
tts!!.speak(text, TextToSpeech.QUEUE_FLUSH, null, "TTS")
unitRead += 1
sharedPref!!.edit().putInt(KEY_PREFS, unitRead).apply()
} else {
tts!!.speak(errorMssg, TextToSpeech.QUEUE_FLUSH, null, "TTS")
}
}
})
}
/**
* Request app permission for API 23/ Android 6.0
* @param permission string permission requested
*/
@TargetApi(Build.VERSION_CODES.M)
private fun requestPermission(permission: String) {
val MY_PERMISSIONS_REQUEST = 99
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
arrayOf(permission),
MY_PERMISSIONS_REQUEST)
}
}
/**
* Release all the resources when the app is onPause state
*/
override fun onPause() {
super.onPause()
if (tts != null) {
tts!!.stop()
tts!!.shutdown()
}
}
}
| 0 | Kotlin | 0 | 1 | 2d809b5dd248f6bb1c5eda8eee11e59e8f141585 | 8,197 | Edisco | MIT License |
defitrack-protocols/src/main/java/io/defitrack/protocol/alienbase/PoolInfo.kt | decentri-fi | 426,174,152 | false | {"Kotlin": 1038532, "Java": 1948, "Dockerfile": 909} | package io.defitrack.protocol.alienbase
import java.math.BigInteger
class PoolInfo(
val lpToken: String,
val allocPoint: BigInteger,
val lastRewardBlock: BigInteger,
val accAlbPerShare: BigInteger,
val depositFeeBP: BigInteger,
val harvestInterval: BigInteger,
val totalLp: BigInteger
) | 53 | Kotlin | 7 | 9 | e65843453e4c44f5c2626870ceb923eb7ab3c4d0 | 316 | defi-hub | MIT License |
work/src/main/kotlin/net/kotlinx/kotest/modules/BeSpecHeavy.kt | mypojo | 565,799,715 | false | {"Kotlin": 1459231, "Jupyter Notebook": 13439, "Java": 9531} | package net.kotlinx.kotest.modules
import net.kotlinx.kotest.BeSpecKoin
abstract class BeSpecHeavy : BeSpecKoin(MODULES) {
companion object {
val MODULES = BeSpecLight.MODULES + listOf(
AwsModule.moduleConfig(),
DynamoLockModule.moduleConfig(),
ResourceLockModule.moduleConfig(),
)
}
} | 0 | Kotlin | 0 | 1 | 57ff2c63b66b29c70397673a6c71ca08b3f84bdb | 348 | kx_kotlin_support | MIT License |
components/core/ui/decompose/src/desktopMain/kotlin/com/flipperdevices/ui/decompose/internal/DesktopWindowDecorator.kt | flipperdevices | 288,258,832 | false | {"Kotlin": 4167715, "FreeMarker": 10352, "CMake": 1780, "C++": 1152, "Fluent": 21} | package com.flipperdevices.ui.decompose.internal
internal class DesktopWindowDecorator : WindowDecorator {
override fun decorate() = Unit
}
| 21 | Kotlin | 174 | 1,528 | 8f293e596741a6c97409acbc8de10c7ae6e8d8b0 | 145 | Flipper-Android-App | MIT License |
app/src/main/java/tool/xfy9326/milink/nfc/activity/MainActivity.kt | XFY9326 | 724,531,401 | false | {"Kotlin": 124564} | package tool.xfy9326.milink.nfc.activity
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.nfc.tech.Ndef
import android.nfc.tech.NdefFormatable
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import tool.xfy9326.milink.nfc.AppContext
import tool.xfy9326.milink.nfc.R
import tool.xfy9326.milink.nfc.data.NdefWriteData
import tool.xfy9326.milink.nfc.ui.screen.NFCMirrorScreen
import tool.xfy9326.milink.nfc.ui.theme.AppTheme
import tool.xfy9326.milink.nfc.ui.vm.MainViewModel
import tool.xfy9326.milink.nfc.utils.enableNdefReaderMode
import tool.xfy9326.milink.nfc.utils.ignoreTagUntilRemoved
import tool.xfy9326.milink.nfc.utils.showToast
import tool.xfy9326.milink.nfc.utils.tryConnect
import tool.xfy9326.milink.nfc.utils.useCatching
class MainActivity : ComponentActivity() {
private val viewModel by viewModels<MainViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen()
enableEdgeToEdge()
super.onCreate(savedInstanceState)
setContent {
AppTheme {
NFCMirrorScreen(onExit = { finishAndRemoveTask() })
}
}
setupNfcReaderListener()
}
private fun setupNfcReaderListener() {
val nfcAdapter = NfcAdapter.getDefaultAdapter(this)
if (nfcAdapter != null) {
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.nfcWriteData.collect { data ->
data?.let {
nfcAdapter.enableNdefReaderMode(this@MainActivity) {
handleNfcTag(nfcAdapter, it, data)
}
} ?: nfcAdapter.disableReaderMode(this@MainActivity)
}
}
}
} else {
Toast.makeText(AppContext, R.string.no_nfc, Toast.LENGTH_LONG).show()
}
}
private fun makeToast(msg: String): Unit = runOnUiThread { showToast(msg) }
private fun handleNfcTag(nfcAdapter: NfcAdapter, tag: Tag, writeData: NdefWriteData) {
lifecycleScope.launch {
val ndef = Ndef.get(tag)
if (ndef != null) {
writeNdefTag(nfcAdapter, ndef, writeData)
return@launch
}
val ndefFormatable = NdefFormatable.get(tag)
if (ndefFormatable != null) {
formatNdefTag(nfcAdapter, ndefFormatable)
return@launch
}
makeToast(getString(R.string.nfc_ndef_not_supported, tag.techList.joinToString { it.substringAfterLast(".") }))
}
}
private suspend fun formatNdefTag(nfcAdapter: NfcAdapter, ndefFormatable: NdefFormatable): Unit = withContext(Dispatchers.IO) {
ndefFormatable.tryConnect().onSuccess {
it.useCatching {
format(null)
}.onSuccess {
nfcAdapter.ignoreTagUntilRemoved(ndefFormatable.tag)
makeToast(getString(R.string.nfc_ndef_format_success))
}.onFailure {
makeToast(getString(R.string.nfc_ndef_format_failed))
}
}.onFailure {
makeToast(getString(R.string.nfc_connect_failed))
}
}
private suspend fun writeNdefTag(nfcAdapter: NfcAdapter, ndef: Ndef, writeData: NdefWriteData): Unit = withContext(Dispatchers.IO) {
ndef.tryConnect().onSuccess {
it.useCatching {
if (!it.isWritable) {
makeToast(getString(R.string.nfc_write_error_not_writeable))
return@onSuccess
}
if (writeData.readOnly && !it.canMakeReadOnly()) {
makeToast(getString(R.string.nfc_write_error_no_read_only))
return@onSuccess
}
if (writeData.ndefMsg.byteArrayLength > it.maxSize) {
makeToast(getString(R.string.nfc_write_error_max_size))
return@onSuccess
}
try {
it.writeNdefMessage(writeData.ndefMsg)
} catch (e: Exception) {
makeToast(getString(R.string.nfc_write_error))
return@onSuccess
}
if (writeData.readOnly) {
try {
if (!it.makeReadOnly()) {
makeToast(getString(R.string.nfc_write_error_read_only))
return@onSuccess
}
} catch (e: Exception) {
makeToast(getString(R.string.nfc_write_error_read_only))
return@onSuccess
}
}
}.onSuccess {
makeToast(getString(R.string.nfc_write_success))
nfcAdapter.ignoreTagUntilRemoved(ndef.tag)
if (writeData.readOnly) viewModel.closeNfcWriter()
}.onFailure { throwable ->
makeToast(
buildString {
append(getString(R.string.nfc_write_error_unknown))
throwable.message.takeUnless { m -> m.isNullOrBlank() }?.let { m ->
appendLine()
append(m)
}
}
)
}
}.onFailure {
makeToast(getString(R.string.nfc_connect_failed))
}
}
}
| 0 | Kotlin | 0 | 4 | 1e8ff899c563be5e71016761aa140c4e2825145d | 6,006 | MiLinkNFC | MIT License |
app/src/main/java/tool/xfy9326/milink/nfc/activity/MainActivity.kt | XFY9326 | 724,531,401 | false | {"Kotlin": 124564} | package tool.xfy9326.milink.nfc.activity
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.nfc.tech.Ndef
import android.nfc.tech.NdefFormatable
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import tool.xfy9326.milink.nfc.AppContext
import tool.xfy9326.milink.nfc.R
import tool.xfy9326.milink.nfc.data.NdefWriteData
import tool.xfy9326.milink.nfc.ui.screen.NFCMirrorScreen
import tool.xfy9326.milink.nfc.ui.theme.AppTheme
import tool.xfy9326.milink.nfc.ui.vm.MainViewModel
import tool.xfy9326.milink.nfc.utils.enableNdefReaderMode
import tool.xfy9326.milink.nfc.utils.ignoreTagUntilRemoved
import tool.xfy9326.milink.nfc.utils.showToast
import tool.xfy9326.milink.nfc.utils.tryConnect
import tool.xfy9326.milink.nfc.utils.useCatching
class MainActivity : ComponentActivity() {
private val viewModel by viewModels<MainViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen()
enableEdgeToEdge()
super.onCreate(savedInstanceState)
setContent {
AppTheme {
NFCMirrorScreen(onExit = { finishAndRemoveTask() })
}
}
setupNfcReaderListener()
}
private fun setupNfcReaderListener() {
val nfcAdapter = NfcAdapter.getDefaultAdapter(this)
if (nfcAdapter != null) {
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.nfcWriteData.collect { data ->
data?.let {
nfcAdapter.enableNdefReaderMode(this@MainActivity) {
handleNfcTag(nfcAdapter, it, data)
}
} ?: nfcAdapter.disableReaderMode(this@MainActivity)
}
}
}
} else {
Toast.makeText(AppContext, R.string.no_nfc, Toast.LENGTH_LONG).show()
}
}
private fun makeToast(msg: String): Unit = runOnUiThread { showToast(msg) }
private fun handleNfcTag(nfcAdapter: NfcAdapter, tag: Tag, writeData: NdefWriteData) {
lifecycleScope.launch {
val ndef = Ndef.get(tag)
if (ndef != null) {
writeNdefTag(nfcAdapter, ndef, writeData)
return@launch
}
val ndefFormatable = NdefFormatable.get(tag)
if (ndefFormatable != null) {
formatNdefTag(nfcAdapter, ndefFormatable)
return@launch
}
makeToast(getString(R.string.nfc_ndef_not_supported, tag.techList.joinToString { it.substringAfterLast(".") }))
}
}
private suspend fun formatNdefTag(nfcAdapter: NfcAdapter, ndefFormatable: NdefFormatable): Unit = withContext(Dispatchers.IO) {
ndefFormatable.tryConnect().onSuccess {
it.useCatching {
format(null)
}.onSuccess {
nfcAdapter.ignoreTagUntilRemoved(ndefFormatable.tag)
makeToast(getString(R.string.nfc_ndef_format_success))
}.onFailure {
makeToast(getString(R.string.nfc_ndef_format_failed))
}
}.onFailure {
makeToast(getString(R.string.nfc_connect_failed))
}
}
private suspend fun writeNdefTag(nfcAdapter: NfcAdapter, ndef: Ndef, writeData: NdefWriteData): Unit = withContext(Dispatchers.IO) {
ndef.tryConnect().onSuccess {
it.useCatching {
if (!it.isWritable) {
makeToast(getString(R.string.nfc_write_error_not_writeable))
return@onSuccess
}
if (writeData.readOnly && !it.canMakeReadOnly()) {
makeToast(getString(R.string.nfc_write_error_no_read_only))
return@onSuccess
}
if (writeData.ndefMsg.byteArrayLength > it.maxSize) {
makeToast(getString(R.string.nfc_write_error_max_size))
return@onSuccess
}
try {
it.writeNdefMessage(writeData.ndefMsg)
} catch (e: Exception) {
makeToast(getString(R.string.nfc_write_error))
return@onSuccess
}
if (writeData.readOnly) {
try {
if (!it.makeReadOnly()) {
makeToast(getString(R.string.nfc_write_error_read_only))
return@onSuccess
}
} catch (e: Exception) {
makeToast(getString(R.string.nfc_write_error_read_only))
return@onSuccess
}
}
}.onSuccess {
makeToast(getString(R.string.nfc_write_success))
nfcAdapter.ignoreTagUntilRemoved(ndef.tag)
if (writeData.readOnly) viewModel.closeNfcWriter()
}.onFailure { throwable ->
makeToast(
buildString {
append(getString(R.string.nfc_write_error_unknown))
throwable.message.takeUnless { m -> m.isNullOrBlank() }?.let { m ->
appendLine()
append(m)
}
}
)
}
}.onFailure {
makeToast(getString(R.string.nfc_connect_failed))
}
}
}
| 0 | Kotlin | 0 | 4 | 1e8ff899c563be5e71016761aa140c4e2825145d | 6,006 | MiLinkNFC | MIT License |
app/src/main/java/dev/spikeysanju/wiggles/view/Details.kt | Spikeysanju | 342,802,106 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* 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
*
* https://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 dev.spikeysanju.wiggles.view
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
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.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import dev.spikeysanju.wiggles.R
import dev.spikeysanju.wiggles.component.DogInfoCard
import dev.spikeysanju.wiggles.component.InfoCard
import dev.spikeysanju.wiggles.component.OwnerCard
import dev.spikeysanju.wiggles.data.FakeDogDatabase
@Composable
fun Details(navController: NavController, id: Int) {
Scaffold(
topBar = {
TopAppBar(
title = { Text("Details") },
backgroundColor = MaterialTheme.colors.background,
contentColor = colorResource(id = R.color.text),
navigationIcon = {
Icon(
imageVector = Icons.Default.ArrowBack,
contentDescription = null,
modifier = Modifier
.size(24.dp, 24.dp)
.clickable {
navController.navigateUp()
},
tint = colorResource(id = R.color.text)
)
}
)
},
content = {
DetailsView(id)
}
)
}
@Composable
fun DetailsView(id: Int) {
LazyColumn(
modifier = Modifier
.fillMaxSize()
.background(color = colorResource(id = R.color.background))
) {
val dog = FakeDogDatabase.dogList[id]
// Basic details
item {
dog.apply {
val dogImage: Painter = painterResource(id = dog.image)
Image(
modifier = Modifier
.fillMaxWidth()
.height(346.dp),
painter = dogImage,
alignment = Alignment.CenterStart,
contentDescription = "",
contentScale = ContentScale.Crop
)
Spacer(modifier = Modifier.height(16.dp))
DogInfoCard(name, gender, location)
}
}
// My story details
item {
dog.apply {
Spacer(modifier = Modifier.height(24.dp))
Title(title = "My Story")
Spacer(modifier = Modifier.height(16.dp))
Text(
text = about,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp, 0.dp, 16.dp, 0.dp),
color = colorResource(id = R.color.text),
style = MaterialTheme.typography.body2,
textAlign = TextAlign.Start
)
}
}
// Quick info
item {
dog.apply {
Spacer(modifier = Modifier.height(24.dp))
Title(title = "Dog info")
Spacer(modifier = Modifier.height(16.dp))
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp, 0.dp, 16.dp, 0.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
InfoCard(title = "Age", value = dog.age.toString().plus(" yrs"))
InfoCard(title = "Color", value = color)
InfoCard(title = "Weight", value = weight.toString().plus("Kg"))
}
}
}
// Owner info
item {
dog.apply {
Spacer(modifier = Modifier.height(24.dp))
Title(title = "Owner info")
Spacer(modifier = Modifier.height(16.dp))
owner.apply {
OwnerCard(name, bio, image)
}
}
}
// CTA - Adopt me button
item {
Spacer(modifier = Modifier.height(36.dp))
Button(
onClick = { /* Do something! */ },
modifier = Modifier
.fillMaxWidth()
.height(52.dp)
.padding(16.dp, 0.dp, 16.dp, 0.dp),
colors = ButtonDefaults.textButtonColors(
backgroundColor = colorResource(id = R.color.blue),
contentColor = Color.White
)
) {
Text("Adopt me")
}
Spacer(modifier = Modifier.height(24.dp))
}
}
}
@Composable
fun Title(title: String) {
Text(
text = title,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp, 0.dp, 0.dp, 0.dp),
color = colorResource(id = R.color.text),
style = MaterialTheme.typography.subtitle1,
fontWeight = FontWeight.W600,
textAlign = TextAlign.Start
)
}
| 2 | null | 70 | 414 | 940f6a0797b70b15d39aeed75e7ddc204082d86b | 6,906 | Wiggles | Apache License 2.0 |
src/test/kotlin/com/forgerock/sapi/gateway/ob/uk/tests/functional/payment/domestic/payments/legacy/LegacyCreateDomesticPaymentTest.kt | SecureApiGateway | 330,627,234 | false | null | package com.forgerock.sapi.gateway.ob.uk.tests.functional.payment.domestic.payments.legacy
import assertk.assertThat
import assertk.assertions.contains
import assertk.assertions.isEqualTo
import assertk.assertions.isNotEmpty
import assertk.assertions.isNotNull
import com.forgerock.sapi.gateway.framework.conditions.Status
import com.forgerock.sapi.gateway.framework.configuration.psu
import com.forgerock.sapi.gateway.framework.extensions.junit.CreateTppCallback
import com.forgerock.sapi.gateway.framework.extensions.junit.EnabledIfVersion
import com.forgerock.sapi.gateway.framework.http.fuel.defaultMapper
import com.forgerock.sapi.gateway.framework.signature.signPayloadSubmitPayment
import com.forgerock.sapi.gateway.framework.signature.signPayloadSubmitPaymentInvalidB64ClaimTrue
import com.forgerock.sapi.gateway.ob.uk.framework.constants.INVALID_SIGNING_KID
import com.forgerock.sapi.gateway.ob.uk.support.discovery.payment3_1_1
import com.forgerock.sapi.gateway.ob.uk.support.discovery.payment3_1_3
import com.forgerock.sapi.gateway.ob.uk.support.discovery.payment3_1_4
import com.forgerock.sapi.gateway.ob.uk.support.payment.PaymentAS
import com.forgerock.sapi.gateway.ob.uk.support.payment.PaymentFactory
import com.forgerock.sapi.gateway.ob.uk.support.payment.PaymentFactory.Companion.copyOBWriteDomestic2DataInitiation
import com.forgerock.sapi.gateway.ob.uk.support.payment.PaymentFactory.Companion.mapOBDomestic2ToOBWriteDomestic2DataInitiation
import com.forgerock.sapi.gateway.ob.uk.support.payment.PaymentRS
import com.forgerock.sapi.gateway.uk.common.shared.api.meta.obie.OBVersion
import com.github.kittinunf.fuel.core.FuelError
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Test
import uk.org.openbanking.datamodel.payment.*
import uk.org.openbanking.testsupport.payment.OBWriteDomesticConsentTestDataFactory.*
class LegacyCreateDomesticPaymentTest(val tppResource: CreateTppCallback.TppResource) {
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.4",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"]
)
@Test
fun createDomesticPayments_v3_1_4() {
// Given
val consentRequest = aValidOBWriteDomesticConsent4()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse4>(
payment3_1_4.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_4,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse4>(
PaymentFactory.urlWithConsentId(
payment3_1_4.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_4
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(copyOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
val signedPayload = signPayloadSubmitPayment(
defaultMapper.writeValueAsString(paymentSubmissionRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
// When
val result = PaymentRS().submitPayment<OBWriteDomesticResponse4>(
payment3_1_4.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode,
signedPayload,
tppResource.tpp,
OBVersion.v3_1_4
)
// Then
assertThat(result).isNotNull()
assertThat(result.data).isNotNull()
assertThat(result.data.consentId).isNotEmpty()
if (consent.data.charges.isNullOrEmpty())
{
assertThat(result.data.charges).isNotEmpty()
}
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.4",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"]
)
@Test
fun shouldCreateDomesticPayments_throwsPaymentAlreadyExists_v3_1_4() {
// Given
val consentRequest = aValidOBWriteDomesticConsent4()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse4>(
payment3_1_4.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_4,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse4>(
PaymentFactory.urlWithConsentId(
payment3_1_4.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_4
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(copyOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
val signedPayload = signPayloadSubmitPayment(
defaultMapper.writeValueAsString(paymentSubmissionRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
// When
val exception = assertThrows(AssertionError::class.java) {
PaymentRS().submitPayment<OBWriteDomesticResponse4>(
payment3_1_4.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode,
signedPayload,
tppResource.tpp, OBVersion.v3_1_4
)
}
// Then
assertThat(exception.message.toString()).contains(com.forgerock.sapi.gateway.ob.uk.framework.errors.PAYMENT_SUBMISSION_ALREADY_EXISTS)
assertThat((exception.cause as FuelError).response.statusCode).isEqualTo(403)
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.4",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"]
)
@Test
fun shouldCreateDomesticPayments_throwsSendInvalidFormatDetachedJws_v3_1_4() {
// Given
val consentRequest = aValidOBWriteDomesticConsent4()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse4>(
payment3_1_4.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_4,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse4>(
PaymentFactory.urlWithConsentId(
payment3_1_4.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_4
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(copyOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
// When
val exception = assertThrows(AssertionError::class.java) {
PaymentRS().submitPayment<OBWriteDomesticResponse4>(
payment3_1_4.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode,
com.forgerock.sapi.gateway.ob.uk.framework.constants.INVALID_FORMAT_DETACHED_JWS,
tppResource.tpp,
OBVersion.v3_1_4
)
}
// Then
assertThat((exception.cause as FuelError).response.statusCode).isEqualTo(400)
assertThat(exception.message.toString()).contains(com.forgerock.sapi.gateway.ob.uk.framework.errors.INVALID_FORMAT_DETACHED_JWS_ERROR)
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.4",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"]
)
@Test
fun shouldCreateDomesticPayments_throwsNoDetachedJws_v3_1_4() {
// Given
val consentRequest = aValidOBWriteDomesticConsent4()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse4>(
payment3_1_4.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_4,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse4>(
PaymentFactory.urlWithConsentId(
payment3_1_4.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_4
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(copyOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
// When
val exception = assertThrows(AssertionError::class.java) {
PaymentRS().submitPaymentNoDetachedJws<OBWriteDomesticResponse4>(
payment3_1_4.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode
)
}
// Then
assertThat((exception.cause as FuelError).response.statusCode).isEqualTo(400)
assertThat(exception.message.toString()).contains(com.forgerock.sapi.gateway.ob.uk.framework.errors.NO_DETACHED_JWS)
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.4",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"]
)
@Test
fun shouldCreateDomesticPayments_throwsNotPermittedB64HeaderAddedInTheDetachedJws_v3_1_4() {
// Given
val consentRequest = aValidOBWriteDomesticConsent4()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse4>(
payment3_1_4.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_4,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse4>(
PaymentFactory.urlWithConsentId(
payment3_1_4.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_4
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(copyOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
val signedPayload =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(paymentSubmissionRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid,
true
)
// When
val exception = assertThrows(AssertionError::class.java) {
PaymentRS().submitPayment<OBWriteDomesticResponse4>(
payment3_1_4.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode,
signedPayload,
tppResource.tpp, OBVersion.v3_1_4
)
}
// Then
assertThat((exception.cause as FuelError).response.responseMessage).isEqualTo(com.forgerock.sapi.gateway.ob.uk.framework.errors.UNAUTHORIZED)
assertThat((exception.cause as FuelError).response.statusCode).isEqualTo(401)
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.4",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"]
)
@Test
fun shouldCreateDomesticPayments_throwsSendInvalidKidDetachedJws_v3_1_4() {
// Given
val consentRequest = aValidOBWriteDomesticConsent4()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse4>(
payment3_1_4.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_4,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse4>(
PaymentFactory.urlWithConsentId(
payment3_1_4.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_4
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(copyOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
val signedPayload =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(paymentSubmissionRequest),
tppResource.tpp.signingKey,
INVALID_SIGNING_KID
)
// When
val exception = assertThrows(AssertionError::class.java) {
PaymentRS().submitPayment<OBWriteDomesticResponse4>(
payment3_1_4.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode,
signedPayload,
tppResource.tpp, OBVersion.v3_1_4
)
}
// Then
assertThat((exception.cause as FuelError).response.statusCode).isEqualTo(401)
assertThat((exception.cause as FuelError).response.responseMessage).isEqualTo(com.forgerock.sapi.gateway.ob.uk.framework.errors.UNAUTHORIZED)
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.4",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"]
)
@Test
fun shouldCreateDomesticPayments_throwsInvalidDetachedJws_detachedJwsHasDifferentConsentIdThanTheBody_v3_1_4() {
// Given
val consentRequest = aValidOBWriteDomesticConsent4()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse4>(
payment3_1_4.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_4,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse4>(
PaymentFactory.urlWithConsentId(
payment3_1_4.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_4
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(copyOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
patchedConsent.data.consentId = com.forgerock.sapi.gateway.ob.uk.framework.constants.INVALID_CONSENT_ID
val paymentSubmissionWithInvalidConsentId = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(copyOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
val signedPayload =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(paymentSubmissionWithInvalidConsentId),
tppResource.tpp.signingKey,
INVALID_SIGNING_KID
)
// When
val exception = assertThrows(AssertionError::class.java) {
PaymentRS().submitPayment<OBWriteDomesticResponse4>(
payment3_1_4.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode,
signedPayload,
tppResource.tpp, OBVersion.v3_1_4
)
}
// Then
assertThat((exception.cause as FuelError).response.responseMessage).isEqualTo(com.forgerock.sapi.gateway.ob.uk.framework.errors.UNAUTHORIZED)
assertThat((exception.cause as FuelError).response.statusCode).isEqualTo(401)
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.4",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"]
)
@Test
fun shouldCreateDomesticPayments_throwsInvalidDetachedJws_detachedJwsHasDifferentAmountThanTheBody_v3_1_4() {
// Given
val consentRequest = aValidOBWriteDomesticConsent4()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse4>(
payment3_1_4.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_4,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse4>(
PaymentFactory.urlWithConsentId(
payment3_1_4.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_4
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(copyOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
patchedConsent.data.initiation.instructedAmount.amount = "123123"
val paymentSubmissionInvalidAmount = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(copyOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
val signedPayload =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(paymentSubmissionInvalidAmount),
tppResource.tpp.signingKey,
INVALID_SIGNING_KID
)
// When
val exception = assertThrows(AssertionError::class.java) {
PaymentRS().submitPayment<OBWriteDomesticResponse4>(
payment3_1_4.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode,
signedPayload,
tppResource.tpp, OBVersion.v3_1_4
)
}
// Then
assertThat((exception.cause as FuelError).response.statusCode).isEqualTo(401)
assertThat((exception.cause as FuelError).response.responseMessage).isEqualTo(com.forgerock.sapi.gateway.ob.uk.framework.errors.UNAUTHORIZED)
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.3",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"],
compatibleVersions = ["v.3.1.2"]
)
@Test
fun createDomesticPayments_v3_1_3() {
// Given
val consentRequest = aValidOBWriteDomesticConsent3()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse3>(
payment3_1_3.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_3,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse3>(
PaymentFactory.urlWithConsentId(
payment3_1_3.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_3
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(copyOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
val signedPayload =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(paymentSubmissionRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid,
true
)
// When
val result = PaymentRS().submitPayment<OBWriteDomesticResponse3>(
payment3_1_3.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode,
signedPayload,
tppResource.tpp, OBVersion.v3_1_3
)
// Then
assertThat(result).isNotNull()
assertThat(result.data).isNotNull()
assertThat(result.data.consentId).isNotEmpty()
if (consent.data.charges.isNullOrEmpty())
{
assertThat(result.data.charges).isNotEmpty()
}
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.3",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"],
compatibleVersions = ["v.3.1.2"]
)
@Test
fun shouldCreateDomesticPayments_throwsPaymentAlreadyExists_v3_1_3() {
// Given
val consentRequest = aValidOBWriteDomesticConsent3()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse3>(
payment3_1_3.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_3,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse3>(
PaymentFactory.urlWithConsentId(
payment3_1_3.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_3
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(copyOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
val signedPayload =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(paymentSubmissionRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid,
true
)
// When
val exception = assertThrows(AssertionError::class.java) {
PaymentRS().submitPayment<OBWriteDomesticResponse3>(
payment3_1_3.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode,
signedPayload,
tppResource.tpp, OBVersion.v3_1_3
)
}
// Then
assertThat(exception.message.toString()).contains(com.forgerock.sapi.gateway.ob.uk.framework.errors.PAYMENT_SUBMISSION_ALREADY_EXISTS)
assertThat((exception.cause as FuelError).response.statusCode).isEqualTo(403)
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.3",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"],
compatibleVersions = ["v.3.1.2"]
)
@Test
fun shouldCreateDomesticPayments_throwsSendInvalidFormatDetachedJws_v3_1_3() {
// Given
val consentRequest = aValidOBWriteDomesticConsent3()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse3>(
payment3_1_3.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_3,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse3>(
PaymentFactory.urlWithConsentId(
payment3_1_3.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_3
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(copyOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
// When
val exception = assertThrows(AssertionError::class.java) {
PaymentRS().submitPayment<OBWriteDomesticResponse3>(
payment3_1_3.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode,
com.forgerock.sapi.gateway.ob.uk.framework.constants.INVALID_FORMAT_DETACHED_JWS,
tppResource.tpp, OBVersion.v3_1_3
)
}
// Then
assertThat((exception.cause as FuelError).response.statusCode).isEqualTo(400)
assertThat(exception.message.toString()).contains(com.forgerock.sapi.gateway.ob.uk.framework.errors.INVALID_FORMAT_DETACHED_JWS_ERROR)
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.3",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"],
compatibleVersions = ["v.3.1.2"]
)
@Test
fun shouldCreateDomesticPayments_throwsNoDetachedJws_v3_1_3() {
// Given
val consentRequest = aValidOBWriteDomesticConsent3()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse3>(
payment3_1_3.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_3,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse3>(
PaymentFactory.urlWithConsentId(
payment3_1_3.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_3
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(copyOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
// When
val exception = assertThrows(AssertionError::class.java) {
PaymentRS().submitPaymentNoDetachedJws<OBWriteDomesticResponse3>(
payment3_1_3.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode
)
}
// Then
assertThat((exception.cause as FuelError).response.statusCode).isEqualTo(400)
assertThat(exception.message.toString()).contains(com.forgerock.sapi.gateway.ob.uk.framework.errors.NO_DETACHED_JWS)
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.3",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"],
compatibleVersions = ["v.3.1.2"]
)
@Test
fun shouldCreateDomesticPayments_throwsSendInvalidKidDetachedJws_v3_1_3() {
// Given
val consentRequest = aValidOBWriteDomesticConsent3()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse3>(
payment3_1_3.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_3,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse3>(
PaymentFactory.urlWithConsentId(
payment3_1_3.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_3
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(copyOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
val signedPayload =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(paymentSubmissionRequest),
tppResource.tpp.signingKey,
INVALID_SIGNING_KID,
true
)
// When
val exception = assertThrows(AssertionError::class.java) {
PaymentRS().submitPayment<OBWriteDomesticResponse3>(
payment3_1_3.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode,
signedPayload,
tppResource.tpp, OBVersion.v3_1_3
)
}
// Then
assertThat((exception.cause as FuelError).response.statusCode).isEqualTo(401)
assertThat((exception.cause as FuelError).response.responseMessage).isEqualTo(com.forgerock.sapi.gateway.ob.uk.framework.errors.UNAUTHORIZED)
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.3",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"],
compatibleVersions = ["v.3.1.2"]
)
@Test
fun shouldCreateDomesticPayments_throwsB64ClaimMissingDetachedJws_v3_1_3() {
// Given
val consentRequest = aValidOBWriteDomesticConsent3()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse3>(
payment3_1_3.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_3,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse3>(
PaymentFactory.urlWithConsentId(
payment3_1_3.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_3
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(copyOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
val signedPayload =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(paymentSubmissionRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
// When
val exception = assertThrows(AssertionError::class.java) {
PaymentRS().submitPayment<OBWriteDomesticResponse3>(
payment3_1_3.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode,
signedPayload,
tppResource.tpp, OBVersion.v3_1_3
)
}
// Then
assertThat((exception.cause as FuelError).response.statusCode).isEqualTo(401)
assertThat((exception.cause as FuelError).response.responseMessage).isEqualTo(com.forgerock.sapi.gateway.ob.uk.framework.errors.UNAUTHORIZED)
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.3",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"],
compatibleVersions = ["v.3.1.2"]
)
@Test
fun shouldCreateDomesticPayments_throwsB64ClaimShouldBeFalseDetachedJws_v3_1_3() {
// Given
val consentRequest = aValidOBWriteDomesticConsent3()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse3>(
payment3_1_3.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_3,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse3>(
PaymentFactory.urlWithConsentId(
payment3_1_3.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_3
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(copyOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
val signedPayload =
signPayloadSubmitPaymentInvalidB64ClaimTrue(
defaultMapper.writeValueAsString(paymentSubmissionRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
// When
val exception = assertThrows(AssertionError::class.java) {
PaymentRS().submitPayment<OBWriteDomesticResponse3>(
payment3_1_3.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode,
signedPayload,
tppResource.tpp, OBVersion.v3_1_3
)
}
// Then
assertThat((exception.cause as FuelError).response.statusCode).isEqualTo(401)
assertThat((exception.cause as FuelError).response.responseMessage).isEqualTo(com.forgerock.sapi.gateway.ob.uk.framework.errors.UNAUTHORIZED)
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.3",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"],
compatibleVersions = ["v.3.1.2"]
)
@Test
fun shouldCreateDomesticPayments_throwsInvalidDetachedJws_detachedJwsHasDifferentConsentIdThanTheBody_v3_1_3() {
// Given
val consentRequest = aValidOBWriteDomesticConsent3()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse3>(
payment3_1_3.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_3,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse3>(
PaymentFactory.urlWithConsentId(
payment3_1_3.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_3
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(copyOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
patchedConsent.data.consentId = com.forgerock.sapi.gateway.ob.uk.framework.constants.INVALID_CONSENT_ID
val paymentSubmissionWithInvalidConsentId = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(copyOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
val signedPayload = signPayloadSubmitPayment(
defaultMapper.writeValueAsString(paymentSubmissionWithInvalidConsentId),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
// When
val exception = assertThrows(AssertionError::class.java) {
PaymentRS().submitPayment<OBWriteDomesticResponse3>(
payment3_1_3.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode,
signedPayload,
tppResource.tpp,
OBVersion.v3_1_3
)
}
// Then
assertThat((exception.cause as FuelError).response.responseMessage).isEqualTo(com.forgerock.sapi.gateway.ob.uk.framework.errors.UNAUTHORIZED)
assertThat((exception.cause as FuelError).response.statusCode).isEqualTo(401)
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.3",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"],
compatibleVersions = ["v.3.1.2"]
)
@Test
fun shouldCreateDomesticPayments_throwsInvalidDetachedJws_detachedJwsHasDifferentAmountThanTheBody_v3_1_3() {
// Given
val consentRequest = aValidOBWriteDomesticConsent3()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse3>(
payment3_1_3.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_3,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse3>(
PaymentFactory.urlWithConsentId(
payment3_1_3.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_3
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(copyOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
patchedConsent.data.initiation.instructedAmount.amount = "123123"
val paymentSubmissionInvalidAmount = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(copyOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
val signedPayload = signPayloadSubmitPayment(
defaultMapper.writeValueAsString(paymentSubmissionInvalidAmount),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
// When
val exception = assertThrows(AssertionError::class.java) {
PaymentRS().submitPayment<OBWriteDomesticResponse3>(
payment3_1_3.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode,
signedPayload,
tppResource.tpp,
OBVersion.v3_1_3
)
}
// Then
assertThat((exception.cause as FuelError).response.statusCode).isEqualTo(401)
assertThat((exception.cause as FuelError).response.responseMessage).isEqualTo(com.forgerock.sapi.gateway.ob.uk.framework.errors.UNAUTHORIZED)
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.1",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"],
compatibleVersions = ["v.3.1"]
)
@Test
fun createDomesticPayments_v3_1_1() {
// Given
val consentRequest = aValidOBWriteDomesticConsent2()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse2>(
payment3_1_1.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_1,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse2>(
PaymentFactory.urlWithConsentId(
payment3_1_1.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_1
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(mapOBDomestic2ToOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
val signedPayload =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(paymentSubmissionRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid,
true
)
// When
val result = PaymentRS().submitPayment<OBWriteDomesticResponse2>(
payment3_1_1.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode,
signedPayload,
tppResource.tpp, OBVersion.v3_1_1
)
// Then
assertThat(result).isNotNull()
assertThat(result.data).isNotNull()
assertThat(result.data.consentId).isNotEmpty()
if (consent.data.charges.isNullOrEmpty())
{
assertThat(result.data.charges).isNotEmpty()
}
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.1",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"],
compatibleVersions = ["v.3.1"]
)
@Test
fun shouldCreateDomesticPayments_throwsPaymentAlreadyExists_v3_1_1() {
// Given
val consentRequest = aValidOBWriteDomesticConsent2()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse2>(
payment3_1_1.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_1,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse2>(
PaymentFactory.urlWithConsentId(
payment3_1_1.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_1
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(mapOBDomestic2ToOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
val signedPayload =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(paymentSubmissionRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid,
true
)
// When
val exception = assertThrows(AssertionError::class.java) {
PaymentRS().submitPayment<OBWriteDomesticResponse2>(
payment3_1_1.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode,
signedPayload,
tppResource.tpp, OBVersion.v3_1_1
)
}
// Then
assertThat(exception.message.toString()).contains(com.forgerock.sapi.gateway.ob.uk.framework.errors.PAYMENT_SUBMISSION_ALREADY_EXISTS)
assertThat((exception.cause as FuelError).response.statusCode).isEqualTo(403)
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.1",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"],
compatibleVersions = ["v.3.1"]
)
@Test
fun shouldCreateDomesticPayments_throwsSendInvalidFormatDetachedJws_v3_1_1() {
// Given
val consentRequest = aValidOBWriteDomesticConsent2()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse2>(
payment3_1_1.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_1,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse2>(
PaymentFactory.urlWithConsentId(
payment3_1_1.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_1
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(mapOBDomestic2ToOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
// When
val exception = assertThrows(AssertionError::class.java) {
PaymentRS().submitPayment<OBWriteDomesticResponse2>(
payment3_1_1.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode,
com.forgerock.sapi.gateway.ob.uk.framework.constants.INVALID_FORMAT_DETACHED_JWS,
tppResource.tpp, OBVersion.v3_1_1
)
}
// Then
assertThat((exception.cause as FuelError).response.statusCode).isEqualTo(400)
assertThat(exception.message.toString()).contains(com.forgerock.sapi.gateway.ob.uk.framework.errors.INVALID_FORMAT_DETACHED_JWS_ERROR)
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.1",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"],
compatibleVersions = ["v.3.1"]
)
@Test
fun shouldCreateDomesticPayments_throwsNoDetachedJws_v3_1_1() {
// Given
val consentRequest = aValidOBWriteDomesticConsent2()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse2>(
payment3_1_1.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_1,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse2>(
PaymentFactory.urlWithConsentId(
payment3_1_1.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_1
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(mapOBDomestic2ToOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
// When
val exception = assertThrows(AssertionError::class.java) {
PaymentRS().submitPaymentNoDetachedJws<OBWriteDomesticResponse2>(
payment3_1_1.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode
)
}
// Then
assertThat((exception.cause as FuelError).response.statusCode).isEqualTo(400)
assertThat(exception.message.toString()).contains(com.forgerock.sapi.gateway.ob.uk.framework.errors.NO_DETACHED_JWS)
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.1",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"],
compatibleVersions = ["v.3.1"]
)
@Test
fun shouldCreateDomesticPayments_throwsSendInvalidKidDetachedJws_v3_1_1() {
// Given
val consentRequest = aValidOBWriteDomesticConsent2()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse2>(
payment3_1_1.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_1,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse2>(
PaymentFactory.urlWithConsentId(
payment3_1_1.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_1
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(mapOBDomestic2ToOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
val signedPayload =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(paymentSubmissionRequest),
tppResource.tpp.signingKey,
INVALID_SIGNING_KID
)
// When
val exception = assertThrows(AssertionError::class.java) {
PaymentRS().submitPayment<OBWriteDomesticResponse2>(
payment3_1_1.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode,
signedPayload,
tppResource.tpp, OBVersion.v3_1_1
)
}
// Then
assertThat((exception.cause as FuelError).response.statusCode).isEqualTo(401)
assertThat((exception.cause as FuelError).response.responseMessage).isEqualTo(com.forgerock.sapi.gateway.ob.uk.framework.errors.UNAUTHORIZED)
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.1",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"],
compatibleVersions = ["v.3.1"]
)
@Test
fun shouldCreateDomesticPayments_throwsB64ClaimMissingDetachedJws_v3_1_1() {
// Given
val consentRequest = aValidOBWriteDomesticConsent2()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse2>(
payment3_1_1.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_1,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse2>(
PaymentFactory.urlWithConsentId(
payment3_1_1.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_1
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(mapOBDomestic2ToOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
val signedPayload =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(paymentSubmissionRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
// When
val exception = assertThrows(AssertionError::class.java) {
PaymentRS().submitPayment<OBWriteDomesticResponse2>(
payment3_1_1.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode,
signedPayload,
tppResource.tpp,
OBVersion.v3_1_1
)
}
// Then
assertThat((exception.cause as FuelError).response.statusCode).isEqualTo(401)
assertThat((exception.cause as FuelError).response.responseMessage).isEqualTo(com.forgerock.sapi.gateway.ob.uk.framework.errors.UNAUTHORIZED)
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.1",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"],
compatibleVersions = ["v.3.1"]
)
@Test
fun shouldCreateDomesticPayments_throwsB64ClaimShouldBeFalseDetachedJws_v3_1_1() {
// Given
val consentRequest = aValidOBWriteDomesticConsent2()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse2>(
payment3_1_1.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_1,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse2>(
PaymentFactory.urlWithConsentId(
payment3_1_1.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_1
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(mapOBDomestic2ToOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
val signedPayload =
signPayloadSubmitPaymentInvalidB64ClaimTrue(
defaultMapper.writeValueAsString(paymentSubmissionRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
// When
val exception = assertThrows(AssertionError::class.java) {
PaymentRS().submitPayment<OBWriteDomesticResponse2>(
payment3_1_1.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode,
signedPayload,
tppResource.tpp,
OBVersion.v3_1_1
)
}
// Then
assertThat((exception.cause as FuelError).response.statusCode).isEqualTo(401)
assertThat((exception.cause as FuelError).response.responseMessage).isEqualTo(com.forgerock.sapi.gateway.ob.uk.framework.errors.UNAUTHORIZED)
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.1",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"],
compatibleVersions = ["v.3.1"]
)
@Test
fun shouldCreateDomesticPayments_throwsInvalidDetachedJws_detachedJwsHasDifferentConsentIdThanTheBody_v3_1_1() {
// Given
val consentRequest = aValidOBWriteDomesticConsent2()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse2>(
payment3_1_1.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_1,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse2>(
PaymentFactory.urlWithConsentId(
payment3_1_1.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_1
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(mapOBDomestic2ToOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
patchedConsent.data.consentId = com.forgerock.sapi.gateway.ob.uk.framework.constants.INVALID_CONSENT_ID
val paymentSubmissionWithInvalidConsentId = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(mapOBDomestic2ToOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
val signedPayload = signPayloadSubmitPayment(
defaultMapper.writeValueAsString(paymentSubmissionWithInvalidConsentId),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
// When
val exception = assertThrows(AssertionError::class.java) {
PaymentRS().submitPayment<OBWriteDomesticResponse2>(
payment3_1_1.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode,
signedPayload,
tppResource.tpp,
OBVersion.v3_1_1
)
}
// Then
assertThat((exception.cause as FuelError).response.responseMessage).isEqualTo(com.forgerock.sapi.gateway.ob.uk.framework.errors.UNAUTHORIZED)
assertThat((exception.cause as FuelError).response.statusCode).isEqualTo(401)
}
@EnabledIfVersion(
type = "payments",
apiVersion = "v3.1.1",
operations = ["CreateDomesticPayment", "CreateDomesticPaymentConsent", "GetDomesticPaymentConsent"],
apis = ["domestic-payments", "domestic-payment-consents"],
compatibleVersions = ["v.3.1"]
)
@Test
fun shouldCreateDomesticPayments_throwsInvalidDetachedJws_detachedJwsHasDifferentAmountThanTheBody_v3_1_1() {
// Given
val consentRequest = aValidOBWriteDomesticConsent2()
val signedPayloadConsent =
signPayloadSubmitPayment(
defaultMapper.writeValueAsString(consentRequest),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
val consent = PaymentRS().consent<OBWriteDomesticConsentResponse2>(
payment3_1_1.Links.links.CreateDomesticPaymentConsent,
consentRequest,
tppResource.tpp,
OBVersion.v3_1_1,
signedPayloadConsent
)
assertThat(consent).isNotNull()
assertThat(consent.data).isNotNull()
assertThat(consent.data.consentId).isNotEmpty()
Assertions.assertThat(consent.data.status.toString()).`is`(Status.consentCondition)
// accessToken to submit payment use the grant type authorization_code
val accessTokenAuthorizationCode = PaymentAS().authorizeConsent(
consent.data.consentId,
tppResource.tpp.registrationResponse,
psu,
tppResource.tpp
)
val patchedConsent = PaymentRS().getConsent<OBWriteDomesticConsentResponse2>(
PaymentFactory.urlWithConsentId(
payment3_1_1.Links.links.GetDomesticPaymentConsent,
consent.data.consentId
),
tppResource.tpp,
OBVersion.v3_1_1
)
assertThat(patchedConsent).isNotNull()
assertThat(patchedConsent.data).isNotNull()
assertThat(patchedConsent.risk).isNotNull()
assertThat(patchedConsent.data.consentId).isNotEmpty()
Assertions.assertThat(patchedConsent.data.status.toString()).`is`(Status.consentCondition)
val paymentSubmissionRequest = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(mapOBDomestic2ToOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
patchedConsent.data.initiation.instructedAmount.amount = "123123"
val paymentSubmissionInvalidAmount = OBWriteDomestic2().data(
OBWriteDomestic2Data()
.consentId(patchedConsent.data.consentId)
.initiation(mapOBDomestic2ToOBWriteDomestic2DataInitiation(patchedConsent.data.initiation))
).risk(patchedConsent.risk)
val signedPayload = signPayloadSubmitPayment(
defaultMapper.writeValueAsString(paymentSubmissionInvalidAmount),
tppResource.tpp.signingKey,
tppResource.tpp.signingKid
)
// When
val exception = assertThrows(AssertionError::class.java) {
PaymentRS().submitPayment<OBWriteDomesticResponse2>(
payment3_1_1.Links.links.CreateDomesticPayment,
paymentSubmissionRequest,
accessTokenAuthorizationCode,
signedPayload,
tppResource.tpp,
OBVersion.v3_1_1
)
}
// Then
assertThat((exception.cause as FuelError).response.statusCode).isEqualTo(401)
assertThat((exception.cause as FuelError).response.responseMessage).isEqualTo(com.forgerock.sapi.gateway.ob.uk.framework.errors.UNAUTHORIZED)
}
}
| 7 | null | 0 | 5 | d8b50e474df5df5a8e0ca0743ab377a52192fbc7 | 89,982 | secure-api-gateway-ob-uk-functional-tests | Apache License 2.0 |
plugins/search-everywhere-ml/ranking/test/com/intellij/searchEverywhereMl/ranking/SearchEverywhereLoggingTestCase.kt | ingokegel | 72,937,917 | false | null | package com.intellij.searchEverywhereMl.ranking
import com.intellij.ide.actions.searcheverywhere.ActionSearchEverywhereContributor
import com.intellij.ide.actions.searcheverywhere.SearchAdapter
import com.intellij.ide.actions.searcheverywhere.SearchEverywhereMlContributorReplacement
import com.intellij.ide.actions.searcheverywhere.SearchEverywhereUI
import com.intellij.internal.statistic.FUCollectorTestCase
import com.intellij.openapi.extensions.ExtensionPoint
import com.intellij.openapi.extensions.impl.ExtensionPointImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.searchEverywhereMl.log.MLSE_RECORDER_ID
import com.intellij.searchEverywhereMl.ranking.SearchEverywhereMLStatisticsCollector.Fields.SEARCH_RESTARTED
import com.intellij.searchEverywhereMl.ranking.SearchEverywhereMLStatisticsCollector.Fields.SESSION_FINISHED
import com.intellij.testFramework.LightPlatformTestCase
import com.intellij.testFramework.PlatformTestUtil
import com.jetbrains.fus.reporting.model.lion3.LogEvent
import java.util.concurrent.CompletableFuture
import javax.swing.SwingUtilities
abstract class SearchEverywhereLoggingTestCase : LightPlatformTestCase() {
private val extensionPointMaskManager = ExtensionPointMaskManager()
private fun createSearchEverywhereUI(project: Project): SearchEverywhereUI = SearchEverywhereUI(project, listOf(
MockSearchEverywhereContributor(ActionSearchEverywhereContributor::class.java.simpleName) { pattern, progressIndicator, consumer ->
consumer.process("registry")
}
))
fun runSearchEverywhereAndCollectLogEvents(testProcedure: SearchEverywhereUI.() -> Unit): List<LogEvent> {
return runSearchEverywhereAndCollectLogEvents(::createSearchEverywhereUI, testProcedure)
}
fun runSearchEverywhereAndCollectLogEvents(searchEverywhereUIProvider: (Project) -> SearchEverywhereUI,
testProcedure: SearchEverywhereUI.() -> Unit): List<LogEvent> {
maskContributorReplacementService()
extensionPointMaskManager.mask()
val result = performTest(searchEverywhereUIProvider, testProcedure)
extensionPointMaskManager.dispose()
return result.filter { it.event.id in listOf(SESSION_FINISHED.eventId, SEARCH_RESTARTED.eventId) }
}
private fun performTest(searchEverywhereUIProvider: (Project) -> SearchEverywhereUI,
testProcedure: SearchEverywhereUI.() -> Unit): List<LogEvent> {
val emptyDisposable = Disposer.newDisposable()
return FUCollectorTestCase.collectLogEvents(MLSE_RECORDER_ID, emptyDisposable) {
val searchEverywhereUI = searchEverywhereUIProvider.invoke(project)
PlatformTestUtil.waitForAlarm(10) // wait for rebuild list (session started)
testProcedure(searchEverywhereUI)
Disposer.dispose(searchEverywhereUI) // Otherwise, the instance seems to be reused between different tests
}.also {
Disposer.dispose(emptyDisposable)
}
}
fun SearchEverywhereUI.type(query: CharSequence) = also { searchEverywhereUI ->
query.forEach { character ->
// We are going to add a listener to search finished, so that every character
// is typed right after the list of results gets updated.
// Otherwise, we'd typed all characters pretty much at once.
val future = CompletableFuture<Unit>()
searchEverywhereUI.addSearchListener(object : SearchAdapter() {
override fun searchFinished(items: MutableList<Any>) {
future.complete(Unit)
SwingUtilities.invokeLater { searchEverywhereUI.removeSearchListener(this) }
}
})
searchEverywhereUI.searchField.text += character
PlatformTestUtil.waitForFuture(future)
}
}
private fun maskContributorReplacementService() {
// Otherwise it will attempt to replace the mock contributor,
// for which we need the search provider id to be ActionsSearchEverywhereContributor
// to be replaced with SemanticActionSearchEverywhereContributor,
// that will fail, as it will try to cast the mock contributor to the action's one
SearchEverywhereMlContributorReplacement.EP_NAME.point.maskForSingleTest(emptyList())
}
protected fun <V : Any> ExtensionPoint<V>.maskForSingleTest(newList: List<V>) {
extensionPointMaskManager.addServiceToMask(this, newList)
}
private class ExtensionPointMaskManager {
private val serviceMaskDisposable = Disposer.newDisposable()
private val servicesToMask = mutableListOf<() -> Unit>()
fun <T : Any> addServiceToMask(ep: ExtensionPoint<T>, maskWith: List<T>) {
val maskingFunction = { (ep as ExtensionPointImpl<T>).maskAll(maskWith, serviceMaskDisposable, false) }
servicesToMask.add(maskingFunction)
}
fun mask() {
servicesToMask.forEach { it.invoke() }
}
fun dispose() {
Disposer.dispose(serviceMaskDisposable)
servicesToMask.clear()
}
}
}
| 251 | null | 5079 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 4,948 | intellij-community | Apache License 2.0 |
src/main/kotlin/io/unthrottled/amii/personality/MoodStatusBarProvider.kt | ani-memes | 303,354,188 | false | null | package io.unthrottled.amii.personality
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.StatusBar
import com.intellij.openapi.wm.StatusBarWidget
import com.intellij.openapi.wm.StatusBarWidgetFactory
import io.unthrottled.amii.config.Config
class MoodStatusBarProvider : StatusBarWidgetFactory {
companion object {
private const val ID = "io.unthrottled.amii.personality.MoodStatusBarProvider"
}
override fun getId(): String = ID
override fun getDisplayName(): String =
"MIKU Mood Display"
override fun disposeWidget(widget: StatusBarWidget) {
widget.dispose()
}
override fun isAvailable(project: Project): Boolean =
true
override fun createWidget(project: Project): StatusBarWidget =
MoodStatusBarWidget(project)
override fun canBeEnabledOn(statusBar: StatusBar): Boolean =
true
override fun isConfigurable(): Boolean = true
override fun isEnabledByDefault(): Boolean =
Config.instance.showMood
}
| 7 | null | 14 | 257 | c9a4ef10f6e1a5ce68dc3a007b45cadbc33deed0 | 984 | AMII | Apache License 2.0 |
src/main/kotlin/dev/fakek/FakeContext.kt | CodyEngel | 226,218,138 | false | null | @file:Suppress("WildcardImport")
package dev.fakek
import com.github.javafaker.Faker
import dev.fakek.fakes.FakeSemanticVersion
import dev.fakek.fakes.*
/**
* The top level function for interacting with FakeK. This provides an instance of [FakeContext] scoped to this
* function. This allows for all interactions with [FakeContext] to persist during the usage of [fakek].
*
* @param fakeContext provides a [FakeContext] instance to be used, the default value is a new instance of
* [FakeContext].
* @param fakeContextScope provides a scope on the provided [fakeContext] instance.
*/
fun <T> fakek(
fakeContext: FakeContext = FakeContext(),
fakeContextScope: FakeContext.() -> T
): T = fakeContext.fakeContextScope()
/**
* FakeContext acts as a Context object for the library. It provides an easy way to access all of the fakes within the
* library along with caching certain values to allow for proper scoping with the [fakek] function.
*
* @param faker is an instance of [Faker] which will be used for generating the various fakes. This will default to a
* new instance of [Faker].
*/
class FakeContext(private val faker: Faker = Faker.instance()) {
private val fakerAddress by lazy { faker.address() }
private val fakerAncient by lazy { faker.ancient() }
private val fakerApp by lazy { faker.app() }
private val fakerArtist by lazy { faker.artist() }
private val fakerAvatar by lazy { faker.avatar() }
private val fakerAviation by lazy { faker.aviation() }
private val fakerBeer by lazy { faker.beer() }
private val fakerBook by lazy { faker.book() }
private val fakerBoolean by lazy { faker.bool() }
private val fakerCat by lazy { faker.cat() }
private val fakerColor by lazy { faker.color() }
private val fakerCompany by lazy { faker.company() }
private val fakerCrypto by lazy { faker.crypto() }
private val fakerDisease by lazy { faker.medical() }
private val fakerDog by lazy { faker.dog() }
private val fakerEducator by lazy { faker.educator() }
private val fakerInternet by lazy { faker.internet() }
private val fakerJob by lazy { faker.job() }
private val fakerName by lazy { faker.name() }
private val fakerSSN by lazy { faker.idNumber() }
/**
* Provides a [FakeAddress].
*/
val fakeAddress by lazy { FakeAddress(fakerAddress) }
/**
* Provides a [FakeAncient].
*/
val fakeAncient by lazy { FakeAncient(fakerAncient) }
/**
* Provides a [FakeApp].
*/
val fakeApp by lazy { FakeApp(fakerApp, FakeSemanticVersion()) }
/**
* Provides a [FakeArtist].
*/
val fakeArtist by lazy { FakeArtist(fakerArtist) }
/**
* Provides a [FakeAvatar].
*/
val fakeAvatar by lazy { FakeAvatar(fakerAvatar) }
/**
* Provides a [FakeAviation].
*/
val fakeAviation by lazy { FakeAviation(fakerAviation) }
/**
* Provides a [FakeBeer].
*/
val fakeBeer by lazy { FakeBeer(fakerBeer) }
/**
* Provides a [FakeBook].
*/
val fakeBook by lazy { FakeBook(fakerBook) }
/**
* Provides a [FakeBoolean].
*/
val fakeBoolean by lazy { FakeBoolean(fakerBoolean) }
/**
* Provides a [FakeCat].
*/
val fakeCat by lazy { FakeCat(fakerCat) }
/**
* Provides a [FakeColor].
*/
val fakeColor by lazy { FakeColor(fakerColor) }
/**
* Provides a [FakeCommerce].
*/
val fakeCommerce by lazy { FakeCommerce(fakeAddress, fakeCompany) }
/**
* Provides a [FakeCompany].
*/
val fakeCompany by lazy { FakeCompany(fakerCompany, fakeUrl) }
/**
* Provides a [FakeCreditCard].
*/
val fakeCreditCard by lazy { FakeCreditCard.create() }
/**
* Provides a [fakeCrypto].
*/
val fakeCrypto by lazy { FakeCrypto(fakerCrypto) }
/**
* Provides a [FakeDisease].
*/
val fakeDisease by lazy { FakeDisease(fakerDisease) }
/**
* Provides a [FakeEducator].
*/
val fakeEducator by lazy { FakeEducator(fakerEducator) }
/**
* Provides a [FakeEmailAddress] making use of [fakeName] to help generate parts of the email address.
*/
val fakeEmailAddress by lazy { FakeEmailAddress(fakeName) }
/**
* Provides a [FakeName].
*/
val fakeName by lazy { FakeName(fakerName) }
/**
* Provides a [FakePassword].
*/
val fakePassword by lazy { FakePassword(fakerInternet) }
/**
* Provides a [FakeSSN].
*/
val fakeSSN by lazy { FakeSSN(fakerSSN) }
/**
* Provides a [FakeUrl].
*/
val fakeUrl by lazy { FakeUrl(fakerInternet) }
/**
* Provides a [FakeDog].
*/
val fakeDog by lazy { FakeDog(fakerDog) }
/**
* Provides a [FakeJob].
*/
val fakeJob by lazy { FakeJob(fakerJob) }
}
| 6 | Kotlin | 7 | 7 | e3d1442059b1196a020c71fb9424266bf12fe1a1 | 4,846 | fakek | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.