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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
idea/testData/intentions/toInfixCall/doubleFunctionCall.kt | staltz | 38,581,975 | true | {"Java": 15450397, "Kotlin": 8578737, "JavaScript": 176060, "HTML": 22810, "Lex": 17327, "Protocol Buffer": 13024, "ANTLR": 9689, "CSS": 9431, "Shell": 3931, "IDL": 3257, "Groovy": 3010, "Batchfile": 2831} | fun foo(x: Int) {
(x.<caret>times(1)).div(2)
}
| 0 | Java | 0 | 1 | 80074c71fa925a1c7173e3fffeea4cdc5872460f | 51 | kotlin | Apache License 2.0 |
app/src/main/java/org/stepic/droid/configuration/ConfigImpl.kt | StepicOrg | 42,045,161 | false | null | package org.stepic.droid.configuration
import android.content.Context
import com.google.gson.FieldNamingPolicy
import com.google.gson.GsonBuilder
import org.stepic.droid.di.AppSingleton
import org.stepic.droid.web.Api
import java.io.InputStreamReader
import java.nio.charset.Charset
import javax.inject.Inject
@AppSingleton
class ConfigImpl
private constructor() : Config {
@AppSingleton
class ConfigFactory
@Inject
constructor(private val context: Context) {
fun create(): ConfigImpl {
return context.assets.open("configs/config.json").use {
val gson = GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create()
gson.fromJson(InputStreamReader(it, Charset.defaultCharset()), ConfigImpl::class.java)
}
}
}
private val apiHostUrl: String? = null
private val oauthClientId: String? = null
private val oauthClientSecret: String? = null
private val grantType: String? = null
private val oauthClientIdSocial: String? = null
private val oauthClientSecretSocial: String? = null
private val grantTypeSocial: String? = null
private val refreshGrantType: String? = null
private val redirectUri: String? = null
private val zendeskHost: String? = null
private val courseCloseable: Boolean = false
private val customUpdate: Boolean = false
private val updateEndpoint: String? = null
private val firebaseDomain: String? = null
private val googleServerClientId: String? = null
private val termsOfService: String? = null
private val privacyPolicy: String? = null
private val csrfCookieName: String? = null
private val sessionCookieName: String? = null
private val amplitudeApiKey: String? = null
private val isAppInStore: Boolean = false
override fun getOAuthClientId(type: Api.TokenType) = when (type) {
Api.TokenType.social -> oauthClientIdSocial
Api.TokenType.loginPassword -> oauthClientId
}
override fun getBaseUrl() = apiHostUrl
override fun getOAuthClientSecret(type: Api.TokenType) = when (type) {
Api.TokenType.social -> oauthClientSecretSocial
Api.TokenType.loginPassword -> oauthClientSecret
}
override fun getGrantType(type: Api.TokenType) = when (type) {
Api.TokenType.social -> grantTypeSocial
Api.TokenType.loginPassword -> grantType
}
override fun getRefreshGrantType() = refreshGrantType
override fun getRedirectUri() = redirectUri
override fun getZendeskHost() = zendeskHost
override fun isUserCanDropCourse() = courseCloseable
override fun isCustomUpdateEnable() = customUpdate
override fun getUpdateEndpoint() = updateEndpoint
override fun getFirebaseDomain() = firebaseDomain
override fun getGoogleServerClientId() = googleServerClientId
override fun getPrivacyPolicyUrl() = privacyPolicy
override fun getTermsOfServiceUrl() = termsOfService
override fun getCsrfTokenCookieName() = csrfCookieName
override fun getSessionCookieName() = sessionCookieName
override fun isAppInStore() = isAppInStore
override fun getAmplitudeApiKey() = amplitudeApiKey
}
| 13 | null | 54 | 189 | dd12cb96811a6fc2a7addcd969381570e335aca7 | 3,267 | stepik-android | Apache License 2.0 |
src/main/kotlin/com/aemtools/lang/htl/file/HtlFileViewProvider.kt | iannovic | 107,144,305 | true | {"Kotlin": 574047, "HTML": 14948, "Java": 4019, "Lex": 3652} | package com.aemtools.lang.htl.file
import com.aemtools.lang.htl.HtlLanguage.getDefaultTemplateLang
import com.aemtools.lang.htl.psi.HtlTypes.HEL
import com.aemtools.lang.htl.psi.HtlTypes.OUTER_LANGUAGE
import com.intellij.lang.Language
import com.intellij.lang.LanguageParserDefinitions
import com.intellij.lang.ParserDefinition
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.LanguageSubstitutors
import com.intellij.psi.MultiplePsiFilesPerDocumentFileViewProvider
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.psi.impl.source.PsiFileImpl
import com.intellij.psi.templateLanguages.ConfigurableTemplateLanguageFileViewProvider
import com.intellij.psi.templateLanguages.TemplateDataElementType
import com.intellij.psi.templateLanguages.TemplateDataLanguageMappings
import com.intellij.util.containers.ContainerUtil
import gnu.trove.THashSet
import java.util.concurrent.ConcurrentMap
/**
* @author <NAME>
*/
class HtlFileViewProvider @JvmOverloads constructor(
manager: PsiManager,
virtualFile: VirtualFile,
physical: Boolean,
val myBaseLanguage: Language,
val myTemplateLanguage: Language = getTemplateDataLanguage(manager, virtualFile))
: MultiplePsiFilesPerDocumentFileViewProvider(manager, virtualFile, physical),
ConfigurableTemplateLanguageFileViewProvider {
companion object {
private val TEMPLATE_DATA_TO_LANG: ConcurrentMap<String, TemplateDataElementType>
= ContainerUtil.newConcurrentMap()
private fun getTemplateDataElementType(lang: Language): TemplateDataElementType {
var result = TEMPLATE_DATA_TO_LANG.get(lang.id)
if (result != null) {
return result
}
val created = TemplateDataElementType("SIGHTLY_DATA_TEMPLATE", lang, OUTER_LANGUAGE, HEL)
return TEMPLATE_DATA_TO_LANG.putIfAbsent(lang.id, created) ?: created
}
}
override fun getBaseLanguage(): Language = myBaseLanguage
override fun getTemplateDataLanguage(): Language = myTemplateLanguage
override fun supportsIncrementalReparse(rootLanguage: Language): Boolean = false
override fun getLanguages(): Set<Language> {
return THashSet<Language>(listOf(myBaseLanguage, myTemplateLanguage))
}
override fun cloneInner(virtualFile: VirtualFile): MultiplePsiFilesPerDocumentFileViewProvider {
return HtlFileViewProvider(manager, virtualFile, false, myBaseLanguage, myTemplateLanguage)
}
override fun createFile(lang: Language): PsiFile? {
val parserDefinition = getDefinition(lang) ?: return null
return when {
lang.`is`(templateDataLanguage) -> {
val file: PsiFileImpl = parserDefinition.createFile(this) as PsiFileImpl
file.contentElementType = getTemplateDataElementType(myBaseLanguage)
file
}
lang.isKindOf(baseLanguage) -> {
parserDefinition.createFile(this)
}
else -> null
}
}
private fun getDefinition(lang: Language): ParserDefinition? {
return if (lang.isKindOf(myBaseLanguage))
LanguageParserDefinitions.INSTANCE.forLanguage(if (lang.`is`(baseLanguage)) lang else baseLanguage)
else
LanguageParserDefinitions.INSTANCE.forLanguage(lang)
}
}
/**
* Get template data language.
*
* @param manager the psi manager
* @param virtualFile the virtual file
*
* @return the template language
*/
fun getTemplateDataLanguage(manager: PsiManager, virtualFile: VirtualFile): Language {
val mappings = TemplateDataLanguageMappings.getInstance(manager.project)
var dataLang: Language? = null
if (mappings != null) {
dataLang = mappings.getMapping(virtualFile)
}
if (dataLang == null) {
dataLang = getDefaultTemplateLang().language
}
val substituteLanguage = LanguageSubstitutors.INSTANCE.substituteLanguage(dataLang, virtualFile, manager.project)
if (TemplateDataLanguageMappings.getTemplateableLanguages().contains(substituteLanguage)) {
dataLang = substituteLanguage
}
return dataLang
}
| 0 | Kotlin | 0 | 0 | d9c1558872fd5e32f18e0bab0afa8f4495da95b0 | 3,981 | aemtools | MIT License |
compose/src/main/java/dev/medzik/android/compose/ui/textfield/AnimatedTextFieldBadge.kt | M3DZIK | 698,762,035 | false | {"Kotlin": 116204} | package dev.medzik.android.compose.ui.textfield
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.unit.dp
import dev.medzik.android.compose.theme.infoContainer
import dev.medzik.android.compose.theme.isDark
import dev.medzik.android.compose.theme.spacing
import dev.medzik.android.compose.theme.successContainer
import dev.medzik.android.compose.theme.warningContainer
@Composable
internal fun AnimatedTextFieldBadge(
modifier: Modifier = Modifier,
badge: TextFieldValue.ValueLabel? = null,
error: String? = null
) {
val type = when {
error != null -> TextFieldValue.ValueLabel.Type.ERROR
badge != null -> badge.type
else -> TextFieldValue.ValueLabel.Type.ERROR
}
AnimatedTextFieldBadge(
modifier = modifier,
type = type,
text = error ?: badge?.text ?: "",
)
}
@Composable
internal fun AnimatedTextFieldBadge(
modifier: Modifier = Modifier,
type: TextFieldValue.ValueLabel.Type,
text: String
) {
AnimatedTextFieldBadge(
modifier = modifier.padding(
top = 8.dp,
bottom = 8.dp,
),
backgroundColor = when (type) {
TextFieldValue.ValueLabel.Type.SUCCESS -> MaterialTheme.colorScheme.successContainer
TextFieldValue.ValueLabel.Type.INFO -> MaterialTheme.colorScheme.infoContainer
TextFieldValue.ValueLabel.Type.WARNING -> MaterialTheme.colorScheme.warningContainer
TextFieldValue.ValueLabel.Type.ERROR -> MaterialTheme.colorScheme.errorContainer
},
text = text
)
}
@Composable
internal fun AnimatedTextFieldBadge(
modifier: Modifier = Modifier,
backgroundColor: Color,
text: String
) {
val backgroundColorState = animateColorAsState(
backgroundColor,
label = "TextFieldBadge background color"
)
val contentColor = run {
val color = if (MaterialTheme.colorScheme.isDark) {
Color.White
} else {
Color.Black
}
val tint = backgroundColor.copy(alpha = 0.1f)
tint.compositeOver(color)
}
val contentColorState = animateColorAsState(
contentColor,
label = "TextFieldBadge content color"
)
Row(
modifier = modifier
.clip(MaterialTheme.shapes.small)
.drawBehind {
val color = backgroundColorState.value
drawRect(color)
}
.padding(
horizontal = MaterialTheme.spacing.small,
vertical = MaterialTheme.spacing.extraSmall
),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
modifier = Modifier.animateContentSize(),
text = text,
color = contentColorState.value,
style = MaterialTheme.typography.labelSmall,
)
}
}
| 0 | Kotlin | 0 | 2 | bb2fed8304f2bb20429549f2ea47852d3acecf31 | 3,422 | android-libs | MIT License |
app/src/main/java/com/nbmlon/mushroomer/ui/commu/CommuFragmentBoard_hot.kt | nbmLon99 | 658,672,044 | false | {"Kotlin": 222650} | package com.nbmlon.mushroomer.ui.commu
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import com.nbmlon.mushroomer.R
import com.nbmlon.mushroomer.data.posts.PostsRepository
import com.nbmlon.mushroomer.databinding.FragmentCommuHotBinding
/**
* 인기게시판
*/
class CommuFragmentBoard_hot private constructor(): CommuBoardFragment() {
companion object {
const val TAG = "CommuFragmentBoard_hot"
// TODO: Rename and change types and number of parameters
@JvmStatic
fun getInstance(param1: Int) =
CommuFragmentBoard_hot().apply {
arguments = Bundle().apply {
putInt(BOARD_TYPE_ORDINAL, param1)
}
}
}
private var board_typd_idx: Int? = null
private lateinit var mBoardType: BoardType
private var _binding: FragmentCommuHotBinding? = null
private val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
board_typd_idx = it.getInt(BOARD_TYPE_ORDINAL)
mBoardType = BoardType.values()[board_typd_idx!!]
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentCommuHotBinding.inflate(layoutInflater)
Log.d(TAG, mBoardType.name)
val viewModelFactory = BoardViewModelFactory(
owner = this,
repository = PostsRepository(),
boardType = mBoardType
)
val viewModel: ViewModelBoard by viewModels { viewModelFactory }
bindView(
boardType = mBoardType,
sortGroup = null,
boardGroup = binding.boardRadioGroup,
list = binding.postRV
)
bindState(
uiState = viewModel.state,
pagingData = viewModel.pagingDataFlow,
uiActions = viewModel.accept
)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.apply {
btnBack.setOnClickListener { requireActivity().onBackPressedDispatcher.onBackPressed() }
btnSearch.setOnClickListener {
requireActivity().supportFragmentManager.beginTransaction()
.replace(R.id.FragmentContainer, CommuFragment_search.getInstance(board_typd_idx!!), CommuFragment_search.TAG)
.addToBackStack(null)
.commit()
}
}
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
} | 11 | Kotlin | 0 | 1 | f6441c70f542efd789bbb52a342992e042c9ff5e | 2,867 | Mushroomer | Apache License 2.0 |
app/src/main/java/com/vitorpamplona/amethyst/model/Settings.kt | vitorpamplona | 587,850,619 | false | {"Kotlin": 3777160, "Shell": 1488, "Java": 921} | /**
* Copyright (c) 2024 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.model
import androidx.compose.runtime.Stable
import com.vitorpamplona.amethyst.R
@Stable
data class Settings(
val theme: ThemeType = ThemeType.SYSTEM,
val preferredLanguage: String? = null,
val automaticallyShowImages: ConnectivityType = ConnectivityType.ALWAYS,
val automaticallyStartPlayback: ConnectivityType = ConnectivityType.ALWAYS,
val automaticallyShowUrlPreview: ConnectivityType = ConnectivityType.ALWAYS,
val automaticallyHideNavigationBars: BooleanType = BooleanType.ALWAYS,
val automaticallyShowProfilePictures: ConnectivityType = ConnectivityType.ALWAYS,
val dontShowPushNotificationSelector: Boolean = false,
val dontAskForNotificationPermissions: Boolean = false,
)
enum class ThemeType(val screenCode: Int, val resourceId: Int) {
SYSTEM(0, R.string.system),
LIGHT(1, R.string.light),
DARK(2, R.string.dark),
}
fun parseThemeType(code: Int?): ThemeType {
return when (code) {
ThemeType.SYSTEM.screenCode -> ThemeType.SYSTEM
ThemeType.LIGHT.screenCode -> ThemeType.LIGHT
ThemeType.DARK.screenCode -> ThemeType.DARK
else -> {
ThemeType.SYSTEM
}
}
}
enum class ConnectivityType(val prefCode: Boolean?, val screenCode: Int, val resourceId: Int) {
ALWAYS(null, 0, R.string.connectivity_type_always),
WIFI_ONLY(true, 1, R.string.connectivity_type_wifi_only),
NEVER(false, 2, R.string.connectivity_type_never),
}
fun parseConnectivityType(code: Boolean?): ConnectivityType {
return when (code) {
ConnectivityType.ALWAYS.prefCode -> ConnectivityType.ALWAYS
ConnectivityType.WIFI_ONLY.prefCode -> ConnectivityType.WIFI_ONLY
ConnectivityType.NEVER.prefCode -> ConnectivityType.NEVER
else -> {
ConnectivityType.ALWAYS
}
}
}
fun parseConnectivityType(screenCode: Int): ConnectivityType {
return when (screenCode) {
ConnectivityType.ALWAYS.screenCode -> ConnectivityType.ALWAYS
ConnectivityType.WIFI_ONLY.screenCode -> ConnectivityType.WIFI_ONLY
ConnectivityType.NEVER.screenCode -> ConnectivityType.NEVER
else -> {
ConnectivityType.ALWAYS
}
}
}
enum class BooleanType(val prefCode: Boolean?, val screenCode: Int, val reourceId: Int) {
ALWAYS(null, 0, R.string.connectivity_type_always),
NEVER(false, 1, R.string.connectivity_type_never),
}
fun parseBooleanType(code: Boolean?): BooleanType {
return when (code) {
BooleanType.ALWAYS.prefCode -> BooleanType.ALWAYS
BooleanType.NEVER.prefCode -> BooleanType.NEVER
else -> {
BooleanType.ALWAYS
}
}
}
fun parseBooleanType(screenCode: Int): BooleanType {
return when (screenCode) {
BooleanType.ALWAYS.screenCode -> BooleanType.ALWAYS
BooleanType.NEVER.screenCode -> BooleanType.NEVER
else -> {
BooleanType.ALWAYS
}
}
}
| 5 | Kotlin | 3 | 995 | 0bb39f91b9dddf81dcec63f3d97674f26872fbd0 | 4,081 | amethyst | MIT License |
kotlinknifer/src/main/java/com/devrapid/kotlinknifer/recyclerview/itemdecorator/VerticalItemDecorator.kt | pokk | 87,917,798 | false | null | package com.devrapid.kotlinknifer.recyclerview.itemdecorator
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
class VerticalItemDecorator(
private val topBottom: Int,
private val leftRight: Int = topBottom,
) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val position: Int = parent.getChildAdapterPosition(view)
val childrenCount: Int = parent.childCount
when {
0 == position -> outRect.set(leftRight, topBottom, leftRight, topBottom / 2)
childrenCount - 1 != position -> outRect.set(leftRight, topBottom / 2, leftRight, topBottom)
else -> outRect.set(leftRight, topBottom / 2, leftRight, topBottom / 2)
}
}
}
| 0 | Kotlin | 1 | 2 | a389edf7794ba79d7b2e937c134b0c3f811a9185 | 845 | KotlinKnifer | Apache License 2.0 |
tensorflow/src/main/kotlin/wumo/sim/tensorflow/ops/variables/VariableLike.kt | wumo | 305,330,037 | false | {"Maven POM": 11, "Text": 7, "Python": 54, "Kotlin": 262, "Protocol Buffer Text Format": 2, "Java": 14, "ANTLR": 1, "Shell": 3, "CMake": 2, "C++": 291, "C": 22, "Prolog": 1, "M4": 3, "TeX": 2, "X PixMap": 1} | package wumo.sim.tensorflow.ops.variables
import wumo.sim.tensorflow.core.Graph
import wumo.sim.tensorflow.ops.HasName
import wumo.sim.tensorflow.ops.Op
import wumo.sim.tensorflow.ops.Output
import wumo.sim.tensorflow.ops.OutputConvertible
import wumo.sim.tensorflow.types.DataType
import wumo.sim.util.Shape
interface VariableLike : OutputConvertible,HasName {
/** Graph where this variable is val ined. */
val graph: Graph
/** Data type of this variable. */
val dataType: DataType<*>
/** Shape of this variable. */
val shape: Shape
/** Returns a cached op which reads the last value of this partitioned variable.
*
* You can not assign a new value to the returned tensor as it is not a reference to the variable.
*
* The returned op output will not inherit the control dependencies from the native where the value is used, which is
* equivalent behavior to that of getting the value of a variable.
*
* NOTE: You usually do not need to call this method directly, as all ops that use variables do so by internally
* converting them to tensors.
*/
val value: Output
/** Op responsible for initializing this variable. */
val initializer: Op
/** Op output that is `true` when the variable has been initialized and `false` otherwise. */
val isInitialized: Output
/** Value of the initialized variable. You should use this instead of the variable itself to initialize
* another variable with a value that depends on the value of this variable.
*
* Example:
* ```
* // Initialize `v` with random values, and then use `initializedValue` to guarantee that `v` has been initialized
* // before its value is used to initialize `w`. The random tensor will only be sampled once.
* val v = tf.variable("v", FLOAT, Shape(10, 40), tf.RandomTruncatedNormalInitializer())
* val w = tf.variable("w", initializer = tf.ConstantInitializer(v.initializedValue * 2.0))
* ```
*/
val initializedValue: Output
/** Creates an op that reads the value of this variable.
*
* This method should be used when there are multiple reads, or when it is desirable to read the value only after
* some condition is true.
*
* The returned value may be different from that of [[value]] depending on the device being used, the control
* dependencies, etc.
*
* @return Created op.
*/
fun read(name: String = "Read"): Output
/** Creates an op that reads the value of this variable sparsely, using the provided `indices`.
*
* This method should be used when there are multiple reads, or when it is desirable to read the value only after
* some condition is true.
*
* @param indices Indices to use for the sparse read.
* @param name Name for the created op.
* @return Created op.
*/
fun gather(indices: Output, name: String = "Gather"): Output
/** Creates an op that assigns the provided value to this variable and returns its value.
*
* @param value Value to assign the variable to.
* @param name Name for created op.
* @return Variable value read op, after the assignment.
*/
fun assign(value: Output, name: String = "Assign"): Output
/** Creates an op that adds the provided value to the current value of the variable and returns its value.
*
* @param value Value to add to the current variable value.
* @param name Name for created op.
* @return Variable value read op, after the addition.
*/
fun assignAdd(value: Output, name: String = "AssignAdd"): Output
/** Creates an op that subtracts the provided value from the current value of the variable and returns its value.
*
* @param value Value to subtract from the current variable value.
* @param name Name for created op.
* @return Variable value read op, after the subtraction.
*/
fun assignSub(value: Output, name: String = "AssignAdd"): Output
/** Creates an op that subtracts the provided sparse value from the current value of the variable and returns its
* value.
*
* @param indices Indices corresponding to the `values` being subtracted.
* @param values Values to be subtracted, corresponding to the provided `indices`.
* @param name Name for created op.
* @return Variable value read op, after the subtraction.
*/
fun assignScatterSub(indices: Output, values: Output, use_locking: Boolean = false, name: String = "ScatterSub"): Output
/** Converts this variable to an op output. This function simply returns an op corresponding to the variable value. */
override fun toOutput() = value
} | 1 | null | 1 | 1 | 2a3a5118239b27eeb268cd1e7bdbfe5f5604dab6 | 4,606 | sim-world | MIT License |
app/src/main/java/com/faigenbloom/familybudget/repositories/FamilyRepository.kt | ZakharchenkoWork | 706,155,222 | false | {"Kotlin": 746176} | package com.faigenbloom.familybudget.repositories
import com.faigenbloom.familybudget.datasources.BaseDataSource
import com.faigenbloom.familybudget.datasources.ID
import com.faigenbloom.familybudget.datasources.IdSource
import com.faigenbloom.familybudget.datasources.db.entities.FamilyEntity
import com.faigenbloom.familybudget.datasources.db.entities.PersonEntity
import com.faigenbloom.familybudget.datasources.firebase.FamilyNetworkSource
import com.faigenbloom.familybudget.datasources.firebase.models.FamilyModel
import com.faigenbloom.familybudget.repositories.mappers.FamilySourceMapper
import com.faigenbloom.familybudget.repositories.mappers.PersonSourceMapper
class FamilyRepository(
private val repository: AuthRepository,
private val dataBaseSource: BaseDataSource,
private val networkSource: FamilyNetworkSource,
private val personSourceMapper: PersonSourceMapper,
private val familySourceMapper: FamilySourceMapper,
private val idSource: IdSource,
) {
suspend fun getFamilyName(familyId: String): String {
return networkSource.getFamily(familyId)?.name ?: ""
}
suspend fun loadFamily(personId: String): FamilyEntity? {
val familyId = networkSource.getFamilyId(personId)
familyId?.let {
networkSource.getFamily(familyId)?.let {
dataBaseSource.saveFamily(familySourceMapper.forDB(it))
updateFamilyMembers(familyId)
}
}
return dataBaseSource.getFamily()
}
private suspend fun updateFamilyMembers(familyId: String) {
networkSource.getFamilyMembers(familyId)?.let {
it.forEach {
it?.let {
dataBaseSource.saveFamilyMember(personSourceMapper.forDB(it))
}
}
}
}
suspend fun loadFamily(): FamilyEntity {
return dataBaseSource.getFamily() ?: FamilyEntity("", "")
}
suspend fun saveFamily(familyEntity: FamilyEntity) {
networkSource.createFamily(
FamilyModel(
id = familyEntity.id,
name = familyEntity.name,
members = getFamilyMembers().let {
if (it.isEmpty() || it[0].familyId != familyEntity.id) {
emptyList()
} else {
it.map { it.id }
}
},
),
)
dataBaseSource.saveFamily(familyEntity)
}
suspend fun getFamilyMembers(): List<PersonEntity> {
return dataBaseSource.getFamilyMembers().ifEmpty {
if (idSource[ID.FAMILY].isNotEmpty()) {
updateFamilyMembers(idSource[ID.FAMILY])
dataBaseSource.getFamilyMembers()
} else {
emptyList()
}
}
}
suspend fun saveFamilyMember(member: PersonEntity) {
dataBaseSource.saveFamilyMember(member)
}
suspend fun saveFamilyMembers(members: List<PersonEntity>) {
val oldFamilyMembers = getFamilyMembers()
members.forEach {
if (oldFamilyMembers.contains(it).not()) {
networkSource.createFamilyMember(
personSourceMapper.forServer(it),
oldFamilyMembers.map { personSourceMapper.forServer(it) },
)
dataBaseSource.saveFamilyMember(it)
}
}
}
suspend fun getCurrentFamilyMember(): PersonEntity {
val personId = idSource[ID.USER].ifEmpty {
repository.isAuthenticated()
idSource[ID.USER]
}
return getFamilyMembers()
.first { it.id == personId }
}
suspend fun deleteUserFromFamily() {
dataBaseSource.clean()
}
suspend fun migrateFamilyMember(member: PersonEntity, newFamilyId: String) {
networkSource.updateFamilyMember(
personSourceMapper.forServer(member.copy(isHidden = true)),
)
val newFamilyMembers =
networkSource.getFamilyMembers(newFamilyId)?.filterNotNull() ?: emptyList()
networkSource.createFamilyMember(
personSourceMapper.forServer(member.copy(familyId = newFamilyId)),
newFamilyMembers,
)
}
}
| 0 | Kotlin | 0 | 0 | e81fa66d6afd5b79d3299583a73378c3ee1463ca | 4,276 | FamilyBudget | Apache License 2.0 |
util-ktx/lib-util-ktx/src/main/java/ru/surfstudio/android/utilktx/ktx/ui/activity/ActivityExtension.kt | surfstudio | 139,034,657 | false | null | /*
* Copyright (c) 2019-present, SurfStudio LLC.
*
* 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 ru.surfstudio.android.utilktx.ktx.ui.activity
import android.app.Activity
import android.graphics.Rect
import ru.surfstudio.android.utilktx.ktx.ui.context.getDisplayMetrics
import ru.surfstudio.android.utilktx.util.KeyboardUtil
/**
* Extension-методы для Activity
*/
/**
* Листенер на скрытие / появление клавиатуры
* Осторожно! Может реагировать не только на события открытия/скрытия клавиатуры
*/
fun Activity.keyboardVisibilityToggleListener(listener: (Boolean) -> Unit) {
val rootView = window.decorView
rootView.viewTreeObserver
.addOnGlobalLayoutListener {
val rect = Rect()
rootView.getWindowVisibleDisplayFrame(rect)
val screenHeight = rootView.height
val keypadHeight = screenHeight - rect.bottom
listener(keypadHeight > screenHeight * 0.15)
}
}
/**
* Скрытие экранной клавиатуры
*/
fun Activity.hideKeyboard() {
KeyboardUtil.hideSoftKeyboard(this)
}
/**
* Возвращает ширину или высоту экрана
*/
fun Activity.getDisplayParam(param: DisplayParam): Int {
val metrics = getDisplayMetrics()
windowManager.defaultDisplay.getMetrics(metrics)
return when (param) {
DisplayParam.WIDTH -> metrics.widthPixels
DisplayParam.HEIGHT -> metrics.heightPixels
}
} | 5 | null | 30 | 249 | 6d73ebcaac4b4bd7186e84964cac2396a55ce2cc | 1,939 | SurfAndroidStandard | Apache License 2.0 |
cdk/src/main/kotlin/com/shinythings/CognitoStack.kt | Partyschaum | 599,731,955 | false | null | package com.shinythings
import dev.stratospheric.cdk.ApplicationEnvironment
import software.amazon.awscdk.Duration
import software.amazon.awscdk.Environment
import software.amazon.awscdk.Stack
import software.amazon.awscdk.StackProps
import software.amazon.awscdk.customresources.AwsCustomResource
import software.amazon.awscdk.customresources.AwsCustomResourcePolicy
import software.amazon.awscdk.customresources.AwsSdkCall
import software.amazon.awscdk.customresources.PhysicalResourceId
import software.amazon.awscdk.customresources.SdkCallsPolicyOptions
import software.amazon.awscdk.services.cognito.AccountRecovery
import software.amazon.awscdk.services.cognito.AutoVerifiedAttrs
import software.amazon.awscdk.services.cognito.CognitoDomainOptions
import software.amazon.awscdk.services.cognito.Mfa
import software.amazon.awscdk.services.cognito.OAuthFlows
import software.amazon.awscdk.services.cognito.OAuthScope
import software.amazon.awscdk.services.cognito.OAuthSettings
import software.amazon.awscdk.services.cognito.PasswordPolicy
import software.amazon.awscdk.services.cognito.SignInAliases
import software.amazon.awscdk.services.cognito.StandardAttribute
import software.amazon.awscdk.services.cognito.StandardAttributes
import software.amazon.awscdk.services.cognito.UserPool
import software.amazon.awscdk.services.cognito.UserPoolClient
import software.amazon.awscdk.services.cognito.UserPoolClientIdentityProvider
import software.amazon.awscdk.services.cognito.UserPoolDomain
import software.amazon.awscdk.services.ssm.StringParameter
import software.constructs.Construct
class CognitoStack(
scope: Construct,
id: String,
private val awsEnvironment: Environment,
private val applicationEnvironment: ApplicationEnvironment,
inputParameters: CognitoInputParameters,
) : Stack(
scope,
id,
StackProps.builder()
.stackName(applicationEnvironment.prefix("Cognito"))
.env(awsEnvironment)
.build()
) {
val outputParameters: CognitoOutputParameters
private val logoutUrl =
"https://${inputParameters.loginPageDomainPrefix}.auth.${awsEnvironment.region}.amazoncognito.com/logout"
init {
val userPool = createUserPool(applicationName = inputParameters.applicationName)
val userPoolClient = createUserPoolClient(
userPool = userPool,
applicationName = inputParameters.applicationName,
applicationUrl = inputParameters.applicationUrl,
)
createUserPoolDomain(
userPool = userPool,
loginPageDomainPrefix = inputParameters.loginPageDomainPrefix,
)
outputParameters = writeOutputParametersToParameterStore(
userPool = userPool,
userPoolClient = userPoolClient,
)
}
private fun createUserPool(applicationName: String) =
UserPool.Builder.create(this, "userPool")
.userPoolName("$applicationName-user-pool")
.selfSignUpEnabled(false)
.standardAttributes(
StandardAttributes.builder()
.email(
StandardAttribute.builder()
.required(true)
.mutable(false)
.build()
)
.build()
)
.signInAliases(
SignInAliases.builder()
.username(true)
.email(true)
.build()
)
.signInCaseSensitive(true)
.autoVerify(
AutoVerifiedAttrs.builder()
.email(true)
.build()
)
.mfa(Mfa.OFF)
.accountRecovery(AccountRecovery.EMAIL_ONLY)
.passwordPolicy(
PasswordPolicy.builder()
.requireLowercase(true)
.requireDigits(true)
.requireSymbols(true)
.requireUppercase(true)
.minLength(12)
.tempPasswordValidity(Duration.days(7))
.build()
)
.build()
private fun createUserPoolClient(userPool: UserPool, applicationName: String, applicationUrl: String) =
UserPoolClient.Builder.create(this, "userPoolClient")
.userPoolClientName("$applicationName-client")
.generateSecret(true)
.userPool(userPool)
.oAuth(
OAuthSettings.builder()
.callbackUrls(
listOf(
"$applicationUrl/login/oauth2/code/cognito",
"http://localhost:8080/login/oauth2/code/cognito",
)
)
.logoutUrls(
listOf(
applicationUrl,
"http://localhost:8080",
)
)
.flows(
OAuthFlows.builder()
.authorizationCodeGrant(true)
.build()
)
.scopes(
listOf(
OAuthScope.EMAIL,
OAuthScope.OPENID,
OAuthScope.PROFILE
)
)
.build()
)
.supportedIdentityProviders(
listOf(UserPoolClientIdentityProvider.COGNITO)
)
.build()
private fun createUserPoolDomain(userPool: UserPool, loginPageDomainPrefix: String) =
UserPoolDomain.Builder.create(this, "userPoolDomain")
.userPool(userPool)
.cognitoDomain(
CognitoDomainOptions.builder()
.domainPrefix(loginPageDomainPrefix)
.build()
)
private fun writeOutputParametersToParameterStore(
userPool: UserPool,
userPoolClient: UserPoolClient
): CognitoOutputParameters {
StringParameter.Builder.create(this, "userPoolId")
.parameterName(createParameterName(applicationEnvironment, ParameterName.USER_POOL_ID))
.stringValue(userPool.userPoolId)
.build()
StringParameter.Builder.create(this, "userPoolClientId")
.parameterName(createParameterName(applicationEnvironment, ParameterName.USER_POOL_CLIENT_ID))
.stringValue(userPoolClient.userPoolClientId)
.build()
StringParameter.Builder.create(this, "logoutUrl")
.parameterName(createParameterName(applicationEnvironment, ParameterName.USER_POOL_LOGOUT_URL))
.stringValue(logoutUrl)
.build()
StringParameter.Builder.create(this, "providerUrl")
.parameterName(createParameterName(applicationEnvironment, ParameterName.USER_POOL_PROVIDER_URL))
.stringValue(userPool.userPoolProviderUrl)
.build()
// CloudFormation does not expose the UserPoolClient secret, so we can't access it directly with
// CDK. As a workaround, we create a custom resource that calls the AWS API to get the secret, and
// then store it in the parameter store like the other parameters.
// Source: https://github.com/aws/aws-cdk/issues/7225
val fetchUserPoolClientMetadata = AwsSdkCall.builder()
.region(awsEnvironment.region)
.service("CognitoIdentityServiceProvider")
.action("describeUserPoolClient")
.parameters(
mapOf(
"UserPoolId" to userPool.userPoolId,
"ClientId" to userPoolClient.userPoolClientId,
)
)
.physicalResourceId(PhysicalResourceId.of(userPoolClient.userPoolClientId))
.build()
val describeUserPoolResource = AwsCustomResource.Builder.create(this, "describeUserPool")
.resourceType("Custom::DescribeCognitoUserPoolClient")
.installLatestAwsSdk(false)
.onCreate(fetchUserPoolClientMetadata)
.onUpdate(fetchUserPoolClientMetadata)
.policy(
AwsCustomResourcePolicy.fromSdkCalls(
SdkCallsPolicyOptions.builder()
.resources(AwsCustomResourcePolicy.ANY_RESOURCE)
.build()
)
)
.build()
val userPoolClientSecret = describeUserPoolResource.getResponseField("UserPoolClient.ClientSecret")
StringParameter.Builder.create(this, "userPoolClientSecret")
.parameterName(createParameterName(applicationEnvironment, ParameterName.USER_POOL_CLIENT_SECRET))
.stringValue(userPoolClientSecret)
.build()
return CognitoOutputParameters(
userPoolId = userPool.userPoolId,
userPoolClientId = userPoolClient.userPoolClientId,
userPoolClientSecret = userPoolClientSecret,
logoutUrl = logoutUrl,
providerUrl = userPool.userPoolProviderUrl,
)
}
companion object {
fun getOutputParametersFromParameterStore(
scope: Construct,
applicationEnvironment: ApplicationEnvironment
) = CognitoOutputParameters(
userPoolId = getParameter(scope, ParameterName.USER_POOL_ID, applicationEnvironment),
userPoolClientId = getParameter(scope, ParameterName.USER_POOL_CLIENT_ID, applicationEnvironment),
userPoolClientSecret = getParameter(scope, ParameterName.USER_POOL_CLIENT_SECRET, applicationEnvironment),
logoutUrl = getParameter(scope, ParameterName.USER_POOL_LOGOUT_URL, applicationEnvironment),
providerUrl = getParameter(scope, ParameterName.USER_POOL_PROVIDER_URL, applicationEnvironment),
)
private fun createParameterName(applicationEnvironment: ApplicationEnvironment, parameterName: ParameterName) =
"${applicationEnvironment.environmentName}-${applicationEnvironment.applicationName}-Cognito-${parameterName.identifier}"
private fun getParameter(
scope: Construct,
parameterName: ParameterName,
applicationEnvironment: ApplicationEnvironment
) = StringParameter.fromStringParameterName(
scope,
parameterName.name,
createParameterName(
applicationEnvironment = applicationEnvironment,
parameterName = parameterName,
)
).stringValue
}
data class CognitoInputParameters(
val applicationName: String,
val applicationUrl: String,
val loginPageDomainPrefix: String,
)
data class CognitoOutputParameters(
val userPoolId: String,
val userPoolClientId: String,
val userPoolClientSecret: String,
val logoutUrl: String,
val providerUrl: String,
)
enum class ParameterName(val identifier: String) {
USER_POOL_ID("userPoolId"),
USER_POOL_CLIENT_ID("userPoolClientId"),
USER_POOL_CLIENT_SECRET("userPoolClientSecret"),
USER_POOL_LOGOUT_URL("userPoolLogoutUrl"),
USER_POOL_PROVIDER_URL("userPoolProviderUrl"),
}
}
| 3 | Kotlin | 0 | 0 | 84552b54e92ae07e90ab5d739544840c4290187a | 11,409 | stratospheric-kotlin | MIT License |
Plugins/ChatLogger/src/main/kotlin/tw/xserver/plugin/logger/chat/ChatLogger.kt | IceXinShou | 830,436,296 | false | {"Kotlin": 163517} | package tw.xserver.plugin.logger.chat
import net.dv8tion.jda.api.entities.Guild
import net.dv8tion.jda.api.entities.IMentionable
import net.dv8tion.jda.api.entities.Member
import net.dv8tion.jda.api.entities.Message
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel
import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel
import net.dv8tion.jda.api.events.guild.GuildLeaveEvent
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent
import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent
import net.dv8tion.jda.api.events.interaction.component.EntitySelectInteractionEvent
import net.dv8tion.jda.api.events.message.MessageDeleteEvent
import net.dv8tion.jda.api.events.message.MessageReceivedEvent
import net.dv8tion.jda.api.events.message.MessageUpdateEvent
import net.dv8tion.jda.api.exceptions.ErrorResponseException
import net.dv8tion.jda.api.interactions.DiscordLocale
import net.dv8tion.jda.api.utils.messages.MessageCreateData
import net.dv8tion.jda.api.utils.messages.MessageEditData
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import tw.xserver.loader.builtin.placeholder.Placeholder
import tw.xserver.loader.builtin.placeholder.Substitutor
import tw.xserver.plugin.creator.message.MessageCreator
import tw.xserver.plugin.logger.chat.Event.COMPONENT_PREFIX
import tw.xserver.plugin.logger.chat.Event.PLUGIN_DIR_FILE
import tw.xserver.plugin.logger.chat.JsonManager.dataMap
import tw.xserver.plugin.logger.chat.lang.PlaceholderLocalizations
import java.io.File
import java.util.stream.Collectors
internal object ChatLogger {
internal const val KEEP_ALL_LOG = true
private val logger: Logger = LoggerFactory.getLogger(this::class.java)
private val creator = MessageCreator(File(PLUGIN_DIR_FILE, "lang"), COMPONENT_PREFIX)
fun setting(event: SlashCommandInteractionEvent) = event.hook.editOriginal(
getSettingMenu(
dataMap.computeIfAbsent(event.channelIdLong) { ChannelData(event.guild!!.idLong) },
event.userLocale,
Placeholder.getSubstitutor(event)
)
).queue()
fun onToggle(event: ButtonInteractionEvent) {
// update
val channelData = JsonManager.toggle(event.guild!!.idLong, event.channel.idLong)
// reply
event.hook.editOriginal(
getSettingMenu(
channelData,
event.userLocale,
Placeholder.getSubstitutor(event)
)
).queue()
event.deferEdit().queue()
}
fun onDelete(event: ButtonInteractionEvent) {
// update
JsonManager.delete(event.guild!!.idLong, event.channel.idLong)
// reply
event.editMessage(
creator.getEditBuilder(
"delete",
event.userLocale,
Placeholder.getSubstitutor(event)
).build()
).queue()
}
fun onSelect(event: EntitySelectInteractionEvent) {
// update
val guild = event.guild!!
val channelIds = event.values
.stream()
.map { obj: IMentionable -> obj.idLong }
.collect(Collectors.toList())
val channelData = when (event.componentId.removePrefix(COMPONENT_PREFIX)) {
"modify_allow" -> {
JsonManager.addAllowChannels(
guildId = guild.idLong,
listenChannelId = event.channelIdLong,
detectedChannelIds = channelIds
)
}
"modify_block" -> {
JsonManager.addBlockChannels(
guildId = guild.idLong,
listenChannelId = event.channelIdLong,
detectedChannelIds = channelIds
)
}
else -> throw Exception("Unknown key ${event.componentId.removePrefix(COMPONENT_PREFIX)}")
}
// reply
event.hook.editOriginal(
getSettingMenu(
channelData,
event.userLocale,
Placeholder.getSubstitutor(event)
)
).queue()
event.deferEdit().queue()
}
fun createSel(event: ButtonInteractionEvent, componentId: String) {
event.editMessage(
creator.getEditBuilder(
componentId,
event.userLocale, Placeholder.getSubstitutor(event)
).build()
).queue()
}
fun receiveMessage(event: MessageReceivedEvent) {
if (!DbManager.isListenable(event.channel.idLong)) return
val messageContent = getMessageContent(event.message)
DbManager.receiveMessage(
event.guild.id,
event.channel.idLong,
event.messageIdLong,
event.author.idLong,
messageContent
)
}
fun updateMessage(event: MessageUpdateEvent) {
val channelId = event.channel.idLong
if (!DbManager.isListenable(channelId)) return
val listenChannelIds: List<Long> = dataMap.entries
.filter { (_, value) -> channelId in value.getCurrentDetectChannels() }
.map { (key, _) -> key }
if (listenChannelIds.isEmpty()) return
try {
val newMessage = getMessageContent(event.message)
val (oldMessage, _, updateCount) = DbManager.updateMessage(
event.guild.id,
event.channel.idLong,
event.messageIdLong,
newMessage
)
val substitutor = Placeholder.getSubstitutor(event.member!!).putAll(
"cl_msg_after_url" to event.message.jumpUrl,
"cl_category_mention" to event.guildChannel.asTextChannel().parentCategory!!.asMention,
"cl_channel_mention" to event.channel.asMention,
"cl_change_count" to updateCount.toString(),
"cl_msg_before" to oldMessage,
"cl_msg_after" to newMessage
)
sendListenChannel("on-msg-update", event.guild, listenChannelIds, substitutor)
} catch (e: MessageNotFound) {
return
}
}
fun deleteMessage(event: MessageDeleteEvent) {
val channelId = event.channel.idLong
if (!DbManager.isListenable(event.channel.idLong)) return
val listenChannelIds: List<Long> = dataMap.entries
.filter { (_, value) -> channelId in value.getCurrentDetectChannels() }
.map { (key, _) -> key }
if (listenChannelIds.isEmpty()) return
try {
val (oldMessage: String, userId: Long, updateCount: Int) = DbManager.deleteMessage(
event.guild.id,
event.channel.idLong,
event.messageIdLong,
)
event.guild.retrieveMemberById(userId).queue { member ->
val substitutor = Placeholder.getSubstitutor(member).putAll(
"cl_category_mention" to event.guildChannel.asTextChannel().parentCategory!!.asMention,
"cl_channel_mention" to event.channel.asMention,
"cl_change_count" to updateCount.toString(),
"cl_msg" to oldMessage,
)
sendListenChannel("on-msg-delete", event.guild, listenChannelIds, substitutor)
}
} catch (e: MessageNotFound) {
return
} catch (e: ErrorResponseException) {
when (e.errorCode) {
// Unknown Member
10007 -> {
sendListenChannel("on-msg-delete", event.guild, listenChannelIds, Placeholder.globalPlaceholder)
return
}
}
}
}
internal fun onGuildLeave(event: GuildLeaveEvent) {
if (KEEP_ALL_LOG) return
DbManager.deleteDatabase(event.guild.id)
}
private fun sendListenChannel(key: String, guild: Guild, listenChannelId: List<Long>, substitutor: Substitutor) {
val message = MessageCreateData.fromEditData(
creator.getEditBuilder(key, guild.locale, substitutor).build()
)
listenChannelId.forEach {
val listenChannel = guild.getGuildChannelById(it)
if (listenChannel == null) {
DbManager.markChannelAsUnavailable(it)
return
}
when (listenChannel) {
is TextChannel -> listenChannel.sendMessage(message).queue()
is VoiceChannel -> listenChannel.sendMessage(message).queue()
else -> throw Exception("Unknown channel type")
}
}
}
private fun getMessageContent(message: Message): String {
if (message.embeds.isEmpty()) {
// It's a default message
return message.contentRaw
}
// It's an embed message
return StringBuilder().apply {
for (embed in message.embeds) {
append(embed.author?.let { "${it.name}\n" } ?: "")
append("${embed.title}\n\n")
append(embed.description)
for (field in embed.fields) {
append("${field.name}\n")
append("${field.value}\n\n")
}
}
}.toString()
}
private fun getSettingMenu(
channelData: ChannelData,
locale: DiscordLocale,
substitutor: Substitutor
): MessageEditData {
val allowListFormat = PlaceholderLocalizations.allowListFormat[locale]
val blockListFormat = PlaceholderLocalizations.blockListFormat[locale]
val allowString = StringBuilder().apply {
if (!channelData.getAllowArray().isEmpty) channelData.getAllowArray().map { it.asString }
.forEach { detectedChannelId ->
append(
substitutor.parse(
allowListFormat
.replace("%allowlist_channel_mention%", "<#${detectedChannelId}>")
.replace("%allowlist_channel_id%", detectedChannelId)
)
)
} else {
append(substitutor.parse(PlaceholderLocalizations.empty[locale]))
}
}.toString()
val blockString = StringBuilder().apply {
if (!channelData.getBlockArray().isEmpty) channelData.getBlockArray().map { it.asString }
.forEach { detectedChannelId ->
append(
substitutor.parse(
blockListFormat
.replace("%blocklist_channel_mention%", "<#${detectedChannelId}>")
.replace("%blocklist_channel_id%", detectedChannelId)
)
)
} else {
append(substitutor.parse(PlaceholderLocalizations.empty[locale]))
}
}.toString()
substitutor.apply {
putAll(
"cl_channel_mode" to if (channelData.getChannelMode()) "ALLOW" else "BLOCK",
"cl_allow_list_format" to allowString,
"cl_block_list_format" to blockString
)
}
return creator.getEditBuilder("chat-logger@setting", locale, substitutor).build()
}
} | 0 | Kotlin | 0 | 1 | 5da8e70c066ba9b22ea563c1587edd57cbd1a371 | 11,400 | XsDiscordBotKt | Apache License 2.0 |
app/src/main/java/com/example/satu/ui/activities/transfer/TransferPinActivity.kt | synrgy-satu | 829,466,485 | false | {"Kotlin": 221544} | package com.example.satu.ui.activities.transfer
import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.example.satu.R
import com.example.satu.data.model.response.transfer.DataTransfer
import com.example.satu.databinding.ActivityTransferPinBinding
import com.example.satu.ui.activities.mutation.PinValidationResponse
import com.example.satu.ui.activities.mutation.network.RetrofitClient
import com.example.satu.ui.factory.TransferViewModelfactory
import com.example.satu.ui.viewmodel.TransferViewModel
import com.example.satu.utils.ProgressDialogUtils
import com.example.satu.utils.SnackbarUtils
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import retrofit2.Call
import retrofit2.Response
class TransferPinActivity : AppCompatActivity() {
private val passwordList = mutableListOf<Int>() // To keep track of input
private var isPasswordVisible = false // To track visibility state
private val correctPin = listOf(6, 6, 6, 6, 6, 6)
private lateinit var binding : ActivityTransferPinBinding
private val viewModel: TransferViewModel by viewModels {
TransferViewModelfactory.getInstance(application)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityTransferPinBinding.inflate(layoutInflater)
setContentView(binding.root)
// Find the views
val llEnterPassword = findViewById<LinearLayout>(R.id.llEnterPassword)
val llNumberPin = findViewById<LinearLayout>(R.id.llNumberPin)
val tvShowPassword = findViewById<TextView>(R.id.tvShowPassword)
// Set the initial visibility of llNumberPin to GONE
llNumberPin.visibility = View.GONE
// Set an OnClickListener on llEnterPassword to change the visibility of llNumberPin and update tvShowPassword
llEnterPassword.setOnClickListener {
llNumberPin.visibility = View.VISIBLE
// Update drawable for tvShowPassword
updateShowPasswordIcon(tvShowPassword)
}
// Handle the Show Password button toggle
tvShowPassword.setOnClickListener {
isPasswordVisible = !isPasswordVisible
updatePasswordViews() // Update views based on visibility state
updateShowPasswordIcon(tvShowPassword) // Update icon
}
// Number buttons
val numberButtons = listOf(
R.id.tvNumber1, R.id.tvNumber2, R.id.tvNumber3,
R.id.tvNumber4, R.id.tvNumber5, R.id.tvNumber6,
R.id.tvNumber7, R.id.tvNumber8, R.id.tvNumber9,
R.id.tvNumber0
)
for (id in numberButtons) {
findViewById<TextView>(id).setOnClickListener { v ->
handleNumberClick(v as TextView)
}
}
// Delete button
findViewById<View>(R.id.ivDelete).setOnClickListener {
handleDelete()
}
}
private fun handleNumberClick(view: TextView) {
val number = view.text.toString().toInt()
val passwordListSize = passwordList.size
if (passwordListSize < 6) {
passwordList.add(number)
updatePasswordViews()
if (passwordListSize == 5) { // If all 6 digits are entered
validatePin(passwordList.joinToString(""))
}
}
}
private fun handleDelete() {
if (passwordList.isNotEmpty()) {
passwordList.removeAt(passwordList.size - 1)
updatePasswordViews()
}
}
private fun updatePasswordViews() {
val drawableFilled = ContextCompat.getDrawable(this, R.drawable.ic_circle)
val drawableEmpty = ContextCompat.getDrawable(this, R.drawable.ic_min)
val passwordViews = listOf(
R.id.tvPassword1, R.id.tvPassword2, R.id.tvPassword3,
R.id.tvPassword4, R.id.tvPassword5, R.id.tvPassword6
).map { id -> findViewById<TextView>(id) }
passwordViews.forEachIndexed { index, textView ->
textView?.let {
if (index < passwordList.size) {
if (isPasswordVisible) {
it.text = passwordList[index].toString() // Show the number
it.setPadding(0, 25, 0, 0)
it.setTypeface(null, Typeface.BOLD)
it.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null)
} else {
it.text = "" // Hide the number
it.setPadding(0, 0, 0, 35)
it.setCompoundDrawablesWithIntrinsicBounds(null, null, null, drawableFilled)
}
} else {
it.text = ""
it.setCompoundDrawablesWithIntrinsicBounds(null, null, null, drawableEmpty)
}
}
}
}
private fun updateShowPasswordIcon(tvShowPassword: TextView) {
val drawableStart = if (isPasswordVisible) {
ContextCompat.getDrawable(this, R.drawable.ic_eye) // Eye closed icon
} else {
ContextCompat.getDrawable(this, R.drawable.ic_eye_slash) // Eye open icon
}
tvShowPassword.setCompoundDrawablesWithIntrinsicBounds(drawableStart, null, null, null)
}
private fun validatePin(pin: String) {
val sharedPrefToken = getSharedPreferences("UserToken", Context.MODE_PRIVATE)
val tokens = sharedPrefToken.getString("token", "")
val token = "Bearer $tokens"
val body: RequestBody = "".toRequestBody("text/plain".toMediaTypeOrNull())
val call = RetrofitClient.apiService.validatePin(token, pin, body)
call.enqueue(object : retrofit2.Callback<PinValidationResponse> {
override fun onResponse(
call: Call<PinValidationResponse>,
response: Response<PinValidationResponse>
) {
if (response.isSuccessful && response.body()?.status == true) {
val sharedPref = getSharedPreferences("UserProfile", Context.MODE_PRIVATE)
val pin = sharedPref.getString("pin", "")
val debitedRekeningNumberString = sharedPref.getString("rekening_number", "")
val debitedRekeningNumber: Long? = debitedRekeningNumberString?.toLongOrNull()
val sharedPrefTFRekning = getSharedPreferences("UserTransferRekening", Context.MODE_PRIVATE)
val targetRekeningNumberString = sharedPrefTFRekning .getString("targetRekeningNumber", "")
val targetRekeningNumber : Long? = targetRekeningNumberString?.toLongOrNull()
val nameTujuan = sharedPrefTFRekning .getString("namaRekeningTujuan", "")
val sharedPrefTF = getSharedPreferences("UserTransfer", Context.MODE_PRIVATE)
val amountString = sharedPrefTF.getString("nominal", "")
val amount : Long? = amountString?.toLongOrNull()
val note= sharedPrefTF.getString("catatan", "")
val sharedPrefToken = getSharedPreferences("UserToken", Context.MODE_PRIVATE)
val token = sharedPrefToken .getString("token", "")
if (debitedRekeningNumber != null) {
if (targetRekeningNumber != null) {
if (amount != null) {
if (note != null) {
if (token != null) {
if (pin != null) {
viewModel.addTransfer(token, debitedRekeningNumber, targetRekeningNumber, amount, pin, note).observe(this@TransferPinActivity) { result ->
when (result) {
is com.example.common.Result.Loading -> ProgressDialogUtils.showProgressDialog(this@TransferPinActivity)
is com.example.common.Result.Success -> result.data.data?.let { onLoginSuccess(it) }
is com.example.common.Result.Error -> onLoginError(result.error)
}
}
}
}
}
}
} else {
showSnackBar("Pin salah")
}
// val intent = Intent(this@QrisVerificationActivity, QrisReceiptActivity::class.java)
// startActivity(intent)
}
}else {
// Show an error message
Toast.makeText(this@TransferPinActivity, "PIN tidak valid", Toast.LENGTH_SHORT).show()
passwordList.clear()
updatePasswordViews()
}
}
private fun onLoginSuccess(data: DataTransfer) {
ProgressDialogUtils.hideProgressDialog()
val nominal = data.amount ?: 0
val referenceNumber = data.referenceNumber ?: 0
val waktuTransaksi = data.createdDate ?: ""
val note = data.note ?: ""
val namaPenerima = getSharedPreferences("UserTransferRekening", Context.MODE_PRIVATE)
.getString("namaRekeningTujuan", "") ?: ""
val rekeningTujuan = getSharedPreferences("UserTransferRekening", Context.MODE_PRIVATE)
.getString("targetRekeningNumber", "") ?: ""
val sharedPref = getSharedPreferences("UserProfile", Context.MODE_PRIVATE)
val fullName = sharedPref.getString("full_name", "")
val debitedRekeningNumber = sharedPref.getString("rekening_number", "")
val intent = Intent(this@TransferPinActivity, TransferReceiptActivity::class.java).apply {
putExtra("nominal", nominal.toString())
putExtra("waktu_transaksi", waktuTransaksi)
putExtra("nama_penerima", namaPenerima)
putExtra("rekening_tujuan", rekeningTujuan)
putExtra("rekening_pengirim", debitedRekeningNumber)
putExtra("nama_pengirim", fullName)
putExtra("note", note)
putExtra("referenceNumber", referenceNumber)
}
startActivity(intent)
clearSharedPreferences()
finish()
}
private fun onLoginError(errorMessage: String) {
ProgressDialogUtils.hideProgressDialog()
showSnackBar(errorMessage)
}
private fun showSnackBar(message: String) {
SnackbarUtils.showWithDismissAction(binding.root, message)
}
private fun clearSharedPreferences() {
getSharedPreferences("UserTransfer", Context.MODE_PRIVATE).edit().clear().apply()
getSharedPreferences("UserTransferRekening", Context.MODE_PRIVATE).edit().clear().apply()
}
override fun onFailure(call: Call<PinValidationResponse>, t: Throwable) {
// Handle error
Log.d("error", t.message.toString())
Toast.makeText(this@TransferPinActivity, "Failed to validate PIN: ${t.message}", Toast.LENGTH_SHORT).show()
}
})
}
} | 1 | Kotlin | 0 | 0 | f26cf59385a8112a8649b449d964cc50933ba568 | 12,121 | android-satu | Open Market License |
src/main/kotlin/leight/user/LockedUserException.kt | marek-hanzal | 259,577,282 | false | null | package leight.user
open class LockedUserException(message: String, cause: Throwable? = null) : UserException(message, cause)
| 112 | Kotlin | 0 | 1 | 7a485228438c5fb9a61b1862e8164f5e87361e4a | 127 | DeRivean | Apache License 2.0 |
simple-icons/src/commonMain/kotlin/compose/icons/simpleicons/Scopus.kt | DevSrSouza | 311,134,756 | false | {"Kotlin": 36719092} | package compose.icons.simpleicons
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.SimpleIcons
public val SimpleIcons.Scopus: ImageVector
get() {
if (_scopus != null) {
return _scopus!!
}
_scopus = Builder(name = "Scopus", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(24.0f, 19.059f)
lineToRelative(-0.14f, -1.777f)
curveToRelative(-1.426f, 0.772f, -2.945f, 1.076f, -4.465f, 1.076f)
curveToRelative(-3.319f, 0.0f, -5.96f, -2.782f, -5.96f, -6.475f)
curveToRelative(0.0f, -3.903f, 2.595f, -6.31f, 5.633f, -6.31f)
curveToRelative(1.917f, 0.0f, 3.39f, 0.303f, 4.792f, 1.075f)
lineTo(24.0f, 4.895f)
curveToRelative(-1.286f, -0.608f, -2.337f, -0.889f, -4.698f, -0.889f)
curveToRelative(-4.534f, 0.0f, -7.97f, 3.53f, -7.97f, 8.017f)
curveToRelative(0.0f, 5.12f, 4.09f, 7.924f, 7.9f, 7.924f)
curveToRelative(1.916f, 0.0f, 3.506f, -0.257f, 4.768f, -0.888f)
close()
moveTo(9.046f, 15.599f)
curveToRelative(0.0f, -2.22f, -1.964f, -3.225f, -3.857f, -4.347f)
curveTo(3.716f, 10.364f, 2.15f, 9.756f, 2.15f, 8.12f)
curveToRelative(0.0f, -1.215f, 0.889f, -2.548f, 2.642f, -2.548f)
curveToRelative(1.519f, 0.0f, 2.57f, 0.234f, 3.903f, 1.029f)
lineToRelative(0.117f, -1.847f)
curveToRelative(-1.239f, -0.514f, -2.127f, -0.748f, -4.137f, -0.748f)
curveTo(1.8f, 4.006f, 0.047f, 5.876f, 0.047f, 8.26f)
curveToRelative(0.0f, 2.384f, 2.103f, 3.413f, 4.02f, 4.581f)
curveToRelative(1.426f, 0.865f, 2.922f, 1.45f, 2.922f, 2.992f)
curveToRelative(0.0f, 1.496f, -1.333f, 2.571f, -2.922f, 2.571f)
curveToRelative(-1.566f, 0.0f, -2.594f, -0.35f, -3.786f, -1.075f)
lineTo(0.0f, 19.176f)
curveToRelative(1.215f, 0.56f, 2.454f, 0.818f, 4.16f, 0.818f)
curveToRelative(2.385f, 0.0f, 4.885f, -1.473f, 4.885f, -4.395f)
close()
}
}
.build()
return _scopus!!
}
private var _scopus: ImageVector? = null
| 17 | Kotlin | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 3,030 | compose-icons | MIT License |
recruitment-fandom/app/src/main/java/gs/kar/rfandom/MainActivity.kt | mouradaldmi | 175,237,266 | false | {"Java": 66699, "Kotlin": 47653, "Swift": 2168, "Python": 1967, "Go": 1603} | package gs.kar.rfandom
import android.databinding.ObservableArrayList
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.View
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.github.nitrico.lastadapter.LastAdapter
import com.github.nitrico.lastadapter.Type
import gs.kar.rfandom.databinding.ItemImageBinding
import gs.kar.rfandom.databinding.ItemTitleBinding
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.channels.consumeEach
import kotlinx.coroutines.experimental.launch
import org.kodein.di.generic.instance
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
viewpager.adapter = TabsPagerAdapter(supportFragmentManager)
tablayout.setupWithViewPager(viewpager)
}
inner class TabsPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment {
return when (position) {
0 -> WikisFragment()
else -> ImagesFragment()
}
}
override fun getPageTitle(position: Int): CharSequence? {
return when(position) {
0 -> "Titles"
else -> "Images"
}
}
override fun getCount(): Int {
return 2
}
}
class WikisFragment : Fragment() {
private val state: State<FandomState> by DI.instance()
private val update: Update<Message, FandomState> by DI.instance()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_wikis, container, false) as RecyclerView
view.layoutManager = LinearLayoutManager(context)
return view
}
override fun onStart() {
super.onStart()
bind(view as RecyclerView)
}
private fun bind(view: RecyclerView) {
val titleType = Type<ItemTitleBinding>(R.layout.item_title)
launch {
val observable = ObservableArrayList<Wiki>()
launch(UI) {
LastAdapter(observable, BR.item).map<Wiki>(titleType).into(view)
}
val channel = state.subscribe()
channel.consumeEach { fandom ->
launch(UI) { observable.appendFrom(fandom.wikis) }
}
}
view.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (!view.canScrollVertically(1)) {
update.send(OnNextPage())
}
}
})
}
}
class ImagesFragment : Fragment() {
private val state: State<FandomState> by DI.instance()
private val update: Update<Message, FandomState> by DI.instance()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_images, container, false) as RecyclerView
view.layoutManager = GridLayoutManager(context, 2)
return view
}
override fun onStart() {
super.onStart()
bind(view as RecyclerView)
}
private fun bind(view: RecyclerView) {
val imageType = Type<ItemImageBinding>(R.layout.item_image)
.onBind {
val url = it.binding.item?.image
if (url != null) Glide.with(view).load(url).into(it.binding.thumbnail)
}
launch {
val observable = ObservableArrayList<Wiki>()
launch(UI) {
LastAdapter(observable, BR.item).map<Wiki>(imageType).into(view)
}
val channel = state.subscribe()
channel.consumeEach { fandom ->
launch(UI) { observable.appendFrom(fandom.wikis) }
}
}
view.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (!view.canScrollVertically(1)) {
update.send(OnNextPage())
}
}
})
}
}
}
| 0 | Java | 1 | 0 | 7f5dd4cdb2b218088f65062bd19f7b50dcd22134 | 5,351 | challenges | Apache License 2.0 |
server/server/src/test/kotlin/org/jetbrains/bsp/bazel/server/sync/TargetTagsResolverTest.kt | JetBrains | 826,262,028 | false | {"Kotlin": 3064918, "Starlark": 370388, "Java": 165158, "Scala": 37245, "Python": 34754, "Lex": 17493, "Dockerfile": 8674, "Shell": 7379, "HTML": 1310, "Rust": 680, "Go": 428, "C++": 113} | package org.jetbrains.bsp.bazel.server.sync
import io.kotest.matchers.shouldBe
import org.jetbrains.bsp.bazel.info.BspTargetInfo.TargetInfo
import org.jetbrains.bsp.bazel.server.model.Tag
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ValueSource
class TargetTagsResolverTest {
@Test
fun `should map executable targets`() {
val targetInfo =
TargetInfo
.newBuilder()
.also {
it.executable = true
}.build()
val tags = TargetTagsResolver().resolveTags(targetInfo)
tags shouldBe setOf(Tag.APPLICATION)
}
@Test
fun `should map test targets`() {
val targetInfo =
TargetInfo
.newBuilder()
.also {
it.kind = "blargh_test"
it.executable = true
}.build()
val tags = TargetTagsResolver().resolveTags(targetInfo)
tags shouldBe setOf(Tag.TEST)
}
@Test
fun `should map intellij_plugin_debug_target`() {
val targetInfo =
TargetInfo
.newBuilder()
.also {
it.kind = "intellij_plugin_debug_target"
}.build()
val tags = TargetTagsResolver().resolveTags(targetInfo)
tags shouldBe setOf(Tag.INTELLIJ_PLUGIN, Tag.APPLICATION)
}
@Test
fun `should map no-ide and manual tags`() {
val targetInfo =
TargetInfo
.newBuilder()
.also {
it.addTags("no-ide")
it.addTags("manual")
}.build()
val tags = TargetTagsResolver().resolveTags(targetInfo)
tags shouldBe setOf(Tag.NO_IDE, Tag.MANUAL)
}
@ParameterizedTest
@ValueSource(strings = ["resources_union", "java_import", "aar_import"])
fun `should handle special cases`(name: String) {
val targetInfo =
TargetInfo
.newBuilder()
.also {
it.kind = name
}.build()
val tags = TargetTagsResolver().resolveTags(targetInfo)
tags shouldBe setOf(Tag.LIBRARY)
}
}
| 2 | Kotlin | 18 | 45 | 1d79484cfdf8fc31d3a4b214655e857214071723 | 1,976 | hirschgarten | Apache License 2.0 |
src/main/kotlin/io/mustelidae/seaotter/domain/editor/command/ResizeCommand.kt | stray-cat-developers | 154,283,194 | false | {"Kotlin": 136637, "Shell": 223} | package io.mustelidae.seaotter.domain.editor.command
import io.mustelidae.seaotter.domain.editor.image.ImageScalingFlabbyImage
import io.mustelidae.seaotter.domain.editor.image.ImgscalrFlabbyImage
import java.awt.image.BufferedImage
class ResizeCommand(private var bufferedImage: BufferedImage) : EditCommand<ResizeOption> {
override fun execute(option: ResizeOption) {
if (option.scale != null) {
if (option.scale == 100.0) {
return
}
val flabbyImage = if (option.scale > 100.0) {
ImageScalingFlabbyImage(bufferedImage)
} else {
ImgscalrFlabbyImage(bufferedImage)
}
flabbyImage.resize(option.scale)
bufferedImage = flabbyImage.getBufferedImage()
} else {
if (option.width == bufferedImage.width && option.height == bufferedImage.height) {
return
}
val flabbyImage = if (option.keepRatio) {
ImgscalrFlabbyImage(bufferedImage)
} else {
ImageScalingFlabbyImage(bufferedImage)
}
flabbyImage.resize(option.width!!, option.height!!)
bufferedImage = flabbyImage.getBufferedImage()
}
}
override fun getBufferedImage(): BufferedImage = bufferedImage
}
| 2 | Kotlin | 0 | 1 | db4acbffaa27ca1d0e22a832aecb5ba1cccf61e8 | 1,352 | sea-otter | MIT License |
src/test/kotlin/com/glancebar/apiboilerplate/controller/AuthorityControllerTest.kt | yisen-cai | 321,651,755 | false | null | package com.glancebar.apiboilerplate.controller
import com.glancebar.apiboilerplate.service.AuthorityService
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.http.MediaType
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import org.springframework.test.web.servlet.result.MockMvcResultMatchers
/**
*
* @author YISEN
* @date 2020/12/16
*/
@SpringBootTest
@AutoConfigureMockMvc
internal class AuthorityControllerTest {
@Autowired
lateinit var authorityController: AuthorityController
@MockBean
lateinit var authorityService: AuthorityService
@Autowired
lateinit var mockMvc: MockMvc
@Test
@Disabled("")
fun addAuthority() {
val body =
"""
{
"name": "API",
"description: "Basic user authority of normal user."
}
""".trimIndent()
mockMvc.perform(
MockMvcRequestBuilders.post("/authorities")
.contentType(body)
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(
MockMvcResultMatchers.status().isCreated
)
.andExpect(
MockMvcResultMatchers
.content()
.contentType(MediaType.APPLICATION_JSON)
)
}
@Test
fun getAuthority() {
}
@Test
fun getAuthorities() {
}
@Test
fun updateAuthorities() {
}
@Test
fun deleteAuthorities() {
}
} | 1 | Kotlin | 0 | 1 | beb48202163b6bd39001661969a2a640bc359734 | 1,909 | api-boilerplate | Apache License 2.0 |
compiler/src/main/kotlin/io/github/aplcornell/viaduct/circuitcodegeneration/AbstractCodeGenerator.kt | apl-cornell | 169,159,978 | false | {"Kotlin": 1117382, "Java": 43793, "C++": 13898, "Lex": 12293, "Python": 11983, "Dockerfile": 1951, "Makefile": 1762, "SWIG": 1212, "Shell": 950} | package io.github.aplcornell.viaduct.circuitcodegeneration
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.MemberName
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.TypeName
import io.github.aplcornell.viaduct.syntax.Arguments
import io.github.aplcornell.viaduct.syntax.Protocol
import io.github.aplcornell.viaduct.syntax.circuit.ArrayTypeNode
import io.github.aplcornell.viaduct.syntax.circuit.CircuitDeclarationNode
import io.github.aplcornell.viaduct.syntax.circuit.CircuitLetNode
import io.github.aplcornell.viaduct.syntax.circuit.CircuitStatementNode
import io.github.aplcornell.viaduct.syntax.circuit.ExpressionNode
import io.github.aplcornell.viaduct.syntax.circuit.IndexExpressionNode
import io.github.aplcornell.viaduct.syntax.circuit.LookupNode
import io.github.aplcornell.viaduct.syntax.circuit.OperatorApplicationNode
import io.github.aplcornell.viaduct.syntax.circuit.OperatorNode
import io.github.aplcornell.viaduct.syntax.circuit.ReduceNode
import io.github.aplcornell.viaduct.syntax.types.ValueType
abstract class AbstractCodeGenerator(val context: CodeGeneratorContext) : CodeGenerator {
override fun paramType(protocol: Protocol, sourceType: ValueType): TypeName = typeTranslator(sourceType)
override fun storageType(protocol: Protocol, sourceType: ValueType): TypeName = typeTranslator(sourceType)
fun paramType(protocol: Protocol, sourceType: ArrayTypeNode): TypeName =
kotlinType(sourceType.shape, paramType(protocol, sourceType.elementType.value))
fun storageType(protocol: Protocol, sourceType: ArrayTypeNode): TypeName =
kotlinType(sourceType.shape, storageType(protocol, sourceType.elementType.value))
override fun circuitBody(
protocol: Protocol,
circuitDeclaration: CircuitDeclarationNode,
outParams: List<CodeBlock>,
): CodeBlock {
val builder = CodeBlock.builder()
for (stmt in circuitDeclaration.body) {
generate(protocol, builder, stmt)
}
circuitDeclaration.body.returnStatement.values.forEachIndexed { index, value ->
builder.addStatement(
"%L.set(%L)",
outParams[index],
indexExpression(value, context),
)
}
return builder.build()
}
private fun generate(protocol: Protocol, builder: CodeBlock.Builder, stmt: CircuitStatementNode) {
when (stmt) {
is CircuitLetNode -> {
builder.addStatement(
"val %N = %L",
context.kotlinName(stmt.name.value),
stmt.indices.new(context, exp(protocol, stmt.value)),
)
}
}
}
open fun exp(protocol: Protocol, expr: ExpressionNode): CodeBlock = when (expr) {
is IndexExpressionNode -> indexExpression(expr, context)
is LookupNode -> {
CodeBlock.of("%N", context.kotlinName(expr.variable.value))
.lookup(expr.indices.map { indexExpression(it, context) })
}
is ReduceNode -> reduce(protocol, expr)
is OperatorApplicationNode -> CodeBlock.of(
"(%L)",
operatorApplication(protocol, expr.operator, expr.arguments.map { exp(protocol, it) }),
)
}
open fun operatorApplication(protocol: Protocol, op: OperatorNode, arguments: List<CodeBlock>): CodeBlock =
throw UnsupportedOperatorException(protocol, op)
private fun reduce(protocol: Protocol, r: ReduceNode): CodeBlock {
val builder = CodeBlock.builder()
builder.add(Arguments(listOf(r.indices), r.indices.bound.sourceLocation).new(context, exp(protocol, r.body)))
val left = context.newTemporary("left")
val right = context.newTemporary("right")
builder.beginControlFlow(
".%M { %N, %N ->",
MemberName("kotlin.collections", "reduceOrNull"),
left,
right,
)
builder.add(
operatorApplication(
protocol,
r.operator,
listOf(CodeBlock.of(left), CodeBlock.of(right)),
),
)
builder.endControlFlow()
builder.add("?: %L", exp(protocol, r.defaultValue))
return builder.build()
}
override fun setup(protocol: Protocol): Iterable<PropertySpec> = listOf()
}
| 31 | Kotlin | 4 | 20 | 567491fdcfd313bf287b8cdd374e80f1e005ac62 | 4,394 | viaduct | MIT License |
home/src/main/java/com/pyamsoft/tickertape/home/HomePortfolio.kt | pyamsoft | 371,196,339 | false | {"Kotlin": 1132677, "Shell": 2191} | /*
* Copyright 2024 pyamsoft
*
* 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.pyamsoft.tickertape.home
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.Crossfade
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.pyamsoft.pydroid.theme.keylines
import com.pyamsoft.tickertape.home.item.HomePortfolioSummaryItem
import kotlinx.coroutines.CoroutineScope
@Composable
internal fun HomePortfolio(
modifier: Modifier = Modifier,
state: HomePortfolioViewState,
onRefresh: CoroutineScope.() -> Unit,
) {
val loadingState by state.isLoadingPortfolio.collectAsStateWithLifecycle()
val portfolio by state.portfolio.collectAsStateWithLifecycle()
val portfolioError by state.portfolioError.collectAsStateWithLifecycle()
val isEmptyPortfolio =
remember(portfolio) { portfolio.let { it == null || it.stocks.positions.isEmpty() } }
val isLoading = remember(loadingState) { loadingState == HomeBaseViewState.LoadingState.LOADING }
val isVisible =
remember(
isEmptyPortfolio,
isLoading,
) {
!isEmptyPortfolio || isLoading
}
// As long as we are blank
LaunchedEffect(isEmptyPortfolio) {
val scope = this
// Load even if not currently visible
scope.onRefresh()
}
Crossfade(
modifier = modifier,
label = "Portfolio Summary",
targetState = portfolioError,
) { err ->
if (err == null) {
Column {
AnimatedVisibility(
visible = isVisible,
) {
Text(
modifier =
Modifier.padding(
start = MaterialTheme.keylines.content,
bottom = MaterialTheme.keylines.baseline,
),
text = "My Portfolio Summary",
style =
MaterialTheme.typography.body1.copy(
fontWeight = FontWeight.W400,
),
)
}
Box(
modifier = Modifier.fillMaxWidth().height(HomeScreenDefaults.PORTFOLIO_HEIGHT),
) {
portfolio?.also { p ->
HomePortfolioSummaryItem(
modifier =
Modifier.matchParentSize().padding(horizontal = MaterialTheme.keylines.content),
portfolio = p,
)
}
Loading(
modifier = Modifier.matchParentSize(),
isLoading = isLoading,
)
}
}
} else {
Error(
modifier = Modifier.fillMaxWidth(),
error = err,
)
}
}
}
@Composable
private fun Loading(
isLoading: Boolean,
modifier: Modifier = Modifier,
) {
AnimatedVisibility(
modifier = modifier,
visible = isLoading,
enter = fadeIn(),
exit = fadeOut(),
) {
Box(
modifier = modifier.padding(MaterialTheme.keylines.content),
contentAlignment = Alignment.Center,
) {
CircularProgressIndicator()
}
}
}
@Composable
private fun Error(
modifier: Modifier = Modifier,
error: Throwable,
) {
Column(
modifier = modifier.padding(MaterialTheme.keylines.content),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(
textAlign = TextAlign.Center,
text = error.message ?: "An unexpected error occurred",
style =
MaterialTheme.typography.body1.copy(
color = MaterialTheme.colors.error,
),
)
Text(
modifier = Modifier.padding(top = MaterialTheme.keylines.content),
textAlign = TextAlign.Center,
text = "Please try again later.",
style = MaterialTheme.typography.body2,
)
}
}
@Preview
@Composable
private fun PreviewPortfolio() {
Surface {
HomePortfolio(
state = MutableHomeViewState(),
onRefresh = {},
)
}
}
| 1 | Kotlin | 0 | 7 | 9b793a0fb08c4bcf87d4f9e2c25628ddf534ba40 | 5,424 | tickertape | Apache License 2.0 |
app/src/main/java/com/thread0/weather/util/AQIUtil.kt | wuzelong | 384,625,570 | false | null | /*
* @Copyright: 2020-2021 www.thread0.com Inc. All rights reserved.
*/
package com.thread0.weather.util
import com.thread0.weather.R
object AQIUtil {
/**
* 获取AQI对应颜色
*/
fun getColor(aqi:Int): Int {
return when(aqi){
in 0..50-> R.color.btn_text
in 51..100->R.color.yellow
in 101..150->R.color.yellow_FF980
in 151..200->R.color.choice_ring
in 201..300->R.color.brown
else->R.color.purple
}
}
/**
* 获取AQI对应颜色(十六进制)
*/
fun getColorOx(aqi:Int): String {
return when(aqi){
in 0..50-> "#33C759"
in 51..100->"#C2C95E"
in 101..150->"#FF9800"
in 151..200->"#FF3B30"
in 201..300->"#734A26"
else->"#4B2060"
}
}
/**
* 获取AQI对应等级
*/
fun getQuality(aqi:Int): String{
return when(aqi){
in 0..50->"优"
in 51..100->"良"
in 101..150->"轻度污染"
in 151..200->"中度污染"
in 201..300->"重度污染"
else->"严重污染"
}
}
} | 0 | Kotlin | 0 | 1 | 00f93f0c656d3734c4d3bb10c66ec94f6e030d7e | 1,113 | weather | Apache License 2.0 |
src/main/kotlin/org/wfanet/measurement/reporting/service/api/v2alpha/ReportsService.kt | world-federation-of-advertisers | 349,561,061 | false | null | /*
* Copyright 2023 The Cross-Media Measurement Authors
*
* 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.wfanet.measurement.reporting.service.api.v2alpha
import com.google.protobuf.Timestamp
import com.google.protobuf.util.Timestamps
import com.google.type.Date
import com.google.type.Interval
import com.google.type.copy
import com.google.type.date
import com.google.type.interval
import io.grpc.Status
import io.grpc.StatusException
import io.grpc.StatusRuntimeException
import java.time.DateTimeException
import java.time.LocalDate
import java.time.Period
import java.time.temporal.ChronoField
import java.time.temporal.ChronoUnit
import java.time.temporal.Temporal
import java.time.temporal.TemporalAdjusters
import java.time.zone.ZoneRulesException
import kotlin.math.min
import kotlin.random.Random
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.flatMapMerge
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.toList
import org.projectnessie.cel.Env
import org.wfanet.measurement.api.v2alpha.MeasurementConsumerKey
import org.wfanet.measurement.common.base64UrlDecode
import org.wfanet.measurement.common.base64UrlEncode
import org.wfanet.measurement.common.grpc.failGrpc
import org.wfanet.measurement.common.grpc.grpcRequire
import org.wfanet.measurement.common.grpc.grpcRequireNotNull
import org.wfanet.measurement.common.toProtoTime
import org.wfanet.measurement.config.reporting.MetricSpecConfig
import org.wfanet.measurement.internal.reporting.v2.CreateReportRequest as InternalCreateReportRequest
import org.wfanet.measurement.internal.reporting.v2.CreateReportRequestKt
import org.wfanet.measurement.internal.reporting.v2.MetricCalculationSpec as InternalMetricCalculationSpec
import org.wfanet.measurement.internal.reporting.v2.MetricCalculationSpec
import org.wfanet.measurement.internal.reporting.v2.MetricCalculationSpecsGrpcKt.MetricCalculationSpecsCoroutineStub
import org.wfanet.measurement.internal.reporting.v2.Report as InternalReport
import org.wfanet.measurement.internal.reporting.v2.ReportKt as InternalReportKt
import org.wfanet.measurement.internal.reporting.v2.ReportsGrpcKt.ReportsCoroutineStub
import org.wfanet.measurement.internal.reporting.v2.StreamReportsRequest
import org.wfanet.measurement.internal.reporting.v2.batchGetMetricCalculationSpecsRequest
import org.wfanet.measurement.internal.reporting.v2.createReportRequest as internalCreateReportRequest
import org.wfanet.measurement.internal.reporting.v2.getReportRequest as internalGetReportRequest
import org.wfanet.measurement.internal.reporting.v2.report as internalReport
import org.wfanet.measurement.reporting.service.api.submitBatchRequests
import org.wfanet.measurement.reporting.service.api.v2alpha.MetadataPrincipalServerInterceptor.Companion.withPrincipalName
import org.wfanet.measurement.reporting.service.api.v2alpha.ReportScheduleInfoServerInterceptor.Companion.reportScheduleInfoFromCurrentContext
import org.wfanet.measurement.reporting.v2alpha.BatchCreateMetricsResponse
import org.wfanet.measurement.reporting.v2alpha.BatchGetMetricsResponse
import org.wfanet.measurement.reporting.v2alpha.CreateMetricRequest
import org.wfanet.measurement.reporting.v2alpha.CreateReportRequest
import org.wfanet.measurement.reporting.v2alpha.GetReportRequest
import org.wfanet.measurement.reporting.v2alpha.ListReportsPageToken
import org.wfanet.measurement.reporting.v2alpha.ListReportsPageTokenKt
import org.wfanet.measurement.reporting.v2alpha.ListReportsRequest
import org.wfanet.measurement.reporting.v2alpha.ListReportsResponse
import org.wfanet.measurement.reporting.v2alpha.Metric
import org.wfanet.measurement.reporting.v2alpha.MetricsGrpcKt.MetricsCoroutineStub
import org.wfanet.measurement.reporting.v2alpha.Report
import org.wfanet.measurement.reporting.v2alpha.ReportKt
import org.wfanet.measurement.reporting.v2alpha.ReportsGrpcKt.ReportsCoroutineImplBase
import org.wfanet.measurement.reporting.v2alpha.batchCreateMetricsRequest
import org.wfanet.measurement.reporting.v2alpha.batchGetMetricsRequest
import org.wfanet.measurement.reporting.v2alpha.copy
import org.wfanet.measurement.reporting.v2alpha.listReportsPageToken
import org.wfanet.measurement.reporting.v2alpha.listReportsResponse
import org.wfanet.measurement.reporting.v2alpha.report
private const val MIN_PAGE_SIZE = 1
private const val DEFAULT_PAGE_SIZE = 50
private const val MAX_PAGE_SIZE = 1000
private const val BATCH_CREATE_METRICS_LIMIT = 1000
private const val BATCH_GET_METRICS_LIMIT = 100
private typealias InternalReportingMetricEntries =
Map<String, InternalReport.ReportingMetricCalculationSpec>
class ReportsService(
private val internalReportsStub: ReportsCoroutineStub,
private val internalMetricCalculationSpecsStub: MetricCalculationSpecsCoroutineStub,
private val metricsStub: MetricsCoroutineStub,
private val metricSpecConfig: MetricSpecConfig,
private val secureRandom: Random,
) : ReportsCoroutineImplBase() {
private data class CreateReportInfo(
val parent: String,
val requestId: String,
val timeIntervals: List<Interval>?,
val reportingInterval: Report.ReportingInterval?,
)
override suspend fun listReports(request: ListReportsRequest): ListReportsResponse {
val parentKey: MeasurementConsumerKey =
grpcRequireNotNull(MeasurementConsumerKey.fromName(request.parent)) {
"Parent is either unspecified or invalid."
}
val listReportsPageToken = request.toListReportsPageToken()
val principal: ReportingPrincipal = principalFromCurrentContext
when (principal) {
is MeasurementConsumerPrincipal -> {
if (parentKey != principal.resourceKey) {
failGrpc(Status.PERMISSION_DENIED) {
"Cannot list Reports belonging to other MeasurementConsumers."
}
}
}
}
val streamInternalReportsRequest: StreamReportsRequest =
listReportsPageToken.toStreamReportsRequest()
val results: List<InternalReport> =
try {
internalReportsStub.streamReports(streamInternalReportsRequest).toList()
} catch (e: StatusException) {
throw when (e.status.code) {
Status.Code.DEADLINE_EXCEEDED -> Status.DEADLINE_EXCEEDED
Status.Code.CANCELLED -> Status.CANCELLED
else -> Status.UNKNOWN
}
.withCause(e)
.withDescription("Unable to list Reports.")
.asRuntimeException()
}
if (results.isEmpty()) {
return ListReportsResponse.getDefaultInstance()
}
val nextPageToken: ListReportsPageToken? =
if (results.size > listReportsPageToken.pageSize) {
listReportsPageToken.copy {
lastReport =
ListReportsPageTokenKt.previousPageEnd {
cmmsMeasurementConsumerId = results[results.lastIndex - 1].cmmsMeasurementConsumerId
createTime = results[results.lastIndex - 1].createTime
externalReportId = results[results.lastIndex - 1].externalReportId
}
}
} else {
null
}
val subResults: List<InternalReport> =
results.subList(0, min(results.size, listReportsPageToken.pageSize))
// Get metrics.
val metricNames: Flow<String> = flow {
buildSet {
for (internalReport in subResults) {
for (reportingMetricEntry in internalReport.reportingMetricEntriesMap) {
for (metricCalculationSpecReportingMetrics in
reportingMetricEntry.value.metricCalculationSpecReportingMetricsList) {
for (reportingMetric in metricCalculationSpecReportingMetrics.reportingMetricsList) {
val name =
MetricKey(
internalReport.cmmsMeasurementConsumerId,
reportingMetric.externalMetricId,
)
.toName()
if (!contains(name)) {
emit(name)
add(name)
}
}
}
}
}
}
}
val callRpc: suspend (List<String>) -> BatchGetMetricsResponse = { items ->
batchGetMetrics(principal.resourceKey.toName(), items)
}
val externalIdToMetricMap: Map<String, Metric> = buildMap {
submitBatchRequests(metricNames, BATCH_GET_METRICS_LIMIT, callRpc) { response ->
response.metricsList
}
.collect { metrics: List<Metric> ->
for (metric in metrics) {
computeIfAbsent(checkNotNull(MetricKey.fromName(metric.name)).metricId) { metric }
}
}
}
return listReportsResponse {
reports +=
filterReports(
subResults.map { internalReport ->
convertInternalReportToPublic(internalReport, externalIdToMetricMap)
},
request.filter,
)
if (nextPageToken != null) {
this.nextPageToken = nextPageToken.toByteString().base64UrlEncode()
}
}
}
override suspend fun getReport(request: GetReportRequest): Report {
val reportKey =
grpcRequireNotNull(ReportKey.fromName(request.name)) {
"Report name is either unspecified or invalid"
}
val principal: ReportingPrincipal = principalFromCurrentContext
when (principal) {
is MeasurementConsumerPrincipal -> {
if (reportKey.parentKey != principal.resourceKey) {
failGrpc(Status.PERMISSION_DENIED) {
"Cannot get Report belonging to other MeasurementConsumers."
}
}
}
}
val internalReport =
try {
internalReportsStub.getReport(
internalGetReportRequest {
cmmsMeasurementConsumerId = reportKey.cmmsMeasurementConsumerId
externalReportId = reportKey.reportId
}
)
} catch (e: StatusException) {
throw when (e.status.code) {
Status.Code.DEADLINE_EXCEEDED -> Status.DEADLINE_EXCEEDED
Status.Code.CANCELLED -> Status.CANCELLED
Status.Code.NOT_FOUND -> Status.NOT_FOUND
else -> Status.UNKNOWN
}
.withCause(e)
.withDescription("Unable to get Report.")
.asRuntimeException()
}
// Get metrics.
val metricNames: Flow<String> = flow {
buildSet {
for (reportingMetricEntry in internalReport.reportingMetricEntriesMap) {
for (metricCalculationSpecReportingMetrics in
reportingMetricEntry.value.metricCalculationSpecReportingMetricsList) {
for (reportingMetric in metricCalculationSpecReportingMetrics.reportingMetricsList) {
val name =
MetricKey(
internalReport.cmmsMeasurementConsumerId,
reportingMetric.externalMetricId,
)
.toName()
if (!contains(name)) {
emit(name)
add(name)
}
}
}
}
}
}
val callRpc: suspend (List<String>) -> BatchGetMetricsResponse = { items ->
batchGetMetrics(principal.resourceKey.toName(), items)
}
val externalIdToMetricMap: Map<String, Metric> = buildMap {
submitBatchRequests(metricNames, BATCH_GET_METRICS_LIMIT, callRpc) { response ->
response.metricsList
}
.collect { metrics: List<Metric> ->
for (metric in metrics) {
computeIfAbsent(checkNotNull(MetricKey.fromName(metric.name)).metricId) { metric }
}
}
}
// Convert the internal report to public and return.
return convertInternalReportToPublic(internalReport, externalIdToMetricMap)
}
private suspend fun batchGetMetrics(
parent: String,
metricNames: List<String>,
): BatchGetMetricsResponse {
return try {
metricsStub
.withPrincipalName(parent)
.batchGetMetrics(
batchGetMetricsRequest {
this.parent = parent
names += metricNames
}
)
} catch (e: StatusException) {
throw when (e.status.code) {
Status.Code.INVALID_ARGUMENT ->
Status.INVALID_ARGUMENT.withDescription("Unable to get Metrics.\n${e.message}")
Status.Code.PERMISSION_DENIED ->
Status.PERMISSION_DENIED.withDescription("Unable to get Metrics.\n${e.message}")
else -> Status.UNKNOWN.withDescription("Unable to get Metrics.\n${e.message}")
}
.withCause(e)
.asRuntimeException()
}
}
override suspend fun createReport(request: CreateReportRequest): Report {
val parentKey: MeasurementConsumerKey =
grpcRequireNotNull(MeasurementConsumerKey.fromName(request.parent)) {
"Parent is either unspecified or invalid."
}
val principal: ReportingPrincipal = principalFromCurrentContext
when (principal) {
is MeasurementConsumerPrincipal -> {
if (parentKey != principal.resourceKey) {
failGrpc(Status.PERMISSION_DENIED) {
"Cannot create a Report for another MeasurementConsumer."
}
}
}
}
grpcRequire(request.hasReport()) { "Report is not specified." }
grpcRequire(request.reportId.matches(RESOURCE_ID_REGEX)) { "Report ID is invalid." }
grpcRequire(request.report.reportingMetricEntriesList.isNotEmpty()) {
"No ReportingMetricEntry is specified."
}
validateTime(request.report)
val externalMetricCalculationSpecIds: List<String> =
request.report.reportingMetricEntriesList.flatMap { reportingMetricEntry ->
reportingMetricEntry.value.metricCalculationSpecsList.map {
val key =
grpcRequireNotNull(MetricCalculationSpecKey.fromName(it)) {
"MetricCalculationSpec name $it is invalid."
}
key.metricCalculationSpecId
}
}
val externalIdToMetricCalculationSpecMap: Map<String, InternalMetricCalculationSpec> =
createExternalIdToMetricCalculationSpecMap(
parentKey.measurementConsumerId,
externalMetricCalculationSpecIds,
)
// Build an internal CreateReportRequest.
// The internal report in CreateReportRequest has several
// ReportingMetrics without request IDs and external metric IDs.
val internalCreateReportRequest: InternalCreateReportRequest =
buildInternalCreateReportRequest(request, externalIdToMetricCalculationSpecMap)
// Create an internal report
// The internal report service will fill request IDs in
// MetricCalculationSpec.ReportingMetrics. If there are existing metrics based on the
// request IDs, the external metric IDs will also be filled.
val internalReport =
try {
internalReportsStub.createReport(internalCreateReportRequest)
} catch (e: StatusException) {
throw when (e.status.code) {
Status.Code.DEADLINE_EXCEEDED ->
Status.DEADLINE_EXCEEDED.withDescription("Unable to create Report.")
Status.Code.CANCELLED -> Status.CANCELLED.withDescription("Unable to create Report.")
Status.Code.FAILED_PRECONDITION ->
Status.FAILED_PRECONDITION.withDescription(
"Unable to create Report. The measurement consumer not found."
)
Status.Code.ALREADY_EXISTS ->
Status.ALREADY_EXISTS.withDescription(
"Report with ID ${request.reportId} already exists under ${request.parent}"
)
Status.Code.NOT_FOUND ->
if (e.message!!.contains("external_report_schedule_id")) {
Status.NOT_FOUND.withDescription(
"ReportSchedule associated with the Report not found."
)
} else if (e.message!!.contains("external_metric_calculation_spec_id")) {
Status.NOT_FOUND.withDescription(
"MetricCalculationSpec used in the Report not found."
)
} else {
Status.NOT_FOUND.withDescription("ReportingSet used in the Report not found.")
}
else -> Status.UNKNOWN.withDescription("Unable to create Report.")
}
.withCause(e)
.asRuntimeException()
}
// Create metrics.
val createMetricRequests: Flow<CreateMetricRequest> =
@OptIn(ExperimentalCoroutinesApi::class)
internalReport.reportingMetricEntriesMap.entries.asFlow().flatMapMerge { entry ->
entry.value.metricCalculationSpecReportingMetricsList.asFlow().flatMapMerge {
metricCalculationSpecReportingMetrics ->
metricCalculationSpecReportingMetrics.reportingMetricsList.asFlow().map {
it.toCreateMetricRequest(
principal.resourceKey,
entry.key,
externalIdToMetricCalculationSpecMap
.getValue(metricCalculationSpecReportingMetrics.externalMetricCalculationSpecId)
.details
.filter,
)
}
}
}
val callRpc: suspend (List<CreateMetricRequest>) -> BatchCreateMetricsResponse = { items ->
batchCreateMetrics(request.parent, items)
}
val externalIdToMetricMap: Map<String, Metric> = buildMap {
submitBatchRequests(createMetricRequests, BATCH_CREATE_METRICS_LIMIT, callRpc) { response ->
response.metricsList
}
.collect { metrics: List<Metric> ->
for (metric in metrics) {
computeIfAbsent(checkNotNull(MetricKey.fromName(metric.name)).metricId) { metric }
}
}
}
// Once all metrics are created, get the updated internal report with the metric IDs filled.
val updatedInternalReport =
try {
internalReportsStub.getReport(
internalGetReportRequest {
cmmsMeasurementConsumerId = internalReport.cmmsMeasurementConsumerId
externalReportId = internalReport.externalReportId
}
)
} catch (e: StatusException) {
throw Status.UNKNOWN.withDescription("Unable to create Report.")
.withCause(e)
.withDescription("Report created, but error returning the Report.")
.asRuntimeException()
}
// Convert the internal report to public and return.
return convertInternalReportToPublic(updatedInternalReport, externalIdToMetricMap)
}
/** Returns a map of external IDs to [InternalMetricCalculationSpec]. */
private suspend fun createExternalIdToMetricCalculationSpecMap(
cmmsMeasurementConsumerId: String,
externalMetricCalculationSpecIds: List<String>,
): Map<String, InternalMetricCalculationSpec> {
return try {
internalMetricCalculationSpecsStub
.batchGetMetricCalculationSpecs(
batchGetMetricCalculationSpecsRequest {
this.cmmsMeasurementConsumerId = cmmsMeasurementConsumerId
this.externalMetricCalculationSpecIds += externalMetricCalculationSpecIds.toHashSet()
}
)
.metricCalculationSpecsList
.associateBy({ it.externalMetricCalculationSpecId }, { it })
} catch (e: StatusException) {
throw when (e.status.code) {
Status.Code.DEADLINE_EXCEEDED ->
Status.DEADLINE_EXCEEDED.withDescription(
"Unable to get MetricCalculationSpecs in Report."
)
Status.Code.CANCELLED ->
Status.CANCELLED.withDescription("Unable to get MetricCalculationSpecs in Report.")
Status.Code.NOT_FOUND ->
Status.NOT_FOUND.withDescription("MetricCalculationSpec in Report not found.")
else -> Status.UNKNOWN.withDescription("Unable to get MetricCalculationSpecs in Report.")
}
.withCause(e)
.asRuntimeException()
}
}
/** Converts an internal [InternalReport] to a public [Report]. */
private suspend fun convertInternalReportToPublic(
internalReport: InternalReport,
externalIdToMetricMap: Map<String, Metric>,
): Report {
return report {
name =
ReportKey(internalReport.cmmsMeasurementConsumerId, internalReport.externalReportId)
.toName()
tags.putAll(internalReport.details.tagsMap)
reportingMetricEntries +=
internalReport.reportingMetricEntriesMap.map { internalReportingMetricEntry ->
internalReportingMetricEntry.toReportingMetricEntry(
internalReport.cmmsMeasurementConsumerId
)
}
if (internalReport.details.hasReportingInterval()) {
reportingInterval = internalReport.details.reportingInterval.toReportingInterval()
} else {
timeIntervals = internalReport.details.timeIntervals.toTimeIntervals()
}
val metrics: List<Metric> =
internalReport.externalMetricIds.map { externalMetricId ->
externalIdToMetricMap.getValue(externalMetricId)
}
state = inferReportState(metrics)
createTime = internalReport.createTime
if (state == Report.State.SUCCEEDED || state == Report.State.FAILED) {
val externalMetricCalculationSpecIds =
internalReport.reportingMetricEntriesMap.flatMap { reportingMetricCalculationSpec ->
reportingMetricCalculationSpec.value.metricCalculationSpecReportingMetricsList.map {
it.externalMetricCalculationSpecId
}
}
val externalIdToMetricCalculationMap: Map<String, InternalMetricCalculationSpec> =
createExternalIdToMetricCalculationSpecMap(
internalReport.cmmsMeasurementConsumerId,
externalMetricCalculationSpecIds,
)
this.metricCalculationResults +=
buildMetricCalculationResults(
internalReport.cmmsMeasurementConsumerId,
internalReport.reportingMetricEntriesMap,
externalIdToMetricMap,
externalIdToMetricCalculationMap,
)
}
if (internalReport.externalReportScheduleId.isNotEmpty()) {
reportSchedule =
ReportScheduleKey(
internalReport.cmmsMeasurementConsumerId,
internalReport.externalReportScheduleId,
)
.toName()
}
}
}
/** Builds [Report.MetricCalculationResult]s. */
private fun buildMetricCalculationResults(
cmmsMeasurementConsumerId: String,
internalReportingMetricEntries: InternalReportingMetricEntries,
externalIdToMetricMap: Map<String, Metric>,
externalIdToMetricCalculationMap: Map<String, InternalMetricCalculationSpec>,
): List<Report.MetricCalculationResult> {
return internalReportingMetricEntries.flatMap { (reportingSetId, reportingMetricCalculationSpec)
->
val reportingSetName = ReportingSetKey(cmmsMeasurementConsumerId, reportingSetId).toName()
reportingMetricCalculationSpec.metricCalculationSpecReportingMetricsList.map {
metricCalculationSpecReportingMetrics ->
val metricCalculationSpec =
externalIdToMetricCalculationMap.getValue(
metricCalculationSpecReportingMetrics.externalMetricCalculationSpecId
)
ReportKt.metricCalculationResult {
this.metricCalculationSpec =
MetricCalculationSpecKey(
metricCalculationSpec.cmmsMeasurementConsumerId,
metricCalculationSpec.externalMetricCalculationSpecId,
)
.toName()
displayName = metricCalculationSpec.details.displayName
reportingSet = reportingSetName
resultAttributes +=
metricCalculationSpecReportingMetrics.reportingMetricsList.map { reportingMetric ->
val metric =
externalIdToMetricMap[reportingMetric.externalMetricId]
?: error("Got a metric not associated with the report.")
ReportKt.MetricCalculationResultKt.resultAttribute {
this.metric = metric.name
groupingPredicates += reportingMetric.details.groupingPredicatesList
filter = metricCalculationSpec.details.filter
metricSpec = metric.metricSpec
timeInterval = metric.timeInterval
state = metric.state
if (metric.state == Metric.State.SUCCEEDED) {
metricResult = metric.result
}
}
}
}
}
}
}
/** Creates a batch of [Metric]s. */
private suspend fun batchCreateMetrics(
parent: String,
createMetricRequests: List<CreateMetricRequest>,
): BatchCreateMetricsResponse {
return try {
metricsStub
.withPrincipalName(parent)
.batchCreateMetrics(
batchCreateMetricsRequest {
this.parent = parent
requests += createMetricRequests
}
)
} catch (e: StatusException) {
throw when (e.status.code) {
Status.Code.PERMISSION_DENIED -> Status.PERMISSION_DENIED.withDescription(e.message)
Status.Code.INVALID_ARGUMENT -> Status.INVALID_ARGUMENT.withDescription(e.message)
Status.Code.NOT_FOUND -> Status.NOT_FOUND.withDescription(e.message)
Status.Code.FAILED_PRECONDITION -> Status.FAILED_PRECONDITION.withDescription(e.message)
else -> Status.UNKNOWN.withDescription("Unable to create Metrics.")
}
.withCause(e)
.asRuntimeException()
}
}
/** Builds an [InternalCreateReportRequest]. */
private fun buildInternalCreateReportRequest(
request: CreateReportRequest,
externalIdToMetricCalculationMap: Map<String, InternalMetricCalculationSpec>,
): InternalCreateReportRequest {
val cmmsMeasurementConsumerId =
checkNotNull(MeasurementConsumerKey.fromName(request.parent)).measurementConsumerId
return internalCreateReportRequest {
report = internalReport {
@Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA")
details =
InternalReportKt.details {
tags.putAll(request.report.tagsMap)
when (request.report.timeCase) {
Report.TimeCase.TIME_INTERVALS -> {
timeIntervals = request.report.timeIntervals.toInternal()
}
Report.TimeCase.REPORTING_INTERVAL -> {
reportingInterval = request.report.reportingInterval.toInternal()
}
Report.TimeCase.TIME_NOT_SET ->
failGrpc(Status.INVALID_ARGUMENT) { "The time in Report is not specified." }
}
}
this.cmmsMeasurementConsumerId = cmmsMeasurementConsumerId
reportingMetricEntries.putAll(
buildInternalReportingMetricEntries(request, externalIdToMetricCalculationMap)
)
}
requestId = request.requestId
externalReportId = request.reportId
val reportScheduleInfo: ReportScheduleInfoServerInterceptor.ReportScheduleInfo? =
reportScheduleInfoFromCurrentContext
if (reportScheduleInfo != null) {
val reportScheduleKey =
grpcRequireNotNull(ReportScheduleKey.fromName(reportScheduleInfo.name)) {
"reportScheduleName is invalid"
}
this.reportScheduleInfo =
CreateReportRequestKt.reportScheduleInfo {
externalReportScheduleId = reportScheduleKey.reportScheduleId
nextReportCreationTime = reportScheduleInfo.nextReportCreationTime
}
}
}
}
/** Builds an [InternalReportingMetricEntries] from a [CreateReportRequest]. */
private fun buildInternalReportingMetricEntries(
request: CreateReportRequest,
externalIdToMetricCalculationMap: Map<String, InternalMetricCalculationSpec>,
): InternalReportingMetricEntries {
val measurementConsumerKey = checkNotNull(MeasurementConsumerKey.fromName(request.parent))
val createReportInfo =
if (request.report.hasTimeIntervals()) {
CreateReportInfo(
request.parent,
request.requestId,
request.report.timeIntervals.timeIntervalsList,
null,
)
} else {
CreateReportInfo(request.parent, request.requestId, null, request.report.reportingInterval)
}
return request.report.reportingMetricEntriesList.associate { reportingMetricEntry ->
val reportingSetKey =
grpcRequireNotNull(ReportingSetKey.fromName(reportingMetricEntry.key)) {
"Invalid reporting set name ${reportingMetricEntry.key}."
}
if (
reportingSetKey.cmmsMeasurementConsumerId != measurementConsumerKey.measurementConsumerId
) {
failGrpc(Status.PERMISSION_DENIED) {
"Cannot access reporting set ${reportingMetricEntry.key}."
}
}
grpcRequire(reportingMetricEntry.hasValue()) {
"Value in ReportingMetricEntry with key-${reportingMetricEntry.key} is not set."
}
grpcRequire(reportingMetricEntry.value.metricCalculationSpecsList.isNotEmpty()) {
"There is no MetricCalculationSpec associated to ${reportingMetricEntry.key}."
}
val reportingSetId = reportingSetKey.reportingSetId
reportingSetId to
InternalReportKt.reportingMetricCalculationSpec {
metricCalculationSpecReportingMetrics +=
reportingMetricEntry.value.metricCalculationSpecsList.map { metricCalculationSpecName ->
val metricCalculationSpecKey =
grpcRequireNotNull(MetricCalculationSpecKey.fromName(metricCalculationSpecName)) {
"MetricCalculationSpec name $metricCalculationSpecName is invalid."
}
buildInternalMetricCalculationSpecReportingMetrics(
externalIdToMetricCalculationMap.getValue(
metricCalculationSpecKey.metricCalculationSpecId
),
createReportInfo,
)
}
}
}
}
/**
* Builds an [InternalReport.MetricCalculationSpecReportingMetrics] from a
* [Report.ReportingMetricEntry].
*/
private fun buildInternalMetricCalculationSpecReportingMetrics(
internalMetricCalculationSpec: InternalMetricCalculationSpec,
createReportInfo: CreateReportInfo,
): InternalReport.MetricCalculationSpecReportingMetrics {
val timeIntervals: List<Interval> =
if (createReportInfo.timeIntervals != null) {
grpcRequire(!internalMetricCalculationSpec.details.hasMetricFrequencySpec()) {
"metric_calculation_spec with metric_frequency_spec set not allowed when time_intervals is set."
}
createReportInfo.timeIntervals
} else {
if (!internalMetricCalculationSpec.details.hasMetricFrequencySpec()) {
generateTimeIntervals(checkNotNull(createReportInfo.reportingInterval), null, null)
} else {
val trailingWindow: InternalMetricCalculationSpec.TrailingWindow? =
if (internalMetricCalculationSpec.details.hasTrailingWindow()) {
internalMetricCalculationSpec.details.trailingWindow
} else {
null
}
val generatedTimeIntervals: List<Interval> =
generateTimeIntervals(
checkNotNull(createReportInfo.reportingInterval),
internalMetricCalculationSpec.details.metricFrequencySpec,
trailingWindow,
)
grpcRequire(generatedTimeIntervals.isNotEmpty()) {
"No time intervals can be generated from the combination of the reporting_interval and metric_calculation_spec ${
MetricCalculationSpecKey(
internalMetricCalculationSpec.cmmsMeasurementConsumerId,
internalMetricCalculationSpec.externalMetricCalculationSpecId,
).toName()
}"
}
generatedTimeIntervals
}
}
// Expand groupings to predicate groups in Cartesian product
val groupings: List<List<String>> =
internalMetricCalculationSpec.details.groupingsList.map { it.predicatesList }
val groupingsCartesianProduct: List<List<String>> = cartesianProduct(groupings)
return InternalReportKt.metricCalculationSpecReportingMetrics {
externalMetricCalculationSpecId =
internalMetricCalculationSpec.externalMetricCalculationSpecId
// Fan out to a list of reportingMetrics with the Cartesian product of metric specs,
// predicate groups, and time intervals.
reportingMetrics +=
timeIntervals.flatMap { timeInterval ->
internalMetricCalculationSpec.details.metricSpecsList.flatMap { metricSpec ->
groupingsCartesianProduct.map { groupingPredicates ->
InternalReportKt.reportingMetric {
details =
InternalReportKt.ReportingMetricKt.details {
this.metricSpec =
try {
metricSpec
.toMetricSpec()
.withDefaults(metricSpecConfig, secureRandom)
.toInternal()
} catch (e: MetricSpecDefaultsException) {
failGrpc(Status.INVALID_ARGUMENT) {
listOfNotNull("Invalid metric spec.", e.message, e.cause?.message)
.joinToString(separator = "\n")
}
} catch (e: Exception) {
failGrpc(Status.UNKNOWN) { "Failed to read the metric spec." }
}
this.timeInterval = timeInterval
this.groupingPredicates += groupingPredicates
}
}
}
}
}
}
}
/**
* Outputs the Cartesian product of any number of lists with elements in the same type.
*
* Note that Cartesian product allows duplicates.
*
* @param lists contains the lists that will be used to generate the Cartesian product. All lists
* must not be empty.
* @return the Cartesian product of the given lists. If [lists] is empty, return a list containing
* an empty list.
*/
private fun <T> cartesianProduct(lists: List<List<T>>): List<List<T>> {
if (lists.isEmpty()) return listOf(listOf())
var result: List<List<T>> = lists.first().map { listOf(it) }
for (list in lists.drop(1)) {
result = result.flatMap { xList -> list.map { yVal -> xList + listOf(yVal) } }
}
return result
}
private fun filterReports(reports: List<Report>, filter: String): List<Report> {
return try {
filterList(ENV, reports, filter)
} catch (e: IllegalArgumentException) {
throw Status.INVALID_ARGUMENT.withDescription(e.message).asRuntimeException()
}
}
companion object {
private val RESOURCE_ID_REGEX = Regex("^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$")
private val ENV: Env = buildCelEnvironment(Report.getDefaultInstance())
}
}
/** Infers the [Report.State] based on the [Metric]s. */
private fun inferReportState(metrics: Collection<Metric>): Report.State {
if (metrics.isEmpty()) {
return Report.State.RUNNING
}
val metricStates = metrics.map { it.state }
return if (metricStates.all { it == Metric.State.SUCCEEDED }) {
Report.State.SUCCEEDED
} else if (metricStates.any { it == Metric.State.FAILED }) {
Report.State.FAILED
} else {
Report.State.RUNNING
}
}
/** Gets all external metric IDs used in the [InternalReport]. */
private val InternalReport.externalMetricIds: List<String>
get() =
reportingMetricEntriesMap.flatMap { (_, reportingMetricCalculationSpec) ->
reportingMetricCalculationSpec.metricCalculationSpecReportingMetricsList.flatMap {
it.reportingMetricsList.map { reportingMetric -> reportingMetric.externalMetricId }
}
}
/** Converts a public [ListReportsRequest] to a [ListReportsPageToken]. */
private fun ListReportsRequest.toListReportsPageToken(): ListReportsPageToken {
grpcRequire(pageSize >= 0) { "Page size cannot be less than 0" }
val source = this
val parentKey: MeasurementConsumerKey =
grpcRequireNotNull(MeasurementConsumerKey.fromName(parent)) {
"Parent is either unspecified or invalid."
}
val cmmsMeasurementConsumerId = parentKey.measurementConsumerId
return if (pageToken.isNotBlank()) {
ListReportsPageToken.parseFrom(pageToken.base64UrlDecode()).copy {
grpcRequire(this.cmmsMeasurementConsumerId == cmmsMeasurementConsumerId) {
"Arguments must be kept the same when using a page token"
}
if (source.pageSize in MIN_PAGE_SIZE..MAX_PAGE_SIZE) {
pageSize = source.pageSize
}
}
} else {
listReportsPageToken {
pageSize =
when {
source.pageSize < MIN_PAGE_SIZE -> DEFAULT_PAGE_SIZE
source.pageSize > MAX_PAGE_SIZE -> MAX_PAGE_SIZE
else -> source.pageSize
}
this.cmmsMeasurementConsumerId = cmmsMeasurementConsumerId
}
}
}
/**
* Validate [Report] time fields.
*
* @throws
* * [StatusRuntimeException] with [Status.INVALID_ARGUMENT] if error found.
*/
private fun validateTime(report: Report) {
if (report.hasTimeIntervals()) {
grpcRequire(report.timeIntervals.timeIntervalsList.isNotEmpty()) {
"TimeIntervals timeIntervalsList is empty."
}
report.timeIntervals.timeIntervalsList.forEach {
grpcRequire(it.startTime.seconds > 0 || it.startTime.nanos > 0) {
"TimeInterval startTime is unspecified."
}
grpcRequire(it.endTime.seconds > 0 || it.endTime.nanos > 0) {
"TimeInterval endTime is unspecified."
}
grpcRequire(
it.endTime.seconds > it.startTime.seconds || it.endTime.nanos > it.startTime.nanos
) {
"TimeInterval endTime is not later than startTime."
}
}
} else if (report.hasReportingInterval()) {
grpcRequire(report.reportingInterval.hasReportStart()) { "report_start is missing." }
val reportStart = report.reportingInterval.reportStart
grpcRequire(
reportStart.year > 0 &&
reportStart.month > 0 &&
reportStart.day > 0 &&
(reportStart.hasUtcOffset() || reportStart.hasTimeZone())
) {
"report_start missing either year, month, day, or time_offset."
}
grpcRequire(report.reportingInterval.hasReportEnd()) { "report_end is missing." }
val reportEnd = report.reportingInterval.reportEnd
grpcRequire(reportEnd.year > 0 && reportEnd.month > 0 && reportEnd.day > 0) {
"report_end not a full date."
}
grpcRequire(
date {
year = reportStart.year
month = reportStart.month
day = reportStart.day
}
.isBefore(reportEnd)
) {
"report_end be after report_start."
}
} else {
failGrpc { "time is not set." }
}
}
private fun Date.isBefore(other: Date): Boolean {
return LocalDate.of(this.year, this.month, this.day)
.isBefore(LocalDate.of(other.year, other.month, other.day))
}
/**
* Generate a list of time intervals using the [Report.ReportingInterval], the
* [MetricCalculationSpec.MetricFrequencySpec], and the [MetricCalculationSpec.TrailingWindow].
*/
private fun generateTimeIntervals(
reportingInterval: Report.ReportingInterval,
frequencySpec: MetricCalculationSpec.MetricFrequencySpec?,
trailingWindow: MetricCalculationSpec.TrailingWindow? = null,
): List<Interval> {
val reportEndDateTime =
reportingInterval.reportStart.copy {
year = reportingInterval.reportEnd.year
month = reportingInterval.reportEnd.month
day = reportingInterval.reportEnd.day
}
return if (reportingInterval.reportStart.hasUtcOffset()) {
val offsetDateTime =
try {
reportingInterval.reportStart.toOffsetDateTime()
} catch (e: DateTimeException) {
throw Status.INVALID_ARGUMENT.withDescription(
"report_start.utc_offset is not in valid range."
)
.asRuntimeException()
}
if (frequencySpec == null) {
listOf(
interval {
startTime = offsetDateTime.toInstant().toProtoTime()
endTime = reportEndDateTime.toOffsetDateTime().toInstant().toProtoTime()
}
)
} else {
generateTimeIntervals(
offsetDateTime,
reportEndDateTime.toOffsetDateTime(),
checkNotNull(frequencySpec),
trailingWindow,
)
}
} else {
val zonedDateTime =
try {
reportingInterval.reportStart.toZonedDateTime()
} catch (e: ZoneRulesException) {
throw Status.INVALID_ARGUMENT.withDescription("report_start.time_zone.id is invalid")
.asRuntimeException()
}
if (frequencySpec == null) {
listOf(
interval {
startTime = zonedDateTime.toInstant().toProtoTime()
endTime = reportEndDateTime.toZonedDateTime().toInstant().toProtoTime()
}
)
} else {
generateTimeIntervals(
zonedDateTime,
reportEndDateTime.toZonedDateTime(),
checkNotNull(frequencySpec),
trailingWindow,
)
}
}
}
/**
* Generate a list of time intervals using [Temporal]s representing the start and end of the time
* range to create time intervals for, the [MetricCalculationSpec.MetricFrequencySpec], and the
* [MetricCalculationSpec.TrailingWindow].
*/
private fun generateTimeIntervals(
reportStartTemporal: Temporal,
reportEndTemporal: Temporal,
frequencySpec: MetricCalculationSpec.MetricFrequencySpec,
trailingWindow: MetricCalculationSpec.TrailingWindow? = null,
): List<Interval> {
val firstTimeIntervalEndTemporal: Temporal =
@Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA")
when (frequencySpec.frequencyCase) {
MetricCalculationSpec.MetricFrequencySpec.FrequencyCase.DAILY -> reportStartTemporal
MetricCalculationSpec.MetricFrequencySpec.FrequencyCase.WEEKLY ->
reportStartTemporal.with(
TemporalAdjusters.nextOrSame(
java.time.DayOfWeek.valueOf(frequencySpec.weekly.dayOfWeek.name)
)
)
MetricCalculationSpec.MetricFrequencySpec.FrequencyCase.MONTHLY -> {
val lastDayOfMonthTemporal = reportStartTemporal.with(TemporalAdjusters.lastDayOfMonth())
val lastDayOfMonth = lastDayOfMonthTemporal.get(ChronoField.DAY_OF_MONTH)
if (
frequencySpec.monthly.dayOfMonth <= lastDayOfMonth &&
reportStartTemporal.get(ChronoField.DAY_OF_MONTH) <= frequencySpec.monthly.dayOfMonth
) {
reportStartTemporal.with(
TemporalAdjusters.ofDateAdjuster { date: LocalDate ->
date.withDayOfMonth(frequencySpec.monthly.dayOfMonth)
}
)
} else if (frequencySpec.monthly.dayOfMonth > lastDayOfMonth) {
lastDayOfMonthTemporal
} else {
val nextMonthEndTemporal =
reportStartTemporal.plus(Period.ofMonths(1)).with(TemporalAdjusters.lastDayOfMonth())
nextMonthEndTemporal.with(
TemporalAdjusters.ofDateAdjuster { date: LocalDate ->
date.withDayOfMonth(
minOf(
nextMonthEndTemporal.get(ChronoField.DAY_OF_MONTH),
frequencySpec.monthly.dayOfMonth,
)
)
}
)
}
}
MetricCalculationSpec.MetricFrequencySpec.FrequencyCase.FREQUENCY_NOT_SET -> {
throw Status.INVALID_ARGUMENT.withDescription("frequency is not set").asRuntimeException()
}
}
val isWindowReportStart = trailingWindow == null
val reportStartTimestamp = reportStartTemporal.toTimestamp()
val reportEndTimestamp = reportEndTemporal.toTimestamp()
return buildList {
var nextTimeIntervalEndTemporal = firstTimeIntervalEndTemporal
// Set a cap to prevent an infinite loop in case of an error.
val maxNumTimeIntervals = ChronoUnit.DAYS.between(reportStartTemporal, reportEndTemporal) + 1
for (i in 1..maxNumTimeIntervals) {
// An interval is only created if there is a period of time between the report start and the
// potential end of the interval.
if (ChronoUnit.SECONDS.between(reportStartTemporal, nextTimeIntervalEndTemporal) > 0L) {
val nextTimeIntervalEndTimestamp = nextTimeIntervalEndTemporal.toTimestamp()
if (Timestamps.compare(nextTimeIntervalEndTimestamp, reportEndTimestamp) > 0) {
break
}
val nextTimeIntervalStartTimestamp: Timestamp =
if (isWindowReportStart) {
reportStartTimestamp
} else {
val newTimestamp =
buildReportTimeIntervalStartTimestamp(
checkNotNull(trailingWindow),
nextTimeIntervalEndTemporal,
)
// The start of any interval to be created is bounded by the report start.
if (Timestamps.compare(reportStartTimestamp, newTimestamp) >= 0) {
reportStartTimestamp
} else {
newTimestamp
}
}
add(
interval {
startTime = nextTimeIntervalStartTimestamp
endTime = nextTimeIntervalEndTimestamp
}
)
}
nextTimeIntervalEndTemporal =
@Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA")
when (frequencySpec.frequencyCase) {
MetricCalculationSpec.MetricFrequencySpec.FrequencyCase.DAILY -> {
nextTimeIntervalEndTemporal.plus(Period.ofDays(1))
}
MetricCalculationSpec.MetricFrequencySpec.FrequencyCase.WEEKLY -> {
nextTimeIntervalEndTemporal.with(
TemporalAdjusters.next(
java.time.DayOfWeek.valueOf(frequencySpec.weekly.dayOfWeek.name)
)
)
}
MetricCalculationSpec.MetricFrequencySpec.FrequencyCase.MONTHLY -> {
val nextMonthEndTemporal =
nextTimeIntervalEndTemporal
.plus(Period.ofMonths(1))
.with(TemporalAdjusters.lastDayOfMonth())
nextMonthEndTemporal.with(
TemporalAdjusters.ofDateAdjuster { date: LocalDate ->
date.withDayOfMonth(
minOf(
nextMonthEndTemporal.get(ChronoField.DAY_OF_MONTH),
frequencySpec.monthly.dayOfMonth,
)
)
}
)
}
MetricCalculationSpec.MetricFrequencySpec.FrequencyCase.FREQUENCY_NOT_SET -> {
throw Status.FAILED_PRECONDITION.withDescription("frequency is not set")
.asRuntimeException()
}
}
}
}
}
/**
* Given a [MetricCalculationSpec.TrailingWindow] and a [Temporal] that represents the end of the
* interval, create a [Timestamp] that represents the start of the interval.
*/
private fun buildReportTimeIntervalStartTimestamp(
trailingWindow: MetricCalculationSpec.TrailingWindow,
intervalEndTemporal: Temporal,
): Timestamp {
@Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") // Protobuf case fields cannot be null.
return when (trailingWindow.increment) {
MetricCalculationSpec.TrailingWindow.Increment.DAY ->
intervalEndTemporal.minus(Period.ofDays(trailingWindow.count))
MetricCalculationSpec.TrailingWindow.Increment.WEEK ->
intervalEndTemporal.minus(Period.ofWeeks(trailingWindow.count))
MetricCalculationSpec.TrailingWindow.Increment.MONTH ->
intervalEndTemporal.minus(Period.ofMonths(trailingWindow.count))
MetricCalculationSpec.TrailingWindow.Increment.INCREMENT_UNSPECIFIED,
MetricCalculationSpec.TrailingWindow.Increment.UNRECOGNIZED ->
error("trailing_window missing increment")
}.toTimestamp()
}
| 150 | null | 11 | 36 | ba2d2d8d3d4527d844e6d168273b1c2fabfd5d4e | 48,253 | cross-media-measurement | Apache License 2.0 |
compiler/testData/codegen/boxInline/callableReference/classLevel2.kt | JakeWharton | 99,388,807 | false | null | // Enable when using lambdas as extension lambdas is supported (KT-13312)
// IGNORE_BACKEND: JS
// FILE: 1.kt
package test
class A(val z: Int) {
fun calc() = z
fun test() = call(A(z), A::calc)
}
inline fun call(p: A, s: A.() -> Int): Int {
return p.s()
}
// FILE: 2.kt
import test.*
fun box() : String {
val call = A(11).test()
return if (call == 11) "OK" else "fail"
}
| 179 | null | 5640 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 397 | kotlin | Apache License 2.0 |
v2-model/src/commonMain/kotlin/com/bselzer/gw2/v2/model/guild/log/JoinedLog.kt | Woody230 | 388,820,096 | false | {"Kotlin": 750899} | package com.bselzer.gw2.v2.model.guild.log
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* The [user] has joined the guild.
*/
@Serializable
@SerialName("joined")
class JoinedLog : GuildLog() | 2 | Kotlin | 0 | 2 | 7bd43646f94d1e8de9c20dffcc2753707f6e455b | 235 | GW2Wrapper | Apache License 2.0 |
web/src/main/kotlin/no/nav/su/se/bakover/web/services/AccessCheckProxy.kt | navikt | 227,366,088 | false | {"Kotlin": 10056854, "Shell": 4388, "TSQL": 1233, "Dockerfile": 1209} | package no.nav.su.se.bakover.web.services
import arrow.core.Either
import arrow.core.getOrElse
import behandling.domain.Stønadsbehandling
import behandling.domain.fradrag.LeggTilFradragsgrunnlagRequest
import behandling.klage.domain.KlageId
import behandling.klage.domain.UprosessertKlageinstanshendelse
import behandling.revurdering.domain.bosituasjon.KunneIkkeLeggeTilBosituasjongrunnlagForRevurdering
import behandling.revurdering.domain.bosituasjon.LeggTilBosituasjonerForRevurderingCommand
import behandling.søknadsbehandling.domain.KunneIkkeOppretteSøknadsbehandling
import behandling.søknadsbehandling.domain.bosituasjon.LeggTilBosituasjonerCommand
import dokument.domain.Dokument
import dokument.domain.GenererDokumentCommand
import dokument.domain.KunneIkkeLageDokument
import dokument.domain.brev.BrevService
import dokument.domain.brev.Brevvalg
import dokument.domain.brev.HentDokumenterForIdType
import dokument.domain.journalføring.Journalpost
import dokument.domain.journalføring.KunneIkkeHenteJournalposter
import no.nav.su.se.bakover.common.UUID30
import no.nav.su.se.bakover.common.domain.PdfA
import no.nav.su.se.bakover.common.domain.Saksnummer
import no.nav.su.se.bakover.common.domain.attestering.Attestering
import no.nav.su.se.bakover.common.domain.oppgave.OppgaveId
import no.nav.su.se.bakover.common.domain.sak.Behandlingssammendrag
import no.nav.su.se.bakover.common.domain.sak.SakInfo
import no.nav.su.se.bakover.common.domain.sak.Sakstype
import no.nav.su.se.bakover.common.ident.NavIdentBruker
import no.nav.su.se.bakover.common.persistence.SessionContext
import no.nav.su.se.bakover.common.persistence.TransactionContext
import no.nav.su.se.bakover.common.person.Fnr
import no.nav.su.se.bakover.common.tid.Tidspunkt
import no.nav.su.se.bakover.common.tid.YearRange
import no.nav.su.se.bakover.common.tid.periode.Måned
import no.nav.su.se.bakover.common.tid.periode.Periode
import no.nav.su.se.bakover.domain.AlleredeGjeldendeSakForBruker
import no.nav.su.se.bakover.domain.Sak
import no.nav.su.se.bakover.domain.jobcontext.SendPåminnelseNyStønadsperiodeContext
import no.nav.su.se.bakover.domain.klage.AvsluttetKlage
import no.nav.su.se.bakover.domain.klage.AvvistKlage
import no.nav.su.se.bakover.domain.klage.IverksattAvvistKlage
import no.nav.su.se.bakover.domain.klage.Klage
import no.nav.su.se.bakover.domain.klage.KlageTilAttestering
import no.nav.su.se.bakover.domain.klage.KunneIkkeAvslutteKlage
import no.nav.su.se.bakover.domain.klage.KunneIkkeBekrefteKlagesteg
import no.nav.su.se.bakover.domain.klage.KunneIkkeIverksetteAvvistKlage
import no.nav.su.se.bakover.domain.klage.KunneIkkeLeggeTilFritekstForAvvist
import no.nav.su.se.bakover.domain.klage.KunneIkkeOppretteKlage
import no.nav.su.se.bakover.domain.klage.KunneIkkeOversendeKlage
import no.nav.su.se.bakover.domain.klage.KunneIkkeSendeKlageTilAttestering
import no.nav.su.se.bakover.domain.klage.KunneIkkeTolkeKlageinstanshendelse
import no.nav.su.se.bakover.domain.klage.KunneIkkeUnderkjenneKlage
import no.nav.su.se.bakover.domain.klage.KunneIkkeVilkårsvurdereKlage
import no.nav.su.se.bakover.domain.klage.KunneIkkeVurdereKlage
import no.nav.su.se.bakover.domain.klage.OpprettetKlage
import no.nav.su.se.bakover.domain.klage.OversendtKlage
import no.nav.su.se.bakover.domain.klage.TolketKlageinstanshendelse
import no.nav.su.se.bakover.domain.klage.VilkårsvurdertKlage
import no.nav.su.se.bakover.domain.klage.VurdertKlage
import no.nav.su.se.bakover.domain.klage.brev.KunneIkkeLageBrevutkast
import no.nav.su.se.bakover.domain.oppdrag.avstemming.Avstemming
import no.nav.su.se.bakover.domain.oppgave.OppdaterOppgaveInfo
import no.nav.su.se.bakover.domain.oppgave.OppgaveConfig
import no.nav.su.se.bakover.domain.oppgave.OppgaveService
import no.nav.su.se.bakover.domain.personhendelse.Personhendelse
import no.nav.su.se.bakover.domain.regulering.AvsluttetRegulering
import no.nav.su.se.bakover.domain.regulering.IverksattRegulering
import no.nav.su.se.bakover.domain.regulering.KunneIkkeAvslutte
import no.nav.su.se.bakover.domain.regulering.KunneIkkeOppretteRegulering
import no.nav.su.se.bakover.domain.regulering.KunneIkkeRegulereManuelt
import no.nav.su.se.bakover.domain.regulering.Regulering
import no.nav.su.se.bakover.domain.regulering.ReguleringId
import no.nav.su.se.bakover.domain.regulering.ReguleringService
import no.nav.su.se.bakover.domain.regulering.ReguleringSomKreverManuellBehandling
import no.nav.su.se.bakover.domain.regulering.Reguleringssupplement
import no.nav.su.se.bakover.domain.regulering.StartAutomatiskReguleringForInnsynCommand
import no.nav.su.se.bakover.domain.revurdering.AbstraktRevurdering
import no.nav.su.se.bakover.domain.revurdering.GjenopptaYtelseRevurdering
import no.nav.su.se.bakover.domain.revurdering.IverksattRevurdering
import no.nav.su.se.bakover.domain.revurdering.KunneIkkeAvslutteRevurdering
import no.nav.su.se.bakover.domain.revurdering.KunneIkkeLeggeTilVedtaksbrevvalg
import no.nav.su.se.bakover.domain.revurdering.OpprettetRevurdering
import no.nav.su.se.bakover.domain.revurdering.Revurdering
import no.nav.su.se.bakover.domain.revurdering.RevurderingId
import no.nav.su.se.bakover.domain.revurdering.StansAvYtelseRevurdering
import no.nav.su.se.bakover.domain.revurdering.UnderkjentRevurdering
import no.nav.su.se.bakover.domain.revurdering.attestering.KunneIkkeSendeRevurderingTilAttestering
import no.nav.su.se.bakover.domain.revurdering.attestering.SendTilAttesteringRequest
import no.nav.su.se.bakover.domain.revurdering.beregning.KunneIkkeBeregneOgSimulereRevurdering
import no.nav.su.se.bakover.domain.revurdering.brev.KunneIkkeForhåndsvarsle
import no.nav.su.se.bakover.domain.revurdering.brev.KunneIkkeLageBrevutkastForAvsluttingAvRevurdering
import no.nav.su.se.bakover.domain.revurdering.brev.KunneIkkeLageBrevutkastForRevurdering
import no.nav.su.se.bakover.domain.revurdering.brev.LeggTilBrevvalgRequest
import no.nav.su.se.bakover.domain.revurdering.gjenopptak.GjenopptaYtelseRequest
import no.nav.su.se.bakover.domain.revurdering.gjenopptak.GjenopptaYtelseService
import no.nav.su.se.bakover.domain.revurdering.gjenopptak.KunneIkkeIverksetteGjenopptakAvYtelseForRevurdering
import no.nav.su.se.bakover.domain.revurdering.gjenopptak.KunneIkkeSimulereGjenopptakAvYtelse
import no.nav.su.se.bakover.domain.revurdering.iverksett.KunneIkkeIverksetteRevurdering
import no.nav.su.se.bakover.domain.revurdering.oppdater.KunneIkkeOppdatereRevurdering
import no.nav.su.se.bakover.domain.revurdering.oppdater.OppdaterRevurderingCommand
import no.nav.su.se.bakover.domain.revurdering.opphør.AnnullerKontrollsamtaleVedOpphørService
import no.nav.su.se.bakover.domain.revurdering.opprett.KunneIkkeOppretteRevurdering
import no.nav.su.se.bakover.domain.revurdering.opprett.OpprettRevurderingCommand
import no.nav.su.se.bakover.domain.revurdering.service.RevurderingOgFeilmeldingerResponse
import no.nav.su.se.bakover.domain.revurdering.service.RevurderingService
import no.nav.su.se.bakover.domain.revurdering.stans.IverksettStansAvYtelseITransaksjonResponse
import no.nav.su.se.bakover.domain.revurdering.stans.KunneIkkeIverksetteStansYtelse
import no.nav.su.se.bakover.domain.revurdering.stans.KunneIkkeStanseYtelse
import no.nav.su.se.bakover.domain.revurdering.stans.StansAvYtelseITransaksjonResponse
import no.nav.su.se.bakover.domain.revurdering.stans.StansYtelseRequest
import no.nav.su.se.bakover.domain.revurdering.stans.StansYtelseService
import no.nav.su.se.bakover.domain.revurdering.underkjenn.KunneIkkeUnderkjenneRevurdering
import no.nav.su.se.bakover.domain.revurdering.vilkår.formue.KunneIkkeLeggeTilFormuegrunnlag
import no.nav.su.se.bakover.domain.revurdering.vilkår.fradag.KunneIkkeLeggeTilFradragsgrunnlag
import no.nav.su.se.bakover.domain.revurdering.vilkår.uføre.KunneIkkeLeggeTilUføreVilkår
import no.nav.su.se.bakover.domain.revurdering.vilkår.utenlandsopphold.KunneIkkeLeggeTilUtenlandsopphold
import no.nav.su.se.bakover.domain.sak.FantIkkeSak
import no.nav.su.se.bakover.domain.sak.FeilVedHentingAvGjeldendeVedtaksdataForPeriode
import no.nav.su.se.bakover.domain.sak.KunneIkkeHenteGjeldendeGrunnlagsdataForVedtak
import no.nav.su.se.bakover.domain.sak.KunneIkkeHenteGjeldendeVedtaksdata
import no.nav.su.se.bakover.domain.sak.KunneIkkeOppretteDokument
import no.nav.su.se.bakover.domain.sak.NySak
import no.nav.su.se.bakover.domain.sak.OpprettDokumentRequest
import no.nav.su.se.bakover.domain.sak.SakService
import no.nav.su.se.bakover.domain.sak.fnr.KunneIkkeOppdatereFødselsnummer
import no.nav.su.se.bakover.domain.sak.fnr.OppdaterFødselsnummerPåSakCommand
import no.nav.su.se.bakover.domain.søknad.LukkSøknadCommand
import no.nav.su.se.bakover.domain.søknad.Søknad
import no.nav.su.se.bakover.domain.søknad.søknadinnhold.SøknadInnhold
import no.nav.su.se.bakover.domain.søknadsbehandling.BeregnetSøknadsbehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.IverksattSøknadsbehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.LukketSøknadsbehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.SimulertSøknadsbehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.Søknadsbehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingId
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingService
import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingTilAttestering
import no.nav.su.se.bakover.domain.søknadsbehandling.UnderkjentSøknadsbehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.VilkårsvurdertSøknadsbehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.brev.utkast.BrevutkastForSøknadsbehandlingCommand
import no.nav.su.se.bakover.domain.søknadsbehandling.brev.utkast.KunneIkkeGenerereBrevutkastForSøknadsbehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.grunnlag.KunneIkkeLeggeTilSkattegrunnlag
import no.nav.su.se.bakover.domain.søknadsbehandling.grunnlag.SøknadsbehandlingSkattCommand
import no.nav.su.se.bakover.domain.søknadsbehandling.iverksett.IverksattSøknadsbehandlingResponse
import no.nav.su.se.bakover.domain.søknadsbehandling.iverksett.IverksettSøknadsbehandlingCommand
import no.nav.su.se.bakover.domain.søknadsbehandling.iverksett.IverksettSøknadsbehandlingService
import no.nav.su.se.bakover.domain.søknadsbehandling.iverksett.KunneIkkeIverksetteSøknadsbehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.iverksett.OpprettKontrollsamtaleVedNyStønadsperiodeService
import no.nav.su.se.bakover.domain.søknadsbehandling.iverksett.avslå.manglendedokumentasjon.AvslåManglendeDokumentasjonCommand
import no.nav.su.se.bakover.domain.søknadsbehandling.iverksett.avslå.manglendedokumentasjon.KunneIkkeAvslåSøknad
import no.nav.su.se.bakover.domain.søknadsbehandling.simuler.KunneIkkeSimulereBehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.tilAttestering.KunneIkkeSendeSøknadsbehandlingTilAttestering
import no.nav.su.se.bakover.domain.søknadsbehandling.underkjenn.KunneIkkeUnderkjenneSøknadsbehandling
import no.nav.su.se.bakover.domain.søknadsbehandling.vilkår.KunneIkkeLeggeTilVilkår
import no.nav.su.se.bakover.domain.vedtak.GjeldendeVedtaksdata
import no.nav.su.se.bakover.domain.vedtak.InnvilgetForMåned
import no.nav.su.se.bakover.domain.vedtak.KunneIkkeFerdigstilleVedtak
import no.nav.su.se.bakover.domain.vilkår.familiegjenforening.LeggTilFamiliegjenforeningRequest
import no.nav.su.se.bakover.domain.vilkår.fastopphold.KunneIkkeLeggeFastOppholdINorgeVilkår
import no.nav.su.se.bakover.domain.vilkår.fastopphold.LeggTilFastOppholdINorgeRequest
import no.nav.su.se.bakover.domain.vilkår.flyktning.KunneIkkeLeggeTilFlyktningVilkår
import no.nav.su.se.bakover.domain.vilkår.flyktning.LeggTilFlyktningVilkårRequest
import no.nav.su.se.bakover.domain.vilkår.formue.LeggTilFormuevilkårRequest
import no.nav.su.se.bakover.domain.vilkår.institusjonsopphold.KunneIkkeLeggeTilInstitusjonsoppholdVilkår
import no.nav.su.se.bakover.domain.vilkår.institusjonsopphold.LeggTilInstitusjonsoppholdVilkårRequest
import no.nav.su.se.bakover.domain.vilkår.lovligopphold.KunneIkkeLeggetilLovligOppholdVilkårForSøknadsbehandling
import no.nav.su.se.bakover.domain.vilkår.lovligopphold.LeggTilLovligOppholdRequest
import no.nav.su.se.bakover.domain.vilkår.opplysningsplikt.KunneIkkeLeggeTilOpplysningsplikt
import no.nav.su.se.bakover.domain.vilkår.opplysningsplikt.LeggTilOpplysningspliktRequest
import no.nav.su.se.bakover.domain.vilkår.oppmøte.KunneIkkeLeggeTilPersonligOppmøteVilkårForRevurdering
import no.nav.su.se.bakover.domain.vilkår.oppmøte.KunneIkkeLeggeTilPersonligOppmøteVilkårForSøknadsbehandling
import no.nav.su.se.bakover.domain.vilkår.oppmøte.LeggTilPersonligOppmøteVilkårRequest
import no.nav.su.se.bakover.domain.vilkår.pensjon.KunneIkkeLeggeTilPensjonsVilkår
import no.nav.su.se.bakover.domain.vilkår.pensjon.LeggTilPensjonsVilkårRequest
import no.nav.su.se.bakover.domain.vilkår.uføre.LeggTilUførevurderingerRequest
import no.nav.su.se.bakover.domain.vilkår.utenlandsopphold.LeggTilFlereUtenlandsoppholdRequest
import no.nav.su.se.bakover.hendelse.domain.HendelseId
import no.nav.su.se.bakover.kontrollsamtale.domain.Kontrollsamtale
import no.nav.su.se.bakover.kontrollsamtale.domain.KontrollsamtaleService
import no.nav.su.se.bakover.kontrollsamtale.domain.KunneIkkeHenteKontrollsamtale
import no.nav.su.se.bakover.kontrollsamtale.domain.KunneIkkeSetteNyDatoForKontrollsamtale
import no.nav.su.se.bakover.kontrollsamtale.domain.UtløptFristForKontrollsamtaleService
import no.nav.su.se.bakover.kontrollsamtale.infrastructure.setup.KontrollsamtaleSetup
import no.nav.su.se.bakover.oppgave.domain.KunneIkkeOppdatereOppgave
import no.nav.su.se.bakover.oppgave.domain.OppgaveHttpKallResponse
import no.nav.su.se.bakover.service.SendPåminnelserOmNyStønadsperiodeService
import no.nav.su.se.bakover.service.avstemming.AvstemmingFeilet
import no.nav.su.se.bakover.service.avstemming.AvstemmingService
import no.nav.su.se.bakover.service.klage.KlageService
import no.nav.su.se.bakover.service.klage.KlageVurderingerRequest
import no.nav.su.se.bakover.service.klage.KlageinstanshendelseService
import no.nav.su.se.bakover.service.klage.NyKlageRequest
import no.nav.su.se.bakover.service.klage.UnderkjennKlageRequest
import no.nav.su.se.bakover.service.klage.VurderKlagevilkårRequest
import no.nav.su.se.bakover.service.nøkkeltall.NøkkeltallService
import no.nav.su.se.bakover.service.personhendelser.DryrunResult
import no.nav.su.se.bakover.service.personhendelser.PersonhendelseService
import no.nav.su.se.bakover.service.statistikk.ResendStatistikkhendelserService
import no.nav.su.se.bakover.service.søknad.AvslåSøknadManglendeDokumentasjonService
import no.nav.su.se.bakover.service.søknad.FantIkkeSøknad
import no.nav.su.se.bakover.service.søknad.KunneIkkeLageSøknadPdf
import no.nav.su.se.bakover.service.søknad.KunneIkkeOppretteSøknad
import no.nav.su.se.bakover.service.søknad.OpprettManglendeJournalpostOgOppgaveResultat
import no.nav.su.se.bakover.service.søknad.SøknadService
import no.nav.su.se.bakover.service.søknad.lukk.LukkSøknadService
import no.nav.su.se.bakover.service.søknadsbehandling.SøknadsbehandlingServices
import no.nav.su.se.bakover.service.utbetaling.UtbetalingService
import no.nav.su.se.bakover.service.vedtak.FerdigstillVedtakService
import no.nav.su.se.bakover.vedtak.application.VedtakService
import nøkkeltall.domain.Nøkkeltall
import person.domain.KunneIkkeHentePerson
import person.domain.Person
import person.domain.PersonRepo
import person.domain.PersonService
import vedtak.domain.KunneIkkeStarteNySøknadsbehandling
import vedtak.domain.Stønadsvedtak
import vedtak.domain.Vedtak
import vedtak.domain.VedtakSomKanRevurderes
import vilkår.inntekt.domain.grunnlag.Fradragsgrunnlag
import vilkår.skatt.application.FrioppslagSkattRequest
import vilkår.skatt.application.KunneIkkeGenerereSkattePdfOgJournalføre
import vilkår.skatt.application.KunneIkkeHenteOgLagePdfAvSkattegrunnlag
import vilkår.skatt.application.SkatteService
import vilkår.skatt.domain.Skattegrunnlag
import vilkår.uføre.domain.Uføregrunnlag
import vilkår.vurderinger.domain.GrunnlagsdataOgVilkårsvurderinger
import økonomi.domain.Fagområde
import økonomi.domain.kvittering.Kvittering
import økonomi.domain.simulering.ForskjellerMellomUtbetalingOgSimulering
import økonomi.domain.simulering.SimuleringFeilet
import økonomi.domain.utbetaling.KunneIkkeKlaregjøreUtbetaling
import økonomi.domain.utbetaling.Utbetaling
import økonomi.domain.utbetaling.UtbetalingFeilet
import økonomi.domain.utbetaling.UtbetalingKlargjortForOversendelse
import java.time.LocalDate
import java.util.UUID
import kotlin.reflect.KClass
open class AccessCheckProxy(
private val personRepo: PersonRepo,
private val services: Services,
) {
fun proxy(): Services {
return Services(
avstemming = object : AvstemmingService {
override fun grensesnittsavstemming(fagområde: Fagområde): Either<AvstemmingFeilet, Avstemming.Grensesnittavstemming> {
return services.avstemming.grensesnittsavstemming(fagområde)
}
override fun grensesnittsavstemming(
fraOgMed: Tidspunkt,
tilOgMed: Tidspunkt,
fagområde: Fagområde,
): Either<AvstemmingFeilet, Avstemming.Grensesnittavstemming> {
return services.avstemming.grensesnittsavstemming(fraOgMed, tilOgMed, fagområde)
}
override fun konsistensavstemming(
løpendeFraOgMed: LocalDate,
fagområde: Fagområde,
): Either<AvstemmingFeilet, Avstemming.Konsistensavstemming.Ny> {
return services.avstemming.konsistensavstemming(løpendeFraOgMed, fagområde)
}
override fun konsistensavstemmingUtførtForOgPåDato(dato: LocalDate, fagområde: Fagområde): Boolean {
return services.avstemming.konsistensavstemmingUtførtForOgPåDato(dato, fagområde)
}
},
utbetaling = object : UtbetalingService {
override fun hentUtbetalingerForSakId(sakId: UUID) = kastKanKunKallesFraAnnenService()
override fun oppdaterMedKvittering(
utbetalingId: UUID30,
kvittering: Kvittering,
sessionContext: SessionContext?,
) = kastKanKunKallesFraAnnenService()
override fun simulerUtbetaling(
utbetalingForSimulering: Utbetaling.UtbetalingForSimulering,
): Either<SimuleringFeilet, Utbetaling.SimulertUtbetaling> {
kastKanKunKallesFraAnnenService()
}
override fun klargjørUtbetaling(
utbetaling: Utbetaling.SimulertUtbetaling,
transactionContext: TransactionContext,
): Either<KunneIkkeKlaregjøreUtbetaling, UtbetalingKlargjortForOversendelse<UtbetalingFeilet.Protokollfeil>> {
kastKanKunKallesFraAnnenService()
}
override fun hentGjeldendeUtbetaling(
sakId: UUID,
forDato: LocalDate,
) = kastKanKunKallesFraAnnenService()
},
sak = object : SakService {
override fun hentSak(sakId: UUID): Either<FantIkkeSak, Sak> {
assertHarTilgangTilSak(sakId)
return services.sak.hentSak(sakId)
}
override fun hentSak(sakId: UUID, sessionContext: SessionContext): Either<FantIkkeSak, Sak> {
return services.sak.hentSak(sakId, sessionContext)
}
override fun hentSaker(fnr: Fnr): Either<FantIkkeSak, List<Sak>> {
return services.sak.hentSaker(fnr).also {
it.map { saker -> saker.map { sak -> assertHarTilgangTilSak(sak.id) } }
}
}
override fun hentSak(fnr: Fnr, type: Sakstype): Either<FantIkkeSak, Sak> {
// Siden vi også vil kontrollere på EPS må vi hente ut saken først
// og sjekke på hele den (i stedet for å gjøre assertHarTilgangTilPerson(fnr))
return services.sak.hentSak(fnr, type).also {
it.map { sak -> assertHarTilgangTilSak(sak.id) }
}
}
override fun hentSak(saksnummer: Saksnummer): Either<FantIkkeSak, Sak> {
return services.sak.hentSak(saksnummer).also {
it.map { sak -> assertHarTilgangTilSak(sak.id) }
}
}
override fun hentSak(hendelseId: HendelseId): Either<FantIkkeSak, Sak> {
return services.sak.hentSak(hendelseId).also {
it.map { sak -> assertHarTilgangTilSak(sak.id) }
}
}
override fun hentSakForUtbetalingId(utbetalingId: UUID30) = kastKanKunKallesFraAnnenService()
override fun hentGjeldendeVedtaksdata(
sakId: UUID,
periode: Periode,
): Either<KunneIkkeHenteGjeldendeVedtaksdata, GjeldendeVedtaksdata?> {
assertHarTilgangTilSak(sakId)
return services.sak.hentGjeldendeVedtaksdata(sakId, periode)
}
override fun historiskGrunnlagForVedtaketsPeriode(
sakId: UUID,
vedtakId: UUID,
): Either<KunneIkkeHenteGjeldendeGrunnlagsdataForVedtak, GjeldendeVedtaksdata> {
assertHarTilgangTilSak(sakId)
return services.sak.historiskGrunnlagForVedtaketsPeriode(
sakId = sakId,
vedtakId = vedtakId,
)
}
override fun hentSakidOgSaksnummer(fnr: Fnr) = kastKanKunKallesFraAnnenService()
override fun hentSakInfo(sakId: UUID): Either<FantIkkeSak, SakInfo> {
kastKanKunKallesFraAnnenService()
}
override fun hentSakForRevurdering(revurderingId: RevurderingId): Sak {
assertHarTilgangTilRevurdering(revurderingId)
return services.sak.hentSakForRevurdering(revurderingId)
}
override fun hentSakForRevurdering(revurderingId: RevurderingId, sessionContext: SessionContext): Sak {
kastKanKunKallesFraAnnenService()
}
override fun hentSakForSøknadsbehandling(søknadsbehandlingId: SøknadsbehandlingId): Sak {
kastKanKunKallesFraAnnenService()
}
override fun hentSakForVedtak(vedtakId: UUID): Sak? {
kastKanKunKallesFraAnnenService()
}
override fun hentSakForSøknad(søknadId: UUID): Either<FantIkkeSak, Sak> {
assertHarTilgangTilSøknad(søknadId)
return services.sak.hentSakForSøknad(søknadId)
}
override fun opprettFritekstDokument(request: OpprettDokumentRequest): Either<KunneIkkeOppretteDokument, Dokument.UtenMetadata> {
assertHarTilgangTilSak(request.sakId)
return services.sak.opprettFritekstDokument(request)
}
override fun lagreOgSendFritekstDokument(request: OpprettDokumentRequest): Either<KunneIkkeOppretteDokument, Dokument.MedMetadata> {
assertHarTilgangTilSak(request.sakId)
return services.sak.lagreOgSendFritekstDokument(request)
}
override fun hentAlleJournalposter(sakId: UUID): Either<KunneIkkeHenteJournalposter, List<Journalpost>> {
assertHarTilgangTilSak(sakId)
return services.sak.hentAlleJournalposter(sakId)
}
override fun oppdaterFødselsnummer(command: OppdaterFødselsnummerPåSakCommand): Either<KunneIkkeOppdatereFødselsnummer, Sak> {
assertHarTilgangTilSak(command.sakId)
return services.sak.oppdaterFødselsnummer(command)
}
override fun hentSakIdSaksnummerOgFnrForAlleSaker() = kastKanKunKallesFraAnnenService()
override fun opprettSak(sak: NySak) {
assertHarTilgangTilPerson(sak.fnr)
return services.sak.opprettSak(sak)
}
override fun hentÅpneBehandlingerForAlleSaker(): List<Behandlingssammendrag> {
// vi gjør ikke noe assert fordi vi ikke sender noe sensitiv info.
// Samtidig som at dem går gjennom hentSak() når de skal saksbehandle
return services.sak.hentÅpneBehandlingerForAlleSaker()
}
override fun hentFerdigeBehandlingerForAlleSaker(): List<Behandlingssammendrag> {
return services.sak.hentFerdigeBehandlingerForAlleSaker()
}
override fun hentAlleredeGjeldendeSakForBruker(fnr: Fnr): AlleredeGjeldendeSakForBruker {
assertHarTilgangTilPerson(fnr)
return services.sak.hentAlleredeGjeldendeSakForBruker(fnr)
}
},
søknad = object : SøknadService {
override fun nySøknad(
søknadInnhold: SøknadInnhold,
identBruker: NavIdentBruker,
): Either<KunneIkkeOppretteSøknad, Pair<Saksnummer, Søknad>> {
assertHarTilgangTilPerson(søknadInnhold.personopplysninger.fnr)
return services.søknad.nySøknad(søknadInnhold, identBruker)
}
override fun persisterSøknad(
søknad: Søknad.Journalført.MedOppgave.Lukket,
sessionContext: SessionContext,
) = kastKanKunKallesFraAnnenService()
override fun hentSøknad(søknadId: UUID): Either<FantIkkeSøknad, Søknad> {
assertHarTilgangTilSøknad(søknadId)
return services.søknad.hentSøknad(søknadId)
}
override fun hentSøknadPdf(søknadId: UUID): Either<KunneIkkeLageSøknadPdf, PdfA> {
assertHarTilgangTilSøknad(søknadId)
return services.søknad.hentSøknadPdf(søknadId)
}
override fun opprettManglendeJournalpostOgOppgave(): OpprettManglendeJournalpostOgOppgaveResultat {
// Dette er et driftsendepunkt og vi vil ikke returnere kode 6/7/person-sensitive data.
return services.søknad.opprettManglendeJournalpostOgOppgave()
}
},
brev = object : BrevService {
override fun lagDokument(
command: GenererDokumentCommand,
id: UUID,
): Either<KunneIkkeLageDokument, Dokument.UtenMetadata> {
kastKanKunKallesFraAnnenService()
}
override fun lagreDokument(dokument: Dokument.MedMetadata) = kastKanKunKallesFraAnnenService()
override fun lagreDokument(
dokument: Dokument.MedMetadata,
transactionContext: TransactionContext,
) = kastKanKunKallesFraAnnenService()
override fun hentDokumenterFor(hentDokumenterForIdType: HentDokumenterForIdType): List<Dokument> {
when (hentDokumenterForIdType) {
is HentDokumenterForIdType.HentDokumenterForRevurdering -> assertHarTilgangTilRevurdering(
RevurderingId(hentDokumenterForIdType.id),
)
is HentDokumenterForIdType.HentDokumenterForSak -> assertHarTilgangTilSak(
hentDokumenterForIdType.id,
)
is HentDokumenterForIdType.HentDokumenterForSøknad -> assertHarTilgangTilSøknad(
hentDokumenterForIdType.id,
)
is HentDokumenterForIdType.HentDokumenterForVedtak -> assertHarTilgangTilVedtak(
hentDokumenterForIdType.id,
)
is HentDokumenterForIdType.HentDokumenterForKlage -> assertHarTilgangTilKlage(
KlageId(hentDokumenterForIdType.id),
)
}.let {
return services.brev.hentDokumenterFor(hentDokumenterForIdType)
}
}
},
lukkSøknad = object : LukkSøknadService {
override fun lukkSøknad(command: LukkSøknadCommand): Triple<Søknad.Journalført.MedOppgave.Lukket, LukketSøknadsbehandling?, Fnr> {
assertHarTilgangTilSøknad(command.søknadId)
return services.lukkSøknad.lukkSøknad(command)
}
override fun lagBrevutkast(
command: LukkSøknadCommand,
): Pair<Fnr, PdfA> {
assertHarTilgangTilSøknad(command.søknadId)
return services.lukkSøknad.lagBrevutkast(command)
}
},
oppgave = object : OppgaveService {
override fun opprettOppgave(config: OppgaveConfig) = kastKanKunKallesFraAnnenService()
override fun opprettOppgaveMedSystembruker(config: OppgaveConfig) = kastKanKunKallesFraAnnenService()
override fun lukkOppgave(oppgaveId: OppgaveId) = kastKanKunKallesFraAnnenService()
override fun lukkOppgaveMedSystembruker(oppgaveId: OppgaveId) = kastKanKunKallesFraAnnenService()
override fun oppdaterOppgave(
oppgaveId: OppgaveId,
oppdaterOppgaveInfo: OppdaterOppgaveInfo,
): Either<KunneIkkeOppdatereOppgave, OppgaveHttpKallResponse> = kastKanKunKallesFraAnnenService()
override fun oppdaterOppgaveMedSystembruker(
oppgaveId: OppgaveId,
oppdaterOppgaveInfo: OppdaterOppgaveInfo,
): Either<KunneIkkeOppdatereOppgave, OppgaveHttpKallResponse> = kastKanKunKallesFraAnnenService()
override fun hentOppgave(oppgaveId: OppgaveId) = kastKanKunKallesFraAnnenService()
},
person = object : PersonService {
override fun hentPerson(fnr: Fnr): Either<KunneIkkeHentePerson, Person> {
assertHarTilgangTilPerson(fnr)
return services.person.hentPerson(fnr)
}
override fun hentPersonMedSystembruker(fnr: Fnr) = kastKanKunKallesFraAnnenService()
override fun hentAktørIdMedSystembruker(fnr: Fnr) = kastKanKunKallesFraAnnenService()
override fun sjekkTilgangTilPerson(fnr: Fnr): Either<KunneIkkeHentePerson, Unit> {
return services.person.sjekkTilgangTilPerson(fnr)
}
override fun hentFnrForSak(sakId: UUID) = kastKanKunKallesFraAnnenService()
},
søknadsbehandling = SøknadsbehandlingServices(
iverksettSøknadsbehandlingService = object : IverksettSøknadsbehandlingService {
override fun iverksett(command: IverksettSøknadsbehandlingCommand): Either<KunneIkkeIverksetteSøknadsbehandling, Triple<Sak, IverksattSøknadsbehandling, Stønadsvedtak>> {
assertHarTilgangTilSøknadsbehandling(command.behandlingId)
return services.søknadsbehandling.iverksettSøknadsbehandlingService.iverksett(command)
}
override fun iverksett(iverksattSøknadsbehandlingResponse: IverksattSøknadsbehandlingResponse<*>) {
kastKanKunKallesFraAnnenService()
}
},
søknadsbehandlingService = object : SøknadsbehandlingService {
val service = services.søknadsbehandling.søknadsbehandlingService
override fun opprett(
request: SøknadsbehandlingService.OpprettRequest,
hentSak: (() -> Sak)?,
): Either<KunneIkkeOppretteSøknadsbehandling, Pair<Sak, VilkårsvurdertSøknadsbehandling.Uavklart>> {
assertHarTilgangTilSøknad(request.søknadId)
return service.opprett(request, hentSak)
}
override fun beregn(request: SøknadsbehandlingService.BeregnRequest): Either<SøknadsbehandlingService.KunneIkkeBeregne, BeregnetSøknadsbehandling> {
assertHarTilgangTilSøknadsbehandling(request.behandlingId)
return service.beregn(request)
}
override fun simuler(request: SøknadsbehandlingService.SimulerRequest): Either<KunneIkkeSimulereBehandling, SimulertSøknadsbehandling> {
assertHarTilgangTilSøknadsbehandling(request.behandlingId)
return service.simuler(request)
}
override fun sendTilAttestering(request: SøknadsbehandlingService.SendTilAttesteringRequest): Either<KunneIkkeSendeSøknadsbehandlingTilAttestering, SøknadsbehandlingTilAttestering> {
assertHarTilgangTilSøknadsbehandling(request.behandlingId)
return service.sendTilAttestering(request)
}
override fun underkjenn(request: SøknadsbehandlingService.UnderkjennRequest): Either<KunneIkkeUnderkjenneSøknadsbehandling, UnderkjentSøknadsbehandling> {
assertHarTilgangTilSøknadsbehandling(request.behandlingId)
return service.underkjenn(request)
}
override fun genererBrevutkast(
command: BrevutkastForSøknadsbehandlingCommand,
): Either<KunneIkkeGenerereBrevutkastForSøknadsbehandling, Pair<PdfA, Fnr>> {
assertHarTilgangTilSøknadsbehandling(command.søknadsbehandlingId)
return service.genererBrevutkast(command)
}
override fun hent(request: SøknadsbehandlingService.HentRequest): Either<SøknadsbehandlingService.FantIkkeBehandling, Søknadsbehandling> {
assertHarTilgangTilSøknadsbehandling(request.behandlingId)
return service.hent(request)
}
override fun oppdaterStønadsperiode(request: SøknadsbehandlingService.OppdaterStønadsperiodeRequest): Either<Sak.KunneIkkeOppdatereStønadsperiode, VilkårsvurdertSøknadsbehandling> {
assertHarTilgangTilSøknadsbehandling(request.behandlingId)
return service.oppdaterStønadsperiode(request)
}
override fun leggTilUførevilkår(
request: LeggTilUførevurderingerRequest,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<SøknadsbehandlingService.KunneIkkeLeggeTilUføreVilkår, Søknadsbehandling> {
assertHarTilgangTilSøknadsbehandling(request.behandlingId as SøknadsbehandlingId)
return service.leggTilUførevilkår(request, saksbehandler)
}
override fun leggTilLovligOpphold(
request: LeggTilLovligOppholdRequest,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeLeggetilLovligOppholdVilkårForSøknadsbehandling, Søknadsbehandling> {
assertHarTilgangTilSøknadsbehandling(request.behandlingId as SøknadsbehandlingId)
return service.leggTilLovligOpphold(request, saksbehandler)
}
override fun leggTilFamiliegjenforeningvilkår(
request: LeggTilFamiliegjenforeningRequest,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<SøknadsbehandlingService.KunneIkkeLeggeTilFamiliegjenforeningVilkårService, Søknadsbehandling> {
assertHarTilgangTilSøknadsbehandling(request.behandlingId as SøknadsbehandlingId)
return service.leggTilFamiliegjenforeningvilkår(request, saksbehandler)
}
override fun leggTilFradragsgrunnlag(
request: LeggTilFradragsgrunnlagRequest,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<SøknadsbehandlingService.KunneIkkeLeggeTilFradragsgrunnlag, Søknadsbehandling> {
assertHarTilgangTilSøknadsbehandling(request.behandlingId as SøknadsbehandlingId)
return service.leggTilFradragsgrunnlag(request, saksbehandler)
}
override fun leggTilFormuevilkår(
request: LeggTilFormuevilkårRequest,
): Either<KunneIkkeLeggeTilVilkår.KunneIkkeLeggeTilFormuevilkår, Søknadsbehandling> {
assertHarTilgangTilSøknadsbehandling(request.behandlingId as SøknadsbehandlingId)
return service.leggTilFormuevilkår(request)
}
override fun hentForSøknad(søknadId: UUID) = kastKanKunKallesFraAnnenService()
override fun persisterSøknadsbehandling(
lukketSøknadbehandling: LukketSøknadsbehandling,
tx: TransactionContext,
) = kastKanKunKallesFraAnnenService()
override fun leggTilUtenlandsopphold(
request: LeggTilFlereUtenlandsoppholdRequest,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<SøknadsbehandlingService.KunneIkkeLeggeTilUtenlandsopphold, VilkårsvurdertSøknadsbehandling> {
assertHarTilgangTilSøknadsbehandling(request.behandlingId as SøknadsbehandlingId)
return service.leggTilUtenlandsopphold(request, saksbehandler)
}
override fun leggTilOpplysningspliktVilkår(request: LeggTilOpplysningspliktRequest.Søknadsbehandling): Either<KunneIkkeLeggeTilOpplysningsplikt, VilkårsvurdertSøknadsbehandling> {
assertHarTilgangTilSøknadsbehandling(request.behandlingId)
return service.leggTilOpplysningspliktVilkår(request)
}
override fun leggTilPensjonsVilkår(
request: LeggTilPensjonsVilkårRequest,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeLeggeTilPensjonsVilkår, VilkårsvurdertSøknadsbehandling> {
assertHarTilgangTilSøknadsbehandling(request.behandlingId as SøknadsbehandlingId)
return service.leggTilPensjonsVilkår(request, saksbehandler)
}
override fun leggTilFlyktningVilkår(
request: LeggTilFlyktningVilkårRequest,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeLeggeTilFlyktningVilkår, VilkårsvurdertSøknadsbehandling> {
assertHarTilgangTilSøknadsbehandling(request.behandlingId as SøknadsbehandlingId)
return service.leggTilFlyktningVilkår(request, saksbehandler)
}
override fun leggTilFastOppholdINorgeVilkår(
request: LeggTilFastOppholdINorgeRequest,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeLeggeFastOppholdINorgeVilkår, VilkårsvurdertSøknadsbehandling> {
assertHarTilgangTilSøknadsbehandling(request.behandlingId as SøknadsbehandlingId)
return service.leggTilFastOppholdINorgeVilkår(request, saksbehandler)
}
override fun leggTilPersonligOppmøteVilkår(
request: LeggTilPersonligOppmøteVilkårRequest,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeLeggeTilPersonligOppmøteVilkårForSøknadsbehandling, VilkårsvurdertSøknadsbehandling> {
assertHarTilgangTilSøknadsbehandling(request.behandlingId as SøknadsbehandlingId)
return service.leggTilPersonligOppmøteVilkår(request, saksbehandler)
}
override fun leggTilInstitusjonsoppholdVilkår(
request: LeggTilInstitusjonsoppholdVilkårRequest,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeLeggeTilInstitusjonsoppholdVilkår, VilkårsvurdertSøknadsbehandling> {
assertHarTilgangTilSøknadsbehandling(request.behandlingId as SøknadsbehandlingId)
return service.leggTilInstitusjonsoppholdVilkår(request, saksbehandler)
}
override fun leggTilBosituasjongrunnlag(
request: LeggTilBosituasjonerCommand,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<behandling.søknadsbehandling.domain.bosituasjon.KunneIkkeLeggeTilBosituasjongrunnlag, VilkårsvurdertSøknadsbehandling> {
assertHarTilgangTilSøknadsbehandling(request.behandlingId as SøknadsbehandlingId)
return service.leggTilBosituasjongrunnlag(request, saksbehandler)
}
override fun oppdaterSkattegrunnlag(
command: SøknadsbehandlingSkattCommand,
): Either<KunneIkkeLeggeTilSkattegrunnlag, Søknadsbehandling> {
assertHarTilgangTilSøknadsbehandling(command.behandlingId)
return service.oppdaterSkattegrunnlag(command)
}
override fun lagre(søknadsbehandling: Søknadsbehandling) = kastKanKunKallesFraAnnenService()
override fun hentSisteInnvilgetSøknadsbehandlingGrunnlagForSakFiltrerVekkSøknadsbehandling(
sakId: UUID,
søknadsbehandlingId: SøknadsbehandlingId,
): Either<FeilVedHentingAvGjeldendeVedtaksdataForPeriode, Pair<Periode, GrunnlagsdataOgVilkårsvurderinger>> {
assertHarTilgangTilSak(sakId)
return service.hentSisteInnvilgetSøknadsbehandlingGrunnlagForSakFiltrerVekkSøknadsbehandling(
sakId,
søknadsbehandlingId,
)
}
},
),
ferdigstillVedtak = object : FerdigstillVedtakService {
override fun ferdigstillVedtakEtterUtbetaling(
utbetaling: Utbetaling.OversendtUtbetaling.MedKvittering,
) = kastKanKunKallesFraAnnenService()
override fun ferdigstillVedtak(vedtakId: UUID): Either<KunneIkkeFerdigstilleVedtak, VedtakSomKanRevurderes> {
assertHarTilgangTilVedtak(vedtakId)
return services.ferdigstillVedtak.ferdigstillVedtak(vedtakId)
}
override fun lukkOppgaveMedBruker(behandling: Stønadsbehandling) = kastKanKunKallesFraAnnenService()
},
revurdering = object : RevurderingService {
override fun hentRevurdering(revurderingId: RevurderingId): AbstraktRevurdering? {
assertHarTilgangTilRevurdering(revurderingId)
return services.revurdering.hentRevurdering(revurderingId)
}
override fun opprettRevurdering(
command: OpprettRevurderingCommand,
): Either<KunneIkkeOppretteRevurdering, OpprettetRevurdering> {
assertHarTilgangTilSak(command.sakId)
return services.revurdering.opprettRevurdering(command)
}
override fun oppdaterRevurdering(
command: OppdaterRevurderingCommand,
): Either<KunneIkkeOppdatereRevurdering, OpprettetRevurdering> {
assertHarTilgangTilRevurdering(command.revurderingId)
return services.revurdering.oppdaterRevurdering(command)
}
override fun beregnOgSimuler(
revurderingId: RevurderingId,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeBeregneOgSimulereRevurdering, RevurderingOgFeilmeldingerResponse> {
assertHarTilgangTilRevurdering(revurderingId)
return services.revurdering.beregnOgSimuler(
revurderingId = revurderingId,
saksbehandler = saksbehandler,
)
}
override fun lagreOgSendForhåndsvarsel(
revurderingId: RevurderingId,
utførtAv: NavIdentBruker.Saksbehandler,
fritekst: String,
): Either<KunneIkkeForhåndsvarsle, Revurdering> {
assertHarTilgangTilRevurdering(revurderingId)
return services.revurdering.lagreOgSendForhåndsvarsel(
revurderingId,
utførtAv,
fritekst,
)
}
override fun lagBrevutkastForForhåndsvarsling(
revurderingId: RevurderingId,
utførtAv: NavIdentBruker.Saksbehandler,
fritekst: String,
): Either<KunneIkkeLageBrevutkastForRevurdering, PdfA> {
assertHarTilgangTilRevurdering(revurderingId)
return services.revurdering.lagBrevutkastForForhåndsvarsling(revurderingId, utførtAv, fritekst)
}
override fun sendTilAttestering(
request: SendTilAttesteringRequest,
): Either<KunneIkkeSendeRevurderingTilAttestering, Revurdering> {
assertHarTilgangTilRevurdering(request.revurderingId)
return services.revurdering.sendTilAttestering(request)
}
override fun leggTilBrevvalg(request: LeggTilBrevvalgRequest): Either<KunneIkkeLeggeTilVedtaksbrevvalg, Revurdering> {
assertHarTilgangTilRevurdering(request.revurderingId)
return services.revurdering.leggTilBrevvalg(request)
}
override fun lagBrevutkastForRevurdering(
revurderingId: RevurderingId,
): Either<KunneIkkeLageBrevutkastForRevurdering, PdfA> {
assertHarTilgangTilRevurdering(revurderingId)
return services.revurdering.lagBrevutkastForRevurdering(revurderingId)
}
override fun iverksett(
revurderingId: RevurderingId,
attestant: NavIdentBruker.Attestant,
): Either<KunneIkkeIverksetteRevurdering, IverksattRevurdering> {
assertHarTilgangTilRevurdering(revurderingId)
return services.revurdering.iverksett(revurderingId, attestant)
}
override fun underkjenn(
revurderingId: RevurderingId,
attestering: Attestering.Underkjent,
): Either<KunneIkkeUnderkjenneRevurdering, UnderkjentRevurdering> {
assertHarTilgangTilRevurdering(revurderingId)
return services.revurdering.underkjenn(revurderingId, attestering)
}
override fun leggTilUførevilkår(
request: LeggTilUførevurderingerRequest,
): Either<KunneIkkeLeggeTilUføreVilkår, RevurderingOgFeilmeldingerResponse> {
assertHarTilgangTilRevurdering(request.behandlingId as RevurderingId)
return services.revurdering.leggTilUførevilkår(request)
}
override fun leggTilUtenlandsopphold(
request: LeggTilFlereUtenlandsoppholdRequest,
): Either<KunneIkkeLeggeTilUtenlandsopphold, RevurderingOgFeilmeldingerResponse> {
assertHarTilgangTilRevurdering(request.behandlingId as RevurderingId)
return services.revurdering.leggTilUtenlandsopphold(request)
}
override fun leggTilFradragsgrunnlag(request: LeggTilFradragsgrunnlagRequest): Either<KunneIkkeLeggeTilFradragsgrunnlag, RevurderingOgFeilmeldingerResponse> {
assertHarTilgangTilRevurdering(request.behandlingId as RevurderingId)
return services.revurdering.leggTilFradragsgrunnlag(request)
}
override fun leggTilBosituasjongrunnlag(request: LeggTilBosituasjonerForRevurderingCommand): Either<KunneIkkeLeggeTilBosituasjongrunnlagForRevurdering, RevurderingOgFeilmeldingerResponse> {
assertHarTilgangTilRevurdering(request.behandlingId as RevurderingId)
return services.revurdering.leggTilBosituasjongrunnlag(request)
}
override fun leggTilFormuegrunnlag(request: LeggTilFormuevilkårRequest): Either<KunneIkkeLeggeTilFormuegrunnlag, RevurderingOgFeilmeldingerResponse> {
assertHarTilgangTilRevurdering(request.behandlingId as RevurderingId)
return services.revurdering.leggTilFormuegrunnlag(request)
}
override fun avsluttRevurdering(
revurderingId: RevurderingId,
begrunnelse: String,
brevvalg: Brevvalg.SaksbehandlersValg?,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeAvslutteRevurdering, AbstraktRevurdering> {
assertHarTilgangTilRevurdering(revurderingId)
return services.revurdering.avsluttRevurdering(
revurderingId,
begrunnelse,
brevvalg,
saksbehandler,
)
}
override fun leggTilOpplysningspliktVilkår(request: LeggTilOpplysningspliktRequest.Revurdering): Either<KunneIkkeLeggeTilOpplysningsplikt, RevurderingOgFeilmeldingerResponse> {
assertHarTilgangTilRevurdering(request.behandlingId)
return services.revurdering.leggTilOpplysningspliktVilkår(request)
}
override fun leggTilPensjonsVilkår(request: LeggTilPensjonsVilkårRequest): Either<KunneIkkeLeggeTilPensjonsVilkår, RevurderingOgFeilmeldingerResponse> {
assertHarTilgangTilRevurdering(request.behandlingId as RevurderingId)
return services.revurdering.leggTilPensjonsVilkår(request)
}
override fun leggTilLovligOppholdVilkår(
request: LeggTilLovligOppholdRequest,
) = assertHarTilgangTilRevurdering(request.behandlingId as RevurderingId).let {
services.revurdering.leggTilLovligOppholdVilkår(request)
}
override fun leggTilFlyktningVilkår(request: LeggTilFlyktningVilkårRequest): Either<KunneIkkeLeggeTilFlyktningVilkår, RevurderingOgFeilmeldingerResponse> {
assertHarTilgangTilRevurdering(request.behandlingId as RevurderingId)
return services.revurdering.leggTilFlyktningVilkår(request)
}
override fun leggTilFastOppholdINorgeVilkår(request: LeggTilFastOppholdINorgeRequest): Either<KunneIkkeLeggeFastOppholdINorgeVilkår, RevurderingOgFeilmeldingerResponse> {
assertHarTilgangTilRevurdering(request.behandlingId as RevurderingId)
return services.revurdering.leggTilFastOppholdINorgeVilkår(request)
}
override fun leggTilPersonligOppmøteVilkår(request: LeggTilPersonligOppmøteVilkårRequest): Either<KunneIkkeLeggeTilPersonligOppmøteVilkårForRevurdering, RevurderingOgFeilmeldingerResponse> {
assertHarTilgangTilRevurdering(request.behandlingId as RevurderingId)
return services.revurdering.leggTilPersonligOppmøteVilkår(request)
}
override fun leggTilInstitusjonsoppholdVilkår(request: LeggTilInstitusjonsoppholdVilkårRequest): Either<KunneIkkeLeggeTilInstitusjonsoppholdVilkår, RevurderingOgFeilmeldingerResponse> {
assertHarTilgangTilRevurdering(request.behandlingId as RevurderingId)
return services.revurdering.leggTilInstitusjonsoppholdVilkår(request)
}
override fun defaultTransactionContext(): TransactionContext {
return services.revurdering.defaultTransactionContext()
}
override fun lagBrevutkastForAvslutting(
revurderingId: RevurderingId,
fritekst: String,
avsluttetAv: NavIdentBruker,
): Either<KunneIkkeLageBrevutkastForAvsluttingAvRevurdering, Pair<Fnr, PdfA>> {
assertHarTilgangTilRevurdering(revurderingId)
return services.revurdering.lagBrevutkastForAvslutting(revurderingId, fritekst, avsluttetAv)
}
},
stansYtelse = object : StansYtelseService {
override fun stansAvYtelse(request: StansYtelseRequest): Either<KunneIkkeStanseYtelse, StansAvYtelseRevurdering.SimulertStansAvYtelse> {
assertHarTilgangTilSak(request.sakId)
return services.stansYtelse.stansAvYtelse(request)
}
override fun stansAvYtelseITransaksjon(
request: StansYtelseRequest,
transactionContext: TransactionContext,
): StansAvYtelseITransaksjonResponse {
kastKanKunKallesFraAnnenService()
}
override fun iverksettStansAvYtelse(
revurderingId: RevurderingId,
attestant: NavIdentBruker.Attestant,
): Either<KunneIkkeIverksetteStansYtelse, StansAvYtelseRevurdering.IverksattStansAvYtelse> {
assertHarTilgangTilRevurdering(revurderingId)
return services.stansYtelse.iverksettStansAvYtelse(
revurderingId = revurderingId,
attestant = attestant,
)
}
override fun iverksettStansAvYtelseITransaksjon(
revurderingId: RevurderingId,
attestant: NavIdentBruker.Attestant,
transactionContext: TransactionContext,
): IverksettStansAvYtelseITransaksjonResponse {
kastKanKunKallesFraAnnenService()
}
},
gjenopptaYtelse = object : GjenopptaYtelseService {
override fun gjenopptaYtelse(
request: GjenopptaYtelseRequest,
): Either<KunneIkkeSimulereGjenopptakAvYtelse, Pair<GjenopptaYtelseRevurdering.SimulertGjenopptakAvYtelse, ForskjellerMellomUtbetalingOgSimulering?>> {
assertHarTilgangTilSak(request.sakId)
return services.gjenopptaYtelse.gjenopptaYtelse(request)
}
override fun iverksettGjenopptakAvYtelse(
revurderingId: RevurderingId,
attestant: NavIdentBruker.Attestant,
): Either<KunneIkkeIverksetteGjenopptakAvYtelseForRevurdering, GjenopptaYtelseRevurdering.IverksattGjenopptakAvYtelse> {
assertHarTilgangTilRevurdering(revurderingId)
return services.gjenopptaYtelse.iverksettGjenopptakAvYtelse(revurderingId, attestant)
}
},
vedtakService = object : VedtakService {
override fun lagre(vedtak: Vedtak) = kastKanKunKallesFraAnnenService()
override fun lagreITransaksjon(
vedtak: Vedtak,
tx: TransactionContext,
) = kastKanKunKallesFraAnnenService()
override fun hentForVedtakId(vedtakId: UUID) = kastKanKunKallesFraAnnenService()
override fun hentForRevurderingId(revurderingId: RevurderingId) = kastKanKunKallesFraAnnenService()
override fun hentJournalpostId(vedtakId: UUID) = kastKanKunKallesFraAnnenService()
override fun hentInnvilgetFnrForMåned(måned: Måned): InnvilgetForMåned {
return services.vedtakService.hentInnvilgetFnrForMåned(måned)
}
override fun hentForUtbetaling(utbetalingId: UUID30) = kastKanKunKallesFraAnnenService()
override fun hentForBrukerFødselsnumreOgFraOgMedMåned(
fødselsnumre: List<Fnr>,
fraOgMed: Måned,
) = kastKanKunKallesFraAnnenService()
override fun hentForEpsFødselsnumreOgFraOgMedMåned(
fnr: List<Fnr>,
fraOgMedEllerSenere: Måned,
) = kastKanKunKallesFraAnnenService()
override fun hentSøknadsbehandlingsvedtakFraOgMed(fraOgMed: LocalDate): List<UUID> =
kastKanKunKallesFraAnnenService()
override fun startNySøknadsbehandlingForAvslag(
sakId: UUID,
vedtakId: UUID,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeStarteNySøknadsbehandling, Søknadsbehandling> {
assertHarTilgangTilVedtak(vedtakId)
return services.vedtakService.startNySøknadsbehandlingForAvslag(sakId, vedtakId, saksbehandler)
}
},
nøkkeltallService = object : NøkkeltallService {
override fun hentNøkkeltall(): Nøkkeltall {
return services.nøkkeltallService.hentNøkkeltall()
}
},
avslåSøknadManglendeDokumentasjonService = object : AvslåSøknadManglendeDokumentasjonService {
override fun avslå(command: AvslåManglendeDokumentasjonCommand): Either<KunneIkkeAvslåSøknad, Sak> {
assertHarTilgangTilSøknad(command.søknadId)
return services.avslåSøknadManglendeDokumentasjonService.avslå(command)
}
override fun genererBrevForhåndsvisning(command: AvslåManglendeDokumentasjonCommand): Either<KunneIkkeAvslåSøknad, Pair<Fnr, PdfA>> {
assertHarTilgangTilSøknad(command.søknadId)
return services.avslåSøknadManglendeDokumentasjonService.genererBrevForhåndsvisning(command)
}
},
klageService = object : KlageService {
override fun opprett(request: NyKlageRequest): Either<KunneIkkeOppretteKlage, OpprettetKlage> {
assertHarTilgangTilSak(request.sakId)
return services.klageService.opprett(request)
}
override fun vilkårsvurder(request: VurderKlagevilkårRequest): Either<KunneIkkeVilkårsvurdereKlage, VilkårsvurdertKlage> {
assertHarTilgangTilKlage(request.klageId)
return services.klageService.vilkårsvurder(request)
}
override fun bekreftVilkårsvurderinger(
klageId: KlageId,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeBekrefteKlagesteg, VilkårsvurdertKlage.Bekreftet> {
assertHarTilgangTilKlage(klageId)
return services.klageService.bekreftVilkårsvurderinger(klageId, saksbehandler)
}
override fun vurder(request: KlageVurderingerRequest): Either<KunneIkkeVurdereKlage, VurdertKlage> {
assertHarTilgangTilKlage(request.klageId)
return services.klageService.vurder(request)
}
override fun bekreftVurderinger(
klageId: KlageId,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeBekrefteKlagesteg, VurdertKlage.Bekreftet> {
assertHarTilgangTilKlage(klageId)
return services.klageService.bekreftVurderinger(klageId, saksbehandler)
}
override fun leggTilAvvistFritekstTilBrev(
klageId: KlageId,
saksbehandler: NavIdentBruker.Saksbehandler,
fritekst: String,
): Either<KunneIkkeLeggeTilFritekstForAvvist, AvvistKlage> {
assertHarTilgangTilKlage(klageId)
return services.klageService.leggTilAvvistFritekstTilBrev(klageId, saksbehandler, fritekst)
}
override fun sendTilAttestering(
klageId: KlageId,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeSendeKlageTilAttestering, KlageTilAttestering> {
assertHarTilgangTilKlage(klageId)
return services.klageService.sendTilAttestering(klageId, saksbehandler)
}
override fun underkjenn(request: UnderkjennKlageRequest): Either<KunneIkkeUnderkjenneKlage, Klage> {
assertHarTilgangTilKlage(request.klageId)
return services.klageService.underkjenn(request)
}
override fun oversend(
klageId: KlageId,
attestant: NavIdentBruker.Attestant,
): Either<KunneIkkeOversendeKlage, OversendtKlage> {
assertHarTilgangTilKlage(klageId)
return services.klageService.oversend(klageId, attestant)
}
override fun iverksettAvvistKlage(
klageId: KlageId,
attestant: NavIdentBruker.Attestant,
): Either<KunneIkkeIverksetteAvvistKlage, IverksattAvvistKlage> {
assertHarTilgangTilKlage(klageId)
return services.klageService.iverksettAvvistKlage(klageId, attestant)
}
override fun brevutkast(
klageId: KlageId,
ident: NavIdentBruker,
): Either<KunneIkkeLageBrevutkast, PdfA> {
assertHarTilgangTilKlage(klageId)
return services.klageService.brevutkast(klageId, ident)
}
override fun avslutt(
klageId: KlageId,
saksbehandler: NavIdentBruker.Saksbehandler,
begrunnelse: String,
): Either<KunneIkkeAvslutteKlage, AvsluttetKlage> {
assertHarTilgangTilKlage(klageId)
return services.klageService.avslutt(
klageId = klageId,
saksbehandler = saksbehandler,
begrunnelse = begrunnelse,
)
}
},
klageinstanshendelseService = object : KlageinstanshendelseService {
override fun lagre(hendelse: UprosessertKlageinstanshendelse) = kastKanKunKallesFraAnnenService()
override fun håndterUtfallFraKlageinstans(
deserializeAndMap: (id: UUID, opprettet: Tidspunkt, json: String) -> Either<KunneIkkeTolkeKlageinstanshendelse, TolketKlageinstanshendelse>,
) = kastKanKunKallesFraAnnenService()
},
reguleringService = object : ReguleringService {
override fun startAutomatiskRegulering(
fraOgMedMåned: Måned,
supplement: Reguleringssupplement,
): List<Either<KunneIkkeOppretteRegulering, Regulering>> {
return services.reguleringService.startAutomatiskRegulering(fraOgMedMåned, supplement)
}
override fun startAutomatiskReguleringForInnsyn(
command: StartAutomatiskReguleringForInnsynCommand,
) {
return services.reguleringService.startAutomatiskReguleringForInnsyn(command)
}
override fun avslutt(
reguleringId: ReguleringId,
avsluttetAv: NavIdentBruker,
): Either<KunneIkkeAvslutte, AvsluttetRegulering> {
return services.reguleringService.avslutt(reguleringId, avsluttetAv)
}
override fun hentStatusForÅpneManuelleReguleringer(): List<ReguleringSomKreverManuellBehandling> {
return services.reguleringService.hentStatusForÅpneManuelleReguleringer()
}
override fun hentSakerMedÅpenBehandlingEllerStans(): List<Saksnummer> {
return services.reguleringService.hentSakerMedÅpenBehandlingEllerStans()
}
override fun regulerManuelt(
reguleringId: ReguleringId,
uføregrunnlag: List<Uføregrunnlag>,
fradrag: List<Fradragsgrunnlag>,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeRegulereManuelt, IverksattRegulering> {
return services.reguleringService.regulerManuelt(
reguleringId,
uføregrunnlag,
fradrag,
saksbehandler,
)
}
override fun oppdaterReguleringerMedSupplement(
fraOgMedMåned: Måned,
supplement: Reguleringssupplement,
) {
return services.reguleringService.oppdaterReguleringerMedSupplement(fraOgMedMåned, supplement)
}
},
sendPåminnelserOmNyStønadsperiodeService = object : SendPåminnelserOmNyStønadsperiodeService {
override fun sendPåminnelser(): SendPåminnelseNyStønadsperiodeContext {
kastKanKunKallesFraAnnenService()
}
},
skatteService = object : SkatteService {
override fun hentSamletSkattegrunnlag(
fnr: Fnr,
saksbehandler: NavIdentBruker.Saksbehandler,
): Skattegrunnlag {
assertHarTilgangTilPerson(fnr)
return services.skatteService.hentSamletSkattegrunnlag(fnr, saksbehandler)
}
override fun hentSamletSkattegrunnlagForÅr(
fnr: Fnr,
saksbehandler: NavIdentBruker.Saksbehandler,
yearRange: YearRange,
): Skattegrunnlag {
assertHarTilgangTilPerson(fnr)
return services.skatteService.hentSamletSkattegrunnlagForÅr(fnr, saksbehandler, yearRange)
}
override fun hentOgLagSkattePdf(request: FrioppslagSkattRequest): Either<KunneIkkeHenteOgLagePdfAvSkattegrunnlag, PdfA> {
assertHarTilgangTilPerson(request.fnr)
return services.skatteService.hentOgLagSkattePdf(request)
}
override fun hentLagOgJournalførSkattePdf(request: FrioppslagSkattRequest): Either<KunneIkkeGenerereSkattePdfOgJournalføre, PdfA> {
assertHarTilgangTilPerson(request.fnr)
return services.skatteService.hentLagOgJournalførSkattePdf(request)
}
},
kontrollsamtaleSetup = object : KontrollsamtaleSetup {
override val kontrollsamtaleService: KontrollsamtaleService = object : KontrollsamtaleService {
val service = services.kontrollsamtaleSetup.kontrollsamtaleService
override fun nyDato(
sakId: UUID,
dato: LocalDate,
): Either<KunneIkkeSetteNyDatoForKontrollsamtale, Unit> {
assertHarTilgangTilSak(sakId)
return service.nyDato(sakId, dato)
}
override fun hentNestePlanlagteKontrollsamtale(
sakId: UUID,
sessionContext: SessionContext,
): Either<KunneIkkeHenteKontrollsamtale, Kontrollsamtale> {
assertHarTilgangTilSak(sakId)
return service.hentNestePlanlagteKontrollsamtale(sakId)
}
override fun hentInnkalteKontrollsamtalerMedFristUtløptPåDato(fristPåDato: LocalDate) =
kastKanKunKallesFraAnnenService()
override fun lagre(kontrollsamtale: Kontrollsamtale, sessionContext: SessionContext) =
kastKanKunKallesFraAnnenService()
override fun hentKontrollsamtaler(sakId: UUID): List<Kontrollsamtale> {
assertHarTilgangTilSak(sakId)
return service.hentKontrollsamtaler(sakId)
}
override fun kallInn(
sakId: UUID,
kontrollsamtale: Kontrollsamtale,
) = kastKanKunKallesFraAnnenService()
override fun hentPlanlagteKontrollsamtaler(
sessionContext: SessionContext,
) = kastKanKunKallesFraAnnenService()
override fun defaultSessionContext() = service.defaultSessionContext()
override fun hentFristUtløptFørEllerPåDato(fristFørEllerPåDato: LocalDate) =
kastKanKunKallesFraAnnenService()
}
override val annullerKontrollsamtaleService: AnnullerKontrollsamtaleVedOpphørService
get() = kastKanKunKallesFraAnnenService()
override val opprettPlanlagtKontrollsamtaleService: OpprettKontrollsamtaleVedNyStønadsperiodeService
get() = kastKanKunKallesFraAnnenService()
override val utløptFristForKontrollsamtaleService: UtløptFristForKontrollsamtaleService
get() = kastKanKunKallesFraAnnenService()
},
resendStatistikkhendelserService =
object : ResendStatistikkhendelserService {
override fun resendIverksattSøknadsbehandling(fraOgMedDato: LocalDate) {
// Driftsendepunkt, ingen direkteoppslag på person og ingen returdata
services.resendStatistikkhendelserService.resendIverksattSøknadsbehandling(fraOgMedDato)
}
override fun resendStatistikkForVedtak(vedtakId: UUID, requiredType: KClass<*>?): Either<Unit, Unit> {
// Driftsendepunkt - returnerer ikke data, bare status
return services.resendStatistikkhendelserService.resendStatistikkForVedtak(vedtakId, requiredType)
}
},
personhendelseService = object : PersonhendelseService {
override fun prosesserNyHendelse(fraOgMed: Måned, personhendelse: Personhendelse.IkkeTilknyttetSak) {
// Driftsendepunkt ingen returdata
services.personhendelseService.prosesserNyHendelse(fraOgMed, personhendelse)
}
override fun opprettOppgaverForPersonhendelser() {
// Driftsendepunkt ingen returdata
services.personhendelseService.opprettOppgaverForPersonhendelser()
}
override fun dryRunPersonhendelser(
fraOgMed: Måned,
personhendelser: List<Personhendelse.IkkeTilknyttetSak>,
): DryrunResult {
// Driftsendepunkt - minimal returdata
return services.personhendelseService.dryRunPersonhendelser(fraOgMed, personhendelser)
}
},
)
}
/**
* Denne skal kun brukes fra en annen service.
* Når en service bruker en annen service, vil den ha den ikke-proxyede versjonen.
* Vi kaster derfor her for å unngå at noen bruker metoden fra feil plass (som ville ha omgått tilgangssjekk).
*/
private fun kastKanKunKallesFraAnnenService(): Nothing =
throw IllegalStateException("This should only be called from another service")
private fun assertHarTilgangTilPerson(fnr: Fnr) {
services.person.sjekkTilgangTilPerson(fnr).getOrElse {
throw Tilgangssjekkfeil(it, fnr)
}
}
private fun assertHarTilgangTilSak(sakId: UUID) {
personRepo.hentFnrForSak(sakId).forEach { assertHarTilgangTilPerson(it) }
}
private fun assertHarTilgangTilSøknad(søknadId: UUID) {
personRepo.hentFnrForSøknad(søknadId).forEach { assertHarTilgangTilPerson(it) }
}
private fun assertHarTilgangTilSøknadsbehandling(behandlingId: SøknadsbehandlingId) {
personRepo.hentFnrForBehandling(behandlingId.value).forEach { assertHarTilgangTilPerson(it) }
}
@Suppress("unused")
private fun assertHarTilgangTilUtbetaling(utbetalingId: UUID30) {
personRepo.hentFnrForUtbetaling(utbetalingId).forEach { assertHarTilgangTilPerson(it) }
}
private fun assertHarTilgangTilRevurdering(revurderingId: RevurderingId) {
personRepo.hentFnrForRevurdering(revurderingId.value).forEach { assertHarTilgangTilPerson(it) }
}
private fun assertHarTilgangTilVedtak(vedtakId: UUID) {
personRepo.hentFnrForVedtak(vedtakId).forEach { assertHarTilgangTilPerson(it) }
}
private fun assertHarTilgangTilKlage(klageId: KlageId) {
personRepo.hentFnrForKlage(klageId.value).forEach { assertHarTilgangTilPerson(it) }
}
}
class Tilgangssjekkfeil(val feil: KunneIkkeHentePerson, val fnr: Fnr) : RuntimeException("Underliggende feil: $feil")
| 9 | Kotlin | 1 | 1 | fbeb1614c40e0f6fce631d4beb1ba25e2f78ddda | 75,337 | su-se-bakover | MIT License |
teller-android/src/test/java/com/levibostian/teller/TellerTest.kt | levibostian | 132,034,933 | false | null | package com.levibostian.teller
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import com.google.common.truth.Truth.assertThat
import com.levibostian.teller.error.TellerLimitedFunctionalityException
import com.levibostian.teller.util.ConstantsUtil
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.junit.MockitoJUnitRunner
import kotlin.test.assertFailsWith
@RunWith(MockitoJUnitRunner::class)
class TellerTest {
@Mock private lateinit var sharedPreferences: SharedPreferences
@Mock private lateinit var sharedPreferencesEditor: SharedPreferences.Editor
@Mock private lateinit var application: Application
@Before
fun setup() {
`when`(sharedPreferences.edit()).thenReturn(sharedPreferencesEditor)
`when`(sharedPreferencesEditor.clear()).thenReturn(sharedPreferencesEditor)
whenever(application.getSharedPreferences(ConstantsUtil.NAMESPACE, Context.MODE_PRIVATE)).thenReturn(sharedPreferences)
}
@Test
fun clear_deletesAllData() {
Teller(sharedPreferences, false).clear()
verify(sharedPreferencesEditor).clear()
verify(sharedPreferencesEditor).commit()
}
@Test
fun init_setPropertiesCorrectly() {
Teller.getInstance(application).apply {
assertThat(sharedPreferences).isEqualTo(sharedPreferences)
assertThat(unitTesting).isFalse()
}
}
@Test
fun initTesting_setPropertiesCorrectly() {
Teller.getTestingInstance(sharedPreferences).apply {
assertThat(sharedPreferences).isEqualTo(sharedPreferences)
assertThat(unitTesting).isFalse()
}
}
@Test
fun initUnitTesting_setPropertiesCorrectly() {
Teller.getUnitTestingInstance().apply {
assertThat(sharedPreferences).isNull()
assertThat(unitTesting).isTrue()
}
}
@Test
fun clear_throwExceptionIfInitUnitTesting() {
assertFailsWith(TellerLimitedFunctionalityException::class) {
Teller.getUnitTestingInstance().clear()
}
}
} | 25 | null | 3 | 15 | 32772b08cf5d939279c4057386b2bb67d4663569 | 2,297 | Teller-Android | MIT License |
src/main/kotlin/com/kalikov/game/EnemyFactoryView.kt | kalikov | 696,277,791 | false | {"Kotlin": 435569} | package com.kalikov.game
class EnemyFactoryView(
private val imageManager: ImageManager,
private val enemyFactory: EnemyFactory,
private val x: Pixel,
private val y: Pixel
) {
fun draw(surface: ScreenSurface) {
val image = imageManager.getImage("enemy")
for (i in 0 until enemyFactory.enemiesToCreateCount) {
val col = i % 2
val row = i / 2
surface.draw(x + t(col).toPixel(), y + t(row).toPixel(), image)
}
}
} | 0 | Kotlin | 0 | 0 | c531a38c9ef654f06f7beab648dd98285f25d58d | 495 | battle-city | MIT License |
app/src/main/java/com/comunidadedevspace/taskbeats/presentation/TaskListFavoriteFragment.kt | RenanPdeOliveira | 615,246,251 | false | {"Kotlin": 64621} | package com.comunidadedevspace.taskbeats.presentation
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.comunidadedevspace.taskbeats.R
import com.comunidadedevspace.taskbeats.data.local.entity.TaskItem
import com.comunidadedevspace.taskbeats.databinding.FragmentTaskListFavoriteBinding
import com.comunidadedevspace.taskbeats.presentation.adapter.TaskListAdapter
import com.comunidadedevspace.taskbeats.presentation.events.TaskListEvents
import com.comunidadedevspace.taskbeats.presentation.viewmodel.ProvideViewModelFactory
import com.comunidadedevspace.taskbeats.presentation.viewmodel.TaskListViewModel
import com.comunidadedevspace.taskbeats.util.UiEvent
import kotlinx.coroutines.launch
class TaskListFavoriteFragment : Fragment() {
private var _binding: FragmentTaskListFavoriteBinding? = null
private val binding get() = _binding!!
private val viewModel by viewModels<TaskListViewModel> {
ProvideViewModelFactory(requireActivity().application)
}
private var adapter = TaskListAdapter(::openListItemClicked, ::changeIsFavorite)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentTaskListFavoriteBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.recyclerViewTaskFavorite.adapter = adapter
viewLifecycleOwner.lifecycleScope.launch {
viewModel.uiEvent.collect { event ->
when (event) {
is UiEvent.Navigate -> {
when (event.route) {
"detail_screen" -> adapter =
TaskListAdapter(::openListItemClicked, ::changeIsFavorite)
}
}
else -> Unit
}
}
}
}
override fun onStart() {
super.onStart()
getFavoriteList()
}
private fun getFavoriteList() {
viewModel.taskList.observe(viewLifecycleOwner) { list ->
val newList = list.filter { it.isFavorite }
binding.linearLayoutEmpty.isVisible = newList.isEmpty()
adapter.submitList(newList)
}
}
private fun openListItemClicked(task: TaskItem) {
val intent = TaskListDetailActivity.start(requireContext(), task)
requireActivity().startActivity(intent)
}
private fun changeIsFavorite(task: TaskItem) {
viewModel.onEvent(
TaskListEvents.OnFavoriteButtonClick(
TaskItem(
task.id,
task.title,
task.desc,
!task.isFavorite,
if (task.isFavorite) R.drawable.baseline_outline_grade_24 else R.drawable.baseline_grade_24
)
)
)
}
override fun onDestroy() {
super.onDestroy()
_binding = null
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*/
@JvmStatic
fun newInstance() = TaskListFavoriteFragment()
}
} | 0 | Kotlin | 0 | 0 | d9b08f6a291622d6c5f208f10238f01988db14dc | 3,586 | TaskBeats | The Unlicense |
core/src/main/kotlin/materialui/components/slider/enums/SliderValueLabelDisplay.kt | subroh0508 | 167,797,152 | false | null | package materialui.components.slider.enums
@Suppress("EnumEntryName")
enum class SliderValueLabelDisplay {
on, auto, off
}
| 14 | Kotlin | 27 | 81 | a959a951ace3b9bd49dc5405bea150d4d53cf162 | 128 | kotlin-material-ui | MIT License |
data/src/main/java/com/tamimattafi/pizza/android/data/local/IPizzaLocalDataSource.kt | tamimattafi | 428,131,583 | false | {"Kotlin": 96172} | package com.tamimattafi.pizza.android.data.local
import com.tamimattafi.pizza.domain.model.Pizza
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.core.Flowable
interface IPizzaLocalDataSource {
fun insert(pizza: Pizza): Completable
fun insertAll(pizzaList: List<Pizza>): Completable
fun get(id: Int): Flowable<Pizza>
fun getAll(): Flowable<List<Pizza>>
fun search(query: String): Flowable<List<Pizza>>
} | 0 | Kotlin | 1 | 0 | b0732e71ca1aeb4b6934fa2ec512c61620adc5b9 | 449 | i-pizza-android | Apache License 2.0 |
src/main/kotlin/com/swisschain/matching/engine/order/process/context/StopLimitOrderContext.kt | swisschain | 255,464,363 | false | {"Gradle": 2, "Text": 2, "Ignore List": 1, "Markdown": 1, "Kotlin": 578, "XML": 2, "Shell": 2, "Batchfile": 1, "Java": 3, "Protocol Buffer": 14, "Java Properties": 1, "INI": 2, "YAML": 2} | package com.swisschain.matching.engine.order.process.context
import com.swisschain.matching.engine.daos.Asset
import com.swisschain.matching.engine.daos.LimitOrder
import com.swisschain.matching.engine.order.transaction.ExecutionContext
import com.swisschain.matching.engine.services.validators.impl.OrderValidationResult
import com.swisschain.matching.engine.utils.NumberUtils
import java.math.BigDecimal
class StopLimitOrderContext(val order: LimitOrder,
val executionContext: ExecutionContext) {
val limitAsset: Asset? = if (order.isBuySide()) {
executionContext.assetPairsById[order.assetPairId]?.let { executionContext.assetsById[it.quotingAssetId] }
} else {
executionContext.assetPairsById[order.assetPairId]?.let { executionContext.assetsById[it.baseAssetId] }
}
val limitVolume: BigDecimal? = calculateLimitVolume()
var validationResult: OrderValidationResult? = null
var immediateExecutionPrice: BigDecimal? = null
private fun calculateLimitVolume(): BigDecimal? {
return if (order.isBuySide()) {
val limitPrice = order.upperPrice ?: order.lowerPrice
if (limitPrice != null)
NumberUtils.setScaleRoundUp(order.volume * limitPrice, limitAsset!!.accuracy)
else null
} else order.getAbsVolume()
}
} | 1 | null | 1 | 1 | 5ef23544e9c5b21864ec1de7ad0f3e254044bbaa | 1,351 | Exchange.MatchingEngine | Apache License 2.0 |
telegram-bot/src/jvmTest/kotlin/eu/vendeli/api/chat/ChatInviteLinkMethodsTest.kt | vendelieu | 496,567,172 | false | {"Kotlin": 925708, "CSS": 356} | package eu.vendeli.api.chat
import BotTestContext
import ChatTestingOnlyCondition
import eu.vendeli.tgbot.api.chat.createChatInviteLink
import eu.vendeli.tgbot.api.chat.editChatInviteLink
import eu.vendeli.tgbot.api.chat.exportChatInviteLink
import eu.vendeli.tgbot.api.chat.revokeChatInviteLink
import io.kotest.core.annotation.EnabledIf
import io.kotest.matchers.booleans.shouldBeFalse
import io.kotest.matchers.booleans.shouldBeTrue
import io.kotest.matchers.shouldBe
import io.kotest.matchers.string.shouldNotBeBlank
import java.time.temporal.ChronoUnit
@EnabledIf(ChatTestingOnlyCondition::class)
class ChatInviteLinkMethodsTest : BotTestContext() {
@Test
suspend fun `create chat invite link method test`() {
val expireUnix = CUR_INSTANT.plusSeconds(120).truncatedTo(ChronoUnit.SECONDS)
val result = createChatInviteLink().options {
name = "test"
createsJoinRequest = true
expireDate = expireUnix
}.sendReturning(CHAT_ID, bot).shouldSuccess()
with(result) {
creator.id shouldBe BOT_ID
isPrimary.shouldBeFalse()
isRevoked.shouldBeFalse()
name shouldBe "test"
createsJoinRequest.shouldBeTrue()
expireDate shouldBe expireUnix
}
}
@Test
suspend fun `edit chat invite link method test`() {
val inviteLink = createChatInviteLink().options {
name = "test"
createsJoinRequest = true
}.sendReturning(CHAT_ID, bot).shouldSuccess()
val expireUnix = CUR_INSTANT.plusMillis(1000).truncatedTo(ChronoUnit.SECONDS)
val result = editChatInviteLink(inviteLink.inviteLink).options {
name = "test2"
expireDate = expireUnix
createsJoinRequest = false
}.sendReturning(CHAT_ID, bot).shouldSuccess()
with(result) {
creator.id shouldBe BOT_ID
isPrimary.shouldBeFalse()
isRevoked.shouldBeFalse()
name shouldBe "test2"
createsJoinRequest.shouldBeFalse()
expireDate shouldBe expireUnix
}
}
@Test
suspend fun `export chat invite link method test`() {
val result = exportChatInviteLink().sendReturning(CHAT_ID, bot).shouldSuccess()
result.shouldNotBeBlank()
}
@Test
suspend fun `revoke chat invite link method test`() {
val inviteLink = createChatInviteLink().options {
name = "test"
createsJoinRequest = true
}.sendReturning(CHAT_ID, bot).shouldSuccess()
val result = revokeChatInviteLink(inviteLink.inviteLink).sendReturning(CHAT_ID, bot).shouldSuccess()
with(result) {
creator.id shouldBe BOT_ID
isPrimary.shouldBeFalse()
isRevoked.shouldBeTrue()
name shouldBe "test"
createsJoinRequest.shouldBeTrue()
}
}
}
| 6 | Kotlin | 6 | 165 | c1ddf4a42c577410af31249dc650858320668263 | 2,921 | telegram-bot | Apache License 2.0 |
komf-core/src/commonMain/kotlin/snd/komf/providers/mal/MalMetadataProvider.kt | Snd-R | 463,859,568 | false | {"Kotlin": 694478, "Dockerfile": 582} | package snd.komf.providers.mal
import io.github.oshai.kotlinlogging.KotlinLogging
import snd.komf.model.Image
import snd.komf.providers.MetadataProvider
import snd.komf.util.NameSimilarityMatcher
import snd.komf.providers.CoreProviders.MAL
import snd.komf.model.MatchQuery
import snd.komf.model.MediaType
import snd.komf.model.ProviderBookId
import snd.komf.model.ProviderBookMetadata
import snd.komf.model.ProviderSeriesId
import snd.komf.model.ProviderSeriesMetadata
import snd.komf.model.SeriesSearchResult
import snd.komf.providers.mal.model.MalMediaType.DOUJINSHI
import snd.komf.providers.mal.model.MalMediaType.LIGHT_NOVEL
import snd.komf.providers.mal.model.MalMediaType.MANGA
import snd.komf.providers.mal.model.MalMediaType.MANHUA
import snd.komf.providers.mal.model.MalMediaType.MANHWA
import snd.komf.providers.mal.model.MalMediaType.NOVEL
import snd.komf.providers.mal.model.MalMediaType.OEL
import snd.komf.providers.mal.model.MalMediaType.ONE_SHOT
private val logger = KotlinLogging.logger {}
private val mangaMediaTypes = listOf(MANGA, ONE_SHOT, DOUJINSHI, MANHWA, MANHUA, OEL)
private val novelMediaTypes = listOf(NOVEL, LIGHT_NOVEL)
class MalMetadataProvider(
private val malClient: MalClient,
private val metadataMapper: MalMetadataMapper,
private val nameMatcher: NameSimilarityMatcher,
private val fetchSeriesCovers: Boolean,
mediaType: MediaType,
) : MetadataProvider {
private val seriesTypes = when (mediaType) {
MediaType.MANGA -> mangaMediaTypes
MediaType.NOVEL -> novelMediaTypes
MediaType.COMIC -> throw IllegalStateException("Comics media type is not supported")
}
override fun providerName() = MAL
override suspend fun getSeriesMetadata(seriesId: ProviderSeriesId): ProviderSeriesMetadata {
val series = malClient.getSeries(seriesId.value.toInt())
val thumbnail = if (fetchSeriesCovers) malClient.getThumbnail(series) else null
return metadataMapper.toSeriesMetadata(series, thumbnail)
}
override suspend fun getSeriesCover(seriesId: ProviderSeriesId): Image? {
val series = malClient.getSeries(seriesId.value.toInt())
return malClient.getThumbnail(series)
}
override suspend fun getBookMetadata(seriesId: ProviderSeriesId, bookId: ProviderBookId): ProviderBookMetadata {
throw UnsupportedOperationException()
}
override suspend fun searchSeries(seriesName: String, limit: Int): Collection<SeriesSearchResult> {
if (seriesName.length < 3) {
logger.warn { "$seriesName is less than 3 characters. Can't perform a search" }
return emptyList()
}
return malClient.searchSeries(seriesName.take(64)).data
.filter { seriesTypes.contains(it.node.mediaType) }
.take(limit)
.map { metadataMapper.toSeriesSearchResult(it.node) }
}
override suspend fun matchSeriesMetadata(matchQuery: MatchQuery): ProviderSeriesMetadata? {
val seriesName = matchQuery.seriesName
if (seriesName.length < 3) {
logger.warn { "$seriesName is less than 3 characters. Can't perform a search" }
return null
}
val searchResults = malClient.searchSeries(seriesName.take(64))
val match = searchResults.data
.map { it.node }
.filter { seriesTypes.contains(it.mediaType) }
.firstOrNull {
val titles = listOfNotNull(
it.title,
it.alternativeTitles.en,
it.alternativeTitles.ja
) + it.alternativeTitles.synonyms
nameMatcher.matches(seriesName, titles)
}
return match?.let {
val series = malClient.getSeries(it.id)
val thumbnail = if (fetchSeriesCovers) malClient.getThumbnail(series) else null
metadataMapper.toSeriesMetadata(series, thumbnail)
}
}
}
| 30 | Kotlin | 19 | 309 | 4c260a3dcd326a5e1d74ac9662eec8124ab7e461 | 3,951 | komf | MIT License |
app/src/main/java/co/rahulchowdhury/addtothings/HomeActivity.kt | rahulchowdhury | 224,971,234 | false | null | package com.sanardev.instagramapijavatest
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class HomeActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
}
} | 2 | null | 6 | 6 | e9ec5c32c8401189932d9291734a1427fe58b1f7 | 314 | add-to-things | Apache License 2.0 |
browser-kotlin/src/jsMain/kotlin/web/gpu/GPUShaderModuleDescriptor.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6272741} | // Automatically generated - do not modify!
package web.gpu
import kotlinx.js.JsPlainObject
@JsPlainObject
external interface GPUShaderModuleDescriptor :
GPUObjectDescriptorBase {
var code: String
var sourceMap: Any?
}
| 0 | Kotlin | 8 | 36 | 95b065622a9445caf058ad2581f4c91f9e2b0d91 | 234 | types-kotlin | Apache License 2.0 |
browser-kotlin/src/jsMain/kotlin/web/gpu/GPUShaderModuleDescriptor.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6272741} | // Automatically generated - do not modify!
package web.gpu
import kotlinx.js.JsPlainObject
@JsPlainObject
external interface GPUShaderModuleDescriptor :
GPUObjectDescriptorBase {
var code: String
var sourceMap: Any?
}
| 0 | Kotlin | 8 | 36 | 95b065622a9445caf058ad2581f4c91f9e2b0d91 | 234 | types-kotlin | Apache License 2.0 |
app/src/main/java/com/transcodium/wirepurse/DialogActivity.kt | razzbee | 195,604,153 | false | null | package com.transcodium.wirepurse
import android.os.Bundle
import android.os.PersistableBundle
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlin.coroutines.CoroutineContext
open class DialogActivity : AppCompatActivity(), CoroutineScope {
var job: Job? = null
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main
override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
super.onCreate(savedInstanceState, persistentState)
val winSize = getWindowSize()
val winWith = winSize.widthPixels * 0.95
val winHeight = winSize.heightPixels * 0.80
window.setLayout(
winWith.toInt(),
winHeight.toInt()
)
job = Job()
}
} | 0 | Kotlin | 0 | 0 | d55181e5afbdb7a7afeb88da61d324f1cc4ab373 | 935 | wirepurse-android | Apache License 2.0 |
features/anime/src/main/java/com/doskoch/template/anime/screens/favorite/FavoriteAnimeScreen.kt | VitaliyDoskoch | 263,280,184 | false | {"Kotlin": 233695, "Shell": 270} | package com.doskoch.template.anime.screens.favorite
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.paging.ExperimentalPagingApi
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemsIndexed
import com.doskoch.template.anime.R
import com.doskoch.template.anime.common.ui.AnimeItem
import com.doskoch.template.anime.di.Module
import com.doskoch.template.core.components.theme.Dimensions
import com.doskoch.template.core.ui.modifier.simpleVerticalScrollbar
import com.doskoch.template.core.ui.paging.PagingScaffold
import com.google.accompanist.systemuicontroller.rememberSystemUiController
@OptIn(ExperimentalPagingApi::class)
@Composable
fun FavoriteAnimeScreen(vm: FavoriteAnimeViewModel = viewModel { Module.favoriteAnimeViewModel() }) {
val state = vm.state.collectAsState().value
Scaffold(
topBar = {
TopBar(state = state)
}
) { paddingValues ->
val items = state.pagingFlow.collectAsLazyPagingItems()
PagingScaffold(
itemCount = items.itemCount,
loadState = items.loadState,
modifier = Modifier
.fillMaxSize()
) {
val lazyListState = rememberLazyListState()
LazyColumn(
modifier = Modifier
.padding(paddingValues)
.navigationBarsPadding()
.fillMaxSize()
.simpleVerticalScrollbar(lazyListState),
state = lazyListState
) {
itemsIndexed(
items = items,
key = { _, item -> item.id }
) { position, item ->
item?.let {
AnimeItem(
item = item,
position = position,
onFavoriteClick = { state.actions.onItemFavoriteClick(item) },
modifier = Modifier
.clickable { state.actions.onItemClick(item) }
)
}
}
}
}
}
}
@Composable
private fun TopBar(state: FavoriteAnimeState) {
val systemUiController = rememberSystemUiController()
val statusBarColor = MaterialTheme.colors.primary
SideEffect {
systemUiController.setStatusBarColor(statusBarColor)
}
TopAppBar(
modifier = Modifier
.statusBarsPadding(),
title = {
Text(
text = stringResource(R.string.favorite_anime_screen_toolbar_title),
style = MaterialTheme.typography.subtitle1,
color = MaterialTheme.colors.onPrimary
)
},
navigationIcon = {
IconButton(
onClick = state.actions.onBackClick
) {
Icon(
painter = painterResource(R.drawable.ic_arrow_back),
contentDescription = stringResource(R.string.common_desc_navigate_back),
modifier = Modifier
.size(Dimensions.icon_24)
)
}
}
)
}
| 0 | Kotlin | 0 | 2 | 477c3dbb8ab046b3ab9204912535516c8487e254 | 4,171 | Template | MIT License |
apollo-gradle-plugin/src/test/kotlin/com/apollographql/apollo3/gradle/test/SourceDirectorySetTests.kt | apollographql | 69,469,299 | false | null | package com.apollographql.apollo3.gradle.test
import com.apollographql.apollo3.gradle.util.TestUtils
import com.apollographql.apollo3.gradle.util.generatedChild
import org.gradle.testkit.runner.TaskOutcome
import org.junit.Assert
import org.junit.Test
import java.io.File
class SourceDirectorySetTests {
}
| 129 | Kotlin | 559 | 3,046 | 7a1a291d5edc7d66d088c06b47975ef8a79fc439 | 310 | apollo-android | MIT License |
matrix/common/src/testFixtures/kotlin/fake/FakeCredentialsStore.kt | ShadowJonathan | 471,471,233 | true | {"Kotlin": 586327, "Java": 13756, "Shell": 763, "Prolog": 113} | package fake
import app.dapk.st.matrix.common.CredentialsStore
import io.mockk.coEvery
import io.mockk.mockk
import test.delegateReturn
class FakeCredentialsStore : CredentialsStore by mockk() {
fun givenCredentials() = coEvery { credentials() }.delegateReturn()
} | 0 | null | 0 | 0 | 2ab2253e7a1335f8c25b5e69be0dc1ec9c254958 | 270 | small-talk | Apache License 2.0 |
core/src/main/java/com/gordonfromblumberg/calculator/Texts.kt | Gordon-from-Blumberg | 673,508,452 | false | null | package com.gordonfromblumberg.calculator
object Texts {
const val addButton = "Добавить"
const val calculateButton = "Посчитать"
const val nameCol = "Название"
const val proteinsCol = "Б/100г"
const val fatsCol = "Ж/100г"
const val carbohydratesCol = "У/100г"
const val kcalCol = "Ккал/100г"
const val massCol = "Масса,г"
const val total = "Итого"
const val addIngredientTitle = "Добавить ингредиент"
const val calculateTitle = "Посчитать"
} | 0 | Kotlin | 0 | 0 | 30a40c8c6c057c2e109037240e21c3e8a4170e56 | 489 | calculator | MIT License |
script-utils-common/src/main/kotlin/com/github/pambrose/common/script/AbstractExprEvaluatorPool.kt | pambrose | 212,692,041 | false | {"Kotlin": 179543, "Java": 1287, "Makefile": 548} | /*
* Copyright © 2023 Paul Ambrose ([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.github.pambrose.common.script
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.runBlocking
abstract class AbstractExprEvaluatorPool<T : AbstractExprEvaluator>(
val size: Int,
) {
protected val channel = Channel<AbstractExprEvaluator>(size)
private suspend fun borrow() = channel.receive()
val isEmpty get() = channel.isEmpty
private suspend fun recycle(scriptObject: AbstractExprEvaluator) = channel.send(scriptObject)
fun <R> blockingEval(expr: String): R =
runBlocking {
eval(expr)
}
suspend fun <R> eval(expr: String): R =
borrow()
.let { engine ->
try {
@Suppress("UNCHECKED_CAST")
engine.eval(expr) as R
} finally {
recycle(engine)
}
}
}
| 0 | Kotlin | 0 | 0 | c6b6b7439057fd272ea68f591ae1bfa08ad4f490 | 1,403 | common-utils | Apache License 2.0 |
app/src/main/java/dev/abhaycloud/fdtracker/domain/model/biometrics/BiometricCheckResult.kt | Abhay-cloud | 816,359,684 | false | {"Kotlin": 164703} | package dev.abhaycloud.fdtracker.domain.model.biometrics
sealed interface BiometricCheckResult {
data object Available : BiometricCheckResult
data object NoHardware : BiometricCheckResult
data object HardwareUnavailable : BiometricCheckResult
data object NoneEnrolled : BiometricCheckResult
} | 2 | Kotlin | 4 | 32 | a8ab2db4b600c29ecfffe45c263305bf939a5142 | 309 | Fixed-Deposit-Tracker | MIT License |
limp/src/commonMain/kotlin/dev/bitspittle/limp/methods/collection/MapMethod.kt | bitspittle | 583,402,131 | false | null | package dev.bitspittle.limp.methods.collection
import dev.bitspittle.limp.Environment
import dev.bitspittle.limp.Evaluator
import dev.bitspittle.limp.Method
import dev.bitspittle.limp.types.Expr
/**
* map (List) ('Expr) -> List
*
* Take a list and an expression and return a new list with that expression applied on each element.
*/
class MapMethod : Method("map", 2) {
override suspend fun invoke(
env: Environment,
eval: Evaluator,
params: List<Any>,
options: Map<String, Any>,
rest: List<Any>
): Any {
val list = env.expectConvert<List<Any>>(params[0])
val transform = env.expectConvert<Expr>(params[1])
return list.map { item ->
env.scoped { // Don't let values defined during the lambda escape
env.expectConvert<Any>(eval.extend(mapOf("\$it" to item)).evaluate(env, transform))
}
}
}
} | 1 | Kotlin | 0 | 0 | 551cbe3fe06f9bdb630eb81d2f6a00b387b62d6b | 921 | limp | MIT License |
buildSrc/src/main/kotlin/karakum/browser/TagName.kt | karakum-team | 393,199,102 | false | null | package karakum.browser
internal const val HTML_TAG_NAME = "HtmlTagName"
internal const val SVG_TAG_NAME = "SvgTagName"
internal const val MATHML_TAG_NAME = "MathMLTagName"
internal const val SVG_NAMESPACE = "http://www.w3.org/2000/svg"
internal const val MATHML_NAMESPACE = "http://www.w3.org/1998/Math/MathML"
private fun tagNameBody(
tagType: String,
elementType: String,
): String = """
sealed external interface $tagType<T : $elementType>
inline fun <T : $elementType> $tagType(
tagName: String,
): $tagType<T> =
tagName.unsafeCast<$tagType<T>>()
""".trimIndent()
internal fun tagNames(
source: String,
): Sequence<ConversionResult> {
return sequenceOf(
tagDictionary("HTML", source, HTML_TAG_NAME),
tagDictionary("SVG", source, SVG_TAG_NAME, SVG_NAMESPACE),
tagDictionary("MathML", source, MATHML_TAG_NAME, MATHML_NAMESPACE),
ConversionResult(
name = HTML_TAG_NAME,
body = tagNameBody(HTML_TAG_NAME, "HTMLElement"),
pkg = "web.html",
),
ConversionResult(
name = SVG_TAG_NAME,
body = tagNameBody(SVG_TAG_NAME, "SVGElement"),
pkg = "web.svg",
),
ConversionResult(
name = MATHML_TAG_NAME,
body = tagNameBody(MATHML_TAG_NAME, "MathMLElement"),
pkg = "web.mathml",
),
)
}
private fun tagDictionary(
name: String,
source: String,
groupTagName: String,
namespace: String? = null,
): ConversionResult {
val elementType = name + "Element"
val members = source
.substringAfter("interface ${elementType}TagNameMap {\n")
.substringBefore("\n}")
.trimIndent()
.splitToSequence("\n")
.joinToString("\n\n") { line ->
val (tagName, tagType) = line
.removePrefix("\"")
.removeSuffix(";")
.split("\": ")
val propertyName = when (tagName) {
"object",
"var",
-> "`$tagName`"
else -> tagName.replace("-x", "X")
}
"""
inline val $propertyName: $groupTagName<$tagType>
get() = $groupTagName("$tagName")
""".trimIndent()
}
val namespaceBody = if (namespace != null) {
"""
@JsValue("$namespace")
external object ${name.uppercase()}_NAMESPACE: ElementNamespace
""".trimIndent()
} else null
val body = sequenceOf(
namespaceBody,
"object $name {\n$members\n}",
).filterNotNull()
.joinToString("\n\n")
return ConversionResult(
name = name,
body = body,
pkg = "web.${name.lowercase()}",
)
}
| 0 | null | 8 | 36 | 95b065622a9445caf058ad2581f4c91f9e2b0d91 | 2,768 | types-kotlin | Apache License 2.0 |
codebase/android/feature/transactions/src/main/java/com/makeappssimple/abhimanyu/financemanager/android/feature/transactions/edit_transaction/snackbar/EditTransactionScreenSnackbarType.kt | Abhimanyu14 | 429,663,688 | false | {"Kotlin": 1876553} | package com.makeappssimple.abhimanyu.financemanager.android.feature.transactions.edit_transaction.snackbar
import com.makeappssimple.abhimanyu.financemanager.android.core.ui.base.ScreenSnackbarType
internal sealed class EditTransactionScreenSnackbarType : ScreenSnackbarType {
data object EditTransactionFailed : EditTransactionScreenSnackbarType()
data object EditTransactionSuccessful : EditTransactionScreenSnackbarType()
data object None : EditTransactionScreenSnackbarType()
}
| 11 | Kotlin | 0 | 3 | 7e080a68bc038bd64d2d406b75a49e8f1ea2a791 | 496 | finance-manager | Apache License 2.0 |
compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/input/pointer/PointerInputEventProcessorTest.kt | RikkaW | 389,105,112 | false | null | /*
* Copyright 2020 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.
*/
@file:Suppress("DEPRECATION")
package androidx.compose.ui.input.pointer
import android.view.InputDevice
import android.view.KeyEvent as AndroidKeyEvent
import android.view.MotionEvent
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.autofill.Autofill
import androidx.compose.ui.autofill.AutofillTree
import androidx.compose.ui.draganddrop.DragAndDropManager
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.focus.FocusOwner
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.GraphicsContext
import androidx.compose.ui.graphics.Matrix
import androidx.compose.ui.graphics.layer.GraphicsLayer
import androidx.compose.ui.hapticfeedback.HapticFeedback
import androidx.compose.ui.input.InputModeManager
import androidx.compose.ui.input.key.KeyEvent
import androidx.compose.ui.layout.Measurable
import androidx.compose.ui.layout.MeasureResult
import androidx.compose.ui.layout.MeasureScope
import androidx.compose.ui.layout.layout
import androidx.compose.ui.modifier.ModifierLocalManager
import androidx.compose.ui.node.InternalCoreApi
import androidx.compose.ui.node.LayoutNode
import androidx.compose.ui.node.LayoutNodeDrawScope
import androidx.compose.ui.node.MeasureAndLayoutDelegate
import androidx.compose.ui.node.OwnedLayer
import androidx.compose.ui.node.Owner
import androidx.compose.ui.node.OwnerSnapshotObserver
import androidx.compose.ui.node.RootForTest
import androidx.compose.ui.platform.AccessibilityManager
import androidx.compose.ui.platform.ClipboardManager
import androidx.compose.ui.platform.PlatformTextInputSessionScope
import androidx.compose.ui.platform.SoftwareKeyboardController
import androidx.compose.ui.platform.TextToolbar
import androidx.compose.ui.platform.ViewConfiguration
import androidx.compose.ui.platform.WindowInfo
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.input.TextInputService
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.minus
import androidx.compose.ui.unit.toOffset
import androidx.compose.ui.util.fastMaxBy
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import com.google.common.truth.Truth.assertThat
import java.util.concurrent.Executors
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.asCoroutineDispatcher
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
// TODO(shepshapard): Write the following PointerInputEvent to PointerInputChangeEvent tests
// 2 down, 2 move, 2 up, converted correctly
// 3 down, 3 move, 3 up, converted correctly
// down, up, down, up, converted correctly
// 2 down, 1 up, same down, both up, converted correctly
// 2 down, 1 up, new down, both up, converted correctly
// new is up, throws exception
// TODO(shepshapard): Write the following hit testing tests
// 2 down, one hits, target receives correct event
// 2 down, one moves in, one out, 2 up, target receives correct event stream
// down, up, receives down and up
// down, move, up, receives all 3
// down, up, then down and misses, target receives down and up
// down, misses, moves in bounds, up, target does not receive event
// down, hits, moves out of bounds, up, target receives all events
// TODO(shepshapard): Write the following offset testing tests
// 3 simultaneous moves, offsets are correct
// TODO(shepshapard): Write the following pointer input dispatch path tests:
// down, move, up, on 2, hits all 5 passes
@MediumTest
@RunWith(AndroidJUnit4::class)
class PointerInputEventProcessorTest {
private lateinit var pointerInputEventProcessor: PointerInputEventProcessor
private lateinit var testOwner: TestOwner
private val positionCalculator = object : PositionCalculator {
override fun screenToLocal(positionOnScreen: Offset): Offset = positionOnScreen
override fun localToScreen(localPosition: Offset): Offset = localPosition
override fun localToScreen(localTransform: Matrix) {}
}
@Before
fun setup() {
testOwner = TestOwner()
pointerInputEventProcessor = PointerInputEventProcessor(testOwner.root)
}
private fun addToRoot(vararg layoutNodes: LayoutNode) {
layoutNodes.forEachIndexed { index, node ->
testOwner.root.insertAt(index, node)
}
testOwner.measureAndLayout()
}
@Test
@OptIn(ExperimentalComposeUiApi::class)
fun pointerTypePassed() {
val pointerTypes = listOf(
PointerType.Unknown,
PointerType.Touch,
PointerType.Mouse,
PointerType.Stylus,
PointerType.Eraser
)
// Arrange
val pointerInputFilter = PointerInputFilterMock()
val layoutNode = LayoutNode(
0,
0,
500,
500,
PointerInputModifierImpl2(
pointerInputFilter
)
)
addToRoot(layoutNode)
val offset = Offset(100f, 200f)
val previousEvents = mutableListOf<PointerInputEventData>()
val events = pointerTypes.mapIndexed { index, pointerType ->
previousEvents += PointerInputEventData(
id = PointerId(index.toLong()),
uptime = index.toLong(),
positionOnScreen = Offset(offset.x + index, offset.y + index),
position = Offset(offset.x + index, offset.y + index),
originalEventPosition = Offset(offset.x + index, offset.y + index),
down = true,
pressure = 1.0f,
type = pointerType
)
val data = previousEvents.map {
it.copy(uptime = index.toLong())
}
PointerInputEvent(index.toLong(), data)
}
// Act
events.forEach { pointerInputEventProcessor.process(it) }
// Assert
val log = pointerInputFilter.log.getOnPointerEventFilterLog()
// Verify call count
assertThat(log)
.hasSize(PointerEventPass.values().size * pointerTypes.size)
// Verify types of the pointers
repeat(pointerTypes.size) { eventIndex ->
PointerEventPass.values().forEachIndexed { passIndex, pass ->
val item = log[passIndex + (eventIndex * PointerEventPass.values().size)]
assertThat(item.pass).isEqualTo(pass)
val changes = item.pointerEvent.changes
assertThat(changes.size).isEqualTo(eventIndex + 1)
for (i in 0..eventIndex) {
val pointerType = pointerTypes[i]
val change = changes[i]
assertThat(change.type).isEqualTo(pointerType)
}
}
}
}
/**
* PointerInputEventProcessor doesn't currently support reentrancy and
* b/233209795 indicates that it is likely causing a crash. This test
* ensures that if we have reentrancy that we exit without handling
* the event. This test can be replaced with tests supporting reentrant
* behavior when reentrancy is supported.
*/
@Test
fun noReentrancy() {
var reentrancyCount = 0
// Arrange
val reentrantPointerInputFilter = object : PointerInputFilter() {
override fun onPointerEvent(
pointerEvent: PointerEvent,
pass: PointerEventPass,
bounds: IntSize
) {
if (pass != PointerEventPass.Initial) {
return
}
if (reentrancyCount > 1) {
// Don't allow infinite recursion. Just enough to break the test.
return
}
val oldId = pointerEvent.changes.fastMaxBy { it.id.value }!!.id.value.toInt()
val event = PointerInputEvent(oldId + 1, 14, Offset.Zero, true)
// force a reentrant call
val result = pointerInputEventProcessor.process(event)
assertThat(result.anyMovementConsumed).isFalse()
assertThat(result.dispatchedToAPointerInputModifier).isFalse()
pointerEvent.changes.forEach { it.consume() }
reentrancyCount++
}
override fun onCancel() {
}
}
val layoutNode = LayoutNode(
0,
0,
500,
500,
PointerInputModifierImpl2(reentrantPointerInputFilter)
)
addToRoot(layoutNode)
// Act
val result =
pointerInputEventProcessor.process(PointerInputEvent(8712, 3, Offset.Zero, true))
// Assert
assertThat(reentrancyCount).isEqualTo(1)
assertThat(result.anyMovementConsumed).isFalse()
assertThat(result.dispatchedToAPointerInputModifier).isTrue()
}
@Test
fun process_downMoveUp_convertedCorrectlyAndTraversesAllPassesInCorrectOrder() {
// Arrange
val pointerInputFilter = PointerInputFilterMock()
val layoutNode = LayoutNode(
0,
0,
500,
500,
PointerInputModifierImpl2(
pointerInputFilter
)
)
addToRoot(layoutNode)
val offset = Offset(100f, 200f)
val offset2 = Offset(300f, 400f)
val events = arrayOf(
PointerInputEvent(8712, 3, offset, true),
PointerInputEvent(8712, 11, offset2, true),
PointerInputEvent(8712, 13, offset2, false)
)
val down = down(8712, 3, offset.x, offset.y)
val move = down.moveTo(11, offset2.x, offset2.y)
val up = move.up(13)
val expectedChanges = arrayOf(down, move, up)
// Act
events.forEach { pointerInputEventProcessor.process(it) }
// Assert
val log = pointerInputFilter.log.getOnPointerEventFilterLog()
// Verify call count
assertThat(log)
.hasSize(PointerEventPass.values().size * expectedChanges.size)
// Verify call values
var count = 0
expectedChanges.forEach { change ->
PointerEventPass.values().forEach { pass ->
val item = log[count]
PointerEventSubject
.assertThat(item.pointerEvent)
.isStructurallyEqualTo(pointerEventOf(change))
assertThat(item.pass).isEqualTo(pass)
count++
}
}
}
@Test
fun process_downHits_targetReceives() {
// Arrange
val childOffset = Offset(100f, 200f)
val pointerInputFilter = PointerInputFilterMock()
val layoutNode = LayoutNode(
100, 200, 301, 401,
PointerInputModifierImpl2(
pointerInputFilter
)
)
addToRoot(layoutNode)
val offsets = arrayOf(
Offset(100f, 200f),
Offset(300f, 200f),
Offset(100f, 400f),
Offset(300f, 400f)
)
val events = Array(4) { index ->
PointerInputEvent(index, 5, offsets[index], true)
}
val expectedChanges = Array(4) { index ->
PointerInputChange(
id = PointerId(index.toLong()),
5,
offsets[index] - childOffset,
true,
5,
offsets[index] - childOffset,
false,
isInitiallyConsumed = false
)
}
// Act
events.forEach {
pointerInputEventProcessor.process(it)
}
// Assert
val log =
pointerInputFilter
.log
.getOnPointerEventFilterLog()
.filter { it.pass == PointerEventPass.Initial }
// Verify call count
assertThat(log)
.hasSize(expectedChanges.size)
// Verify call values
expectedChanges.forEachIndexed { index, change ->
val item = log[index]
PointerEventSubject
.assertThat(item.pointerEvent)
.isStructurallyEqualTo(pointerEventOf(change))
}
}
@Test
fun process_downMisses_targetDoesNotReceive() {
// Arrange
val pointerInputFilter = PointerInputFilterMock()
val layoutNode = LayoutNode(
100, 200, 301, 401,
PointerInputModifierImpl2(
pointerInputFilter
)
)
addToRoot(layoutNode)
val offsets = arrayOf(
Offset(99f, 200f),
Offset(99f, 400f),
Offset(100f, 199f),
Offset(100f, 401f),
Offset(300f, 199f),
Offset(300f, 401f),
Offset(301f, 200f),
Offset(301f, 400f)
)
val events = Array(8) { index ->
PointerInputEvent(index, 0, offsets[index], true)
}
// Act
events.forEach {
pointerInputEventProcessor.process(it)
}
// Assert
assertThat(pointerInputFilter.log.getOnPointerEventFilterLog()).hasSize(0)
}
@Test
fun process_downHits3of3_all3PointerNodesReceive() {
process_partialTreeHits(3)
}
@Test
fun process_downHits2of3_correct2PointerNodesReceive() {
process_partialTreeHits(2)
}
@Test
fun process_downHits1of3_onlyCorrectPointerNodesReceives() {
process_partialTreeHits(1)
}
private fun process_partialTreeHits(numberOfChildrenHit: Int) {
// Arrange
val log = mutableListOf<LogEntry>()
val childPointerInputFilter = PointerInputFilterMock(log)
val middlePointerInputFilter = PointerInputFilterMock(log)
val parentPointerInputFilter = PointerInputFilterMock(log)
val childLayoutNode =
LayoutNode(
100, 100, 200, 200,
PointerInputModifierImpl2(
childPointerInputFilter
)
)
val middleLayoutNode: LayoutNode =
LayoutNode(
100, 100, 400, 400,
PointerInputModifierImpl2(
middlePointerInputFilter
)
).apply {
insertAt(0, childLayoutNode)
}
val parentLayoutNode: LayoutNode =
LayoutNode(
0, 0, 500, 500,
PointerInputModifierImpl2(
parentPointerInputFilter
)
).apply {
insertAt(0, middleLayoutNode)
}
addToRoot(parentLayoutNode)
val offset = when (numberOfChildrenHit) {
3 -> Offset(250f, 250f)
2 -> Offset(150f, 150f)
1 -> Offset(50f, 50f)
else -> throw IllegalStateException()
}
val event = PointerInputEvent(0, 5, offset, true)
// Act
pointerInputEventProcessor.process(event)
// Assert
val filteredLog = log.getOnPointerEventFilterLog().filter {
it.pass == PointerEventPass.Initial
}
when (numberOfChildrenHit) {
3 -> {
assertThat(filteredLog).hasSize(3)
assertThat(filteredLog[0].pointerInputFilter)
.isSameInstanceAs(parentPointerInputFilter)
assertThat(filteredLog[1].pointerInputFilter)
.isSameInstanceAs(middlePointerInputFilter)
assertThat(filteredLog[2].pointerInputFilter)
.isSameInstanceAs(childPointerInputFilter)
}
2 -> {
assertThat(filteredLog).hasSize(2)
assertThat(filteredLog[0].pointerInputFilter)
.isSameInstanceAs(parentPointerInputFilter)
assertThat(filteredLog[1].pointerInputFilter)
.isSameInstanceAs(middlePointerInputFilter)
}
1 -> {
assertThat(filteredLog).hasSize(1)
assertThat(filteredLog[0].pointerInputFilter)
.isSameInstanceAs(parentPointerInputFilter)
}
else -> throw IllegalStateException()
}
}
@Test
fun process_modifiedChange_isPassedToNext() {
// Arrange
val expectedInput = PointerInputChange(
id = PointerId(0),
5,
Offset(100f, 0f),
true,
3,
Offset(0f, 0f),
true,
isInitiallyConsumed = false
)
val expectedOutput = PointerInputChange(
id = PointerId(0),
5,
Offset(100f, 0f),
true,
3,
Offset(0f, 0f),
true,
isInitiallyConsumed = true
)
val pointerInputFilter = PointerInputFilterMock(
mutableListOf(),
pointerEventHandler = { pointerEvent, pass, _ ->
if (pass == PointerEventPass.Initial) {
val change = pointerEvent
.changes
.first()
if (change.positionChanged()) change.consume()
}
}
)
val layoutNode = LayoutNode(
0, 0, 500, 500,
PointerInputModifierImpl2(
pointerInputFilter
)
)
addToRoot(layoutNode)
val down = PointerInputEvent(
0,
3,
Offset(0f, 0f),
true
)
val move = PointerInputEvent(
0,
5,
Offset(100f, 0f),
true
)
// Act
pointerInputEventProcessor.process(down)
pointerInputFilter.log.clear()
pointerInputEventProcessor.process(move)
// Assert
val log = pointerInputFilter.log.getOnPointerEventFilterLog()
assertThat(log).hasSize(3)
PointerInputChangeSubject
.assertThat(log[0].pointerEvent.changes.first())
.isStructurallyEqualTo(expectedInput)
PointerInputChangeSubject
.assertThat(log[1].pointerEvent.changes.first())
.isStructurallyEqualTo(expectedOutput)
}
@Test
fun process_nodesAndAdditionalOffsetIncreasinglyInset_dispatchInfoIsCorrect() {
process_dispatchInfoIsCorrect(
0, 0, 100, 100,
2, 11, 100, 100,
23, 31, 100, 100,
43, 51,
99, 99
)
}
@Test
fun process_nodesAndAdditionalOffsetIncreasinglyOutset_dispatchInfoIsCorrect() {
process_dispatchInfoIsCorrect(
0, 0, 100, 100,
-2, -11, 100, 100,
-23, -31, 100, 100,
-43, -51,
1, 1
)
}
@Test
fun process_nodesAndAdditionalOffsetNotOffset_dispatchInfoIsCorrect() {
process_dispatchInfoIsCorrect(
0, 0, 100, 100,
0, 0, 100, 100,
0, 0, 100, 100,
0, 0,
50, 50
)
}
@Suppress("SameParameterValue")
private fun process_dispatchInfoIsCorrect(
pX1: Int,
pY1: Int,
pX2: Int,
pY2: Int,
mX1: Int,
mY1: Int,
mX2: Int,
mY2: Int,
cX1: Int,
cY1: Int,
cX2: Int,
cY2: Int,
aOX: Int,
aOY: Int,
pointerX: Int,
pointerY: Int
) {
// Arrange
val log = mutableListOf<LogEntry>()
val childPointerInputFilter = PointerInputFilterMock(log)
val middlePointerInputFilter = PointerInputFilterMock(log)
val parentPointerInputFilter = PointerInputFilterMock(log)
val childOffset = Offset(cX1.toFloat(), cY1.toFloat())
val childLayoutNode = LayoutNode(
cX1, cY1, cX2, cY2,
PointerInputModifierImpl2(
childPointerInputFilter
)
)
val middleOffset = Offset(mX1.toFloat(), mY1.toFloat())
val middleLayoutNode: LayoutNode = LayoutNode(
mX1, mY1, mX2, mY2,
PointerInputModifierImpl2(
middlePointerInputFilter
)
).apply {
insertAt(0, childLayoutNode)
}
val parentLayoutNode: LayoutNode = LayoutNode(
pX1, pY1, pX2, pY2,
PointerInputModifierImpl2(
parentPointerInputFilter
)
).apply {
insertAt(0, middleLayoutNode)
}
val outerLayoutNode = LayoutNode(
aOX,
aOY,
aOX + parentLayoutNode.width,
aOY + parentLayoutNode.height
)
outerLayoutNode.insertAt(0, parentLayoutNode)
addToRoot(outerLayoutNode)
val additionalOffset = IntOffset(aOX, aOY)
val offset = Offset(pointerX.toFloat(), pointerY.toFloat())
val down = PointerInputEvent(0, 7, offset, true)
val expectedPointerInputChanges = arrayOf(
PointerInputChange(
id = PointerId(0),
7,
offset - additionalOffset,
true,
7,
offset - additionalOffset,
false,
isInitiallyConsumed = false
),
PointerInputChange(
id = PointerId(0),
7,
offset - middleOffset - additionalOffset,
true,
7,
offset - middleOffset - additionalOffset,
false,
isInitiallyConsumed = false
),
PointerInputChange(
id = PointerId(0),
7,
offset - middleOffset - childOffset - additionalOffset,
true,
7,
offset - middleOffset - childOffset - additionalOffset,
false,
isInitiallyConsumed = false
)
)
val expectedSizes = arrayOf(
IntSize(pX2 - pX1, pY2 - pY1),
IntSize(mX2 - mX1, mY2 - mY1),
IntSize(cX2 - cX1, cY2 - cY1)
)
// Act
pointerInputEventProcessor.process(down)
// Assert
val filteredLog = log.getOnPointerEventFilterLog()
// Verify call count
assertThat(filteredLog).hasSize(PointerEventPass.values().size * 3)
// Verify call values
filteredLog.verifyOnPointerEventCall(
0,
parentPointerInputFilter,
pointerEventOf(expectedPointerInputChanges[0]),
PointerEventPass.Initial,
expectedSizes[0]
)
filteredLog.verifyOnPointerEventCall(
1,
middlePointerInputFilter,
pointerEventOf(expectedPointerInputChanges[1]),
PointerEventPass.Initial,
expectedSizes[1]
)
filteredLog.verifyOnPointerEventCall(
2,
childPointerInputFilter,
pointerEventOf(expectedPointerInputChanges[2]),
PointerEventPass.Initial,
expectedSizes[2]
)
filteredLog.verifyOnPointerEventCall(
3,
childPointerInputFilter,
pointerEventOf(expectedPointerInputChanges[2]),
PointerEventPass.Main,
expectedSizes[2]
)
filteredLog.verifyOnPointerEventCall(
4,
middlePointerInputFilter,
pointerEventOf(expectedPointerInputChanges[1]),
PointerEventPass.Main,
expectedSizes[1]
)
filteredLog.verifyOnPointerEventCall(
5,
parentPointerInputFilter,
pointerEventOf(expectedPointerInputChanges[0]),
PointerEventPass.Main,
expectedSizes[0]
)
filteredLog.verifyOnPointerEventCall(
6,
parentPointerInputFilter,
pointerEventOf(expectedPointerInputChanges[0]),
PointerEventPass.Final,
expectedSizes[0]
)
filteredLog.verifyOnPointerEventCall(
7,
middlePointerInputFilter,
pointerEventOf(expectedPointerInputChanges[1]),
PointerEventPass.Final,
expectedSizes[1]
)
filteredLog.verifyOnPointerEventCall(
8,
childPointerInputFilter,
pointerEventOf(expectedPointerInputChanges[2]),
PointerEventPass.Final,
expectedSizes[2]
)
}
/**
* This test creates a layout of this shape:
*
* -------------
* | | |
* | t | |
* | | |
* |-----| |
* | |
* | |-----|
* | | |
* | | t |
* | | |
* -------------
*
* Where there is one child in the top right, and one in the bottom left, and 2 down touches,
* one in the top left and one in the bottom right.
*/
@Test
fun process_2DownOn2DifferentPointerNodes_hitAndDispatchInfoAreCorrect() {
// Arrange
val log = mutableListOf<LogEntry>()
val childPointerInputFilter1 = PointerInputFilterMock(log)
val childPointerInputFilter2 = PointerInputFilterMock(log)
val childLayoutNode1 =
LayoutNode(
0, 0, 50, 50,
PointerInputModifierImpl2(
childPointerInputFilter1
)
)
val childLayoutNode2 =
LayoutNode(
50, 50, 100, 100,
PointerInputModifierImpl2(
childPointerInputFilter2
)
)
addToRoot(childLayoutNode1, childLayoutNode2)
val offset1 = Offset(25f, 25f)
val offset2 = Offset(75f, 75f)
val down = PointerInputEvent(
5,
listOf(
PointerInputEventData(0, 5, offset1, true),
PointerInputEventData(1, 5, offset2, true)
)
)
val expectedChange1 =
PointerInputChange(
id = PointerId(0),
5,
offset1,
true,
5,
offset1,
false,
isInitiallyConsumed = false
)
val expectedChange2 =
PointerInputChange(
id = PointerId(1),
5,
offset2 - Offset(50f, 50f),
true,
5,
offset2 - Offset(50f, 50f),
false,
isInitiallyConsumed = false
)
// Act
pointerInputEventProcessor.process(down)
// Assert
// Verify call count
val child1Log = log.getOnPointerEventFilterLog().filter {
it.pointerInputFilter === childPointerInputFilter1
}
val child2Log = log.getOnPointerEventFilterLog().filter {
it.pointerInputFilter === childPointerInputFilter2
}
assertThat(child1Log).hasSize(PointerEventPass.values().size)
assertThat(child2Log).hasSize(PointerEventPass.values().size)
// Verify call values
val expectedBounds = IntSize(50, 50)
child1Log.verifyOnPointerEventCall(
0,
null,
pointerEventOf(expectedChange1),
PointerEventPass.Initial,
expectedBounds
)
child1Log.verifyOnPointerEventCall(
1,
null,
pointerEventOf(expectedChange1),
PointerEventPass.Main,
expectedBounds
)
child1Log.verifyOnPointerEventCall(
2,
null,
pointerEventOf(expectedChange1),
PointerEventPass.Final,
expectedBounds
)
child2Log.verifyOnPointerEventCall(
0,
null,
pointerEventOf(expectedChange2),
PointerEventPass.Initial,
expectedBounds
)
child2Log.verifyOnPointerEventCall(
1,
null,
pointerEventOf(expectedChange2),
PointerEventPass.Main,
expectedBounds
)
child2Log.verifyOnPointerEventCall(
2,
null,
pointerEventOf(expectedChange2),
PointerEventPass.Final,
expectedBounds
)
}
/**
* This test creates a layout of this shape:
*
* ---------------
* | t | |
* | | |
* | |-------| |
* | | t | |
* | | | |
* | | | |
* |--| |-------|
* | | | t |
* | | | |
* | | | |
* | |--| |
* | | |
* ---------------
*
* There are 3 staggered children and 3 down events, the first is on child 1, the second is on
* child 2 in a space that overlaps child 1, and the third is in a space that overlaps both
* child 2.
*/
@Test
fun process_3DownOnOverlappingPointerNodes_hitAndDispatchInfoAreCorrect() {
val log = mutableListOf<LogEntry>()
val childPointerInputFilter1 = PointerInputFilterMock(log)
val childPointerInputFilter2 = PointerInputFilterMock(log)
val childPointerInputFilter3 = PointerInputFilterMock(log)
val childLayoutNode1 = LayoutNode(
0, 0, 100, 100,
PointerInputModifierImpl2(
childPointerInputFilter1
)
)
val childLayoutNode2 = LayoutNode(
50, 50, 150, 150,
PointerInputModifierImpl2(
childPointerInputFilter2
)
)
val childLayoutNode3 = LayoutNode(
100, 100, 200, 200,
PointerInputModifierImpl2(
childPointerInputFilter3
)
)
addToRoot(childLayoutNode1, childLayoutNode2, childLayoutNode3)
val offset1 = Offset(25f, 25f)
val offset2 = Offset(75f, 75f)
val offset3 = Offset(125f, 125f)
val down = PointerInputEvent(
5,
listOf(
PointerInputEventData(0, 5, offset1, true),
PointerInputEventData(1, 5, offset2, true),
PointerInputEventData(2, 5, offset3, true)
)
)
val expectedChange1 =
PointerInputChange(
id = PointerId(0),
5,
offset1,
true,
5,
offset1,
false,
isInitiallyConsumed = false
)
val expectedChange2 =
PointerInputChange(
id = PointerId(1),
5,
offset2 - Offset(50f, 50f),
true,
5,
offset2 - Offset(50f, 50f),
false,
isInitiallyConsumed = false
)
val expectedChange3 =
PointerInputChange(
id = PointerId(2),
5,
offset3 - Offset(100f, 100f),
true,
5,
offset3 - Offset(100f, 100f),
false,
isInitiallyConsumed = false
)
// Act
pointerInputEventProcessor.process(down)
// Assert
val child1Log = log.getOnPointerEventFilterLog().filter {
it.pointerInputFilter === childPointerInputFilter1
}
val child2Log = log.getOnPointerEventFilterLog().filter {
it.pointerInputFilter === childPointerInputFilter2
}
val child3Log = log.getOnPointerEventFilterLog().filter {
it.pointerInputFilter === childPointerInputFilter3
}
assertThat(child1Log).hasSize(PointerEventPass.values().size)
assertThat(child2Log).hasSize(PointerEventPass.values().size)
assertThat(child3Log).hasSize(PointerEventPass.values().size)
// Verify call values
val expectedBounds = IntSize(100, 100)
child1Log.verifyOnPointerEventCall(
0,
null,
pointerEventOf(expectedChange1),
PointerEventPass.Initial,
expectedBounds
)
child1Log.verifyOnPointerEventCall(
1,
null,
pointerEventOf(expectedChange1),
PointerEventPass.Main,
expectedBounds
)
child1Log.verifyOnPointerEventCall(
2,
null,
pointerEventOf(expectedChange1),
PointerEventPass.Final,
expectedBounds
)
child2Log.verifyOnPointerEventCall(
0,
null,
pointerEventOf(expectedChange2),
PointerEventPass.Initial,
expectedBounds
)
child2Log.verifyOnPointerEventCall(
1,
null,
pointerEventOf(expectedChange2),
PointerEventPass.Main,
expectedBounds
)
child2Log.verifyOnPointerEventCall(
2,
null,
pointerEventOf(expectedChange2),
PointerEventPass.Final,
expectedBounds
)
child3Log.verifyOnPointerEventCall(
0,
null,
pointerEventOf(expectedChange3),
PointerEventPass.Initial,
expectedBounds
)
child3Log.verifyOnPointerEventCall(
1,
null,
pointerEventOf(expectedChange3),
PointerEventPass.Main,
expectedBounds
)
child3Log.verifyOnPointerEventCall(
2,
null,
pointerEventOf(expectedChange3),
PointerEventPass.Final,
expectedBounds
)
}
/**
* This test creates a layout of this shape:
*
* ---------------
* | |
* | t |
* | |
* | |-------| |
* | | | |
* | | t | |
* | | | |
* | |-------| |
* | |
* | t |
* | |
* ---------------
*
* There are 3 staggered children and 3 down events, the first is on child 1, the second is on
* child 2 in a space that overlaps child 1, and the third is in a space that overlaps both
* child 2.
*/
@Test
fun process_3DownOnFloatingPointerNodeV_hitAndDispatchInfoAreCorrect() {
val childPointerInputFilter1 = PointerInputFilterMock()
val childPointerInputFilter2 = PointerInputFilterMock()
val childLayoutNode1 = LayoutNode(
0, 0, 100, 150,
PointerInputModifierImpl2(
childPointerInputFilter1
)
)
val childLayoutNode2 = LayoutNode(
25, 50, 75, 100,
PointerInputModifierImpl2(
childPointerInputFilter2
)
)
addToRoot(childLayoutNode1, childLayoutNode2)
val offset1 = Offset(50f, 25f)
val offset2 = Offset(50f, 75f)
val offset3 = Offset(50f, 125f)
val down = PointerInputEvent(
7,
listOf(
PointerInputEventData(0, 7, offset1, true),
PointerInputEventData(1, 7, offset2, true),
PointerInputEventData(2, 7, offset3, true)
)
)
val expectedChange1 =
PointerInputChange(
id = PointerId(0),
7,
offset1,
true,
7,
offset1,
false,
isInitiallyConsumed = false
)
val expectedChange2 =
PointerInputChange(
id = PointerId(1),
7,
offset2 - Offset(25f, 50f),
true,
7,
offset2 - Offset(25f, 50f),
false,
isInitiallyConsumed = false
)
val expectedChange3 =
PointerInputChange(
id = PointerId(2),
7,
offset3,
true,
7,
offset3,
false,
isInitiallyConsumed = false
)
// Act
pointerInputEventProcessor.process(down)
// Assert
val log1 = childPointerInputFilter1.log.getOnPointerEventFilterLog()
val log2 = childPointerInputFilter2.log.getOnPointerEventFilterLog()
// Verify call count
assertThat(log1).hasSize(PointerEventPass.values().size)
assertThat(log2).hasSize(PointerEventPass.values().size)
// Verify call values
PointerEventPass.values().forEachIndexed { index, pass ->
log1.verifyOnPointerEventCall(
index,
null,
pointerEventOf(expectedChange1, expectedChange3),
pass,
IntSize(100, 150)
)
log2.verifyOnPointerEventCall(
index,
null,
pointerEventOf(expectedChange2),
pass,
IntSize(50, 50)
)
}
}
/**
* This test creates a layout of this shape:
*
* -----------------
* | |
* | |-------| |
* | | | |
* | t | t | t |
* | | | |
* | |-------| |
* | |
* -----------------
*
* There are 3 staggered children and 3 down events, the first is on child 1, the second is on
* child 2 in a space that overlaps child 1, and the third is in a space that overlaps both
* child 2.
*/
@Test
fun process_3DownOnFloatingPointerNodeH_hitAndDispatchInfoAreCorrect() {
val childPointerInputFilter1 = PointerInputFilterMock()
val childPointerInputFilter2 = PointerInputFilterMock()
val childLayoutNode1 = LayoutNode(
0, 0, 150, 100,
PointerInputModifierImpl2(
childPointerInputFilter1
)
)
val childLayoutNode2 = LayoutNode(
50, 25, 100, 75,
PointerInputModifierImpl2(
childPointerInputFilter2
)
)
addToRoot(childLayoutNode1, childLayoutNode2)
val offset1 = Offset(25f, 50f)
val offset2 = Offset(75f, 50f)
val offset3 = Offset(125f, 50f)
val down = PointerInputEvent(
11,
listOf(
PointerInputEventData(0, 11, offset1, true),
PointerInputEventData(1, 11, offset2, true),
PointerInputEventData(2, 11, offset3, true)
)
)
val expectedChange1 =
PointerInputChange(
id = PointerId(0),
11,
offset1,
true,
11,
offset1,
false,
isInitiallyConsumed = false
)
val expectedChange2 =
PointerInputChange(
id = PointerId(1),
11,
offset2 - Offset(50f, 25f),
true,
11,
offset2 - Offset(50f, 25f),
false,
isInitiallyConsumed = false
)
val expectedChange3 =
PointerInputChange(
id = PointerId(2),
11,
offset3,
true,
11,
offset3,
false,
isInitiallyConsumed = false
)
// Act
pointerInputEventProcessor.process(down)
// Assert
val log1 = childPointerInputFilter1.log.getOnPointerEventFilterLog()
val log2 = childPointerInputFilter2.log.getOnPointerEventFilterLog()
// Verify call count
assertThat(log1).hasSize(PointerEventPass.values().size)
assertThat(log2).hasSize(PointerEventPass.values().size)
// Verify call values
PointerEventPass.values().forEachIndexed { index, pass ->
log1.verifyOnPointerEventCall(
index,
null,
pointerEventOf(expectedChange1, expectedChange3),
pass,
IntSize(150, 100)
)
log2.verifyOnPointerEventCall(
index,
null,
pointerEventOf(expectedChange2),
pass,
IntSize(50, 50)
)
}
}
/**
* This test creates a layout of this shape:
* 0 1 2 3 4
* ......... .........
* 0 . t . . t .
* . |---|---|---| .
* 1 . t | t | | t | t .
* ....|---| |---|....
* 2 | |
* ....|---| |---|....
* 3 . t | t | | t | t .
* . |---|---|---| .
* 4 . t . . t .
* ......... .........
*
* 4 LayoutNodes with PointerInputModifiers that are clipped by their parent LayoutNode. 4
* touches touch just inside the parent LayoutNode and inside the child LayoutNodes. 8
* touches touch just outside the parent LayoutNode but inside the child LayoutNodes.
*
* Because layout node bounds are not used to clip pointer input hit testing, all pointers
* should hit.
*/
@Test
fun process_4DownInClippedAreaOfLnsWithPims_onlyCorrectPointersHit() {
// Arrange
val pointerInputFilterTopLeft = PointerInputFilterMock()
val pointerInputFilterTopRight = PointerInputFilterMock()
val pointerInputFilterBottomLeft = PointerInputFilterMock()
val pointerInputFilterBottomRight = PointerInputFilterMock()
val layoutNodeTopLeft = LayoutNode(
-1, -1, 1, 1,
PointerInputModifierImpl2(
pointerInputFilterTopLeft
)
)
val layoutNodeTopRight = LayoutNode(
2, -1, 4, 1,
PointerInputModifierImpl2(
pointerInputFilterTopRight
)
)
val layoutNodeBottomLeft = LayoutNode(
-1, 2, 1, 4,
PointerInputModifierImpl2(
pointerInputFilterBottomLeft
)
)
val layoutNodeBottomRight = LayoutNode(
2, 2, 4, 4,
PointerInputModifierImpl2(
pointerInputFilterBottomRight
)
)
val parentLayoutNode = LayoutNode(1, 1, 4, 4).apply {
insertAt(0, layoutNodeTopLeft)
insertAt(1, layoutNodeTopRight)
insertAt(2, layoutNodeBottomLeft)
insertAt(3, layoutNodeBottomRight)
}
addToRoot(parentLayoutNode)
val offsetsTopLeft =
listOf(
Offset(0f, 1f),
Offset(1f, 0f),
Offset(1f, 1f)
)
val offsetsTopRight =
listOf(
Offset(3f, 0f),
Offset(3f, 1f),
Offset(4f, 1f)
)
val offsetsBottomLeft =
listOf(
Offset(0f, 3f),
Offset(1f, 3f),
Offset(1f, 4f)
)
val offsetsBottomRight =
listOf(
Offset(3f, 3f),
Offset(3f, 4f),
Offset(4f, 3f)
)
val allOffsets = offsetsTopLeft + offsetsTopRight + offsetsBottomLeft + offsetsBottomRight
val pointerInputEvent =
PointerInputEvent(
11,
(allOffsets.indices).map {
PointerInputEventData(it, 11, allOffsets[it], true)
}
)
// Act
pointerInputEventProcessor.process(pointerInputEvent)
// Assert
val expectedChangesTopLeft =
(offsetsTopLeft.indices).map {
PointerInputChange(
id = PointerId(it.toLong()),
11,
Offset(
offsetsTopLeft[it].x,
offsetsTopLeft[it].y
),
true,
11,
Offset(
offsetsTopLeft[it].x,
offsetsTopLeft[it].y
),
false,
isInitiallyConsumed = false
)
}
val expectedChangesTopRight =
(offsetsTopLeft.indices).map {
PointerInputChange(
id = PointerId(it.toLong() + 3),
11,
Offset(
offsetsTopRight[it].x - 3f,
offsetsTopRight[it].y
),
true,
11,
Offset(
offsetsTopRight[it].x - 3f,
offsetsTopRight[it].y
),
false,
isInitiallyConsumed = false
)
}
val expectedChangesBottomLeft =
(offsetsTopLeft.indices).map {
PointerInputChange(
id = PointerId(it.toLong() + 6),
11,
Offset(
offsetsBottomLeft[it].x,
offsetsBottomLeft[it].y - 3f
),
true,
11,
Offset(
offsetsBottomLeft[it].x,
offsetsBottomLeft[it].y - 3f
),
false,
isInitiallyConsumed = false
)
}
val expectedChangesBottomRight =
(offsetsTopLeft.indices).map {
PointerInputChange(
id = PointerId(it.toLong() + 9),
11,
Offset(
offsetsBottomRight[it].x - 3f,
offsetsBottomRight[it].y - 3f
),
true,
11,
Offset(
offsetsBottomRight[it].x - 3f,
offsetsBottomRight[it].y - 3f
),
false,
isInitiallyConsumed = false
)
}
// Verify call values
val logTopLeft = pointerInputFilterTopLeft.log.getOnPointerEventFilterLog()
val logTopRight = pointerInputFilterTopRight.log.getOnPointerEventFilterLog()
val logBottomLeft = pointerInputFilterBottomLeft.log.getOnPointerEventFilterLog()
val logBottomRight = pointerInputFilterBottomRight.log.getOnPointerEventFilterLog()
PointerEventPass.values().forEachIndexed { index, pass ->
logTopLeft.verifyOnPointerEventCall(
index = index,
expectedEvent = pointerEventOf(*expectedChangesTopLeft.toTypedArray()),
expectedPass = pass
)
logTopRight.verifyOnPointerEventCall(
index = index,
expectedEvent = pointerEventOf(*expectedChangesTopRight.toTypedArray()),
expectedPass = pass
)
logBottomLeft.verifyOnPointerEventCall(
index = index,
expectedEvent = pointerEventOf(*expectedChangesBottomLeft.toTypedArray()),
expectedPass = pass
)
logBottomRight.verifyOnPointerEventCall(
index = index,
expectedEvent = pointerEventOf(*expectedChangesBottomRight.toTypedArray()),
expectedPass = pass
)
}
}
/**
* This test creates a layout of this shape:
*
* |---|
* |tt |
* |t |
* |---|t
* tt
*
* But where the additional offset suggest something more like this shape.
*
* tt
* t|---|
* | t|
* | tt|
* |---|
*
* Without the additional offset, it would be expected that only the top left 3 pointers would
* hit, but with the additional offset, only the bottom right 3 hit.
*/
@Test
fun process_rootIsOffset_onlyCorrectPointersHit() {
// Arrange
val singlePointerInputFilter = PointerInputFilterMock()
val layoutNode = LayoutNode(
0, 0, 2, 2,
PointerInputModifierImpl2(
singlePointerInputFilter
)
)
val outerLayoutNode = LayoutNode(1, 1, 3, 3)
outerLayoutNode.insertAt(0, layoutNode)
addToRoot(outerLayoutNode)
val offsetsThatHit =
listOf(
Offset(2f, 2f),
Offset(2f, 1f),
Offset(1f, 2f)
)
val offsetsThatMiss =
listOf(
Offset(0f, 0f),
Offset(0f, 1f),
Offset(1f, 0f)
)
val allOffsets = offsetsThatHit + offsetsThatMiss
val pointerInputEvent =
PointerInputEvent(
11,
(allOffsets.indices).map {
PointerInputEventData(it, 11, allOffsets[it], true)
}
)
// Act
pointerInputEventProcessor.process(pointerInputEvent)
// Assert
val expectedChanges =
(offsetsThatHit.indices).map {
PointerInputChange(
id = PointerId(it.toLong()),
11,
offsetsThatHit[it] - Offset(1f, 1f),
true,
11,
offsetsThatHit[it] - Offset(1f, 1f),
false,
isInitiallyConsumed = false
)
}
val log = singlePointerInputFilter.log.getOnPointerEventFilterLog()
// Verify call count
assertThat(log).hasSize(PointerEventPass.values().size)
// Verify call values
PointerEventPass.values().forEachIndexed { index, pass ->
log.verifyOnPointerEventCall(
index = index,
expectedEvent = pointerEventOf(*expectedChanges.toTypedArray()),
expectedPass = pass
)
}
}
@Test
fun process_downOn3NestedPointerInputModifiers_hitAndDispatchInfoAreCorrect() {
val pointerInputFilter1 = PointerInputFilterMock()
val pointerInputFilter2 = PointerInputFilterMock()
val pointerInputFilter3 = PointerInputFilterMock()
val modifier = PointerInputModifierImpl2(pointerInputFilter1) then
PointerInputModifierImpl2(pointerInputFilter2) then
PointerInputModifierImpl2(pointerInputFilter3)
val layoutNode = LayoutNode(
25, 50, 75, 100,
modifier
)
addToRoot(layoutNode)
val offset1 = Offset(50f, 75f)
val down = PointerInputEvent(
7,
listOf(
PointerInputEventData(0, 7, offset1, true)
)
)
val expectedChange =
PointerInputChange(
id = PointerId(0),
7,
offset1 - Offset(25f, 50f),
true,
7,
offset1 - Offset(25f, 50f),
false,
isInitiallyConsumed = false
)
// Act
pointerInputEventProcessor.process(down)
// Assert
val log1 = pointerInputFilter1.log.getOnPointerEventFilterLog()
val log2 = pointerInputFilter2.log.getOnPointerEventFilterLog()
val log3 = pointerInputFilter3.log.getOnPointerEventFilterLog()
// Verify call count
assertThat(log1).hasSize(PointerEventPass.values().size)
assertThat(log2).hasSize(PointerEventPass.values().size)
assertThat(log3).hasSize(PointerEventPass.values().size)
// Verify call values
PointerEventPass.values().forEachIndexed { index, pass ->
log1.verifyOnPointerEventCall(
index = index,
expectedEvent = pointerEventOf(expectedChange),
expectedPass = pass,
expectedBounds = IntSize(50, 50)
)
log2.verifyOnPointerEventCall(
index = index,
expectedEvent = pointerEventOf(expectedChange),
expectedPass = pass,
expectedBounds = IntSize(50, 50)
)
log3.verifyOnPointerEventCall(
index = index,
expectedEvent = pointerEventOf(expectedChange),
expectedPass = pass,
expectedBounds = IntSize(50, 50)
)
}
}
@Test
fun process_downOnDeeplyNestedPointerInputModifier_hitAndDispatchInfoAreCorrect() {
val pointerInputFilter = PointerInputFilterMock()
val layoutNode1 =
LayoutNode(
1, 5, 500, 500,
PointerInputModifierImpl2(pointerInputFilter)
)
val layoutNode2: LayoutNode = LayoutNode(2, 6, 500, 500).apply {
insertAt(0, layoutNode1)
}
val layoutNode3: LayoutNode = LayoutNode(3, 7, 500, 500).apply {
insertAt(0, layoutNode2)
}
val layoutNode4: LayoutNode = LayoutNode(4, 8, 500, 500).apply {
insertAt(0, layoutNode3)
}
addToRoot(layoutNode4)
val offset1 = Offset(499f, 499f)
val downEvent = PointerInputEvent(
7,
listOf(
PointerInputEventData(0, 7, offset1, true)
)
)
val expectedChange =
PointerInputChange(
id = PointerId(0),
7,
offset1 - Offset(1f + 2f + 3f + 4f, 5f + 6f + 7f + 8f),
true,
7,
offset1 - Offset(1f + 2f + 3f + 4f, 5f + 6f + 7f + 8f),
false,
isInitiallyConsumed = false
)
// Act
pointerInputEventProcessor.process(downEvent)
// Assert
val log = pointerInputFilter.log.getOnPointerEventFilterLog()
// Verify call count
assertThat(log).hasSize(PointerEventPass.values().size)
// Verify call values
PointerEventPass.values().forEachIndexed { index, pass ->
log.verifyOnPointerEventCall(
index = index,
expectedEvent = pointerEventOf(expectedChange),
expectedPass = pass,
expectedBounds = IntSize(499, 495)
)
}
}
@Test
fun process_downOnComplexPointerAndLayoutNodePath_hitAndDispatchInfoAreCorrect() {
val pointerInputFilter1 = PointerInputFilterMock()
val pointerInputFilter2 = PointerInputFilterMock()
val pointerInputFilter3 = PointerInputFilterMock()
val pointerInputFilter4 = PointerInputFilterMock()
val layoutNode1 = LayoutNode(
1, 6, 500, 500,
PointerInputModifierImpl2(pointerInputFilter1)
then PointerInputModifierImpl2(pointerInputFilter2)
)
val layoutNode2: LayoutNode = LayoutNode(2, 7, 500, 500).apply {
insertAt(0, layoutNode1)
}
val layoutNode3 =
LayoutNode(
3, 8, 500, 500,
PointerInputModifierImpl2(pointerInputFilter3)
then PointerInputModifierImpl2(pointerInputFilter4)
).apply {
insertAt(0, layoutNode2)
}
val layoutNode4: LayoutNode = LayoutNode(4, 9, 500, 500).apply {
insertAt(0, layoutNode3)
}
val layoutNode5: LayoutNode = LayoutNode(5, 10, 500, 500).apply {
insertAt(0, layoutNode4)
}
addToRoot(layoutNode5)
val offset1 = Offset(499f, 499f)
val downEvent = PointerInputEvent(
3,
listOf(
PointerInputEventData(0, 3, offset1, true)
)
)
val expectedChange1 =
PointerInputChange(
id = PointerId(0),
3,
offset1 - Offset(
1f + 2f + 3f + 4f + 5f,
6f + 7f + 8f + 9f + 10f
),
true,
3,
offset1 - Offset(
1f + 2f + 3f + 4f + 5f,
6f + 7f + 8f + 9f + 10f
),
false,
isInitiallyConsumed = false
)
val expectedChange2 =
PointerInputChange(
id = PointerId(0),
3,
offset1 - Offset(3f + 4f + 5f, 8f + 9f + 10f),
true,
3,
offset1 - Offset(3f + 4f + 5f, 8f + 9f + 10f),
false,
isInitiallyConsumed = false
)
// Act
pointerInputEventProcessor.process(downEvent)
// Assert
val log1 = pointerInputFilter1.log.getOnPointerEventFilterLog()
val log2 = pointerInputFilter2.log.getOnPointerEventFilterLog()
val log3 = pointerInputFilter3.log.getOnPointerEventFilterLog()
val log4 = pointerInputFilter4.log.getOnPointerEventFilterLog()
// Verify call count
assertThat(log1).hasSize(PointerEventPass.values().size)
assertThat(log2).hasSize(PointerEventPass.values().size)
assertThat(log3).hasSize(PointerEventPass.values().size)
assertThat(log4).hasSize(PointerEventPass.values().size)
// Verify call values
PointerEventPass.values().forEachIndexed { index, pass ->
log1.verifyOnPointerEventCall(
index = index,
expectedEvent = pointerEventOf(expectedChange1),
expectedPass = pass,
expectedBounds = IntSize(499, 494)
)
log2.verifyOnPointerEventCall(
index = index,
expectedEvent = pointerEventOf(expectedChange1),
expectedPass = pass,
expectedBounds = IntSize(499, 494)
)
log3.verifyOnPointerEventCall(
index = index,
expectedEvent = pointerEventOf(expectedChange2),
expectedPass = pass,
expectedBounds = IntSize(497, 492)
)
log4.verifyOnPointerEventCall(
index = index,
expectedEvent = pointerEventOf(expectedChange2),
expectedPass = pass,
expectedBounds = IntSize(497, 492)
)
}
}
@Test
fun process_downOnFullyOverlappingPointerInputModifiers_onlyTopPointerInputModifierReceives() {
val pointerInputFilter1 = PointerInputFilterMock()
val pointerInputFilter2 = PointerInputFilterMock()
val layoutNode1 = LayoutNode(
0, 0, 100, 100,
PointerInputModifierImpl2(
pointerInputFilter1
)
)
val layoutNode2 = LayoutNode(
0, 0, 100, 100,
PointerInputModifierImpl2(
pointerInputFilter2
)
)
addToRoot(layoutNode1, layoutNode2)
val down = PointerInputEvent(
1, 0, Offset(50f, 50f), true
)
// Act
pointerInputEventProcessor.process(down)
// Assert
assertThat(pointerInputFilter2.log.getOnPointerEventFilterLog()).hasSize(3)
assertThat(pointerInputFilter1.log.getOnPointerEventFilterLog()).hasSize(0)
}
@Test
fun process_downOnPointerInputModifierInLayoutNodeWithNoSize_downNotReceived() {
val pointerInputFilter1 = PointerInputFilterMock()
val layoutNode1 = LayoutNode(
0, 0, 0, 0,
PointerInputModifierImpl2(pointerInputFilter1)
)
addToRoot(layoutNode1)
val down = PointerInputEvent(
1, 0, Offset(0f, 0f), true
)
// Act
pointerInputEventProcessor.process(down)
// Assert
assertThat(pointerInputFilter1.log.getOnPointerEventFilterLog()).hasSize(0)
}
// Cancel Handlers
@Test
fun processCancel_noPointers_doesntCrash() {
pointerInputEventProcessor.processCancel()
}
@Test
fun processCancel_downThenCancel_pimOnlyReceivesCorrectDownThenCancel() {
// Arrange
val pointerInputFilter = PointerInputFilterMock()
val layoutNode = LayoutNode(
0, 0, 500, 500,
PointerInputModifierImpl2(pointerInputFilter)
)
addToRoot(layoutNode)
val pointerInputEvent =
PointerInputEvent(
7,
5,
Offset(250f, 250f),
true
)
val expectedChange =
PointerInputChange(
id = PointerId(7),
5,
Offset(250f, 250f),
true,
5,
Offset(250f, 250f),
false,
isInitiallyConsumed = false
)
// Act
pointerInputEventProcessor.process(pointerInputEvent)
pointerInputEventProcessor.processCancel()
// Assert
val log = pointerInputFilter.log.filter {
it is OnPointerEventFilterEntry || it is OnCancelFilterEntry
}
// Verify call count
assertThat(log).hasSize(PointerEventPass.values().size + 1)
// Verify call values
PointerEventPass.values().forEachIndexed { index, pass ->
log.verifyOnPointerEventCall(
index = index,
expectedEvent = pointerEventOf(expectedChange),
expectedPass = pass
)
}
log.verifyOnCancelCall(PointerEventPass.values().size)
}
@Test
fun processCancel_downDownOnSamePimThenCancel_pimOnlyReceivesCorrectChangesThenCancel() {
// Arrange
val pointerInputFilter = PointerInputFilterMock()
val layoutNode = LayoutNode(
0, 0, 500, 500,
PointerInputModifierImpl2(
pointerInputFilter
)
)
addToRoot(layoutNode)
val pointerInputEvent1 =
PointerInputEvent(
7,
5,
Offset(200f, 200f),
true
)
val pointerInputEvent2 =
PointerInputEvent(
10,
listOf(
PointerInputEventData(
7,
10,
Offset(200f, 200f),
true
),
PointerInputEventData(
9,
10,
Offset(300f, 300f),
true
)
)
)
val expectedChanges1 =
listOf(
PointerInputChange(
id = PointerId(7),
5,
Offset(200f, 200f),
true,
5,
Offset(200f, 200f),
false,
isInitiallyConsumed = false
)
)
val expectedChanges2 =
listOf(
PointerInputChange(
id = PointerId(7),
10,
Offset(200f, 200f),
true,
5,
Offset(200f, 200f),
true,
isInitiallyConsumed = false
),
PointerInputChange(
id = PointerId(9),
10,
Offset(300f, 300f),
true,
10,
Offset(300f, 300f),
false,
isInitiallyConsumed = false
)
)
// Act
pointerInputEventProcessor.process(pointerInputEvent1)
pointerInputEventProcessor.process(pointerInputEvent2)
pointerInputEventProcessor.processCancel()
// Assert
val log = pointerInputFilter.log.filter {
it is OnPointerEventFilterEntry || it is OnCancelFilterEntry
}
// Verify call count
assertThat(log).hasSize(PointerEventPass.values().size * 2 + 1)
// Verify call values
var index = 0
PointerEventPass.values().forEach { pass ->
log.verifyOnPointerEventCall(
index = index,
expectedEvent = pointerEventOf(*expectedChanges1.toTypedArray()),
expectedPass = pass
)
index++
}
PointerEventPass.values().forEach { pass ->
log.verifyOnPointerEventCall(
index = index,
expectedEvent = pointerEventOf(*expectedChanges2.toTypedArray()),
expectedPass = pass
)
index++
}
log.verifyOnCancelCall(index)
}
@Test
fun processCancel_downOn2DifferentPimsThenCancel_pimsOnlyReceiveCorrectDownsThenCancel() {
// Arrange
val pointerInputFilter1 = PointerInputFilterMock()
val layoutNode1 = LayoutNode(
0, 0, 199, 199,
PointerInputModifierImpl2(pointerInputFilter1)
)
val pointerInputFilter2 = PointerInputFilterMock()
val layoutNode2 = LayoutNode(
200, 200, 399, 399,
PointerInputModifierImpl2(pointerInputFilter2)
)
addToRoot(layoutNode1, layoutNode2)
val pointerInputEventData1 =
PointerInputEventData(
7,
5,
Offset(100f, 100f),
true
)
val pointerInputEventData2 =
PointerInputEventData(
9,
5,
Offset(300f, 300f),
true
)
val pointerInputEvent = PointerInputEvent(
5,
listOf(pointerInputEventData1, pointerInputEventData2)
)
val expectedChange1 =
PointerInputChange(
id = PointerId(7),
5,
Offset(100f, 100f),
true,
5,
Offset(100f, 100f),
false,
isInitiallyConsumed = false
)
val expectedChange2 =
PointerInputChange(
id = PointerId(9),
5,
Offset(100f, 100f),
true,
5,
Offset(100f, 100f),
false,
isInitiallyConsumed = false
)
// Act
pointerInputEventProcessor.process(pointerInputEvent)
pointerInputEventProcessor.processCancel()
// Assert
val log1 =
pointerInputFilter1.log.filter {
it is OnPointerEventFilterEntry || it is OnCancelFilterEntry
}
val log2 =
pointerInputFilter2.log.filter {
it is OnPointerEventFilterEntry || it is OnCancelFilterEntry
}
// Verify call count
assertThat(log1).hasSize(PointerEventPass.values().size + 1)
assertThat(log2).hasSize(PointerEventPass.values().size + 1)
// Verify call values
var index = 0
PointerEventPass.values().forEach { pass ->
log1.verifyOnPointerEventCall(
index = index,
expectedEvent = pointerEventOf(expectedChange1),
expectedPass = pass
)
log2.verifyOnPointerEventCall(
index = index,
expectedEvent = pointerEventOf(expectedChange2),
expectedPass = pass
)
index++
}
log1.verifyOnCancelCall(index)
log2.verifyOnCancelCall(index)
}
@Test
fun processCancel_downMoveCancel_pimOnlyReceivesCorrectDownMoveCancel() {
// Arrange
val pointerInputFilter = PointerInputFilterMock()
val layoutNode = LayoutNode(
0, 0, 500, 500,
PointerInputModifierImpl2(pointerInputFilter)
)
addToRoot(layoutNode)
val down =
PointerInputEvent(
7,
5,
Offset(200f, 200f),
true
)
val move =
PointerInputEvent(
7,
10,
Offset(300f, 300f),
true
)
val expectedDown =
PointerInputChange(
id = PointerId(7),
5,
Offset(200f, 200f),
true,
5,
Offset(200f, 200f),
false,
isInitiallyConsumed = false
)
val expectedMove =
PointerInputChange(
id = PointerId(7),
10,
Offset(300f, 300f),
true,
5,
Offset(200f, 200f),
true,
isInitiallyConsumed = false
)
// Act
pointerInputEventProcessor.process(down)
pointerInputEventProcessor.process(move)
pointerInputEventProcessor.processCancel()
// Assert
val log = pointerInputFilter.log.filter {
it is OnPointerEventFilterEntry || it is OnCancelFilterEntry
}
// Verify call count
assertThat(log).hasSize(PointerEventPass.values().size * 2 + 1)
// Verify call values
var index = 0
PointerEventPass.values().forEach { pass ->
log.verifyOnPointerEventCall(
index = index,
expectedEvent = pointerEventOf(expectedDown),
expectedPass = pass
)
index++
}
PointerEventPass.values().forEach { pass ->
log.verifyOnPointerEventCall(
index = index,
expectedEvent = pointerEventOf(expectedMove),
expectedPass = pass
)
index++
}
log.verifyOnCancelCall(index)
}
@Test
fun processCancel_downCancelMoveUp_pimOnlyReceivesCorrectDownCancel() {
// Arrange
val pointerInputFilter = PointerInputFilterMock()
val layoutNode = LayoutNode(
0, 0, 500, 500,
PointerInputModifierImpl2(pointerInputFilter)
)
addToRoot(layoutNode)
val down =
PointerInputEvent(
7,
5,
Offset(200f, 200f),
true
)
val expectedDown =
PointerInputChange(
id = PointerId(7),
5,
Offset(200f, 200f),
true,
5,
Offset(200f, 200f),
false,
isInitiallyConsumed = false
)
// Act
pointerInputEventProcessor.process(down)
pointerInputEventProcessor.processCancel()
// Assert
val log = pointerInputFilter.log.filter {
it is OnPointerEventFilterEntry || it is OnCancelFilterEntry
}
// Verify call count
assertThat(log).hasSize(PointerEventPass.values().size + 1)
// Verify call values
var index = 0
PointerEventPass.values().forEach { pass ->
log.verifyOnPointerEventCall(
index = index,
expectedEvent = pointerEventOf(expectedDown),
expectedPass = pass
)
index++
}
log.verifyOnCancelCall(index)
}
@Test
fun processCancel_downCancelDown_pimOnlyReceivesCorrectDownCancelDown() {
// Arrange
val pointerInputFilter = PointerInputFilterMock()
val layoutNode = LayoutNode(
0, 0, 500, 500,
PointerInputModifierImpl2(
pointerInputFilter
)
)
addToRoot(layoutNode)
val down1 =
PointerInputEvent(
7,
5,
Offset(200f, 200f),
true
)
val down2 =
PointerInputEvent(
7,
10,
Offset(200f, 200f),
true
)
val expectedDown1 =
PointerInputChange(
id = PointerId(7),
5,
Offset(200f, 200f),
true,
5,
Offset(200f, 200f),
false,
isInitiallyConsumed = false
)
val expectedDown2 =
PointerInputChange(
id = PointerId(7),
10,
Offset(200f, 200f),
true,
10,
Offset(200f, 200f),
false,
isInitiallyConsumed = false
)
// Act
pointerInputEventProcessor.process(down1)
pointerInputEventProcessor.processCancel()
pointerInputEventProcessor.process(down2)
// Assert
val log = pointerInputFilter.log.filter {
it is OnPointerEventFilterEntry || it is OnCancelFilterEntry
}
// Verify call count
assertThat(log).hasSize(PointerEventPass.values().size * 2 + 1)
// Verify call values
var index = 0
PointerEventPass.values().forEach { pass ->
log.verifyOnPointerEventCall(
index = index,
expectedEvent = pointerEventOf(expectedDown1),
expectedPass = pass
)
index++
}
log.verifyOnCancelCall(index)
index++
PointerEventPass.values().forEach { pass ->
log.verifyOnPointerEventCall(
index = index,
expectedEvent = pointerEventOf(expectedDown2),
expectedPass = pass
)
index++
}
}
@Test
fun process_layoutNodeRemovedDuringInput_correctPointerInputChangesReceived() {
// Arrange
val childPointerInputFilter = PointerInputFilterMock()
val childLayoutNode = LayoutNode(
0, 0, 100, 100,
PointerInputModifierImpl2(childPointerInputFilter)
)
val parentPointerInputFilter = PointerInputFilterMock()
val parentLayoutNode: LayoutNode = LayoutNode(
0, 0, 100, 100,
PointerInputModifierImpl2(parentPointerInputFilter)
).apply {
insertAt(0, childLayoutNode)
}
addToRoot(parentLayoutNode)
val offset = Offset(50f, 50f)
val down = PointerInputEvent(0, 7, offset, true)
val up = PointerInputEvent(0, 11, offset, false)
val expectedDownChange =
PointerInputChange(
id = PointerId(0),
7,
offset,
true,
7,
offset,
false,
isInitiallyConsumed = false
)
val expectedUpChange =
PointerInputChange(
id = PointerId(0),
11,
offset,
false,
7,
offset,
true,
isInitiallyConsumed = false
)
// Act
pointerInputEventProcessor.process(down)
parentLayoutNode.removeAt(0, 1)
pointerInputEventProcessor.process(up)
// Assert
val parentLog = parentPointerInputFilter.log.getOnPointerEventFilterLog()
val childLog = childPointerInputFilter.log.getOnPointerEventFilterLog()
// Verify call count
assertThat(parentLog).hasSize(PointerEventPass.values().size * 2)
assertThat(childLog).hasSize(PointerEventPass.values().size)
// Verify call values
parentLog.verifyOnPointerEventCall(
index = 0,
expectedEvent = pointerEventOf(expectedDownChange),
expectedPass = PointerEventPass.Initial
)
parentLog.verifyOnPointerEventCall(
index = 1,
expectedEvent = pointerEventOf(expectedDownChange),
expectedPass = PointerEventPass.Main
)
parentLog.verifyOnPointerEventCall(
index = 2,
expectedEvent = pointerEventOf(expectedDownChange),
expectedPass = PointerEventPass.Final
)
parentLog.verifyOnPointerEventCall(
index = 3,
expectedEvent = pointerEventOf(expectedUpChange),
expectedPass = PointerEventPass.Initial
)
parentLog.verifyOnPointerEventCall(
index = 4,
expectedEvent = pointerEventOf(expectedUpChange),
expectedPass = PointerEventPass.Main
)
parentLog.verifyOnPointerEventCall(
index = 5,
expectedEvent = pointerEventOf(expectedUpChange),
expectedPass = PointerEventPass.Final
)
childLog.verifyOnPointerEventCall(
index = 0,
expectedEvent = pointerEventOf(expectedDownChange),
expectedPass = PointerEventPass.Initial
)
childLog.verifyOnPointerEventCall(
index = 1,
expectedEvent = pointerEventOf(expectedDownChange),
expectedPass = PointerEventPass.Main
)
childLog.verifyOnPointerEventCall(
index = 2,
expectedEvent = pointerEventOf(expectedDownChange),
expectedPass = PointerEventPass.Final
)
}
@Test
fun process_layoutNodeRemovedDuringInput_cancelDispatchedToCorrectPointerInputModifierImpl2() {
// Arrange
val childPointerInputFilter = PointerInputFilterMock()
val childLayoutNode = LayoutNode(
0, 0, 100, 100,
PointerInputModifierImpl2(childPointerInputFilter)
)
val parentPointerInputFilter = PointerInputFilterMock()
val parentLayoutNode: LayoutNode = LayoutNode(
0, 0, 100, 100,
PointerInputModifierImpl2(parentPointerInputFilter)
).apply {
insertAt(0, childLayoutNode)
}
addToRoot(parentLayoutNode)
val down =
PointerInputEvent(0, 7, Offset(50f, 50f), true)
val up = PointerInputEvent(0, 11, Offset(50f, 50f), false)
// Act
pointerInputEventProcessor.process(down)
parentLayoutNode.removeAt(0, 1)
pointerInputEventProcessor.process(up)
// Assert
assertThat(childPointerInputFilter.log.getOnCancelFilterLog()).hasSize(1)
assertThat(parentPointerInputFilter.log.getOnCancelFilterLog()).hasSize(0)
}
@Test
fun process_pointerInputModifierRemovedDuringInput_correctPointerInputChangesReceived() {
// Arrange
val childPointerInputFilter = PointerInputFilterMock()
val childLayoutNode = LayoutNode(
0, 0, 100, 100,
PointerInputModifierImpl2(
childPointerInputFilter
)
)
val parentPointerInputFilter = PointerInputFilterMock()
val parentLayoutNode: LayoutNode = LayoutNode(
0, 0, 100, 100,
PointerInputModifierImpl2(
parentPointerInputFilter
)
).apply {
insertAt(0, childLayoutNode)
}
addToRoot(parentLayoutNode)
val offset = Offset(50f, 50f)
val down = PointerInputEvent(0, 7, offset, true)
val up = PointerInputEvent(0, 11, offset, false)
val expectedDownChange =
PointerInputChange(
id = PointerId(0),
7,
offset,
true,
7,
offset,
false,
isInitiallyConsumed = false
)
val expectedUpChange =
PointerInputChange(
id = PointerId(0),
11,
offset,
false,
7,
offset,
true,
isInitiallyConsumed = false
)
// Act
pointerInputEventProcessor.process(down)
childLayoutNode.modifier = Modifier
pointerInputEventProcessor.process(up)
// Assert
val parentLog = parentPointerInputFilter.log.getOnPointerEventFilterLog()
val childLog = childPointerInputFilter.log.getOnPointerEventFilterLog()
// Verify call count
assertThat(parentLog).hasSize(PointerEventPass.values().size * 2)
assertThat(childLog).hasSize(PointerEventPass.values().size)
// Verify call values
parentLog.verifyOnPointerEventCall(
index = 0,
expectedEvent = pointerEventOf(expectedDownChange),
expectedPass = PointerEventPass.Initial
)
parentLog.verifyOnPointerEventCall(
index = 1,
expectedEvent = pointerEventOf(expectedDownChange),
expectedPass = PointerEventPass.Main
)
parentLog.verifyOnPointerEventCall(
index = 2,
expectedEvent = pointerEventOf(expectedDownChange),
expectedPass = PointerEventPass.Final
)
parentLog.verifyOnPointerEventCall(
index = 3,
expectedEvent = pointerEventOf(expectedUpChange),
expectedPass = PointerEventPass.Initial
)
parentLog.verifyOnPointerEventCall(
index = 4,
expectedEvent = pointerEventOf(expectedUpChange),
expectedPass = PointerEventPass.Main
)
parentLog.verifyOnPointerEventCall(
index = 5,
expectedEvent = pointerEventOf(expectedUpChange),
expectedPass = PointerEventPass.Final
)
childLog.verifyOnPointerEventCall(
index = 0,
expectedEvent = pointerEventOf(expectedDownChange),
expectedPass = PointerEventPass.Initial
)
childLog.verifyOnPointerEventCall(
index = 1,
expectedEvent = pointerEventOf(expectedDownChange),
expectedPass = PointerEventPass.Main
)
childLog.verifyOnPointerEventCall(
index = 2,
expectedEvent = pointerEventOf(expectedDownChange),
expectedPass = PointerEventPass.Final
)
}
@Test
fun process_pointerInputModifierRemovedDuringInput_cancelDispatchedToCorrectPim() {
// Arrange
val childPointerInputFilter = PointerInputFilterMock()
val childLayoutNode = LayoutNode(
0, 0, 100, 100,
PointerInputModifierImpl2(childPointerInputFilter)
)
val parentPointerInputFilter = PointerInputFilterMock()
val parentLayoutNode: LayoutNode = LayoutNode(
0, 0, 100, 100,
PointerInputModifierImpl2(parentPointerInputFilter)
).apply {
insertAt(0, childLayoutNode)
}
addToRoot(parentLayoutNode)
val down =
PointerInputEvent(0, 7, Offset(50f, 50f), true)
val up =
PointerInputEvent(0, 11, Offset(50f, 50f), false)
// Act
pointerInputEventProcessor.process(down)
childLayoutNode.modifier = Modifier
pointerInputEventProcessor.process(up)
// Assert
assertThat(childPointerInputFilter.log.getOnCancelFilterLog()).hasSize(1)
assertThat(parentPointerInputFilter.log.getOnCancelFilterLog()).hasSize(0)
}
@Test
fun process_downNoPointerInputModifiers_nothingInteractedWithAndNoMovementConsumed() {
val pointerInputEvent =
PointerInputEvent(0, 7, Offset(0f, 0f), true)
val result: ProcessResult = pointerInputEventProcessor.process(pointerInputEvent)
assertThat(result).isEqualTo(
ProcessResult(
dispatchedToAPointerInputModifier = false,
anyMovementConsumed = false
)
)
}
@Test
fun process_downNoPointerInputModifiersHit_nothingInteractedWithAndNoMovementConsumed() {
// Arrange
val pointerInputFilter = PointerInputFilterMock()
val layoutNode = LayoutNode(
0, 0, 1, 1,
PointerInputModifierImpl2(
pointerInputFilter
)
)
addToRoot(layoutNode)
val offsets =
listOf(
Offset(-1f, 0f),
Offset(0f, -1f),
Offset(1f, 0f),
Offset(0f, 1f)
)
val pointerInputEvent =
PointerInputEvent(
11,
(offsets.indices).map {
PointerInputEventData(it, 11, offsets[it], true)
}
)
// Act
val result: ProcessResult = pointerInputEventProcessor.process(pointerInputEvent)
// Assert
assertThat(result).isEqualTo(
ProcessResult(
dispatchedToAPointerInputModifier = false,
anyMovementConsumed = false
)
)
}
@Test
fun process_downPointerInputModifierHit_somethingInteractedWithAndNoMovementConsumed() {
// Arrange
val pointerInputFilter = PointerInputFilterMock()
val layoutNode = LayoutNode(
0, 0, 1, 1,
PointerInputModifierImpl2(
pointerInputFilter
)
)
addToRoot(layoutNode)
val pointerInputEvent =
PointerInputEvent(0, 11, Offset(0f, 0f), true)
// Act
val result = pointerInputEventProcessor.process(pointerInputEvent)
// Assert
assertThat(result).isEqualTo(
ProcessResult(
dispatchedToAPointerInputModifier = true,
anyMovementConsumed = false
)
)
}
@Test
fun process_downHitsPifRemovedPointerMoves_nothingInteractedWithAndNoMovementConsumed() {
// Arrange
val pointerInputFilter = PointerInputFilterMock()
val layoutNode = LayoutNode(
0, 0, 1, 1,
PointerInputModifierImpl2(
pointerInputFilter
)
)
addToRoot(layoutNode)
val down = PointerInputEvent(0, 11, Offset(0f, 0f), true)
pointerInputEventProcessor.process(down)
val move = PointerInputEvent(0, 11, Offset(1f, 0f), true)
// Act
testOwner.root.removeAt(0, 1)
val result = pointerInputEventProcessor.process(move)
// Assert
assertThat(result).isEqualTo(
ProcessResult(
dispatchedToAPointerInputModifier = false,
anyMovementConsumed = false
)
)
}
@Test
fun process_downHitsPointerMovesNothingConsumed_somethingInteractedWithAndNoMovementConsumed() {
// Arrange
val pointerInputFilter = PointerInputFilterMock()
val layoutNode = LayoutNode(
0, 0, 1, 1,
PointerInputModifierImpl2(
pointerInputFilter
)
)
addToRoot(layoutNode)
val down = PointerInputEvent(0, 11, Offset(0f, 0f), true)
pointerInputEventProcessor.process(down)
val move = PointerInputEvent(0, 11, Offset(1f, 0f), true)
// Act
val result = pointerInputEventProcessor.process(move)
// Assert
assertThat(result).isEqualTo(
ProcessResult(
dispatchedToAPointerInputModifier = true,
anyMovementConsumed = false
)
)
}
@Test
fun process_downHitsPointerMovementConsumed_somethingInteractedWithAndMovementConsumed() {
// Arrange
val pointerInputFilter: PointerInputFilter =
PointerInputFilterMock(
pointerEventHandler = { pointerEvent, pass, _ ->
if (pass == PointerEventPass.Initial) {
pointerEvent.changes.forEach {
if (it.positionChange() != Offset.Zero) it.consume()
}
}
}
)
val layoutNode = LayoutNode(
0, 0, 1, 1,
PointerInputModifierImpl2(
pointerInputFilter
)
)
addToRoot(layoutNode)
val down = PointerInputEvent(0, 11, Offset(0f, 0f), true)
pointerInputEventProcessor.process(down)
val move = PointerInputEvent(0, 11, Offset(1f, 0f), true)
// Act
val result = pointerInputEventProcessor.process(move)
// Assert
assertThat(result).isEqualTo(
ProcessResult(
dispatchedToAPointerInputModifier = true,
anyMovementConsumed = true
)
)
}
@Test
fun processResult_trueTrue_propValuesAreCorrect() {
val processResult1 = ProcessResult(
dispatchedToAPointerInputModifier = true,
anyMovementConsumed = true
)
assertThat(processResult1.dispatchedToAPointerInputModifier).isTrue()
assertThat(processResult1.anyMovementConsumed).isTrue()
}
@Test
fun processResult_trueFalse_propValuesAreCorrect() {
val processResult1 = ProcessResult(
dispatchedToAPointerInputModifier = true,
anyMovementConsumed = false
)
assertThat(processResult1.dispatchedToAPointerInputModifier).isTrue()
assertThat(processResult1.anyMovementConsumed).isFalse()
}
@Test
fun processResult_falseTrue_propValuesAreCorrect() {
val processResult1 = ProcessResult(
dispatchedToAPointerInputModifier = false,
anyMovementConsumed = true
)
assertThat(processResult1.dispatchedToAPointerInputModifier).isFalse()
assertThat(processResult1.anyMovementConsumed).isTrue()
}
@Test
fun processResult_falseFalse_propValuesAreCorrect() {
val processResult1 = ProcessResult(
dispatchedToAPointerInputModifier = false,
anyMovementConsumed = false
)
assertThat(processResult1.dispatchedToAPointerInputModifier).isFalse()
assertThat(processResult1.anyMovementConsumed).isFalse()
}
@Test
fun buttonsPressed() {
// Arrange
val pointerInputFilter = PointerInputFilterMock()
val layoutNode = LayoutNode(
0,
0,
500,
500,
PointerInputModifierImpl2(
pointerInputFilter
)
)
addToRoot(layoutNode)
class ButtonValidation(
vararg pressedValues: Int,
val primary: Boolean = false,
val secondary: Boolean = false,
val tertiary: Boolean = false,
val back: Boolean = false,
val forward: Boolean = false,
val anyPressed: Boolean = true,
) {
val pressedValues = pressedValues
}
val buttonCheckerMap = mapOf(
MotionEvent.BUTTON_PRIMARY to ButtonValidation(0, primary = true),
MotionEvent.BUTTON_SECONDARY to ButtonValidation(1, secondary = true),
MotionEvent.BUTTON_TERTIARY to ButtonValidation(2, tertiary = true),
MotionEvent.BUTTON_STYLUS_PRIMARY to ButtonValidation(0, primary = true),
MotionEvent.BUTTON_STYLUS_SECONDARY to ButtonValidation(1, secondary = true),
MotionEvent.BUTTON_BACK to ButtonValidation(3, back = true),
MotionEvent.BUTTON_FORWARD to ButtonValidation(4, forward = true),
MotionEvent.BUTTON_PRIMARY or MotionEvent.BUTTON_TERTIARY to
ButtonValidation(0, 2, primary = true, tertiary = true),
MotionEvent.BUTTON_BACK or MotionEvent.BUTTON_STYLUS_PRIMARY to
ButtonValidation(0, 3, primary = true, back = true),
0 to ButtonValidation(anyPressed = false)
)
for (entry in buttonCheckerMap) {
val buttonState = entry.key
val validator = entry.value
val event = PointerInputEvent(
0,
listOf(PointerInputEventData(0, 0L, Offset.Zero, true)),
MotionEvent.obtain(
0L,
0L,
MotionEvent.ACTION_DOWN,
1,
arrayOf(PointerProperties(1, MotionEvent.TOOL_TYPE_MOUSE)),
arrayOf(PointerCoords(0f, 0f)),
0,
buttonState,
0.1f,
0.1f,
0,
0,
InputDevice.SOURCE_MOUSE,
0
)
)
pointerInputEventProcessor.process(event)
with(
(pointerInputFilter.log.last() as OnPointerEventFilterEntry).pointerEvent.buttons
) {
assertThat(isPrimaryPressed).isEqualTo(validator.primary)
assertThat(isSecondaryPressed).isEqualTo(validator.secondary)
assertThat(isTertiaryPressed).isEqualTo(validator.tertiary)
assertThat(isBackPressed).isEqualTo(validator.back)
assertThat(isForwardPressed).isEqualTo(validator.forward)
assertThat(areAnyPressed).isEqualTo(validator.anyPressed)
val firstIndex = validator.pressedValues.firstOrNull() ?: -1
val lastIndex = validator.pressedValues.lastOrNull() ?: -1
assertThat(indexOfFirstPressed()).isEqualTo(firstIndex)
assertThat(indexOfLastPressed()).isEqualTo(lastIndex)
for (i in 0..10) {
assertThat(isPressed(i)).isEqualTo(validator.pressedValues.contains(i))
}
}
}
}
@Test
fun metaState() {
// Arrange
val pointerInputFilter = PointerInputFilterMock()
val layoutNode = LayoutNode(
0,
0,
500,
500,
PointerInputModifierImpl2(
pointerInputFilter
)
)
addToRoot(layoutNode)
class MetaValidation(
val control: Boolean = false,
val meta: Boolean = false,
val alt: Boolean = false,
val shift: Boolean = false,
val sym: Boolean = false,
val function: Boolean = false,
val capsLock: Boolean = false,
val scrollLock: Boolean = false,
val numLock: Boolean = false
)
val buttonCheckerMap = mapOf(
AndroidKeyEvent.META_CTRL_ON to MetaValidation(control = true),
AndroidKeyEvent.META_META_ON to MetaValidation(meta = true),
AndroidKeyEvent.META_ALT_ON to MetaValidation(alt = true),
AndroidKeyEvent.META_SYM_ON to MetaValidation(sym = true),
AndroidKeyEvent.META_SHIFT_ON to MetaValidation(shift = true),
AndroidKeyEvent.META_FUNCTION_ON to MetaValidation(function = true),
AndroidKeyEvent.META_CAPS_LOCK_ON to MetaValidation(capsLock = true),
AndroidKeyEvent.META_SCROLL_LOCK_ON to MetaValidation(scrollLock = true),
AndroidKeyEvent.META_NUM_LOCK_ON to MetaValidation(numLock = true),
AndroidKeyEvent.META_CTRL_ON or AndroidKeyEvent.META_SHIFT_ON or
AndroidKeyEvent.META_NUM_LOCK_ON to
MetaValidation(control = true, shift = true, numLock = true),
0 to MetaValidation(),
)
for (entry in buttonCheckerMap) {
val metaState = entry.key
val validator = entry.value
val event = PointerInputEvent(
0,
listOf(PointerInputEventData(0, 0L, Offset.Zero, true)),
MotionEvent.obtain(
0L,
0L,
MotionEvent.ACTION_DOWN,
1,
arrayOf(PointerProperties(1, MotionEvent.TOOL_TYPE_MOUSE)),
arrayOf(PointerCoords(0f, 0f)),
metaState,
0,
0.1f,
0.1f,
0,
0,
InputDevice.SOURCE_MOUSE,
0
)
)
pointerInputEventProcessor.process(event)
val keyboardModifiers = (pointerInputFilter.log.last() as OnPointerEventFilterEntry)
.pointerEvent.keyboardModifiers
with(keyboardModifiers) {
assertThat(isCtrlPressed).isEqualTo(validator.control)
assertThat(isMetaPressed).isEqualTo(validator.meta)
assertThat(isAltPressed).isEqualTo(validator.alt)
assertThat(isAltGraphPressed).isFalse()
assertThat(isSymPressed).isEqualTo(validator.sym)
assertThat(isShiftPressed).isEqualTo(validator.shift)
assertThat(isFunctionPressed).isEqualTo(validator.function)
assertThat(isCapsLockOn).isEqualTo(validator.capsLock)
assertThat(isScrollLockOn).isEqualTo(validator.scrollLock)
assertThat(isNumLockOn).isEqualTo(validator.numLock)
}
}
}
private fun PointerInputEventProcessor.process(event: PointerInputEvent) =
process(event, positionCalculator)
}
private class PointerInputModifierImpl2(override val pointerInputFilter: PointerInputFilter) :
PointerInputModifier
internal fun LayoutNode(x: Int, y: Int, x2: Int, y2: Int, modifier: Modifier = Modifier) =
LayoutNode().apply {
this.modifier = Modifier
.layout { measurable, constraints ->
val placeable = measurable.measure(constraints)
layout(placeable.width, placeable.height) {
placeable.place(x, y)
}
}
.then(modifier)
measurePolicy = object : LayoutNode.NoIntrinsicsMeasurePolicy("not supported") {
override fun MeasureScope.measure(
measurables: List<Measurable>,
constraints: Constraints
): MeasureResult =
innerCoordinator.layout(x2 - x, y2 - y) {
measurables.forEach { it.measure(constraints).place(0, 0) }
}
}
}
@OptIn(ExperimentalComposeUiApi::class, InternalCoreApi::class)
private class TestOwner : Owner {
val onEndListeners = mutableListOf<() -> Unit>()
var position: IntOffset = IntOffset.Zero
override val root = LayoutNode(0, 0, 500, 500)
private val delegate = MeasureAndLayoutDelegate(root)
init {
root.attach(this)
delegate.updateRootConstraints(Constraints(maxWidth = 500, maxHeight = 500))
}
override fun requestFocus(): Boolean = false
override val rootForTest: RootForTest
get() = TODO("Not yet implemented")
override val hapticFeedBack: HapticFeedback
get() = TODO("Not yet implemented")
override val inputModeManager: InputModeManager
get() = TODO("Not yet implemented")
override val clipboardManager: ClipboardManager
get() = TODO("Not yet implemented")
override val accessibilityManager: AccessibilityManager
get() = TODO("Not yet implemented")
override val graphicsContext: GraphicsContext
get() = TODO("Not yet implemented")
override val dragAndDropManager: DragAndDropManager
get() = TODO("Not yet implemented")
override val textToolbar: TextToolbar
get() = TODO("Not yet implemented")
override val autofillTree: AutofillTree
get() = TODO("Not yet implemented")
override val autofill: Autofill?
get() = null
override val density: Density
get() = Density(1f)
override val textInputService: TextInputService
get() = TODO("Not yet implemented")
override val softwareKeyboardController: SoftwareKeyboardController
get() = TODO("Not yet implemented")
override suspend fun textInputSession(
session: suspend PlatformTextInputSessionScope.() -> Nothing
): Nothing {
TODO("Not yet implemented")
}
override fun screenToLocal(positionOnScreen: Offset): Offset {
TODO("Not yet implemented")
}
override fun localToScreen(localPosition: Offset): Offset {
TODO("Not yet implemented")
}
override fun localToScreen(localTransform: Matrix) {
TODO("Not yet implemented")
}
override val pointerIconService: PointerIconService
get() = TODO("Not yet implemented")
override val focusOwner: FocusOwner
get() = TODO("Not yet implemented")
override val windowInfo: WindowInfo
get() = TODO("Not yet implemented")
@Deprecated(
"fontLoader is deprecated, use fontFamilyResolver",
replaceWith = ReplaceWith("fontFamilyResolver")
)
@Suppress("OverridingDeprecatedMember", "DEPRECATION")
override val fontLoader: Font.ResourceLoader
get() = TODO("Not yet implemented")
override val fontFamilyResolver: FontFamily.Resolver
get() = TODO("Not yet implemented")
override val layoutDirection: LayoutDirection
get() = LayoutDirection.Ltr
override var showLayoutBounds: Boolean
get() = false
set(@Suppress("UNUSED_PARAMETER") value) {}
override fun onRequestMeasure(
layoutNode: LayoutNode,
affectsLookahead: Boolean,
forceRequest: Boolean,
scheduleMeasureAndLayout: Boolean
) {
if (affectsLookahead) {
delegate.requestLookaheadRemeasure(layoutNode)
} else {
delegate.requestRemeasure(layoutNode)
}
}
override fun onRequestRelayout(
layoutNode: LayoutNode,
affectsLookahead: Boolean,
forceRequest: Boolean
) {
if (affectsLookahead) {
delegate.requestLookaheadRelayout(layoutNode)
} else {
delegate.requestRelayout(layoutNode)
}
}
override fun requestOnPositionedCallback(layoutNode: LayoutNode) {
TODO("Not yet implemented")
}
override fun onAttach(node: LayoutNode) {
}
override fun onDetach(node: LayoutNode) {
}
override fun calculatePositionInWindow(localPosition: Offset): Offset =
localPosition + position.toOffset()
override fun calculateLocalPosition(positionInWindow: Offset): Offset =
positionInWindow - position.toOffset()
override fun measureAndLayout(sendPointerUpdate: Boolean) {
delegate.measureAndLayout()
}
override fun measureAndLayout(layoutNode: LayoutNode, constraints: Constraints) {
delegate.measureAndLayout(layoutNode, constraints)
}
override fun forceMeasureTheSubtree(layoutNode: LayoutNode, affectsLookahead: Boolean) {
delegate.forceMeasureTheSubtree(layoutNode, affectsLookahead)
}
override fun createLayer(
drawBlock: (Canvas) -> Unit,
invalidateParentLayer: () -> Unit,
explicitLayer: GraphicsLayer?
): OwnedLayer {
TODO("Not yet implemented")
}
override fun onSemanticsChange() {
}
override fun onLayoutChange(layoutNode: LayoutNode) {
}
override fun getFocusDirection(keyEvent: KeyEvent): FocusDirection? {
TODO("Not yet implemented")
}
override val measureIteration: Long
get() = 0
override val viewConfiguration: ViewConfiguration
get() = TODO("Not yet implemented")
override val snapshotObserver = OwnerSnapshotObserver { it.invoke() }
override val modifierLocalManager: ModifierLocalManager = ModifierLocalManager(this)
override val coroutineContext: CoroutineContext =
Executors.newFixedThreadPool(3).asCoroutineDispatcher()
override fun registerOnEndApplyChangesListener(listener: () -> Unit) {
onEndListeners += listener
}
override fun onEndApplyChanges() {
while (onEndListeners.isNotEmpty()) {
onEndListeners.removeAt(0).invoke()
}
}
override fun registerOnLayoutCompletedListener(listener: Owner.OnLayoutCompletedListener) {
TODO("Not yet implemented")
}
override val sharedDrawScope = LayoutNodeDrawScope()
}
private fun List<LogEntry>.verifyOnPointerEventCall(
index: Int,
expectedPif: PointerInputFilter? = null,
expectedEvent: PointerEvent,
expectedPass: PointerEventPass,
expectedBounds: IntSize? = null
) {
val logEntry = this[index]
assertThat(logEntry).isInstanceOf(OnPointerEventFilterEntry::class.java)
val entry = logEntry as OnPointerEventFilterEntry
if (expectedPif != null) {
assertThat(entry.pointerInputFilter).isSameInstanceAs(expectedPif)
}
PointerEventSubject
.assertThat(entry.pointerEvent)
.isStructurallyEqualTo(expectedEvent)
assertThat(entry.pass).isEqualTo(expectedPass)
if (expectedBounds != null) {
assertThat(entry.bounds).isEqualTo(expectedBounds)
}
}
private fun List<LogEntry>.verifyOnCancelCall(
index: Int
) {
val logEntry = this[index]
assertThat(logEntry).isInstanceOf(OnCancelFilterEntry::class.java)
}
| 6 | null | 983 | 7 | 6d53f95e5d979366cf7935ad7f4f14f76a951ea5 | 107,320 | androidx | Apache License 2.0 |
skribenten-backend/src/main/kotlin/no/nav/pensjon/brev/skribenten/routes/Pen.kt | navikt | 375,334,697 | false | {"Kotlin": 1656546, "TypeScript": 153560, "TeX": 12814, "Shell": 9153, "CSS": 6527, "Python": 4661, "Dockerfile": 2199, "JavaScript": 2067, "HTML": 380} | package no.nav.pensjon.brev.skribenten.routes
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.util.*
import no.nav.pensjon.brev.skribenten.auth.UnauthorizedException
import no.nav.pensjon.brev.skribenten.getClaim
import no.nav.pensjon.brev.skribenten.services.*
data class OrderLetterRequest(
val brevkode: String,
val spraak: SpraakKode,
val sakId: Long,
val gjelderPid: String,
val landkode: String? = null,
val mottakerText: String? = null,
)
fun Route.penRoute(penService: PenService, safService: SafService) {
route("/pen") {
post("/extream") {
// // TODO skal vi validere metadata?
// val request = call.receive<OrderLetterRequest>()
// //TODO try to get extra claims when authorizing user instead of using graph service.
// val name = getClaim("name") ?: throw UnauthorizedException("Could not find name of user")
//
// // TODO create respond on error or similar function to avoid boilerplate. RespondOnError?
// val onPremisesSamAccountName: String =
// when (val response = microsoftGraphService.getOnPremisesSamAccountName(call)) {
// is ServiceResult.Ok -> response.result
// is ServiceResult.Error, is ServiceResult.AuthorizationError -> {
// respondWithResult(response)
// return@post
// }
// }
//
// //TODO better error handling.
// // TODO access controls for e-blanketter
// penService.bestillExtreamBrev(call, request, name, onPremisesSamAccountName).map { journalpostId ->
// val error = safService.waitForJournalpostStatusUnderArbeid(call, journalpostId)
// if (error != null) {
// if (error.type == SafService.JournalpostLoadingError.ErrorType.TIMEOUT) {
// call.respond(HttpStatusCode.RequestTimeout, error.error)
// } else {
// call.respondText(text = error.error, status = HttpStatusCode.InternalServerError)
// }
// } else {
// respondWithResult(penService.redigerExtreamBrev(call, journalpostId))
// }
// }
}
post("/doksys") {
// val name = getClaim("name") ?: throw UnauthorizedException("Could not find name of user")
// val request = call.receive<OrderLetterRequest>()
// val onPremisesSamAccountName: String =
// when (val response = microsoftGraphService.getOnPremisesSamAccountName(call)) {
// is ServiceResult.Ok -> response.result
// is ServiceResult.Error, is ServiceResult.AuthorizationError -> {
// respondWithResult(response)
// return@post
// }
// }
// respondWithResult(
// penService.bestillDoksysBrev(call, request, name, onPremisesSamAccountName),
// onError = { _, _ -> },
// )
// when (val response = penService.bestillDoksysBrev(call, request, name, onPremisesSamAccountName)) {
// is ServiceResult.Ok -> {
// val journalpostId = response.result
// respondWithResult(penService.redigerDoksysBrev(call, journalpostId))
// }
//
// is ServiceResult.Error, is ServiceResult.AuthorizationError -> {
// respondWithResult(response)
// return@post
// }
// }
}
//TODO Check access using /tilganger(?). Is there an on behalf of endpoint which checks access?
get("/sak/{sakId}") {
val sakId = call.parameters.getOrFail("sakId")
respondWithResult(penService.hentSak(call, sakId))
}
}
} | 5 | Kotlin | 3 | 1 | d142c620414bd87549bdb2f39a80ae86b4394240 | 4,065 | pensjonsbrev | MIT License |
game-plugins/src/main/kotlin/org/alter/plugins/content/area/edgeville/objs/trapdoor.plugin.kts | AlterRSPS | 421,831,790 | false | null | package org.alter.plugins.content.area.edgeville.objs
val OPEN_SFX = 62
val CLOSE_SFX = 60
on_obj_option(obj = Objs.TRAPDOOR_1579, option = "open") {
open(player, player.getInteractingGameObj())
}
on_obj_option(obj = Objs.TRAPDOOR_1581, option = "close") {
close(player, player.getInteractingGameObj())
}
on_obj_option(obj = Objs.TRAPDOOR_1581, option = "climb-down") {
player.moveTo(3096, 9867)
}
fun open(p: Player, obj: GameObject) {
p.playSound(OPEN_SFX)
p.filterableMessage("You close the trapdoor.")
world.spawn(DynamicObject(obj, Objs.TRAPDOOR_1581))
}
fun close(p: Player, obj: GameObject) {
p.playSound(CLOSE_SFX)
p.filterableMessage("The trapdoor opens...")
world.spawn(DynamicObject(obj, Objs.TRAPDOOR_1579))
} | 8 | null | 33 | 23 | 8d3b3cb38ab6a0e4bed7976cb2dbfcf75bfac9b3 | 763 | Alter | Apache License 2.0 |
src/main/kotlin/best/leafyalex/gainzclient/utils/WebHook.kt | ProbAlex | 861,028,735 | false | {"Kotlin": 145411, "Java": 2465} | package best.leafyalex.gainzclient.utils
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import java.io.BufferedReader
import java.io.DataOutputStream
import java.io.InputStreamReader
import java.net.URL
import javax.net.ssl.HttpsURLConnection
object WebHook {
fun sendEmbed(url: String, embed: JsonObject) {
val body = JsonObject()
body.addProperty("content", "")
body.addProperty("username", "Gainz Watcher")
body.addProperty("avatar_url", "https://media.discordapp.net/attachments/1186644651852169248/1282117921564266593/IMG_0259.png?ex=66de30dd&is=66dcdf5d&hm=bc1c022c6bb1ebe888df5f420b439b056ba29436dd8365cf015daeab5bcab237&=&format=webp&quality=lossless&width=529&height=676")
val arr = JsonArray()
arr.add(embed)
body.add("embeds", arr)
println("Sending webhook with body...")
println(body.toString())
val url = URL(url)
val conn = url.openConnection() as HttpsURLConnection
try {
conn.addRequestProperty("Content-Type", "application/json")
conn.addRequestProperty("User-Agent", "Gainz-Client-Webhook")
conn.doOutput = true
conn.requestMethod = "POST"
DataOutputStream(conn.outputStream).use { it.writeBytes(body.toString()) }
BufferedReader(InputStreamReader(conn.inputStream)).use { bf ->
var line: String?
while (bf.readLine().also { line = it } != null) {
println(line)
}
}
} catch (e: Exception) {
println("bruh")
println(conn.responseMessage)
println(conn.errorStream)
e.printStackTrace()
// just print all the messages
}
}
fun buildEmbed(title: String, description: String, fields: JsonArray, footer: JsonObject, author: JsonObject, thumbnail: JsonObject, color: Int): JsonObject {
val obj = JsonObject()
obj.addProperty("title", title)
if (description != "")
obj.addProperty("description", description)
obj.addProperty("color", color)
obj.add("footer", footer)
obj.add("author", author)
obj.add("thumbnail", thumbnail)
obj.add("fields", fields)
return obj
}
fun buildFields(fields: ArrayList<Map<String, String>>): JsonArray {
val arr = JsonArray()
for (field in fields) {
val obj = JsonObject()
obj.addProperty("name", field["name"])
obj.addProperty("value", field["value"])
obj.addProperty("inline", field["inline"] == "true")
arr.add(obj)
}
return arr
}
fun buildAuthor(name: String, icon: String): JsonObject {
val obj = JsonObject()
obj.addProperty("name", name)
obj.addProperty("icon_url", icon)
return obj
}
fun buildThumbnail(url: String): JsonObject {
val obj = JsonObject()
obj.addProperty("url", url)
return obj
}
fun buildFooter(text: String, icon: String): JsonObject {
val obj = JsonObject()
obj.addProperty("text", text)
obj.addProperty("icon_url", icon)
return obj
}
} | 0 | Kotlin | 0 | 0 | b07663acd80e3c6680ed278b1f2e503d4507d1ce | 3,266 | GainzClient | MIT License |
8vim/src/main/kotlin/inc/flide/vim8/datastore/ui/SwitchPreference.kt | 8VIM | 72,917,629 | false | {"Kotlin": 560253} | package inc.flide.vim8.datastore.ui
import androidx.annotation.DrawableRes
import androidx.compose.foundation.selection.toggleable
import androidx.compose.material3.Switch
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import inc.flide.vim8.datastore.model.PreferenceData
import inc.flide.vim8.datastore.model.PreferenceModel
import inc.flide.vim8.datastore.model.observeAsState
@Composable
internal fun <T : PreferenceModel> PreferenceUiScope<T>.SwitchPreference(
pref: PreferenceData<Boolean>,
modifier: Modifier = Modifier,
@DrawableRes iconId: Int? = null,
iconSpaceReserved: Boolean = this.iconSpaceReserved,
title: String,
summaryOn: String? = null,
summaryOff: String? = null,
summary: String? = null,
enabledIf: PreferenceDataEvaluator = { true },
visibleIf: PreferenceDataEvaluator = { true }
) {
val prefValue by pref.observeAsState()
val evalScope = PreferenceDataEvaluatorScope.instance()
if (this.visibleIf(evalScope) && visibleIf(evalScope)) {
val isEnabled = this.enabledIf(evalScope) && enabledIf(evalScope)
Preference(
modifier = modifier.toggleable(
value = prefValue,
enabled = isEnabled,
role = Role.Switch,
onValueChange = { pref.set(it) }
),
title = title,
iconId = iconId,
iconSpaceReserved = iconSpaceReserved,
summary = when {
prefValue && summaryOn != null -> summaryOn
!prefValue && summaryOff != null -> summaryOff
summary != null -> summary
else -> null
},
enabledIf = enabledIf,
trailing = {
Switch(checked = prefValue, enabled = isEnabled, onCheckedChange = null)
}
)
}
}
| 73 | Kotlin | 61 | 461 | 089482f6bb5f715bc9168b8289957cee865573ae | 1,964 | 8VIM | Apache License 2.0 |
backend/src/main/kotlin/com/denchic45/studiversity/feature/course/work/submission/usecase/FindSubmissionsByWorkUseCase.kt | denchic45 | 435,895,363 | false | null | package com.denchic45.studiversity.feature.course.work.submission.usecase
import com.denchic45.studiversity.feature.course.work.submission.SubmissionRepository
import com.denchic45.studiversity.feature.membership.repository.UserMembershipRepository
import com.denchic45.studiversity.transaction.SuspendTransactionWorker
import com.denchic45.stuiversity.api.role.model.Role
import java.util.*
class FindSubmissionsByWorkUseCase(
private val suspendTransactionWorker: SuspendTransactionWorker,
private val userMembershipRepository: UserMembershipRepository,
private val submissionRepository: SubmissionRepository
) {
suspend operator fun invoke(courseId: UUID, courseWorkId: UUID) = suspendTransactionWorker {
submissionRepository.findByWorkId(
courseId,
courseWorkId,
userMembershipRepository.findMemberIdsByScopeAndRole(courseId, Role.Student.id)
)
}
} | 0 | Kotlin | 0 | 5 | abe66e3c117adfd0cbbaee288b00aaf78acd6772 | 925 | Studiversity | Apache License 2.0 |
app/src/main/java/org/simple/clinic/summary/medicalhistory/MedicalHistorySummaryUpdate.kt | simpledotorg | 132,515,649 | false | null | package org.simple.clinic.summary.medicalhistory
import com.spotify.mobius.Next
import com.spotify.mobius.Next.dispatch
import com.spotify.mobius.Update
import org.simple.clinic.medicalhistory.MedicalHistory
import org.simple.clinic.medicalhistory.MedicalHistoryQuestion.DIAGNOSED_WITH_DIABETES
import org.simple.clinic.medicalhistory.MedicalHistoryQuestion.DIAGNOSED_WITH_HYPERTENSION
import org.simple.clinic.mobius.next
class MedicalHistorySummaryUpdate : Update<MedicalHistorySummaryModel, MedicalHistorySummaryEvent, MedicalHistorySummaryEffect> {
private val diagnosisQuestions = setOf(DIAGNOSED_WITH_HYPERTENSION, DIAGNOSED_WITH_DIABETES)
override fun update(
model: MedicalHistorySummaryModel,
event: MedicalHistorySummaryEvent
): Next<MedicalHistorySummaryModel, MedicalHistorySummaryEffect> {
return when (event) {
is MedicalHistoryLoaded -> next(model.medicalHistoryLoaded(event.medicalHistory))
is SummaryMedicalHistoryAnswerToggled -> medicalHistoryAnswerToggled(event, model.medicalHistory!!)
is CurrentFacilityLoaded -> next(model.currentFacilityLoaded(event.facility))
}
}
private fun medicalHistoryAnswerToggled(
event: SummaryMedicalHistoryAnswerToggled,
savedMedicalHistory: MedicalHistory
): Next<MedicalHistorySummaryModel, MedicalHistorySummaryEffect> {
val effects = mutableSetOf<MedicalHistorySummaryEffect>()
val toggledQuestion = event.question
if (toggledQuestion in diagnosisQuestions) {
effects.add(HideDiagnosisError)
}
val updatedMedicalHistory = savedMedicalHistory.answered(toggledQuestion, event.answer)
effects.add(SaveUpdatedMedicalHistory(updatedMedicalHistory))
return dispatch(effects)
}
}
| 4 | Kotlin | 56 | 179 | 9c8f86e6a9d2b707b746822e078c04f7cec03d53 | 1,735 | simple-android | MIT License |
docs-examples/example-kotlin/src/test/kotlin/io/micronaut/rabbitmq/docs/serdes/ProductInfo.kt | micronaut-projects | 167,575,069 | false | null | package io.micronaut.nats.docs.consumer.custom.type
// tag::clazz[]
class ProductInfo(val size: String?, // <1>
val count: Long, // <2>
val sealed: Boolean)// <3>
// end::clazz[]
| 9 | null | 9 | 19 | ab5234345d3b9986a2dd49c7035a3f71655d6612 | 216 | micronaut-rabbitmq | Apache License 2.0 |
src/main/kotlin/pers/neige/banker/loot/impl/Rank.kt | Neige7 | 624,015,130 | false | null | package pers.neige.banker.loot.impl
import org.bukkit.Bukkit
import org.bukkit.configuration.ConfigurationSection
import pers.neige.banker.loot.LootGenerator
import pers.neige.banker.manager.LootManager
import pers.neige.neigeitems.manager.ActionManager
import java.util.concurrent.ConcurrentHashMap
import kotlin.math.min
class Rank(data: ConfigurationSection) : LootGenerator(data) {
// 获取战利品动作
private val lootAction = let {
var lootAction = data.get("LootAction")
if (lootAction == null) {
lootAction = arrayListOf<Any>()
} else if (lootAction !is List<*>) {
lootAction = arrayListOf(lootAction)
}
lootAction as List<*>
}
private val guaranteeAction: Any? = data.get("GuaranteeAction")
override fun run(
damageData: Map<String, Double>,
sortedDamageData: List<Map.Entry<String, Double>>,
totalDamage: Double,
params: MutableMap<String, String>?
) {
val length = min((lootAction).size, sortedDamageData.size)
// 遍历每个战利品配置
for (index in 0 until length) {
// 获取玩家ID
val name = sortedDamageData[index].key
// 获取在线玩家, 玩家不在线则停止执行
val player = Bukkit.getPlayer(name) ?: continue
// 执行动作
(params?.toMutableMap<String, Any?>() ?: mutableMapOf()).also { map ->
map["rank"] = (index + 1).toString()
map["damage"] = "%.2f".format(damageData[name])
map["totalDamage"] = "%.2f".format(totalDamage)
map["lootAmount"] = lootAction.size
// 执行动作
ActionManager.runAction(
player,
lootAction[index],
map,
map
)
}
}
// 如果存在没领到战利品的人
if (sortedDamageData.size > lootAction.size) {
// 如果存在保底战利品
if (guaranteeAction != null) {
// 发放保底战利品
for (index in lootAction.size until sortedDamageData.size) {
// 获取玩家ID
val name = sortedDamageData[index].key
// 获取在线玩家, 玩家不在线则停止执行
val player = Bukkit.getPlayer(name) ?: continue
(params?.toMutableMap<String, Any?>() ?: mutableMapOf()).also { map ->
map["rank"] = (index + 1).toString()
map["damage"] = "%.2f".format(damageData[name])
map["totalDamage"] = "%.2f".format(totalDamage)
map["lootAmount"] = lootAction.size
// 执行动作
ActionManager.runAction(
player,
lootAction[index],
map,
map
)
}
}
}
}
}
} | 0 | Kotlin | 0 | 0 | dff3b51852ea47d9bc10b8c9444a23063d865dca | 2,963 | Banker | MIT License |
app/src/main/java/android/thortechasia/popularmovie/ui/movie/MoviePresenter.kt | riefist | 160,018,829 | false | null | package android.thortechasia.popularmovie.ui.movie
import android.thortechasia.popularmovie.data.repository.MovieRepository
import android.thortechasia.popularmovie.utils.scheduler.AppSchedulerProvider
import android.thortechasia.popularmovie.utils.scheduler.SchedulerProvider
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.addTo
import io.reactivex.rxkotlin.subscribeBy
import io.reactivex.schedulers.Schedulers
import timber.log.Timber
class MoviePresenter(val movieRepository: MovieRepository,
val compositeDisposable: CompositeDisposable,
val schedulerProvider: SchedulerProvider) : MovieContract.Presenter {
private var mView: MovieContract.View? = null
override fun onAttach(view: MovieContract.View) {
mView = view
}
override fun onDetach() {
mView = null
compositeDisposable.clear()
}
override fun getPopularMovies() {
mView?.showLoading()
movieRepository.getPopularMovies()
.observeOn(schedulerProvider.ui())
.subscribeOn(schedulerProvider.io())
.subscribeBy(
onSuccess = {
mView?.hideLoading()
mView?.showPopularMovies(it)
},
onError = {
mView?.hideLoading()
mView?.failureGetPopularMovies(it)
Timber.e(it)
}
).addTo(compositeDisposable)
}
} | 0 | Kotlin | 2 | 1 | 6ec35276828745ba7e4857c1a586f707e780f981 | 1,530 | PopularMovie | MIT License |
src/i_introduction/_12_Extensions_On_Collections/ExtensionsOnCollections.kt | zhaoqingchris | 75,694,136 | false | null | package i_introduction._12_Extensions_On_Collections
import util.TODO
import util.doc12
fun todoTask12(): Nothing = TODO(
"""
Task 12.
In Kotlin standard library there are lots of extension functions that make the work with collections more convenient.
Rewrite the previous example once more using an extension function 'sortedDescending'.
Kotlin code can be easily mixed with Java code.
Thus in Kotlin we don't introduce our own collections, but use standard Java ones (slightly improved).
Read about read-only and mutable views on Java collections.
""",
documentation = doc12()
)
fun task12(): List<Int> {
val array = arrayListOf(1, 5, 2)
array.sort { i, j -> j - i }
return array
}
| 0 | Kotlin | 0 | 0 | db5b24369a3fb02c0b20f2cd790dd7835a324fad | 763 | kotlin-koans-solution | MIT License |
src/test/kotlin/org/web3j/fabric/shim/ChaincodeDslTest.kt | web3j | 164,084,544 | false | {"Kotlin": 9949} | package org.web3j.fabric.shim
import org.web3j.fabric.shim.ChaincodeDsl.Companion.chaincode
import org.web3j.fabric.shim.ChaincodeDsl.Companion.error
import org.web3j.fabric.shim.ChaincodeDsl.Companion.success
import org.assertj.core.api.Assertions.assertThat
import org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR
import org.hyperledger.fabric.shim.Chaincode.Response.Status.SUCCESS
import org.hyperledger.fabric.shim.ChaincodeStub
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
class ChaincodeDslTest {
private lateinit var stub: ChaincodeStub
private val result = chaincode {
init {
function("success") {
success("message")
}
function("error") {
error("message")
}
function("throwable") {
error(Exception("message"))
}
}
invoke {
function("negate") {
success("OK", getArg<Boolean>(0).not())
}
function("sum") {
var sum = 0
for (i in stringArgs.indices) {
sum += getArg<Int>(i)
}
success("OK", sum)
}
}
}
@Before
fun setUp() {
stub = mock(ChaincodeStub::class.java)
}
@Test
fun testSuccess() {
`when`(stub.function).thenReturn("success")
val response = result.init(stub)
assertThat(response.status).isEqualTo(SUCCESS)
assertThat(response.message).isEqualTo("message")
}
@Test
fun testError() {
`when`(stub.function).thenReturn("error")
val response = result.init(stub)
assertThat(response.status).isEqualTo(INTERNAL_SERVER_ERROR)
assertThat(response.message).isEqualTo("message")
}
@Test
fun testException() {
`when`(stub.function).thenReturn("throwable")
val response = result.init(stub)
assertThat(response.status).isEqualTo(INTERNAL_SERVER_ERROR)
assertThat(response.message).isEqualTo("message")
}
@Test
fun testNegate() {
`when`(stub.function).thenReturn("negate")
`when`(stub.stringArgs).thenReturn(listOf("true"))
val response = result.invoke(stub)
assertThat(response.status).isEqualTo(SUCCESS)
assertThat(response.payload).isEqualTo(false.toString().toByteArray())
}
@Test
fun testSum() {
`when`(stub.function).thenReturn("sum")
`when`(stub.stringArgs).thenReturn(listOf(1, 2, 3).map { it.toString() })
val response = result.invoke(stub)
assertThat(response.status).isEqualTo(SUCCESS)
assertThat(String(response.payload).toInt()).isEqualTo(6)
}
} | 0 | Kotlin | 1 | 2 | 5ae3505b3b143587b48c8e1e65f4e0f63c0af65a | 2,841 | fabric | Apache License 2.0 |
BanknotesCatalogApp/src/main/java/com/pako2k/banknotescatalog/localsource/FlagsLocalDataSource.kt | Pako2K | 746,171,800 | false | {"Kotlin": 553837} | package com.pako2k.banknotescatalog.localsource
import android.content.res.AssetManager
import android.graphics.BitmapFactory
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import kotlinx.coroutines.coroutineScope
import java.io.IOException
private const val FLAGS_DIR = ""
private const val FLAGS_EXT = "png"
class FlagsLocalDataSource (
private val assetManager: AssetManager,
private val sourceAssetsDir : String = FLAGS_DIR,
private val flagsExt : String = FLAGS_EXT
){
suspend fun getFlags() : Map<String,ImageBitmap> = coroutineScope{
getFlagsSync()
/* val tmp = mutableMapOf<String,ImageBitmap>()
try {
val fileNames = assetManager.list(sourceAssetsDir) ?: arrayOf<String>()
for (fileName in fileNames){
try {
val fileIS = assetManager.open(fileName)
val bitmap = BitmapFactory.decodeStream(fileIS)
if (bitmap != null)
tmp[fileName.substringBeforeLast(".$flagsExt")] = bitmap.asImageBitmap()
}
catch (exc : IOException){
}
}
}
catch (exc : IOException){
}
tmp
*/
}
fun getFlagsSync() : Map<String,ImageBitmap> {
val tmp = mutableMapOf<String,ImageBitmap>()
try {
val fileNames = assetManager.list(sourceAssetsDir) ?: arrayOf<String>()
for (fileName in fileNames){
try {
val fileIS = assetManager.open(fileName)
val bitmap = BitmapFactory.decodeStream(fileIS)
if (bitmap != null)
tmp[fileName.substringBeforeLast(".$flagsExt")] = bitmap.asImageBitmap()
}
catch (_: IOException){
}
}
}
catch (_ : IOException){
}
return tmp
}
}
| 0 | Kotlin | 0 | 0 | 7d34e72896434a1fedd78c439eaf0a57899ef97f | 2,001 | BanknotesCatalog | MIT License |
examples/kotlin/src/main/kotlin/com/example/ondeck/postgresql/Queries.kt | sqlc-dev | 193,160,679 | false | null | // Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.16.0
package com.example.ondeck.postgresql
import java.sql.Connection
import java.sql.SQLException
import java.sql.Statement
import java.sql.Types
import java.time.LocalDateTime
interface Queries {
@Throws(SQLException::class)
fun createCity(name: String, slug: String): City?
@Throws(SQLException::class)
fun createVenue(
slug: String,
name: String,
city: String,
spotifyPlaylist: String,
status: Status,
statuses: List<Status>,
tags: List<String>): Int?
@Throws(SQLException::class)
fun deleteVenue(slug: String)
@Throws(SQLException::class)
fun getCity(slug: String): City?
@Throws(SQLException::class)
fun getVenue(slug: String, city: String): Venue?
@Throws(SQLException::class)
fun listCities(): List<City>
@Throws(SQLException::class)
fun listVenues(city: String): List<Venue>
@Throws(SQLException::class)
fun updateCityName(name: String, slug: String)
@Throws(SQLException::class)
fun updateVenueName(name: String, slug: String): Int?
@Throws(SQLException::class)
fun venueCountByCity(): List<VenueCountByCityRow>
}
| 7 | null | 9 | 9,303 | e4fd0793730a3afb8d74a05b78e6f3db0b9f2c90 | 1,206 | sqlc | MIT License |
reaktive/src/commonMain/kotlin/com/badoo/reaktive/single/Repeat.kt | amrfarid140 | 277,184,092 | true | {"Kotlin": 1333783, "Swift": 6264, "HTML": 1109, "Ruby": 150} | package com.badoo.reaktive.single
import com.badoo.reaktive.observable.Observable
import com.badoo.reaktive.observable.repeat
fun <T> Single<T>.repeat(count: Int = -1): Observable<T> = asObservable().repeat(count = count)
| 0 | null | 0 | 0 | 6ae4e8caf147e784f21f16dcc49a6b8fe8ed6d92 | 224 | Reaktive | Apache License 2.0 |
myhairdiary/app/src/main/java/com/example/myhairdiary/register/Register.kt | sungdoolim | 238,624,065 | false | {"Text": 2, "Markdown": 7, "Gradle": 27, "Java Properties": 18, "Shell": 9, "Ignore List": 18, "Batchfile": 9, "Proguard": 9, "Kotlin": 162, "XML": 353, "JSON": 4, "Java": 9} | package com.example.myhairdiary.register
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.myhairdiary.MainActivity
import com.example.myhairdiary.R
import com.example.myhairdiary.designers.designer
import com.example.myhairdiary.firedb.fireDB
import com.google.firebase.firestore.FirebaseFirestore
import kotlinx.android.synthetic.main.activity_register.*
class Register : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register)
val db=fireDB()
register_bt.setOnClickListener(){
var id=etid.getText()
var name=etpw.getText()
db.createData(id.toString(),name.toString())
var intent= Intent(this, MainActivity::class.java)
startActivity(intent)
}
login_bt.setOnClickListener(){
var id=etloginid.text
val pref=getSharedPreferences("ins",0)
var edit=pref.edit()
edit.putString("id",id.toString())
edit.apply()
var firestore = FirebaseFirestore.getInstance()
firestore?.collection("hair_diary").whereEqualTo("id",id.toString()).get()
.addOnCompleteListener {
if(it.isSuccessful){
for(dc in it.result!!.documents){
println("\nget test!!! : ${dc.getString("ttttt")}")
// println("${len+1} : ${dc.toString()}")
edit.putString("perm",dc.toObject(designer::class.java)?.perm.toString())
edit.putString("index",dc.toObject(designer::class.java)?.index.toString())
edit.apply()
}
var intent= Intent(this, MainActivity::class.java)
startActivity(intent)
}else{
println("fail")
}
}
}
}
}
| 1 | null | 1 | 1 | dc08834dafcef20209ba15bcff114f9f55775913 | 2,112 | android_practice | Apache License 2.0 |
app/src/main/java/org/citruscircuits/viewer/fragments/team_details/TeamDetailsFragment.kt | frc1678 | 804,234,032 | false | {"Kotlin": 418437} | package org.citruscircuits.viewer.fragments.team_details
import android.content.Context
import android.os.Bundle
import android.util.AttributeSet
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import org.citruscircuits.viewer.MainViewerActivity
import org.citruscircuits.viewer.R
import org.citruscircuits.viewer.constants.Constants
import org.citruscircuits.viewer.getTeamName
import kotlinx.android.synthetic.main.team_details.view.*
import org.citruscircuits.viewer.constants.Translations
import java.io.File
// The fragment class for the Team Details display that occurs when you click on a
// team in the match details page.
class TeamDetailsFragment : Fragment() {
private var teamNumber: String? = null
private var teamName: String? = null
private var lfm: Boolean = false
private var refreshId: String? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.team_details, container, false)
populateTeamDetailsEssentials(root)
updateDatapointDisplayListView(root)
robotPics(root)
/*
This creates the on menu select listener for the TeamDetails fragment navigation bar.
The purpose of this navigation bar is to switch between the type of data that the
list view in team details displays. The list view adapter contents can be altered
in Constants.kt -> FIELDS_TO_BE_DISPLAYED_TEAM_DETAILS. FIELDS_TO_BE_DISPLAYED_TEAM_DETAILS
is a map of a string key to arraylist<string> value, with each string key being the menu
items and the contents of each arraylist<string> being the specific data points displayed
in each of the menu item's adapter settings sections.
*/
return root
}
// Prepare the TeamDetails page by populating each text view and other XML element
// with its team specific information.
private fun populateTeamDetailsEssentials(root: View) {
// If a fragment intent (bundle arguments) exists from the previous activity (MainViewerActivity),
// then set the team number display on TeamDetails to the team number provided with the intent.
// If the team number from the MainViewerActivity's match schedule list view cell position
// is null, the default display will show '0' for the team number on TeamDetails.
arguments?.let {
teamNumber = it.getString(Constants.TEAM_NUMBER, Constants.NULL_CHARACTER)
teamName = getTeamName(teamNumber!!)
lfm = it.getBoolean("LFM")
}
root.tv_team_number.text = teamNumber.toString()
root.tv_team_name.text = teamName ?: Constants.NULL_CHARACTER
}
// gets the lfm equivalent of each of the given datapoints
private fun getLFMEquivalent(datapointList: List<String>): List<String> {
var lfmDatapoints: MutableList<String> = mutableListOf()
for (datapoint in datapointList) {
if (!Constants.CATEGORY_NAMES.contains(datapoint) && !Constants.TEAM_AND_LFM_SHARED_DATAPOINTS.contains(datapoint)) {
lfmDatapoints.add("lfm_$datapoint")
}
else if (Constants.TEAM_AND_LFM_SHARED_DATAPOINTS.contains(datapoint)) {
lfmDatapoints.add(datapoint)
}
else {
lfmDatapoints.add(Translations.TEAM_TO_LFM_HEADERS[datapoint]?: datapoint)
}
}
return lfmDatapoints
}
// Updates the adapter for the list view of each team in the match details display.
private fun updateDatapointDisplayListView(root: View) {
// We set the adapter for their list view according to
// the team number and the current section. We also include a list of the
// data points we expect to be displayed on the TeamDetails list view.
var user = MainViewerActivity.UserDatapoints.contents?.get("selected")?.asString
var datapoints: MutableList<String> = mutableListOf()
var userdatapoints = MainViewerActivity.UserDatapoints.contents?.get(user)?.asJsonArray
if (userdatapoints != null) {
for (i in userdatapoints) {
if (Constants.FIELDS_TO_BE_DISPLAYED_TEAM_DETAILS.contains(i.asString)) {
datapoints.add(i.asString)
}
}
}
if (lfm) {
root.btn_lfm.text = getString(R.string.to_all_matches)
root.btn_lfm.textSize = 12F
} else {
root.btn_lfm.text = getString(R.string.to_last_four_matches)
root.btn_lfm.textSize = 16F
}
val adapter = TeamDetailsAdapter(
context = requireActivity(),
datapointsDisplayed = if (lfm) getLFMEquivalent(datapoints) else datapoints,
teamNumber = teamNumber!!,
visualDataBar = ("Visual Data Bars" in (if (lfm) getLFMEquivalent(datapoints) else datapoints))
)
if (refreshId == null) {
refreshId = MainViewerActivity.refreshManager.addRefreshListener {
Log.d("data-refresh", "Updated: team-details")
adapter.notifyDataSetChanged()
}
}
root.lv_datapoint_display.adapter = adapter
// Repopulates the list view based on whether LFM is toggled or not
root.btn_lfm.setOnClickListener {
lfm = !lfm
if (lfm) {
root.btn_lfm.text = getString(R.string.to_all_matches)
root.btn_lfm.textSize = 12F
} else {
root.btn_lfm.text = getString(R.string.to_last_four_matches)
root.btn_lfm.textSize = 16F
}
this.arguments?.putBoolean("LFM", lfm)
val adapter = TeamDetailsAdapter(
context = requireActivity(),
datapointsDisplayed = if (lfm) getLFMEquivalent(datapoints) else datapoints,
teamNumber = teamNumber!!,
visualDataBar = ("Visual Data Bars" in (if (lfm) getLFMEquivalent(datapoints) else datapoints))
)
root.lv_datapoint_display.adapter = adapter
}
root.btn_auto_paths.setOnClickListener {
parentFragmentManager.beginTransaction()
.setCustomAnimations(R.anim.fade_in, R.anim.fade_out).addToBackStack(null)
.replace((requireView().parent as ViewGroup).id, AutoPathsFragment().apply {
arguments = bundleOf(Constants.TEAM_NUMBER to teamNumber)
}).commit()
}
}
// Displays a button to view the team's picture if the picture file exists on the phone
private fun robotPics(root: View) {
val robotPicFragmentArguments = Bundle()
val robotPicFragment = RobotPicFragment()
if (!File(
Constants.DOWNLOADS_FOLDER,
"${teamNumber}_full_robot.jpg"
).exists() &&
!File(
Constants.DOWNLOADS_FOLDER,
"${teamNumber}_front.jpg"
).exists() &&
!File(
Constants.DOWNLOADS_FOLDER,
"${teamNumber}_side.jpg"
).exists()
) {
root.robot_pic_button.layoutParams = LinearLayout.LayoutParams(0, 0, 0f)
root.tv_team_number.gravity = Gravity.CENTER_HORIZONTAL
root.tv_team_name.gravity = Gravity.CENTER_HORIZONTAL
} else {
root.robot_pic_button.setOnClickListener {
robotPicFragmentArguments.putString(Constants.TEAM_NUMBER, teamNumber)
robotPicFragment.arguments = robotPicFragmentArguments
requireActivity().supportFragmentManager.beginTransaction()
.addToBackStack(null)
.replace(R.id.nav_host_fragment, robotPicFragment, "robot_pic")
.commit()
}
}
}
override fun onDestroy() {
super.onDestroy()
MainViewerActivity.refreshManager.removeRefreshListener(refreshId)
}
} | 0 | Kotlin | 0 | 0 | f38e2f99c1b16f6f5a89342b4619c19082346b09 | 8,327 | viewer-2024-public | MIT License |
samples/rickymortykmm/shared/src/commonMain/kotlin/io/spherelabs/rickymortykmm/domain/GetCharacterByIdUseCase.kt | getspherelabs | 646,328,849 | false | null | package io.spherelabs.rickymortykmm.domain
import io.spherelabs.rickymortykmm.remote.dto.CharacterDto
import io.spherelabs.rickymortykmm.repository.RickyMortyRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
interface GetCharacterByIdUseCase {
fun execute(id: Int): Flow<Result<CharacterDto>>
}
class DefaultGetCharacterByIdUseCase(
private val repository: RickyMortyRepository
) : GetCharacterByIdUseCase {
override fun execute(id: Int): Flow<Result<CharacterDto>> {
return flow {
try {
emit(Result.success(repository.fetchCharacterById(id)))
} catch (e: Exception) {
emit(Result.failure(e))
}
}
}
}
| 6 | Kotlin | 1 | 9 | 0e6b5aecfcea88d5c6ff7070df2e0ce07edc5457 | 737 | meteor | Apache License 2.0 |
core/ds_component/src/main/java/com/sabufung/app/ds/component/button/Button.kt | sabufung30 | 552,990,093 | false | null | package com.sabufung.app.ds.component.button
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.Dp
import com.sabufung.app.ds.theme.DsSizing
import com.sabufung.app.ds.theme.DsTypography
object Button {
sealed class SizeVariant {
@get:Composable
abstract val labelStyle: TextStyle
@get:Composable
abstract val iconSize: Dp
@get:Composable
abstract val padding: PaddingValues
object Large : SizeVariant() {
override val labelStyle: TextStyle
@Composable
get() = DsTypography.largeStrong
override val iconSize: Dp
@Composable
get() = DsSizing.measure24
override val padding: PaddingValues
@Composable
get() = PaddingValues(DsSizing.spacing16)
}
object Medium : SizeVariant() {
override val labelStyle: TextStyle
@Composable
get() = DsTypography.mediumStrong
override val iconSize: Dp
@Composable
get() = DsSizing.measure20
override val padding: PaddingValues
@Composable
get() = PaddingValues(
start = DsSizing.spacing16,
top = DsSizing.spacing12,
end = DsSizing.spacing16,
bottom = DsSizing.spacing12
)
}
object Small : SizeVariant() {
override val labelStyle: TextStyle
@Composable
get() = DsTypography.xSmallStrong
override val iconSize: Dp
@Composable
get() = DsSizing.measure12
override val padding: PaddingValues
@Composable
get() = PaddingValues(DsSizing.spacing8)
}
}
sealed class Width {
abstract val modifier: Modifier
/**
* use [Modifier.weight] for balancing horizontal weight when it has sibling components
*/
object Fluid : Width() {
override val modifier: Modifier
@get:Composable
get() {
return Modifier.fillMaxWidth()
}
}
class Specified(val width: Dp) : Width() {
override val modifier: Modifier
@get:Composable
get() = Modifier.width(width = width)
}
object Unspecified : Width() {
override val modifier: Modifier
@get:Composable
get() = Modifier.wrapContentWidth()
}
}
}
| 0 | Kotlin | 0 | 0 | 8676c8953db22c321b92c92881debb6e45c17c74 | 2,980 | property-listing | Apache License 2.0 |
app/src/main/java/jp/mihailskuzmins/sugoinihongoapp/models/wordStudy/WordQuizQuestionOptionModel.kt | MihailsKuzmins | 240,947,625 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 10, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 323, "XML": 156, "Java": 1, "JSON": 1} | package jp.mihailskuzmins.sugoinihongoapp.models.wordStudy
import jp.mihailskuzmins.sugoinihongoapp.persistence.models.Word
class WordQuizQuestionOptionModel(
override val original: String,
override val translation: String,
override val transcription: String,
val isCorrect: Boolean
) : Word | 1 | null | 1 | 1 | 57e19b90b4291dc887a92f6d57f9be349373a444 | 297 | sugoi-nihongo-android | Apache License 2.0 |
web-regresjonstest/src/test/kotlin/no/nav/su/se/bakover/web/søknadsbehandling/flyktning/LeggTilFlyktningVilkårIT.kt | navikt | 227,366,088 | false | {"Kotlin": 9239094, "Shell": 4372, "TSQL": 1233, "Dockerfile": 800} | package no.nav.su.se.bakover.web.søknadsbehandling.flyktning
import io.kotest.matchers.shouldBe
import no.nav.su.se.bakover.common.brukerrolle.Brukerrolle
import no.nav.su.se.bakover.common.extensions.desember
import no.nav.su.se.bakover.common.extensions.januar
import no.nav.su.se.bakover.web.SharedRegressionTestData
import no.nav.su.se.bakover.web.sak.assertSakJson
import no.nav.su.se.bakover.web.sak.hent.hentSak
import no.nav.su.se.bakover.web.søknad.digitalUføreSøknadJson
import no.nav.su.se.bakover.web.søknad.ny.NySøknadJson
import no.nav.su.se.bakover.web.søknad.ny.nyDigitalSøknad
import no.nav.su.se.bakover.web.søknadsbehandling.BehandlingJson
import no.nav.su.se.bakover.web.søknadsbehandling.ny.nySøknadsbehandling
import no.nav.su.se.bakover.web.søknadsbehandling.virkningstidspunkt.leggTilVirkningstidspunkt
import org.json.JSONObject
import org.junit.jupiter.api.Test
import org.skyscreamer.jsonassert.JSONAssert
internal class LeggTilFlyktningVilkårIT {
@Test
fun `legg til flyktningvilkår`() {
SharedRegressionTestData.withTestApplicationAndEmbeddedDb {
nyDigitalSøknad(client = this.client).also { nySøknadResponse ->
val sakId = NySøknadJson.Response.hentSakId(nySøknadResponse)
val sakJson = hentSak(sakId, this.client)
val søknadId = NySøknadJson.Response.hentSøknadId(nySøknadResponse)
assertSakJson(
actualSakJson = sakJson,
expectedSaksnummer = 2021,
expectedSøknader = "[${
digitalUføreSøknadJson(
SharedRegressionTestData.fnr,
SharedRegressionTestData.epsFnr,
)
}]",
expectedSakstype = "uføre",
)
nySøknadsbehandling(
sakId = sakId,
søknadId = søknadId,
brukerrolle = Brukerrolle.Saksbehandler,
client = this.client,
).also { nyBehandlingResponse ->
val behandlingId = BehandlingJson.hentBehandlingId(nyBehandlingResponse)
val fraOgMed: String = 1.januar(2022).toString()
val tilOgMed: String = 31.desember(2022).toString()
leggTilVirkningstidspunkt(
sakId = sakId,
behandlingId = behandlingId,
fraOgMed = fraOgMed,
tilOgMed = tilOgMed,
client = this.client,
)
leggTilFlyktningVilkår(
sakId = sakId,
behandlingId = behandlingId,
fraOgMed = fraOgMed,
tilOgMed = tilOgMed,
body = { innvilgetFlyktningVilkårJson(fraOgMed, tilOgMed) },
brukerrolle = Brukerrolle.Saksbehandler,
url = "/saker/$sakId/behandlinger/$behandlingId/flyktning",
client = this.client,
).also { behandlingJson ->
JSONAssert.assertEquals(
JSONObject(BehandlingJson.hentFlyktningVilkår(behandlingJson)).toString(),
//language=JSON
"""
{
"vurderinger": [
{
"resultat": "VilkårOppfylt",
"periode": {
"fraOgMed": "2022-01-01",
"tilOgMed": "2022-12-31"
}
}
],
"resultat": "VilkårOppfylt"
}
""".trimIndent(),
true,
)
BehandlingJson.hentStatus(behandlingJson) shouldBe "OPPRETTET"
}
leggTilFlyktningVilkår(
sakId = sakId,
behandlingId = behandlingId,
fraOgMed = fraOgMed,
tilOgMed = tilOgMed,
body = { avslåttFlyktningVilkårJson(fraOgMed, tilOgMed) },
brukerrolle = Brukerrolle.Saksbehandler,
url = "/saker/$sakId/behandlinger/$behandlingId/flyktning",
client = this.client,
).also { behandlingJson ->
JSONAssert.assertEquals(
JSONObject(BehandlingJson.hentFlyktningVilkår(behandlingJson)).toString(),
//language=JSON
"""
{
"vurderinger": [
{
"resultat": "VilkårIkkeOppfylt",
"periode": {
"fraOgMed": "2022-01-01",
"tilOgMed": "2022-12-31"
}
}
],
"resultat": "VilkårIkkeOppfylt"
}
""".trimIndent(),
true,
)
BehandlingJson.hentStatus(behandlingJson) shouldBe "VILKÅRSVURDERT_AVSLAG"
}
}
}
}
}
}
| 9 | Kotlin | 1 | 1 | d7157394e11b5b3c714a420a96211abb0a53ea45 | 5,869 | su-se-bakover | MIT License |
src/main/java/movies/spring/data/neo4j/SecurityConfig.kt | hriddle | 143,642,375 | true | {"Kotlin": 42155} | package movies.spring.data.neo4j
import movies.spring.data.neo4j.infrastructure.security.TokenAuthenticationFilter
import movies.spring.data.neo4j.infrastructure.security.TokenAuthenticationProvider
import movies.spring.data.neo4j.repositories.UserRepository
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
class SecurityConfig(
val profileRepository: UserRepository,
@Value("\${api.key}") val apiKey: String
) : WebSecurityConfigurerAdapter() {
@Throws(Exception::class)
override fun configure(http: HttpSecurity) {
http.addFilterBefore(TokenAuthenticationFilter(authenticationManager()),
BasicAuthenticationFilter::class.java)
http.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().authorizeRequests()
.antMatchers("/authorization/**", "/public/**").permitAll()
.antMatchers("/**").authenticated()
}
@Throws(Exception::class)
override fun configure(auth: AuthenticationManagerBuilder?) {
auth!!.authenticationProvider(tokenAuthenticationProvider())
}
@Bean
fun tokenAuthenticationProvider() = TokenAuthenticationProvider(profileRepository, apiKey)
}
| 0 | Kotlin | 0 | 0 | 0160ed8beb682720dbfbef42bbf0f5eb5168aa21 | 2,093 | movies-kotlin-spring-data-neo4j | Apache License 2.0 |
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/LungsOff.kt | walter-juan | 868,046,028 | false | {"Kotlin": 34345428} | package com.woowla.compose.icon.collections.tabler.tabler.outline
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.Round
import androidx.compose.ui.graphics.StrokeJoin
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 com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup
public val OutlineGroup.LungsOff: ImageVector
get() {
if (_lungsOff != null) {
return _lungsOff!!
}
_lungsOff = Builder(name = "LungsOff", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(6.583f, 6.608f)
curveToRelative(-1.206f, 1.058f, -2.07f, 2.626f, -2.933f, 5.449f)
curveToRelative(-0.42f, 1.37f, -0.636f, 2.962f, -0.648f, 4.775f)
curveToRelative(-0.012f, 1.675f, 1.261f, 3.054f, 2.877f, 3.161f)
lineToRelative(0.203f, 0.007f)
curveToRelative(1.611f, 0.0f, 2.918f, -1.335f, 2.918f, -2.98f)
verticalLineToRelative(-8.02f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(15.0f, 11.0f)
verticalLineToRelative(-3.743f)
curveToRelative(0.0f, -0.694f, 0.552f, -1.257f, 1.233f, -1.257f)
curveToRelative(0.204f, 0.0f, 0.405f, 0.052f, 0.584f, 0.15f)
lineToRelative(0.13f, 0.083f)
curveToRelative(1.46f, 1.059f, 2.432f, 2.647f, 3.405f, 5.824f)
curveToRelative(0.42f, 1.37f, 0.636f, 2.962f, 0.648f, 4.775f)
curveToRelative(0.0f, 0.063f, 0.0f, 0.125f, 0.0f, 0.187f)
moveToRelative(-1.455f, 2.51f)
curveToRelative(-0.417f, 0.265f, -0.9f, 0.43f, -1.419f, 0.464f)
lineToRelative(-0.202f, 0.007f)
curveToRelative(-1.613f, 0.0f, -2.92f, -1.335f, -2.92f, -2.98f)
verticalLineToRelative(-2.02f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(9.0f, 12.0f)
arcToRelative(2.99f, 2.99f, 0.0f, false, false, 2.132f, -0.89f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(12.0f, 4.0f)
verticalLineToRelative(4.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(3.0f, 3.0f)
lineToRelative(18.0f, 18.0f)
}
}
.build()
return _lungsOff!!
}
private var _lungsOff: ImageVector? = null
| 0 | Kotlin | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 4,112 | compose-icon-collections | MIT License |
common/common-mail/src/main/kotlin/com/blank/common/mail/config/properties/MailProperties.kt | qq781846712 | 705,955,843 | false | {"Kotlin": 848578, "Vue": 376959, "TypeScript": 137544, "Java": 45954, "HTML": 29445, "SCSS": 19657, "JavaScript": 3399, "Batchfile": 2056, "Shell": 1786, "Dockerfile": 1306} | package com.blank.common.mail.config.properties
import org.springframework.boot.context.properties.ConfigurationProperties
/**
* JavaMail 配置属性
*/
@ConfigurationProperties(prefix = "mail")
class MailProperties {
/**
* 过滤开关
*/
var enabled: Boolean? = null
/**
* SMTP服务器域名
*/
var host: String? = null
/**
* SMTP服务端口
*/
var port: Int? = null
/**
* 是否需要用户名密码验证
*/
var auth: Boolean = false
/**
* 用户名
*/
var user: String? = null
/**
* 密码
*/
var pass: String? = null
/**
* 发送方,遵循RFC-822标准
*/
var from: String? = null
/**
* 使用 STARTTLS安全连接,STARTTLS是对纯文本通信协议的扩展。它将纯文本连接升级为加密连接(TLS或SSL), 而不是使用一个单独的加密通信端口。
*/
var starttlsEnable: Boolean = false
/**
* 使用 SSL安全连接
*/
var sslEnable: Boolean = false
/**
* SMTP超时时长,单位毫秒,缺省值不超时
*/
var timeout: Long? = null
/**
* Socket连接超时值,单位毫秒,缺省值不超时
*/
var connectionTimeout: Long? = null
}
| 1 | Kotlin | 0 | 0 | e7ce0812d564f79ef655788829d983c25e51592a | 1,025 | Ruoyi-Vue-Plus-Kotlin | Apache License 2.0 |
core/src/main/java/com/github/dudgns0507/core/util/ext/BaseExt.kt | dudgns0507 | 379,595,025 | false | null | package com.github.dudgns0507.core.util.ext | 1 | null | 1 | 2 | c69453e3898271eba176975a8f5d1f2cc38386aa | 43 | MVVM-cropo | The Unlicense |
src/main/kotlin/no/nav/dagpenger/iverksett/api/IverksettingValidatorService.kt | navikt | 611,752,955 | false | {"Kotlin": 304290, "Gherkin": 44293, "Shell": 626, "Dockerfile": 121} | package no.nav.dagpenger.iverksett.api
import no.nav.dagpenger.iverksett.api.domene.IverksettDagpenger
import no.nav.dagpenger.iverksett.api.domene.erKonsistentMed
import no.nav.dagpenger.iverksett.api.domene.personIdent
import no.nav.dagpenger.iverksett.api.domene.sakId
import no.nav.dagpenger.iverksett.api.tilstand.IverksettResultatService
import no.nav.dagpenger.iverksett.infrastruktur.advice.ApiFeil
import no.nav.dagpenger.iverksett.infrastruktur.featuretoggle.FeatureToggleService
import no.nav.dagpenger.kontrakter.oppdrag.OppdragStatus
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
@Service
class IverksettingValidatorService(
private val iverksettResultatService: IverksettResultatService,
private val iverksettingService: IverksettingService,
private val featureToggleService: FeatureToggleService,
) {
fun valider(iverksett: IverksettDagpenger) {
/* Med DB-oppslag */
validerAtBehandlingIkkeAlleredeErMottatt(iverksett)
validerKonsistensMellomVedtak(iverksett)
validerAtIverksettingErForSammeSakOgPersonSomForrige(iverksett)
validerAtForrigeBehandlingErFerdigIverksattMotOppdrag(iverksett)
}
internal fun validerKonsistensMellomVedtak(iverksett: IverksettDagpenger) {
val forrigeIverksettResultat = iverksett.behandling.forrigeBehandlingId?.let {
iverksettResultatService.hentIverksettResultat(it) ?: throw ApiFeil(
"Forrige behandling med id $it er ikke mottatt for iverksetting",
HttpStatus.BAD_REQUEST,
)
}
if (!forrigeIverksettResultat.erKonsistentMed(iverksett.forrigeIverksetting)) {
throw ApiFeil(
"Mottatt og faktisk forrige iverksatting er ikke konsistente",
HttpStatus.BAD_REQUEST,
)
}
}
internal fun validerAtIverksettingErForSammeSakOgPersonSomForrige(iverksett: IverksettDagpenger) {
val forrigeIverksett = try {
iverksettingService.hentForrigeIverksett(iverksett)
} catch (e: IllegalStateException) {
throw ApiFeil(e.message ?: "Fant ikke forrige iverksetting", HttpStatus.CONFLICT)
}
val forrigeSakId = forrigeIverksett?.sakId
if (forrigeSakId != null && forrigeSakId != iverksett.sakId) {
throw ApiFeil(
"Forrige behandling er knyttet til en annen sak enn denne iverksettingen gjelder",
HttpStatus.BAD_REQUEST,
)
}
val forrigePersonident = forrigeIverksett?.personIdent
if (forrigePersonident != null && forrigePersonident != iverksett.personIdent) {
throw ApiFeil(
"Forrige behandling er knyttet til en annen person enn denne iverksettingen gjelder",
HttpStatus.BAD_REQUEST,
)
}
}
internal fun validerAtForrigeBehandlingErFerdigIverksattMotOppdrag(iverksett: IverksettDagpenger?) {
iverksett?.behandling?.forrigeBehandlingId?.apply {
val forrigeResultat = iverksettResultatService.hentIverksettResultat(this)
val forrigeErUtenUtbetalingsperioder =
forrigeResultat?.tilkjentYtelseForUtbetaling?.utbetalingsoppdrag?.utbetalingsperiode?.isEmpty() ?: true
val forrigeErKvittertOk =
forrigeResultat?.oppdragResultat?.oppdragStatus == OppdragStatus.KVITTERT_OK
val forrigeErOkMotOppdrag = forrigeErUtenUtbetalingsperioder || forrigeErKvittertOk
if (!forrigeErOkMotOppdrag) {
throw ApiFeil("Forrige iverksetting er ikke ferdig håndtert mhp oppdrag", HttpStatus.CONFLICT)
}
}
}
internal fun validerAtBehandlingIkkeAlleredeErMottatt(iverksett: IverksettDagpenger) {
if (iverksettingService.hentIverksetting(iverksett.behandling.behandlingId) != null) {
throw ApiFeil(
"Behandling med id ${iverksett.behandling.behandlingId} er allerede mottattt",
HttpStatus.CONFLICT,
)
}
}
}
| 1 | Kotlin | 0 | 0 | fc64be50e9a8cdb9ca9b55666b83793fa610a98f | 4,105 | dp-iverksett | MIT License |
sdk/src/main/java/io/portone/sdk/android/type/CashReceiptType.kt | portone-io | 835,174,061 | false | {"Kotlin": 197769, "HTML": 1179} | package io.portone.sdk.android.type
enum class CashReceiptType {
PERSONAL, // 소득공제용
CORPORATE, // 지출증빙용
ANONYMOUS; // 국세청번호 자동발급 케이스 대응
}
| 0 | Kotlin | 0 | 2 | 07509908b066a19fc5e0e96afca415816687d2f4 | 151 | android-sdk | MIT License |
app/src/main/java/com/example/restaurant/cleanArchitecture/data/repository/ShopRepository.kt | Imranseu17 | 481,709,159 | false | null | package com.example.restaurant.cleanArchitecture.data.repository
import androidx.lifecycle.MutableLiveData
import com.example.restaurant.cleanArchitecture.data.model.Root
import com.example.restaurant.cleanArchitecture.data.remote.APIService
import com.example.restaurant.cleanArchitecture.data.remote.RetroClass
import io.reactivex.rxjava3.core.Observable
class ShopRepository {
lateinit var apiService: APIService
private var _id = MutableLiveData<String>()
var shopResponseObservableWithID: Observable<Root>
get():Observable<Root> {
apiService = RetroClass.getAPIService()
shopResponseObservableWithID = apiService.
getShop("f5c06c8896e2d2d4", _id.value!!,"json")
return shopResponseObservableWithID
}
set(value) {}
var shopResponseObservable: Observable<Root>
get():Observable<Root> {
apiService = RetroClass.getAPIService()
shopResponseObservable = apiService.
getAllShops("f5c06c8896e2d2d4","Z011","json")
return shopResponseObservable
}
set(value) {}
constructor(_id: MutableLiveData<String>) {
this._id = _id
}
} | 0 | Kotlin | 1 | 0 | e89ed3bfde75b32383c425ecaca9b4dd6b53ad6d | 1,203 | ShopApplication | Apache License 2.0 |
socorro/src/main/java/com/soumya/wwdablu/socorro/SocorroConfig.kt | wwdablu | 158,618,914 | false | null | package com.soumya.wwdablu.socorro
import android.text.TextUtils
class SocorroConfig {
enum class SourceFileFrom {
Assets,
Raw,
Resources
}
private var endPoint: String = ""
private var codeResponseMap: HashMap<Int, String> = HashMap()
private var delay: Int = 0
private var fileContainer: SourceFileFrom = SourceFileFrom.Raw
private var responseCode: Int = 200
private var success: Boolean = true
companion object {
fun createWith() : SocorroConfig {
return SocorroConfig()
}
}
fun endPoint(endPoint: String) : SocorroConfig {
if(TextUtils.isEmpty(endPoint)) {
return this
}
this.endPoint = endPoint
return this
}
internal fun getEndPoint() : String {
return this.endPoint
}
fun putCodeResponseMap(code: Int, fileName: String) : SocorroConfig {
codeResponseMap.put(code, fileName)
return this
}
internal fun getCodeResponseMap(code: Int) : String? {
if(codeResponseMap.containsKey(code)) {
return codeResponseMap[code]
}
return null
}
fun delay(delay: Int) : SocorroConfig {
this.delay = delay
return this
}
internal fun getDelay() : Int {
return this.delay
}
fun sourceFileFrom(from: SourceFileFrom) : SocorroConfig {
this.fileContainer = from
return this
}
internal fun getFileContainer() : SourceFileFrom {
return this.fileContainer
}
fun responseCode(code: Int) : SocorroConfig {
this.responseCode = code
return this
}
internal fun getResponseCode() : Int {
return this.responseCode
}
fun success(success: Boolean) : SocorroConfig {
this.success = success
return this
}
internal fun isSuccess() : Boolean {
return this.success
}
private constructor()
} | 0 | Kotlin | 0 | 0 | 71ff5a3333c24d987a8dc1a9235d24407fe48cee | 1,971 | Socorro | MIT License |
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/CompleteStageHandlerTest.kt | spinnaker | 19,834,314 | false | null | /*
* Copyright 2017 Netflix, Inc.
*
* 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.netflix.spinnaker.orca.q.handler
import com.netflix.spectator.api.NoopRegistry
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.CANCELED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.FAILED_CONTINUE
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.NOT_STARTED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SKIPPED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.STOPPED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SUCCEEDED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.TERMINAL
import com.netflix.spinnaker.orca.StageResolver
import com.netflix.spinnaker.orca.api.simplestage.SimpleStage
import com.netflix.spinnaker.orca.api.simplestage.SimpleStageInput
import com.netflix.spinnaker.orca.api.simplestage.SimpleStageOutput
import com.netflix.spinnaker.orca.api.simplestage.SimpleStageStatus
import com.netflix.spinnaker.orca.events.StageComplete
import com.netflix.spinnaker.orca.exceptions.DefaultExceptionHandler
import com.netflix.spinnaker.orca.exceptions.ExceptionHandler
import com.netflix.spinnaker.orca.api.test.pipeline
import com.netflix.spinnaker.orca.api.test.stage
import com.netflix.spinnaker.orca.api.test.task
import com.netflix.spinnaker.orca.pipeline.DefaultStageDefinitionBuilderFactory
import com.netflix.spinnaker.orca.api.pipeline.graph.StageDefinitionBuilder
import com.netflix.spinnaker.orca.api.pipeline.graph.TaskNode
import com.netflix.spinnaker.orca.pipeline.expressions.PipelineExpressionEvaluator
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType.PIPELINE
import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution
import com.netflix.spinnaker.orca.api.pipeline.graph.StageGraphBuilder
import com.netflix.spinnaker.orca.api.pipeline.SyntheticStageOwner.STAGE_AFTER
import com.netflix.spinnaker.orca.api.pipeline.SyntheticStageOwner.STAGE_BEFORE
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor
import com.netflix.spinnaker.orca.pipeline.util.StageNavigator
import com.netflix.spinnaker.orca.q.CancelStage
import com.netflix.spinnaker.orca.q.CompleteExecution
import com.netflix.spinnaker.orca.q.CompleteStage
import com.netflix.spinnaker.orca.q.ContinueParentStage
import com.netflix.spinnaker.orca.q.DummyTask
import com.netflix.spinnaker.orca.q.RunTask
import com.netflix.spinnaker.orca.q.StartStage
import com.netflix.spinnaker.orca.q.buildAfterStages
import com.netflix.spinnaker.orca.q.buildBeforeStages
import com.netflix.spinnaker.orca.q.buildFailureStages
import com.netflix.spinnaker.orca.q.buildTasks
import com.netflix.spinnaker.orca.q.get
import com.netflix.spinnaker.orca.q.multiTaskStage
import com.netflix.spinnaker.orca.q.singleTaskStage
import com.netflix.spinnaker.orca.q.stageWithParallelBranches
import com.netflix.spinnaker.orca.q.stageWithSyntheticAfter
import com.netflix.spinnaker.orca.q.stageWithSyntheticBefore
import com.netflix.spinnaker.orca.q.stageWithSyntheticOnFailure
import com.netflix.spinnaker.q.Message
import com.netflix.spinnaker.q.Queue
import com.netflix.spinnaker.spek.and
import com.netflix.spinnaker.spek.but
import com.netflix.spinnaker.time.fixedClock
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.argumentCaptor
import com.nhaarman.mockito_kotlin.check
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.isA
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.never
import com.nhaarman.mockito_kotlin.reset
import com.nhaarman.mockito_kotlin.times
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.verifyZeroInteractions
import com.nhaarman.mockito_kotlin.whenever
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.fail
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP
import org.jetbrains.spek.subject.SubjectSpek
import org.springframework.context.ApplicationEventPublisher
import java.time.Duration.ZERO
object CompleteStageHandlerTest : SubjectSpek<CompleteStageHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
val stageNavigator: StageNavigator = mock()
val publisher: ApplicationEventPublisher = mock()
val exceptionHandler: ExceptionHandler = DefaultExceptionHandler()
val clock = fixedClock()
val registry = NoopRegistry()
val contextParameterProcessor: ContextParameterProcessor = mock()
val emptyStage = object : StageDefinitionBuilder {}
val stageWithTaskAndAfterStages = object : StageDefinitionBuilder {
override fun getType() = "stageWithTaskAndAfterStages"
override fun taskGraph(stage: StageExecution, builder: TaskNode.Builder) {
builder.withTask("dummy", DummyTask::class.java)
}
override fun afterStages(parent: StageExecution, graph: StageGraphBuilder) {
graph.add {
it.type = singleTaskStage.type
it.name = "After Stage"
it.context = mapOf("key" to "value")
}
}
}
val stageThatBlowsUpPlanningAfterStages = object : StageDefinitionBuilder {
override fun getType() = "stageThatBlowsUpPlanningAfterStages"
override fun taskGraph(stage: StageExecution, builder: TaskNode.Builder) {
builder.withTask("dummy", DummyTask::class.java)
}
override fun afterStages(parent: StageExecution, graph: StageGraphBuilder) {
throw RuntimeException("there is some problem actually")
}
}
val stageWithNothingButAfterStages = object : StageDefinitionBuilder {
override fun getType() = "stageWithNothingButAfterStages"
override fun afterStages(parent: StageExecution, graph: StageGraphBuilder) {
graph.add {
it.type = singleTaskStage.type
it.name = "After Stage"
}
}
}
val emptyApiStage = object : SimpleStage<Any> {
override fun getName() = "emptyApiStage"
override fun execute(simpleStageInput: SimpleStageInput<Any>): SimpleStageOutput<Any, Any> {
return SimpleStageOutput()
}
}
val successfulApiStage = object : SimpleStage<Any> {
override fun getName() = "successfulApiStage"
override fun execute(simpleStageInput: SimpleStageInput<Any>): SimpleStageOutput<Any, Any> {
val output = SimpleStageOutput<Any, Any>()
output.status = SimpleStageStatus.SUCCEEDED
return output
}
}
subject(GROUP) {
CompleteStageHandler(
queue,
repository,
stageNavigator,
publisher,
clock,
listOf(exceptionHandler),
contextParameterProcessor,
registry,
DefaultStageDefinitionBuilderFactory(
StageResolver(
listOf(
singleTaskStage,
multiTaskStage,
stageWithSyntheticBefore,
stageWithSyntheticAfter,
stageWithParallelBranches,
stageWithTaskAndAfterStages,
stageThatBlowsUpPlanningAfterStages,
stageWithSyntheticOnFailure,
stageWithNothingButAfterStages,
stageWithSyntheticOnFailure,
emptyStage
),
listOf(
emptyApiStage,
successfulApiStage
)
)
)
)
}
fun resetMocks() = reset(queue, repository, publisher)
describe("completing top level stages") {
setOf(SUCCEEDED, FAILED_CONTINUE).forEach { taskStatus ->
describe("when a stage's tasks complete with $taskStatus status") {
and("it is already complete") {
val pipeline = pipeline {
stage {
refId = "1"
type = multiTaskStage.type
multiTaskStage.plan(this)
tasks[0].status = SUCCEEDED
tasks[1].status = taskStatus
tasks[2].status = SUCCEEDED
status = taskStatus
endTime = clock.instant().minusSeconds(2).toEpochMilli()
}
}
val message = CompleteStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("ignores the message") {
verify(repository, never()).storeStage(any())
verifyZeroInteractions(queue)
verifyZeroInteractions(publisher)
}
}
and("it is the last stage") {
val pipeline = pipeline {
stage {
refId = "1"
type = singleTaskStage.type
singleTaskStage.plan(this)
tasks.first().status = taskStatus
status = RUNNING
}
}
val message = CompleteStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("updates the stage state") {
verify(repository).storeStage(check {
assertThat(it.status).isEqualTo(taskStatus)
assertThat(it.endTime).isEqualTo(clock.millis())
})
}
it("completes the execution") {
verify(queue).push(CompleteExecution(pipeline))
}
it("does not emit any commands") {
verify(queue, never()).push(any<RunTask>())
}
it("publishes an event") {
verify(publisher).publishEvent(check<StageComplete> {
assertThat(it.executionType).isEqualTo(pipeline.type)
assertThat(it.executionId).isEqualTo(pipeline.id)
assertThat(it.stageId).isEqualTo(message.stageId)
assertThat(it.status).isEqualTo(taskStatus)
})
}
}
and("there is a single downstream stage") {
val pipeline = pipeline {
stage {
refId = "1"
type = singleTaskStage.type
singleTaskStage.plan(this)
tasks.first().status = taskStatus
status = RUNNING
}
stage {
refId = "2"
requisiteStageRefIds = setOf("1")
type = singleTaskStage.type
}
}
val message = CompleteStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("updates the stage state") {
verify(repository).storeStage(check {
assertThat(it.status).isEqualTo(taskStatus)
assertThat(it.endTime).isEqualTo(clock.millis())
})
}
it("runs the next stage") {
verify(queue).push(StartStage(
message.executionType,
message.executionId,
message.application,
pipeline.stages.last().id
))
}
it("does not run any tasks") {
verify(queue, never()).push(any<RunTask>())
}
}
and("there are multiple downstream stages") {
val pipeline = pipeline {
stage {
refId = "1"
type = singleTaskStage.type
singleTaskStage.plan(this)
tasks.first().status = taskStatus
status = RUNNING
}
stage {
refId = "2"
requisiteStageRefIds = setOf("1")
type = singleTaskStage.type
}
stage {
refId = "3"
requisiteStageRefIds = setOf("1")
type = singleTaskStage.type
}
}
val message = CompleteStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("runs the next stages") {
argumentCaptor<StartStage>().apply {
verify(queue, times(2)).push(capture())
assertThat(allValues.map { it.stageId }.toSet()).isEqualTo(pipeline.stages[1..2].map { it.id }.toSet())
}
}
}
and("there are parallel stages still running") {
val pipeline = pipeline {
stage {
refId = "1"
type = singleTaskStage.type
singleTaskStage.plan(this)
tasks.first().status = taskStatus
status = RUNNING
}
stage {
refId = "2"
type = singleTaskStage.type
status = RUNNING
}
}
val message = CompleteStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("still signals completion of the execution") {
verify(queue).push(CompleteExecution(pipeline))
}
}
setOf(CANCELED, TERMINAL, STOPPED).forEach { failureStatus ->
and("there are parallel stages that failed") {
val pipeline = pipeline {
stage {
refId = "1"
type = singleTaskStage.type
singleTaskStage.plan(this)
tasks.first().status = SUCCEEDED
status = RUNNING
}
stage {
refId = "2"
type = singleTaskStage.type
status = failureStatus
}
}
val message = CompleteStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("still signals completion of the execution") {
verify(queue).push(CompleteExecution(pipeline))
}
}
}
and("there are still synthetic stages to plan") {
val pipeline = pipeline {
stage {
refId = "1"
name = "wait"
status = RUNNING
type = stageWithTaskAndAfterStages.type
stageWithTaskAndAfterStages.plan(this)
tasks.first().status = taskStatus
}
}
val message = CompleteStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving the message") {
subject.handle(message)
}
it("adds a new AFTER_STAGE") {
assertThat(pipeline.stages.map { it.type }).isEqualTo(listOf("stageWithTaskAndAfterStages", "singleTaskStage"))
}
it("starts the new AFTER_STAGE") {
verify(queue).push(StartStage(message, pipeline.stages[1].id))
}
it("does not update the status of the stage itself") {
verify(repository, never()).storeStage(pipeline.stageById(message.stageId))
}
it("does not signal completion of the execution") {
verify(queue, never()).push(isA<CompleteExecution>())
}
}
and("planning synthetic stages throws an exception") {
val pipeline = pipeline {
stage {
refId = "1"
name = "wait"
status = RUNNING
type = stageThatBlowsUpPlanningAfterStages.type
stageThatBlowsUpPlanningAfterStages.plan(this)
tasks.first().status = taskStatus
}
}
val message = CompleteStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
assertThat(pipeline.stages.map { it.type }).isEqualTo(listOf(stageThatBlowsUpPlanningAfterStages.type))
}
afterGroup(::resetMocks)
on("receiving the message") {
subject.handle(message)
}
it("makes the stage TERMINAL") {
assertThat(pipeline.stageById(message.stageId).status).isEqualTo(TERMINAL)
}
it("correctly records exception") {
assertThat(pipeline.stageById(message.stageId).context).containsKey("exception")
val exceptionContext = pipeline.stageById(message.stageId).context["exception"] as ExceptionHandler.Response
assertThat(exceptionContext.exceptionType).isEqualTo(RuntimeException().javaClass.simpleName)
}
it("runs cancellation") {
verify(queue).push(CancelStage(pipeline.stageById(message.stageId)))
}
it("signals completion of the execution") {
verify(queue).push(CompleteExecution(pipeline))
}
}
}
}
given("a stage had no synthetics or tasks") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
name = "empty"
status = RUNNING
type = emptyStage.type
}
stage {
refId = "2"
type = singleTaskStage.type
name = "downstream"
requisiteStageRefIds = setOf("1")
}
}
val message = CompleteStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
action("receiving the message") {
subject.handle(message)
}
it("just marks the stage as SKIPPED") {
verify(repository).storeStage(check {
assertThat(it.id).isEqualTo(message.stageId)
assertThat(it.status).isEqualTo(SKIPPED)
})
}
it("starts anything downstream") {
verify(queue).push(StartStage(pipeline.stageByRef("2")))
}
}
setOf(TERMINAL, CANCELED).forEach { taskStatus ->
describe("when a stage's task fails with $taskStatus status") {
val pipeline = pipeline {
stage {
refId = "1"
type = multiTaskStage.type
multiTaskStage.plan(this)
tasks[0].status = SUCCEEDED
tasks[1].status = taskStatus
tasks[2].status = NOT_STARTED
status = RUNNING
}
stage {
refId = "2"
requisiteStageRefIds = listOf("1")
type = singleTaskStage.type
}
}
val message = CompleteStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving the message") {
subject.handle(message)
}
it("updates the stage state") {
verify(repository).storeStage(check {
assertThat(it.status).isEqualTo(taskStatus)
assertThat(it.endTime).isEqualTo(clock.millis())
})
}
it("does not run any downstream stages") {
verify(queue, never()).push(isA<StartStage>())
}
it("fails the execution") {
verify(queue).push(CompleteExecution(
message.executionType,
message.executionId,
message.application
))
}
it("runs the stage's cancellation routine") {
verify(queue).push(CancelStage(message))
}
it("publishes an event") {
verify(publisher).publishEvent(check<StageComplete> {
assertThat(it.executionType).isEqualTo(pipeline.type)
assertThat(it.executionId).isEqualTo(pipeline.id)
assertThat(it.stageId).isEqualTo(message.stageId)
assertThat(it.status).isEqualTo(taskStatus)
})
}
}
}
describe("when none of a stage's tasks ever started") {
val pipeline = pipeline {
stage {
refId = "1"
type = multiTaskStage.type
multiTaskStage.plan(this)
tasks[0].status = NOT_STARTED
tasks[1].status = NOT_STARTED
tasks[2].status = NOT_STARTED
status = RUNNING
}
stage {
refId = "2"
requisiteStageRefIds = listOf("1")
type = singleTaskStage.type
}
}
val message = CompleteStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving the message") {
subject.handle(message)
}
it("updates the stage state") {
verify(repository).storeStage(check {
assertThat(it.status).isEqualTo(TERMINAL)
assertThat(it.endTime).isEqualTo(clock.millis())
})
}
it("does not run any downstream stages") {
verify(queue, never()).push(isA<StartStage>())
}
it("fails the execution") {
verify(queue).push(CompleteExecution(
message.executionType,
message.executionId,
message.application
))
}
it("runs the stage's cancellation routine") {
verify(queue).push(CancelStage(message))
}
it("publishes an event") {
verify(publisher).publishEvent(check<StageComplete> {
assertThat(it.executionType).isEqualTo(pipeline.type)
assertThat(it.executionId).isEqualTo(pipeline.id)
assertThat(it.stageId).isEqualTo(message.stageId)
assertThat(it.status).isEqualTo(TERMINAL)
})
}
}
given("a stage had no tasks or before stages") {
but("does have after stages") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithNothingButAfterStages.type
status = RUNNING
}
}
val message = CompleteStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("plans and starts the after stages") {
argumentCaptor<Message>().apply {
verify(queue).push(capture())
firstValue.let { capturedMessage ->
when (capturedMessage) {
is StartStage -> pipeline.stageById(capturedMessage.stageId).apply {
assertThat(parentStageId).isEqualTo(message.stageId)
assertThat(name).isEqualTo("After Stage")
}
else ->
fail("Expected a StartStage message but got a ${capturedMessage.javaClass.simpleName}")
}
}
}
}
it("does not complete the pipeline") {
verify(queue, never()).push(isA<CompleteExecution>())
}
it("does not mark the stage as failed") {
assertThat(pipeline.stageById(message.stageId).status).isEqualTo(RUNNING)
}
}
}
mapOf(STAGE_BEFORE to stageWithSyntheticBefore, STAGE_AFTER to stageWithSyntheticAfter).forEach { syntheticType, stageBuilder ->
setOf(TERMINAL, CANCELED, STOPPED).forEach { failureStatus ->
describe("when a $syntheticType synthetic stage completed with $failureStatus") {
val pipeline = pipeline {
stage {
refId = "1"
status = RUNNING
type = stageBuilder.type
if (syntheticType == STAGE_BEFORE) {
stageBuilder.buildBeforeStages(this)
} else {
stageBuilder.buildAfterStages(this)
}
stageBuilder.plan(this)
}
}
val message = CompleteStage(pipeline.stageByRef("1"))
beforeGroup {
pipeline
.stages
.first { it.syntheticStageOwner == syntheticType }
.status = failureStatus
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving the message") {
subject.handle(message)
}
it("updates the stage state") {
verify(repository).storeStage(check {
assertThat(it.status).isEqualTo(failureStatus)
assertThat(it.endTime).isEqualTo(clock.millis())
})
}
}
}
describe("when any $syntheticType synthetic stage completed with FAILED_CONTINUE") {
val pipeline = pipeline {
stage {
refId = "1"
status = RUNNING
type = stageBuilder.type
if (syntheticType == STAGE_BEFORE) {
stageBuilder.buildBeforeStages(this)
} else {
stageBuilder.buildAfterStages(this)
}
stageBuilder.plan(this)
}
}
val message = CompleteStage(pipeline.stageByRef("1"))
beforeGroup {
pipeline
.stages
.first { it.syntheticStageOwner == syntheticType }
.status = FAILED_CONTINUE
pipeline.stageById(message.stageId).tasks.forEach { it.status = SUCCEEDED }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving the message") {
subject.handle(message)
}
it("updates the stage state") {
verify(repository).storeStage(check {
assertThat(it.status).isEqualTo(FAILED_CONTINUE)
assertThat(it.endTime).isEqualTo(clock.millis())
})
}
it("does not do anything silly like running the after stage again") {
verify(queue, never()).push(isA<StartStage>())
}
}
}
describe("when all after stages have completed successfully") {
val pipeline = pipeline {
stage {
refId = "1"
status = RUNNING
type = stageWithSyntheticAfter.type
stageWithSyntheticAfter.plan(this)
stageWithSyntheticAfter.buildAfterStages(this)
}
}
val message = CompleteStage(pipeline.stageByRef("1"))
beforeGroup {
pipeline
.stages
.filter { it.syntheticStageOwner == STAGE_AFTER }
.forEach { it.status = SUCCEEDED }
pipeline.stageById(message.stageId).tasks.forEach { it.status = SUCCEEDED }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving the message") {
subject.handle(message)
}
it("does not do anything silly like running the after stage again") {
verify(queue, never()).push(isA<StartStage>())
}
}
given("after stages were planned but not run yet") {
val pipeline = pipeline {
stage {
refId = "2"
type = "deploy"
name = "Deploy"
status = RUNNING
stage {
refId = "2=1"
type = "createServerGroup"
name = "Deploy in us-west-2"
status = RUNNING
task {
name = "determineSourceServerGroup"
status = SUCCEEDED
}
stage {
refId = "2=1>3"
type = "applySourceServerGroupCapacity"
name = "restoreMinCapacityFromSnapshot"
syntheticStageOwner = STAGE_AFTER
requisiteStageRefIds = setOf("2=1>2")
}
stage {
refId = "2=1>2"
type = "disableCluster"
name = "disableCluster"
syntheticStageOwner = STAGE_AFTER
requisiteStageRefIds = setOf("2=1>1")
}
stage {
refId = "2=1>1"
type = "shrinkCluster"
name = "shrinkCluster"
syntheticStageOwner = STAGE_AFTER
}
}
}
}
val message = CompleteStage(pipeline.stageByRef("2=1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("starts the first after stage") {
verify(queue).push(StartStage(pipeline.stageByRef("2=1>1")))
}
}
}
describe("completing synthetic stages") {
given("a synthetic stage's task completes with $SUCCEEDED") {
and("it comes before its parent stage") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithSyntheticBefore.type
stageWithSyntheticBefore.buildBeforeStages(this)
stageWithSyntheticBefore.buildTasks(this)
}
}
and("there are more before stages") {
val message = CompleteStage(pipeline.stageByRef("1<1"))
beforeGroup {
pipeline.stageById(message.stageId).apply {
status = RUNNING
singleTaskStage.plan(this)
tasks.first().status = SUCCEEDED
}
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving the message") {
subject.handle(message)
}
it("runs the next synthetic stage") {
verify(queue).push(StartStage(
pipeline.stageByRef("1<2")
))
}
}
and("it is the last before stage") {
val message = CompleteStage(pipeline.stageByRef("1<2"))
beforeGroup {
pipeline.stageById(message.stageId).apply {
status = RUNNING
singleTaskStage.plan(this)
tasks.first().status = SUCCEEDED
}
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving the message") {
subject.handle(message)
}
it("signals the parent stage to run") {
verify(queue).ensure(ContinueParentStage(
pipeline.stageByRef("1"),
STAGE_BEFORE
), ZERO)
}
}
}
and("it comes after its parent stage") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithSyntheticAfter.type
stageWithSyntheticAfter.buildBeforeStages(this)
stageWithSyntheticAfter.buildTasks(this)
stageWithSyntheticAfter.buildAfterStages(this)
}
}
and("there are more after stages") {
val message = CompleteStage(pipeline.stageByRef("1>1"))
beforeGroup {
pipeline.stageById(message.stageId).apply {
status = RUNNING
singleTaskStage.plan(this)
tasks.first().status = SUCCEEDED
}
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving the message") {
subject.handle(message)
}
it("runs the next synthetic stage") {
verify(queue).push(StartStage(
message.executionType,
message.executionId,
message.application,
pipeline.stages.last().id
))
}
}
and("it is the last after stage") {
val message = CompleteStage(pipeline.stageByRef("1>2"))
beforeGroup {
pipeline.stageById(message.stageId).apply {
status = RUNNING
singleTaskStage.plan(this)
tasks.first().status = SUCCEEDED
}
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving the message") {
subject.handle(message)
}
it("tells the parent stage to continue") {
verify(queue)
.ensure(ContinueParentStage(
pipeline.stageById(message.stageId).parent!!,
STAGE_AFTER
), ZERO)
}
}
}
given("a synthetic stage's task ends with $FAILED_CONTINUE status") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithSyntheticBefore.type
stageWithSyntheticBefore.buildBeforeStages(this)
stageWithSyntheticBefore.plan(this)
}
}
val message = CompleteStage(pipeline.stageByRef("1<1"))
beforeGroup {
pipeline.stageById(message.stageId).apply {
status = RUNNING
singleTaskStage.plan(this)
tasks.first().status = FAILED_CONTINUE
}
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
on("receiving the message") {
subject.handle(message)
}
afterGroup(::resetMocks)
it("rolls up to the parent stage") {
verify(queue).push(message.copy(stageId = pipeline.stageByRef("1").id))
}
}
given("a synthetic stage's task ends with $FAILED_CONTINUE status and the synthetic allows siblings to continue") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithSyntheticBefore.type
stageWithSyntheticBefore.buildBeforeStages(this)
stageWithSyntheticBefore.plan(this)
}
}
val syntheticStage = pipeline.stageByRef("1<1")
syntheticStage.allowSiblingStagesToContinueOnFailure = true
val message = CompleteStage(syntheticStage)
beforeGroup {
pipeline.stageById(message.stageId).apply {
status = RUNNING
singleTaskStage.plan(this)
tasks.first().status = FAILED_CONTINUE
}
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
on("receiving the message") {
subject.handle(message)
}
afterGroup(::resetMocks)
it("starts executing the next sibling") {
verify(queue).push(StartStage(pipeline.stageByRef("1<2")))
}
}
}
setOf(TERMINAL, CANCELED).forEach { taskStatus ->
given("a synthetic stage's task ends with $taskStatus status") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithSyntheticBefore.type
stageWithSyntheticBefore.buildBeforeStages(this)
stageWithSyntheticBefore.plan(this)
}
}
val message = CompleteStage(pipeline.stageByRef("1<1"))
beforeGroup {
pipeline.stageById(message.stageId).apply {
status = RUNNING
singleTaskStage.plan(this)
tasks.first().status = taskStatus
}
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
on("receiving the message") {
subject.handle(message)
}
afterGroup(::resetMocks)
it("rolls up to the parent stage") {
verify(queue).push(message.copy(stageId = pipeline.stageByRef("1").id))
}
it("runs the stage's cancel routine") {
verify(queue).push(CancelStage(message))
}
}
}
given("a synthetic stage's task ends with $TERMINAL status and parent stage should continue on failure") {
val pipeline = pipeline {
stage {
refId = "1"
context = mapOf("continuePipeline" to true) // should continue on failure
type = stageWithSyntheticBefore.type
stageWithSyntheticBefore.buildBeforeStages(this)
stageWithSyntheticBefore.plan(this)
}
}
val message = CompleteStage(pipeline.stageByRef("1<1"))
beforeGroup {
pipeline.stageById(message.stageId).apply {
status = RUNNING
singleTaskStage.plan(this)
tasks.first().status = TERMINAL
}
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
on("receiving the message") {
subject.handle(message)
}
afterGroup(::resetMocks)
it("rolls up to the parent stage") {
verify(queue).push(message.copy(stageId = pipeline.stageByRef("1").id))
}
it("runs the parent stage's complete routine") {
verify(queue).push(CompleteStage(message.copy(stageId = pipeline.stageByRef("1").id)))
}
}
}
describe("branching stages") {
listOf(SUCCEEDED, FAILED_CONTINUE).forEach { status ->
context("when one branch completes with $status") {
val pipeline = pipeline {
stage {
refId = "1"
name = "parallel"
type = stageWithParallelBranches.type
stageWithParallelBranches.buildBeforeStages(this)
stageWithParallelBranches.buildTasks(this)
}
}
val message = pipeline.stageByRef("1<1").let { completedSynthetic ->
singleTaskStage.buildTasks(completedSynthetic)
completedSynthetic.tasks.forEach { it.status = SUCCEEDED }
CompleteStage(completedSynthetic)
}
beforeGroup {
pipeline.stageById(message.stageId).status = RUNNING
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving the message") {
subject.handle(message)
}
it("signals the parent stage to try to run") {
verify(queue)
.ensure(ContinueParentStage(pipeline.stageByRef("1"), STAGE_BEFORE), ZERO)
}
}
given("all branches are complete") {
val pipeline = pipeline {
stage {
refId = "1"
name = "parallel"
type = stageWithParallelBranches.type
stageWithParallelBranches.buildBeforeStages(this)
stageWithParallelBranches.buildTasks(this)
}
}
pipeline.stages.filter { it.parentStageId != null }.forEach {
singleTaskStage.buildTasks(it)
it.tasks.forEach { it.status = SUCCEEDED }
}
val message = CompleteStage(pipeline.stageByRef("1<1"))
beforeGroup {
pipeline.stageById(message.stageId).status = RUNNING
pipeline.stageByRef("1<2").status = SUCCEEDED
pipeline.stageByRef("1<3").status = SUCCEEDED
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving the message") {
subject.handle(message)
}
it("signals the parent stage to try to run") {
verify(queue)
.ensure(ContinueParentStage(pipeline.stageByRef("1"), STAGE_BEFORE), ZERO)
}
}
}
}
describe("surfacing expression evaluation errors") {
fun exceptionErrors(stages: List<StageExecution>): List<*> =
stages.flatMap {
((it.context["exception"] as Map<*, *>)["details"] as Map<*, *>)["errors"] as List<*>
}
given("an exception in the stage context") {
val expressionError = "Expression foo failed for field bar"
val existingException = "Existing error"
val pipeline = pipeline {
stage {
refId = "1"
name = "wait"
context = mapOf(
"exception" to mapOf("details" to mapOf("errors" to mutableListOf(existingException))),
PipelineExpressionEvaluator.SUMMARY to mapOf("failedExpression" to listOf(mapOf("description" to expressionError, "level" to "ERROR")))
)
status = RUNNING
type = singleTaskStage.type
singleTaskStage.plan(this)
tasks.first().status = SUCCEEDED
}
}
val message = CompleteStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving the message") {
subject.handle(message)
}
it("should contain evaluation summary as well as the existing error") {
val errors = exceptionErrors(pipeline.stages)
assertThat(errors.size).isEqualTo(2)
expressionError in errors
existingException in errors
}
}
given("no other exception errors in the stage context") {
val expressionError = "Expression foo failed for field bar"
val pipeline = pipeline {
stage {
refId = "1"
name = "wait"
context = mutableMapOf<String, Any>(
PipelineExpressionEvaluator.SUMMARY to mapOf("failedExpression" to listOf(mapOf("description" to expressionError, "level" to "ERROR")))
)
status = RUNNING
type = singleTaskStage.type
singleTaskStage.plan(this)
tasks.first().status = SUCCEEDED
}
}
val message = CompleteStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving the message") {
subject.handle(message)
}
it("should only contain evaluation error message") {
val errors = exceptionErrors(pipeline.stages)
assertThat(errors.size).isEqualTo(1)
expressionError in errors
}
}
given("a stage configured to be TERMINAL if it contains any expression errors") {
val pipeline = pipeline {
stage {
refId = "1"
name = "wait"
context = mapOf(
"failOnFailedExpressions" to true,
PipelineExpressionEvaluator.SUMMARY to mapOf(
"failedExpression" to listOf(mapOf("description" to "failed expression foo", "level" to "ERROR"))
)
)
status = RUNNING
type = singleTaskStage.type
singleTaskStage.plan(this)
tasks.first().status = SUCCEEDED
}
}
val message = CompleteStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving the message") {
subject.handle(message)
}
it("should fail the stage") {
assertThat(pipeline.stageById(message.stageId).status).isEqualTo(TERMINAL)
}
}
}
given("a stage ends with TERMINAL status") {
and("it has not run its on failure stages yet") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithSyntheticOnFailure.type
stageWithSyntheticOnFailure.buildBeforeStages(this)
stageWithSyntheticOnFailure.plan(this)
}
}
val message = CompleteStage(pipeline.stageByRef("1"))
beforeGroup {
pipeline.stageById(message.stageId).apply {
status = RUNNING
tasks.first().status = TERMINAL
}
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving the message") {
subject.handle(message)
}
it("plans the first 'OnFailure' stage") {
val onFailureStage = pipeline.stages.first { it.name == "onFailure1" }
verify(queue).push(StartStage(onFailureStage))
}
it("does not (yet) update the stage status") {
assertThat(pipeline.stageById(message.stageId).status).isEqualTo(RUNNING)
}
}
and("it has already run its on failure stages") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithSyntheticOnFailure.type
stageWithSyntheticOnFailure.buildBeforeStages(this)
stageWithSyntheticOnFailure.plan(this)
stageWithSyntheticOnFailure.buildFailureStages(this)
}
}
val message = CompleteStage(pipeline.stageByRef("1"))
beforeGroup {
pipeline.stageById(message.stageId).apply {
status = RUNNING
tasks.first().status = TERMINAL
}
pipeline.stages.filter { it.parentStageId == message.stageId }.forEach {
it.status = SUCCEEDED
}
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving the message again") {
subject.handle(message)
}
it("does not re-plan any 'OnFailure' stages") {
val onFailureStage = pipeline.stages.first { it.name == "onFailure1" }
verify(queue, never()).push(StartStage(onFailureStage))
verify(queue).push(CancelStage(message))
}
it("updates the stage status") {
assertThat(pipeline.stageById(message.stageId).status).isEqualTo(TERMINAL)
}
}
}
describe("stage planning failure behavior") {
given("a stage that failed to plan its before stages") {
val pipeline = pipeline {
stage {
refId = "1"
context = mutableMapOf<String, Any>("beforeStagePlanningFailed" to true)
type = stageWithSyntheticOnFailure.type
stageWithSyntheticOnFailure.buildFailureStages(this)
}
}
val message = CompleteStage(pipeline.stageByRef("1"))
and("it has not run its on failure stages yet") {
beforeGroup {
pipeline.stageById(message.stageId).apply {
status = RUNNING
}
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving the message") {
subject.handle(message)
}
it("plans the first on failure stage") {
val onFailureStage = pipeline.stages.first { it.name == "onFailure1" }
verify(queue).push(StartStage(onFailureStage))
}
it("does not (yet) update the stage status") {
assertThat(pipeline.stageById(message.stageId).status).isEqualTo(RUNNING)
}
}
and("it has already run its on failure stages") {
beforeGroup {
pipeline.stageById(message.stageId).apply {
status = RUNNING
}
pipeline.stages.filter { it.parentStageId == message.stageId }.forEach {
it.status = SUCCEEDED
}
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving the message again") {
subject.handle(message)
}
it("does not re-plan on failure stages") {
val onFailureStage = pipeline.stages.first { it.name == "onFailure1" }
verify(queue, never()).push(StartStage(onFailureStage))
verify(queue).push(CancelStage(message))
}
it("updates the stage status") {
assertThat(pipeline.stageById(message.stageId).status).isEqualTo(TERMINAL)
}
}
}
}
given("api stage completed successfully") {
val pipeline = pipeline {
stage {
refId = "1"
type = successfulApiStage.name
}
}
val message = CompleteStage(pipeline.stageByRef("1"))
pipeline.stageById(message.stageId).apply {
status = SUCCEEDED
}
it("stage was successfully ran") {
assertThat(pipeline.stageById(message.stageId).status).isEqualTo(SUCCEEDED)
}
}
})
| 78 | null | 808 | 246 | 3e98d0a79d72805d16c8a5eb63c4cf1a5bdbbfbc | 49,473 | orca | Apache License 2.0 |
net.akehurst.kotlinx/kotlinx-reflect-gradle-plugin/src/main/kotlin/KotlinxReflectFirExtensionRegistrar.kt | dhakehurst | 189,049,817 | false | {"Kotlin": 177637} | package net.akehurst.kotlinx.reflect.gradle.plugin
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.extensions.FirExtensionRegistrar
import org.jetbrains.kotlin.fir.extensions.FirExtensionRegistrarAdapter
class KotlinxReflectFirExtensionRegistrar(
val messageCollector: MessageCollector,
val kotlinxReflectRegisterForModuleClassFqName: String,
val forReflection: List<String>
) : FirExtensionRegistrar() {
override fun ExtensionRegistrarContext.configurePlugin() {
messageCollector.report(CompilerMessageSeverity.LOGGING, "KotlinxReflect-FIR: ExtensionRegistrarContext.configurePlugin")
+{ it:FirSession -> KotlinxReflectFirDeclarationGenerationExtension(it, messageCollector, kotlinxReflectRegisterForModuleClassFqName, forReflection) }
}
}
| 0 | Kotlin | 0 | 1 | 0f29e96aa48d84efb1cd41ec469a68040b31ecc3 | 943 | net.akehurst.kotlinx | Apache License 2.0 |
app/src/main/java/com/honeybilly/cleanbrowser/App.kt | liqQi | 140,266,723 | false | {"Kotlin": 46672, "Java": 6682} | package com.honeybilly.cleanbrowser
import android.app.Application
import com.honeybilly.cleanbrowser.data.DaoMaster
import com.honeybilly.cleanbrowser.data.DaoSession
import com.honeybilly.cleanbrowser.data.WebViewOpenHelper
/**
* Created by liqi on 11:36.
*
*
*/
class App : Application() {
private lateinit var daoSession: DaoSession
override fun onCreate() {
super.onCreate()
instance = this
val helper = WebViewOpenHelper(this, DB_NAME)
val db = helper.writableDb
daoSession = DaoMaster(db).newSession()
}
fun getSession(): DaoSession = daoSession
companion object {
lateinit var instance: App
private set
private const val DB_NAME = "web"
}
} | 0 | Kotlin | 0 | 0 | 175c1c0f3dc328f16c371895704d08e5ff31fedb | 749 | simplebrowser | Apache License 2.0 |
coachmark/src/main/java/com/android/library/coachmark/utility/ShapeType.kt | chhatrasal09 | 179,552,987 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 16, "XML": 18, "Java": 2} | package com.android.library.coachmark.utility
enum class ShapeType {
INSIDE,
OUTSIDE
} | 5 | Kotlin | 6 | 35 | 9db2f55dc14d93a50d7f8f709d680e827e7cdbbf | 95 | CoachMark | Apache License 2.0 |
linkable-text/src/main/java/com/github/fobid/linkabletext/widget/UrlSpanNoUnderline.kt | fobidlim | 73,983,043 | false | null | package com.github.fobid.linkabletext.widget
import android.text.TextPaint
import android.text.style.URLSpan
internal class URLSpanNoUnderline(
url: String
) : URLSpan(url) {
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
ds.isUnderlineText = false
}
} | 1 | Kotlin | 5 | 26 | efa562b99d84c46815a854608e8870e01517d949 | 308 | linkable-text-android | Apache License 2.0 |
crowdin/src/main/java/com/crowdin/platform/data/remote/Connectivity.kt | Sav22999 | 233,290,149 | true | {"Kotlin": 305831} | package com.crowdin.platform.data.remote
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkInfo
internal class Connectivity private constructor() {
companion object {
fun isOnline(context: Context): Boolean {
val info = getNetworkInfo(context)
return info != null && info.isConnected
}
fun isNetworkAllowed(context: Context, networkType: NetworkType): Boolean {
val currentNetworkType = getCurrentNetworkType(context)
when {
networkType == NetworkType.ALL &&
(currentNetworkType == NetworkType.WIFI ||
currentNetworkType == NetworkType.CELLULAR) -> {
return true
}
networkType == NetworkType.WIFI && currentNetworkType == NetworkType.WIFI -> {
return true
}
networkType == NetworkType.CELLULAR && currentNetworkType == NetworkType.CELLULAR -> {
return true
}
}
return false
}
private fun getNetworkInfo(context: Context): NetworkInfo? {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return cm.activeNetworkInfo
}
private fun getCurrentNetworkType(context: Context): NetworkType {
val info = getNetworkInfo(context)
var type = NetworkType.UNKNOWN
if (info != null && info.isConnected) {
type = NetworkType.fromConnectivityType(info.type)
}
return type
}
}
}
enum class NetworkType {
UNKNOWN,
ALL,
CELLULAR,
WIFI;
companion object {
fun fromConnectivityType(connectivityType: Int): NetworkType {
when (connectivityType) {
ConnectivityManager.TYPE_ETHERNET, ConnectivityManager.TYPE_WIFI -> return WIFI
ConnectivityManager.TYPE_MOBILE -> return CELLULAR
}
return UNKNOWN
}
}
}
| 0 | null | 0 | 0 | b1cb5894bfa51408fa6ac8dbec8f0815ff5909bf | 2,138 | mobile-sdk-android | MIT License |
app/src/main/kotlin/cz/covid19cz/erouska/ui/main/MainVM.kt | 4n6strider | 304,637,652 | true | {"Kotlin": 257534, "Java": 1863, "Shell": 384} | package cz.covid19cz.erouska.ui.main
import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.OnLifecycleEvent
import arch.livedata.SafeMutableLiveData
import com.google.firebase.auth.FirebaseAuth
import cz.covid19cz.erouska.R
import cz.covid19cz.erouska.ui.base.BaseVM
class MainVM @ViewModelInject constructor(): BaseVM() {
val serviceRunning = SafeMutableLiveData(false)
private val auth: FirebaseAuth = FirebaseAuth.getInstance()
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {
if (auth.currentUser == null) {
setNavigationGraph(R.navigation.nav_graph, R.id.nav_welcome_fragment)
} else {
setNavigationGraph(R.navigation.nav_graph, R.id.nav_dashboard)
}
}
} | 0 | null | 0 | 0 | 8c1e2822c53085b8d2ea0b017fe2bdb158d9db34 | 800 | erouska-android | MIT License |
SerawaziApplication/app/src/main/java/com/greenrevive/serawaziapplication/API_KEY.kt | MutindaVictoria | 718,561,733 | false | {"Kotlin": 107697} | package com.greenrevive.serawaziapplication
object API_KEY {
const val MY_API_KEY = "<KEY>"
} | 0 | Kotlin | 0 | 0 | 3e68806907fa0489274d5625a35d220ffb79c9a0 | 98 | Serawazi-Mobile | MIT License |
client/src/androidMain/kotlin/com/oztechan/ccc/client/base/BaseViewModel.kt | CurrencyConverterCalculator | 102,633,334 | false | null | /*
* Copyright (c) 2020 <NAME>. All rights reserved.
*/
package com.github.mustafaozhan.ccc.client.base
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineScope
@Suppress("EmptyDefaultConstructor")
actual open class BaseViewModel actual constructor() : ViewModel() {
protected actual val clientScope: CoroutineScope = viewModelScope
actual override fun onCleared() {
super.onCleared()
}
}
| 20 | Kotlin | 21 | 170 | 97e7f7c9a1b0342bef0fa551f8dd335c95861ab8 | 476 | CCC | Apache License 2.0 |
NotesFirebase(Kotlin)/app/src/main/java/com/example/notesfirebase/utlis/Config.kt | DSC-Galgotias | 547,749,268 | false | null | package com.example.notesfirebase.utlis
import android.content.Context
import androidx.appcompat.app.AlertDialog
import com.example.notesfirebase.R
import com.google.android.material.dialog.MaterialAlertDialogBuilder
object Config {
var dialog: AlertDialog? = null
fun showDialog(context: Context) {
dialog = MaterialAlertDialogBuilder(context)
.setView(R.layout.loading_layout)
.setCancelable(false)
.create()
dialog?.show()
}
fun hideDialog() {
dialog?.dismiss()
}
} | 1 | Java | 72 | 10 | 78d025801bb11983cca12b7e1766321d2bc19ac5 | 551 | Hacktoberfest2022 | MIT License |
domain/src/test/java/com/instaleap/domain/usecase/GetFavoriteTvUseCaseTest.kt | rovargas15 | 845,909,506 | false | {"Kotlin": 255524, "Shell": 3714} | package com.instaleap.domain.usecase
import com.instaleap.domain.model.Tv
import com.instaleap.domain.repository.TvRepository
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Test
class GetFavoriteTvUseCaseTest {
private val repository: TvRepository = mockk()
private val getAllTvUseCase = GetAllTvUseCase(repository)
@Test
fun `Give success When invoke Then return tv list`() =
runBlocking {
// Given
val tvList = listOf<Tv>(mockk())
coEvery { repository.getTvByCategoryCache() } returns flowOf(tvList)
// When
val result = getAllTvUseCase.invoke()
// Then
assertEquals(tvList, result.firstOrNull())
coVerify { repository.getTvByCategoryCache() }
}
}
| 0 | Kotlin | 0 | 0 | 277fc502e04753aa81295f167523691033ae8fd0 | 980 | Instaflix | Apache License 2.0 |
app/src/main/java/ca/on/hojat/gamenews/feature_info/presentation/widgets/header/artworks/GameInfoArtworkUiModelMapper.kt | hojat72elect | 574,228,468 | false | null | package ca.on.hojat.gamenews.feature_info.presentation.widgets.header.artworks
import ca.on.hojat.gamenews.core.factories.IgdbImageSize
import ca.on.hojat.gamenews.core.factories.IgdbImageUrlFactory
import ca.on.hojat.gamenews.core.domain.entities.Image
import com.paulrybitskyi.hiltbinder.BindType
import javax.inject.Inject
internal interface GameInfoArtworkUiModelMapper {
fun mapToUiModel(image: Image): GameInfoArtworkUiModel
}
@BindType(installIn = BindType.Component.VIEW_MODEL)
internal class GameInfoArtworkUiModelMapperImpl @Inject constructor(
private val igdbImageUrlFactory: IgdbImageUrlFactory,
) : GameInfoArtworkUiModelMapper {
override fun mapToUiModel(image: Image): GameInfoArtworkUiModel {
return igdbImageUrlFactory.createUrl(
image = image,
config = IgdbImageUrlFactory.Config(IgdbImageSize.BIG_SCREENSHOT),
)
?.let { url -> GameInfoArtworkUiModel.UrlImage(id = image.id, url = url) }
?: GameInfoArtworkUiModel.DefaultImage
}
}
internal fun GameInfoArtworkUiModelMapper.mapToUiModels(
images: List<Image>,
): List<GameInfoArtworkUiModel> {
if (images.isEmpty()) return listOf(GameInfoArtworkUiModel.DefaultImage)
return images.map(::mapToUiModel)
.filterIsInstance<GameInfoArtworkUiModel.UrlImage>()
}
| 0 | Kotlin | 0 | 2 | 80ff667af63e00b09aac129bb1206f520452700a | 1,330 | GameHub | Apache License 2.0 |
day11/src/main/java/com/joeygibson/aoc2022/day11/App.kt | joeygibson | 571,669,607 | false | {"Kotlin": 79226, "Shell": 3320, "Python": 1872} | package com.joeygibson.aoc2022.day11
import com.googlecode.lanterna.terminal.Terminal
import picocli.CommandLine
import java.io.File
import java.io.IOException
import java.util.concurrent.Callable
import kotlin.system.exitProcess
@CommandLine.Command(
name = "day11",
mixinStandardHelpOptions = true,
version = ["day11 1.0.0"],
description = ["AoC 2022 day11"]
)
class App : Callable<Int> {
@CommandLine.Parameters(index = "0", description = ["The file to process"])
val file: File? = null
private lateinit var terminal: Terminal
@Throws(IOException::class)
override fun call(): Int {
if (file == null) {
println("Usage: day11 <input file>")
exitProcess(1)
}
val lines = file.readText().split("\n\n")
.map {
it.split("\n")
}
printResults("part1", part1(buildMonkeys(lines)))
printResults("part2", part2(buildMonkeys(lines)))
return 0
}
private fun buildMonkeys(fileLines: List<List<String>>): List<Monkey> {
return fileLines
.map { lines ->
val id = lines[0].split(" ")[1].replace(":", "").toInt()
val items = lines[1].split(": ")[1]
.split(""",\s*""".toRegex())
.map { Item(it.toLong()) }
.toMutableList()
val opChunks = lines[2].split("old ")[1].split(" ")
val op = if (opChunks[1] != "old") {
if (opChunks[0] == "+") {
{ old: Long -> old + opChunks[1].toInt() }
} else {
{ old: Long -> old * opChunks[1].toInt() }
}
} else {
if (opChunks[0] == "+") {
{ old: Long -> old + old }
} else {
{ old: Long -> old * old }
}
}
val test = lines[3].split("divisible by ")[1].toLong()
val trueMonkey = lines[4].split("monkey ")[1].toInt()
val falseMonkey = lines[5].split("monkey ")[1].toInt()
Monkey(id, items, test, trueMonkey, falseMonkey, op)
}
}
private fun part1(monkeys: List<Monkey>): Any {
(0 until 20).forEach { turn ->
monkeys.forEach { monkey ->
monkey.takeTurn(monkeys, 3)
}
}
return monkeys
.sortedByDescending { it.inspectionCount }
.take(2)
.map { it.inspectionCount }
.reduce { a, b -> a * b }
}
private fun part2(monkeys: List<Monkey>): Any {
val worryReducer = monkeys
.map { it.test }
.fold(1L) { a, b -> a * b }
(0 until 10_000).forEach { turn ->
monkeys.forEach { monkey ->
monkey.takeTurn(monkeys, worryReducer)
}
}
return monkeys
.sortedByDescending { it.inspectionCount }
.take(2)
.map { it.inspectionCount }
.reduce { a, b -> a * b }
}
}
data class Item(var worry: Long) {
fun inspect(op: (Long) -> Long) {
worry = op(worry)
assert(worry >= 0)
}
fun expressBoredom(worryReducer: Long) {
if (worryReducer == 3L) {
worry /= 3
} else {
worry %= worryReducer
}
}
fun test(testVal: Long): Boolean = worry % testVal == 0L
}
data class Monkey(
val number: Int,
val items: MutableList<Item>,
val test: Long,
val trueMonkey: Int,
val falseMonkey: Int,
val operation: (Long) -> Long
) {
var inspectionCount = 0L
fun takeTurn(monkeys: List<Monkey>, worryReducer: Long) {
items.forEach { item ->
item.inspect(operation)
item.expressBoredom(worryReducer)
if (item.test(test)) {
monkeys[trueMonkey].items.add(item)
} else {
monkeys[falseMonkey].items.add(item)
}
inspectionCount++
}
items.clear()
}
} | 0 | Kotlin | 0 | 0 | c66e8434fb3156550485c11703aae0a4b36b584b | 4,173 | adventofcode2022 | MIT License |
schoolDomain/src/main/kotlin/com/intelligentbackpack/schooldomain/entities/calendar/alteration/IntervalOfDaysAlteration.kt | IntelligentBackpack | 629,745,884 | false | null | package com.intelligentbackpack.schooldomain.entities.calendar.alteration
import java.time.LocalDate
/**
* Represents an alteration event that alters the original calendar for an interval of days
*
* @property initialDate the initial date of the interval
* @property finalDate the final date of the interval
*/
interface IntervalOfDaysAlteration : AlterationEvent {
val initialDate: LocalDate
val finalDate: LocalDate
}
| 0 | Kotlin | 0 | 0 | 61bfdc8c21801a14d67c62b69a07a0fb341aab6d | 435 | IntelligentBackpackApp | MIT License |
door-compiler/src/main/kotlin/com/ustadmobile/lib/annotationprocessor/core/ext/KSAnnotatedExt.kt | UstadMobile | 344,538,858 | false | null | package com.ustadmobile.lib.annotationprocessor.core.ext
import com.google.devtools.ksp.KspExperimental
import com.google.devtools.ksp.getAnnotationsByType
import com.google.devtools.ksp.isAnnotationPresent
import com.google.devtools.ksp.symbol.KSAnnotated
import com.google.devtools.ksp.symbol.KSAnnotation
import kotlin.reflect.KClass
/**
* As per experimental getAnnotationsByType, but returns the KSAnnotation instance
*/
fun <T: Annotation> KSAnnotated.getKSAnnotationsByType(annotationKClass: KClass<T>): Sequence<KSAnnotation> {
return annotations.filter { it.isAnnotationClass(annotationKClass) }
}
/**
* Wrapper to avoid OptIn. This implementation is trivial and could be changed.
*/
@OptIn(KspExperimental::class)
fun <T: Annotation> KSAnnotated.hasAnnotation(annotationKClazz: KClass<T>): Boolean {
return isAnnotationPresent(annotationKClazz)
}
fun <T: Annotation> KSAnnotated.hasAnyAnnotation(vararg annotationKClass: KClass<out T>): Boolean {
return annotationKClass.any { this.hasAnnotation(it) }
}
@OptIn(KspExperimental::class)
fun <T: Annotation> KSAnnotated.getAnnotation(annotationKClazz: KClass<T>): T? {
return getAnnotationsByType(annotationKClazz).firstOrNull()
}
@OptIn(KspExperimental::class)
fun <T: Annotation> KSAnnotated.getAnnotations(annotationKClazz: KClass<T>): List<T> {
return getAnnotationsByType(annotationKClazz).toList()
}
@OptIn(KspExperimental::class)
fun <T: Annotation> KSAnnotated.getAnnotationOrNull(annotationKClazz: KClass<T>): T? {
return getAnnotationsByType(annotationKClazz).firstOrNull()
}
| 0 | Kotlin | 0 | 89 | 58f93d9057ece78cc3f8be3d4d235c0204a15f11 | 1,580 | door | Apache License 2.0 |
src/me/anno/remsstudio/utils/Naming.kt | AntonioNoack | 266,471,164 | false | {"Kotlin": 996755, "GLSL": 6755, "Java": 1308} | package me.anno.remsstudio.utils
object Naming {
fun incrementName(name: String): String {
val lastHash = name.lastIndexOf('#')
if (lastHash > -1) {
val value = name.substring(lastHash + 1).trim().toIntOrNull()
if (value != null) {
return "${name.substring(0, lastHash)}#${value + 1}"
}
}
return "${name.trim()} #2"
}
} | 2 | Kotlin | 3 | 19 | c9c0d366d1f2d08a57da72f7315bb161579852f2 | 412 | RemsStudio | Apache License 2.0 |
src/main/kotlin/Atom.kt | zensum | 100,732,002 | false | null | package leia
import java.util.concurrent.atomic.AtomicReference
/**
* An atom wraps provides a single element of state. It does this by providing
* an [AtomicReference] to an immutable value.
*/
interface Atom<T> {
val reference: AtomicReference<T>
} | 0 | null | 2 | 5 | 4b7689b8338b8dd369b92cb5badb9b223740e062 | 259 | leia | MIT License |
src/main/kotlin/com/framstag/semtrail/scanner/TokenType.kt | Framstag | 166,638,904 | false | {"Kotlin": 44789, "HTML": 11242, "CSS": 5572, "Dockerfile": 432, "Shell": 182} | package com.framstag.semtrail
enum class TokenType {
LEFT_BRACKET,
RIGHT_BRACKET,
LEFT_CURLY_BRACKET,
RIGHT_CURLY_BRACKET,
QUOTE,
SYMBOL,
ATOM,
STRING,
EOL
} | 7 | Kotlin | 0 | 0 | 61b8d2f4d0531980dada89f1c10b0255fae41fd9 | 194 | semtrail | Apache License 2.0 |
src/commonMain/kotlin/io/github/rk012/taskboard/Taskboard.kt | rk012 | 468,767,458 | false | {"Kotlin": 27599} | package io.github.rk012.taskboard
import com.benasher44.uuid.uuid4
import io.github.rk012.taskboard.exceptions.NoSuchLabelException
import io.github.rk012.taskboard.items.Goal
import io.github.rk012.taskboard.items.Task
import io.github.rk012.taskboard.items.TaskObject
import io.github.rk012.taskboard.serialization.SerializableTaskboard
import kotlinx.datetime.Clock
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlin.reflect.KClass
class Taskboard(var name: String) {
private val taskObjects = mutableMapOf<String, TaskObject>()
private val labels = mutableListOf<String>()
enum class SortOptions(internal val comparable: (TaskObject) -> Comparable<*>) {
DEPENDENTS({ -1 * it.getDependentSet().size }), // negated for descending order
TIME({ it.time }),
NAME({ it.name })
}
enum class FilterItems(internal val clazz: KClass<*>) {
TASK(Task::class),
GOAL(Goal::class),
ALL(TaskObject::class)
}
companion object {
private fun createFromSerializable(s: SerializableTaskboard): Taskboard {
val tb = Taskboard(s.name)
s.labels.forEach { tb.labels.add(it) }
s.tasks.forEach { tb.taskObjects[it.id] = Task.createFromSerializable(it) }
s.goals.forEach { tb.taskObjects[it.id] = Goal.createFromSerializable(it) }
tb.taskObjects.values.forEach {
when (it) {
is Task -> it.loadDependencies(tb)
is Goal -> it.loadDependencies(tb)
}
}
return tb
}
fun fromJson(json: String) = createFromSerializable(Json.decodeFromString(json))
}
private fun <T> Collection<T>.containsAny(other: Collection<T>): Boolean {
other.forEach {
if (contains(it)) return true
}
return false
}
operator fun get(id: String) = taskObjects[id]
fun createTask(
name: String,
time: LocalDateTime = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
): Task {
var id = uuid4().toString().split('-').joinToString("")
if (!taskObjects.containsKey(id.substring(0..7))) {
id = id.substring(0..7)
}
val task = Task(name, id, time)
taskObjects[task.id] = task
return task
}
fun createGoal(
name: String,
time: LocalDateTime = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
): Goal {
var id = uuid4().toString().split('-').joinToString("")
if (!taskObjects.containsKey(id.substring(0..7))) {
id = id.substring(0..7)
}
val goal = Goal(name, id, time)
taskObjects[goal.id] = goal
return goal
}
fun removeObject(obj: TaskObject): Boolean {
if (taskObjects.remove(obj.id) == null) return false
obj.delink()
return true
}
fun createLabel(name: String): Boolean = if (!hasLabel(name)) {
labels.add(name)
true
} else false
fun hasLabel(name: String) = labels.contains(name)
fun addLabel(obj: TaskObject, name: String, createNew: Boolean = false): Boolean {
if (createNew) createLabel(name)
return if (hasLabel(name) && !obj.labels.contains(name)) obj.labels.add(name) else false
}
fun removeLabel(obj: TaskObject, name: String): Boolean = if (!hasLabel(name)) false else obj.labels.remove(name)
fun deleteLabel(name: String): Boolean = if (!hasLabel(name)) false else {
taskObjects.values.filter { it.labels.contains(name) }.forEach { it.labels.remove(name) }
labels.remove(name)
true
}
fun query(
sortOptions: List<SortOptions> = emptyList(),
includeLabels: List<String> = emptyList(),
requireAllLabels: Boolean = false,
excludeLabels: List<String> = emptyList(),
excludeCompleted: Boolean = false,
excludeNotStarted: Boolean = false,
filterItem: FilterItems = FilterItems.ALL
): List<TaskObject> {
val sortComparables = mutableListOf<(TaskObject) -> Comparable<*>?>()
sortOptions.forEach {
sortComparables.add(it.comparable)
}
SortOptions.values().forEach {
if (!sortComparables.contains(it.comparable)) sortComparables.add(it.comparable)
}
includeLabels.forEach {
if (!hasLabel(it)) throw NoSuchLabelException(it)
}
excludeLabels.forEach {
if (!hasLabel(it)) throw NoSuchLabelException(it)
}
return taskObjects.values.filter {
filterItem.clazz.isInstance(it) &&
(
includeLabels.isEmpty() ||
(!requireAllLabels && it.labels.containsAny(includeLabels)) ||
(requireAllLabels && it.labels.containsAll(includeLabels))
) &&
(!excludeCompleted || it.status != TaskStatus.COMPLETE) &&
(!excludeNotStarted || it.status != TaskStatus.NOT_STARTED) &&
!it.labels.containsAny(excludeLabels)
}.sortedWith(compareBy(*sortComparables.toTypedArray()))
}
private fun toSerializable() = SerializableTaskboard(
name,
labels,
taskObjects.values.filterIsInstance<Task>().map { it.toSerializable() },
taskObjects.values.filterIsInstance<Goal>().map { it.toSerializable() }
)
fun toJson() = Json.encodeToString(toSerializable())
} | 0 | Kotlin | 0 | 0 | 07a039313cdbceec35dfce820c59c78ba7c0d9ac | 5,801 | taskboard-core | MIT License |
wear/wear-phone-interactions/src/test/java/androidx/wear/phone/interactions/authentication/RemoteAuthTest.kt | RikkaW | 389,105,112 | 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
*
* 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 androidx.wear.phone.interactions.authentication
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.net.Uri
import android.os.Build
import android.os.IBinder
import android.os.RemoteException
import android.util.Pair
import androidx.annotation.RequiresApi
import androidx.test.core.app.ApplicationProvider
import androidx.wear.phone.interactions.WearPhoneInteractionsTestRunner
import com.google.common.truth.Truth.assertThat
import java.util.concurrent.Executor
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito
import org.robolectric.Shadows
import org.robolectric.annotation.Config
import org.robolectric.annotation.internal.DoNotInstrument
/** Unit tests for [RemoteAuthClient]. */
@RunWith(WearPhoneInteractionsTestRunner::class)
@DoNotInstrument // Needed because it is defined in the "android" package.
@Config(minSdk = 26)
@RequiresApi(Build.VERSION_CODES.O)
public class RemoteAuthTest {
@Config(minSdk = 26)
@RequiresApi(Build.VERSION_CODES.O)
internal companion object {
private val context: Context = ApplicationProvider.getApplicationContext()
private val shadowPackageManager = Shadows.shadowOf(context.packageManager)
private val DIRECT_EXECUTOR = Executor { command -> command.run() }
private const val authProviderUrlA = "http://myrequesturl/a?client_id=iamtheclient"
private const val authProviderUrlB = "http://myrequesturl/b?client_id=iamtheclient"
private val responseUrl = Uri.parse("http://myresponseurl")
private val appPackageName = context.packageName
private var requestA: OAuthRequest
private var requestB: OAuthRequest
init {
setSystemFeatureChina(false)
requestA =
OAuthRequest.Builder(context)
.setAuthProviderUrl(Uri.parse(authProviderUrlA))
.setCodeChallenge(CodeChallenge(CodeVerifier()))
.build()
requestB =
OAuthRequest.Builder(context)
.setAuthProviderUrl(Uri.parse(authProviderUrlB))
.setCodeChallenge(CodeChallenge(CodeVerifier()))
.build()
}
private val response = OAuthResponse.Builder().setResponseUrl(responseUrl).build()
// Note: This can't be static as Robolectric isn't set up at class init time.
private val mServiceName = ComponentName(
"com.google.android.wearable.app", "auth_lib_shouldnt_care_about_this"
)
private val mockCallback: RemoteAuthClient.Callback =
Mockito.mock(RemoteAuthClient.Callback::class.java)
private fun setSystemFeatureChina(value: Boolean) {
shadowPackageManager.setSystemFeature("cn.google", value)
}
}
private var fakeServiceBinder: FakeServiceBinder = FakeServiceBinder()
private var fakeService: FakeClockworkHomeAuthService = FakeClockworkHomeAuthService()
private var clientUnderTest: RemoteAuthClient =
RemoteAuthClient(fakeServiceBinder, DIRECT_EXECUTOR, appPackageName)
private val executor: Executor = SyncExecutor()
@Test
public fun doesntConnectUntilARequestIsMade() {
// WHEN the client is created
// THEN the Auth library should not yet connect to Clockwork Home
assertThat(fakeServiceBinder.state).isEqualTo(ConnectionState.DISCONNECTED)
}
@Test
public fun sendAuthorizationRequestShouldMakeConnectionToClockworkHome() {
setSystemFeatureChina(false)
val requestUri = "http://myrequesturl?client_id=xxx"
// WHEN an authorization request is sent
clientUnderTest.sendAuthorizationRequest(
OAuthRequest.Builder(context)
.setAuthProviderUrl(Uri.parse(requestUri))
.setCodeChallenge(CodeChallenge(CodeVerifier()))
.build(),
executor,
mockCallback
)
// THEN a connection is made to Clockwork Home's Auth service
assertThat(fakeServiceBinder.state).isEqualTo(ConnectionState.CONNECTING)
}
@Test
public fun sendAuthorizationRequestShouldCallBinderMethod() {
// WHEN an authorization request is sent
clientUnderTest.sendAuthorizationRequest(requestA, executor, mockCallback)
fakeServiceBinder.completeConnection()
// THEN a request is made to Clockwork Home
val request = fakeService.requests[0]
val requestReceived = request.first
// THEN the request url is set correctly
assertThat(requestReceived.requestUrl).isEqualTo(requestA.requestUrl)
assertThat(requestReceived.requestUrl.toString().indexOf(authProviderUrlA)).isEqualTo(0)
}
@Test
public fun twoQueuedAuthorizationRequestsBeforeConnectCompletes() {
// GIVEN two authorization requests were made before connecting to Clockwork Home completes
clientUnderTest.sendAuthorizationRequest(requestA, executor, mockCallback)
clientUnderTest.sendAuthorizationRequest(requestB, executor, mockCallback)
// WHEN the connection does complete
fakeServiceBinder.completeConnection()
// THEN two requests are made to Clockwork Home
val requestAReceived = fakeService.requests[0].first
val requestBReceived = fakeService.requests[1].first
assertThat(fakeService.requests.size.toLong()).isEqualTo(2)
// THEN the request url is set correctly for both (A then B)
assertThat(requestAReceived.requestUrl).isEqualTo(requestA.requestUrl)
assertThat(requestBReceived.requestUrl).isEqualTo(requestB.requestUrl)
assertThat(requestAReceived.requestUrl.toString().indexOf(authProviderUrlA)).isEqualTo(0)
assertThat(requestBReceived.requestUrl.toString().indexOf(authProviderUrlB)).isEqualTo(0)
}
@Test
@Throws(RemoteException::class)
public fun requestCompletionShouldCallBackToClient() {
// GIVEN an authorization request was sent
clientUnderTest.sendAuthorizationRequest(requestA, executor, mockCallback)
fakeServiceBinder.completeConnection()
val request = fakeService.requests[0]
// WHEN the request completes
// callback supplied earlier is called with the correct request URL and response URL
Mockito.verify(mockCallback).onAuthorizationResponse(request.first, response)
}
@Test
@Throws(RemoteException::class)
public fun doesntDisconnectWhenRequestStillInProgress() {
// GIVEN 2 authorization requests were sent
clientUnderTest.sendAuthorizationRequest(requestA, executor, mockCallback)
// GIVEN the async binding to Clockwork Home completed after the 1st but before the 2nd
fakeServiceBinder.completeConnection()
clientUnderTest.sendAuthorizationRequest(requestB, executor, mockCallback)
// WHEN the first one completes
RemoteAuthService.sendResponseToCallback(
response,
fakeService.requests[0].second
)
// THEN the service remains connected (as there's still a request ongoing, and we won't get
// the callback for the other request if we unbind now)
assertThat(fakeServiceBinder.state).isEqualTo(ConnectionState.CONNECTED)
}
@Test
@Throws(RemoteException::class)
public fun disconnectsWhenAllRequestsComplete() {
// GIVEN 2 authorization requests were sent
clientUnderTest.sendAuthorizationRequest(requestA, executor, mockCallback)
// GIVEN the async binding to Clockwork Home completed after the 1st but before the 2nd
fakeServiceBinder.completeConnection()
clientUnderTest.sendAuthorizationRequest(requestB, executor, mockCallback)
RemoteAuthService.sendResponseToCallback(
response,
fakeService.requests[0].second
)
// WHEN the other completes
RemoteAuthService.sendResponseToCallback(
response,
fakeService.requests[1].second
)
// THEN the OAuth library disconnects from Clockwork Home
assertThat(fakeServiceBinder.state).isEqualTo(ConnectionState.DISCONNECTED)
}
internal enum class ConnectionState {
DISCONNECTED, CONNECTING, CONNECTED
}
/** Fakes binding to Clockwork Home. */
private inner class FakeServiceBinder : RemoteAuthClient.ServiceBinder {
var state = ConnectionState.DISCONNECTED
private var serviceConnection: ServiceConnection? = null
override fun bindService(
intent: Intent,
connection: ServiceConnection,
flags: Int
): Boolean {
if (intent.getPackage() != RemoteAuthClient.WEARABLE_PACKAGE_NAME) {
throw UnsupportedOperationException()
}
if (intent.action != RemoteAuthClient.ACTION_AUTH) {
throw UnsupportedOperationException()
}
check(state == ConnectionState.DISCONNECTED) { "Already connected or connecting" }
state = ConnectionState.CONNECTING
serviceConnection = connection
return true
}
fun completeConnection() {
assertThat(ConnectionState.CONNECTING).isEqualTo(state)
state = ConnectionState.CONNECTED
serviceConnection!!.onServiceConnected(mServiceName, fakeService.onBind(Intent()))
}
override fun unbindService(connection: ServiceConnection?) {
check(state != ConnectionState.DISCONNECTED) { "Not connected; can't disconnect" }
state = ConnectionState.DISCONNECTED
serviceConnection = null
}
}
/**
* Fake implementation of the OAuth service in Clockwork Home. Instead of talking to the user's
* phone, this class just records the method calls that were made so we can handle them manually
* in our tests.
*/
private inner class FakeClockworkHomeAuthService : RemoteAuthService() {
private val requestHandler: RemoteAuthRequestHandler
val requests: MutableList<Pair<OAuthRequest, kotlin.Pair<String, Int>>> =
ArrayList()
init {
requestHandler = AuthenticationRequestHandler()
}
override fun onBind(intent: Intent): IBinder {
return onBind(intent, requestHandler)
}
override fun verifyPackageName(context: Context, requestPackageName: String?): Boolean {
return true
}
private inner class AuthenticationRequestHandler : RemoteAuthRequestHandler {
override fun isAuthSupported(): Boolean {
return true
}
override fun sendAuthRequest(
request: OAuthRequest,
packageNameAndRequestId: kotlin.Pair<String, Int>
) {
if (fakeServiceBinder.state != ConnectionState.CONNECTED) {
throw RemoteException("not connected")
}
requests.add(Pair.create(request, packageNameAndRequestId))
mockCallback.onAuthorizationResponse(request, response)
}
}
}
}
private class SyncExecutor : Executor {
override fun execute(command: Runnable?) {
command?.run()
}
}
| 21 | null | 862 | 7 | 6d53f95e5d979366cf7935ad7f4f14f76a951ea5 | 12,047 | androidx | Apache License 2.0 |
src/main/kotlin/no/nb/mlt/wls/domain/model/HostName.kt | NationalLibraryOfNorway | 800,484,682 | false | {"Kotlin": 98706, "JavaScript": 911, "Dockerfile": 782} | package no.nb.mlt.wls.core.data
import org.springframework.http.HttpStatus
import org.springframework.web.server.ResponseStatusException
enum class HostName {
AXIELL
}
fun throwIfInvalidClientName(
clientName: String,
hostName: HostName
) {
if (clientName.uppercase() == hostName.name) return
throw ResponseStatusException(
HttpStatus.FORBIDDEN,
"You do not have access to view resources owned by $hostName"
)
}
| 0 | Kotlin | 0 | 0 | 8f0fa54352fef42de550ef7072794c4d05eb9c94 | 455 | warehouse-logistics-service | MIT License |
paymentsheet-example/src/androidTest/java/com/stripe/android/test/core/ui/ClickTextInWebView.kt | stripe | 6,926,049 | false | {"Kotlin": 13558068, "Java": 109098, "Ruby": 45764, "HTML": 42045, "Shell": 23226, "Python": 21891} | package com.stripe.android.test.core.ui
import androidx.test.uiautomator.By
import androidx.test.uiautomator.UiDevice
import androidx.test.uiautomator.UiObject2
import androidx.test.uiautomator.Until
private const val DefaultDelayInMillis = 5_000L
private const val DefaultTimeoutInMillis = 10_000L
internal fun UiDevice.clickTextInWebView(
label: String,
delay: Boolean = false,
selectAmongOccurrences: (List<UiObject2>) -> UiObject2 = { it.single() },
) {
if (delay) {
// Some WebView texts are slowly animating in, and UiAutomator seems to struggle
// with this. These texts can provide this delay to improve the odds.
Thread.sleep(DefaultDelayInMillis)
}
val occurrences = wait(Until.findObjects(By.textContains(label)), DefaultTimeoutInMillis)
selectAmongOccurrences(occurrences).click()
}
| 102 | Kotlin | 636 | 1,251 | 98f7c4d7c3e05981d973aa4725a7307ce18998ee | 851 | stripe-android | MIT License |
src/gaea/src/main/kotlin/com/synebula/gaea/data/serialization/ISerializer.kt | synebula-myths | 205,819,036 | false | null | package com.synebula.gaea.data.serialization
/**
* 序列化器
*/
interface ISerializer {
/**
* 序列化
*
* @param <S> 源数据类型
* @param <T> 目标数据类型
* @param src 源数据
* @return 目标数据
*/
fun <S, T> serialize(src: S): T
} | 0 | Kotlin | 0 | 0 | 487176b208813794f2e8cbca38240ddfbc276e5f | 249 | gaea | MIT License |
kirby/src/main/java/com/kosoku/kirby/extension/DialogFragmentExtensions.kt | Kosoku | 478,798,167 | false | {"Kotlin": 31998} | package com.kosoku.kirby.extension
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import com.kosoku.kirby.fragment.KBYFragment
import com.kosoku.kirby.fragment.NavigationFragment
import timber.log.Timber
/**
* Extension on [DialogFragment] to get the fragment it was presented from
*/
fun DialogFragment.presentingFragment(): Fragment? {
var retval = this.parentFragment
return if (retval == null) {
val lastIndex = activity?.supportFragmentManager?.fragments?.lastIndex ?: 0
retval = if (lastIndex == 0) {
activity?.supportFragmentManager?.fragments?.lastOrNull()
} else {
activity?.supportFragmentManager?.fragments?.get(lastIndex-1)
}
if (retval is NavigationFragment) {
if (retval.childFragmentManager.fragments.isNotEmpty()) {
retval.childFragmentManager.fragments.lastOrNull()
} else {
retval
}
} else {
retval
}
} else {
if (retval is NavigationFragment && !retval.isModal) {
retval.presentingFragment()
} else {
retval
}
}
}
/**
* Extension on [DialogFragment] to recursively dismiss the current fragment and its presenters
*/
fun DialogFragment.dismissRecursively() {
val fragmentsToDismiss: MutableList<DialogFragment> = mutableListOf(this)
var parent: DialogFragment? = this.presentingFragment() as? DialogFragment
while (parent != null) {
if ((parent as? KBYFragment<*>)?.isModal == true || (parent.parentFragment as? NavigationFragment)?.isModal == true) {
fragmentsToDismiss.add(parent)
}
val presenter = parent.presentingFragment()
if ((presenter as? KBYFragment<*>)?.isModal == true || (presenter?.parentFragment as? NavigationFragment)?.isModal == true) {
parent = if (presenter is NavigationFragment && presenter.isModal) {
presenter
} else if (presenter is KBYFragment<*> && presenter.isModal) {
presenter
} else {
presenter.parentFragment as? DialogFragment
}
if (parent != null) {
fragmentsToDismiss.add(parent)
}
} else {
parent = null
}
}
fragmentsToDismiss.forEach { it.dismiss() }
}
| 0 | Kotlin | 1 | 1 | da4218586d91072314a9cf75011a9edccbd9e907 | 2,405 | Kirby | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.