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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cryptic-sequences-core/jvmTest/src/net/plcarmel/crypticsequences/core/numbers/BinaryBaseSystemTest.kt | plcarmel | 344,168,944 | false | null | package net.plcarmel.crypticsequences.core.numbers
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource
class BinaryBaseSystemTest {
@ParameterizedTest
@CsvSource(
" 2, 1, 2",
" 2, 2, 4",
" 2, 3, 8",
" 4, 1, 4",
" 4, 2, 16",
" 4, 3, 64",
" 8, 1, 8",
" 8, 2, 64",
" 8, 3, 512",
" 8, 8, 16777216",
"16, 1, 16",
"16, 2, 256",
"16, 3, 4096",
"16, 8, 4294967296"
)
fun nb_values_are_computed_correctly(base: Int, wordSize: Int, expectedNbValues: Long) {
assertEquals(1, base.countOneBits())
assertEquals(expectedNbValues, BinaryBaseSystem(nbBits=base.countTrailingZeroBits()).nbValues(wordSize))
}
@ParameterizedTest
@CsvSource(
" 2, 0",
" 2, 1",
" 2, 12",
" 2, 123",
" 4, 0",
" 4, 1",
" 4, 12",
" 4, 123",
" 8, 1",
" 8, 12",
" 8, 123",
" 8, 1234",
"16, 1",
"16, 12",
"16, 123",
"16, 1234",
"16, 1",
"16, 12",
"16, 123",
"16, 1234",
)
fun combine_digits_at_is_inverse_of_extract_digits_at(base: Int, value: Long) {
assertEquals(1, base.countOneBits())
val baseSystem = BinaryBaseSystem(nbBits = base.countTrailingZeroBits())
val bytes = byteArrayOf(0,0,0,0,0,0,0,0,0,0,0,0,0,0)
baseSystem.extractDigitsAt(bytes, value, 1, 10)
assertEquals(value, baseSystem.combineDigitsFrom(bytes, 1, 10))
}
@Test
fun extract_digits_at_adds_padding() {
val baseSystem = GenericBaseSystem(10)
val bytes = byteArrayOf(1,1,1,1,1,1,1,1,1,1,1,1,1,1)
baseSystem.extractDigitsAt(bytes, 4567, 4, 7)
Assertions.assertArrayEquals(byteArrayOf(1, 1, 1, 1, 7, 6, 5, 4, 0, 0, 0, 1, 1, 1), bytes)
}
@ParameterizedTest
@CsvSource(
" 2, 127, 1, 1, 1, 1, 1, 1, 1, 0",
" 2, 255, 1, 1, 1, 1, 1, 1, 1, 1",
" 2, 70, 0, 1, 1, 0, 0, 0, 1, 0",
" 2, 65, 1, 0, 0, 0, 0, 0, 1, 0",
" 8, 7384794, 2, 3, 3, 7, 2, 1, 4, 3",
" 8, 8050747, 3, 7, 0, 4, 5, 5, 6, 3",
" 8, 9257120, 0, 4, 2, 0, 4, 2, 3, 4",
" 8, 1237406, 6, 3, 6, 0, 6, 5, 4, 0",
" 8, 6435778, 2, 0, 7, 1, 3, 4, 0, 3",
" 8, 3565425, 1, 6, 5, 3, 6, 4, 5, 1"
)
fun extract_digits_at_is_implemented_correctly(
base: Int,
number: Long,
b0: Byte, b1: Byte, b2: Byte, b3: Byte,
b4: Byte, b5: Byte, b6: Byte, b7: Byte
) {
val baseSystem = GenericBaseSystem(base)
val bytes = byteArrayOf(7,7,7,7,7,7,7,7)
baseSystem.extractDigitsAt(bytes, number, 0, 8)
Assertions.assertArrayEquals(byteArrayOf(b0, b1, b2, b3, b4, b5, b6, b7), bytes)
}
}
| 0 | Kotlin | 0 | 0 | 2792e9632fef0cb22c4bacc49f209d3463ec5b19 | 2,876 | cryptic-sequences | MIT License |
plugin/src/main/kotlin/io/github/addoncommunity/galactifun/scripting/dsl/gen/NoiseMap.kt | Slimefun-Addon-Community | 624,085,324 | false | {"Kotlin": 166551} | package io.github.addoncommunity.galactifun.scripting.dsl.gen
import io.github.addoncommunity.galactifun.util.worldgen.DoubleChunkGrid
import org.bukkit.util.noise.OctaveGenerator
import org.bukkit.util.noise.SimplexOctaveGenerator
class NoiseMap(noises: Map<String, AbstractPerlin.PerlinConfig>) {
private val noises = noises.mapValues { Noise(it.value) }
@Volatile
private var initted = false
internal fun init(seed: Long) {
if (initted) return
synchronized(this) {
if (initted) return
noises.values.forEach { it.init(seed) }
initted = true
}
}
class Noise internal constructor(config: AbstractPerlin.PerlinConfig) {
private val octaves = config.octaves
private val scale = config.scale
private val amplitude = config.amplitude
private val frequency = config.frequency
private val smoothen = config.smoothen
@Volatile
private lateinit var noise: OctaveGenerator
private val grid = DoubleChunkGrid()
internal fun init(seed: Long) {
noise = SimplexOctaveGenerator(seed, octaves)
noise.setScale(scale)
}
operator fun invoke(x: Int, z: Int): Double {
return grid.getOrSet(x, z) {
var noise = noise.noise(x.toDouble(), z.toDouble(), frequency, amplitude, true)
if (smoothen) {
noise *= noise
}
noise
}
}
}
} | 1 | Kotlin | 2 | 5 | 8c1d3470440bf0672e63f1ebbe5554ea1822865d | 1,531 | Galactifun2 | Apache License 2.0 |
kotlin-mui-icons/src/main/generated/mui/icons/material/FileDownloadOffOutlined.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/FileDownloadOffOutlined")
@file:JsNonModule
package mui.icons.material
@JsName("default")
external val FileDownloadOffOutlined: SvgIconComponent
| 12 | Kotlin | 145 | 983 | a99345a0160a80a7a90bf1adfbfdc83a31a18dd6 | 228 | kotlin-wrappers | Apache License 2.0 |
Adapter/src/main/java/com/angcyo/dsladapter/DslAdapterItem.kt | angcyo | 201,440,286 | false | null | package com.angcyo.dsladapter
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.os.Build
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.angcyo.dsladapter.SwipeMenuHelper.Companion.SWIPE_MENU_TYPE_DEFAULT
import com.angcyo.dsladapter.SwipeMenuHelper.Companion.SWIPE_MENU_TYPE_FLOWING
import com.angcyo.library.L
import com.angcyo.library.UndefinedDrawable
import com.angcyo.library.ex.className
import com.angcyo.library.ex.elseNull
import com.angcyo.library.ex.undefined_size
import com.angcyo.tablayout.clamp
import com.angcyo.widget.DslViewHolder
import com.angcyo.widget.base.*
import com.angcyo.widget.recycler.RecyclerBottomLayout
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
*
* Email:<EMAIL>
* @author angcyo
* @date 2019/05/07
* Copyright (c) 2019 ShenZhen O&M Cloud Co., Ltd. All rights reserved.
*/
open class DslAdapterItem : LifecycleOwner {
companion object {
/**负载,请求刷新部分界面*/
const val PAYLOAD_UPDATE_PART = 0x1_00_00
/**负载,强制更新媒体, 比如图片*/
const val PAYLOAD_UPDATE_MEDIA = 0x2_00_00
}
/**适配器, 自动赋值[com.angcyo.dsladapter.DslAdapter.onBindViewHolder]*/
var itemDslAdapter: DslAdapter? = null
//<editor-fold desc="update操作">
/**[notifyItemChanged]*/
open fun updateAdapterItem(payload: Any? = PAYLOAD_UPDATE_PART, useFilterList: Boolean = true) {
itemDslAdapter?.notifyItemChanged(this, payload, useFilterList).elseNull {
L.w("跳过操作! updateAdapterItem需要[itemDslAdapter],请赋值.")
}
}
/**
* 通过diff更新
* @param notifyUpdate 是否需要触发 [Depend] 关系链.
* */
open fun updateItemDepend(
filterParams: FilterParams = FilterParams(
fromDslAdapterItem = this,
updateDependItemWithEmpty = false,
payload = PAYLOAD_UPDATE_PART
)
) {
itemDslAdapter?.updateItemDepend(filterParams).elseNull {
L.w("跳过操作! updateItemDepend需要[itemDslAdapter],请赋值.")
}
}
/**更新选项*/
open fun updateItemSelector(select: Boolean, notifyUpdate: Boolean = false) {
itemDslAdapter?.itemSelectorHelper?.selector(
SelectorParams(
this,
select.toSelectOption(),
notifySelectListener = true,
notifyItemSelectorChange = true,
updateItemDepend = notifyUpdate
)
).elseNull {
L.w("跳过操作! updateItemSelector需要[itemDslAdapter],请赋值.")
}
}
//</editor-fold desc="update操作">
//<editor-fold desc="Grid相关属性">
/**
* 在 GridLayoutManager 中, 需要占多少个 span. -1表示满屏
* [itemIsGroupHead]
* [com.angcyo.dsladapter.DslAdapter.onViewAttachedToWindow]
* 需要[dslSpanSizeLookup]支持.
*
* 在[StaggeredGridLayoutManager]中, 会使用[layoutParams.isFullSpan]的方式满屏
* */
var itemSpanCount = 1
//</editor-fold>
//<editor-fold desc="标准属性">
/**布局的xml id, 必须设置.*/
open var itemLayoutId: Int = -1
/**附加的数据*/
var itemData: Any? = null
set(value) {
field = value
onSetItemData(value)
}
/**[itemData]*/
open fun onSetItemData(data: Any?) {
}
/**强制指定item的宽高*/
var itemWidth: Int = undefined_size
var itemMinWidth: Int = undefined_size
var itemHeight: Int = undefined_size
var itemMinHeight: Int = undefined_size
/**padding值*/
var itemPaddingLeft: Int = undefined_size
var itemPaddingRight: Int = undefined_size
var itemPaddingTop: Int = undefined_size
var itemPaddingBottom: Int = undefined_size
/**指定item的背景*/
var itemBackgroundDrawable: Drawable? = UndefinedDrawable()
/**是否激活item, 目前只能控制click, longClick事件不被回调*/
var itemEnable: Boolean = true
set(value) {
field = value
onSetItemEnable(value)
}
/**[itemEnable]*/
open fun onSetItemEnable(enable: Boolean) {
}
/**唯一标识此item的值*/
var itemTag: String? = null
/**
* 界面绑定入口
* [DslAdapter.onBindViewHolder(com.angcyo.widget.DslViewHolder, int, java.util.List<? extends java.lang.Object>)]
* */
var itemBind: (itemHolder: DslViewHolder, itemPosition: Int, adapterItem: DslAdapterItem, payloads: List<Any>) -> Unit =
{ itemHolder, itemPosition, adapterItem, payloads ->
onItemBind(itemHolder, itemPosition, adapterItem, payloads)
itemBindOverride(itemHolder, itemPosition, adapterItem, payloads)
}
/**
* 点击事件和长按事件封装
* */
var itemClick: ((View) -> Unit)? = null
var itemLongClick: ((View) -> Boolean)? = null
//使用节流方式处理点击事件
var _clickListener: View.OnClickListener? = ThrottleClickListener(action = { view ->
notNull(itemClick, view) {
itemClick?.invoke(view)
}
})
var _longClickListener: View.OnLongClickListener? =
View.OnLongClickListener { view -> itemLongClick?.invoke(view) ?: false }
open fun onItemBind(
itemHolder: DslViewHolder,
itemPosition: Int,
adapterItem: DslAdapterItem,
payloads: List<Any>
) {
_initItemBackground(itemHolder)
_initItemSize(itemHolder)
_initItemPadding(itemHolder)
_initItemListener(itemHolder)
onItemBind(itemHolder, itemPosition, adapterItem)
}
open fun onItemBind(
itemHolder: DslViewHolder,
itemPosition: Int,
adapterItem: DslAdapterItem
) {
//no op
}
/**用于覆盖默认操作*/
var itemBindOverride: (itemHolder: DslViewHolder, itemPosition: Int, adapterItem: DslAdapterItem, payloads: List<Any>) -> Unit =
{ _, _, _, _ ->
}
/**
* [DslAdapter.onViewAttachedToWindow]
* */
var itemViewAttachedToWindow: (itemHolder: DslViewHolder, itemPosition: Int) -> Unit =
{ itemHolder, itemPosition ->
onItemViewAttachedToWindow(itemHolder, itemPosition)
}
/**
* [DslAdapter.onViewDetachedFromWindow]
* */
var itemViewDetachedToWindow: (itemHolder: DslViewHolder, itemPosition: Int) -> Unit =
{ itemHolder, itemPosition ->
onItemViewDetachedToWindow(itemHolder, itemPosition)
}
/**
* [DslAdapter.onViewRecycled]
* */
var itemViewRecycled: (itemHolder: DslViewHolder, itemPosition: Int) -> Unit =
{ itemHolder, itemPosition ->
onItemViewRecycled(itemHolder, itemPosition)
}
//</editor-fold desc="标准属性">
//<editor-fold desc="内部初始化">
//初始化背景
open fun _initItemBackground(itemHolder: DslViewHolder) {
itemHolder.itemView.isSelected = itemIsSelected
if (itemBackgroundDrawable !is UndefinedDrawable) {
itemHolder.itemView.apply {
setBgDrawable(itemBackgroundDrawable)
}
}
}
//初始化宽高
open fun _initItemSize(itemHolder: DslViewHolder) {
val itemView = itemHolder.itemView
if (itemView is RecyclerBottomLayout) {
//RecyclerBottomLayout不支持调整item height
return
}
//初始化默认值
if (itemMinWidth == undefined_size && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
itemMinWidth = itemView.minimumWidth
}
if (itemMinHeight == undefined_size && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
itemMinHeight = itemView.minimumHeight
}
//设置
if (itemMinWidth != undefined_size) {
itemView.minimumWidth = itemMinWidth
when (itemView) {
is ConstraintLayout -> itemView.minWidth = itemMinWidth
}
}
if (itemMinHeight != undefined_size) {
itemView.minimumHeight = itemMinHeight
when (itemView) {
is ConstraintLayout -> itemView.minHeight = itemMinHeight
}
}
//初始化默认值
if (itemWidth == undefined_size) {
itemWidth = itemView.layoutParams.width
}
if (itemHeight == undefined_size) {
itemHeight = itemView.layoutParams.height
}
//设置
itemView.setWidthHeight(itemWidth, itemHeight)
}
//初始化事件
open fun _initItemListener(itemHolder: DslViewHolder) {
if (itemClick == null || _clickListener == null || !itemEnable) {
itemHolder.itemView.isClickable = false
} else {
itemHolder.clickItem(_clickListener)
}
if (itemLongClick == null || _longClickListener == null || !itemEnable) {
itemHolder.itemView.isLongClickable = false
} else {
itemHolder.itemView.setOnLongClickListener(_longClickListener)
}
}
//初始化padding
open fun _initItemPadding(itemHolder: DslViewHolder) {
if (itemPaddingLeft == undefined_size) {
itemPaddingLeft = itemHolder.itemView.paddingLeft
}
if (itemPaddingRight == undefined_size) {
itemPaddingRight = itemHolder.itemView.paddingRight
}
if (itemPaddingTop == undefined_size) {
itemPaddingTop = itemHolder.itemView.paddingTop
}
if (itemPaddingBottom == undefined_size) {
itemPaddingBottom = itemHolder.itemView.paddingBottom
}
itemHolder.itemView.setPadding(
itemPaddingLeft,
itemPaddingTop,
itemPaddingRight,
itemPaddingBottom
)
}
//</editor-fold desc="内部初始化">
//<editor-fold desc="分组相关属性">
/**
* 当前item, 是否是分组的头, 设置了分组, 默认会开启悬停
*
* 如果为true, 哪里折叠此分组是, 会 伪删除 这个分组头, 到下一个分组头 中间的 data
* */
var itemIsGroupHead = false
set(value) {
field = value
if (value) {
itemIsHover = true
itemDragEnable = false
itemSpanCount = -1
}
}
/**
* 当前分组是否[展开]
* */
var itemGroupExtend: Boolean by UpdateDependProperty(true)
/**是否需要隐藏item*/
var itemHidden: Boolean by UpdateDependProperty(false)
//</editor-fold>
//<editor-fold desc="悬停相关属性">
/**
* 是否需要悬停, 在使用了 [HoverItemDecoration] 时, 有效.
* [itemIsGroupHead]
* */
var itemIsHover: Boolean = itemIsGroupHead
//</editor-fold>
//<editor-fold desc="表单/分割线配置">
/**
* 需要插入分割线的大小
* */
var itemTopInsert = 0
var itemLeftInsert = 0
var itemRightInsert = 0
var itemBottomInsert = 0
var itemDecorationColor = Color.TRANSPARENT
/**更强大的分割线自定义, 在color绘制后绘制*/
var itemDecorationDrawable: Drawable? = null
/**
* 仅绘制offset的区域
* */
var onlyDrawOffsetArea = false
/**
* 分割线绘制时的偏移
* */
var itemTopOffset = 0
var itemLeftOffset = 0
var itemRightOffset = 0
var itemBottomOffset = 0
/**可以覆盖设置分割线的边距*/
var onSetItemOffset: (rect: Rect) -> Unit = {}
/**分割线入口 [DslItemDecoration]*/
fun setItemOffsets(rect: Rect) {
rect.set(itemLeftInsert, itemTopInsert, itemRightInsert, itemBottomInsert)
onSetItemOffset(rect)
}
/**
* 绘制不同方向的分割线时, 触发的回调, 可以用来设置不同方向分割线的颜色
* */
var eachDrawItemDecoration: (left: Int, top: Int, right: Int, bottom: Int) -> Unit =
{ _, _, _, _ ->
}
/**自定义绘制*/
var onDraw: ((
canvas: Canvas,
paint: Paint,
itemView: View,
offsetRect: Rect,
itemCount: Int,
position: Int,
drawRect: Rect
) -> Unit)? = null
/**
* 分割线支持需要[DslItemDecoration]
* */
open fun draw(
canvas: Canvas,
paint: Paint,
itemView: View,
offsetRect: Rect,
itemCount: Int,
position: Int,
drawRect: Rect
) {
//super.draw(canvas, paint, itemView, offsetRect, itemCount, position)
onDraw?.let {
it(canvas, paint, itemView, offsetRect, itemCount, position, drawRect)
return
}
eachDrawItemDecoration(0, itemTopInsert, 0, 0)
paint.color = itemDecorationColor
val drawOffsetArea = onlyDrawOffsetArea
if (itemTopInsert > 0) {
if (onlyDrawOffsetArea) {
//绘制左右区域
if (itemLeftOffset > 0) {
drawRect.set(
itemView.left,
itemView.top - offsetRect.top,
itemView.left + itemLeftOffset,
itemView.top
)
canvas.drawRect(drawRect, paint)
onDrawItemDecorationDrawable(canvas, drawRect)
}
if (itemRightOffset > 0) {
drawRect.set(
itemView.right - itemRightOffset,
itemView.top - offsetRect.top,
itemView.right,
itemView.top
)
canvas.drawRect(drawRect, paint)
onDrawItemDecorationDrawable(canvas, drawRect)
}
} else {
drawRect.set(
itemView.left + itemLeftOffset,
itemView.top - offsetRect.top,
itemView.right - itemRightOffset,
itemView.top
)
canvas.drawRect(drawRect, paint)
onDrawItemDecorationDrawable(canvas, drawRect)
}
}
onlyDrawOffsetArea = drawOffsetArea
eachDrawItemDecoration(0, 0, 0, itemBottomInsert)
paint.color = itemDecorationColor
if (itemBottomInsert > 0) {
if (onlyDrawOffsetArea) {
//绘制左右区域
if (itemLeftOffset > 0) {
drawRect.set(
itemView.left,
itemView.bottom,
itemView.left + itemLeftOffset,
itemView.bottom + offsetRect.bottom
)
canvas.drawRect(drawRect, paint)
onDrawItemDecorationDrawable(canvas, drawRect)
}
if (itemRightOffset > 0) {
drawRect.set(
itemView.right - itemRightOffset,
itemView.bottom,
itemView.right,
itemView.bottom + offsetRect.bottom
)
canvas.drawRect(drawRect, paint)
onDrawItemDecorationDrawable(canvas, drawRect)
}
} else {
drawRect.set(
itemView.left + itemLeftOffset,
itemView.bottom,
itemView.right - itemRightOffset,
itemView.bottom + offsetRect.bottom
)
canvas.drawRect(drawRect, paint)
onDrawItemDecorationDrawable(canvas, drawRect)
}
}
onlyDrawOffsetArea = drawOffsetArea
eachDrawItemDecoration(itemLeftInsert, 0, 0, 0)
paint.color = itemDecorationColor
if (itemLeftInsert > 0) {
if (onlyDrawOffsetArea) {
//绘制上下区域
if (itemTopOffset > 0) {
drawRect.set(
itemView.left - offsetRect.left,
itemView.top,
itemView.left,
itemTopOffset
)
canvas.drawRect(drawRect, paint)
onDrawItemDecorationDrawable(canvas, drawRect)
}
if (itemBottomOffset < 0) {
drawRect.set(
itemView.left - offsetRect.left,
itemView.bottom - itemBottomOffset,
itemView.left,
itemView.bottom
)
canvas.drawRect(drawRect, paint)
onDrawItemDecorationDrawable(canvas, drawRect)
}
} else {
drawRect.set(
itemView.left - offsetRect.left,
itemView.top + itemTopOffset,
itemView.left,
itemView.bottom - itemBottomOffset
)
canvas.drawRect(drawRect, paint)
onDrawItemDecorationDrawable(canvas, drawRect)
}
}
onlyDrawOffsetArea = drawOffsetArea
eachDrawItemDecoration(0, 0, itemRightInsert, 0)
paint.color = itemDecorationColor
if (itemRightInsert > 0) {
if (onlyDrawOffsetArea) {
//绘制上下区域
if (itemTopOffset > 0) {
drawRect.set(
itemView.right,
itemView.top,
itemView.right + offsetRect.right,
itemTopOffset
)
canvas.drawRect(drawRect, paint)
onDrawItemDecorationDrawable(canvas, drawRect)
}
if (itemBottomOffset < 0) {
drawRect.set(
itemView.right,
itemView.bottom - itemBottomOffset,
itemView.right + offsetRect.right,
itemView.bottom
)
canvas.drawRect(drawRect, paint)
onDrawItemDecorationDrawable(canvas, drawRect)
}
} else {
drawRect.set(
itemView.right,
itemView.top + itemTopOffset,
itemView.right + offsetRect.right,
itemView.bottom - itemBottomOffset
)
canvas.drawRect(drawRect, paint)
onDrawItemDecorationDrawable(canvas, drawRect)
}
}
onlyDrawOffsetArea = drawOffsetArea
}
var onDrawItemDecorationDrawable: (canvas: Canvas, rect: Rect) -> Unit = { canvas, rect ->
itemDecorationDrawable?.let {
it.setBounds(rect.left, rect.top, rect.right, rect.bottom)
it.draw(canvas)
}
}
//</editor-fold desc="表单/分割线配置">
//<editor-fold desc="Diff相关">
/**
* 决定
* [RecyclerView.Adapter.notifyItemInserted]
* [RecyclerView.Adapter.notifyItemRemoved]
* 的执行
* */
var thisAreItemsTheSame: (
fromItem: DslAdapterItem?, newItem: DslAdapterItem,
oldItemPosition: Int, newItemPosition: Int
) -> Boolean =
{ _, newItem, oldItemPosition, newItemPosition ->
this == newItem ||
(this.className() == newItem.className() && oldItemPosition == newItemPosition)
}
/**
* [RecyclerView.Adapter.notifyItemChanged]
* */
var thisAreContentsTheSame: (
fromItem: DslAdapterItem?, newItem: DslAdapterItem,
oldItemPosition: Int, newItemPosition: Int
) -> Boolean =
{ fromItem, newItem, _, _ ->
when {
itemChanging || newItem.itemChanging -> false
(newItem.itemData != null && this.itemData != null && newItem.itemData == this.itemData) -> true
fromItem == null -> this == newItem
else -> this != fromItem && this == newItem
}
}
var thisGetChangePayload: (
fromItem: DslAdapterItem?, filterPayload: Any?, newItem: DslAdapterItem,
oldItemPosition: Int, newItemPosition: Int
) -> Any? =
{ _, filterPayload, _, _, _ ->
filterPayload ?: PAYLOAD_UPDATE_PART
}
//</editor-fold desc="Diff相关">
//<editor-fold desc="定向更新">
/**标识此[Item]是否发生过改变, 可用于实现退出界面提示是否保存内容.*/
var itemChanged = false
set(value) {
field = value
if (value) {
itemChangeListener(this)
}
}
/**[Item]是否正在改变, 会影响[thisAreContentsTheSame]的判断, 并且会在[Diff]计算完之后, 设置为`false`*/
var itemChanging = false
set(value) {
field = value
if (value) {
itemChanged = true
}
}
/**
* 当[itemChanged]为true之后, 触发的回调.
* 如果拦截了默认操作, 需要注意[updateItemDepend]方法的触发时机
*
* 提供一个可以完全被覆盖的方法*/
var itemChangeListener: (DslAdapterItem) -> Unit = {
onItemChangeListener(it)
}
/**其次, 提供一个可以被子类覆盖的方法*/
open fun onItemChangeListener(item: DslAdapterItem) {
updateItemDepend()
}
/**
* [checkItem] 是否需要关联到处理列表
* [itemIndex] 分组折叠之后数据列表中的index
*
* 返回 true 时, [checkItem] 进行 [hide] 操作
* */
var isItemInHiddenList: (checkItem: DslAdapterItem, itemIndex: Int) -> Boolean =
{ _, _ -> false }
/**
* [itemIndex] 最终过滤之后数据列表中的index
* 返回 true 时, [checkItem] 会收到 来自 [this] 的 [itemUpdateFrom] 触发的回调
* */
var isItemInUpdateList: (checkItem: DslAdapterItem, itemIndex: Int) -> Boolean =
{ _, _ -> false }
/**入口方法*/
var itemUpdateFrom: (fromItem: DslAdapterItem) -> Unit = {
onItemUpdateFrom(it)
}
/**覆盖方法 [itemUpdateFrom]*/
open fun onItemUpdateFrom(fromItem: DslAdapterItem) {
}
//</editor-fold desc="定向更新">
//<editor-fold desc="单选/多选相关">
/**是否选中, 需要 [ItemSelectorHelper.selectorModel] 的支持. */
var itemIsSelected = false
/**是否 允许被选中*/
var isItemCanSelected: (fromSelector: Boolean, toSelector: Boolean) -> Boolean =
{ from, to -> from != to }
var onItemSelectorChange: (selectorParams: SelectorParams) -> Unit = {
if (it.updateItemDepend) {
updateItemDepend()
}
}
/**选中变化后触发*/
open fun _itemSelectorChange(selectorParams: SelectorParams) {
onItemSelectorChange(selectorParams)
}
//</editor-fold desc="单选/多选相关">
//<editor-fold desc="群组相关">
/**动态计算的属性*/
val itemGroupParams: ItemGroupParams
get() =
itemDslAdapter?.findItemGroupParams(this) ?: ItemGroupParams(
0,
this,
mutableListOf(this)
)
/**所在的分组名, 只用来做快捷变量存储*/
var itemGroups: List<String> = listOf()
/**核心群组判断的方法*/
var isItemInGroups: (newItem: DslAdapterItem) -> Boolean = { newItem ->
var result = if (itemGroups.isEmpty()) {
//如果自身没有配置分组信息, 那么取相同类名, 布局id一样的item, 当做一组
className() == newItem.className() && itemLayoutId == newItem.itemLayoutId
} else {
false
}
for (group in newItem.itemGroups) {
result = result || itemGroups.contains(group)
if (result) {
break
}
}
result
}
//</editor-fold>
//<editor-fold desc="拖拽相关">
/**
* 当前[DslAdapterItem]是否可以被拖拽.需要[DragCallbackHelper]的支持
* [itemIsGroupHead]
* [DragCallbackHelper.getMovementFlags]
* */
var itemDragEnable = true
/**
* 当前[DslAdapterItem]是否可以被侧滑删除.需要[DragCallbackHelper]的支持
* */
var itemSwipeEnable = true
/**支持拖拽的方向, 0表示不开启拖拽
* [ItemTouchHelper.LEFT]
* [ItemTouchHelper.RIGHT]
* [ItemTouchHelper.UP]
* [ItemTouchHelper.DOWN]
* */
var itemDragFlag = -1
/**支持滑动删除的方向, 0表示不开启滑动
* [ItemTouchHelper.LEFT]
* [ItemTouchHelper.RIGHT]
* */
var itemSwipeFlag = -1
/**[dragItem]是否可以在此位置[this]放下*/
var isItemCanDropOver: (dragItem: DslAdapterItem) -> Boolean = {
itemDragEnable
}
//</editor-fold>
//<editor-fold desc="侧滑菜单相关">
/**用于控制打开or关闭菜单*/
var _itemSwipeMenuHelper: SwipeMenuHelper? = null
/**是否激活侧滑菜单.需要[SwipeMenuHelper]的支持*/
var itemSwipeMenuEnable = true
/**支持滑动菜单打开的手势方向.
* [ItemTouchHelper.LEFT]
* [ItemTouchHelper.RIGHT]
* */
var itemSwipeMenuFlag = ItemTouchHelper.LEFT
/**滑动菜单滑动的方式*/
var itemSwipeMenuType = SWIPE_MENU_TYPE_DEFAULT
/**侧滑菜单滑动至多少距离, 重写此方法, 自行处理UI效果*/
var itemSwipeMenuTo: (itemHolder: DslViewHolder, dX: Float, dY: Float) -> Unit =
{ itemHolder, dX, dY ->
onItemSwipeMenuTo(itemHolder, dX, dY)
}
/**滑动菜单的宽度*/
var itemSwipeWidth: (itemHolder: DslViewHolder) -> Int = {
it.itemView.getChildOrNull(0).mW()
}
/**滑动菜单的高度*/
var itemSwipeHeight: (itemHolder: DslViewHolder) -> Int = {
it.itemView.getChildOrNull(0).mH()
}
/**请将menu, 布局在第1个child的位置, 并且布局的[left]和[top]都是0
* 默认的UI效果就是, TranslationX.
* 默认实现暂时只支持左/右滑动的菜单, 上/下滑动菜单不支持
* */
open fun onItemSwipeMenuTo(itemHolder: DslViewHolder, dX: Float, dY: Float) {
val parent = itemHolder.itemView
if (parent is ViewGroup && parent.childCount > 1) {
//菜单最大的宽度, 用于限制滑动的边界
val menuWidth = itemSwipeWidth(itemHolder)
val tX = clamp(dX, -menuWidth.toFloat(), menuWidth.toFloat())
parent.forEach { index, child ->
if (index == 0) {
if (itemSwipeMenuType == SWIPE_MENU_TYPE_FLOWING) {
if (dX > 0) {
child.translationX = -menuWidth + tX
} else {
child.translationX = parent.mW() + tX
}
} else {
if (dX > 0) {
child.translationX = 0f
} else {
child.translationX = (parent.mW() - menuWidth).toFloat()
}
}
} else {
child.translationX = tX
}
}
}
}
//</editor-fold>
//<editor-fold desc="Tree 树结构相关">
/**
* 折叠/展开 依旧使用[itemGroupExtend]控制
*
* 子项列表
* */
var itemSubList: MutableList<DslAdapterItem> = mutableListOf()
/**
* 在控制[itemSubList]之前, 都会回调此方法.
* 相当于hook了[itemSubList], 可以在[itemSubList]为空时, 展示[加载中Item]等
* */
var itemLoadSubList: () -> Unit = {}
/**父级列表, 会自动赋值*/
var itemParentList: MutableList<DslAdapterItem> = mutableListOf()
//</editor-fold>
//<editor-fold desc="Lifecycle支持">
val lifecycleRegistry = LifecycleRegistry(this)
override fun getLifecycle(): Lifecycle {
return lifecycleRegistry
}
/**请勿覆盖[itemViewAttachedToWindow]*/
open fun onItemViewAttachedToWindow(itemHolder: DslViewHolder, itemPosition: Int) {
lifecycleRegistry.currentState = Lifecycle.State.RESUMED
}
/**请勿覆盖[itemViewDetachedToWindow]*/
open fun onItemViewDetachedToWindow(itemHolder: DslViewHolder, itemPosition: Int) {
lifecycleRegistry.currentState = Lifecycle.State.STARTED
}
/**请勿覆盖[itemViewRecycled]*/
open fun onItemViewRecycled(itemHolder: DslViewHolder, itemPosition: Int) {
lifecycleRegistry.currentState = Lifecycle.State.DESTROYED
itemHolder.clear()
}
//</editor-fold desc="Lifecycle支持">
}
class UpdateDependProperty<T>(var value: T) : ReadWriteProperty<DslAdapterItem, T> {
override fun getValue(thisRef: DslAdapterItem, property: KProperty<*>): T = value
override fun setValue(thisRef: DslAdapterItem, property: KProperty<*>, value: T) {
val old = this.value
this.value = value
if (old != value) {
thisRef.updateItemDepend(FilterParams(thisRef, updateDependItemWithEmpty = true))
}
}
} | 4 | null | 37 | 350 | 6dec07e4695c7795d9ed5cc3c754202c9562c111 | 27,917 | DslAdapter | MIT License |
src/test/kotlin/no/nav/familie/ef/sak/infotrygd/InfotrygdPeriodeTestUtil.kt | navikt | 206,805,010 | false | null | package no.nav.familie.ef.sak.infotrygd
import no.nav.familie.kontrakter.ef.infotrygd.InfotrygdAktivitetstype
import no.nav.familie.kontrakter.ef.infotrygd.InfotrygdEndringKode
import no.nav.familie.kontrakter.ef.infotrygd.InfotrygdOvergangsstønadKode
import no.nav.familie.kontrakter.ef.infotrygd.InfotrygdPeriode
import no.nav.familie.kontrakter.ef.infotrygd.InfotrygdSakstype
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.YearMonth
object InfotrygdPeriodeTestUtil {
fun lagInfotrygdPeriode(
personIdent: String = "1",
stønadFom: LocalDate = YearMonth.now().atDay(1),
stønadTom: LocalDate = YearMonth.now().atEndOfMonth(),
opphørsdato: LocalDate? = null,
stønadId: Int = 1,
vedtakId: Int = 1,
beløp: Int = 1,
inntektsgrunnlag: Int = 1,
inntektsreduksjon: Int = 1,
samordningsfradrag: Int = 1,
utgifterBarnetilsyn: Int = 1,
kode: InfotrygdEndringKode = InfotrygdEndringKode.NY,
sakstype: InfotrygdSakstype = InfotrygdSakstype.SØKNAD,
aktivitetstype: InfotrygdAktivitetstype? = InfotrygdAktivitetstype.BRUKERKONTAKT,
kodeOvergangsstønad: InfotrygdOvergangsstønadKode? = InfotrygdOvergangsstønadKode.BARN_UNDER_1_3_ÅR,
barnIdenter: List<String> = emptyList()
): InfotrygdPeriode {
return InfotrygdPeriode(
personIdent = personIdent,
kode = kode,
sakstype = sakstype,
kodeOvergangsstønad = kodeOvergangsstønad,
aktivitetstype = aktivitetstype,
brukerId = "k40123",
stønadId = stønadId.toLong(),
vedtakId = vedtakId.toLong(),
inntektsgrunnlag = inntektsgrunnlag,
inntektsreduksjon = inntektsreduksjon,
samordningsfradrag = samordningsfradrag,
utgifterBarnetilsyn = utgifterBarnetilsyn,
månedsbeløp = beløp,
engangsbeløp = beløp,
startDato = LocalDate.now(),
vedtakstidspunkt = LocalDateTime.now(),
stønadFom = stønadFom,
stønadTom = stønadTom,
opphørsdato = opphørsdato,
barnIdenter = barnIdenter
)
}
}
| 8 | Kotlin | 2 | 0 | d1d8385ead500c4d24739b970940af854fa5fe2c | 2,228 | familie-ef-sak | MIT License |
kzen-auto-js/src/jsMain/kotlin/tech/kzen/auto/client/api/ReactWrapper.kt | alexoooo | 131,353,826 | false | {"Kotlin": 1902613, "Java": 163744, "CSS": 5632, "JavaScript": 203} | package tech.kzen.auto.client.api
import js.objects.JsoDsl
import react.ChildrenBuilder
interface ReactWrapper<T: react.Props> {
fun ChildrenBuilder.child(block: @JsoDsl T.() -> Unit)
fun child(builder: ChildrenBuilder, block: @JsoDsl T.() -> Unit) {
builder.apply {
child(block)
}
}
} | 1 | Kotlin | 1 | 1 | 97a140f0599d1eb3dc9dd3075b6a4fdbc5daaba0 | 329 | kzen-auto | MIT License |
app/src/main/java/com/akusuka/githubers/widget/MyFavoriteStackWidget.kt | ayadiyulianto | 297,043,731 | false | null | package com.akusuka.githubers.widget
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.widget.RemoteViews
import androidx.core.app.TaskStackBuilder
import androidx.core.net.toUri
import com.akusuka.githubers.DetailActivity
import com.akusuka.githubers.FavoriteActivity
import com.akusuka.githubers.R
class MyFavoriteStackWidget : AppWidgetProvider() {
companion object {
fun sendRefreshBroadcast(context: Context) {
val intent = Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE)
intent.component = ComponentName(context, MyFavoriteStackWidget::class.java)
context.sendBroadcast(intent)
}
}
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
// update all widget
for (appWidgetId in appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId)
}
}
private fun updateAppWidget(context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int) {
val intent = Intent(context, StackWidgetService::class.java)
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
intent.data = intent.toUri(Intent.URI_INTENT_SCHEME).toUri()
val views = RemoteViews(context.packageName, R.layout.widget_my_favorite_stack)
views.setRemoteAdapter(R.id.stack_view, intent)
views.setEmptyView(R.id.stack_view, R.id.empty_view)
// onclick title widget
val titleIntent = Intent(context, FavoriteActivity::class.java)
val titlePendingIntent = PendingIntent.getActivity(context, 0, titleIntent, 0)
views.setOnClickPendingIntent(R.id.banner_text, titlePendingIntent)
// onclick item info
val clickIntentTemplate = Intent(context, DetailActivity::class.java)
val clickPendingIntentTemplate: PendingIntent? = TaskStackBuilder.create(context)
.addNextIntentWithParentStack(clickIntentTemplate)
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
views.setPendingIntentTemplate(R.id.stack_view, clickPendingIntentTemplate)
appWidgetManager.updateAppWidget(appWidgetId, views)
}
override fun onReceive(context: Context, intent: Intent) {
super.onReceive(context, intent)
if (intent.action == AppWidgetManager.ACTION_APPWIDGET_UPDATE) {
// refresh all widgets
val mgr = AppWidgetManager.getInstance(context)
val cn = ComponentName(context, MyFavoriteStackWidget::class.java)
mgr.notifyAppWidgetViewDataChanged(mgr.getAppWidgetIds(cn), R.id.stack_view)
}
}
} | 0 | Kotlin | 0 | 0 | 251dfd3ac15b43defab7928fe46f9f9d01928028 | 2,830 | Githubers | MIT License |
compiler/testData/diagnostics/testsWithStdLib/contracts/smartcasts/callWithDefaultValue.kt | JetBrains | 3,432,266 | false | null | // LANGUAGE: +AllowContractsForCustomFunctions +UseReturnsEffect
// OPT_IN: kotlin.contracts.ExperimentalContracts
// DIAGNOSTICS: -INVISIBLE_REFERENCE -INVISIBLE_MEMBER
import kotlin.contracts.*
fun myAssert(condition: Boolean, message: String = "") {
contract {
returns() implies (condition)
}
if (!condition) throw kotlin.IllegalArgumentException(message)
}
fun test(x: Any?) {
myAssert(x is String)
x.length
} | 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 444 | kotlin | Apache License 2.0 |
src/test/kotlin/no/nav/amt/deltaker/bff/innbygger/InnbyggerServiceTest.kt | navikt | 701,285,451 | false | {"Kotlin": 484428, "PLpgSQL": 635, "Dockerfile": 194} | package no.nav.amt.deltaker.bff.innbygger
import io.kotest.matchers.shouldBe
import kotlinx.coroutines.runBlocking
import no.nav.amt.deltaker.bff.deltaker.DeltakerService
import no.nav.amt.deltaker.bff.deltaker.db.DeltakerRepository
import no.nav.amt.deltaker.bff.deltaker.db.sammenlignDeltakere
import no.nav.amt.deltaker.bff.deltaker.model.sammenlignVedtak
import no.nav.amt.deltaker.bff.utils.MockResponseHandler
import no.nav.amt.deltaker.bff.utils.SingletonPostgresContainer
import no.nav.amt.deltaker.bff.utils.data.TestData
import no.nav.amt.deltaker.bff.utils.data.TestRepository
import no.nav.amt.deltaker.bff.utils.mockAmtDeltakerClient
import org.junit.Assert.assertThrows
import org.junit.BeforeClass
import org.junit.Test
class InnbyggerServiceTest {
private val amtDeltakerClient = mockAmtDeltakerClient()
private val deltakerService = DeltakerService(DeltakerRepository(), amtDeltakerClient)
private val innbyggerService = InnbyggerService(amtDeltakerClient, deltakerService)
companion object {
@JvmStatic
@BeforeClass
fun setup() {
SingletonPostgresContainer.start()
}
}
@Test
fun `fattVedtak - deltaker har ikke vedtak som kan fattes - feiler`() {
val deltaker = TestData.lagDeltaker()
assertThrows(IllegalArgumentException::class.java) {
runBlocking {
innbyggerService.fattVedtak(deltaker)
}
}
}
@Test
fun `fattVedtak - deltaker har vedtak som kan fattes - kaller amtDeltaker og oppdaterer deltaker`() {
val deltaker = deltakerMedIkkeFattetVedtak()
TestRepository.insert(deltaker)
val deltakerMedFattetVedtak = deltaker.fattVedtak()
MockResponseHandler.addFattVedtakResponse(deltakerMedFattetVedtak, deltaker.ikkeFattetVedtak!!)
runBlocking {
val oppdatertDeltaker = innbyggerService.fattVedtak(deltaker)
oppdatertDeltaker.ikkeFattetVedtak shouldBe null
deltaker.ikkeFattetVedtak!!.id shouldBe oppdatertDeltaker.fattetVedtak!!.id
sammenlignDeltakere(oppdatertDeltaker, deltakerMedFattetVedtak)
sammenlignVedtak(oppdatertDeltaker.vedtaksinformasjon!!, deltakerMedFattetVedtak.vedtaksinformasjon!!)
}
}
}
| 1 | Kotlin | 0 | 0 | fe05b04d1b3bde5879076daca8326e6025a6e67c | 2,291 | amt-deltaker-bff | MIT License |
ybatis/src/test/kotlin/com.sununiq/handler/ForEachProcessorTest.kt | Sitrone | 155,659,453 | false | null | package com.sununiq.handler
import com.sununiq.entity.Column
import com.sununiq.entity.Table
import com.sununiq.handler.token.TokenParser
import com.sununiq.util.parseXml
import com.sununiq.util.println
import com.sununiq.util.removeChildNodes
import com.sununiq.util.transform2String
import org.apache.commons.lang3.StringEscapeUtils
import org.apache.commons.lang3.StringUtils
import org.junit.Test
import org.w3c.dom.Node
class ForEachProcessorTest {
@Test
fun testForEach() {
val target = """
<enhancer:foreach list="allColumns" var="elem">
<if test="@{elem.javaName} != null">
and `@{elem.jdbcName}` = #{@{elem.javaName}}
</if>
</enhancer:foreach>
""".trimIndent()
val column1 = Column("id", "id", "long", "long")
val column2 = Column("age", "age", "long", "long")
val columns = listOf(column1, column2)
val table = Table("user", "utf-8", "", "",
columns, columns, columns, Column::class.java, "column",
"com.sununiq.Column", "", mutableMapOf()
)
val nodeProcessor = ForEachProcessor()
val node = parseXml(target).documentElement as Node
val result = nodeProcessor.process(table, node, TokenParser())
println(result)
}
@Test
fun processNode() {
val target = """
<select id="selectEntity" parameterType="@{domainClassName}"
resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from @{tableName}
where 1 = 1
<enhancer:foreach list="allColumns" var="elem">
<if test="@{elem.javaName} != null">
and `@{elem.jdbcName}` = #{@{elem.javaName}}
</if>
</enhancer:foreach>
limit 1
</select>
""".trimIndent()
val document = parseXml(target)
val element = document.documentElement
element.tagName.println()
// element.textContent.println()
val content = transform2String(element.childNodes)
transform2String(document).println()
removeChildNodes(element)
transform2String(document).println()
val textNode = document.createTextNode(content)
element.appendChild(textNode)
transform2String(document).println()
StringEscapeUtils.unescapeXml(transform2String(document)).println()
}
@Test
fun testHandleAttrubute() {
val target = """
<select id="selectEntity" parameterType="@{domainClassName}"
resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from @{tableName}
where 1 = 1
<enhancer:foreach list="allColumns" var="elem">
<if test="@{elem.javaName} != null">
and `@{elem.jdbcName}` = #{@{elem.javaName}}
</if>
</enhancer:foreach>
limit 1
</select>
""".trimIndent()
val document = parseXml(target)
val element = document.documentElement
val attributes = element.attributes
}
@Test
fun testHandleWithBracket() {
val target = """
<insert id="insertBatch"
keyProperty="@{primaryColumns.0.jdbcName}" useGeneratedKeys="true"
parameterType="java.util.List">
insert into @{tableName}
(<include refid="Base_Column_List" />)
values
<foreach collection="list" index="index" item="item"
separator=",">
(
<enhancer:foreach list="allColumns" var="elem"
split=",">
#{item.@{elem.javaName}}
</enhancer:foreach>
)
</foreach>
</insert>
""".trimIndent()
val document = parseXml(target)
val element = document.documentElement
val attributes = element.attributes
for (i in 0 until element.childNodes.length) {
if (element.childNodes.item(i).nodeType == Node.TEXT_NODE) {
i.println()
transform2String(element.childNodes.item(i)).println()
}
}
}
} | 1 | null | 1 | 1 | e06616a6f541f45ec7f61707667eda6af04d15e1 | 4,532 | mybatis-enhancer | MIT License |
compiler/testData/diagnostics/tests/inference/upperBounds/nonNullUpperBound.kt | JakeWharton | 99,388,807 | false | null | fun <R : Any> unescape(value: Any): R? = throw Exception("$value")
fun <T: Any> foo(v: Any): T? = unescape(v)
//--------------
interface A
fun <R : A> unescapeA(value: Any): R? = throw Exception("$value")
fun <T: A> fooA(v: Any): T? = unescapeA(v)
| 181 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 255 | kotlin | Apache License 2.0 |
app/src/main/java/com/ziggeo/androidsdk/demo/util/BundleExtractorDelegate.kt | Ziggeo | 44,632,250 | false | {"Kotlin": 183047} | package com.ziggeo.androidsdk.demo.util
import android.os.Bundle
import androidx.fragment.app.Fragment
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* Created by <NAME> on 25-Sep-19.
* Ziggeo, Inc.
* <EMAIL>
*/
inline fun <reified T> argument(
key: String,
defaultValue: T? = null
): ReadWriteProperty<Fragment, T> =
BundleExtractorDelegate { thisRef ->
extractFromBundle(
bundle = thisRef.arguments,
key = key,
defaultValue = defaultValue
)
}
inline fun <reified T> extractFromBundle(
bundle: Bundle?,
key: String,
defaultValue: T? = null
): T {
val result = bundle?.get(key) ?: defaultValue
if (result != null && result !is T) {
throw ClassCastException("Property $key has different class type")
}
return result as T
}
class BundleExtractorDelegate<R, T>(private val initializer: (R) -> T) : ReadWriteProperty<R, T> {
private object EMPTY
private var value: Any? = EMPTY
override fun setValue(thisRef: R, property: KProperty<*>, value: T) {
this.value = value
}
override fun getValue(thisRef: R, property: KProperty<*>): T {
if (value == EMPTY) {
value = initializer(thisRef)
}
@Suppress("UNCHECKED_CAST")
return value as T
}
} | 5 | Kotlin | 5 | 8 | 0609cda01b8dca9a876732f565974ffee1560808 | 1,355 | android-sdk-demo | Apache License 2.0 |
paypal/src/test/java/com/paysafe/android/paypal/PSPayPalControllerTest.kt | paysafegroup | 768,755,663 | false | {"Kotlin": 637209, "Shell": 912} | /*
* Copyright (c) 2024 Paysafe Group
*/
package com.paysafe.android.paypal
import androidx.activity.result.ActivityResultCaller
import androidx.appcompat.app.AppCompatActivity
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.LifecycleCoroutineScope
import androidx.lifecycle.lifecycleScope
import com.paypal.android.paypalnativepayments.PayPalNativeCheckoutClient
import com.paypal.android.paypalnativepayments.PayPalNativeCheckoutListener
import com.paysafe.android.PaysafeSDK
import com.paysafe.android.core.data.entity.PSResult
import com.paysafe.android.core.data.entity.value
import com.paysafe.android.core.data.service.PSApiClient
import com.paysafe.android.core.domain.model.config.PSEnvironment
import com.paysafe.android.paymentmethods.PaymentMethodsServiceImpl
import com.paysafe.android.paymentmethods.domain.model.AccountConfiguration
import com.paysafe.android.paymentmethods.domain.model.PaymentMethod
import com.paysafe.android.paymentmethods.domain.model.PaymentMethodType
import com.paysafe.android.paypal.domain.model.PSPayPalConfig
import com.paysafe.android.paypal.domain.model.PSPayPalTokenizeOptions
import com.paysafe.android.paypal.exception.amountShouldBePositiveException
import com.paysafe.android.paypal.exception.currencyCodeInvalidIsoException
import com.paysafe.android.paypal.exception.genericApiErrorException
import com.paysafe.android.paypal.exception.improperlyCreatedMerchantAccountConfigException
import com.paysafe.android.paypal.exception.invalidAccountIdForPaymentMethodException
import com.paysafe.android.paypal.exception.payPalFailedAuthorizationException
import com.paysafe.android.paypal.exception.payPalUserCancelledException
import com.paysafe.android.paypal.exception.tokenizationAlreadyInProgressException
import com.paysafe.android.tokenization.PSTokenization
import com.paysafe.android.tokenization.PSTokenizationService
import com.paysafe.android.tokenization.domain.model.paymentHandle.PaymentHandle
import com.paysafe.android.tokenization.domain.model.paymentHandle.TransactionType
import com.paysafe.android.tokenization.domain.model.paymentHandle.paypal.PSPayPalLanguage
import com.paysafe.android.tokenization.domain.model.paymentHandle.paypal.PSPayPalShippingPreference
import com.paysafe.android.tokenization.domain.model.paymentHandle.paypal.PayPalRequest
import io.mockk.Runs
import io.mockk.clearAllMocks
import io.mockk.coEvery
import io.mockk.every
import io.mockk.just
import io.mockk.justRun
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.unmockkAll
import io.mockk.verify
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
@RunWith(RobolectricTestRunner::class)
@OptIn(ExperimentalCoroutinesApi::class)
class PSPayPalControllerTest {
@get:Rule
var instantExecutorRule = InstantTaskExecutorRule()
private val accountIdInput = "accountId"
private val currencyCodeInput = "USD"
private val applicationIdInput = "applicationId"
private val clientIdInput = "clientIdInput"
private val correlationId = "testCorrelationId"
private val application = RuntimeEnvironment.getApplication()
private val psPayPalConfigValidInput = PSPayPalConfig(
currencyCode = currencyCodeInput,
accountId = accountIdInput,
applicationId = applicationIdInput
)
private val psPayPalTokenizeOptions = PSPayPalTokenizeOptions(
amount = 100,
currencyCode = currencyCodeInput,
transactionType = TransactionType.PAYMENT,
merchantRefNum = PaysafeSDK.getMerchantReferenceNumber(),
accountId = accountIdInput,
payPalRequest = PayPalRequest(
consumerId = "consumerId",
recipientDescription = "recipientDescription",
language = PSPayPalLanguage.US,
shippingPreference = PSPayPalShippingPreference.SET_PROVIDED_ADDRESS,
consumerMessage = "consumerMessage",
orderDescription = "orderDescription"
)
)
private lateinit var mockActivity: AppCompatActivity
private lateinit var mockPSApiClient: PSApiClient
private lateinit var mockLifecycleScope: LifecycleCoroutineScope
private lateinit var mockActivityResultCaller: ActivityResultCaller
private lateinit var mockPSTokenizationService: PSTokenizationService
private lateinit var mockPayPalNativeCheckoutClient: PayPalNativeCheckoutClient
private lateinit var mockPSPayPalTokenizeCallback: PSPayPalTokenizeCallback
@Before
fun setUp() {
mockkObject(PaysafeSDK)
justRun { PaysafeSDK.setup(any()) }
mockPSApiClient = mockk(relaxed = true)
mockActivity = Robolectric.buildActivity(AppCompatActivity::class.java).create().get()
mockLifecycleScope = mockk<LifecycleCoroutineScope>(relaxed = true)
mockActivityResultCaller = mockk<ActivityResultCaller>(relaxed = true)
mockPSTokenizationService = mockk<PSTokenization>()
mockPayPalNativeCheckoutClient = mockk<PayPalNativeCheckoutClient>()
every { PaysafeSDK.getPSApiClient() } returns mockPSApiClient
every { mockPSApiClient.getCorrelationId() } returns correlationId
mockPSPayPalTokenizeCallback = mockk<PSPayPalTokenizeCallback>()
every { mockPSPayPalTokenizeCallback.onFailure(any()) } just Runs
every { mockPSPayPalTokenizeCallback.onCancelled(any()) } just Runs
every { mockPSPayPalTokenizeCallback.onSuccess(any()) } just Runs
}
@After
fun clear() {
unmockkAll()
clearAllMocks()
}
private fun providePSPayPalController() = PSPayPalController(
lifecycleScope = mockActivity.lifecycleScope,
psApiClient = mockPSApiClient,
tokenizationService = mockPSTokenizationService,
payPalNativeCheckoutClient = mockPayPalNativeCheckoutClient
)
@Test
fun `IF initialize with invalid currencyCode THEN initialize RETURNS Failure with currencyCodeInvalidIsoException`() =
runTest {
// Arrange
// Act
val result = PSPayPalController.initialize(
application,
mockLifecycleScope,
PSPayPalConfig(
currencyCode = "wrongCurrencyCode",
accountId = accountIdInput,
applicationId = applicationIdInput
),
mockPSApiClient
)
val exception = (result as PSResult.Failure).exception
// Assert
assertEquals(currencyCodeInvalidIsoException(correlationId), exception)
}
@Test
fun `IF initialize and validatePaymentMethods returns Failure THEN initialize RETURNS Failure`() =
runTest {
// Arrange
mockkObject(PSPayPalController)
val toReturnResult = PSResult.Failure(Exception())
coEvery {
PSPayPalController.validatePaymentMethods(any(), any(), any(), any())
} returns toReturnResult
// Act
val result = PSPayPalController.initialize(
application = application,
lifecycleScope = mockLifecycleScope,
config = psPayPalConfigValidInput,
psApiClient = mockPSApiClient
)
// Assert
assertEquals(toReturnResult, result)
}
@Test
fun `IF initialize and validatePaymentMethods returns Success with null THEN initialize RETURNS Failure with improperlyCreatedMerchantAccountConfigException`() =
runTest {
// Arrange
mockkObject(PSPayPalController)
coEvery {
PSPayPalController.validatePaymentMethods(any(), any(), any(), any())
} returns PSResult.Success(null)
// Act
val result = PSPayPalController.initialize(
application = application,
lifecycleScope = mockLifecycleScope,
config = psPayPalConfigValidInput,
psApiClient = mockPSApiClient
)
val exception = (result as PSResult.Failure).exception
// Assert
assertEquals(improperlyCreatedMerchantAccountConfigException(correlationId), exception)
}
@Test
fun `IF initialize and validatePaymentMethods returns Success THEN initialize RETURNS Success`() =
runTest {
// Arrange
Dispatchers.setMain(UnconfinedTestDispatcher(testScheduler))
mockkObject(PSPayPalController)
val validatePaymentMethodsResult = PSResult.Success(clientIdInput)
coEvery {
PSPayPalController.validatePaymentMethods(any(), any(), any(), any())
} returns validatePaymentMethodsResult
val mockPSPayPalController = mockk<PSPayPalController>()
coEvery {
PSPayPalController.handleValidatePaymentMethodsResultSuccess(
validatePaymentMethodsResult = validatePaymentMethodsResult,
psApiClient = any(),
config = any(),
application = any(),
lifecycleScope = any()
)
} returns PSResult.Success(mockPSPayPalController)
// Act
val result = PSPayPalController.initialize(
application = application,
lifecycleScope = mockLifecycleScope,
config = psPayPalConfigValidInput,
psApiClient = mockPSApiClient
)
val controller = (result as PSResult.Success).value!!
// Assert
assertEquals(mockPSPayPalController, controller)
}
@Test
fun `IF validatePaymentMethods returns Success with PROD environment THEN validatePaymentMethods RETURNS Success`() =
runTest {
// Arrange
every { mockPSApiClient.environment } returns PSEnvironment.PROD
mockkObject(PSPayPalController)
val validatePaymentMethodsResult = PSResult.Success(clientIdInput)
// Act
val result = PSPayPalController.handleValidatePaymentMethodsResultSuccess(
validatePaymentMethodsResult = validatePaymentMethodsResult,
psApiClient = mockPSApiClient,
config = psPayPalConfigValidInput,
application = application,
lifecycleScope = mockLifecycleScope
)
val controller = (result as PSResult.Success).value!!
// Assert
assertNotNull(controller)
}
@Test
fun `IF encodeToString THEN logEventContent matches expectedLogString`() =
runTest {
// Arrange
val logEventContent = with(psPayPalConfigValidInput) {
LogEventContent(
currencyCode = currencyCode,
accountId = accountId
)
}
val expectedLogString =
"{\"currencyCode\":\"${logEventContent.currencyCode}\",\"accountId\":\"${logEventContent.accountId}\"}"
// Act
val encodedLogString = Json.encodeToString(logEventContent)
// Assert
assertEquals(expectedLogString, encodedLogString)
}
@Test
fun `IF handleValidatePaymentMethodsResultSuccess returns Success THEN handleValidatePaymentMethodsResultSuccess RETURNS Success`() =
runTest {
// Arrange
// Act
val result = PSPayPalController.handleValidatePaymentMethodsResultSuccess(
validatePaymentMethodsResult = PSResult.Success(clientIdInput),
psApiClient = mockPSApiClient,
config = psPayPalConfigValidInput,
application = application,
lifecycleScope = mockLifecycleScope
)
val controller = (result as PSResult.Success).value!!
// Assert
assertNotNull(controller)
}
@Test
fun `IF validatePaymentMethods and getPaymentMethods returns Failure THEN validatePaymentMethods RETURNS Failure`() =
runTest {
// Arrange
val mockPaymentMethodsService = mockk<PaymentMethodsServiceImpl>()
val expectedException = Exception()
coEvery {
mockPaymentMethodsService.getPaymentMethods(currencyCodeInput)
} returns PSResult.Failure(expectedException)
// Act
val result = PSPayPalController.validatePaymentMethods(
currencyCode = currencyCodeInput,
accountId = accountIdInput,
paymentMethodService = mockPaymentMethodsService,
psApiClient = mockPSApiClient
)
val exception = (result as PSResult.Failure).exception
// Assert
assertEquals(expectedException, exception)
}
@Test
fun `IF validatePaymentMethods and getPaymentMethods returns Success THEN validatePaymentMethods RETURNS Success`() =
runTest {
// Arrange
val mockPaymentMethodsService = mockk<PaymentMethodsServiceImpl>()
val paymentMethodsValid = listOf(
PaymentMethod(
paymentMethod = PaymentMethodType.PAYPAL,
accountId = accountIdInput,
currencyCode = currencyCodeInput,
accountConfiguration = AccountConfiguration(clientId = clientIdInput)
)
)
coEvery {
mockPaymentMethodsService.getPaymentMethods(currencyCodeInput)
} returns PSResult.Success(paymentMethodsValid)
// Act
val result = PSPayPalController.validatePaymentMethods(
currencyCode = currencyCodeInput,
accountId = accountIdInput,
paymentMethodService = mockPaymentMethodsService,
psApiClient = mockPSApiClient
)
val clientId = (result as PSResult.Success).value
// Assert
assertEquals(clientIdInput, clientId)
}
@Test
fun `IF validatePaymentMethods and getPaymentMethods returns no PayPal type THEN validatePaymentMethods RETURNS Failure with invalidAccountIdForPaymentMethodException`() =
runTest {
// Arrange
val mockPaymentMethodsService = mockk<PaymentMethodsServiceImpl>()
val paymentMethodsValid = listOf(
PaymentMethod(
paymentMethod = PaymentMethodType.CARD,
accountId = accountIdInput,
currencyCode = currencyCodeInput,
accountConfiguration = AccountConfiguration(clientId = clientIdInput)
)
)
coEvery {
mockPaymentMethodsService.getPaymentMethods(currencyCodeInput)
} returns PSResult.Success(paymentMethodsValid)
// Act
val result = PSPayPalController.validatePaymentMethods(
currencyCode = currencyCodeInput,
accountId = accountIdInput,
paymentMethodService = mockPaymentMethodsService,
psApiClient = mockPSApiClient
)
val exception = (result as PSResult.Failure).exception
// Assert
assertEquals(invalidAccountIdForPaymentMethodException(correlationId), exception)
}
@Test
fun `IF validatePaymentMethods and getPaymentMethods returns invalid accountId type THEN validatePaymentMethods RETURNS Failure with improperlyCreatedMerchantAccountConfigException`() =
runTest {
// Arrange
val mockPaymentMethodsService = mockk<PaymentMethodsServiceImpl>()
val paymentMethodsValid = listOf(
PaymentMethod(
paymentMethod = PaymentMethodType.PAYPAL,
accountId = "invalidAccountId",
currencyCode = currencyCodeInput,
accountConfiguration = AccountConfiguration(clientId = clientIdInput)
)
)
coEvery {
mockPaymentMethodsService.getPaymentMethods(currencyCodeInput)
} returns PSResult.Success(paymentMethodsValid)
// Act
val result = PSPayPalController.validatePaymentMethods(
currencyCode = currencyCodeInput,
accountId = accountIdInput,
paymentMethodService = mockPaymentMethodsService,
psApiClient = mockPSApiClient
)
val exception = (result as PSResult.Failure).exception
// Assert
assertEquals(improperlyCreatedMerchantAccountConfigException(correlationId), exception)
}
@Test
fun `IF tokenize and tokenizationAlreadyInProgress THEN tokenize RETURNS via callback on Failure with tokenizationAlreadyInProgressException`() =
runTest {
// Arrange
val psPayPalController = providePSPayPalController()
// Act
psPayPalController.tokenizationAlreadyInProgress = true
psPayPalController.tokenize(
payPalConfig = psPayPalConfigValidInput,
payPalTokenizeOptions = psPayPalTokenizeOptions.copy(amount = 0),
callback = mockPSPayPalTokenizeCallback
)
// Verify
verify {
mockPSPayPalTokenizeCallback.onFailure(
tokenizationAlreadyInProgressException(correlationId)
)
}
}
@Test
fun `IF tokenize and amount not valid THEN tokenize RETURNS via callback on Failure with amountShouldBePositiveException`() =
runTest {
// Arrange
val psPayPalController = providePSPayPalController()
// Act
psPayPalController.tokenize(
payPalConfig = psPayPalConfigValidInput,
payPalTokenizeOptions = psPayPalTokenizeOptions.copy(amount = 0),
callback = mockPSPayPalTokenizeCallback
)
// Verify
verify {
mockPSPayPalTokenizeCallback.onFailure(amountShouldBePositiveException(correlationId))
}
}
@Test
fun `IF tokenize and lifecycleScope is null THEN tokenize RETURNS via callback onFailure with genericApiErrorException`() =
runTest {
// Arrange
Dispatchers.setMain(UnconfinedTestDispatcher(testScheduler))
coEvery { mockPSTokenizationService.tokenize(any()) } returns PSResult.Success()
val psPayPalController = providePSPayPalController()
// Act
psPayPalController.lifecycleScopeWeakRef.clear()
psPayPalController.tokenize(
payPalConfig = psPayPalConfigValidInput,
payPalTokenizeOptions = psPayPalTokenizeOptions,
callback = mockPSPayPalTokenizeCallback,
)
// Verify
verify {
mockPSPayPalTokenizeCallback.onFailure(genericApiErrorException(correlationId))
}
}
@Test
fun `IF tokenize and PSTokenization tokenize returns Failure THEN tokenize RETURNS via callback onFailure`() =
runTest {
// Arrange
Dispatchers.setMain(UnconfinedTestDispatcher(testScheduler))
val exceptedException = Exception()
coEvery {
mockPSTokenizationService.tokenize(any())
} returns PSResult.Failure(exceptedException)
val psPayPalController = providePSPayPalController()
// Act
psPayPalController.tokenize(
payPalConfig = psPayPalConfigValidInput,
payPalTokenizeOptions = psPayPalTokenizeOptions,
callback = mockPSPayPalTokenizeCallback,
)
// Verify
verify {
mockPSPayPalTokenizeCallback.onFailure(exceptedException)
}
}
@Test
fun `IF tokenize and PSTokenization tokenize returns Success with null THEN tokenize RETURNS via callback onFailure with genericApiErrorException`() =
runTest {
// Arrange
Dispatchers.setMain(UnconfinedTestDispatcher(testScheduler))
coEvery {
mockPSTokenizationService.tokenize(any())
} returns PSResult.Success(null)
val psPayPalController = providePSPayPalController()
// Act
psPayPalController.tokenize(
payPalConfig = psPayPalConfigValidInput,
payPalTokenizeOptions = psPayPalTokenizeOptions,
callback = mockPSPayPalTokenizeCallback,
)
// Verify
verify {
mockPSPayPalTokenizeCallback.onFailure(genericApiErrorException(correlationId))
}
}
@Test
fun `IF tokenize and PSTokenization tokenize returns Success with PaymentHandle payPalOrderId null THEN tokenize RETURNS via callback onFailure with genericApiErrorException`() =
runTest {
// Arrange
Dispatchers.setMain(UnconfinedTestDispatcher(testScheduler))
val expectedPaymentHandle = PaymentHandle(
merchantRefNum = "",
paymentHandleToken = "",
status = "",
payPalOrderId = null
)
coEvery {
mockPSTokenizationService.tokenize(any())
} returns PSResult.Success(expectedPaymentHandle)
val psPayPalController = providePSPayPalController()
// Act
psPayPalController.tokenize(
payPalConfig = psPayPalConfigValidInput,
payPalTokenizeOptions = psPayPalTokenizeOptions,
callback = mockPSPayPalTokenizeCallback,
)
// Verify
verify {
mockPSPayPalTokenizeCallback.onFailure(genericApiErrorException(correlationId))
}
}
@Test
fun `IF tokenize and PSTokenization tokenize returns Success THEN tokenize starts PayPal checkout`() =
runTest {
// Arrange
Dispatchers.setMain(UnconfinedTestDispatcher(testScheduler))
val expectedPaymentHandle = PaymentHandle(
merchantRefNum = "",
paymentHandleToken = "",
status = "",
payPalOrderId = "payPalOrderId"
)
coEvery {
mockPSTokenizationService.tokenize(any())
} returns PSResult.Success(expectedPaymentHandle)
val psPayPalController = providePSPayPalController()
every { mockPayPalNativeCheckoutClient.startCheckout(any()) } just Runs
every { mockPayPalNativeCheckoutClient.listener = any() } just Runs
// Act
psPayPalController.tokenize(
payPalConfig = psPayPalConfigValidInput,
payPalTokenizeOptions = psPayPalTokenizeOptions,
callback = mockPSPayPalTokenizeCallback,
)
// Verify
verify {
mockPayPalNativeCheckoutClient.listener = any()
mockPayPalNativeCheckoutClient.startCheckout(any())
}
}
@Test
fun `IF handleTokenizeResultSuccess with tokenizeCallback null and PaymentHandle null THEN handleTokenizeResultSuccess RETURNS nothing via callback`() =
runTest {
// Arrange
val psPayPalController = providePSPayPalController()
// Act
psPayPalController.handleTokenizeResultSuccess(
result = PSResult.Success(null)
)
// Assert
assertNull(psPayPalController.tokenizeCallback)
assertFalse(psPayPalController.tokenizationAlreadyInProgress)
}
@Test
fun `IF handleTokenizeResultSuccess with tokenizeCallback null and payPalOrderId null THEN handleTokenizeResultSuccess RETURNS nothing via callback`() =
runTest {
// Arrange
val psPayPalController = providePSPayPalController()
// Act
psPayPalController.handleTokenizeResultSuccess(
result = PSResult.Success(
PaymentHandle(
merchantRefNum = "",
paymentHandleToken = "",
status = "",
payPalOrderId = null
)
)
)
// Assert
assertNull(psPayPalController.tokenizeCallback)
assertFalse(psPayPalController.tokenizationAlreadyInProgress)
}
@Test
fun `IF handleTokenizeResultFailure with tokenizeCallback null THEN handleTokenizeResultFailure RETURNS nothing via callback`() =
runTest {
// Arrange
val psPayPalController = providePSPayPalController()
// Act
psPayPalController.handleTokenizeResultFailure(
result = PSResult.Failure(Exception())
)
// Assert
assertNull(psPayPalController.tokenizeCallback)
assertFalse(psPayPalController.tokenizationAlreadyInProgress)
}
@Test
fun `IF onPayPalCheckoutSuccess and paymentHandle null THEN onPayPalCheckoutSuccess RETURNS via callback onFailure with genericApiErrorException`() =
runTest {
// Arrange
Dispatchers.setMain(UnconfinedTestDispatcher(testScheduler))
coEvery {
mockPSTokenizationService.tokenize(any())
} returns PSResult.Success()
every { mockPayPalNativeCheckoutClient.listener = any() } just Runs
val psPayPalController = providePSPayPalController()
psPayPalController.tokenize(
payPalConfig = psPayPalConfigValidInput,
payPalTokenizeOptions = psPayPalTokenizeOptions,
callback = mockPSPayPalTokenizeCallback,
)
psPayPalController.paymentHandle = null
// Act
psPayPalController.onPayPalCheckoutSuccess()
// Verify
verify {
mockPSPayPalTokenizeCallback.onFailure(genericApiErrorException(correlationId))
}
}
@Test
fun `IF onPayPalCheckoutSuccess and paymentHandle & tokenizeCallback are nulls THEN onPayPalCheckoutSuccess RETURNS nothing via callback`() =
runTest {
// Arrange
every { mockPayPalNativeCheckoutClient.listener = any() } just Runs
val psPayPalController = providePSPayPalController()
psPayPalController.paymentHandle = null
// Act
psPayPalController.onPayPalCheckoutSuccess()
// Assert
assertNull(psPayPalController.tokenizeCallback)
assertFalse(psPayPalController.tokenizationAlreadyInProgress)
}
@Test
fun `IF onPayPalCheckoutSuccess and lifecycleScope is null THEN onPayPalCheckoutSuccess RETURNS via callback onFailure with genericApiErrorException`() =
runTest {
// Arrange
Dispatchers.setMain(UnconfinedTestDispatcher(testScheduler))
val expectedPaymentHandle = PaymentHandle(
merchantRefNum = "",
paymentHandleToken = "",
status = "",
payPalOrderId = "payPalOrderId"
)
coEvery {
mockPSTokenizationService.tokenize(any())
} returns PSResult.Success(expectedPaymentHandle)
val mockListener = mockk<PayPalNativeCheckoutListener>()
every { mockPayPalNativeCheckoutClient.listener } returns mockListener
every { mockPayPalNativeCheckoutClient.listener = any() } just Runs
every { mockPayPalNativeCheckoutClient.startCheckout(any()) } just Runs
val psPayPalController = providePSPayPalController()
psPayPalController.tokenize(
payPalConfig = psPayPalConfigValidInput,
payPalTokenizeOptions = psPayPalTokenizeOptions,
callback = mockPSPayPalTokenizeCallback,
)
psPayPalController.lifecycleScopeWeakRef.clear()
// Act
psPayPalController.onPayPalCheckoutSuccess()
// Verify
verify {
mockPSPayPalTokenizeCallback.onFailure(genericApiErrorException(correlationId))
}
}
@Test
fun `IF onPayPalCheckoutSuccess and lifecycleScope & tokenizeCallback are nulls THEN onPayPalCheckoutSuccess RETURNS nothing via callback`() =
runTest {
// Arrange
every { mockPayPalNativeCheckoutClient.listener = any() } just Runs
val psPayPalController = providePSPayPalController()
val paymentHandle = PaymentHandle(
merchantRefNum = "merchantRefNum",
paymentHandleToken = "paymentHandleToken",
status = "",
payPalOrderId = "payPalOrderId"
)
psPayPalController.paymentHandle = paymentHandle
psPayPalController.lifecycleScopeWeakRef.clear()
// Act
psPayPalController.onPayPalCheckoutSuccess()
// Assert
assertNull(psPayPalController.tokenizeCallback)
assertFalse(psPayPalController.tokenizationAlreadyInProgress)
}
@Test
fun `IF onPayPalCheckoutSuccess and PSTokenization refreshToken returns Success with null THEN onPayPalCheckoutSuccess RETURNS via callback onFailure with genericApiErrorException`() =
runTest {
// Arrange
val testDispatcher = UnconfinedTestDispatcher(testScheduler)
Dispatchers.setMain(testDispatcher)
val paymentHandle = PaymentHandle(
merchantRefNum = "merchantRefNum",
paymentHandleToken = "paymentHandleToken",
status = "",
payPalOrderId = "payPalOrderId"
)
coEvery {
mockPSTokenizationService.refreshToken(paymentHandle)
} returns PSResult.Success()
every { mockPayPalNativeCheckoutClient.listener = any() } just Runs
val psPayPalController = providePSPayPalController()
psPayPalController.tokenizeCallback = mockPSPayPalTokenizeCallback
psPayPalController.paymentHandle = paymentHandle
// Act
psPayPalController.onPayPalCheckoutSuccess(
ioDispatcher = UnconfinedTestDispatcher(testScheduler)
)
// Verify
verify {
mockPSPayPalTokenizeCallback.onFailure(genericApiErrorException(correlationId))
}
}
@Test
fun `IF onPayPalCheckoutSuccess and PSTokenization refreshToken returns Success with null and tokenizeCallback is null THEN onPayPalCheckoutSuccess RETURNS nothing via callback`() =
runTest {
// Arrange
val testDispatcher = UnconfinedTestDispatcher(testScheduler)
Dispatchers.setMain(testDispatcher)
val paymentHandle = PaymentHandle(
merchantRefNum = "merchantRefNum",
paymentHandleToken = "paymentHandleToken",
status = "",
payPalOrderId = "payPalOrderId"
)
coEvery {
mockPSTokenizationService.refreshToken(paymentHandle)
} returns PSResult.Success()
every { mockPayPalNativeCheckoutClient.listener = any() } just Runs
val psPayPalController = providePSPayPalController()
psPayPalController.paymentHandle = paymentHandle
// Act
psPayPalController.onPayPalCheckoutSuccess(
ioDispatcher = UnconfinedTestDispatcher(testScheduler)
)
// Assert
assertNull(psPayPalController.tokenizeCallback)
assertFalse(psPayPalController.tokenizationAlreadyInProgress)
}
@Test
fun `IF onPayPalCheckoutSuccess and PSTokenization refreshToken returns Success THEN onPayPalCheckoutSuccess RETURNS via callback onSuccess`() =
runTest {
// Arrange
val testDispatcher = UnconfinedTestDispatcher(testScheduler)
Dispatchers.setMain(testDispatcher)
val paymentHandle = PaymentHandle(
merchantRefNum = "merchantRefNum",
paymentHandleToken = "paymentHandleToken",
status = "",
payPalOrderId = "payPalOrderId"
)
coEvery {
mockPSTokenizationService.refreshToken(paymentHandle)
} returns PSResult.Success(paymentHandle)
every { mockPayPalNativeCheckoutClient.listener = any() } just Runs
val psPayPalController = providePSPayPalController()
psPayPalController.tokenizeCallback = mockPSPayPalTokenizeCallback
psPayPalController.paymentHandle = paymentHandle
// Act
psPayPalController.onPayPalCheckoutSuccess(
ioDispatcher = UnconfinedTestDispatcher(testScheduler)
)
// Verify
verify {
mockPSPayPalTokenizeCallback.onSuccess(any())
}
}
@Test
fun `IF onPayPalCheckoutSuccess and PSTokenization refreshToken returns Success and tokenizeCallback is null THEN onPayPalCheckoutSuccess RETURNS nothing via callback`() =
runTest {
// Arrange
val testDispatcher = UnconfinedTestDispatcher(testScheduler)
Dispatchers.setMain(testDispatcher)
val paymentHandle = PaymentHandle(
merchantRefNum = "merchantRefNum",
paymentHandleToken = "paymentHandleToken",
status = "",
payPalOrderId = "payPalOrderId"
)
coEvery {
mockPSTokenizationService.refreshToken(paymentHandle)
} returns PSResult.Success(paymentHandle)
every { mockPayPalNativeCheckoutClient.listener = any() } just Runs
val psPayPalController = providePSPayPalController()
psPayPalController.paymentHandle = paymentHandle
// Act
psPayPalController.onPayPalCheckoutSuccess(
ioDispatcher = UnconfinedTestDispatcher(testScheduler)
)
// Assert
assertNull(psPayPalController.tokenizeCallback)
assertFalse(psPayPalController.tokenizationAlreadyInProgress)
}
@Test
fun `IF onPayPalCheckoutSuccess and PSTokenization refreshToken returns Failure THEN onPayPalCheckoutSuccess RETURNS via callback onFailure with genericApiErrorException`() =
runTest {
// Arrange
val testDispatcher = UnconfinedTestDispatcher(testScheduler)
Dispatchers.setMain(testDispatcher)
val paymentHandle = PaymentHandle(
merchantRefNum = "merchantRefNum",
paymentHandleToken = "paymentHandleToken",
status = "",
payPalOrderId = "payPalOrderId"
)
coEvery {
mockPSTokenizationService.refreshToken(paymentHandle)
} returns PSResult.Failure(Exception())
every { mockPayPalNativeCheckoutClient.listener = any() } just Runs
val psPayPalController = providePSPayPalController()
psPayPalController.tokenizeCallback = mockPSPayPalTokenizeCallback
psPayPalController.paymentHandle = paymentHandle
// Act
psPayPalController.onPayPalCheckoutSuccess(
ioDispatcher = UnconfinedTestDispatcher(testScheduler)
)
// Verify
verify {
mockPSPayPalTokenizeCallback.onFailure(genericApiErrorException(correlationId))
}
}
@Test
fun `IF onPayPalCheckoutSuccess and PSTokenization refreshToken returns Failure and tokenizeCallback is null THEN onPayPalCheckoutSuccess RETURNS nothing via callback`() =
runTest {
// Arrange
val testDispatcher = UnconfinedTestDispatcher(testScheduler)
Dispatchers.setMain(testDispatcher)
val paymentHandle = PaymentHandle(
merchantRefNum = "merchantRefNum",
paymentHandleToken = "paymentHandleToken",
status = "",
payPalOrderId = "payPalOrderId"
)
coEvery {
mockPSTokenizationService.refreshToken(paymentHandle)
} returns PSResult.Failure(Exception())
every { mockPayPalNativeCheckoutClient.listener = any() } just Runs
val psPayPalController = providePSPayPalController()
psPayPalController.paymentHandle = paymentHandle
// Act
psPayPalController.onPayPalCheckoutSuccess(
ioDispatcher = UnconfinedTestDispatcher(testScheduler)
)
// Assert
assertNull(psPayPalController.tokenizeCallback)
assertFalse(psPayPalController.tokenizationAlreadyInProgress)
}
@Test
fun `IF onPayPalCheckoutFailure THEN callback RETURNS onFailure with payPalFailedAuthorizationException`() =
runTest {
// Arrange
val testDispatcher = UnconfinedTestDispatcher(testScheduler)
Dispatchers.setMain(testDispatcher)
val paymentHandle = PaymentHandle(
merchantRefNum = "merchantRefNum",
paymentHandleToken = "paymentHandleToken",
status = "",
payPalOrderId = "payPalOrderId"
)
coEvery {
mockPSTokenizationService.refreshToken(paymentHandle)
} returns PSResult.Failure(Exception())
every { mockPayPalNativeCheckoutClient.listener = any() } just Runs
val psPayPalController = providePSPayPalController()
psPayPalController.tokenizeCallback = mockPSPayPalTokenizeCallback
psPayPalController.paymentHandle = paymentHandle
// Act
psPayPalController.onPayPalCheckoutFailure()
// Verify
verify {
mockPSPayPalTokenizeCallback.onFailure(
payPalFailedAuthorizationException(correlationId)
)
}
}
@Test
fun `IF onPayPalCheckoutFailure and tokenizeCallback is null THEN callback RETURNS nothing`() =
runTest {
// Arrange
val testDispatcher = UnconfinedTestDispatcher(testScheduler)
Dispatchers.setMain(testDispatcher)
val paymentHandle = PaymentHandle(
merchantRefNum = "merchantRefNum",
paymentHandleToken = "paymentHandleToken",
status = "",
payPalOrderId = "payPalOrderId"
)
coEvery {
mockPSTokenizationService.refreshToken(paymentHandle)
} returns PSResult.Failure(Exception())
every { mockPayPalNativeCheckoutClient.listener = any() } just Runs
val psPayPalController = providePSPayPalController()
psPayPalController.paymentHandle = paymentHandle
// Act
psPayPalController.onPayPalCheckoutFailure()
// Assert
assertNull(psPayPalController.tokenizeCallback)
assertFalse(psPayPalController.tokenizationAlreadyInProgress)
}
@Test
fun `IF onPayPalCheckoutCanceled THEN callback RETURNS onCancelled with payPalUserCancelledException`() =
runTest {
// Arrange
val testDispatcher = UnconfinedTestDispatcher(testScheduler)
Dispatchers.setMain(testDispatcher)
val paymentHandle = PaymentHandle(
merchantRefNum = "merchantRefNum",
paymentHandleToken = "paymentHandleToken",
status = "",
payPalOrderId = "payPalOrderId"
)
coEvery {
mockPSTokenizationService.refreshToken(paymentHandle)
} returns PSResult.Failure(Exception())
every { mockPayPalNativeCheckoutClient.listener = any() } just Runs
val psPayPalController = providePSPayPalController()
psPayPalController.tokenizeCallback = mockPSPayPalTokenizeCallback
psPayPalController.paymentHandle = paymentHandle
// Act
psPayPalController.onPayPalCheckoutCanceled()
// Verify
verify {
mockPSPayPalTokenizeCallback.onCancelled(payPalUserCancelledException(correlationId))
}
}
@Test
fun `IF onPayPalCheckoutCanceled and tokenizeCallback is null THEN callback RETURNS nothing`() =
runTest {
// Arrange
val testDispatcher = UnconfinedTestDispatcher(testScheduler)
Dispatchers.setMain(testDispatcher)
val paymentHandle = PaymentHandle(
merchantRefNum = "merchantRefNum",
paymentHandleToken = "paymentHandleToken",
status = "",
payPalOrderId = "payPalOrderId"
)
coEvery {
mockPSTokenizationService.refreshToken(paymentHandle)
} returns PSResult.Failure(Exception())
every { mockPayPalNativeCheckoutClient.listener = any() } just Runs
val psPayPalController = providePSPayPalController()
psPayPalController.paymentHandle = paymentHandle
// Act
psPayPalController.onPayPalCheckoutCanceled()
// Assert
assertNull(psPayPalController.tokenizeCallback)
assertFalse(psPayPalController.tokenizationAlreadyInProgress)
}
@Test
fun `IF dispose THEN data is cleared`() =
runTest {
// Arrange
every { mockPayPalNativeCheckoutClient.listener = any() } just Runs
every { mockPayPalNativeCheckoutClient.listener } answers { callOriginal() }
val psPayPalController = providePSPayPalController()
// Act
psPayPalController.dispose()
// Verify
assertNull(mockPayPalNativeCheckoutClient.listener)
assertNull(psPayPalController.tokenizeCallback)
assertNull(psPayPalController.paymentHandle)
assertNull(psPayPalController.lifecycleScopeWeakRef.get())
}
@Test
fun `IF dispose and lifecycle is null THEN data is cleared`() =
runTest {
// Arrange
every { mockPayPalNativeCheckoutClient.listener = any() } just Runs
every { mockPayPalNativeCheckoutClient.listener } answers { callOriginal() }
val psPayPalController = providePSPayPalController()
psPayPalController.lifecycleScopeWeakRef.clear()
// Act
psPayPalController.dispose()
// Verify
assertNull(mockPayPalNativeCheckoutClient.listener)
assertNull(psPayPalController.tokenizeCallback)
assertNull(psPayPalController.paymentHandle)
assertNull(psPayPalController.lifecycleScopeWeakRef.get())
}
} | 0 | Kotlin | 0 | 0 | d0f16d72ef051fc4bc6245a6204ede659f308e05 | 44,306 | paysafe_sdk_android_payments_api | MIT License |
testutils/src/main/java/com/xfinity/resourceprovider/testutils/ResourceProviderAnswers.kt | Comcast | 92,522,817 | false | {"Java": 4858, "Kotlin": 4844} | package com.xfinity.resourceprovider.testutils
import android.graphics.drawable.Drawable
import org.mockito.Mockito
import org.mockito.invocation.InvocationOnMock
import org.mockito.stubbing.Answer
import java.lang.reflect.Method
/**
* This file contains Mockito Answer sub-classes for automatically mocking ResourceProvider function calls.
* Refer to the sample application MainPresenterTest and ResourceProviderTestUtils classes for usage examples
*/
class DrawableProviderAnswer : Answer<Any?> {
private val delegate = Mockito.RETURNS_DEFAULTS!!
private val drawableMap = mutableMapOf<Method, Drawable>()
override fun answer(invocation: InvocationOnMock?): Any? {
val invocationMethodReturn = invocation?.method?.returnType
val drawableType = Drawable::class.java
return when (invocationMethodReturn) {
drawableType -> {
val mappedMock = drawableMap.get(invocation.method)
if (mappedMock != null) {
mappedMock
} else {
val mock = Mockito.mock(Drawable::class.java)
drawableMap.put(invocation.method, mock)
mock
}
}
else -> delegate.answer(invocation)
}
}
}
class StringProviderAnswer : Answer<Any?> {
private val delegate = Mockito.RETURNS_DEFAULTS!!
override fun answer(invocation: InvocationOnMock?): Any? {
val invocationMethodReturn = invocation?.method?.returnType
val stringType = String::class.java
return when (invocationMethodReturn) {
stringType -> invocation.method?.name.toString() + invocation.arguments.joinToString()
else -> delegate.answer(invocation)
}
}
}
class IntegerProviderAnswer : Answer<Any?> {
private val delegate = Mockito.RETURNS_DEFAULTS!!
override fun answer(invocation: InvocationOnMock?): Any? {
val invocationMethodReturn = invocation?.method?.returnType
val intType = Int::class.java
return when (invocationMethodReturn) {
intType -> invocation.method?.name?.hashCode()
else -> delegate.answer(invocation)
}
}
} | 6 | Java | 8 | 19 | f1814941907e0f8c316e15ba85b3cf86c55e56c1 | 2,224 | resourceprovider-utils | Apache License 2.0 |
kotlin/lib/src/jvmAndroidMain/kotlin/xyz/mcxross/kfc/Encode.kt | mcxross | 659,200,090 | false | {"Rust": 24688, "Kotlin": 5756, "HTML": 174} | package xyz.mcxross.kfc
actual object Encode {
actual fun base64ToHex(bytes: String): String = xyz.mcxross.kfc.base64ToHex(bytes)
actual fun hexToBase64(bytes: String): String = xyz.mcxross.kfc.hexToBase64(bytes)
}
| 0 | Rust | 0 | 0 | f981135bdf51a5c8cca86a381b7abfb5221a7ba5 | 221 | kfastcrypto | Apache License 2.0 |
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/api/tag/TagRepository.kt | altaf933 | 122,962,254 | false | {"Gradle": 4, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "YAML": 1, "Proguard": 1, "Kotlin": 485, "XML": 261, "Java": 4} | package io.github.feelfreelinux.wykopmobilny.api.tag
import io.github.feelfreelinux.wykopmobilny.api.UserTokenRefresher
import io.github.feelfreelinux.wykopmobilny.api.errorhandler.ErrorHandler
import io.github.feelfreelinux.wykopmobilny.api.errorhandler.ErrorHandlerTransformer
import io.github.feelfreelinux.wykopmobilny.models.mapper.apiv2.TagEntriesMapper
import io.github.feelfreelinux.wykopmobilny.models.mapper.apiv2.TagLinksMapper
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.ObservedTagResponse
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.ObserveStateResponse
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.responses.TagEntriesResponse
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.responses.TagLinksResponse
import io.github.feelfreelinux.wykopmobilny.utils.LinksPreferencesApi
import io.reactivex.Single
import retrofit2.Retrofit
class TagRepository(retrofit: Retrofit, val userTokenRefresher: UserTokenRefresher, val linksPreferencesApi: LinksPreferencesApi) : TagApi {
private val tagApi by lazy { retrofit.create(TagRetrofitApi::class.java) }
override fun getTagEntries(tag : String, page : Int) = tagApi.getTagEntries(tag, page)
.retryWhen(userTokenRefresher)
.flatMap(ErrorHandler<TagEntriesResponse>())
.map { TagEntriesMapper.map(it)}
override fun getTagLinks(tag : String, page : Int) = tagApi.getTagLinks(tag, page)
.retryWhen(userTokenRefresher)
.flatMap(ErrorHandler<TagLinksResponse>())
.map { TagLinksMapper.map(it, linksPreferencesApi)}
override fun getObservedTags() : Single<List<ObservedTagResponse>> =
tagApi.getObservedTags()
.retryWhen(userTokenRefresher)
.compose<List<ObservedTagResponse>>(ErrorHandlerTransformer())
override fun observe(tag : String) = tagApi.observe(tag)
.retryWhen(userTokenRefresher)
.compose<ObserveStateResponse>(ErrorHandlerTransformer())
override fun unobserve(tag : String) = tagApi.unobserve(tag)
.retryWhen(userTokenRefresher)
.compose<ObserveStateResponse>(ErrorHandlerTransformer())
override fun block(tag : String) = tagApi.block(tag)
.retryWhen(userTokenRefresher)
.compose<ObserveStateResponse>(ErrorHandlerTransformer())
override fun unblock(tag : String) = tagApi.unblock(tag)
.retryWhen(userTokenRefresher)
.compose<ObserveStateResponse>(ErrorHandlerTransformer())
} | 1 | null | 1 | 1 | 0c2d9fc015a5bef5b258481e4233d04ab5705a49 | 2,560 | WykopMobilny | MIT License |
feature_book_details/src/main/java/com/allsoftdroid/feature/book_details/domain/repository/IBaseRepository.kt | pravinyo | 209,936,085 | false | null | package com.allsoftdroid.feature.book_details.domain.repository
import com.allsoftdroid.common.base.extension.Event
import com.allsoftdroid.common.base.extension.Variable
import com.allsoftdroid.feature.book_details.utils.NetworkState
interface IBaseRepository {
fun networkResponse(): Variable<Event<NetworkState>>
} | 3 | Kotlin | 4 | 12 | 8358f69c0cf8dbde18904b0c3a304ec89b518c9b | 323 | AudioBook | MIT License |
src/test/kotlin/no/nav/syfo/testhelper/UserConstants.kt | navikt | 164,875,446 | false | {"Gradle": 1, "Markdown": 2, "CODEOWNERS": 1, "Gradle Kotlin DSL": 1, "Dockerfile": 1, "Shell": 2, "Ignore List": 1, "Batchfile": 1, "YAML": 13, "INI": 1, "Java": 166, "XML": 11, "SQL": 37, "Kotlin": 160, "XSLT": 2, "GraphQL": 2, "PLSQL": 1} | package no.nav.syfo.testhelper
object UserConstants {
const val ARBEIDSTAKER_FNR = "12345678912"
@JvmField
val ARBEIDSTAKER_AKTORID = mockAktorId(ARBEIDSTAKER_FNR)
const val LEDER_FNR = "12987654321"
@JvmField
val LEDER_AKTORID = mockAktorId(LEDER_FNR)
const val VIRKSOMHETSNUMMER = "123456789"
const val VEILEDER_ID = "Z999999"
const val PERSON_TLF = "<EMAIL>"
const val PERSON_EMAIL = "12345678"
}
| 7 | Java | 0 | 0 | 6d3a2604541c974096d942ef38f2f9b632b2d8a2 | 441 | syfooppfolgingsplanservice | MIT License |
src/main/kotlin/icu/windea/pls/lang/util/ParadoxTextColorManager.kt | DragonKnightOfBreeze | 328,104,626 | false | null | package icu.windea.pls.lang
import com.intellij.openapi.project.*
import com.intellij.psi.*
import com.intellij.psi.util.*
import icu.windea.pls.*
import icu.windea.pls.core.*
import icu.windea.pls.core.search.*
import icu.windea.pls.core.search.selector.chained.*
import icu.windea.pls.lang.model.*
import icu.windea.pls.script.psi.*
object ParadoxTextColorHandler {
fun getInfo(name: String, project: Project, contextElement: PsiElement? = null): ParadoxTextColorInfo? {
val selector = definitionSelector(project, contextElement).contextSensitive()
val definition = ParadoxDefinitionSearch.search(name, "textcolor", selector).find()
if(definition == null) return null
return doGetInfoFromCache(definition)
}
private fun doGetInfoFromCache(definition: ParadoxScriptDefinitionElement): ParadoxTextColorInfo? {
return CachedValuesManager.getCachedValue(definition, PlsKeys.cachedTextColorInfo) {
val value = doGetInfo(definition)
CachedValueProvider.Result.create(value, definition)
}
}
private fun doGetInfo(definition: ParadoxScriptDefinitionElement): ParadoxTextColorInfo? {
if(definition !is ParadoxScriptProperty) return null
//要求输入的name必须是单个字母或数字
val name = definition.name
if(name.singleOrNull()?.let { it.isExactLetter() || it.isExactDigit() } != true) return null
val gameType = selectGameType(definition) ?: return null
val rgbList = definition.valueList.mapNotNull { it.intValue() }
val value = ParadoxTextColorInfo(name, gameType, definition.createPointer(), rgbList[0], rgbList[1], rgbList[2])
return value
}
fun getInfos(project: Project, contextElement: PsiElement? = null): List<ParadoxTextColorInfo> {
val selector = definitionSelector(project, contextElement).contextSensitive().distinctByName()
val definitions = ParadoxDefinitionSearch.search("textcolor", selector).findAll()
if(definitions.isEmpty()) return emptyList()
return definitions.mapNotNull { definition -> doGetInfoFromCache(definition) } //it.name == it.definitionInfo.name
}
}
| 9 | null | 4 | 36 | 5577bedd9d2fa15348fce08d737d5726572e07f3 | 2,177 | Paradox-Language-Support | MIT License |
android/app/src/main/kotlin/me/xmcf/kodproject/flutterchannel/download/TaskInfoRes.kt | helixs | 197,500,648 | false | null | package me.xmcf.kodproject.flutterchannel.download
data class TaskInfoRes(
//主键id
var primaryId: Int = 0,
//任务id
var taskId: String,
//任务状态
var status: Int = 0,
//进度
var progress: Int = 0,
//任务下载地址
var url: String,
//文件名称
var filename: String,
//保存目录
var savedDir: String,
//header
var headers: String,
//文件mime
var mimeType: String,
//是否可恢复
var resumable: Boolean = false,
//显示通知栏
var showNotification: Boolean = false,
//打开通知栏文件
var openFileFromNotification: Boolean = false,
//任务创建时间
var timeCreated: Long = 0,
//文件总大小
var allLength: Long = 0,
//文件当前大小
var currentLength: Long = 0
) | 1 | null | 4 | 6 | 9df884a94db5bffd413982a467665751e5e0e27c | 827 | KodExplorerFlutter | Apache License 2.0 |
config/src/main/kotlin/org/springframework/security/config/annotation/web/RequiresChannelDsl.kt | spring-projects | 3,148,979 | false | null | /*
* Copyright 2002-2020 the original author or 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configurers.ChannelSecurityConfigurer
import org.springframework.security.web.access.channel.ChannelDecisionManagerImpl
import org.springframework.security.web.access.channel.ChannelProcessor
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher
import org.springframework.security.web.util.matcher.AnyRequestMatcher
import org.springframework.security.web.util.matcher.RequestMatcher
import org.springframework.util.ClassUtils
import org.springframework.web.servlet.handler.HandlerMappingIntrospector
/**
* A Kotlin DSL to configure [HttpSecurity] channel security using idiomatic
* Kotlin code.
*
* @author Eleftheria Stein
* @since 5.3
* @property channelProcessors the [ChannelProcessor] instances to use in
* [ChannelDecisionManagerImpl]
*/
class RequiresChannelDsl : AbstractRequestMatcherDsl() {
private val channelSecurityRules = mutableListOf<AuthorizationRule>()
private val HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME = "mvcHandlerMappingIntrospector"
private val HANDLER_MAPPING_INTROSPECTOR = "org.springframework.web.servlet.handler.HandlerMappingIntrospector"
private val MVC_PRESENT = ClassUtils.isPresent(
HANDLER_MAPPING_INTROSPECTOR,
RequiresChannelDsl::class.java.classLoader)
private val PATTERN_TYPE = if (MVC_PRESENT) PatternType.MVC else PatternType.ANT
var channelProcessors: List<ChannelProcessor>? = null
/**
* Adds a channel security rule.
*
* @param matches the [RequestMatcher] to match incoming requests against
* @param attribute the configuration attribute to secure the matching request
* (i.e. "REQUIRES_SECURE_CHANNEL")
*/
fun secure(matches: RequestMatcher = AnyRequestMatcher.INSTANCE,
attribute: String = "REQUIRES_SECURE_CHANNEL") {
channelSecurityRules.add(MatcherAuthorizationRule(matches, attribute))
}
/**
* Adds a request authorization rule for an endpoint matching the provided
* pattern.
* If Spring MVC is not an the classpath, it will use an ant matcher.
* If Spring MVC is on the classpath, it will use an MVC matcher.
* The MVC will use the same rules that Spring MVC uses for matching.
* For example, often times a mapping of the path "/path" will match on
* "/path", "/path/", "/path.html", etc.
* If the current request will not be processed by Spring MVC, a reasonable default
* using the pattern as an ant pattern will be used.
*
* @param pattern the pattern to match incoming requests against.
* @param attribute the configuration attribute to secure the matching request
* (i.e. "REQUIRES_SECURE_CHANNEL")
*/
fun secure(pattern: String, attribute: String = "REQUIRES_SECURE_CHANNEL") {
channelSecurityRules.add(PatternAuthorizationRule(pattern = pattern,
patternType = PATTERN_TYPE,
rule = attribute))
}
/**
* Adds a request authorization rule for an endpoint matching the provided
* pattern.
* If Spring MVC is not an the classpath, it will use an ant matcher.
* If Spring MVC is on the classpath, it will use an MVC matcher.
* The MVC will use the same rules that Spring MVC uses for matching.
* For example, often times a mapping of the path "/path" will match on
* "/path", "/path/", "/path.html", etc.
* If the current request will not be processed by Spring MVC, a reasonable default
* using the pattern as an ant pattern will be used.
*
* @param pattern the pattern to match incoming requests against.
* @param servletPath the servlet path to match incoming requests against. This
* only applies when using an MVC pattern matcher.
* @param attribute the configuration attribute to secure the matching request
* (i.e. "REQUIRES_SECURE_CHANNEL")
*/
fun secure(pattern: String, servletPath: String, attribute: String = "REQUIRES_SECURE_CHANNEL") {
channelSecurityRules.add(PatternAuthorizationRule(pattern = pattern,
patternType = PATTERN_TYPE,
servletPath = servletPath,
rule = attribute))
}
/**
* Specify channel security is active.
*/
val requiresSecure = "REQUIRES_SECURE_CHANNEL"
/**
* Specify channel security is inactive.
*/
val requiresInsecure = "REQUIRES_INSECURE_CHANNEL"
internal fun get(): (ChannelSecurityConfigurer<HttpSecurity>.ChannelRequestMatcherRegistry) -> Unit {
return { channelSecurity ->
channelProcessors?.also { channelSecurity.channelProcessors(channelProcessors) }
channelSecurityRules.forEach { rule ->
when (rule) {
is MatcherAuthorizationRule -> channelSecurity.requestMatchers(rule.matcher).requires(rule.rule)
is PatternAuthorizationRule -> {
when (rule.patternType) {
PatternType.ANT -> channelSecurity.requestMatchers(rule.pattern).requires(rule.rule)
PatternType.MVC -> {
val introspector = channelSecurity.applicationContext.getBean(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME, HandlerMappingIntrospector::class.java)
val mvcMatcher = MvcRequestMatcher.Builder(introspector)
.servletPath(rule.servletPath)
.pattern(rule.pattern)
mvcMatcher.setMethod(rule.httpMethod)
channelSecurity.requestMatchers(mvcMatcher).requires(rule.rule)
}
}
}
}
}
}
}
}
| 942 | null | 5864 | 8,737 | 9ba2435cb21a828dd2bccaabcac63dabf12d5dc8 | 6,813 | spring-security | Apache License 2.0 |
src/jsMain/kotlin/baaahs/sim/BrainSurfaceSimulation.kt | baaahs | 174,897,412 | false | null | package baaahs.sim
import baaahs.device.PixelFormat
import baaahs.fixtures.Fixture
import baaahs.fixtures.PixelArrayFixture
import baaahs.mapper.MappingSession
import baaahs.model.Model
import baaahs.randomDelay
import baaahs.sm.brain.BrainManager
import baaahs.sm.brain.sim.BrainSimulatorManager
import baaahs.util.globalLaunch
import baaahs.visualizer.*
import three_ext.toVector3F
actual class BrainSurfaceSimulation actual constructor(
private val surface: Model.Surface,
adapter: EntityAdapter
) : FixtureSimulation {
private val surfaceGeometry by lazy { SurfaceGeometry(surface) }
private val pixelPositions by lazy {
val pixelArranger = adapter.simulationEnv[PixelArranger::class]
pixelArranger.arrangePixels(surfaceGeometry, surface.expectedPixelCount)
}
private val vizPixels by lazy { VizPixels(
pixelPositions,
surfaceGeometry.panelNormal,
surface.transformation,
PixelFormat.default
) }
val brain by lazy {
val brainSimulatorManager = adapter.simulationEnv[BrainSimulatorManager::class]
brainSimulatorManager.createBrain(surface.name, vizPixels)
}
override val mappingData: MappingSession.SurfaceData
by lazy {
MappingSession.SurfaceData(
BrainManager.controllerTypeName,
brain.id,
surface.name,
pixelPositions.size,
pixelPositions.map {
MappingSession.SurfaceData.PixelData(it.toVector3F(), null, null)
},
null, null
)
}
override val itemVisualizer: SurfaceVisualizer by lazy {
SurfaceVisualizer(surface, surfaceGeometry, vizPixels)
}
override val previewFixture: Fixture by lazy {
PixelArrayFixture(
surface,
pixelPositions.size,
surface.name,
PixelArrayPreviewTransport(surface.name, vizPixels),
PixelFormat.default,
1f,
pixelPositions.map { it.toVector3F() }
)
}
override fun start() {
globalLaunch {
randomDelay(1000)
brain.start()
}
}
override fun stop() {
brain.stop()
}
} | 99 | null | 6 | 40 | 77ad22b042fc0ac440410619dd27b468c3b3a600 | 2,266 | sparklemotion | MIT License |
PettCareAndroidApp/app/src/main/java/com/pettcare/app/chat/presentation/userchats/UserChatsUiState.kt | antelukic | 767,127,442 | false | {"Kotlin": 305258} | package com.pettcare.app.chat.presentation.userchats
data class UserChatsUiState(
val users: List<UserChatUiState> = emptyList(),
val query: String = "",
)
data class UserChatUiState(
val photoUrl: String,
val name: String,
val id: String,
)
| 0 | Kotlin | 0 | 0 | e6210463d97ef1235a2f0d84c5658f251f857f9a | 264 | PettCareApp | Apache License 2.0 |
domain/src/main/java/ru/sportivityteam/vucmirea/assistant/domain/usecase/auth/AuthUserUseCase.kt | SportivityTeam | 753,183,017 | false | {"Kotlin": 46772, "Swift": 532} | package ru.sportivityteam.vucmirea.assistant.domain.usecase.auth
import kotlinx.coroutines.flow.Flow
import ru.sportivityteam.vucmirea.assistant.domain.repository.auth.AuthRepository
import ru.sportivityteam.vucmirea.assistant.domain.util.State
interface AuthUserUseCase : suspend (String, String) -> Flow<State<Unit>>
class AuthUserUseCaseImpl(
private val authRepository: AuthRepository
) : AuthUserUseCase {
override suspend operator fun invoke(name: String, group: String) =
authRepository.authUser(name, group)
} | 0 | Kotlin | 0 | 2 | a45c1129bb1cfc56c784778ef3b28afff302ec63 | 537 | assistant-vuc-mirea | MIT License |
idea/idea-native/src/org/jetbrains/kotlin/ide/konan/decompiler/KotlinNativeMetadataDecompiler.kt | ujjwalagrawal17 | 247,057,405 | false | {"Markdown": 61, "Gradle": 622, "Gradle Kotlin DSL": 333, "Java Properties": 13, "Shell": 10, "Ignore List": 11, "Batchfile": 9, "Git Attributes": 7, "Protocol Buffer": 11, "Java": 6439, "Kotlin": 54075, "Proguard": 8, "XML": 1563, "Text": 10562, "JavaScript": 270, "JAR Manifest": 2, "Roff": 211, "Roff Manpage": 36, "INI": 138, "AsciiDoc": 1, "SVG": 31, "HTML": 464, "Groovy": 31, "JSON": 46, "JFlex": 3, "Maven POM": 96, "CSS": 4, "JSON with Comments": 7, "Ant Build System": 50, "Graphviz (DOT)": 39, "C": 1, "YAML": 2, "Ruby": 2, "OpenStep Property List": 2, "Swift": 2, "Objective-C": 2, "Scala": 1} | /*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.ide.konan.decompiler
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.kotlin.backend.common.serialization.metadata.KlibMetadataVersion
import org.jetbrains.kotlin.library.metadata.KlibMetadataSerializerProtocol
import org.jetbrains.kotlin.serialization.konan.NullFlexibleTypeDeserializer
class KotlinNativeMetadataDecompiler : KotlinNativeMetadataDecompilerBase<KlibMetadataVersion>(
KotlinNativeMetaFileType,
{ KlibMetadataSerializerProtocol },
NullFlexibleTypeDeserializer,
{ KlibMetadataVersion.INSTANCE },
{ KlibMetadataVersion.INVALID_VERSION },
KotlinNativeMetaFileType.STUB_VERSION
) {
override fun doReadFile(file: VirtualFile): FileWithMetadata? {
val fragment = KotlinNativeLoadingMetadataCache.getInstance().getCachedPackageFragment(file) ?: return null
return FileWithMetadata.Compatible(fragment, KlibMetadataSerializerProtocol) //todo: check version compatibility
}
}
| 1 | null | 1 | 1 | 9dd201aaf243cf9198cf129b22d3aa38fcff182c | 1,187 | kotlin | Apache License 2.0 |
app/src/main/java/com/bnb/grab/widget/CustomHistoryLayout.kt | slowguy | 115,593,603 | false | null | package com.bnb.grab.widget
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.bnb.grab.R
/**
* Created by wsl on 2018/1/8.
*/
class CustomHistoryLayout : LinearLayout, View.OnClickListener {
var mContext: Context? = null
var attrs: AttributeSet? = null
constructor(context: Context) : this(context, null, 0)
constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0)
constructor(context: Context, attributeSet: AttributeSet?, def: Int) : super(context, attributeSet, def) {
mContext = context
attrs = attributeSet
init()
}
var historyText: TextView? = null
var historyDel: ImageView? = null
private fun init() {
val view = LayoutInflater.from(mContext).inflate(R.layout.layout_custom_history, this, true)
initView(view)
initEvent()
}
private fun initView(view: View?) {
historyText = view!!.findViewById(R.id.historyText) as TextView
historyDel = view!!.findViewById(R.id.historyDel) as ImageView
}
private fun initEvent() {
historyText!!.setOnClickListener(this)
historyDel!!.setOnClickListener(this)
}
open fun setUrl(url: String) {
historyText!!.text = url
}
override fun onClick(v: View?) {
when (v!!.id) {
R.id.historyText -> {
listener!!.textClick((historyText!!.text).toString())
}
// R.id.historyDel -> {
// listener!!.delClick()
// }
}
}
fun setOnHistoryActionListener(listener: OnHistoryActionListener) {
this.listener = listener
}
var listener: OnHistoryActionListener? = null
interface OnHistoryActionListener {
fun textClick(text: String)
// fun delClick()
}
} | 0 | Kotlin | 0 | 0 | 03ddd68ff0aa74c0be3de5ec221ef605405269a8 | 2,002 | slowGrab | Apache License 2.0 |
src/DrawPanel.kt | IvanLuLyf | 144,836,900 | false | null | import java.awt.Color
import java.awt.Graphics
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.awt.event.MouseMotionAdapter
import java.io.File
import java.io.PrintWriter
import java.util.*
import javax.swing.JMenuItem
import javax.swing.JPanel
import javax.swing.JPopupMenu
import javax.swing.JSeparator
class DrawPanel : JPanel() {
private var shapes: Vector<Shape> = Vector()
var shapeSelect: Shape? = null
var shapeTemp: Shape? = null
private var preX: Int = 0
private var preY: Int = 0
var hasChange = false
var type: Int = NONE
set(value) {
field = value
shapeSelect?.selected = false
}
var lineColor: Color = Color.BLACK
set(value) {
field = value
shapeSelect?.lineColor = lineColor
repaint()
}
var fillStyle: Int = 1
set(value) {
field = value
shapeSelect?.fillStyle = fillStyle
repaint()
}
var fillColor: Color = Color.WHITE
set(value) {
field = value
shapeSelect?.fillColor = fillColor
repaint()
}
var fillColor2: Color = Color.WHITE
set(value) {
field = value
shapeSelect?.fillColor2 = fillColor2
repaint()
}
var lineWidth = 1
set(value) {
field = value
shapeSelect?.width = lineWidth
repaint()
}
private val popupMenu: JPopupMenu = JPopupMenu().apply {
add(JMenuItem("剪切").apply { addActionListener { cut() } })
add(JMenuItem("复制").apply { addActionListener { copy() } })
add(JMenuItem("粘贴").apply { addActionListener { paste() } })
add(JSeparator())
add(JMenuItem("置顶").apply { addActionListener { goTop() } })
add(JMenuItem("置底").apply { addActionListener { goBottom() } })
add(JMenuItem("上移").apply { addActionListener { goUp() } })
add(JMenuItem("下移").apply { addActionListener { goDown() } })
}
private val mouseMotionListener = object : MouseMotionAdapter() {
override fun mouseDragged(e: MouseEvent) {
if (type == NONE) {
} else {
val x = e.x
var y = e.y
if (e.isShiftDown) {
val p0 = shapes.lastElement().startPoint
val width = x - p0.x
val height = y - p0.y
y = y - height + width
}
shapes.lastElement().endPoint.x = x
shapes.lastElement().endPoint.y = y
hasChange = true
}
repaint()
}
}
private val mouseListener = object : MouseAdapter() {
override fun mouseReleased(e: MouseEvent) {
if (e.button == MouseEvent.BUTTON3) {
popupMenu.show(this@DrawPanel, e.x, e.y)
} else {
if (type == NONE) {
hasChange = true
shapeSelect?.move(e.x - preX, e.y - preY)
}
repaint()
}
}
override fun mousePressed(e: MouseEvent) {
val x = e.x
val y = e.y
preX = x
preY = y
when (type) {
NONE -> {
shapeSelect?.selected = false
shapeSelect = null
for (i in shapes.size - 1 downTo 0) {
if (shapes[i].isContained(x, y)) {
shapes[i].selected = true
shapeSelect = shapes[i]
repaint()
break
}
}
}
LINE -> {
hasChange = true
shapes.add(Line(lineColor, lineWidth, x, y, x, y))
}
RECTANGLE -> {
hasChange = true
shapes.add(Rectangle(lineColor, fillColor, fillColor2, fillStyle, lineWidth, x, y, x, y))
}
OVAL -> {
hasChange = true
shapes.add(Oval(lineColor, fillColor, fillColor2, fillStyle, lineWidth, x, y, x, y))
}
}
}
}
init {
this.shapes = Vector()
background = Color.WHITE
addMouseListener(mouseListener)
addMouseMotionListener(mouseMotionListener)
}
fun newFile() {
hasChange = false
shapes.clear()
repaint()
}
override fun paint(arg0: Graphics?) {
super.paint(arg0)
for (shape in shapes) {
shape.draw(arg0!!)
}
}
fun loadFile(file: File) {
hasChange = false
shapes.clear()
val scanner = Scanner(file)
setSize(scanner.nextInt(), scanner.nextInt())
background = Color(scanner.nextInt())
while (scanner.hasNext()) {
val sType = scanner.next()
when (sType) {
"L" -> shapes.add(Line(scanner))
"R" -> shapes.add(Rectangle(scanner))
"O" -> shapes.add(Oval(scanner))
else -> {
}
}
}
repaint()
}
fun saveFile(file: File) {
hasChange = false
val printWriter = PrintWriter(file)
printWriter.printf("%d %d ", width, height)
printWriter.println(background.rgb)
for (s in shapes) {
s.output(printWriter)
}
printWriter.close()
}
fun cut() {
if (shapeSelect != null) {
hasChange = true
shapeTemp = shapeSelect
shapes.remove(shapeSelect)
shapeSelect = null
repaint()
}
}
fun copy() {
if (shapeSelect != null) {
shapeTemp = copyShape(shapeSelect!!)
}
}
fun paste() {
if (shapeTemp != null) {
hasChange = true
shapeSelect?.selected = false
val shapeNew = copyShape(shapeTemp!!)
if (shapeNew != null) {
shapeNew.selected = true
shapeSelect = shapeNew
shapes.add(shapeNew)
}
repaint()
}
}
fun goTop() {
if (shapeSelect != null) {
hasChange = true
shapes.remove(shapeSelect)
shapes.add(shapeSelect)
repaint()
}
}
fun goUp() {
if (shapeSelect != null) {
hasChange = true
val i = shapes.indexOf(shapeSelect)
if (i < shapes.size - 1) {
shapes.remove(shapeSelect)
shapes.insertElementAt(shapeSelect, i + 1)
}
repaint()
}
}
fun goBottom() {
if (shapeSelect != null) {
hasChange = true
shapes.remove(shapeSelect)
shapes.insertElementAt(shapeSelect, 0)
repaint()
}
}
fun goDown() {
if (shapeSelect != null) {
hasChange = true
val i = shapes.indexOf(shapeSelect)
if (i > 0) {
shapes.remove(shapeSelect)
shapes.insertElementAt(shapeSelect, i - 1)
}
repaint()
}
}
private fun copyShape(shape: Shape): Shape? {
var shapeNew: Shape? = null
when (shape) {
is Line -> shapeNew = Line(shape)
is Rectangle -> shapeNew = Rectangle(shape)
is Oval -> shapeNew = Oval(shape)
}
return shapeNew
}
companion object {
const val NONE = 0
const val LINE = 1
const val RECTANGLE = 2
const val OVAL = 3
}
}
| 0 | Kotlin | 0 | 0 | 3509a8d8c2b3fb68b4143cb2eb133fde2774895b | 7,882 | PaintPadKotlin | MIT License |
growhabit/src/main/kotlin/com/vsrstudio/growhabit/app/App.kt | rozag | 93,681,622 | false | null | package com.vsrstudio.growhabit.app
import android.app.Application
import com.vsrstudio.growhabit.BuildConfig
import com.vsrstudio.growhabit.crash.CrashProvider
import com.vsrstudio.growhabit.logging.ReleaseTree
import timber.log.Timber
class App : Application() {
override fun onCreate() {
super.onCreate()
/*
* Initialize Timber logging.
*
* Later you should change object : CrashProvider {...} stuff to
* something like FabricCrashProvider or FirebaseCrashProvider
* */
Timber.plant(if (BuildConfig.DEBUG) Timber.DebugTree() else ReleaseTree(object : CrashProvider {
override fun report(t: Throwable) {}
}))
// Do your stuff here (e.g. initialize libraries)
}
} | 0 | Kotlin | 0 | 0 | 2737c476b372d4448ff51db1b93dfb8ac9e3015a | 770 | grow-habit | Apache License 2.0 |
SKIE/kotlin-compiler/core/src/commonMain/kotlin/io/outfoxx/swiftpoet/EnumerationCaseSpec.kt | touchlab | 685,579,240 | false | null | /*
* Copyright 2018 Outfox, 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 io.outfoxx.swiftpoet
import io.outfoxx.swiftpoet.builder.BuilderWithDocs
class EnumerationCaseSpec private constructor(
builder: Builder,
) : AttributedSpec(builder.attributes.toImmutableList(), builder.tags) {
val name = builder.name
val typeOrConstant = builder.typeOrConstant
val doc = builder.doc.build()
fun toBuilder(): Builder {
val builder = Builder(name, typeOrConstant)
builder.doc.add(doc)
builder.attributes += attributes
return builder
}
internal fun emit(codeWriter: CodeWriter) {
codeWriter.emitDoc(doc)
codeWriter.emitAttributes(attributes)
codeWriter.emitCode("case %L", escapeIfKeyword(name))
when (typeOrConstant) {
null -> {}
is CodeBlock -> codeWriter.emitCode(" = %L", typeOrConstant)
is TupleTypeName -> typeOrConstant.emit(codeWriter)
else -> throw IllegalStateException("Invalid enum type of constant")
}
}
class Builder internal constructor(
internal var name: String,
internal var typeOrConstant: Any?,
) : AttributedSpec.Builder<Builder>(), BuilderWithDocs<Builder> {
internal val doc = CodeBlock.builder()
override fun addDoc(format: String, vararg args: Any) = apply {
doc.add(format, *args)
}
override fun addDoc(block: CodeBlock) = apply {
doc.add(block)
}
fun build(): EnumerationCaseSpec {
return EnumerationCaseSpec(this)
}
}
companion object {
@JvmStatic
fun builder(name: String) = Builder(name, null)
@JvmStatic
fun builder(name: String, type: TypeName) = Builder(name, TupleTypeName.of("" to type))
@JvmStatic
fun builder(name: String, type: TupleTypeName) = Builder(name, type)
@JvmStatic
fun builder(name: String, constant: CodeBlock) = Builder(name, constant)
@JvmStatic
fun builder(name: String, constant: String) = Builder(name, CodeBlock.of("%S", constant))
@JvmStatic
fun builder(name: String, constant: Int) = Builder(name, CodeBlock.of("%L", constant.toString()))
}
}
| 9 | null | 8 | 735 | b96044d4dec91e4b85c5b310226c6f56e3bfa2b5 | 2,626 | SKIE | Apache License 2.0 |
kazuki-toolkit/src/main/kotlin/com/anaplan/engineering/kazuki/toolkit/sequence/SequenceOrd.kt | anaplan-engineering | 715,012,365 | false | {"Kotlin": 160848, "Shell": 827} | package com.anaplan.engineering.kazuki.toolkit.sequence
import com.anaplan.engineering.kazuki.core.*
import com.anaplan.engineering.kazuki.toolkit.Ord
object SequenceOrd {
fun <T : Comparable<T>> natural() = Natural<T>()
fun <T> byFunction(ordFn: (T, T) -> Ord) = ByFunction(ordFn)
class Natural<T : Comparable<T>> {
val ascending = function(
command = { s: Sequence<T> -> forall(1..<s.len) { i -> s[i] <= s[i + 1] } },
post = { s, result -> result iff descending(s.reverse()) }
)
val descending = function(
command = { s: Sequence<T> -> forall(1..<s.len) { i -> s[i] >= s[i + 1] } }
// can't use ascending in post without loop
)
// TODO requires construct capability
val insert: (T, Sequence<T>) -> Sequence<T> by lazy {
function(
command = { t, s ->
when {
s.isEmpty() -> mk_Seq(t)
else -> {
val u = s.first()
if (t <= u) mk_Seq(t) cat s else mk_Seq(u) cat insert(t, s.tail())
}
}
},
pre = { _, s -> ascending(s) },
post = { t, s, result ->
println(result)
println(mk_Seq(t) cat s)
ascending(result) && SequenceFunctions<T>().permutation(mk_Seq(t) cat s, result)
},
measure = { _, s -> s.len }
)
}
// TODO requires construct capability
val sort: (Sequence<T>) -> Sequence<T> by lazy {
function(
command = { s ->
when {
s.isEmpty() -> mk_Seq()
s.size == 1 -> s
else -> insert(s.head(), sort(s.tail()))
}
},
post = { s, result -> s.elems == result.elems && ascending(result) },
measure = { s -> s.len }
)
}
}
private val LTE = mk_Set(Ord.LT, Ord.EQ)
class ByFunction<T>(
private val ordFn: (T, T) -> Ord
) {
val ascending = function(
command = { s: Sequence<T> -> forall(1..<s.len) { i -> ordFn(s[i], s[i + 1]) in LTE } },
post = { s, result -> result iff descending(s.reverse()) }
)
val descending = function(
command = { s: Sequence<T> -> forall(1..<s.len) { i -> ordFn(s[i + 1], s[i]) in LTE } }
// can't use ascending in post without loop
)
// TODO requires construct capability
val insert: (T, Sequence<T>) -> Sequence<T> by lazy {
function(
command = { t, s ->
when {
s.isEmpty() -> mk_Seq(t)
else -> {
val u = s.first()
if (ordFn(t, u) in LTE) mk_Seq(t) cat s else mk_Seq(u) cat insert(t, s.tail())
}
}
},
pre = { _, s -> ascending(s) },
post = { t, s, result ->
ascending(result) && SequenceFunctions<T>().permutation(mk_Seq(t) cat s, result)
},
measure = { _, s -> s.len }
)
}
// TODO requires construct capability
val sort: (Sequence<T>) -> Sequence<T> by lazy {
function(
command = { s ->
when {
s.isEmpty() -> mk_Seq()
s.size == 1 -> s
else -> insert(s.head(), sort(s.tail()))
}
},
post = { s, result -> s.elems == result.elems && ascending(result) },
measure = { s -> s.len }
)
}
}
}
| 1 | Kotlin | 1 | 0 | 3caf954207b793c48bd733fd3c35d8ba5f78280d | 3,965 | kazuki | MIT License |
android/src/main/java/com/inspiredandroid/linuxcommandbibliotheca/ui/composables/NestedCommandView.kt | SimonSchubert | 20,982,177 | false | null | package com.inspiredandroid.linuxcommandbibliotheca.ui.composables
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.width
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
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.compose.ui.unit.dp
import com.inspiredandroid.linuxcommandbibliotheca.ui.theme.LinuxTheme
import com.linuxcommandlibrary.shared.CommandElement
/* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@Composable
fun NestedCommandView(
text: String,
command: String,
commandElements: List<CommandElement>,
onNavigate: (String) -> Unit,
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
text,
fontWeight = FontWeight.Bold,
modifier = Modifier.width(40.dp),
textAlign = TextAlign.Center,
)
CommandView(
command,
commandElements,
onNavigate,
)
}
}
@Composable
@Preview
fun NestedCommandViewPreview() {
LinuxTheme {
NestedCommandView(
text = "",
command = "$ find ex?mple.txt",
commandElements = listOf(
CommandElement.Text("$ "),
CommandElement.Man("find"),
CommandElement.Text(" ex?mple.txt"),
),
onNavigate = {},
)
}
}
| 9 | null | 62 | 784 | 99506c12c95e3bd4204c07713b69008834b9bc6e | 2,112 | LinuxCommandLibrary | Apache License 2.0 |
src/main/kotlin/no/nav/hjelpemidler/Application.kt | navikt | 390,976,856 | false | null | package no.nav.hjelpemidler
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import io.ktor.application.call
import io.ktor.application.install
import io.ktor.features.ContentNegotiation
import io.ktor.http.ContentType
import io.ktor.jackson.JacksonConverter
import io.ktor.response.respondRedirect
import io.ktor.routing.get
import io.ktor.routing.routing
import mu.KotlinLogging
import no.nav.helse.rapids_rivers.RapidApplication
import no.nav.helse.rapids_rivers.RapidsConnection
import no.nav.hjelpemidler.configuration.Configuration
import no.nav.hjelpemidler.db.dataSourceFrom
import no.nav.hjelpemidler.db.migrate
import no.nav.hjelpemidler.db.waitForDB
import no.nav.hjelpemidler.metrics.AivenMetrics
import no.nav.hjelpemidler.rivers.NySøknadInnsendt
import no.nav.hjelpemidler.suggestions.SuggestionEnginePostgres
import no.nav.hjelpemidler.suggestions.SuggestionService
import kotlin.time.Duration.Companion.minutes
import kotlin.time.ExperimentalTime
private val logg = KotlinLogging.logger {}
private val objectMapper = jacksonObjectMapper()
.registerModule(JavaTimeModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
@ExperimentalTime
fun main() {
if (!waitForDB(10.minutes)) {
throw Exception("database never became available withing the deadline")
}
// Make sure our database migrations are up to date
migrate(Configuration)
val aivenMetrics = AivenMetrics()
// Set up our database connection
val store = SuggestionEnginePostgres(dataSourceFrom(Configuration), aivenMetrics)
val suggestionService = SuggestionService(store)
// InitialDataset.fetchInitialDatasetFor(store)
RapidApplication.Builder(RapidApplication.RapidApplicationConfig.fromEnv(Configuration.aivenConfig))
.withKtorModule {
installAuthentication()
install(ContentNegotiation) {
register(ContentType.Application.Json, JacksonConverter(objectMapper))
}
routing {
get("/isready-composed") {
// TODO: Check database connection
call.respondRedirect("/isready")
}
ktorRoutes(suggestionService)
}
}
.build().apply {
aivenMetrics.initMetabaseProducer(this)
NySøknadInnsendt(this, store, aivenMetrics)
register(
object : RapidsConnection.StatusListener {
override fun onStartup(rapidsConnection: RapidsConnection) {
logg.debug("On rapid startup")
}
override fun onReady(rapidsConnection: RapidsConnection) {
logg.debug("On rapid ready")
}
override fun onNotReady(rapidsConnection: RapidsConnection) {
logg.debug("On rapid not ready")
}
override fun onShutdown(rapidsConnection: RapidsConnection) {
logg.debug("On rapid shutdown")
}
}
)
}.start()
logg.debug("Debug: After rapid start, end of main func")
}
| 0 | Kotlin | 0 | 0 | c0958927066d53d54d2cf8255951cf9940813135 | 3,457 | hm-forslagsmotor-tilbehoer | MIT License |
src/main/java/net/ccbluex/liquidbounce/features/module/modules/world/Timer.kt | Rmejia39 | 733,988,804 | false | {"Kotlin": 2304965, "Java": 1271227, "GLSL": 13515, "JavaScript": 8926} | /*
* FDPClient Hacked Client
* A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge by LiquidBounce.
* https://github.com/SkidderMC/FDPClient/
*/
package net.ccbluex.liquidbounce.features.module.modules.world
import net.ccbluex.liquidbounce.event.EventTarget
import net.ccbluex.liquidbounce.event.UpdateEvent
import net.ccbluex.liquidbounce.features.module.EnumAutoDisableType
import net.ccbluex.liquidbounce.features.module.Module
import net.ccbluex.liquidbounce.features.module.ModuleCategory
import net.ccbluex.liquidbounce.features.module.ModuleInfo
import net.ccbluex.liquidbounce.utils.MovementUtils
import net.ccbluex.liquidbounce.features.value.BoolValue
import net.ccbluex.liquidbounce.features.value.FloatValue
import net.ccbluex.liquidbounce.utils.misc.RandomUtils
@ModuleInfo(name = "Timer", category = ModuleCategory.WORLD, autoDisable = EnumAutoDisableType.RESPAWN)
object Timer : Module() {
// private val minSpeedValue = FloatValue("Speed", 2F, 0.1F, 10F)
private val maxSpeedValue: FloatValue = object : FloatValue("Max-Timer", 2F, 0.1F, 10F) {
fun onChanged(oldValue: Int, newValue: Int) {
val minTimer = minSpeedValue.get()
if (minTimer > newValue) {
set(minTimer)
}
}
}
private val minSpeedValue: FloatValue = object : FloatValue("Min-Timer", 2F, 0.1F, 10F) {
fun onChanged(oldValue: Int, newValue: Int) {
val maxTimer = maxSpeedValue.get()
if (maxTimer < newValue) {
set(maxTimer)
}
}
}
private val onMoveValue = BoolValue("OnMove", true)
override fun onDisable() {
if (mc.thePlayer == null) {
return
}
mc.timer.timerSpeed = 1F
}
@EventTarget
fun onUpdate(event: UpdateEvent) {
if (MovementUtils.isMoving() || !onMoveValue.get()) {
mc.timer.timerSpeed = RandomUtils.nextFloat(minSpeedValue.get(), maxSpeedValue.get())
return
}
mc.timer.timerSpeed = 1F
}
override val tag: String?
get() = "${RandomUtils.nextFloat(minSpeedValue.get(), maxSpeedValue.get()).toString()}"
}
| 3 | Kotlin | 0 | 0 | b48c4e83c888568111a6665037db7fd3f7813ed3 | 2,218 | FDPClient | MIT License |
src/test/kotlin/no/nav/pensjon/kalkulator/tech/security/egress/token/unt/client/fssgw/FssGatewayUsernameTokenClientTest.kt | navikt | 596,104,195 | false | null | package no.nav.pensjon.kalkulator.tech.security.egress.token.unt.client.fssgw
import no.nav.pensjon.kalkulator.mock.MockSecurityConfiguration.Companion.arrangeSecurityContext
import no.nav.pensjon.kalkulator.mock.WebClientTest
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.web.reactive.function.client.WebClient
class FssGatewayUsernameTokenClientTest : WebClientTest() {
private lateinit var client: FssGatewayUsernameTokenClient
@BeforeEach
fun initialize() {
client = FssGatewayUsernameTokenClient(baseUrl(), WebClient.create())
}
@Test
fun `fetchUsernameToken returns access token data when OK response`() {
arrangeSecurityContext()
arrange(okResponse())
val response = client.fetchUsernameToken()
assertEquals(WS_SECURITY_ELEMENT, response.token)
}
private companion object {
private const val WS_SECURITY_ELEMENT =
"""<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" soapenv:mustUnderstand="1">
<wsse:UsernameToken>
<wsse:Username>srvpselv</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">&secret</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>"""
private fun okResponse() = jsonResponse().setBody(WS_SECURITY_ELEMENT)
}
}
| 1 | Kotlin | 0 | 0 | a642602ae4997fb9d88f97464a85a6c3d9c33a89 | 1,581 | pensjonskalkulator-backend | MIT License |
domain/src/main/java/com/guru/cocktails/domain/model/ingredient/IngredientDetail.kt | morristech | 143,734,527 | false | null | package com.guru.cocktails.domain.model.ingredient
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class IngredientDetail(
val id: Int,
val name: String,
val nameGrouped: String,
val description: String,
val imageName: String,
val imageUrl: String,
val numShowed: Int,
val ingredientType: IngredientType,
val voltage: Double
) : Parcelable | 0 | Kotlin | 0 | 0 | f3feac05ebb51a7a30c2d37ccf76f4269da92f07 | 414 | client-android | MIT License |
acceptance-tests/src/main/kotlin/org/ostelco/at/pgw/OcsTest.kt | sami-alajrami | 145,691,257 | false | {"Gradle": 25, "YAML": 32, "Markdown": 33, "Shell": 31, "Text": 1, "Ignore List": 11, "Batchfile": 1, "Dockerfile": 9, "Kotlin": 146, "XML": 27, "Java": 24, "Java Properties": 2, "OASv2-yaml": 2, "INI": 1, "Protocol Buffer": 2, "JSON": 3, "PlantUML": 19, "SVG": 13, "Cypher": 1} | package org.ostelco.at.pgw
import org.jdiameter.api.Avp
import org.jdiameter.api.Session
import org.junit.After
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Test
import org.ostelco.at.common.createProfile
import org.ostelco.at.common.createSubscription
import org.ostelco.at.common.getLogger
import org.ostelco.at.common.randomInt
import org.ostelco.at.jersey.get
import org.ostelco.diameter.model.RequestType
import org.ostelco.diameter.test.TestClient
import org.ostelco.diameter.test.TestHelper
import org.ostelco.prime.client.model.Bundle
import java.lang.Thread.sleep
import kotlin.test.assertEquals
import kotlin.test.fail
/**
* Integration tests for the OcsApplication. This test uses the diameter-test lib to setup a test P-GW to
* actually send Diameter traffic on the selected DataSource to the OcsApplication. The
* DataSource used is the one in the configuration file for this resources.
*
*/
class OcsTest {
private val logger by getLogger()
private var testClient: TestClient? = null
@Before
fun setUp() {
testClient = TestClient()
testClient?.initStack("/")
}
@After
fun tearDown() {
testClient?.shutdown()
testClient = null
}
private fun simpleCreditControlRequestInit(session: Session) {
val client = testClient ?: fail("Test client is null")
val request = client.createRequest(
DEST_REALM,
DEST_HOST,
session
) ?: fail("Failed to create request")
TestHelper.createInitRequest(request.avps, MSISDN, BUCKET_SIZE)
client.sendNextRequest(request, session)
waitForAnswer()
assertEquals(2001L, client.resultCodeAvp?.integer32?.toLong())
val resultAvps = client.resultAvps ?: fail("Missing AVPs")
assertEquals(RequestType.INITIAL_REQUEST.toLong(), resultAvps.getAvp(Avp.CC_REQUEST_TYPE).integer32.toLong())
assertEquals(DEST_HOST, resultAvps.getAvp(Avp.ORIGIN_HOST).utF8String)
assertEquals(DEST_REALM, resultAvps.getAvp(Avp.ORIGIN_REALM).utF8String)
val resultMSCC = resultAvps.getAvp(Avp.MULTIPLE_SERVICES_CREDIT_CONTROL)
assertEquals(2001L, resultMSCC.grouped.getAvp(Avp.RESULT_CODE).integer32.toLong())
assertEquals(1, resultMSCC.grouped.getAvp(Avp.SERVICE_IDENTIFIER_CCA).unsigned32)
assertEquals(10, resultMSCC.grouped.getAvp(Avp.RATING_GROUP).unsigned32)
val granted = resultMSCC.grouped.getAvp(Avp.GRANTED_SERVICE_UNIT)
assertEquals(BUCKET_SIZE, granted.grouped.getAvp(Avp.CC_TOTAL_OCTETS).unsigned64)
}
private fun simpleCreditControlRequestUpdate(session: Session) {
val client = testClient ?: fail("Test client is null")
val request = client.createRequest(
DEST_REALM,
DEST_HOST,
session
) ?: fail("Failed to create request")
TestHelper.createUpdateRequest(request.avps, MSISDN, BUCKET_SIZE, BUCKET_SIZE)
client.sendNextRequest(request, session)
waitForAnswer()
assertEquals(2001L, client.resultCodeAvp?.integer32?.toLong())
val resultAvps = client.resultAvps ?: fail("Missing AVPs")
assertEquals(DEST_HOST, resultAvps.getAvp(Avp.ORIGIN_HOST).utF8String)
assertEquals(DEST_REALM, resultAvps.getAvp(Avp.ORIGIN_REALM).utF8String)
assertEquals(RequestType.UPDATE_REQUEST.toLong(), resultAvps.getAvp(Avp.CC_REQUEST_TYPE).integer32.toLong())
val resultMSCC = resultAvps.getAvp(Avp.MULTIPLE_SERVICES_CREDIT_CONTROL)
assertEquals(2001L, resultMSCC.grouped.getAvp(Avp.RESULT_CODE).integer32.toLong())
val granted = resultMSCC.grouped.getAvp(Avp.GRANTED_SERVICE_UNIT)
assertEquals(BUCKET_SIZE, granted.grouped.getAvp(Avp.CC_TOTAL_OCTETS).unsigned64)
}
private fun getBalance(): Long {
sleep(200) // wait for 200 ms for balance to be updated in db
return get<List<Bundle>> {
path = "/bundles"
subscriberId = EMAIL
}.first().balance
}
@Test
fun simpleCreditControlRequestInitUpdateAndTerminate() {
val client = testClient ?: fail("Test client is null")
val session = client.createSession() ?: fail("Failed to create session")
simpleCreditControlRequestInit(session)
assertEquals(INITIAL_BALANCE - BUCKET_SIZE, getBalance(), message = "Incorrect balance after init")
simpleCreditControlRequestUpdate(session)
assertEquals(INITIAL_BALANCE - 2 * BUCKET_SIZE, getBalance(), message = "Incorrect balance after update")
val request = client.createRequest(
DEST_REALM,
DEST_HOST,
session
) ?: fail("Failed to create request")
TestHelper.createTerminateRequest(request.avps, MSISDN, BUCKET_SIZE)
client.sendNextRequest(request, session)
waitForAnswer()
assertEquals(2001L, client.resultCodeAvp?.integer32?.toLong())
val resultAvps = client.resultAvps ?: fail("Missing AVPs")
assertEquals(DEST_HOST, resultAvps.getAvp(Avp.ORIGIN_HOST).utF8String)
assertEquals(DEST_REALM, resultAvps.getAvp(Avp.ORIGIN_REALM).utF8String)
assertEquals(RequestType.TERMINATION_REQUEST.toLong(), resultAvps.getAvp(Avp.CC_REQUEST_TYPE).integer32.toLong())
val resultMSCC = resultAvps.getAvp(Avp.MULTIPLE_SERVICES_CREDIT_CONTROL)
assertEquals(2001L, resultMSCC.grouped.getAvp(Avp.RESULT_CODE).integer32.toLong())
assertEquals(1, resultMSCC.grouped.getAvp(Avp.SERVICE_IDENTIFIER_CCA).unsigned32)
assertEquals(10, resultMSCC.grouped.getAvp(Avp.RATING_GROUP).unsigned32)
val validTime = resultMSCC.grouped.getAvp(Avp.VALIDITY_TIME)
assertEquals(86400L, validTime.unsigned32)
assertEquals(INITIAL_BALANCE - 2 * BUCKET_SIZE, getBalance(), message = "Incorrect balance after terminate")
}
@Test
fun creditControlRequestInitTerminateNoCredit() {
val client = testClient ?: fail("Test client is null")
val session = client.createSession() ?: fail("Failed to create session")
val request = client.createRequest(
DEST_REALM,
DEST_HOST,
session
) ?: fail("Failed to create request")
TestHelper.createInitRequest(request.avps, "4333333333", BUCKET_SIZE)
client.sendNextRequest(request, session)
waitForAnswer()
run {
assertEquals(2001L, client.resultCodeAvp?.integer32?.toLong())
val resultAvps = client.resultAvps ?: fail("Missing AVPs")
assertEquals(DEST_HOST, resultAvps.getAvp(Avp.ORIGIN_HOST).utF8String)
assertEquals(DEST_REALM, resultAvps.getAvp(Avp.ORIGIN_REALM).utF8String)
assertEquals(RequestType.INITIAL_REQUEST.toLong(), resultAvps.getAvp(Avp.CC_REQUEST_TYPE).integer32.toLong())
val resultMSCC = resultAvps.getAvp(Avp.MULTIPLE_SERVICES_CREDIT_CONTROL)
assertEquals(2001L, resultMSCC.grouped.getAvp(Avp.RESULT_CODE).integer32.toLong())
assertEquals(1, resultMSCC.grouped.getAvp(Avp.SERVICE_IDENTIFIER_CCA).integer32.toLong())
val granted = resultMSCC.grouped.getAvp(Avp.GRANTED_SERVICE_UNIT)
assertEquals(0L, granted.grouped.getAvp(Avp.CC_TOTAL_OCTETS).unsigned64)
}
// There is 2 step in graceful shutdown. First OCS send terminate, then P-GW report used units in a final update
val updateRequest = client.createRequest(
DEST_REALM,
DEST_HOST,
session
) ?: fail("Failed to create request")
TestHelper.createUpdateRequestFinal(updateRequest.avps, "4333333333")
client.sendNextRequest(updateRequest, session)
waitForAnswer()
run {
assertEquals(2001L, client.resultCodeAvp?.integer32?.toLong())
val resultAvps = client.resultAvps ?: fail("Missing AVPs")
assertEquals(DEST_HOST, resultAvps.getAvp(Avp.ORIGIN_HOST).utF8String)
assertEquals(DEST_REALM, resultAvps.getAvp(Avp.ORIGIN_REALM).utF8String)
assertEquals(RequestType.UPDATE_REQUEST.toLong(), resultAvps.getAvp(Avp.CC_REQUEST_TYPE).integer32.toLong())
val resultMSCC = resultAvps.getAvp(Avp.MULTIPLE_SERVICES_CREDIT_CONTROL)
assertEquals(2001L, resultMSCC.grouped.getAvp(Avp.RESULT_CODE).integer32.toLong())
assertEquals(1, resultMSCC.grouped.getAvp(Avp.SERVICE_IDENTIFIER_CCA).integer32.toLong())
val validTime = resultMSCC.grouped.getAvp(Avp.VALIDITY_TIME)
assertEquals(86400L, validTime.unsigned32)
}
// Last step is user disconnecting connection forcing a terminate
val terminateRequest = client.createRequest(
DEST_REALM,
DEST_HOST,
session
) ?: fail("Failed to create request")
TestHelper.createTerminateRequest(terminateRequest.avps, "4333333333")
client.sendNextRequest(terminateRequest, session)
waitForAnswer()
run {
assertEquals(2001L, client.resultCodeAvp?.integer32?.toLong())
val resultAvps = client.resultAvps ?: fail("Missing AVPs")
assertEquals(DEST_HOST, resultAvps.getAvp(Avp.ORIGIN_HOST).utF8String)
assertEquals(DEST_REALM, resultAvps.getAvp(Avp.ORIGIN_REALM).utF8String)
assertEquals(RequestType.TERMINATION_REQUEST.toLong(), resultAvps.getAvp(Avp.CC_REQUEST_TYPE).integer32.toLong())
}
}
private fun waitForAnswer() {
val client = testClient ?: fail("Test client is null")
var i = 0
while (!client.isAnswerReceived && i < 10) {
i++
try {
Thread.sleep(500)
} catch (e: InterruptedException) {
logger.error("Start Failed", e)
}
}
assertEquals(true, client.isAnswerReceived)
}
companion object {
private const val DEST_REALM = "loltel"
private const val DEST_HOST = "ocs"
private const val INITIAL_BALANCE = 100_000_000L
private const val BUCKET_SIZE = 500L
private lateinit var EMAIL: String
private lateinit var MSISDN: String
@BeforeClass
@JvmStatic
fun createTestUserAndSubscription() {
EMAIL = "ocs-${randomInt()}@test.com"
createProfile(name = "Test OCS User", email = EMAIL)
MSISDN = createSubscription(EMAIL)
}
}
}
| 1 | null | 1 | 1 | b642713279f783ca8fa643713cc34f6c8b3560cb | 10,607 | ostelco-core | Apache License 2.0 |
src/test/kotlin/com/autonomousapps/transform/StandardTransformTest.kt | jjohannes | 476,173,763 | false | null | package com.autonomousapps.transform
import com.autonomousapps.internal.utils.intoSet
import com.autonomousapps.model.Advice
import com.autonomousapps.model.GradleVariantIdentification
import com.autonomousapps.model.ModuleCoordinates
import com.autonomousapps.model.declaration.Bucket
import com.autonomousapps.model.declaration.Declaration
import com.autonomousapps.model.declaration.SourceSetKind
import com.autonomousapps.model.intermediates.Reason
import com.autonomousapps.test.usage
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource
internal class StandardTransformTest {
private val emptyGVI = GradleVariantIdentification(emptySet(), emptyMap())
private fun gvi(defaultCapability: String) = GradleVariantIdentification(setOf(defaultCapability), emptyMap())
private val supportedSourceSets = setOf(
"main",
"release", "debug",
"test",
"testDebug", "testRelease",
"androidTest",
"androidTestDebug"
)
@Nested inner class SingleVariant {
@Test fun `no advice for correct declaration`() {
val identifier = "com.foo:bar"
val usages = usage(Bucket.IMPL, "debug").intoSet()
val declarations = Declaration(
identifier = identifier,
configurationName = "implementation",
gradleVariantIdentification = emptyGVI
).intoSet()
val actual = StandardTransform(
ModuleCoordinates(identifier, "1.0", gvi(identifier)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).isEmpty()
}
@Test fun `should be api`() {
val identifier = "com.foo:bar"
val bucket = Bucket.API
val usages = usage(bucket, "debug").intoSet()
val oldConfiguration = Bucket.IMPL.value
val declarations = Declaration(
identifier = identifier,
configurationName = oldConfiguration,
gradleVariantIdentification = emptyGVI
).intoSet()
val actual = StandardTransform(
ModuleCoordinates(identifier, "1.0", gvi(identifier)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofChange(
coordinates = ModuleCoordinates(identifier, "1.0", emptyGVI),
fromConfiguration = oldConfiguration,
toConfiguration = bucket.value
)
)
}
@Test fun `should be implementation`() {
val identifier = "com.foo:bar"
val bucket = Bucket.IMPL
val usages = usage(bucket, "debug").intoSet()
val oldConfiguration = Bucket.API.value
val declarations = Declaration(
identifier = identifier,
configurationName = oldConfiguration,
gradleVariantIdentification = emptyGVI
).intoSet()
val actual = StandardTransform(
ModuleCoordinates(identifier, "1.0", gvi(identifier)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofChange(
coordinates = ModuleCoordinates(identifier, "1.0", emptyGVI),
fromConfiguration = oldConfiguration,
toConfiguration = bucket.value
)
)
}
@Test fun `no advice for correct variant declaration`() {
val identifier = "com.foo:bar"
val bucket = Bucket.IMPL
val usages = usage(bucket, "debug").intoSet()
val declarations = Declaration(
identifier = identifier,
configurationName = "debugImplementation",
gradleVariantIdentification = emptyGVI
).intoSet()
val actual = StandardTransform(
ModuleCoordinates(identifier, "1.0", gvi(identifier)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).isEmpty()
}
@Test fun `should remove unused dependency`() {
val identifier = "com.foo:bar"
val bucket = Bucket.NONE
val usages = usage(bucket, "debug").intoSet()
val fromConfiguration = "api"
val declarations = Declaration(
identifier = identifier,
configurationName = fromConfiguration,
gradleVariantIdentification = emptyGVI
).intoSet()
val actual = StandardTransform(
ModuleCoordinates(identifier, "1.0", gvi(identifier)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofRemove(ModuleCoordinates(identifier, "1.0", emptyGVI), fromConfiguration)
)
}
@Test fun `should add dependency`() {
val identifier = "com.foo:bar"
val usages = usage(Bucket.IMPL, "debug").intoSet()
val declarations = emptySet<Declaration>()
val actual = StandardTransform(
ModuleCoordinates(identifier, "1.0", gvi(identifier)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofAdd(ModuleCoordinates(identifier, "1.0", emptyGVI), "implementation")
)
}
@Test fun `should not remove runtimeOnly declarations`() {
val identifier = "com.foo:bar"
val usages = usage(Bucket.NONE, "debug").intoSet()
val declarations = Declaration(
identifier = identifier,
configurationName = "runtimeOnly",
gradleVariantIdentification = emptyGVI
).intoSet()
val actual = StandardTransform(
ModuleCoordinates(identifier, "1.0", gvi(identifier)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).isEmpty()
}
@Test fun `should not remove compileOnly declarations`() {
val identifier = "com.foo:bar"
val usages = usage(Bucket.NONE, "debug").intoSet()
val declarations = Declaration(
identifier = identifier,
configurationName = "compileOnly",
gradleVariantIdentification = emptyGVI
).intoSet()
val actual = StandardTransform(
ModuleCoordinates(identifier, "1.0", gvi(identifier)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).isEmpty()
}
}
@Nested inner class MultiVariant {
@Test fun `no advice for correct declaration`() {
val identifier = "com.foo:bar"
val bucket = Bucket.IMPL
val usages = setOf(usage(bucket, "debug"), usage(bucket, "release"))
val declarations = Declaration(
identifier = identifier,
configurationName = "implementation",
gradleVariantIdentification = emptyGVI
).intoSet()
val actual = StandardTransform(
ModuleCoordinates(identifier, "1.0", gvi(identifier)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).isEmpty()
}
@Test fun `no advice for undeclared compileOnly usage`() {
val identifier = "com.foo:bar"
val bucket = Bucket.COMPILE_ONLY
val usages = setOf(usage(bucket, "debug"), usage(bucket, "release"))
val declarations = emptySet<Declaration>()
val actual = StandardTransform(
ModuleCoordinates(identifier, "1.0", gvi(identifier)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).isEmpty()
}
@Test fun `no advice for undeclared runtimeOnly usage`() {
val identifier = "com.foo:bar"
val usages = setOf(
usage(Bucket.RUNTIME_ONLY, "debug"),
usage(Bucket.RUNTIME_ONLY, "release")
)
val declarations = emptySet<Declaration>()
val actual = StandardTransform(
ModuleCoordinates(identifier, "1.0", gvi(identifier)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).isEmpty()
}
@Test fun `should be api`() {
val identifier = "com.foo:bar"
val usages = setOf(usage(Bucket.API, "debug"), usage(Bucket.API, "release"))
val fromConfiguration = "implementation"
val declarations = Declaration(
identifier = identifier,
configurationName = fromConfiguration,
gradleVariantIdentification = emptyGVI
).intoSet()
val actual = StandardTransform(
ModuleCoordinates(identifier, "1.0", gvi(identifier)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofChange(
ModuleCoordinates(identifier, "1.0", emptyGVI), fromConfiguration, "api"
)
)
}
@Test fun `should be api on release variant`() {
val identifier = "com.foo:bar"
val usages = setOf(usage(Bucket.IMPL, "debug"), usage(Bucket.API, "release"))
val declarations = Declaration(
identifier = identifier,
configurationName = "implementation",
gradleVariantIdentification = emptyGVI
).intoSet()
val actual = StandardTransform(
ModuleCoordinates(identifier, "1.0", gvi(identifier)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofChange(ModuleCoordinates(identifier, "1.0", emptyGVI), "implementation", "debugImplementation"),
Advice.ofAdd(ModuleCoordinates(identifier, "1.0", emptyGVI), "releaseApi"),
)
}
@Test fun `should be kapt`() {
val identifier = "com.foo:bar"
val bucket = Bucket.ANNOTATION_PROCESSOR
val usages = setOf(usage(bucket, "debug"), usage(bucket, "release"))
val oldConfiguration = "kaptDebug"
val declarations = Declaration(
identifier = identifier,
configurationName = oldConfiguration,
gradleVariantIdentification = emptyGVI
).intoSet()
val actual = StandardTransform(
ModuleCoordinates(identifier, "1.0", gvi(identifier)), declarations, supportedSourceSets, ":", true
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofChange(
coordinates = ModuleCoordinates(identifier, "1.0", emptyGVI),
fromConfiguration = oldConfiguration,
toConfiguration = "kapt"
)
)
}
@Test fun `should not remove unused and undeclared dependency`() {
val identifier = "com.foo:bar"
val usages = setOf(usage(Bucket.NONE, "debug"), usage(Bucket.NONE, "release"))
val declarations = emptySet<Declaration>()
val actual = StandardTransform(
ModuleCoordinates(identifier, "1.0", gvi(identifier)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).isEmpty()
}
@Test fun `should remove unused dependency`() {
val identifier = "com.foo:bar"
val usages = setOf(usage(Bucket.NONE, "debug"), usage(Bucket.NONE, "release"))
val fromConfiguration = "api"
val declarations = Declaration(
identifier = identifier,
configurationName = fromConfiguration,
gradleVariantIdentification = emptyGVI
).intoSet()
val actual = StandardTransform(
ModuleCoordinates(identifier, "1.0", gvi(identifier)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofRemove(ModuleCoordinates(identifier, "1.0", emptyGVI), fromConfiguration)
)
}
@Test fun `should remove unused dependency on release variant`() {
val identifier = "com.foo:bar"
val usages = setOf(
usage(Bucket.IMPL, "debug"),
usage(Bucket.NONE, "release")
)
val fromConfiguration = "implementation"
val declarations = Declaration(
identifier = identifier,
configurationName = fromConfiguration,
gradleVariantIdentification = emptyGVI
).intoSet()
val actual = StandardTransform(
ModuleCoordinates(identifier, "1.0", gvi(identifier)), declarations, supportedSourceSets, ":"
).reduce(usages)
// change from impl -> debugImpl (implicit "remove from release variant")
assertThat(actual).containsExactly(
Advice.ofChange(ModuleCoordinates(identifier, "1.0", emptyGVI), fromConfiguration, "debugImplementation")
)
}
@Test fun `should add dependency`() {
val identifier = "com.foo:bar"
val usages = setOf(usage(Bucket.IMPL, "debug"), usage(Bucket.IMPL, "release"))
val declarations = emptySet<Declaration>()
val actual = StandardTransform(
ModuleCoordinates(identifier, "1.0", gvi(identifier)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(Advice.ofAdd(ModuleCoordinates(identifier, "1.0", emptyGVI), "implementation"))
}
@Test fun `should add dependency to debug as impl and release as api`() {
val identifier = "com.foo:bar"
val usages = setOf(usage(Bucket.IMPL, "debug"), usage(Bucket.API, "release"))
val declarations = emptySet<Declaration>()
val actual = StandardTransform(
ModuleCoordinates(identifier, "1.0", gvi(identifier)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofAdd(ModuleCoordinates(identifier, "1.0", emptyGVI), "debugImplementation"),
Advice.ofAdd(ModuleCoordinates(identifier, "1.0", emptyGVI), "releaseApi")
)
}
@Test fun `should add dependency to debug as impl and not at all for release`() {
val identifier = "com.foo:bar"
val usages = setOf(usage(Bucket.IMPL, "debug"), usage(Bucket.NONE, "release"))
val declarations = emptySet<Declaration>()
val actual = StandardTransform(
ModuleCoordinates(identifier, "1.0", gvi(identifier)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofAdd(ModuleCoordinates(identifier, "1.0", emptyGVI), "debugImplementation")
)
}
}
@Nested inner class MultiDeclaration {
@Test fun `should consolidate on implementation declaration`() {
val id = "com.foo:bar"
val usages = setOf(usage(Bucket.IMPL, "debug"), usage(Bucket.IMPL, "release"))
val declarations = setOf(
Declaration(id, "debugImplementation", emptyGVI),
Declaration(id, "releaseApi", emptyGVI)
)
val actual = StandardTransform(
ModuleCoordinates(id, "1.0", gvi(id)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofChange(ModuleCoordinates(id, "1.0", emptyGVI), "debugImplementation", "implementation"),
Advice.ofRemove(ModuleCoordinates(id, "1.0", emptyGVI), "releaseApi"),
)
}
@Test fun `should consolidate on implementation declaration, with pathological redundant declaration`() {
val id = "com.foo:bar"
val usages = setOf(usage(Bucket.IMPL, "debug"), usage(Bucket.IMPL, "release"))
val declarations = setOf(
Declaration(id, "implementation", emptyGVI),
Declaration(id, "releaseImplementation", emptyGVI)
)
val actual = StandardTransform(
ModuleCoordinates(id, "1.0", gvi(id)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofRemove(ModuleCoordinates(id, "1.0", emptyGVI), "releaseImplementation")
)
}
@Test fun `should consolidate on kapt`() {
val identifier = "com.foo:bar"
val bucket = Bucket.ANNOTATION_PROCESSOR
val usages = setOf(usage(bucket, "debug"), usage(bucket, "release"))
val declarations = setOf(
Declaration(
identifier = identifier, configurationName = "kaptDebug",
gradleVariantIdentification = emptyGVI
),
Declaration(
identifier = identifier, configurationName = "kaptRelease",
gradleVariantIdentification = emptyGVI
)
)
val actual = StandardTransform(
ModuleCoordinates(identifier, "1.0", gvi(identifier)), declarations, supportedSourceSets, ":", true
).reduce(usages)
// The fact that it's kaptDebug -> kapt and kaptRelease -> null and not the other way around is due to alphabetic
// ordering (Debug comes before Release).
assertThat(actual).containsExactly(
Advice.ofChange(
coordinates = ModuleCoordinates(identifier, "1.0", emptyGVI),
fromConfiguration = "kaptDebug",
toConfiguration = "kapt"
),
Advice.ofRemove(
coordinates = ModuleCoordinates(identifier, "1.0", emptyGVI),
fromConfiguration = "kaptRelease",
)
)
}
@Test fun `should remove release declaration and change debug to api`() {
val id = "com.foo:bar"
val usages = setOf(usage(Bucket.API, "debug"), usage(Bucket.NONE, "release"))
val declarations = setOf(
Declaration(id, "debugImplementation", emptyGVI),
Declaration(id, "releaseApi", emptyGVI)
)
val actual = StandardTransform(
ModuleCoordinates(id, "1.0", gvi(id)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofChange(ModuleCoordinates(id, "1.0", emptyGVI), "debugImplementation", "debugApi"),
Advice.ofRemove(ModuleCoordinates(id, "1.0", emptyGVI), "releaseApi")
)
}
@Test fun `should remove both declarations`() {
val id = "com.foo:bar"
val usages = setOf(usage(Bucket.NONE, "debug"), usage(Bucket.NONE, "release"))
val declarations = setOf(
Declaration(id, "debugImplementation", emptyGVI),
Declaration(id, "releaseApi", emptyGVI)
)
val actual = StandardTransform(
ModuleCoordinates(id, "1.0", gvi(id)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofRemove(ModuleCoordinates(id, "1.0", emptyGVI), "debugImplementation"),
Advice.ofRemove(ModuleCoordinates(id, "1.0", emptyGVI), "releaseApi")
)
}
@Test fun `should change both declarations`() {
val id = "com.foo:bar"
val usages = setOf(usage(Bucket.API, "debug"), usage(Bucket.IMPL, "release"))
val declarations = setOf(
Declaration(id, "debugImplementation", emptyGVI),
Declaration(id, "releaseApi", emptyGVI)
)
val actual = StandardTransform(
ModuleCoordinates(id, "1.0", gvi(id)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofChange(ModuleCoordinates(id, "1.0", emptyGVI), "debugImplementation", "debugApi"),
Advice.ofChange(ModuleCoordinates(id, "1.0", emptyGVI), "releaseApi", "releaseImplementation")
)
}
@Test fun `should change debug to debugImpl and release to releaseApi`() {
val id = "com.foo:bar"
val usages = setOf(
usage(Bucket.IMPL, "debug"),
usage(Bucket.API, "release")
)
val declarations = setOf(
Declaration(id, "implementation", emptyGVI),
Declaration(id, "releaseImplementation", emptyGVI)
)
val actual = StandardTransform(
ModuleCoordinates(id, "1.0", gvi(id)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofChange(ModuleCoordinates(id, "1.0", emptyGVI), "implementation", "debugImplementation"),
Advice.ofChange(ModuleCoordinates(id, "1.0", emptyGVI), "releaseImplementation", "releaseApi")
)
}
}
@Nested inner class Flavors {
// TODO
}
@Nested inner class AndroidScenarios {
@Test fun `junit should be declared as testImplementation`() {
val id = "junit:junit"
val usages = setOf(
usage(bucket = Bucket.NONE, variant = "debug", kind = SourceSetKind.MAIN),
usage(bucket = Bucket.NONE, variant = "release", kind = SourceSetKind.MAIN),
usage(bucket = Bucket.IMPL, variant = "debug", kind = SourceSetKind.TEST),
usage(bucket = Bucket.IMPL, variant = "release", kind = SourceSetKind.TEST),
)
val declarations = Declaration(id, "implementation", emptyGVI).intoSet()
val actual = StandardTransform(
ModuleCoordinates(id, "4.13.2", gvi(id)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofChange(ModuleCoordinates(id, "4.13.2", emptyGVI), "implementation", "testImplementation")
)
}
@Test fun `junit should be declared as androidTestImplementation`() {
val id = "junit:junit"
val usages = setOf(
usage(bucket = Bucket.NONE, variant = "debug", kind = SourceSetKind.MAIN),
usage(bucket = Bucket.NONE, variant = "release", kind = SourceSetKind.MAIN),
usage(bucket = Bucket.IMPL, variant = "debug", kind = SourceSetKind.ANDROID_TEST),
usage(bucket = Bucket.IMPL, variant = "release", kind = SourceSetKind.ANDROID_TEST),
)
val declarations = Declaration(id, "implementation", emptyGVI).intoSet()
val actual = StandardTransform(
ModuleCoordinates(id, "4.13.2", gvi(id)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofChange(ModuleCoordinates(id, "4.13.2", emptyGVI), "implementation", "androidTestImplementation")
)
}
@Test fun `junit should be removed from implementation`() {
val id = "junit:junit"
val usages = setOf(
usage(bucket = Bucket.NONE, variant = "debug", kind = SourceSetKind.MAIN),
usage(bucket = Bucket.IMPL, variant = "debug", kind = SourceSetKind.TEST),
usage(bucket = Bucket.NONE, variant = "release", kind = SourceSetKind.MAIN),
usage(bucket = Bucket.IMPL, variant = "release", kind = SourceSetKind.TEST),
usage(bucket = Bucket.IMPL, variant = "debug", kind = SourceSetKind.ANDROID_TEST),
)
val declarations = setOf(
Declaration(id, "implementation", emptyGVI),
Declaration(id, "testImplementation", emptyGVI),
Declaration(id, "androidTestImplementation", emptyGVI),
)
val actual =
StandardTransform(ModuleCoordinates(id, "4.13.2", gvi(id)), declarations, supportedSourceSets, ":").reduce(
usages
)
assertThat(actual).containsExactly(
Advice.ofRemove(ModuleCoordinates(id, "4.13.2", emptyGVI), "implementation")
)
}
@Test fun `should be debugImplementation and testImplementation`() {
val id = "com.foo:bar"
val usages = setOf(
usage(bucket = Bucket.IMPL, variant = "debug", kind = SourceSetKind.MAIN),
usage(bucket = Bucket.NONE, variant = "release", kind = SourceSetKind.MAIN),
usage(bucket = Bucket.IMPL, variant = "debug", kind = SourceSetKind.TEST),
usage(bucket = Bucket.IMPL, variant = "release", kind = SourceSetKind.TEST),
)
val declarations = Declaration(id, "implementation", emptyGVI).intoSet()
val actual = StandardTransform(
ModuleCoordinates(id, "1.0", gvi(id)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofChange(ModuleCoordinates(id, "1.0", emptyGVI), "implementation", "debugImplementation"),
Advice.ofAdd(ModuleCoordinates(id, "1.0", emptyGVI), "testImplementation")
)
}
@Test fun `should be debugImplementation and androidTestImplementation`() {
val id = "com.foo:bar"
val usages = setOf(
usage(bucket = Bucket.IMPL, variant = "debug", kind = SourceSetKind.MAIN),
usage(bucket = Bucket.NONE, variant = "release", kind = SourceSetKind.MAIN),
usage(bucket = Bucket.IMPL, variant = "debug", kind = SourceSetKind.ANDROID_TEST),
usage(bucket = Bucket.IMPL, variant = "release", kind = SourceSetKind.ANDROID_TEST),
)
val declarations = Declaration(id, "implementation", emptyGVI).intoSet()
val actual = StandardTransform(
ModuleCoordinates(id, "1.0", gvi(id)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofChange(ModuleCoordinates(id, "1.0", emptyGVI), "implementation", "debugImplementation"),
Advice.ofAdd(ModuleCoordinates(id, "1.0", emptyGVI), "androidTestImplementation")
)
}
@Test fun `robolectric should be testRuntimeOnly`() {
val id = "org.robolectric:robolectric"
val usages = setOf(
usage(bucket = Bucket.RUNTIME_ONLY, variant = "test", kind = SourceSetKind.TEST),
)
val declarations = Declaration(id, "testImplementation", emptyGVI).intoSet()
val actual = StandardTransform(
ModuleCoordinates(id, "4.4", gvi(id)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofChange(ModuleCoordinates(id, "4.4", emptyGVI), "testImplementation", "testRuntimeOnly"),
)
}
@Test fun `should be debugImplementation`() {
val id = "com.foo:bar"
val usages = setOf(
usage(bucket = Bucket.IMPL, variant = "debug", kind = SourceSetKind.MAIN),
usage(bucket = Bucket.NONE, variant = "release", kind = SourceSetKind.MAIN),
usage(bucket = Bucket.IMPL, variant = "debug", kind = SourceSetKind.TEST),
usage(bucket = Bucket.IMPL, variant = "release", kind = SourceSetKind.TEST),
)
val declarations = setOf(
Declaration(id, "implementation", emptyGVI),
Declaration(id, "testImplementation", emptyGVI)
)
val actual = StandardTransform(
ModuleCoordinates(id, "1.0", gvi(id)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofChange(ModuleCoordinates(id, "1.0", emptyGVI), "implementation", "debugImplementation")
)
}
@Test fun `does not need to be declared on testImplementation`() {
val id = "com.foo:bar"
val usages = setOf(
usage(bucket = Bucket.IMPL, variant = "debug", kind = SourceSetKind.MAIN),
usage(bucket = Bucket.IMPL, variant = "release", kind = SourceSetKind.MAIN),
usage(bucket = Bucket.IMPL, variant = "debug", kind = SourceSetKind.TEST),
usage(bucket = Bucket.IMPL, variant = "release", kind = SourceSetKind.TEST),
)
val declarations = setOf(
Declaration(id, "implementation", emptyGVI),
Declaration(id, "testImplementation", emptyGVI)
)
val actual = StandardTransform(
ModuleCoordinates(id, "1.0", gvi(id)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofRemove(ModuleCoordinates(id, "1.0", emptyGVI), "testImplementation"),
)
}
@Test fun `does not need to be declared on androidTestImplementation`() {
val id = "com.foo:bar"
val usages = setOf(
usage(bucket = Bucket.IMPL, variant = "debug", kind = SourceSetKind.MAIN),
usage(bucket = Bucket.IMPL, variant = "release", kind = SourceSetKind.MAIN),
usage(bucket = Bucket.IMPL, variant = "debug", kind = SourceSetKind.ANDROID_TEST),
usage(bucket = Bucket.IMPL, variant = "release", kind = SourceSetKind.ANDROID_TEST),
)
val declarations = setOf(
Declaration(id, "implementation", emptyGVI),
Declaration(id, "androidTestImplementation", emptyGVI)
)
val actual = StandardTransform(
ModuleCoordinates(id, "1.0", gvi(id)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofRemove(ModuleCoordinates(id, "1.0", emptyGVI), "androidTestImplementation"),
)
}
@Test fun `should be declared on implementation, not testImplementation`() {
val id = "com.foo:bar"
val usages = setOf(
usage(bucket = Bucket.IMPL, variant = "debug", kind = SourceSetKind.MAIN),
usage(bucket = Bucket.IMPL, variant = "release", kind = SourceSetKind.MAIN),
usage(bucket = Bucket.IMPL, variant = "debug", kind = SourceSetKind.TEST),
usage(bucket = Bucket.IMPL, variant = "release", kind = SourceSetKind.TEST),
)
val declarations = setOf(
Declaration(id, "testImplementation", emptyGVI)
)
val actual = StandardTransform(
ModuleCoordinates(id, "1.0", gvi(id)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofChange(ModuleCoordinates(id, "1.0", emptyGVI), "testImplementation", "implementation"),
)
}
@Test fun `should be declared on implementation, not androidTestImplementation`() {
val id = "com.foo:bar"
val usages = setOf(
usage(bucket = Bucket.IMPL, variant = "debug", kind = SourceSetKind.MAIN),
usage(bucket = Bucket.IMPL, variant = "release", kind = SourceSetKind.MAIN),
usage(bucket = Bucket.IMPL, variant = "debug", kind = SourceSetKind.ANDROID_TEST),
usage(bucket = Bucket.IMPL, variant = "release", kind = SourceSetKind.ANDROID_TEST),
)
val declarations = setOf(
Declaration(id, "androidTestImplementation", emptyGVI)
)
val actual = StandardTransform(
ModuleCoordinates(id, "1.0", gvi(id)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofChange(ModuleCoordinates(id, "1.0", emptyGVI), "androidTestImplementation", "implementation"),
)
}
@Test fun `should be debugRuntimeOnly`() {
val identifier = "com.foo:bar"
val usages = usage(Bucket.RUNTIME_ONLY, "debug").intoSet()
val declarations = Declaration(
identifier = identifier,
configurationName = "debugImplementation",
gradleVariantIdentification = emptyGVI
).intoSet()
val actual = StandardTransform(
ModuleCoordinates(identifier, "1.0", gvi(identifier)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofChange(ModuleCoordinates(identifier, "1.0", emptyGVI), "debugImplementation", "debugRuntimeOnly")
)
}
// https://github.com/autonomousapps/dependency-analysis-android-gradle-plugin/issues/860
@Test fun `should be androidTestRuntimeOnly`() {
val identifier = "org.jetbrains.kotlin:kotlin-test-junit"
val resolvedVersion = "1.7.20"
val usages = usage(
bucket = Bucket.RUNTIME_ONLY,
variant = "debug",
kind = SourceSetKind.ANDROID_TEST
).intoSet()
val declarations = Declaration(
identifier = identifier,
configurationName = "androidTestImplementation",
gradleVariantIdentification = emptyGVI
).intoSet()
val actual = StandardTransform(
ModuleCoordinates(identifier, resolvedVersion, gvi(identifier)), declarations, supportedSourceSets, ":"
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofChange(
ModuleCoordinates(identifier, resolvedVersion, emptyGVI),
"androidTestImplementation",
"androidTestRuntimeOnly"
)
)
}
}
@Nested inner class AnnotationProcessors {
@Test fun `hilt is unused and should be removed`() {
val id = "com.google.dagger:hilt-compiler"
val usages = usage(
bucket = Bucket.NONE,
variant = "debug",
kind = SourceSetKind.MAIN,
reasons = Reason.Unused.intoSet()
).intoSet()
val declarations = Declaration(id, "kapt", emptyGVI).intoSet()
val actual = StandardTransform(
ModuleCoordinates(id, "2.40.5", gvi(id)), declarations, supportedSourceSets, ":", true
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofRemove(ModuleCoordinates(id, "2.40.5", emptyGVI), "kapt")
)
}
@Test fun `hilt should be declared on releaseAnnotationProcessor`() {
val id = "com.google.dagger:hilt-compiler"
val usages = setOf(
usage(
bucket = Bucket.NONE,
variant = "debug",
kind = SourceSetKind.MAIN,
reasons = Reason.Unused.intoSet()
),
usage(
bucket = Bucket.ANNOTATION_PROCESSOR,
variant = "release",
kind = SourceSetKind.MAIN
)
)
val declarations = Declaration(id, "kapt", emptyGVI).intoSet()
val actual = StandardTransform(
ModuleCoordinates(id, "2.40.5", gvi(id)), declarations, supportedSourceSets, ":", false
).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofChange(ModuleCoordinates(id, "2.40.5", emptyGVI), "kapt", "releaseAnnotationProcessor")
)
}
@ParameterizedTest(name = "{0} => {1}")
@CsvSource(
value = [
"true, kapt",
"false, annotationProcessor",
]
)
fun `dagger is used and should be added`(usesKapt: Boolean, toConfiguration: String) {
val id = "com.google.dagger:dagger-compiler"
val coordinates = ModuleCoordinates(id, "2.40.5", emptyGVI)
val usages = usage(
bucket = Bucket.ANNOTATION_PROCESSOR,
variant = "debug",
kind = SourceSetKind.MAIN,
reasons = Reason.AnnotationProcessor("", isKapt = false).intoSet()
).intoSet()
val declarations = emptySet<Declaration>()
val actual = StandardTransform(coordinates, declarations, supportedSourceSets, ":", usesKapt).reduce(usages)
assertThat(actual).containsExactly(
Advice.ofAdd(coordinates, toConfiguration)
)
}
}
}
| 96 | null | 97 | 3 | 6891fbcc85ff3e25592b95fbceab0ee47fa2c12a | 33,570 | dependency-analysis-android-gradle-plugin | Apache License 2.0 |
bbfgradle/tmp/results/BACKUP_DIFF/xbuusfb_FILE.kt | DaniilStepanov | 346,008,310 | false | null | // Bug happens on JVM , JVM -Xuse-ir
//File: tmp/tmp0.kt
fun box() : Any {
1?.toByte()?.hashCode()
return "OK"
}
| 1 | null | 1 | 1 | e772ef1f8f951873ebe7d8f6d73cf19aead480fa | 118 | kotlinWithFuzzer | Apache License 2.0 |
tasks/backend/src/main/kotlin/ams/abramelin/tasks/task/service/TaskService.kt | tilau2328 | 156,662,968 | false | null | package ams.abramelin.tasks.task.service
import ams.abramelin.tasks.task.domain.commands.*
import ams.abramelin.tasks.task.query.TaskEntry
import ams.abramelin.tasks.task.query.TaskRepository
import org.axonframework.commandhandling.gateway.CommandGateway
import org.axonframework.common.IdentifierFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
@Service
class TaskService {
private val identifierFactory = IdentifierFactory.getInstance()
@Autowired
private lateinit var taskRepository: TaskRepository
@Autowired
private lateinit var commandGateway: CommandGateway
fun list(): List<TaskEntry> {
return taskRepository.findAll().toList()
}
fun create(user: String, title: String) {
commandGateway.send<Unit>(CreateTask(identifierFactory.generateIdentifier(), user, title))
}
fun updateTaskTitle(id: String, user: String, title: String) {
commandGateway.send<Unit>(UpdateTaskTitle(id, user, title))
}
fun completeTask(id: String, user: String) {
commandGateway.send<Unit>(CompleteTask(id, user))
}
fun reopenTask(id: String, user: String) {
commandGateway.send<Unit>(ReopenTask(id, user))
}
fun starTask(id: String, user: String) {
commandGateway.send<Unit>(StarTask(id, user))
}
fun unstarTask(id: String, user: String) {
commandGateway.send<Unit>(UnstarTask(id, user))
}
} | 0 | Kotlin | 0 | 0 | e9889bfd73056ef4c07c48ec1bc85e0e2cda61be | 1,482 | Abramelin | Apache License 2.0 |
feature/lists/src/main/kotlin/com/lolo/io/onelist/feature/lists/components/list_chips/ListsFlowRow.kt | lolo-io | 198,519,184 | false | {"Kotlin": 363415, "Roff": 549} | package com.lolo.io.onelist.feature.lists.components.list_chips
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.tooling.preview.Preview
import com.lolo.io.onelist.core.model.ItemList
import com.lolo.io.onelist.core.model.previewMany
import com.lolo.io.onelist.core.ui.composables.ComposePreview
import com.lolo.io.onelist.feature.lists.components.core.reorderable_flow_row.DraggableFlowRow
import com.lolo.io.onelist.feature.lists.components.core.reorderable_flow_row.ReorderableFlowRowItem
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@Composable
fun ListsFlowRow(
lists: List<ItemList>,
selectedList: ItemList,
modifier : Modifier = Modifier,
onClick: (ItemList) -> Unit,
onLongClick: (ItemList) -> Unit = {},
onListReordered: (List<ItemList>) -> Unit = {},
) {
val haptic = LocalHapticFeedback.current
var isDragging by remember { mutableStateOf(false) }
var debounceClickLongClick by remember { mutableStateOf<Job?>(null) }
val bgScope = remember {
CoroutineScope(Dispatchers.Default)
}
DraggableFlowRow(
modifier = modifier,
items = lists,
itemKeys = { it.id },
drawItem = { list, isDragged ->
val state = when {
isDragged -> ListChipState.SHADOW
list == selectedList -> ListChipState.SELECTED
else -> ListChipState.DEFAULT
}
ListChip(label = list.title, state,
onClick = {
if(!isDragging && debounceClickLongClick?.isActive != true) {
onClick(list)
} })
},
drawDragItem = {
ListChip(label = it.title, ListChipState.DRAGGED)
},
onDragStart = {
onLongClick(it)
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
isDragging = true
},
onDragEnd = {
isDragging = false
debounceClickLongClick = bgScope.launch { delay(300) }
},
onDragCancel = {
isDragging = false
debounceClickLongClick = bgScope.launch { delay(300) }
},
onListReordered = onListReordered,
horizontalArrangement = Arrangement.Center,
)
}
@Preview
@Composable
private fun Preview_ListsFlowRow() = ComposePreview {
val lists = ItemList.previewMany(5)
val selectedList = lists.get(0)
ListsFlowRow(lists = lists, selectedList = selectedList,
onClick = { showPreviewDialog(it.title) })
} | 18 | Kotlin | 26 | 92 | ca7df6ec46344bde7c5e357d0784ecdfdecbb78e | 3,037 | OneList | MIT License |
app/src/test/java/com/patmore/android/features/authentication/domain/usecases/GetTwitterUserAccessTokenUseCaseTest.kt | jawnpaul | 514,394,689 | false | {"Kotlin": 189149} | package com.patmore.android.features.authentication.domain.usecases
import com.patmore.android.UnitTest
import com.patmore.android.core.functional.Either
import com.patmore.android.features.authentication.data.remote.model.AccessTokenRequest
import com.patmore.android.features.authentication.domain.repository.IAuthenticationRepository
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.impl.annotations.MockK
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
@ExperimentalCoroutinesApi
class GetTwitterUserAccessTokenUseCaseTest : UnitTest() {
private lateinit var getTwitterUserAccessTokenUseCase: GetTwitterUserAccessTokenUseCase
@MockK
private lateinit var iAuthenticationRepository: IAuthenticationRepository
@Before
fun setUp() {
getTwitterUserAccessTokenUseCase =
GetTwitterUserAccessTokenUseCase(iAuthenticationRepository)
}
@Test
fun `should call get OAuth2 access token`() = runTest {
val params = AccessTokenRequest(code = "", challenge = "", clientID = "", callback = "")
coEvery {
iAuthenticationRepository.getOauth2AccessToken(params)
} returns flow {
emit(Either.Right(Unit))
}
getTwitterUserAccessTokenUseCase.run(params)
coVerify(exactly = 1) {
iAuthenticationRepository.getOauth2AccessToken(params)
}
}
}
| 3 | Kotlin | 1 | 11 | 9a36efdd72ea4b7ee51e09de28c863be52cf53fa | 1,517 | patmore-android | MIT License |
preview-designer/src/com/android/tools/idea/preview/lifecycle/PreviewLifecycleManager.kt | JetBrains | 60,701,247 | false | null | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.preview.lifecycle
import com.android.annotations.concurrency.GuardedBy
import com.android.tools.idea.concurrency.createChildScope
import com.android.tools.idea.concurrency.scopeDisposable
import com.android.tools.idea.preview.essentials.PreviewEssentialsModeManager
import com.android.tools.idea.uibuilder.editor.multirepresentation.PreviewRepresentation
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancel
import org.jetbrains.annotations.TestOnly
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
/**
* Class that manages preview
* [PreviewRepresentation.onActivate]/[PreviewRepresentation.onDeactivate] lifecycle. It allows to
* specify actions that should be executed when the lifecycle events happen and execute custom code
* scoped to the active mode only.
*
* @param parentScope the [PreviewRepresentation] [CoroutineScope]
* @param onInitActivate the code that should be executed on the very first activation
* @param onResumeActivate the code that should be executed on the following activations but not the
* first one
* @param onDeactivate the code that should be executed right away after deactivation
* @param onDelayedDeactivate the deactivation code that can be delayed and not needed to be
* executed right away after the deactivation. This could be because this deactivation will make
* the next activation take a long time and we want to make sure that we only fully deactivate
* when we unlikely to activate again.
*/
class PreviewLifecycleManager
private constructor(
private val parentScope: CoroutineScope,
private val onInitActivate: CoroutineScope.() -> Unit,
private val onResumeActivate: CoroutineScope.() -> Unit,
private val onDeactivate: () -> Unit,
private val onDelayedDeactivate: () -> Unit,
private val scheduleDelayed: (Disposable, () -> Unit) -> Unit,
) {
/**
* @param project the project for the [PreviewRepresentation]
* @param parentScope the [PreviewRepresentation] [CoroutineScope]
* @param onInitActivate the code that should be executed on the very first activation
* @param onResumeActivate the code that should be executed on the following activations but not
* the first one
* @param onDeactivate the code that should be executed right away after deactivation
* @param onDelayedDeactivate the deactivation code that can be delayed and not needed to be
* executed right away after the deactivation. This could be because this deactivation will make
* the next activation take a long time and we want to make sure that we only fully deactivate
* when we unlikely to activate again.
*/
constructor(
project: Project,
parentScope: CoroutineScope,
onInitActivate: CoroutineScope.() -> Unit,
onResumeActivate: CoroutineScope.() -> Unit,
onDeactivate: () -> Unit,
onDelayedDeactivate: () -> Unit,
) : this(
parentScope,
onInitActivate,
onResumeActivate,
onDeactivate,
onDelayedDeactivate,
project.getService(PreviewDeactivationProjectService::class.java).deactivationQueue::
addDelayedAction,
)
private val scopeDisposable = parentScope.scopeDisposable()
/**
* [CoroutineScope] that is valid while this is active. The scope will be cancelled as soon as
* this becomes inactive. This scope is used to launch the tasks that only make sense while in the
* active mode.
*/
@get:Synchronized @set:Synchronized private var activationScope: CoroutineScope? = null
/**
* Lock used during the [onInitActivate]/[onResumeActivate]/[onDeactivate]/[onDelayedDeactivate]
* to avoid activations happening in the middle.
*/
private val activationLock = ReentrantLock()
/**
* Tracks whether this is active or not. The value tracks the [activate] and [deactivate] calls.
*/
private val isActive = AtomicBoolean(false)
/**
* Tracks whether [activate] call has been before or not. This is used to decide whether
* [onInitActivate] or [onResumeActivate] must be called.
*/
@GuardedBy("activationLock") private var isFirstActivation = true
/** The user should call this to indicate that the parent was activated. */
fun activate() =
activationLock.withLock {
if (isActive.get()) return
activationScope?.cancel()
val scope = parentScope.createChildScope(true)
activationScope = scope
isActive.set(true)
if (isFirstActivation) {
isFirstActivation = false
scope.onInitActivate()
} else {
scope.onResumeActivate()
}
}
fun isActive() = isActive.get()
private fun delayedDeactivate() =
activationLock.withLock {
if (!isActive.get()) {
onDelayedDeactivate()
}
}
/**
* The user should call this to indicate that the parent was deactivated. If
* [deactivateImmediately] is false, part of the deactivation might run later, allowing for a
* quicker re-activation.
*/
private fun deactivate(deactivateImmediately: Boolean = false) =
activationLock.withLock {
if (!isActive.get()) return
activationScope?.cancel()
activationScope = null
isActive.set(false)
onDeactivate()
if (deactivateImmediately || PreviewEssentialsModeManager.isEssentialsModeEnabled) {
// When in essentials mode or if deactivateImmediately, deactivate immediately to free
// resources.
onDelayedDeactivate()
} else {
scheduleDelayed(scopeDisposable, this::delayedDeactivate)
}
}
/**
* Call this method to indicate that the parent is being deactivated. The full deactivation might
* be delayed allowing for a quick re-activation.
*/
fun deactivate() = deactivate(false)
/** Call this to indicate that the parent is being deactivated immediately without delay. */
internal fun deactivateImmediately() = deactivate(true)
/** Allows to execute code that only makes sense in the active mode. */
fun <T> executeIfActive(block: CoroutineScope.() -> T): T? = activationScope?.block()
companion object {
@TestOnly
fun createForTest(
parentScope: CoroutineScope,
onInitActivate: CoroutineScope.() -> Unit = {},
onResumeActivate: CoroutineScope.() -> Unit = {},
onDeactivate: () -> Unit = {},
onDelayedDeactivate: () -> Unit = {},
scheduleDelayed: (Disposable, () -> Unit) -> Unit = { _, _ -> },
): PreviewLifecycleManager =
PreviewLifecycleManager(
parentScope,
onInitActivate,
onResumeActivate,
onDeactivate,
onDelayedDeactivate,
scheduleDelayed,
)
}
}
| 5 | null | 227 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 7,422 | android | Apache License 2.0 |
vok-framework-jpa/src/test/kotlin/eu/vaadinonkotlin/vaadin8/jpa/JPADataProviderTest.kt | jhult | 212,693,470 | true | {"Kotlin": 443438, "Java": 7957, "JavaScript": 1242, "CSS": 201, "TSQL": 96} | package eu.vaadinonkotlin.vaadin8.jpa
import com.github.mvysny.dynatest.DynaTest
import com.github.mvysny.dynatest.expectList
import com.github.mvysny.karibudsl.v8.addColumnFor
import com.github.mvysny.karibudsl.v8.grid
import com.github.mvysny.kaributesting.v8.MockVaadin
import com.github.mvysny.kaributesting.v8.expectRow
import com.github.mvysny.kaributesting.v8.expectRows
import com.vaadin.data.provider.Query
import com.vaadin.data.provider.QuerySortOrder
import com.vaadin.ui.UI
import kotlin.streams.toList
import kotlin.test.expect
class JPADataProviderTest : DynaTest({
usingDatabase()
test("noEntities") {
val ds = jpaDataProvider<TestPerson>()
expect(0) { ds.size(Query()) }
expect(false) { ds.isInMemory }
expectList() { ds.fetch(Query()).toList() }
}
test("sorting") {
val ds = jpaDataProvider<TestPerson>()
db { for (i in 15..90) em.persist(TestPerson(name = "test$i", age = i)) }
expect(76) { ds.size(Query()) }
expect((90 downTo 15).toList()) { ds.fetch(Query(0, 100, QuerySortOrder.desc("age").build(), null, null)).toList().map { it.age!! } }
}
test("filter") {
db { for (i in 15..90) em.persist(TestPerson(name = "test$i", age = i)) }
val ds = jpaDataProvider<TestPerson>().and { TestPerson::age between 30..60 }
expect(31) { ds.size(Query()) }
expect((30..60).toList()) { ds.fetch(Query(0, 100, QuerySortOrder.asc("age").build(), null, null)).toList().map { it.age!! } }
}
test("paging") {
db { for (i in 15..90) em.persist(TestPerson(name = "test$i", age = i)) }
val ds = jpaDataProvider<TestPerson>().and { TestPerson::age between 30..60 }
expect((30..39).toList()) { ds.fetch(Query(0, 10, QuerySortOrder.asc("age").build(), null, null)).toList().map { it.age!! } }
expect((40..49).toList()) { ds.fetch(Query(10, 10, QuerySortOrder.asc("age").build(), null, null)).toList().map { it.age!! } }
}
group("Vaadin Grid") {
beforeEach { MockVaadin.setup() }
afterEach { MockVaadin.tearDown() }
test("grid") {
db { for (i in 15..20) em.persist(TestPerson(name = "test$i", age = i)) }
val grid = UI.getCurrent().grid<TestPerson> {
dataProvider = jpaDataProvider<TestPerson>()
addColumnFor(TestPerson::name)
addColumnFor(TestPerson::age)
}
grid.expectRows(6)
grid.expectRow(0, "test15", "15")
}
}
})
| 0 | Kotlin | 0 | 1 | 6c684f111addc6bf47b57ff35aca44badf1741ee | 2,535 | vaadin-on-kotlin | MIT License |
src/main/kotlin/dev/shtanko/algorithms/exercises/UniqueCharacters.kt | ashtanko | 203,993,092 | false | {"Kotlin": 7135393, "Shell": 1168, "Makefile": 1135} | /*
* Copyright 2020 Oleksii Shtanko
*
* 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 dev.shtanko.algorithms.exercises
import java.util.Collections
import java.util.stream.Collectors
/**
* Implement an algorithm to determine if a string has all unique characters
* What if you can not use additional data structures?
*/
fun interface UniqueCharacters {
operator fun invoke(str: String): Boolean
}
class UniqueCharactersSet : UniqueCharacters {
override fun invoke(str: String): Boolean {
if (str.isBlank()) return false
return str.length == str.toSet().size
}
}
/**
* Not use additional data structures
*/
class UniqueCharactersSort : UniqueCharacters {
override fun invoke(str: String): Boolean {
if (str.isBlank()) return false
val chars = str.toCharArray().sorted()
for (i in 0 until chars.size - 1) {
if (chars[i] != chars[i + 1]) {
continue
} else {
return false
}
}
return true
}
}
class UniqueCharactersStream : UniqueCharacters {
override fun invoke(str: String): Boolean {
if (str.isBlank()) return false
return str.chars().filter { e ->
val c = str.chars()
.boxed()
.collect(Collectors.toList())
Collections.frequency(c, e) > 1
}.count() <= 1
}
}
class UniqueCharactersBruteForce : UniqueCharacters {
override fun invoke(str: String): Boolean {
if (str.isBlank()) return false
for (i in str.indices) {
for (j in i + 1 until str.length) {
if (str[i] == str[j]) {
return false
}
}
}
return true
}
}
| 4 | Kotlin | 0 | 19 | 354dd5fb65ab0ec96c42b7772c2cb1d292a96db0 | 2,290 | kotlab | Apache License 2.0 |
app/src/main/java/com/example/anywherefitness/ui/Instructor/InstructorActivity.kt | BuildWeek-Anywhere-Fitness | 210,391,400 | false | null | package com.example.anywherefitness.ui.Instructor
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import com.google.android.material.bottomnavigation.BottomNavigationView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import androidx.fragment.app.Fragment
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.example.anywherefitness.App
import com.example.anywherefitness.R
import com.example.anywherefitness.ui.LoginActivity
class InstructorActivity : AppCompatActivity() {
companion object {
val INSTRUCTOR_USER = "key"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_instructor)
val navView: BottomNavigationView = findViewById(R.id.nav_view)
val navController = findNavController(R.id.nav_host_fragment_instructor)
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
val appBarConfiguration = AppBarConfiguration(
setOf(
R.id.navigation_classes_instructor, R.id.navigation_create_class_instructor
)
)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
navView.setOnNavigationItemSelectedListener {
var selectedFragment: Fragment? = null
when (it.itemId) {
R.id.navigation_classes_instructor -> {
selectedFragment = InstructorClassesFragment()
title = "My Classes"
}
R.id.navigation_create_class_instructor -> {
selectedFragment = CreateClassesFragment()
title = "Create Class"
}
}
selectedFragment?.let { it1 ->
supportFragmentManager.beginTransaction().replace(
R.id.nav_host_fragment_instructor,
it1
).commit()
}
true
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.log_out_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val saveToken = getSharedPreferences(LoginActivity.SAVE_TOKEN, Context.MODE_PRIVATE)
saveToken.edit{
clear()
}
startActivity(Intent(this, LoginActivity::class.java))
finish()
return super.onOptionsItemSelected(item)
}
override fun onDestroy() {
super.onDestroy()
App.repo?.deleteAllClasses()
}
}
| 0 | Kotlin | 0 | 0 | 25a29064b478204e249654b8b2b554a5b2b209e7 | 3,001 | ANDROID-ENGINEER-II | MIT License |
coil-base/src/androidTest/java/coil/RealImageLoaderTest.kt | ianhanniballake | 384,854,300 | false | null | @file:Suppress("SameParameterValue")
package coil
import android.content.ContentResolver.SCHEME_ANDROID_RESOURCE
import android.content.ContentResolver.SCHEME_CONTENT
import android.content.ContentResolver.SCHEME_FILE
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.ColorDrawable
import android.widget.ImageView
import androidx.core.net.toUri
import androidx.test.core.app.ApplicationProvider
import coil.annotation.ExperimentalCoilApi
import coil.base.test.R
import coil.bitmap.BitmapPool
import coil.bitmap.RealBitmapReferenceCounter
import coil.decode.BitmapFactoryDecoder
import coil.decode.DecodeResult
import coil.decode.Decoder
import coil.decode.Options
import coil.fetch.AssetUriFetcher.Companion.ASSET_FILE_PATH_ROOT
import coil.memory.MemoryCache
import coil.memory.RealWeakMemoryCache
import coil.memory.StrongMemoryCache
import coil.request.CachePolicy
import coil.request.DefaultRequestOptions
import coil.request.ErrorResult
import coil.request.ImageRequest
import coil.request.NullRequestDataException
import coil.request.SuccessResult
import coil.size.PixelSize
import coil.size.Precision
import coil.size.Size
import coil.util.Utils
import coil.util.createMockWebServer
import coil.util.decodeBitmapAsset
import coil.util.getDrawableCompat
import coil.util.size
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.suspendCancellableCoroutine
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.mockwebserver.MockWebServer
import okio.BufferedSource
import okio.buffer
import okio.sink
import okio.source
import org.junit.After
import org.junit.Before
import org.junit.Test
import java.io.File
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
@OptIn(ExperimentalCoilApi::class)
class RealImageLoaderTest {
private lateinit var context: Context
private lateinit var server: MockWebServer
private lateinit var strongMemoryCache: StrongMemoryCache
private lateinit var imageLoader: RealImageLoader
@Before
fun before() {
context = ApplicationProvider.getApplicationContext()
server = createMockWebServer(context, IMAGE_NAME, IMAGE_NAME)
val bitmapPool = BitmapPool(Int.MAX_VALUE)
val weakMemoryCache = RealWeakMemoryCache(null)
val referenceCounter = RealBitmapReferenceCounter(weakMemoryCache, bitmapPool, null)
strongMemoryCache = StrongMemoryCache(weakMemoryCache, referenceCounter, Int.MAX_VALUE, null)
imageLoader = RealImageLoader(
context = context,
defaults = DefaultRequestOptions(),
bitmapPool = bitmapPool,
referenceCounter = referenceCounter,
strongMemoryCache = strongMemoryCache,
weakMemoryCache = weakMemoryCache,
callFactory = OkHttpClient(),
eventListenerFactory = EventListener.Factory.NONE,
componentRegistry = ComponentRegistry(),
logger = null
)
}
@After
fun after() {
server.shutdown()
imageLoader.shutdown()
}
// region Test all the supported data types.
@Test
fun string() {
val data = server.url(IMAGE_NAME).toString()
testEnqueue(data)
testExecute(data)
}
@Test
fun httpUri() {
val data = server.url(IMAGE_NAME).toString().toUri()
testEnqueue(data)
testExecute(data)
}
@Test
fun httpUrl() {
val data = server.url(IMAGE_NAME)
testEnqueue(data)
testExecute(data)
}
@Test
fun resourceInt() {
val data = R.drawable.normal
testEnqueue(data)
testExecute(data)
}
@Test
fun resourceIntVector() {
val data = R.drawable.ic_android
testEnqueue(data, PixelSize(100, 100))
testExecute(data, PixelSize(100, 100))
}
@Test
fun resourceUriInt() {
val data = "$SCHEME_ANDROID_RESOURCE://${context.packageName}/${R.drawable.normal}".toUri()
testEnqueue(data)
testExecute(data)
}
@Test
fun resourceUriIntVector() {
val data = "$SCHEME_ANDROID_RESOURCE://${context.packageName}/${R.drawable.ic_android}".toUri()
testEnqueue(data, PixelSize(100, 100))
testExecute(data, PixelSize(100, 100))
}
@Test
fun resourceUriString() {
val data = "$SCHEME_ANDROID_RESOURCE://${context.packageName}/drawable/normal".toUri()
testEnqueue(data)
testExecute(data)
}
@Test
fun resourceUriStringVector() {
val data = "$SCHEME_ANDROID_RESOURCE://${context.packageName}/drawable/ic_android".toUri()
testEnqueue(data, PixelSize(100, 100))
testExecute(data, PixelSize(100, 100))
}
@Test
fun file() {
val data = copyNormalImageAssetToCacheDir()
testEnqueue(data)
testExecute(data)
}
@Test
fun fileUri() {
val data = copyNormalImageAssetToCacheDir().toUri()
testEnqueue(data)
testExecute(data)
}
@Test
fun assetUri() {
val data = "$SCHEME_FILE:///$ASSET_FILE_PATH_ROOT/exif/large_metadata.jpg".toUri()
testEnqueue(data, PixelSize(75, 100))
testExecute(data, PixelSize(100, 133))
}
@Test
fun contentUri() {
val data = "$SCHEME_CONTENT://coil/$IMAGE_NAME".toUri()
testEnqueue(data)
testExecute(data)
}
@Test
fun drawable() {
val data = context.getDrawableCompat(R.drawable.normal)
val expectedSize = PixelSize(1080, 1350)
testEnqueue(data, expectedSize)
testExecute(data, expectedSize)
}
@Test
fun bitmap() {
val data = (context.getDrawableCompat(R.drawable.normal) as BitmapDrawable).bitmap
val expectedSize = PixelSize(1080, 1350)
testEnqueue(data, expectedSize)
testExecute(data, expectedSize)
}
// endregion
@Test
fun unsupportedDataThrows() {
val data = Any()
assertFailsWith<IllegalStateException> { testEnqueue(data) }
assertFailsWith<IllegalStateException> { testExecute(data) }
}
@Test
fun memoryCacheDisabled_preloadDoesNotDecode() {
val imageLoader = ImageLoader.Builder(context)
.componentRegistry {
add(object : Decoder {
override fun handles(source: BufferedSource, mimeType: String?) = true
override suspend fun decode(
pool: BitmapPool,
source: BufferedSource,
size: Size,
options: Options
) = throw IllegalStateException("Decode should not be called.")
})
}
.build()
val url = server.url(IMAGE_NAME)
val cacheFolder = Utils.getDefaultCacheDirectory(context).apply {
deleteRecursively()
mkdirs()
}
assertTrue(cacheFolder.listFiles().isNullOrEmpty())
runBlocking {
suspendCancellableCoroutine<Unit> { continuation ->
val request = ImageRequest.Builder(context)
.data(url)
.memoryCachePolicy(CachePolicy.DISABLED)
.listener(
onSuccess = { _, _ -> continuation.resume(Unit) },
onError = { _, throwable -> continuation.resumeWithException(throwable) },
onCancel = { continuation.resumeWithException(CancellationException()) }
)
.build()
imageLoader.enqueue(request)
}
}
val cacheFile = cacheFolder.listFiles().orEmpty().find { it.name.contains(Cache.key(url)) && it.length() == IMAGE_SIZE }
assertNotNull(cacheFile, "Did not find the image file in the disk cache.")
}
@Test
fun memoryCacheDisabled_getDoesDecode() {
var numDecodes = 0
val imageLoader = ImageLoader.Builder(context)
.componentRegistry {
add(object : Decoder {
private val delegate = BitmapFactoryDecoder(context)
override fun handles(source: BufferedSource, mimeType: String?) = true
override suspend fun decode(
pool: BitmapPool,
source: BufferedSource,
size: Size,
options: Options
): DecodeResult {
numDecodes++
return delegate.decode(pool, source, size, options)
}
})
}
.build()
val url = server.url(IMAGE_NAME)
val cacheFolder = Utils.getDefaultCacheDirectory(context).apply {
deleteRecursively()
mkdirs()
}
assertTrue(cacheFolder.listFiles().isNullOrEmpty())
runBlocking {
val request = ImageRequest.Builder(context)
.data(url)
.memoryCachePolicy(CachePolicy.DISABLED)
.build()
imageLoader.execute(request)
}
val cacheFile = cacheFolder.listFiles().orEmpty().find { it.name.contains(Cache.key(url)) && it.length() == IMAGE_SIZE }
assertNotNull(cacheFile, "Did not find the image file in the disk cache.")
assertEquals(1, numDecodes)
}
@Test
fun nullRequestDataShowsFallbackDrawable() {
val error = ColorDrawable(Color.BLUE)
val fallback = ColorDrawable(Color.BLACK)
runBlocking {
suspendCancellableCoroutine<Unit> { continuation ->
var hasCalledTargetOnError = false
val request = ImageRequest.Builder(context)
.data(null)
.size(100, 100)
.error(error)
.fallback(fallback)
.target(
onStart = { throw IllegalStateException() },
onError = { drawable ->
check(drawable === fallback)
hasCalledTargetOnError = true
},
onSuccess = { throw IllegalStateException() }
)
.listener(
onStart = { throw IllegalStateException() },
onSuccess = { _, _ -> throw IllegalStateException() },
onCancel = { throw IllegalStateException() },
onError = { _, throwable ->
if (hasCalledTargetOnError && throwable is NullRequestDataException) {
continuation.resume(Unit)
} else {
continuation.resumeWithException(throwable)
}
}
)
.build()
imageLoader.enqueue(request)
}
}
}
@Test
fun loadedImageIsPresentInMemoryCache() {
val result = runBlocking {
val request = ImageRequest.Builder(context)
.data(server.url(IMAGE_NAME))
.size(100, 100)
.build()
imageLoader.execute(request)
}
assertTrue(result is SuccessResult)
val bitmap = (result.drawable as BitmapDrawable).bitmap
assertNotNull(bitmap)
assertEquals(bitmap, imageLoader.memoryCache[result.metadata.memoryCacheKey!!])
}
@Test
fun placeholderKeyReturnsCorrectMemoryCacheEntry() {
val key = MemoryCache.Key("fake_key")
val fileName = "normal.jpg"
val bitmap = decodeAssetAndAddToMemoryCache(key, fileName)
runBlocking {
suspendCancellableCoroutine<Unit> { continuation ->
val request = ImageRequest.Builder(context)
.memoryCacheKey(key)
.placeholderMemoryCacheKey(key)
.data("$SCHEME_FILE:///$ASSET_FILE_PATH_ROOT/$fileName")
.size(100, 100)
.precision(Precision.INEXACT)
.allowHardware(true)
.dispatcher(Dispatchers.Main.immediate)
.target(
onStart = {
// The drawable in the memory cache should be returned here.
assertEquals(bitmap, (it as BitmapDrawable).bitmap)
},
onSuccess = {
// The same drawable should be returned since the drawable is valid for this request.
assertEquals(bitmap, (it as BitmapDrawable).bitmap)
}
)
.listener(
onSuccess = { _, _ -> continuation.resume(Unit) },
onError = { _, throwable -> continuation.resumeWithException(throwable) },
onCancel = { continuation.cancel() }
)
.build()
imageLoader.enqueue(request)
}
}
}
private fun testEnqueue(data: Any, expectedSize: PixelSize = PixelSize(80, 100)) {
val imageView = ImageView(context)
imageView.scaleType = ImageView.ScaleType.FIT_CENTER
assertNull(imageView.drawable)
runBlocking {
suspendCancellableCoroutine<Unit> { continuation ->
val request = ImageRequest.Builder(context)
.data(data)
.target(imageView)
.size(100, 100)
.listener(
onSuccess = { _, _ -> continuation.resume(Unit) },
onError = { _, throwable -> continuation.resumeWithException(throwable) },
onCancel = { continuation.resumeWithException(CancellationException()) }
)
.build()
imageLoader.enqueue(request)
}
}
val drawable = imageView.drawable
assertTrue(drawable is BitmapDrawable)
assertEquals(expectedSize, drawable.bitmap.size)
}
private fun testExecute(data: Any, expectedSize: PixelSize = PixelSize(100, 125)) {
val result = runBlocking {
val request = ImageRequest.Builder(context)
.data(data)
.size(100, 100)
.build()
imageLoader.execute(request)
}
if (result is ErrorResult) {
throw result.throwable
}
assertTrue(result is SuccessResult)
val drawable = result.drawable
assertTrue(drawable is BitmapDrawable)
assertEquals(expectedSize, drawable.bitmap.size)
}
private fun copyNormalImageAssetToCacheDir(): File {
val file = File(context.cacheDir, IMAGE_NAME)
val source = context.assets.open(IMAGE_NAME).source()
val sink = file.sink().buffer()
source.use { sink.use { sink.writeAll(source) } }
return file
}
private fun decodeAssetAndAddToMemoryCache(key: MemoryCache.Key, fileName: String): Bitmap {
val bitmap = context.decodeBitmapAsset(fileName)
strongMemoryCache.set(key, bitmap, false)
return bitmap
}
companion object {
private const val IMAGE_NAME = "normal.jpg"
private const val IMAGE_SIZE = 443291L
}
}
| 0 | null | 0 | 1 | e5f7c568e94a58e7552627e83b5fcc9f192df1bd | 15,914 | coil | Apache License 2.0 |
stripe/src/main/java/com/stripe/android/CustomerSessionEphemeralKeyManagerListener.kt | swdreams | 220,836,994 | false | null | package com.stripe.android
import java.util.HashMap
import java.util.concurrent.ThreadPoolExecutor
internal class CustomerSessionEphemeralKeyManagerListener(
private val runnableFactory: CustomerSessionRunnableFactory,
private val executor: ThreadPoolExecutor,
private val listeners: HashMap<String, CustomerSession.RetrievalListener>,
private val productUsage: CustomerSessionProductUsage
) : EphemeralKeyManager.KeyManagerListener<CustomerEphemeralKey> {
override fun onKeyUpdate(
ephemeralKey: CustomerEphemeralKey,
operationId: String,
action: String?,
arguments: Map<String, Any>?
) {
val runnable =
runnableFactory.create(ephemeralKey, operationId, action, arguments)
runnable?.let {
executor.execute(it)
if (action != null) {
productUsage.reset()
}
}
}
override fun onKeyError(
operationId: String,
errorCode: Int,
errorMessage: String
) {
listeners.remove(operationId)?.onError(errorCode, errorMessage, null)
}
}
| 0 | null | 1 | 2 | 413c85d6213d894510cc78684287783e36eeb53b | 1,117 | stripe-android | MIT License |
core/src/main/java/com/dicoding/dummyfilmapp/core/data/source/remote/response/tvshow/TvShowListResponse.kt | r3dz0n3-plysafe | 391,220,918 | false | null | package com.dicoding.dummyfilmapp.core.data.source.remote.response.tvshow
import com.google.gson.annotations.SerializedName
data class TvShowListResponse(
@SerializedName("results")
val results: List<TvShowResponse>
) | 0 | Kotlin | 0 | 0 | e60dc3657296f4e1e8d705d1543f110dc644e27f | 227 | Sub2-Expert-DummyFilmApp | The Unlicense |
src/main/kotlin/dev/bbuck/dragonconsole/ui/InputController.kt | bbuck | 4,627,209 | false | null | package dev.bbuck.dragonconsole.ui
import dev.bbuck.dragonconsole.text.InputString
import dev.bbuck.dragonconsole.text.StoredInput
import java.awt.Toolkit
import javax.swing.JOptionPane
import javax.swing.JOptionPane.showMessageDialog
import javax.swing.JTextPane
import javax.swing.text.AbstractDocument
import javax.swing.text.AttributeSet
import javax.swing.text.DocumentFilter
const val BYPASS = "<DCb />-"
class InputController(var inputAttributeSet: AttributeSet?) : DocumentFilter() {
private var inputRangeStart = 0
var rangeEnd = 0
var protected = false
val inputString = InputString("")
var isReceivingInput = false
var consoleTextPane: JTextPane? = null
var protectedChar = "*"
var bypassRemove = false
var ignoreInput = false
var stored: StoredInput? = null
var consoleInputMethod = true
fun installConsole(textPane: JTextPane) {
consoleTextPane = textPane
}
fun isProtected(): Boolean = protected
fun getBypassPrefix(): String = BYPASS
fun reset() {
inputRangeStart = -1
rangeEnd = 0
protected = false
inputString.clear()
isReceivingInput = false
}
public fun setRangeStart(value: Int) {
if (!isReceivingInput) {
return
}
inputRangeStart = value
if (rangeEnd > 0) {
rangeEnd += value
}
}
public fun getRangeStart() = inputRangeStart
fun setInput(newInput: String) {
if (!isReceivingInput || !isInfiniteInput()) {
return
}
val styledDoc = consoleTextPane?.getStyledDocument()
if (styledDoc == null) {
return
}
val docLength = styledDoc.length
bypassRemove = true
styledDoc.remove(inputRangeStart, docLength - inputRangeStart)
inputString.set(newInput)
val prefix =
if (consoleInputMethod) {
BYPASS
} else {
""
}
val newString =
if (protected) {
getProtectedString(newInput.length)
} else {
newInput
}
styledDoc.insertString(inputRangeStart, "$prefix$newString", inputAttributeSet)
}
fun getInputRangeEnd() = rangeEnd
fun isInfiniteInput(): Boolean = rangeEnd == -1
fun setInputStyle(inputCode: String): Boolean {
inputRangeStart = -1
rangeEnd = 0
protected = false
inputString.clear()
isReceivingInput = true
if (inputCode == "%i;") {
rangeEnd = -1
return false
}
var inputStyle = inputCode.substring(2, inputCode.length - 1)
if (inputStyle.isEmpty()) {
rangeEnd = -1
return false
}
if (inputStyle.last() == '+' || inputStyle.last() == '-') {
protected = inputStyle.last() == '+'
inputStyle = inputStyle.substring(0, inputStyle.length - 1)
}
if (inputStyle.length == 0) {
rangeEnd = -1
return false
}
rangeEnd = inputStyle.toInt()
inputString.set(getInputRangeString())
return true
}
fun getInputRangeString(): String {
if (!isReceivingInput || rangeEnd <= 0) {
return ""
}
val start =
if (inputRangeStart > 0) {
inputRangeStart
} else {
0
}
val numSpaces = rangeEnd - start
return " ".repeat(numSpaces)
}
fun getInputRangeStart(): Int =
if (isReceivingInput) {
inputRangeStart
} else {
-1
}
fun clearText() {
reset()
bypassRemove = true
val styledDoc = consoleTextPane?.getStyledDocument()
if (styledDoc == null) {
return
}
styledDoc.remove(0, styledDoc.length)
}
fun setBasicInput(startPosition: Int) {
inputRangeStart = startPosition
rangeEnd = -1
protected = false
inputString.clear()
isReceivingInput = true
}
fun setProtectedChar(protectedChar: Char) {
this.protectedChar = protectedChar.toString()
}
fun getInput(): String {
isReceivingInput = false
return inputString.get().trim()
}
override fun insertString(
filterBypass: FilterBypass,
offset: Int,
stringValue: String,
attributeSet: AttributeSet
) {
when {
stringValue.startsWith(BYPASS) -> {
val insertable = stringValue.substring(BYPASS.length)
filterBypass.insertString(offset, insertable, attributeSet)
}
(isReceivingInput && isInfiniteInput() && offset >= inputRangeStart) -> {
val insertable =
if (protected) {
getProtectedString(stringValue.length)
} else {
stringValue
}
filterBypass.insertString(offset, insertable, inputAttributeSet)
inputString.insert(offset - inputRangeStart, insertable)
}
else -> Toolkit.getDefaultToolkit().beep()
}
}
override fun replace(
filterBypass: FilterBypass,
offset: Int,
length: Int,
stringValue: String,
attributeSet: AttributeSet
) {
if (stringValue.startsWith(BYPASS)) {
val withoutBypass = stringValue.substring(BYPASS.length)
val replaceString =
if (protected) {
restoreProtectedString(withoutBypass)
} else {
withoutBypass
}
filterBypass.replace(offset, length, replaceString, attributeSet)
return
}
if (ignoreInput) {
return
}
if (!isReceivingInput || inputRangeStart <= 0 || offset < inputRangeStart) {
Toolkit.getDefaultToolkit().beep()
return
}
if (isInfiniteInput()) {
if (protected) {
filterBypass.replace(offset, length, protectedChar, inputAttributeSet)
} else {
filterBypass.replace(offset, length, stringValue, inputAttributeSet)
}
inputString.replace((offset - inputRangeStart), length, stringValue)
return
}
if ((offset + 1) <= rangeEnd) {
val inserted = inputString.rangeInsert((offset - inputRangeStart), stringValue)
if (inserted) {
val replaceString =
if (protected) {
protectedChar
} else {
stringValue
}
filterBypass.replace(offset, length, replaceString, inputAttributeSet)
if (inputString.endIsEmpty()) {
filterBypass.remove(rangeEnd - 1, 1)
} else {
filterBypass.remove(rangeEnd, 1)
}
return
}
}
Toolkit.getDefaultToolkit().beep()
}
override fun remove(filterBypass: FilterBypass, offset: Int, length: Int) {
if (ignoreInput) {
return
}
if (bypassRemove) {
bypassRemove = false
filterBypass.remove(offset, length)
return
}
if (!isReceivingInput || inputRangeStart <= 0 || offset < inputRangeStart) {
Toolkit.getDefaultToolkit().beep()
return
}
if (isInfiniteInput()) {
filterBypass.remove(offset, length)
val start = offset - inputRangeStart
if (start < inputString.length()) {
inputString.remove(start, length)
}
return
}
filterBypass.remove(offset, length)
filterBypass.insertString((rangeEnd - 1), " ", inputAttributeSet)
if (consoleTextPane?.caretPosition == rangeEnd) {
consoleTextPane?.caretPosition = rangeEnd - 1
}
inputString.rangeRemove((offset - inputRangeStart), length)
}
public fun hasStoredInput(): Boolean = stored != null
public fun storeInput() {
stored =
StoredInput(
isInfiniteInput(),
protected,
(rangeEnd - inputRangeStart),
InputString(inputString.get())
)
reset()
}
public fun restoreInput(): Boolean {
val storedInput = stored
if (storedInput == null || !isReceivingInput) {
stored = null
return false
}
if (!storedInput.matches(isInfiniteInput(), protected, (rangeEnd - inputRangeStart))) {
stored = null
return false
}
inputString.set(storedInput.input.get())
val end =
if (isInfiniteInput()) {
0
} else {
rangeEnd - inputRangeStart
}
try {
val replaceString =
if (consoleInputMethod) {
BYPASS + inputString.get()
} else {
inputString.get()
}
val document = consoleTextPane?.styledDocument as AbstractDocument
document.replace(inputRangeStart, end, replaceString, inputAttributeSet)
} catch (exc: Exception) {
showMessageDialog(
null,
"Error #0013\nFailed to restore the Input!\n${exc.message}",
"Error Caught",
JOptionPane.ERROR_MESSAGE
)
}
stored = null
return true
}
private fun getProtectedString(length: Int): String = protectedChar.repeat(length)
private fun restoreProtectedString(original: String): String =
protectedChar.repeat(original.length)
}
| 6 | Kotlin | 19 | 59 | aa68a02b85c095c22565c5322368af880f6ff2b4 | 10,342 | DragonConsole | Apache License 2.0 |
mobile/src/main/java/com/siliconlabs/bledemo/features/demo/wifi_commissioning/activities/WifiCommissioningActivity.kt | SiliconLabs | 85,345,875 | false | null | package com.siliconlabs.bledemo.features.demo.wifi_commissioning.activities
import android.app.AlertDialog
import android.app.ProgressDialog
import android.bluetooth.*
import android.content.*
import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.recyclerview.widget.LinearLayoutManager
import com.siliconlabs.bledemo.bluetooth.ble.GattCharacteristic
import com.siliconlabs.bledemo.bluetooth.ble.GattService
import com.siliconlabs.bledemo.bluetooth.ble.TimeoutGattCallback
import com.siliconlabs.bledemo.R
import com.siliconlabs.bledemo.base.activities.BaseDemoActivity
import com.siliconlabs.bledemo.databinding.ActivityWifiCommissioningBinding
import com.siliconlabs.bledemo.utils.Converters
import com.siliconlabs.bledemo.features.demo.wifi_commissioning.adapters.AccessPointsAdapter
import com.siliconlabs.bledemo.features.demo.wifi_commissioning.models.AccessPoint
import com.siliconlabs.bledemo.features.demo.wifi_commissioning.models.BoardCommand
import com.siliconlabs.bledemo.features.demo.wifi_commissioning.models.SecurityMode
import timber.log.Timber
import java.util.*
/**
* Created by harika on 18-04-2016.
*/
class WifiCommissioningActivity : BaseDemoActivity() {
private lateinit var _binding: ActivityWifiCommissioningBinding
private var progressDialog: ProgressDialog? = null
private var accessPointsAdapter: AccessPointsAdapter? = null
private val accessPoints = ArrayList<AccessPoint>()
private var isItemClicked = false
private var clickedAccessPoint: AccessPoint? = null
private var connectedAccessPoint: AccessPoint? = null
private var characteristicWrite: BluetoothGattCharacteristic? = null
private var characteristicRead: BluetoothGattCharacteristic? = null
private var characteristicNotification: BluetoothGattCharacteristic? = null
private val clientCharacteristicConfig = "00002902-0000-1000-8000-00805f9b34fb"
private val unprintableCharsRegex = Regex("[\\x00-\\x1F]")
private var sendCommand: BoardCommand.Send = BoardCommand.Send.UNKNOWN
private var readCommand: BoardCommand.Response = BoardCommand.Response.UNKNOWN
private val sleepForWrite: Long = 500
private val sleepForRead: Long = 500
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
_binding = ActivityWifiCommissioningBinding.inflate(layoutInflater)
setContentView(_binding.root)
setupRecyclerView()
setupUiListeners()
}
override fun onBluetoothServiceBound() {
service?.also {
it.registerGattCallback(mBluetoothGattCallback)
it.connectedGatt?.discoverServices()
}
showProgressDialog(getString(R.string.ble_detail_device_connection))
}
private fun setupRecyclerView() {
accessPointsAdapter = AccessPointsAdapter(accessPoints, object : AccessPointsAdapter.OnItemClickListener {
override fun onItemClick(itemView: View?, position: Int) {
onAccessPointClicked(position)
}
})
_binding.wifiAccessPtsList.apply {
adapter = accessPointsAdapter
layoutManager = LinearLayoutManager(context)
}
}
private fun setupUiListeners() {
_binding.disconnectBtn.setOnClickListener { showDisconnectionDialog() }
}
private fun showProgressDialog(message: String) {
runOnUiThread {
progressDialog?.dismiss()
progressDialog = ProgressDialog.show(this, getString(R.string.empty_description), message)
}
}
private fun dismissProgressDialog() {
runOnUiThread { progressDialog?.dismiss() }
}
override fun onBackPressed() {
service?.clearConnectedGatt()
super.onBackPressed()
}
private fun onAccessPointClicked(position: Int) {
isItemClicked = true
clickedAccessPoint = accessPointsAdapter?.getItem(position)
showProgressDialog(getString(R.string.check_for_status))
writeCommand(BoardCommand.Send.CHECK_CONNECTION)
}
private fun showToastOnUi(message: String) {
runOnUiThread { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() }
}
fun onAccessPointScanned(accessPoint: AccessPoint) {
dismissProgressDialog()
accessPoints.add(accessPoint)
runOnUiThread { accessPointsAdapter?.notifyDataSetChanged() }
}
fun onAccessPointConnection(isSuccessful: Boolean) {
dismissProgressDialog()
if (isSuccessful) {
showToastOnUi(getString(R.string.ap_connect))
connectedAccessPoint = clickedAccessPoint
connectedAccessPoint?.status = true
runOnUiThread { accessPointsAdapter?.notifyDataSetChanged() }
} else {
showToastOnUi(getString(R.string.ap_connect_fail))
}
}
fun onAccessPointDisconnection(isSuccessful: Boolean) {
dismissProgressDialog()
if (isSuccessful) {
connectedAccessPoint = null
showToastOnUi(getString(R.string.ap_disconnect_success))
scanForAccessPoints()
toggleMainView(isAccessPointConnected = false)
} else {
showToastOnUi(getString(R.string.ap_disconnect_fail))
}
}
fun isAccessPointConnected(isConnected: Boolean) {
dismissProgressDialog()
if (isConnected) {
if (isItemClicked) { /* Board already connected when clicking on item */
showDisconnectionDialog()
} else { /* Board connected when entering the app */
toggleMainView(isAccessPointConnected = true)
}
} else {
clickedAccessPoint?.let { /* No board connected when clicking on item */
if (it.securityMode != SecurityMode.OPEN) showPasswordDialog()
else {
it.password = getString(R.string.empty_description)
writeCommand(BoardCommand.Send.SSID, it.name)
showProgressDialog(getString(R.string.config_AP))
}
} ?: scanForAccessPoints() /* No board connected when entering the app */
}
}
fun onFirmwareVersionReceived(firmwareVersion: String) {
runOnUiThread { _binding.firmwareVersionTv.text = firmwareVersion }
writeCommand(BoardCommand.Send.CHECK_CONNECTION)
}
private fun toggleMainView(isAccessPointConnected: Boolean) {
runOnUiThread {
_binding.apConnectedLayout.visibility = if (isAccessPointConnected) View.VISIBLE else View.GONE
_binding.wifiAccessPtsList.visibility = if (isAccessPointConnected) View.GONE else View.VISIBLE
}
}
private fun showDisconnectionDialog() {
val dialogMessage =
if (connectedAccessPoint?.name == clickedAccessPoint?.name) getString(R.string.disconnect_title)
else getString(R.string.another_ap_connected)
AlertDialog.Builder(this).apply {
setCancelable(false)
setMessage(dialogMessage)
setPositiveButton(getString(R.string.yes)) { dialog: DialogInterface, _: Int ->
showProgressDialog(getString(R.string.disconnect_ap))
writeCommand(BoardCommand.Send.DISCONNECTION)
dialog.cancel()
}
setNegativeButton(getString(R.string.no)) { dialog: DialogInterface, _: Int ->
isItemClicked = false
dialog.cancel()
}
runOnUiThread {
create()
show()
}
}
}
private fun showPasswordDialog() {
val dialogView = layoutInflater.inflate(R.layout.secured_ap_connect_dialog, null)
val password = dialogView.findViewById<EditText>(R.id.password_et)
AlertDialog.Builder(this).apply {
setView(dialogView)
setTitle(clickedAccessPoint?.name)
setPositiveButton(getString(R.string.connect_btn_txt)) { dialog: DialogInterface?, _: Int ->
if (password.text.toString().isNotEmpty()) {
dialog?.dismiss()
showProgressDialog(getString(R.string.config_AP))
clickedAccessPoint?.let {
it.password = password.text.toString()
writeCommand(BoardCommand.Send.SSID, it.name)
}
} else {
showToastOnUi(getString(R.string.invalid_password))
dialog?.dismiss()
}
}
setNegativeButton(getString(R.string.button_cancel)) { dialog: DialogInterface?, _: Int ->
dialog?.dismiss()
}
runOnUiThread {
create()
show()
}
}
}
private fun scanForAccessPoints() {
clickedAccessPoint = null
accessPoints.clear()
runOnUiThread { accessPointsAdapter?.notifyDataSetChanged() }
showProgressDialog(getString(R.string.scanning_for_access_points))
writeCommand(BoardCommand.Send.SCAN)
}
private val mBluetoothGattCallback: TimeoutGattCallback = object : TimeoutGattCallback() {
override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
Timber.d("onConnectionStateChange; status = $status, newState = $newState")
if (newState == BluetoothProfile.STATE_DISCONNECTED) {
onDeviceDisconnected()
}
}
override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
Timber.d("onServicesDiscovered; status = $status")
gatt.getService(GattService.WifiCommissioningService.number)?.let {
characteristicWrite = it.getCharacteristic(GattCharacteristic.WifiCommissioningWrite.uuid)
characteristicRead = it.getCharacteristic(GattCharacteristic.WifiCommissioningRead.uuid)
characteristicNotification = it.getCharacteristic(GattCharacteristic.WifiCommissioningNotify.uuid)
}
if (gatt.setCharacteristicNotification(characteristicNotification, true)) {
Timber.d("Notifications enabled for ${characteristicNotification?.uuid}")
characteristicNotification?.getDescriptor(UUID.fromString(clientCharacteristicConfig))?.let {
it.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
gatt.writeDescriptor(it)
}
}
writeCommand(BoardCommand.Send.GET_FIRMWARE_VERSION)
}
override fun onCharacteristicWrite(gatt: BluetoothGatt,
characteristic: BluetoothGattCharacteristic,
status: Int) {
Timber.d("onCharacteristicWrite; characteristic = ${characteristic.uuid}, sendCommand = $sendCommand, status = $status")
Timber.d("Raw data = ${Arrays.toString(characteristic.value)}")
if (status == BluetoothGatt.GATT_SUCCESS) {
when (sendCommand) {
BoardCommand.Send.SSID -> writeCommand(
BoardCommand.Send.SECURITY_TYPE, clickedAccessPoint?.securityMode?.value?.toString()!!)
BoardCommand.Send.DISCONNECTION -> readOperation()
BoardCommand.Send.SECURITY_TYPE -> {
if (clickedAccessPoint?.password!!.isNotEmpty()) {
writeCommand(BoardCommand.Send.PASSWORD, clickedAccessPoint?.password!!)
} else {
sendCommand = BoardCommand.Send.SSID
readOperation()
}
}
BoardCommand.Send.PASSWORD -> {
sendCommand = BoardCommand.Send.SSID
readOperation()
}
BoardCommand.Send.CHECK_CONNECTION -> {
sendCommand = BoardCommand.Send.CHECK_CONNECTION
readOperation()
}
BoardCommand.Send.GET_FIRMWARE_VERSION -> {
sendCommand = BoardCommand.Send.GET_FIRMWARE_VERSION
readOperation()
}
else -> { }
}
}
}
override fun onCharacteristicRead(gatt: BluetoothGatt,
characteristic: BluetoothGattCharacteristic,
status: Int) {
Timber.d("onCharacteristicRead; characteristic = ${characteristic.uuid}, readCommand = $readCommand, status = $status")
Timber.d("Raw data = ${Arrays.toString(characteristic.value)}")
if (status == BluetoothGatt.GATT_SUCCESS) {
readCommand = BoardCommand.Response.fromInt(
characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0)
)
val statusBit = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 1)
if (readCommand.value != sendCommand.value) {
readOperation()
} else {
when (readCommand) {
BoardCommand.Response.CONNECTION -> {
if (statusBit == 1) {
clickedAccessPoint?.macAddress = convertMacAddressToString(characteristic.value.copyOfRange(3, 9))
clickedAccessPoint?.ipAddress = convertIpAddressToString(characteristic.value.copyOfRange(10, 14))
onAccessPointConnection(true)
} else {
onAccessPointConnection(false)
}
}
BoardCommand.Response.DISCONNECTION -> onAccessPointDisconnection(statusBit == 1)
BoardCommand.Response.CHECK_CONNECTION -> isAccessPointConnected(statusBit == 1)
BoardCommand.Response.FIRMWARE_VERSION -> {
if (statusBit > 0) {
val rawString = characteristic.getStringValue(2)
onFirmwareVersionReceived(rawString.replace(unprintableCharsRegex, ""))
}
}
BoardCommand.Response.UNKNOWN -> {
if (sendCommand != BoardCommand.Send.SSID) readOperation()
}
}
}
}
}
override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) {
Timber.d("onCharacteristicChanged; characteristic = ${characteristic.uuid}")
Timber.d("Raw data = ${Arrays.toString(characteristic.value)}")
if (characteristic.uuid == GattCharacteristic.WifiCommissioningNotify.uuid) {
/* Scanned access point info. */
val rawName = characteristic.getStringValue(2)
val rawSecurityMode = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0)
Timber.d("Raw access point name = $rawName")
onAccessPointScanned(AccessPoint(
name = rawName.replace(unprintableCharsRegex, ""),
securityMode = SecurityMode.fromInt(rawSecurityMode)
))
}
}
}
private fun writeCommand(command: BoardCommand.Send) {
sendCommand = command
writeUntilSuccess(sendCommand.value.toString())
}
private fun writeCommand(command: BoardCommand.Send, additionalData: String) {
sendCommand = command
val stringToWrite = StringBuilder().apply {
append(sendCommand.value)
if (additionalData.length < 10) append('0')
append(additionalData.length)
append(additionalData)
}.toString()
writeUntilSuccess(stringToWrite)
}
private fun writeUntilSuccess(dataToWrite: String) {
Thread {
var writeStatus = false
while (!writeStatus) {
writeStatus = writeToCharacteristic(service?.connectedGatt, characteristicWrite, dataToWrite)
Thread.sleep(sleepForWrite)
}
Timber.d("Command $sendCommand written successfully")
}.start()
}
private fun writeToCharacteristic(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?, data: String): Boolean {
return if (gatt != null && characteristic != null) {
Timber.d("Data to write = $data")
if (data.length > 100) {
Timber.d("Attempt to write to characteristic with more then 64 bytes")
return false
}
characteristic.setValue(data)
gatt.writeCharacteristic(characteristic)
} else {
Timber.d("Fail to write: null references")
false
}
}
private fun readOperation() {
Thread {
service?.connectedGatt?.readCharacteristic(characteristicRead)
Thread.sleep(sleepForRead)
}.start()
}
private fun convertMacAddressToString(rawData: ByteArray) : String {
return StringBuilder().apply {
rawData.forEachIndexed { index, byte ->
val hexValue = Integer.toHexString(Converters.getIntFromTwosComplement(byte))
append(hexValue)
if (hexValue.length == 1) insert(length - 1, '0')
if (index != rawData.size - 1) append(':')
}
}.toString()
}
private fun convertIpAddressToString(rawData: ByteArray) : String {
return StringBuilder().apply {
rawData.forEachIndexed { index, byte ->
append(Converters.getIntFromTwosComplement(byte))
if (index != rawData.size - 1) append('.')
}
}.toString()
}
} | 6 | null | 70 | 96 | 501d1a7554593db61325f5ac3aa0865eb616d00b | 18,281 | EFRConnect-android | Apache License 2.0 |
model/src/main/kotlin/ScanSummary.kt | oss-review-toolkit | 107,540,288 | false | null | /*
* Copyright (C) 2017 The ORT Project Authors (see <https://github.com/oss-review-toolkit/ort/blob/main/NOTICE>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
package org.ossreviewtoolkit.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import java.time.Instant
import org.ossreviewtoolkit.model.config.LicenseFilePatterns
import org.ossreviewtoolkit.model.utils.CopyrightFindingSortedSetConverter
import org.ossreviewtoolkit.model.utils.LicenseFindingSortedSetConverter
import org.ossreviewtoolkit.model.utils.RootLicenseMatcher
import org.ossreviewtoolkit.model.utils.SnippetFindingSortedSetConverter
import org.ossreviewtoolkit.utils.common.FileMatcher
import org.ossreviewtoolkit.utils.spdx.SpdxExpression
/**
* A short summary of the scan results.
*/
@JsonIgnoreProperties("file_count")
data class ScanSummary(
/**
* The time when the scan started.
*/
val startTime: Instant,
/**
* The time when the scan finished.
*/
val endTime: Instant,
/**
* The [SPDX package verification code](https://spdx.dev/spdx_specification_2_0_html#h.2p2csry), calculated from all
* files in the package. Note that if the scanner is configured to ignore certain files they will still be included
* in the calculation of this code.
*/
val packageVerificationCode: String,
/**
* The detected license findings.
*/
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonProperty("licenses")
@JsonSerialize(converter = LicenseFindingSortedSetConverter::class)
val licenseFindings: Set<LicenseFinding> = emptySet(),
/**
* The detected copyright findings.
*/
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonProperty("copyrights")
@JsonSerialize(converter = CopyrightFindingSortedSetConverter::class)
val copyrightFindings: Set<CopyrightFinding> = emptySet(),
/**
* The detected snippet findings.
*/
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonProperty("snippets")
@JsonSerialize(converter = SnippetFindingSortedSetConverter::class)
val snippetFindings: Set<SnippetFinding> = emptySet(),
/**
* The list of issues that occurred during the scan. This property is not serialized if the list is empty to reduce
* the size of the result file. If there are no issues at all, [ScannerRun.hasIssues] already contains that
* information.
*/
@JsonInclude(JsonInclude.Include.NON_EMPTY)
val issues: List<Issue> = emptyList()
) {
companion object {
/**
* A constant for a [ScannerRun] where all properties are empty.
*/
@JvmField
val EMPTY = ScanSummary(
startTime = Instant.EPOCH,
endTime = Instant.EPOCH,
packageVerificationCode = ""
)
}
@get:JsonIgnore
val licenses: Set<SpdxExpression> = licenseFindings.mapTo(mutableSetOf()) { it.license }
/**
* Filter all detected licenses and copyrights from this [ScanSummary] which are underneath [path]. Findings which
* [RootLicenseMatcher] assigns as root license files for [path] are also kept.
*/
fun filterByPath(path: String): ScanSummary {
if (path.isBlank()) return this
val rootLicenseMatcher = RootLicenseMatcher(LicenseFilePatterns.getInstance())
val applicableLicenseFiles = rootLicenseMatcher.getApplicableRootLicenseFindingsForDirectories(
licenseFindings = licenseFindings,
directories = listOf(path)
).values.flatten().mapTo(mutableSetOf()) { it.location.path }
fun TextLocation.matchesPath() = this.path.startsWith("$path/") || this.path in applicableLicenseFiles
return copy(
licenseFindings = licenseFindings.filterTo(mutableSetOf()) { it.location.matchesPath() },
copyrightFindings = copyrightFindings.filterTo(mutableSetOf()) { it.location.matchesPath() }
)
}
/**
* Return a [ScanSummary] which contains only findings whose location / path is not matched by any glob expression
* in [ignorePatterns].
*/
fun filterByIgnorePatterns(ignorePatterns: Collection<String>): ScanSummary {
val matcher = FileMatcher(ignorePatterns)
return copy(
licenseFindings = licenseFindings.filterTo(mutableSetOf()) { !matcher.matches(it.location.path) },
copyrightFindings = copyrightFindings.filterTo(mutableSetOf()) { !matcher.matches(it.location.path) }
)
}
}
| 318 | Kotlin | 243 | 1,172 | 39ce1b7ddf181a7a826b2903e1f90cd03aee8e8c | 5,315 | ort | Apache License 2.0 |
src/main/kotlin/io/github/cianciustyles/Utils.kt | CianciuStyles | 288,737,271 | false | null | package io.github.cianciustyles
import biz.source_code.utils.RawConsoleInput
object Utils {
fun extendSign(x: Int, bitCount: Int): Short {
val num = if (x shr bitCount - 1 and 0b1 == 1) {
(0xFFFF shl bitCount) or x
} else {
x
}
return num.toShort()
}
fun readCharacter(wait: Boolean): Short =
when (val characterRead = RawConsoleInput.read(wait)) {
13 -> 10
else -> characterRead.toShort()
}
}
| 1 | Kotlin | 0 | 1 | e2fcbc7b8033a2c9891ec41cd684cf079f45276d | 506 | lc3-vm-kotlin | The Unlicense |
app/src/main/java/com/example/wishlistapp/MainActivity.kt | clearFrost | 608,639,871 | false | null | package com.example.wishlistapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class MainActivity : AppCompatActivity() {
lateinit var wishlists: List<Wishlist>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val itemInput = findViewById<EditText>(R.id.itemNameEt)
val priceInput = findViewById<EditText>(R.id.priceEt)
val urlInput = findViewById<EditText>(R.id.urlEt)
val submitButton = findViewById<Button>(R.id.submitBtn)
val wishlistsRv = findViewById<RecyclerView>(R.id.wishlistRv)
val adapter = WishlistAdapter(listOf(Wishlist(itemName = "", itemPrice = "", websiteURL = "")))
wishlistsRv.adapter = adapter
wishlistsRv.layoutManager = LinearLayoutManager(this)
submitButton.setOnClickListener {
val newWish = Wishlist(itemInput.text.toString(), priceInput.text.toString(), urlInput.text.toString())
adapter.addToWishlist(adapter.wishlists + newWish)
adapter.notifyDataSetChanged()
Log.d("MyDebugTag",itemInput.text.toString())
itemInput.text.clear()
priceInput.text.clear()
urlInput.text.clear()
}
}
} | 1 | Kotlin | 0 | 0 | 3051cd20c639fa373833eb53166fddce816ccf2d | 1,433 | WishlistApp | Apache License 2.0 |
app/src/main/java/com/kylecorry/trail_sense/tools/beacons/ui/list/BeaconListFragment.kt | kylecorry31 | 215,154,276 | false | null | package com.kylecorry.trail_sense.tools.beacons.ui.list
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import com.kylecorry.andromeda.alerts.Alerts
import com.kylecorry.andromeda.alerts.toast
import com.kylecorry.andromeda.core.coroutines.BackgroundMinimumState
import com.kylecorry.andromeda.core.coroutines.onIO
import com.kylecorry.andromeda.core.coroutines.onMain
import com.kylecorry.andromeda.core.filterIndices
import com.kylecorry.andromeda.core.system.GeoUri
import com.kylecorry.andromeda.core.tryOrNothing
import com.kylecorry.andromeda.fragments.BoundFragment
import com.kylecorry.andromeda.fragments.inBackground
import com.kylecorry.andromeda.gpx.GPXData
import com.kylecorry.andromeda.pickers.Pickers
import com.kylecorry.trail_sense.R
import com.kylecorry.trail_sense.databinding.FragmentBeaconListBinding
import com.kylecorry.trail_sense.shared.CustomUiUtils
import com.kylecorry.trail_sense.shared.FormatService
import com.kylecorry.trail_sense.shared.UserPreferences
import com.kylecorry.trail_sense.shared.extensions.onBackPressed
import com.kylecorry.trail_sense.shared.from
import com.kylecorry.trail_sense.shared.grouping.lists.GroupListManager
import com.kylecorry.trail_sense.shared.grouping.lists.bind
import com.kylecorry.trail_sense.shared.io.IOFactory
import com.kylecorry.trail_sense.shared.permissions.alertNoCameraPermission
import com.kylecorry.trail_sense.shared.permissions.requestCamera
import com.kylecorry.trail_sense.shared.sensors.SensorService
import com.kylecorry.trail_sense.tools.beacons.domain.Beacon
import com.kylecorry.trail_sense.tools.beacons.domain.BeaconGroup
import com.kylecorry.trail_sense.tools.beacons.domain.IBeacon
import com.kylecorry.trail_sense.tools.beacons.infrastructure.commands.CreateBeaconGroupCommand
import com.kylecorry.trail_sense.tools.beacons.infrastructure.commands.DeleteBeaconCommand
import com.kylecorry.trail_sense.tools.beacons.infrastructure.commands.MoveBeaconCommand
import com.kylecorry.trail_sense.tools.beacons.infrastructure.commands.MoveBeaconGroupCommand
import com.kylecorry.trail_sense.tools.beacons.infrastructure.commands.RenameBeaconGroupCommand
import com.kylecorry.trail_sense.tools.beacons.infrastructure.commands.cell.NavigateToNearestCellSignal
import com.kylecorry.trail_sense.tools.beacons.infrastructure.export.BeaconGpxConverter
import com.kylecorry.trail_sense.tools.beacons.infrastructure.export.BeaconGpxImporter
import com.kylecorry.trail_sense.tools.beacons.infrastructure.loading.BeaconLoader
import com.kylecorry.trail_sense.tools.beacons.infrastructure.persistence.BeaconService
import com.kylecorry.trail_sense.tools.beacons.infrastructure.share.BeaconSender
import com.kylecorry.trail_sense.tools.beacons.infrastructure.sort.BeaconSortMethod
import com.kylecorry.trail_sense.tools.beacons.infrastructure.sort.ClosestBeaconSort
import com.kylecorry.trail_sense.tools.beacons.infrastructure.sort.MostRecentBeaconSort
import com.kylecorry.trail_sense.tools.beacons.infrastructure.sort.NameBeaconSort
import com.kylecorry.trail_sense.tools.navigation.infrastructure.Navigator
import com.kylecorry.trail_sense.tools.qr.infrastructure.BeaconQREncoder
import java.time.Instant
class BeaconListFragment : BoundFragment<FragmentBeaconListBinding>() {
private val gps by lazy { sensorService.getGPS() }
private val prefs by lazy { UserPreferences(requireContext()) }
private lateinit var navController: NavController
private val sensorService by lazy { SensorService(requireContext()) }
private val formatService by lazy { FormatService.getInstance(requireContext()) }
private val beaconService by lazy { BeaconService(requireContext()) }
private val beaconLoader by lazy { BeaconLoader(beaconService, prefs.navigation) }
private var sort = BeaconSortMethod.Closest
private val listMapper by lazy {
IBeaconListItemMapper(
requireContext(),
gps,
this::handleBeaconAction,
this::handleBeaconGroupAction
)
}
private var initialLocation: GeoUri? = null
private val gpxService by lazy {
IOFactory().createGpxService(this)
}
private lateinit var manager: GroupListManager<IBeacon>
private var lastRoot: IBeacon? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (requireArguments().containsKey("initial_location")) {
initialLocation = requireArguments().getParcelable("initial_location")
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
navController = findNavController()
sort = prefs.navigation.beaconSort
binding.beaconRecycler.emptyView = binding.beaconEmptyText
manager = GroupListManager(
lifecycleScope,
beaconLoader,
lastRoot,
this::sortBeacons
)
manager.bind(binding.searchbox)
manager.bind(binding.beaconRecycler, binding.beaconTitle.title, listMapper) {
it?.name ?: getString(R.string.beacons)
}
initialLocation?.let {
initialLocation = null
createBeacon(initialLocation = it)
}
binding.beaconTitle.rightButton.setOnClickListener {
val defaultSort = prefs.navigation.beaconSort
Pickers.menu(
it, listOf(
getString(R.string.sort_by, getSortString(defaultSort)),
getString(R.string.export),
getString(R.string.navigate_to_nearest_cell_signal)
)
) { selected ->
when (selected) {
0 -> changeSort()
1 -> onExportBeacons()
2 -> navigateToNearestCellSignal()
}
true
}
}
binding.createMenu.setOverlay(binding.overlayMask)
binding.createMenu.setOnMenuItemClickListener {
when (it.itemId) {
R.id.action_import_qr_beacon -> {
requestCamera { hasPermission ->
if (hasPermission) {
importBeaconFromQR()
} else {
alertNoCameraPermission()
}
}
setCreateMenuVisibility(false)
}
R.id.action_import_gpx_beacons -> {
importBeacons()
setCreateMenuVisibility(false)
}
R.id.action_create_beacon_group -> {
val command =
CreateBeaconGroupCommand(requireContext(), lifecycleScope, beaconService) {
refresh()
}
command.execute(manager.root?.id)
setCreateMenuVisibility(false)
}
R.id.action_create_beacon -> {
setCreateMenuVisibility(false)
createBeacon(group = manager.root?.id)
}
}
true
}
binding.createMenu.setOnHideListener {
binding.createBtn.setImageResource(R.drawable.ic_add)
}
binding.createMenu.setOnShowListener {
binding.createBtn.setImageResource(R.drawable.ic_cancel)
}
binding.createBtn.setOnClickListener {
setCreateMenuVisibility(!isCreateMenuOpen())
}
onBackPressed {
when {
isCreateMenuOpen() -> {
setCreateMenuVisibility(false)
}
else -> {
if (!manager.up()) {
remove()
navController.navigateUp()
}
}
}
}
}
private suspend fun sortBeacons(beacons: List<IBeacon>): List<IBeacon> {
val method = when (sort) {
BeaconSortMethod.MostRecent -> MostRecentBeaconSort(beaconService)
BeaconSortMethod.Closest -> ClosestBeaconSort(beaconService, gps::location)
BeaconSortMethod.Name -> NameBeaconSort()
}
return method.sort(beacons)
}
private fun setCreateMenuVisibility(isShowing: Boolean) {
if (isShowing) {
binding.createMenu.show()
} else {
binding.createMenu.hide()
}
}
private fun isCreateMenuOpen(): Boolean {
return binding.createMenu.isVisible
}
private fun onExportBeacons() {
inBackground {
val gpx = getExportGPX()
onMain {
Pickers.items(
requireContext(),
getString(R.string.export),
gpx.waypoints.map { it.name ?: formatService.formatLocation(it.coordinate) },
List(gpx.waypoints.size) { it },
) {
if (!it.isNullOrEmpty()) {
val selectedWaypoints = gpx.waypoints.filterIndices(it)
export(gpx.copy(waypoints = selectedWaypoints))
}
}
}
}
}
override fun onResume() {
super.onResume()
manager.refresh()
// Get a GPS reading
gps.start(this::onLocationUpdate)
}
override fun onPause() {
gps.stop(this::onLocationUpdate)
tryOrNothing {
lastRoot = manager.root
}
super.onPause()
}
private fun onLocationUpdate(): Boolean {
return false
}
private fun importBeaconFromQR() {
val encoder = BeaconQREncoder()
CustomUiUtils.scanQR(this, getString(R.string.beacon_qr_import_instructions)) {
if (it != null) {
val beacon = encoder.decode(it) ?: return@scanQR true
createBeacon(group = manager.root?.id, initialLocation = GeoUri.from(beacon))
}
false
}
}
private fun changeSort() {
val sortOptions = BeaconSortMethod.values()
Pickers.item(
requireContext(),
getString(R.string.sort),
sortOptions.map { getSortString(it) },
sortOptions.indexOf(prefs.navigation.beaconSort)
) { newSort ->
if (newSort != null) {
prefs.navigation.beaconSort = sortOptions[newSort]
sort = sortOptions[newSort]
onSortChanged()
}
}
}
private fun getSortString(sortMethod: BeaconSortMethod): String {
return when (sortMethod) {
BeaconSortMethod.MostRecent -> getString(R.string.most_recent)
BeaconSortMethod.Closest -> getString(R.string.closest)
BeaconSortMethod.Name -> getString(R.string.name)
}
}
private fun onSortChanged() {
manager.refresh(true)
}
private fun export(gpx: GPXData) {
inBackground(BackgroundMinimumState.Created) {
val exportFile = "trail-sense-${Instant.now().epochSecond}.gpx"
val success = gpxService.export(gpx, exportFile)
onMain {
if (success) {
toast(
resources.getQuantityString(
R.plurals.beacons_exported,
gpx.waypoints.size,
gpx.waypoints.size
)
)
} else {
toast(
getString(R.string.beacon_export_error)
)
}
}
}
}
private fun importBeacons() {
val importer = BeaconGpxImporter(requireContext())
inBackground(BackgroundMinimumState.Created) {
val gpx = gpxService.import()
val waypoints = gpx?.waypoints ?: emptyList()
onMain {
Pickers.items(
requireContext(),
getString(R.string.import_btn),
waypoints.map {
it.name ?: formatService.formatLocation(it.coordinate)
},
List(waypoints.size) { it }
) {
if (it != null) {
inBackground {
val gpxToImport =
GPXData(waypoints.filterIndices(it), emptyList(), emptyList())
val count = onIO {
importer.import(gpxToImport, manager.root?.id)
}
onMain {
Alerts.toast(
requireContext(),
resources.getQuantityString(
R.plurals.beacons_imported,
count,
count
)
)
refresh()
}
}
}
}
}
}
}
private suspend fun getExportGPX(): GPXData = onIO {
val all = beaconService.getBeacons(
manager.root?.id,
includeGroups = true,
maxDepth = null,
includeRoot = true
)
val groups = all.filterIsInstance<BeaconGroup>()
val beacons = all.filterIsInstance<Beacon>()
BeaconGpxConverter().toGPX(beacons, groups)
}
override fun generateBinding(
layoutInflater: LayoutInflater,
container: ViewGroup?
): FragmentBeaconListBinding {
return FragmentBeaconListBinding.inflate(layoutInflater, container, false)
}
private fun createBeacon(
group: Long? = null,
initialLocation: GeoUri? = null,
editingBeaconId: Long? = null
) {
val bundle = bundleOf()
group?.let { bundle.putLong("initial_group", it) }
initialLocation?.let { bundle.putParcelable("initial_location", it) }
editingBeaconId?.let { bundle.putLong("edit_beacon", it) }
navController.navigate(
R.id.action_beaconListFragment_to_placeBeaconFragment,
bundle
)
}
private fun refresh() {
manager.refresh()
}
private fun viewBeacon(id: Long) {
val bundle = bundleOf("beacon_id" to id)
navController.navigate(
R.id.action_beacon_list_to_beaconDetailsFragment,
bundle
)
}
private fun navigate(beacon: Beacon) {
val navigator = Navigator.getInstance(requireContext())
navigator.navigateTo(beacon)
navController.navigate(R.id.action_navigation)
}
private fun delete(beacon: Beacon) {
val command = DeleteBeaconCommand(
requireContext(),
lifecycleScope,
beaconService
) {
refresh()
}
command.execute(beacon)
}
private fun delete(group: BeaconGroup) {
Alerts.dialog(
requireContext(),
getString(R.string.delete),
getString(
R.string.delete_beacon_group_message,
group.name
),
) { cancelled ->
if (!cancelled) {
inBackground {
onIO {
beaconService.delete(group)
}
onMain {
refresh()
}
}
}
}
}
private fun move(beacon: Beacon) {
val command = MoveBeaconCommand(
requireContext(),
lifecycleScope,
beaconService
) {
refresh()
}
command.execute(beacon)
}
private fun move(group: BeaconGroup) {
val command =
MoveBeaconGroupCommand(requireContext(), lifecycleScope, beaconService) { refresh() }
command.execute(group)
}
private fun toggleVisibility(beacon: Beacon) {
inBackground {
val newBeacon = beacon.copy(visible = !beacon.visible)
onIO {
beaconService.add(newBeacon)
}
onMain {
refresh()
}
}
}
private fun rename(group: BeaconGroup) {
val command =
RenameBeaconGroupCommand(requireContext(), lifecycleScope, beaconService) { refresh() }
command.execute(group)
}
private fun navigateToNearestCellSignal() {
inBackground {
val command = NavigateToNearestCellSignal(requireContext())
if (command.execute()) {
onMain {
findNavController().navigate(R.id.action_navigation)
}
} else {
onMain {
toast(getString(R.string.no_recorded_cell_signal_nearby))
}
}
}
}
private fun handleBeaconGroupAction(group: BeaconGroup, action: BeaconGroupAction) {
when (action) {
BeaconGroupAction.Open -> {
manager.open(group.id)
}
BeaconGroupAction.Edit -> rename(group)
BeaconGroupAction.Delete -> delete(group)
BeaconGroupAction.Move -> move(group)
}
}
private fun handleBeaconAction(beacon: Beacon, action: BeaconAction) {
when (action) {
BeaconAction.View -> viewBeacon(beacon.id)
BeaconAction.Edit -> createBeacon(editingBeaconId = beacon.id)
BeaconAction.Navigate -> navigate(beacon)
BeaconAction.Delete -> delete(beacon)
BeaconAction.Move -> move(beacon)
BeaconAction.ToggleVisibility -> toggleVisibility(beacon)
BeaconAction.Share -> BeaconSender(this).send(beacon)
}
}
}
| 456 | null | 66 | 989 | 41176d17b498b2dcecbbe808fbe2ac638e90d104 | 18,447 | Trail-Sense | MIT License |
plugins/kotlin/base/facet/src/org/jetbrains/kotlin/idea/workspaceModel/KotlinModuleSettingsSerializer.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.workspaceModel
import com.intellij.openapi.extensions.ExtensionNotApplicableException
import com.intellij.platform.workspace.jps.entities.ModuleEntity
import com.intellij.platform.workspace.jps.serialization.impl.CustomFacetRelatedEntitySerializer
import com.intellij.platform.workspace.storage.EntitySource
import com.intellij.util.descriptors.ConfigFileItemSerializer
import org.jdom.Element
import org.jetbrains.jps.model.serialization.facet.FacetState
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.config.CompilerSettings
import org.jetbrains.kotlin.idea.facet.KotlinFacetType
import java.io.*
import java.util.*
class KotlinModuleSettingsSerializer : CustomFacetRelatedEntitySerializer<KotlinSettingsEntity>, ConfigFileItemSerializer {
init {
if (!KotlinFacetBridgeFactory.kotlinFacetBridgeEnabled) {
throw ExtensionNotApplicableException.create()
}
}
override val rootEntityType: Class<KotlinSettingsEntity>
get() = KotlinSettingsEntity::class.java
override val supportedFacetType: String
get() = KotlinFacetType.INSTANCE.stringId
override fun loadEntitiesFromFacetState(
moduleEntity: ModuleEntity,
facetState: FacetState,
evaluateEntitySource: (FacetState) -> EntitySource
) {
val entitySource = evaluateEntitySource(facetState)
val kotlinSettingsEntity = KotlinSettingsEntity(
facetState.name, moduleEntity.symbolicId,
emptyList(),
emptyList(),
true,
emptyList(),
emptyList(),
emptySet(),
"",
"",
emptyList(),
false,
"",
false,
emptyList(),
KotlinModuleKind.DEFAULT,
"",
"",
CompilerSettingsData("", "", "", true, "lib"),
"",
entitySource
) {
module = moduleEntity
} as KotlinSettingsEntity.Builder
val facetConfiguration = facetState.configuration
if (facetConfiguration == null) {
return
}
val kotlinFacetSettings = deserializeFacetSettings(facetConfiguration).also { it.updateMergedArguments() }
// Can be optimized by not setting default values
kotlinSettingsEntity.useProjectSettings = kotlinFacetSettings.useProjectSettings
kotlinSettingsEntity.implementedModuleNames = kotlinFacetSettings.implementedModuleNames.toMutableList()
kotlinSettingsEntity.dependsOnModuleNames = kotlinFacetSettings.dependsOnModuleNames.toMutableList()
kotlinSettingsEntity.additionalVisibleModuleNames = kotlinFacetSettings.additionalVisibleModuleNames.toMutableSet()
kotlinSettingsEntity.productionOutputPath = kotlinFacetSettings.productionOutputPath ?: ""
kotlinSettingsEntity.testOutputPath = kotlinFacetSettings.testOutputPath ?: ""
kotlinSettingsEntity.sourceSetNames = kotlinFacetSettings.sourceSetNames.toMutableList()
kotlinSettingsEntity.isTestModule = kotlinFacetSettings.isTestModule
kotlinSettingsEntity.externalProjectId = kotlinFacetSettings.externalProjectId
kotlinSettingsEntity.isHmppEnabled = kotlinFacetSettings.isHmppEnabled
kotlinSettingsEntity.pureKotlinSourceFolders = kotlinFacetSettings.pureKotlinSourceFolders.toMutableList()
kotlinSettingsEntity.kind = kotlinFacetSettings.kind
//if (kotlinFacetSettings.mergedCompilerArguments != null) {
// kotlinSettingsEntity.mergedCompilerArguments = serializeToString(kotlinFacetSettings.mergedCompilerArguments!!)
//}
if (kotlinFacetSettings.compilerArguments != null) {
kotlinSettingsEntity.compilerArguments = serializeToString(kotlinFacetSettings.compilerArguments!!)
}
val compilerSettings = kotlinFacetSettings.compilerSettings
if (compilerSettings != null) {
kotlinSettingsEntity.compilerSettings = CompilerSettingsData(
compilerSettings.additionalArguments,
compilerSettings.scriptTemplates,
compilerSettings.scriptTemplatesClasspath,
compilerSettings.copyJsLibraryFiles,
compilerSettings.outputDirectoryForJsLibraryFiles
)
}
}
override fun serialize(entity: KotlinSettingsEntity, rootElement: Element): Element {
// TODO: optimize compiler arguments serialization
KotlinFacetSettings().apply {
useProjectSettings = entity.useProjectSettings
//mergedCompilerArguments =
// if (entity.mergedCompilerArguments.isEmpty()) null else serializeFromString(entity.mergedCompilerArguments) as CommonCompilerArguments
compilerArguments =
if (entity.compilerArguments.isEmpty()) null else serializeFromString(entity.compilerArguments) as CommonCompilerArguments
val compilerSettingsFromEntity = entity.compilerSettings
val isCompilerSettingsChanged =
CompilerSettings().let {
it.additionalArguments != compilerSettingsFromEntity.additionalArguments ||
it.scriptTemplates != compilerSettingsFromEntity.scriptTemplates ||
it.scriptTemplatesClasspath != compilerSettingsFromEntity.scriptTemplatesClasspath ||
it.copyJsLibraryFiles != compilerSettingsFromEntity.copyJsLibraryFiles ||
it.outputDirectoryForJsLibraryFiles != compilerSettingsFromEntity.outputDirectoryForJsLibraryFiles
}
compilerSettings = if (isCompilerSettingsChanged) CompilerSettings().apply {
additionalArguments = compilerSettingsFromEntity.additionalArguments
scriptTemplates = compilerSettingsFromEntity.scriptTemplates
scriptTemplatesClasspath = compilerSettingsFromEntity.scriptTemplatesClasspath
copyJsLibraryFiles = compilerSettingsFromEntity.copyJsLibraryFiles
outputDirectoryForJsLibraryFiles = compilerSettingsFromEntity.outputDirectoryForJsLibraryFiles
} else null
//externalSystemRunTasks = entity.externalSystemRunTasks
implementedModuleNames = entity.implementedModuleNames
dependsOnModuleNames = entity.dependsOnModuleNames
additionalVisibleModuleNames = entity.additionalVisibleModuleNames
productionOutputPath = entity.productionOutputPath.ifEmpty { null }
testOutputPath = entity.testOutputPath.ifEmpty { null }
kind = entity.kind
sourceSetNames = entity.sourceSetNames
isTestModule = entity.isTestModule
externalProjectId = entity.externalProjectId
isHmppEnabled = entity.isHmppEnabled
pureKotlinSourceFolders = entity.pureKotlinSourceFolders
}.serializeFacetSettings(rootElement)
return rootElement
}
// naive implementation of compile arguments serialization, need to be optimized
companion object {
fun serializeToString(o: Serializable?): String {
if (o == null) return ""
lateinit var res: String
ByteArrayOutputStream().use { baos ->
ObjectOutputStream(baos).use { oos ->
oos.writeObject(o)
}
res = Base64.getEncoder().encodeToString(baos.toByteArray())
}
return res
}
fun serializeFromString(s: String): Any {
val data: ByteArray = Base64.getDecoder().decode(s)
return ObjectInputStream(
ByteArrayInputStream(data)
).use {
it.readObject()
}
}
}
} | 251 | null | 5079 | 16,158 | 831d1a4524048aebf64173c1f0b26e04b61c6880 | 8,035 | intellij-community | Apache License 2.0 |
app/src/main/java/xyz/harmonyapp/olympusblog/ui/main/article/state/ArticleStateEvent.kt | sentrionic | 351,882,310 | false | null | package xyz.harmonyapp.olympusblog.ui.main.article.state
import okhttp3.MultipartBody
import xyz.harmonyapp.olympusblog.utils.StateEvent
sealed class ArticleStateEvent : StateEvent {
class GetArticlesEvent(val clearLayoutManagerState: Boolean = true) : ArticleStateEvent() {
override fun errorInfo(): String {
return "Error retrieving articles."
}
override fun toString(): String {
return "GetArticlesEvent"
}
}
class ArticleSearchEvent(val clearLayoutManagerState: Boolean = true) : ArticleStateEvent() {
override fun errorInfo(): String {
return "Error searching for articles."
}
override fun toString(): String {
return "ArticleSearchEvent"
}
}
class ArticleFeedEvent(val clearLayoutManagerState: Boolean = true) : ArticleStateEvent() {
override fun errorInfo(): String {
return "Error retrieving your feed."
}
override fun toString(): String {
return "ArticleFeedEvent"
}
}
class ArticleBookmarkEvent(val clearLayoutManagerState: Boolean = true) : ArticleStateEvent() {
override fun errorInfo(): String {
return "Error retrieving your bookmarked articles."
}
override fun toString(): String {
return "ArticleBookmarkEvent"
}
}
class ArticlesByTagEvent(val clearLayoutManagerState: Boolean = true) : ArticleStateEvent() {
override fun errorInfo(): String {
return "Error retrieving articles."
}
override fun toString(): String {
return "ArticlesByTagEvent"
}
}
class CleanDBEvent : ArticleStateEvent() {
override fun errorInfo(): String {
return "Error deleting database."
}
override fun toString(): String {
return "CleanDBEvent"
}
}
class CheckAuthorOfArticle : ArticleStateEvent() {
override fun errorInfo(): String {
return "Error checking if you are the author of this article post."
}
override fun toString(): String {
return "CheckAuthorOfArticlePost"
}
}
class DeleteArticleEvent : ArticleStateEvent() {
override fun errorInfo(): String {
return "Error deleting that article."
}
override fun toString(): String {
return "DeleteArticlePostEvent"
}
}
data class CreateNewArticleEvent(
val title: String,
val description: String,
val body: String,
val tags: String,
val image: MultipartBody.Part?
) : ArticleStateEvent() {
override fun errorInfo(): String {
return "Unable to create a new article."
}
override fun toString(): String {
return "CreateNewArticleEvent"
}
}
data class UpdateArticleEvent(
val title: String,
val description: String,
val body: String,
val tags: String,
val image: MultipartBody.Part?
) : ArticleStateEvent() {
override fun errorInfo(): String {
return "Error updating that article."
}
override fun toString(): String {
return "UpdateArticlePostEvent"
}
}
class ToggleFavoriteEvent : ArticleStateEvent() {
override fun errorInfo(): String {
return "Error changing favorites status."
}
override fun toString(): String {
return "ToggleFavoriteEvent"
}
}
class ToggleBookmarkEvent : ArticleStateEvent() {
override fun errorInfo(): String {
return "Error changing bookmark status."
}
override fun toString(): String {
return "ToggleBookmarkEvent"
}
}
class GetArticleCommentsEvent : ArticleStateEvent() {
override fun errorInfo(): String {
return "Error getting article comments."
}
override fun toString(): String {
return "GetArticleComments"
}
}
data class PostCommentEvent(val body: String) : ArticleStateEvent() {
override fun errorInfo(): String {
return "Error posting article comment."
}
override fun toString(): String {
return "PostCommentEvent"
}
}
class DeleteCommentEvent : ArticleStateEvent() {
override fun errorInfo(): String {
return "Error deleting article comment."
}
override fun toString(): String {
return "DeleteCommentEvent"
}
}
class None : ArticleStateEvent() {
override fun errorInfo(): String {
return "None."
}
}
} | 0 | Kotlin | 0 | 0 | 3b784bf9dd60f6cc6889813f2e2932fa3a9b211d | 4,793 | OlympusAndroid | MIT License |
ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/ArgumentListWrappingRuleTest.kt | pinterest | 64,293,719 | false | null | package com.pinterest.ktlint.ruleset.standard.rules
import com.pinterest.ktlint.rule.engine.core.api.editorconfig.MAX_LINE_LENGTH_PROPERTY
import com.pinterest.ktlint.ruleset.standard.rules.ClassSignatureRule.Companion.FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY
import com.pinterest.ktlint.test.KtLintAssertThat.Companion.EOL_CHAR
import com.pinterest.ktlint.test.KtLintAssertThat.Companion.MAX_LINE_LENGTH_MARKER
import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThatRule
import com.pinterest.ktlint.test.LintViolation
import com.pinterest.ktlint.test.MULTILINE_STRING_QUOTE
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
class ArgumentListWrappingRuleTest {
private val argumentListWrappingRuleAssertThat = assertThatRule { ArgumentListWrappingRule() }
@Test
fun `Given a function call and not all arguments are on the same line`() {
val code =
"""
val x = f(
a,
b, c
)
""".trimIndent()
val formattedCode =
"""
val x = f(
a,
b,
c
)
""".trimIndent()
@Suppress("ktlint:standard:argument-list-wrapping", "ktlint:standard:max-line-length")
argumentListWrappingRuleAssertThat(code)
.hasLintViolation(3, 8, "Argument should be on a separate line (unless all arguments can fit a single line)")
.isFormattedAs(formattedCode)
}
@Test
fun `Given a nested function call and not all parameters in the nested call are on the same line`() {
val code =
"""
val x = test(
one("a", "b",
"c"),
"Two"
)
""".trimIndent()
val formattedCode =
"""
val x = test(
one(
"a",
"b",
"c"
),
"Two"
)
""".trimIndent()
argumentListWrappingRuleAssertThat(code)
.addAdditionalRuleProvider { IndentationRule() }
.hasLintViolations(
LintViolation(2, 9, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(2, 14, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(3, 8, "Missing newline before \")\""),
).isFormattedAs(formattedCode)
}
@Test
fun `Given that not all parameters in a function call fit on a single line`() {
val code =
"""
val x = f(a, b, c)
""".trimIndent()
val formattedCode =
"""
val x = f(
a,
b,
c
)
""".trimIndent()
argumentListWrappingRuleAssertThat(code)
.withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 10)
.hasLintViolations(
LintViolation(1, 11, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(1, 14, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(1, 17, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(1, 18, "Missing newline before \")\""),
).isFormattedAs(formattedCode)
}
@Test
fun `Given lambda arguments containing a line break are ignored`() {
val code =
"""
abstract class A(init: String.() -> Int)
class B : A({
toInt()
})
fun test(a: Any, b: (Any) -> Any) {
test(a = "1", b = {
it.toString()
})
}
""".trimIndent()
argumentListWrappingRuleAssertThat(code).hasNoLintViolations()
}
@Test
fun `Issue 928 - Given a lambda argument containing a line break`() {
val code =
"""
val foo =
foo(
bar.apply {
// stuff
}
)
""".trimIndent()
argumentListWrappingRuleAssertThat(code).hasNoLintViolations()
}
@Test
fun `Issue 1010 - Given a lambda containing a line break and a line in that lambda exceeds the max line limit `() {
val code =
"""
abstract class A(init: String.() -> Int)
class B : A({
toInt() // This line exceeds the line limit but will not be reported
})
val foo1 =
test(a = "1", b = {
it.toString() // This line exceeds the line limit but will not be reported
})
val foo2 =
test(a = "1")
val foo3 =
test(a = "1", b = "2")
""".trimIndent()
val formattedCode =
"""
abstract class A(init: String.() -> Int)
class B : A({
toInt() // This line exceeds the line limit but will not be reported
})
val foo1 =
test(a = "1", b = {
it.toString() // This line exceeds the line limit but will not be reported
})
val foo2 =
test(a = "1")
val foo3 =
test(
a = "1",
b = "2"
)
""".trimIndent()
argumentListWrappingRuleAssertThat(code)
.withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 20)
.hasLintViolations(
LintViolation(13, 10, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(13, 19, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(13, 26, "Missing newline before \")\""),
).isFormattedAs(formattedCode)
}
@Test
fun `Given a lambda in an argument of a function call which also contains a line break outside of the lambda`() {
val code =
"""
val foo1 =
foo(
a = "1", b = {
it.toString()
})
val foo2 =
foo("1",
{ it.toString() })
""".trimIndent()
val formattedCode =
"""
val foo1 =
foo(
a = "1",
b = {
it.toString()
}
)
val foo2 =
foo(
"1",
{ it.toString() }
)
""".trimIndent()
argumentListWrappingRuleAssertThat(code)
.addAdditionalRuleProvider { IndentationRule() }
.hasLintViolations(
LintViolation(3, 18, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(5, 6, "Missing newline before \")\""),
LintViolation(7, 9, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(8, 26, "Missing newline before \")\""),
).isFormattedAs(formattedCode)
}
@Test
fun `Given a lambda in an argument of a function call which does not contains a line break outside of the lambda`() {
val code =
"""
val foo =
foo(a = "1", b = {
it.toString()
}, c = "3")
""".trimIndent()
argumentListWrappingRuleAssertThat(code).hasNoLintViolations()
}
@Test
fun `Given some nested lambda parameter argument`() {
val code =
"""
val foo =
foo(
"1",
{
bar(1,
{ "foobar" }, 3)
},
123
)
""".trimIndent()
val formattedCode =
"""
val foo =
foo(
"1",
{
bar(
1,
{ "foobar" },
3
)
},
123
)
""".trimIndent()
argumentListWrappingRuleAssertThat(code)
.hasLintViolations(
LintViolation(5, 17, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(6, 31, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(6, 32, "Missing newline before \")\""),
).isFormattedAs(formattedCode)
}
@Test
fun `Given a parameter (after a multiline lambda parameter) which already does start on a new line`() {
val code =
"""
fun test(a: Any, b: (Any) -> Any, c: Any) {
test(a = "1", b = {
it.toString()
},
c = 123)
}
""".trimIndent()
val formattedCode =
"""
fun test(a: Any, b: (Any) -> Any, c: Any) {
test(
a = "1",
b = {
it.toString()
},
c = 123
)
}
""".trimIndent()
argumentListWrappingRuleAssertThat(code)
.addAdditionalRuleProvider { IndentationRule() }
.hasLintViolations(
LintViolation(2, 10, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(2, 19, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(5, 12, "Missing newline before \")\""),
).isFormattedAs(formattedCode)
}
@Nested
inner class `Given a function call with too man (eg more than 8) arguments` {
@Test
fun `Given that arguments are on a single line but exceeding max line length`() {
val code =
"""
val foo = foo(1, 2, 3, 4, 5, 6, 7, 8, 9)
""".trimIndent()
argumentListWrappingRuleAssertThat(code)
.withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 20)
.hasNoLintViolations()
}
@Test
fun `Given that arguments are spread on multiple lines and not exceeding max line length`() {
val code =
"""
val foo = foo(
1, 2, 3, 4,
5, 6, 7, 8,
9
)
""".trimIndent()
argumentListWrappingRuleAssertThat(code).hasNoLintViolations()
}
}
@Test
fun `Given multiline annotations with inner indents`() {
val code =
"""
class A {
fun f(@Annotation
a: Any,
@Annotation([
"v1",
"v2"
])
b: Any,
c: Any =
false,
@Annotation d: Any,
@SingleLineAnnotation([1, 2])
e: Any) {
}
}
""".trimIndent()
val formattedCode =
"""
class A {
fun f(@Annotation
a: Any,
@Annotation(
[
"v1",
"v2"
]
)
b: Any,
c: Any =
false,
@Annotation d: Any,
@SingleLineAnnotation([1, 2])
e: Any) {
}
}
""".trimIndent()
argumentListWrappingRuleAssertThat(code)
.addAdditionalRuleProvider { IndentationRule() }
.hasLintViolations(
LintViolation(4, 21, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(7, 10, "Missing newline before \")\""),
).isFormattedAs(formattedCode)
}
@Test
fun `Issue 927 - Allow inline block comment before argument`() {
val code =
"""
fun main() {
someMethod(
/* firstName= */ "John",
/* lastName= */ "Doe",
/* age= */ 30
)
}
""".trimIndent()
argumentListWrappingRuleAssertThat(code).hasNoLintViolations()
}
@Nested
inner class `Given an if statement` {
@Test
fun `Issue 929 - Given some if condition calling a function with indented parameters`() {
val code =
"""
fun test(param1: Int, param2: Int) {
if (listOfNotNull(
param1
).isEmpty()
) {
println(1)
} else if (listOfNotNull(
param2
).isEmpty()
) {
println(2)
}
}
""".trimIndent()
argumentListWrappingRuleAssertThat(code).hasNoLintViolations()
}
@Test
fun `Issue 929 - Given some if condition calling a function with indented parameters (preceded by line break)`() {
val code =
"""
fun test(param1: Int, param2: Int) {
if (
listOfNotNull(
param1
).isEmpty()
) {
println(1)
} else if (
listOfNotNull(
param2
).isEmpty()
) {
println(2)
}
}
""".trimIndent()
argumentListWrappingRuleAssertThat(code).hasNoLintViolations()
}
@Test
fun `Given some function call in the else branch`() {
val code =
"""
fun foo(i: Int, j: Int) = 1
fun test() {
val x = if (true) 1 else foo(
2,
3
)
}
""".trimIndent()
argumentListWrappingRuleAssertThat(code).hasNoLintViolations()
}
}
@Test
fun `Issue 929 - Given a when-statement with a function call`() {
val code =
"""
fun foo(i: Int) = true
fun test(i: Int) {
when (foo(
i
)) {
true -> println(1)
false -> println(2)
}
}
""".trimIndent()
argumentListWrappingRuleAssertThat(code).hasNoLintViolations()
}
@Test
fun `Issue 929 - Given a while-statement with a function call`() {
val code =
"""
fun foo(i: Int) = true
fun test(i: Int) {
while (foo(
i
)
) {
println()
}
}
""".trimIndent()
argumentListWrappingRuleAssertThat(code).hasNoLintViolations()
}
@Test
fun `Issue 929 - Given a do-while-statement with a function call`() {
val code =
"""
fun foo(i: Int) = true
fun test(i: Int) {
do {
println()
} while (foo(
i
)
)
}
""".trimIndent()
argumentListWrappingRuleAssertThat(code).hasNoLintViolations()
}
@Test
fun `Given some multiline raw string literal (not containing a string template) which is exceeding the max line length then do not wrap`() {
val code =
"""
val foo1 = someMethod(
$MULTILINE_STRING_QUOTE
longtext longtext longtext longtext longtext longtext longtext longtext
longtext longtext longtext longtext longtext longtext longtext longtext
$MULTILINE_STRING_QUOTE.trimIndent()
)
val foo2 = someMethod(${MULTILINE_STRING_QUOTE}stuff$MULTILINE_STRING_QUOTE)
""".trimIndent()
val formattedCode =
"""
val foo1 = someMethod(
$MULTILINE_STRING_QUOTE
longtext longtext longtext longtext longtext longtext longtext longtext
longtext longtext longtext longtext longtext longtext longtext longtext
$MULTILINE_STRING_QUOTE.trimIndent()
)
val foo2 = someMethod(
${MULTILINE_STRING_QUOTE}stuff$MULTILINE_STRING_QUOTE
)
""".trimIndent()
argumentListWrappingRuleAssertThat(code)
.withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 33)
.hasLintViolations(
LintViolation(8, 23, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(8, 34, "Missing newline before \")\""),
).isFormattedAs(formattedCode)
}
@Test
fun `Given some multiline raw string literal containing a string template and the the content of the string template exceeds the max line length then do wrap`() {
val code =
"""
val foo = someMethod(
$MULTILINE_STRING_QUOTE
some text
${'$'}{println("longtext longtext longtext longtext longtext longtext")}
$MULTILINE_STRING_QUOTE.trimIndent()
)
""".trimIndent()
val formattedCode =
"""
val foo = someMethod(
$MULTILINE_STRING_QUOTE
some text
${'$'}{println(
"longtext longtext longtext longtext longtext longtext"
)}
$MULTILINE_STRING_QUOTE.trimIndent()
)
""".trimIndent()
argumentListWrappingRuleAssertThat(code)
.withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 65)
.hasLintViolations(
LintViolation(4, 15, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(4, 70, "Missing newline before \")\""),
).isFormattedAs(formattedCode)
}
@Test
fun `Given some multiline raw string literal containing a string template not exceeding the max line length then do not wrap`() {
val code =
"""
fun foo() {
json(
$MULTILINE_STRING_QUOTE
{
"array": [
${'$'}{function(arg1, arg2, arg3)}
]
}
$MULTILINE_STRING_QUOTE.trimIndent()
)
}
""".trimIndent()
argumentListWrappingRuleAssertThat(code)
.withEditorConfigOverride(MAX_LINE_LENGTH_PROPERTY to 45)
.hasNoLintViolations()
}
@Nested
inner class `Given a multiline dot qualified expression` {
@Test
fun `Issue 1025 - Given an argument list after multiline dot qualified expression`() {
val code =
"""
private fun replaceLogger(deviceId: String, orgName: String) {
val stateManager: StateManager = StateManager()
stateManager
.firebaseLogger(
mode = 0,
appInstanceIdentity = deviceId,
org = orgName
)
}
""".trimIndent()
argumentListWrappingRuleAssertThat(code).hasNoLintViolations()
}
@Test
fun `Issue 1025 - Given an argument list after dot qualified expression with assignment`() {
val code =
"""
private fun replaceLogger(deviceId: String, orgName: String) {
stateManager
.firebaseLogger = Logging(
mode = if (BuildConfig.DEBUG) Logging.Companion.LogDestination.DEV else Logging.Companion.LogDestination.PROD,
appInstanceIdentity = deviceId,
org = orgName
)
stateManager.firebaseLogger.tellTheCloudAboutMe()
customisation.attachToFirebase(stateManager.firebaseLogger.appCloudPrefix)
}
""".trimIndent()
argumentListWrappingRuleAssertThat(code).hasNoLintViolations()
}
@Test
fun `Issue 1196 - Given an argument list after multiline dot qualified expression`() {
val code =
"""
class MyClass {
private fun initCoilOkHttp() {
Coil.setImageLoader(
ImageLoader.Builder(this)
.crossfade(true)
.okHttpClient(
okHttpClient.newBuilder()
.cache(CoilUtils.createDefaultCache(this))
.build()
)
.build()
)
}
}
""".trimIndent()
argumentListWrappingRuleAssertThat(code).hasNoLintViolations()
}
}
@Test
fun `Issue 1025 - Given an argument list after multiline type argument list`() {
val code =
"""
fun test() {
generic<
Int,
Int>(
1,
2
)
}
""".trimIndent()
argumentListWrappingRuleAssertThat(code).hasNoLintViolations()
}
@Test
fun `Issue 1081 - Given `() {
val code =
"""
package com.foo
class MyClass() {
private fun doSomething() {
if (d == 0 || e == 0f) {
c.ee(hh, d, d, yy)
} else {
foo.blah()
val dr = t - u
val xx = -gg(dr) * rr(2f * d, dr.hh)
foo.bar(
dd,
g - d
)
foo.baz(
a.b, a.c - d
)
foo.biz(
a.b, a.c - d,
a.b, a.c,
a.b + d, a.c
)
foo.baz(
a.x - d, a.c
)
foo.biz(
a.x - d, a.c,
a.x, a.c,
a.x, a.c - d
)
foo.baz(
a.x, a.j + d
)
}
}
}
""".trimIndent()
val formattedCode =
"""
package com.foo
class MyClass() {
private fun doSomething() {
if (d == 0 || e == 0f) {
c.ee(hh, d, d, yy)
} else {
foo.blah()
val dr = t - u
val xx = -gg(dr) * rr(2f * d, dr.hh)
foo.bar(
dd,
g - d
)
foo.baz(
a.b,
a.c - d
)
foo.biz(
a.b,
a.c - d,
a.b,
a.c,
a.b + d,
a.c
)
foo.baz(
a.x - d,
a.c
)
foo.biz(
a.x - d,
a.c,
a.x,
a.c,
a.x,
a.c - d
)
foo.baz(
a.x,
a.j + d
)
}
}
}
""".trimIndent()
argumentListWrappingRuleAssertThat(code)
.hasLintViolations(
LintViolation(16, 22, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(19, 22, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(20, 22, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(21, 26, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(24, 26, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(27, 26, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(28, 22, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(29, 22, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(32, 22, "Argument should be on a separate line (unless all arguments can fit a single line)"),
).isFormattedAs(formattedCode)
}
@Test
fun `Issue 1112 - Given an argument list in lambda in dot qualified expression`() {
val code =
"""
fun main() {
listOf(1, 2, 3).map {
println(
it
)
}
}
""".trimIndent()
argumentListWrappingRuleAssertThat(code).hasNoLintViolations()
}
@Test
fun `Issue 1198 - Given a parameter list with assignment and no dot qualified expression`() {
val code =
"""
fun foo() {
tasks.test {
systemProperties = mutableMapOf(
"junit.jupiter.displayname.generator.default" to
"org.junit.jupiter.api.DisplayNameGenerator\${'$'}ReplaceUnderscores",
"junit.jupiter.execution.parallel.enabled" to
doParallelTesting.toString() as Any,
"junit.jupiter.execution.parallel.mode.default" to
"concurrent",
"junit.jupiter.execution.parallel.mode.classes.default" to
"concurrent"
)
}
}
""".trimIndent()
argumentListWrappingRuleAssertThat(code).hasNoLintViolations()
}
@Test
fun `Issue 1643 - do not wrap arguments if after wrapping rule the max line is no longer exceeded`() {
val code =
"""
// $MAX_LINE_LENGTH_MARKER $EOL_CHAR
class Bar1 {
val barrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr by lazy {
fooooooooooooo("fooooooooooooooooooooooooooooooooooooooooooooo", true)
}
}
class Bar2 {
val barrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr by lazy { fooooooooooooo("fooooooooooooooooooooooooooooooooooooooooooooo", true) }
}
""".trimIndent()
val formattedCode =
"""
// $MAX_LINE_LENGTH_MARKER $EOL_CHAR
class Bar1 {
val barrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr by lazy {
fooooooooooooo("fooooooooooooooooooooooooooooooooooooooooooooo", true)
}
}
class Bar2 {
val barrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr by lazy {
fooooooooooooo("fooooooooooooooooooooooooooooooooooooooooooooo", true)
}
}
""".trimIndent()
argumentListWrappingRuleAssertThat(code)
.setMaxLineLength()
.addAdditionalRuleProvider { WrappingRule() }
.hasLintViolations(
// During lint the violations below are reported because during linting, each rule reports its
// violations independently and can not anticipate on autocorrects which would have been made by other
// rules if those rules (i.e. the 'wrapping' rule) would have executed before the current rule (i.e. the
// 'argument-list-wrapping' rule)
LintViolation(8, 68, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(8, 118, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(8, 122, "Missing newline before \")\""),
).isFormattedAs(formattedCode)
}
@Test
fun `Given a property assignment with a binary expression for which the left hand side operator is a function call`() {
val code =
"""
// $MAX_LINE_LENGTH_MARKER $EOL_CHAR
val foo1 = foobar(foo * bar) + "foo"
val foo2 = foobar("foo", foo * bar) + "foo"
val foo3 = foobar("fooo", foo * bar) + "foo"
""".trimIndent()
argumentListWrappingRuleAssertThat(code)
.setMaxLineLength()
.addAdditionalRuleProvider { BinaryExpressionWrappingRule() }
.addAdditionalRuleProvider { WrappingRule() }
// Although the argument-list-wrapping runs before binary-expression-wrapping, it may not wrap the argument values of a
// function call in case that call is part of a binary expression. It might be better to break the line at the operation
// reference instead.
.hasNoLintViolationsExceptInAdditionalRules()
}
@Test
fun `Given a super type call entry with arguments which after wrapping to the next line does not fit on that line then keep start of body on same line as end of super type call entry`() {
val code =
"""
// $MAX_LINE_LENGTH_MARKER $EOL_CHAR
// Note that the super type call does not fit the line after it has been wrapped
// ...Foo(a: Any, b: Any, c: Any) :
// FooBar(a, "longggggggggggggggggggggggggggggggggggg")
class Foo(a: Any, b: Any, c: Any) : FooBar(a, "longggggggggggggggggggggggggggggggggggg") {
// body
}
""".trimIndent()
val formattedCode =
"""
// $MAX_LINE_LENGTH_MARKER $EOL_CHAR
// Note that the super type call does not fit the line after it has been wrapped
// ...Foo(a: Any, b: Any, c: Any) :
// FooBar(a, "longggggggggggggggggggggggggggggggggggg")
class Foo(a: Any, b: Any, c: Any) :
FooBar(
a,
"longggggggggggggggggggggggggggggggggggg"
) {
// body
}
""".trimIndent()
argumentListWrappingRuleAssertThat(code)
.setMaxLineLength()
.addAdditionalRuleProvider { ClassSignatureRule() }
.addAdditionalRuleProvider { DiscouragedCommentLocationRule() }
.withEditorConfigOverride(FORCE_MULTILINE_WHEN_PARAMETER_COUNT_GREATER_OR_EQUAL_THAN_PROPERTY to 4)
.hasLintViolationForAdditionalRule(5, 37, "Super type should start on a newline")
.hasLintViolations(
LintViolation(5, 44, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(5, 47, "Argument should be on a separate line (unless all arguments can fit a single line)"),
LintViolation(5, 88, "Missing newline before \")\""),
).isFormattedAs(formattedCode)
}
}
| 64 | null | 506 | 5,844 | 81c23d07b00c6d6a841e98cc73bd559722f12f37 | 33,851 | ktlint | MIT License |
app/src/main/java/com/celzero/bravedns/service/ConnectionMonitor.kt | celzero | 270,683,546 | false | null | /*
* Copyright 2021 RethinkDNS and its 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.celzero.bravedns.service
import android.content.Context
import android.net.ConnectivityManager
import android.net.LinkProperties
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.net.TrafficStats
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.os.Message
import android.os.SystemClock
import android.system.ErrnoException
import android.system.OsConstants.ECONNREFUSED
import android.system.OsConstants.RT_SCOPE_UNIVERSE
import android.util.Log
import com.celzero.bravedns.RethinkDnsApplication.Companion.DEBUG
import com.celzero.bravedns.util.InternetProtocol
import com.celzero.bravedns.util.Logger.Companion.LOG_TAG_CONNECTION
import com.celzero.bravedns.util.Utilities.isAtleastQ
import com.celzero.bravedns.util.Utilities.isAtleastS
import com.celzero.bravedns.util.Utilities.isNetworkSame
import com.google.common.collect.Sets
import inet.ipaddr.IPAddressString
import kotlinx.coroutines.async
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.selects.select
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import java.io.Closeable
import java.io.IOException
import java.net.DatagramSocket
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.Socket
import java.util.concurrent.TimeUnit
import kotlin.math.min
class ConnectionMonitor(context: Context, networkListener: NetworkListener) :
ConnectivityManager.NetworkCallback(), KoinComponent {
private val androidValidatedNetworks = false
private val networkSet: MutableSet<Network> = mutableSetOf()
private val networkRequest: NetworkRequest =
if (androidValidatedNetworks)
NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
.apply { if (isAtleastS()) setIncludeOtherUidNetworks(true) }
.build()
else
// add cellular, wifi, bluetooth, ethernet, vpn, wifi aware, low pan
NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.addTransportType(NetworkCapabilities.TRANSPORT_BLUETOOTH)
.addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET)
.apply { if (isAtleastS()) setIncludeOtherUidNetworks(true) }
// api27: .addTransportType(NetworkCapabilities.TRANSPORT_WIFI_AWARE)
// api26: .addTransportType(NetworkCapabilities.TRANSPORT_LOWPAN)
.build()
// An Android handler thread internally operates on a looper
// ref:
// alvinalexander.com/java/jwarehouse/android/core/java/android/app/IntentService.java.shtml
private var handlerThread: HandlerThread
private var serviceHandler: NetworkRequestHandler? = null
private val persistentState by inject<PersistentState>()
private var connectivityManager: ConnectivityManager =
context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE)
as ConnectivityManager
companion object {
// add active network as underlying vpn network
const val MSG_ADD_ACTIVE_NETWORK = 1
// add all available networks as underlying vpn networks
const val MSG_ADD_ALL_NETWORKS = 2
fun networkType(newActiveNetworkCap: NetworkCapabilities?): String {
val a =
if (newActiveNetworkCap?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true) {
"VPN"
} else if (
newActiveNetworkCap?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true
) {
"WiFi"
} else if (
newActiveNetworkCap?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ==
true
) {
"Cellular"
} else {
"Unknown"
}
return a
}
}
// data class that holds the below information for handlers to process the network changes
// all values in OpPrefs should always remain immutable
data class OpPrefs(
val msgType: Int,
val networkSet: Set<Network>,
val isForceUpdate: Boolean,
val testReachability: Boolean,
val dualStack: Boolean
)
init {
try {
connectivityManager.registerNetworkCallback(networkRequest, this)
} catch (e: Exception) {
Log.w(LOG_TAG_CONNECTION, "Exception while registering network callback", e)
networkListener.onNetworkRegistrationFailed()
}
this.handlerThread = HandlerThread(NetworkRequestHandler::class.simpleName)
this.handlerThread.start()
this.serviceHandler = NetworkRequestHandler(context, handlerThread.looper, networkListener)
}
interface NetworkListener {
fun onNetworkDisconnected(networks: UnderlyingNetworks)
fun onNetworkConnected(networks: UnderlyingNetworks)
fun onNetworkRegistrationFailed()
}
fun onVpnStop() {
connectivityManager.unregisterNetworkCallback(this)
destroy()
}
private fun destroy() {
this.serviceHandler?.removeCallbacksAndMessages(null)
this.handlerThread.quitSafely()
this.serviceHandler = null
}
override fun onAvailable(network: Network) {
if (DEBUG) Log.d(LOG_TAG_CONNECTION, "onAvailable: ${network.networkHandle}, $network")
networkSet.add(network)
val cap = connectivityManager.getNetworkCapabilities(network)
if (DEBUG)
Log.d(
LOG_TAG_CONNECTION,
"onAvailable: ${network.networkHandle}, $network, ${networkSet.size}, ${networkType(cap)}"
)
handleNetworkChange()
}
override fun onLost(network: Network) {
if (DEBUG) Log.d(LOG_TAG_CONNECTION, "onLost, ${network.networkHandle}, $network")
networkSet.remove(network)
val cap = connectivityManager.getNetworkCapabilities(network)
if (DEBUG)
Log.d(
LOG_TAG_CONNECTION,
"onLost: ${network.networkHandle}, $network, ${networkSet.size}, ${networkType(cap)}"
)
handleNetworkChange()
}
override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
if (DEBUG)
Log.d(LOG_TAG_CONNECTION, "onCapabilitiesChanged, ${network.networkHandle}, $network")
handleNetworkChange(isForceUpdate = false, TimeUnit.SECONDS.toMillis(3))
}
override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) {
if (DEBUG)
Log.d(LOG_TAG_CONNECTION, "onLinkPropertiesChanged: ${network.networkHandle}, $network")
handleNetworkChange(isForceUpdate = true, TimeUnit.SECONDS.toMillis(3))
}
/**
* Handles user preference changes, ie, when the user elects to see either multiple underlying
* networks, or just one (the active network).
*/
fun onUserPreferenceChangedLocked() {
if (DEBUG) Log.d(LOG_TAG_CONNECTION, "onUserPreferenceChanged")
handleNetworkChange(isForceUpdate = true)
}
/**
* Force updates the VPN's underlying network based on the preference. Will be initiated when
* the VPN start is completed.
*/
fun onVpnStartLocked() {
Log.i(LOG_TAG_CONNECTION, "new vpn is created force update the network")
handleNetworkChange(isForceUpdate = true)
}
private fun handleNetworkChange(
isForceUpdate: Boolean = false,
delay: Long = TimeUnit.SECONDS.toMillis(1)
) {
val isDualStack = InternetProtocol.isAuto(persistentState.internetProtocolType)
val testReachability = isDualStack && !androidValidatedNetworks
val msg =
constructNetworkMessage(
if (persistentState.useMultipleNetworks) MSG_ADD_ALL_NETWORKS
else MSG_ADD_ACTIVE_NETWORK,
isForceUpdate,
testReachability,
isDualStack
)
serviceHandler?.removeMessages(MSG_ADD_ACTIVE_NETWORK, null)
serviceHandler?.removeMessages(MSG_ADD_ALL_NETWORKS, null)
// process after a delay to avoid processing multiple network changes in short bursts
serviceHandler?.sendMessageDelayed(msg, delay)
}
/**
* Constructs the message object for Network handler. Add the active network to the message
* object in case of setUnderlying network has only active networks.
*/
private fun constructNetworkMessage(
what: Int,
isForceUpdate: Boolean,
testReachability: Boolean,
dualStack: Boolean
): Message {
val opPrefs = OpPrefs(what, networkSet, isForceUpdate, testReachability, dualStack)
val message = Message.obtain()
message.what = what
message.obj = opPrefs
return message
}
data class NetworkProperties(
val network: Network,
val capabilities: NetworkCapabilities,
val linkProperties: LinkProperties?,
val networkType: String
)
data class UnderlyingNetworks(
val ipv4Net: List<NetworkProperties>,
val ipv6Net: List<NetworkProperties>,
val useActive: Boolean,
val minMtu: Int,
var isActiveNetworkMetered: Boolean,
var lastUpdated: Long
)
// Handles the network messages from the callback from the connectivity manager
private class NetworkRequestHandler(
ctx: Context,
looper: Looper,
val listener: NetworkListener
) : Handler(looper) {
// number of times the reachability check is performed due to failures
private var reachabilityCount = 0L
private val maxReachabilityCount = 10L
companion object {
private const val MAX_INTERFACE_MTU = 1500 // same as BraveVpnService#VPN_INTERFACE_MTU
private const val MIN_INTERFACE_MTU = 1280
}
private val ip4probes =
listOf(
"192.168.3.11", // google org
"192.168.3.11", // cloudflare
"192.168.3.11" // whatsapp.net
)
// probing with domain names is not viable because some domains will resolve to both
// ipv4 and ipv6 addresses. So, we use ipv6 addresses for probing ipv6 connectivity.
private val ip6probes =
listOf(
"fc00:e968:6179::de52:7100", // google org
"fc00:e968:6179::de52:7100:84e5", // cloudflare
"2606:4700:3033::ac43:a21b" // rethinkdns
)
// ref - https://developer.android.com/reference/kotlin/java/util/LinkedHashSet
// The network list is maintained in a linked-hash-set to preserve insertion and iteration
// order. This is required because {@link android.net.VpnService#setUnderlyingNetworks}
// defines network priority depending on the iteration order, that is, the network
// in the 0th index is preferred over the one at 1st index, and so on.
var currentNetworks: LinkedHashSet<NetworkProperties> = linkedSetOf()
var trackedIpv4Networks: LinkedHashSet<NetworkProperties> = linkedSetOf()
var trackedIpv6Networks: LinkedHashSet<NetworkProperties> = linkedSetOf()
var connectivityManager: ConnectivityManager =
ctx.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE)
as ConnectivityManager
override fun handleMessage(msg: Message) {
// isForceUpdate - true if onUserPreferenceChanged is changes, the messages should be
// processed forcefully regardless of the current and new networks.
when (msg.what) {
MSG_ADD_ACTIVE_NETWORK -> {
val opPrefs = msg.obj as OpPrefs
processActiveNetwork(opPrefs)
}
MSG_ADD_ALL_NETWORKS -> {
val opPrefs = msg.obj as OpPrefs
processAllNetworks(opPrefs)
}
}
}
/**
* tracks the changes in active network. Set the underlying network if the current active
* network is different from already assigned one unless the force update is required.
*/
private fun processActiveNetwork(opPrefs: OpPrefs) {
val newActiveNetwork = connectivityManager.activeNetwork
val newActiveNetworkCap = connectivityManager.getNetworkCapabilities(newActiveNetwork)
// set active network's connection status
val isActiveNetworkMetered = isActiveConnectionMetered()
val newNetworks = createNetworksSet(newActiveNetwork, opPrefs.networkSet)
val isNewNetwork = hasDifference(currentNetworks, newNetworks)
Log.i(
LOG_TAG_CONNECTION,
"Connected network: ${newActiveNetwork?.networkHandle} ${networkType(newActiveNetworkCap)
}, new? $isNewNetwork, force? ${opPrefs.isForceUpdate}, auto? ${opPrefs.testReachability}"
)
if (isNewNetwork || opPrefs.isForceUpdate) {
currentNetworks = newNetworks
repopulateTrackedNetworks(opPrefs, currentNetworks)
informListener(true, isActiveNetworkMetered)
}
}
/** Adds all the available network to the underlying network. */
private fun processAllNetworks(opPrefs: OpPrefs) {
val newActiveNetwork = connectivityManager.activeNetwork
// set active network's connection status
val isActiveNetworkMetered = isActiveConnectionMetered()
val newNetworks = createNetworksSet(newActiveNetwork, opPrefs.networkSet)
val isNewNetwork = hasDifference(currentNetworks, newNetworks)
Log.i(
LOG_TAG_CONNECTION,
"process message MESSAGE_AVAILABLE_NETWORK, ${currentNetworks}, ${newNetworks}; new? $isNewNetwork, force? ${opPrefs.isForceUpdate}, auto? ${opPrefs.testReachability}"
)
if (isNewNetwork || opPrefs.isForceUpdate) {
currentNetworks = newNetworks
repopulateTrackedNetworks(opPrefs, currentNetworks)
informListener(false, isActiveNetworkMetered)
}
}
private fun informListener(
useActiveNetwork: Boolean = false,
isActiveNetworkMetered: Boolean
) {
val sz = trackedIpv4Networks.size + trackedIpv6Networks.size
Log.i(
LOG_TAG_CONNECTION,
"inform network change: ${sz}, all? $useActiveNetwork, metered? $isActiveNetworkMetered"
)
if (sz > 0) {
val underlyingNetworks =
UnderlyingNetworks(
trackedIpv4Networks.map { it }, // map to produce shallow copy
trackedIpv6Networks.map { it },
useActiveNetwork,
determineMtu(useActiveNetwork),
isActiveNetworkMetered,
SystemClock.elapsedRealtime()
)
if (DEBUG) {
trackedIpv4Networks.forEach {
Log.d(LOG_TAG_CONNECTION, "inform4: ${it.network}, ${it.networkType}, $sz")
}
trackedIpv6Networks.forEach {
Log.d(LOG_TAG_CONNECTION, "inform6: ${it.network}, ${it.networkType}, $sz")
}
}
listener.onNetworkConnected(underlyingNetworks)
} else {
val underlyingNetworks =
UnderlyingNetworks(
emptyList(),
emptyList(),
useActiveNetwork,
MAX_INTERFACE_MTU,
isActiveNetworkMetered = false,
SystemClock.elapsedRealtime()
)
listener.onNetworkDisconnected(underlyingNetworks)
}
}
private fun determineMtu(useActiveNetwork: Boolean): Int {
if (!isAtleastQ()) {
return MAX_INTERFACE_MTU
}
var mtu =
if (useActiveNetwork) {
val activeNetwork = connectivityManager.activeNetwork
// consider first network in underlying network as active network, in case
// if active network is null
val lp4 =
trackedIpv4Networks.firstOrNull()?.linkProperties
?: connectivityManager.getLinkProperties(activeNetwork)
val lp6 =
trackedIpv6Networks.firstOrNull()?.linkProperties
?: connectivityManager.getLinkProperties(activeNetwork)
minNonZeroMtu(lp4?.mtu, lp6?.mtu)
} else {
var prev4Lp: LinkProperties? = null
var prev6Lp: LinkProperties? = null
var minMtu4: Int = MAX_INTERFACE_MTU
var minMtu6: Int = MAX_INTERFACE_MTU
// parse through all the networks and get the minimum mtu
trackedIpv4Networks.forEach {
if (DEBUG)
Log.d(LOG_TAG_CONNECTION, "mtu for ipv4: ${it.linkProperties?.mtu}")
val c = it.linkProperties
minMtu4 = minNonZeroMtu(c?.mtu, prev4Lp?.mtu) ?: minMtu4
prev4Lp = c
}
trackedIpv6Networks.forEach {
if (DEBUG)
Log.d(LOG_TAG_CONNECTION, "mtu for ipv6: ${it.linkProperties?.mtu}")
val c = it.linkProperties
minMtu6 = minNonZeroMtu(c?.mtu, prev6Lp?.mtu) ?: minMtu6
prev6Lp = c
}
if (DEBUG)
Log.d(LOG_TAG_CONNECTION, "min mtu for v4 nws: $minMtu4, v6 nws: $minMtu6")
min(minMtu4, minMtu6)
}
// mtu can be 0 or null, set it to default value
// LinkProperties#getMtu() returns 0 if the value is not set
// minNonZeroMtu can returns null
if (mtu == null || mtu == 0) {
mtu = MAX_INTERFACE_MTU
Log.i(LOG_TAG_CONNECTION, "mtu is 0, setting to default $MAX_INTERFACE_MTU")
}
// min value is 1280, set it to 1280 if it is less than 1280
if (mtu < MIN_INTERFACE_MTU) {
mtu = MIN_INTERFACE_MTU
Log.i(LOG_TAG_CONNECTION, "mtu is less than 1280, setting to 1280")
}
Log.i(LOG_TAG_CONNECTION, "current mtu: $mtu")
return mtu
}
private fun minNonZeroMtu(m1: Int?, m2: Int?): Int? {
return if (m1 != null && m1 > 0 && m2 != null && m2 > 0) {
// mtu can be null when lp is null
// mtu can be 0 when the value is not set, see:LinkProperties#getMtu()
min(m1, m2)
} else if (m1 != null && m1 > 0) {
m1
} else if (m2 != null && m2 > 0) {
m2
} else {
null
}
}
private fun isActiveConnectionMetered(): Boolean {
return connectivityManager.isActiveNetworkMetered
}
private fun repopulateTrackedNetworks(
opPrefs: OpPrefs,
networks: LinkedHashSet<NetworkProperties>
) {
val testReachability: Boolean = opPrefs.testReachability
val dualStack: Boolean = opPrefs.dualStack
val activeNetwork = connectivityManager.activeNetwork // null in vpn lockdown mode
trackedIpv4Networks.clear()
trackedIpv6Networks.clear()
networks.forEach outer@{ prop ->
val network: Network? = prop.network
val lp = connectivityManager.getLinkProperties(network)
if (lp == null) {
Log.i(LOG_TAG_CONNECTION, "skipping: $network; no link properties")
return@outer
}
val isActive = isNetworkSame(network, activeNetwork)
if (isActive) {
if (DEBUG) Log.d(LOG_TAG_CONNECTION, "processing active network: $network")
}
if (testReachability) {
val has4 = isIPv4Reachable(network, isActive)
val has6 = isIPv6Reachable(network, isActive)
if (has4) trackedIpv4Networks.add(prop)
if (has6) trackedIpv6Networks.add(prop)
Log.i(LOG_TAG_CONNECTION, "nw: has4? $has4, has6? $has6, $prop")
return@outer
}
var has4 = false
var has6 = false
lp.linkAddresses.forEach inner@{ addr ->
if (has4 && has6) return@outer
// skip if the address scope is not RT_SCOPE_UNIVERSE, as there are some
// addresses which are not reachable outside the network but we will end up
// adding those address for ipv4/ipv6 mode, reachability check will fail in
// dual stack mode.
if (!dualStack && addr.scope != RT_SCOPE_UNIVERSE) {
Log.i(
LOG_TAG_CONNECTION,
"skipping: ${addr.address.hostAddress} with scope: ${addr.scope}"
)
return@inner
}
val address = IPAddressString(addr.address.hostAddress?.toString())
if (hasInternet(network) == true) {
if (address.isIPv6) {
has6 = true
trackedIpv6Networks.add(prop)
Log.i(
LOG_TAG_CONNECTION,
"adding ipv6(${trackedIpv6Networks.size}): $prop; for $address"
)
} else if (address.isIPv4) {
has4 = true
// see #createNetworksSet for why we are using hasInternet
trackedIpv4Networks.add(prop)
Log.i(
LOG_TAG_CONNECTION,
"adding ipv4(${trackedIpv4Networks.size}): $prop; for $address"
)
} else {
Log.i(LOG_TAG_CONNECTION, "unknown lnaddr: $network; $address")
}
}
}
}
redoReachabilityIfNeeded(trackedIpv4Networks, trackedIpv6Networks, opPrefs)
Log.d(
LOG_TAG_CONNECTION,
"repopulate v6: $trackedIpv6Networks,\nv4: $trackedIpv4Networks"
)
trackedIpv4Networks = rearrangeNetworks(trackedIpv4Networks)
trackedIpv6Networks = rearrangeNetworks(trackedIpv6Networks)
}
private fun redoReachabilityIfNeeded(
ipv4: LinkedHashSet<NetworkProperties>,
ipv6: LinkedHashSet<NetworkProperties>,
opPrefs: OpPrefs
) {
if (ipv4.isEmpty() && ipv6.isEmpty()) {
reachabilityCount++
Log.i(LOG_TAG_CONNECTION, "redo reachability, try: $reachabilityCount")
if (reachabilityCount > maxReachabilityCount) return
val message = Message.obtain()
// assume opPrefs is immutable
message.what = opPrefs.msgType
message.obj = opPrefs
val delay = TimeUnit.SECONDS.toMillis(10 * reachabilityCount)
this.sendMessageDelayed(message, delay)
} else {
Log.d(LOG_TAG_CONNECTION, "reset reachability count, prev: $reachabilityCount")
// reset the reachability count
reachabilityCount = 0
}
}
private fun hasDifference(
currentNetworks: LinkedHashSet<NetworkProperties>,
newNetworks: LinkedHashSet<NetworkProperties>
): Boolean {
val cn = currentNetworks.map { it.network }.toSet()
val nn = newNetworks.map { it.network }.toSet()
return Sets.symmetricDifference(cn, nn).isNotEmpty()
}
private fun rearrangeNetworks(
networks: LinkedHashSet<NetworkProperties>
): LinkedHashSet<NetworkProperties> {
val newNetworks: LinkedHashSet<NetworkProperties> = linkedSetOf()
// add active network first, then add non metered networks, then metered networks
val activeNetwork = connectivityManager.activeNetwork
val n = networks.firstOrNull { isNetworkSame(it.network, activeNetwork) }
if (n != null) {
newNetworks.add(n)
}
val nonMeteredNetworks = networks.filter { isConnectionNotMetered(it.capabilities) }
nonMeteredNetworks.forEach {
if (!newNetworks.contains(it)) {
newNetworks.add(it)
}
}
// add remaining networks, ie, metered networks
networks.forEach {
if (!newNetworks.contains(it)) {
newNetworks.add(it)
}
}
return newNetworks
}
private fun isConnectionNotMetered(capabilities: NetworkCapabilities?): Boolean {
return capabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
?: false
}
/**
* Create network set(available networks) based on the user preference. The first element of
* the list must be active network. requireAllNetwork - if true adds all networks to the set
* else adds active network alone to the set.
*/
private fun createNetworksSet(
activeNetwork: Network?,
networkSet: Set<Network>
): LinkedHashSet<NetworkProperties> {
val newNetworks: LinkedHashSet<NetworkProperties> = linkedSetOf()
activeNetwork?.let {
val activeCap = connectivityManager.getNetworkCapabilities(activeNetwork)
val activeLp = connectivityManager.getLinkProperties(activeNetwork)
val nwType =
networkType(activeCap) + ", NotMetered?" + isConnectionNotMetered(activeCap)
val activeProp =
if (activeCap != null) {
NetworkProperties(it, activeCap, activeLp, nwType)
} else {
null
}
// test for internet capability iff opPrefs.testReachability is false
if (/*hasInternet(it) == true &&*/ isVPN(it) == false) {
if (activeProp != null) {
newNetworks.add(activeProp)
}
} else {
// no-op
}
}
val networks =
if (networkSet.isEmpty()) {
if (DEBUG) Log.d(LOG_TAG_CONNECTION, "networkSet is empty")
connectivityManager.allNetworks
} else {
if (DEBUG)
Log.d(
LOG_TAG_CONNECTION,
"networkSet is not empty, size: ${networkSet.size}"
)
networkSet.toTypedArray()
}
networks.forEach {
val cap = connectivityManager.getNetworkCapabilities(it)
val lp = connectivityManager.getLinkProperties(it)
val prop =
if (cap != null) {
val nwType =
networkType(cap) + ", NotMetered?" + isConnectionNotMetered(cap)
NetworkProperties(it, cap, lp, nwType)
} else {
null
}
if (isNetworkSame(it, activeNetwork)) {
return@forEach
}
// test for internet capability iff opPrefs.testReachability is false
if (/*hasInternet(it) == true &&*/ isVPN(it) == false) {
if (prop != null) {
newNetworks.add(prop)
}
} else {
// no-op
}
}
return newNetworks
}
private fun isIPv4Reachable(nw: Network?, isActive: Boolean = false): Boolean =
runBlocking {
coroutineScope {
// select the first reachable IP / domain and return true if any of them is
// reachable
select<Boolean> {
ip4probes.forEach { ip ->
async {
var ok = false
if (isActive) {
ok = isReachable(ip)
}
if (!ok) {
isReachableTcp(nw, ip)
}
ok
}
.onAwait { it }
}
}
.also { coroutineContext.cancelChildren() }
}
}
private fun isIPv6Reachable(nw: Network?, isActive: Boolean = false): Boolean =
runBlocking {
coroutineScope {
select<Boolean> {
ip6probes.forEach { ip ->
async {
var ok = false
if (isActive) {
ok = isReachable(ip)
}
if (!ok) {
isReachableTcp(nw, ip)
}
ok
}
.onAwait { it }
}
}
.also { coroutineContext.cancelChildren() }
}
}
private fun isReachableTcp(nw: Network?, host: String): Boolean {
try {
// https://developer.android.com/reference/android/net/Network#bindSocket(java.net.Socket)
TrafficStats.setThreadStatsTag(Thread.currentThread().id.toIntOrDefault())
val yes = tcp80(nw, host) || udp53(nw, host) || tcp53(nw, host)
if (DEBUG) Log.d(LOG_TAG_CONNECTION, "$host isReachable on network($nw): $yes")
return yes
} catch (e: Exception) {
Log.w(LOG_TAG_CONNECTION, "err isReachable: ${e.message}")
}
return false
}
private fun isReachable(host: String): Boolean {
// The 'isReachable()' function sends an ICMP echo request to the target host. In the
// event of the 'Rethink within Rethink' option being used, ICMP checks will fail.
// Ideally, there is no need to perform ICMP checks. However, 'Rethink within
// Rethink' is not supplied to this handler, these checks will be carried out but will
// result in failure.
try {
val onesec = 1000 // ms
// https://developer.android.com/reference/android/net/Network#bindSocket(java.net.Socket)
TrafficStats.setThreadStatsTag(Thread.currentThread().id.toIntOrDefault())
// https://developer.android.com/reference/java/net/InetAddress#isReachable(int)
// network.getByName() binds the socket to that network; InetAddress.getByName.
// isReachable(network-interface, ttl, timeout) cannot be used here since
// "network-interface" is a java-construct while "Network" is an android-construct
// InetAddress.getByName() will bind the socket to the default active network.
val yes = InetAddress.getByName(host).isReachable(onesec)
if (DEBUG) Log.d(LOG_TAG_CONNECTION, "$host isReachable on network: $yes")
return yes
} catch (e: Exception) {
Log.w(LOG_TAG_CONNECTION, "err isReachable: ${e.message}")
}
return false
}
// https://android.googlesource.com/platform/prebuilts/fullsdk/sources/android-30/+/refs/heads/androidx-benchmark-release/java/net/Inet6AddressImpl.java#217
private fun tcp80(nw: Network?, host: String): Boolean {
val onesec = 1000 // ms
val port80 = 80 // port
var socket: Socket? = null
try {
// port 7 is echo port, blocked by most firewalls. use port 80 instead
val s = InetSocketAddress(host, port80)
socket = Socket()
nw?.bindSocket(socket)
socket.connect(s, onesec)
val c = socket.isConnected
val b = socket.isBound
if (DEBUG) Log.d(LOG_TAG_CONNECTION, "tcpEcho: $host, ${nw?.networkHandle}: $c, $b")
return true
} catch (e: IOException) {
Log.w(LOG_TAG_CONNECTION, "err tcpEcho: ${e.message}, ${e.cause}")
val cause: Throwable = e.cause ?: return false
return (cause is ErrnoException && cause.errno == ECONNREFUSED)
} catch (e: IllegalArgumentException) {
Log.w(LOG_TAG_CONNECTION, "err tcpEcho: ${e.message}, ${e.cause}")
return false
} catch (e: SecurityException) {
Log.w(LOG_TAG_CONNECTION, "err tcpEcho: ${e.message}, ${e.cause}")
return false
} finally {
clos(socket)
}
}
private fun tcp53(nw: Network?, host: String): Boolean {
val port53 = 53 // port
var socket: Socket? = null
try {
socket = Socket()
val s = InetSocketAddress(host, port53)
nw?.bindSocket(socket)
socket.connect(s)
val c = socket.isConnected
val b = socket.isBound
if (DEBUG) Log.d(LOG_TAG_CONNECTION, "udpEcho: $host, ${nw?.networkHandle}: $c, $b")
return true
} catch (e: Exception) {
Log.w(LOG_TAG_CONNECTION, "err udpEcho: ${e.message}")
} finally {
clos(socket)
}
return false
}
private fun udp53(nw: Network?, host: String): Boolean {
val port53 = 53 // port
var socket: DatagramSocket? = null
try {
socket = DatagramSocket()
val s = InetSocketAddress(host, port53)
nw?.bindSocket(socket)
socket.connect(s)
val c = socket.isConnected
val b = socket.isBound
if (DEBUG) Log.d(LOG_TAG_CONNECTION, "udpEcho: $host, ${nw?.networkHandle}: $c, $b")
return true
} catch (e: Exception) {
Log.w(LOG_TAG_CONNECTION, "err udpEcho: ${e.message}")
} finally {
clos(socket)
}
return false
}
private fun clos(socket: Closeable?) {
try {
socket?.close()
} catch (ignored: IOException) {}
}
private fun hasInternet(network: Network?): Boolean? {
// TODO: consider checking for NET_CAPABILITY_NOT_SUSPENDED, NET_CAPABILITY_VALIDATED?
if (network == null) return false
return connectivityManager
.getNetworkCapabilities(network)
?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
}
private fun isNwValidated(network: Network): Boolean {
return connectivityManager
.getNetworkCapabilities(network)
?.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) == true
}
private fun isVPN(network: Network): Boolean? {
return connectivityManager
.getNetworkCapabilities(network)
?.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
}
// convert long to int, if the value is out of range return 10000
private fun Long.toIntOrDefault(): Int {
return if (this < Int.MIN_VALUE || this > Int.MAX_VALUE) {
10000
} else {
this.toInt()
}
}
}
}
| 361 | null | 148 | 2,928 | d618c0935011642592e958d2b420d5d154e0cd79 | 38,621 | rethink-app | Apache License 2.0 |
app/src/test/java/com/babylon/wallet/android/domain/usecases/CreateAccountWithLedgerFactorSourceUseCaseTest.kt | radixdlt | 513,047,280 | false | {"Kotlin": 3958803, "HTML": 215350, "Java": 18496, "Ruby": 2757, "Shell": 1962} | package com.babylon.wallet.android.domain.usecases
import com.babylon.wallet.android.data.repository.ResolveAccountsLedgerStateRepository
import io.mockk.coEvery
import io.mockk.mockk
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import rdx.works.profile.data.model.MnemonicWithPassphrase
import rdx.works.profile.data.model.ProfileState
import rdx.works.profile.data.model.apppreferences.Radix
import rdx.works.profile.data.model.factorsources.DerivationPathScheme
import rdx.works.profile.data.model.pernetwork.DerivationPath
import rdx.works.profile.data.model.pernetwork.addAccounts
import rdx.works.profile.data.model.pernetwork.nextAccountIndex
import rdx.works.profile.data.repository.ProfileRepository
import rdx.works.profile.derivation.model.KeyType
import rdx.works.profile.domain.TestData
internal class CreateAccountWithLedgerFactorSourceUseCaseTest {
private val testDispatcher = StandardTestDispatcher()
private val testScope = TestScope(testDispatcher)
private val resolveAccountsLedgerStateRepository = mockk<ResolveAccountsLedgerStateRepository>()
@Before
fun setUp() {
coEvery { resolveAccountsLedgerStateRepository.invoke(any()) } returns Result.failure(Exception(""))
}
@Test
fun `given profile already exists, creating new ledger account adds it to profile`() {
testScope.runTest {
// given
val mnemonicWithPassphrase = MnemonicWithPassphrase(
mnemonic = "noodle question hungry sail type offer grocery clay nation hello mixture forum",
bip39Passphrase = ""
)
val accountName = "First account"
val network = Radix.Gateway.hammunet.network
val profile = TestData.testProfile2Networks2AccountsEach(mnemonicWithPassphrase)
val profileRepository = Mockito.mock(ProfileRepository::class.java)
whenever(profileRepository.profileState).thenReturn(flowOf(ProfileState.Restored(profile)))
val createAccountWithLedgerFactorSourceUseCase = CreateAccountWithLedgerFactorSourceUseCase(
profileRepository = profileRepository,
resolveAccountsLedgerStateRepository = resolveAccountsLedgerStateRepository,
testDispatcher
)
val derivationPath = DerivationPath.forAccount(
networkId = network.networkId(),
accountIndex = profile.nextAccountIndex(
derivationPathScheme = DerivationPathScheme.CAP_26,
forNetworkId = network.networkId(),
factorSourceID = TestData.ledgerFactorSource.id
),
keyType = KeyType.TRANSACTION_SIGNING
)
val account = createAccountWithLedgerFactorSourceUseCase(
displayName = accountName,
derivedPublicKeyHex = "7229e3b98ffa35a4ce28b891ff0a9f95c9d959eff58d0e61015fab3a3b2d18f9",
derivationPath = derivationPath,
ledgerFactorSourceID = TestData.ledgerFactorSource.id
)
val updatedProfile = profile.addAccounts(
accounts = listOf(account),
onNetwork = network.networkId()
)
verify(profileRepository).saveProfile(updatedProfile)
}
}
} | 10 | Kotlin | 11 | 4 | bc98dd6b6fb563c23fcb84949d8c96cc98d5376b | 3,595 | babylon-wallet-android | Apache License 2.0 |
src/main/kotlin/Settings.kt | vchain-dev | 591,961,105 | false | null | import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
object Settings {
var scheduleDelayDuration: Duration = System.getenv()
.getOrDefault("KOTASK_SCHEDULE_DELAY_SECONDS", "60")
.toInt()
.seconds
var scheduleTTL: Duration = System.getenv()
.getOrDefault("KOTASK_SCHEDULE_CLEANUP_SECONDS", "432000")// 50 days
.toInt()
.seconds
} | 0 | Kotlin | 0 | 3 | 82d96a7edbd03612929e3ed320f55c03f6fca036 | 409 | kotask | MIT License |
library/src/main/java/io/github/chenfei0928/app/RunningEnvironmentUtil.kt | chenfei0928 | 130,954,695 | false | {"Kotlin": 1048340, "Java": 254586} | package io.github.chenfei0928.app
import android.app.ActivityManager
import android.app.Service
import android.content.Context
import androidx.core.content.getSystemService
object RunningEnvironmentUtil {
fun isServiceWork(context: Context, service: Class<out Service>): Boolean {
val runningService = context.getSystemService<ActivityManager>()
?.getRunningServices(40)
?: return false
val serviceName = service.name
return runningService.any { it.service.className == serviceName }
}
}
| 1 | Kotlin | 0 | 8 | bbe587216a2450deb19af90ea4d7d24d23443dd1 | 547 | Util | MIT License |
idea/src/org/jetbrains/kotlin/idea/highlighter/markers/OverridenFunctionMarker.kt | JetBrains | 278,369,660 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.highlighter.markers
import com.intellij.codeInsight.daemon.DaemonBundle
import com.intellij.codeInsight.navigation.BackgroundUpdaterTask
import com.intellij.ide.IdeDeprecatedMessagesBundle
import com.intellij.ide.util.MethodCellRenderer
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DumbService
import com.intellij.psi.*
import com.intellij.psi.presentation.java.ClassPresentationUtil
import com.intellij.psi.search.PsiElementProcessor
import com.intellij.psi.search.PsiElementProcessorAdapter
import com.intellij.psi.search.searches.ClassInheritorsSearch
import com.intellij.psi.search.searches.FunctionalExpressionSearch
import com.intellij.util.CommonProcessors
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.asJava.elements.isTraitFakeOverride
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.presentation.DeclarationByModuleRenderer
import org.jetbrains.kotlin.idea.search.declarationsSearch.forEachDeclaredMemberOverride
import org.jetbrains.kotlin.idea.search.declarationsSearch.forEachOverridingMethod
import org.jetbrains.kotlin.idea.search.declarationsSearch.toPossiblyFakeLightMethods
import org.jetbrains.kotlin.idea.util.isExpectDeclaration
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import java.awt.event.MouseEvent
import javax.swing.JComponent
private fun PsiMethod.isMethodWithDeclarationInOtherClass(): Boolean {
return this is KtLightMethod && this.isTraitFakeOverride()
}
internal fun <T> getOverriddenDeclarations(mappingToJava: MutableMap<PsiElement, T>, classes: Set<PsiClass>): Set<T> {
val overridden = HashSet<T>()
for (aClass in classes) {
aClass.forEachDeclaredMemberOverride { superMember, overridingMember ->
ProgressManager.checkCanceled()
val possiblyFakeLightMethods = overridingMember.toPossiblyFakeLightMethods()
possiblyFakeLightMethods.find { !it.isMethodWithDeclarationInOtherClass() }?.let {
mappingToJava.remove(superMember)?.let { declaration ->
// Light methods points to same methods
// and no reason to keep searching those methods
// those originals are found
if (mappingToJava.remove(it) == null) {
mappingToJava.values.removeIf(superMember::equals)
}
overridden.add(declaration)
}
false
}
mappingToJava.isNotEmpty()
}
}
return overridden
}
// Module-specific version of MarkerType.getSubclassedClassTooltip
fun getModuleSpecificSubclassedClassTooltip(klass: PsiClass): String? {
val processor = PsiElementProcessor.CollectElementsWithLimit(5, HashSet<PsiClass>())
ClassInheritorsSearch.search(klass).forEach(PsiElementProcessorAdapter(processor))
if (processor.isOverflow) {
return if (klass.isInterface) IdeDeprecatedMessagesBundle.message("interface.is.implemented.too.many") else DaemonBundle.message("class.is.subclassed.too.many")
}
val subclasses = processor.toArray(PsiClass.EMPTY_ARRAY)
if (subclasses.isEmpty()) {
val functionalImplementations = PsiElementProcessor.CollectElementsWithLimit(2, HashSet<PsiFunctionalExpression>())
FunctionalExpressionSearch.search(klass).forEach(PsiElementProcessorAdapter(functionalImplementations))
return if (functionalImplementations.collection.isNotEmpty())
KotlinBundle.message("highlighter.text.has.functional.implementations")
else
null
}
val start = IdeDeprecatedMessagesBundle.message(if (klass.isInterface) "interface.is.implemented.by.header" else "class.is.subclassed.by.header")
val shortcuts = ActionManager.getInstance().getAction(IdeActions.ACTION_GOTO_IMPLEMENTATION).shortcutSet.shortcuts
val shortcut = shortcuts.firstOrNull()
val shortCutText = if (shortcut != null)
KotlinBundle.message("highlighter.text.or.press", KeymapUtil.getShortcutText(shortcut))
else
""
val postfix = "<br><div style=''margin-top: 5px''><font size=''2''>" + KotlinBundle.message(
"highlighter.text.click.for.navigate",
shortCutText
) + "</font></div>"
val renderer = DeclarationByModuleRenderer()
val comparator = renderer.comparator
return subclasses.toList().sortedWith(comparator).joinToString(
prefix = "<html><body>$start", postfix = "$postfix</body</html>", separator = "<br>"
) { clazz ->
val moduleNameRequired =
(clazz.safeAs<KtLightClass>()?.kotlinOrigin ?: clazz.safeAs<KtClassOrObject>())?.let { origin ->
origin.hasActualModifier() || origin.isExpectDeclaration()
} ?: false
val moduleName = clazz.module?.name
val elementText = renderer.getElementText(clazz) + (moduleName?.takeIf { moduleNameRequired }?.let { " [$it]" } ?: "")
val refText = (moduleName?.let { "$it:" } ?: "") + ClassPresentationUtil.getNameForClass(clazz, /* qualified = */ true)
" <a href=\"#kotlinClass/$refText\">$elementText</a>"
}
}
fun getOverriddenMethodTooltip(method: PsiMethod): String? {
val processor = PsiElementProcessor.CollectElementsWithLimit<PsiMethod>(5)
method.forEachOverridingMethod(processor = PsiElementProcessorAdapter(processor)::process)
val isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT)
if (processor.isOverflow) {
return if (isAbstract) DaemonBundle.message("method.is.implemented.too.many") else DaemonBundle.message("method.is.overridden.too.many")
}
val comparator = MethodCellRenderer(false).comparator
val overridingJavaMethods = processor.collection.filter { !it.isMethodWithDeclarationInOtherClass() }.sortedWith(comparator)
if (overridingJavaMethods.isEmpty()) return null
val start = if (isAbstract) DaemonBundle.message("method.is.implemented.header") else DaemonBundle.message("method.is.overriden.header")
return com.intellij.codeInsight.daemon.impl.GutterIconTooltipHelper.composeText(
overridingJavaMethods,
start,
" {1}"
)
}
fun buildNavigateToOverriddenMethodPopup(e: MouseEvent?, element: PsiElement?): NavigationPopupDescriptor? {
val method = getPsiMethod(element) ?: return null
if (DumbService.isDumb(method.project)) {
DumbService.getInstance(method.project)
?.showDumbModeNotification(KotlinBundle.message("highlighter.notification.text.navigation.to.overriding.classes.is.not.possible.during.index.update"))
return null
}
val processor = PsiElementProcessor.CollectElementsWithLimit(2, HashSet<PsiMethod>())
if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(
{
method.forEachOverridingMethod {
runReadAction {
processor.execute(it)
}
}
},
KotlinBundle.message("highlighter.title.searching.for.overriding.declarations"),
true,
method.project,
e?.component as JComponent?
)
) {
return null
}
var overridingJavaMethods = processor.collection.filter { !it.isMethodWithDeclarationInOtherClass() }
if (overridingJavaMethods.isEmpty()) return null
val renderer = MethodCellRenderer(false)
overridingJavaMethods = overridingJavaMethods.sortedWith(renderer.comparator)
val methodsUpdater = OverridingMethodsUpdater(method, renderer.comparator)
return NavigationPopupDescriptor(
overridingJavaMethods,
methodsUpdater.getCaption(overridingJavaMethods.size),
KotlinBundle.message("highlighter.title.overriding.declarations.of", method.name),
renderer,
methodsUpdater
)
}
private class OverridingMethodsUpdater(
private val myMethod: PsiMethod,
comparator: Comparator<PsiMethod>,
) : BackgroundUpdaterTask(
myMethod.project,
KotlinBundle.message("highlighter.title.searching.for.overriding.methods"),
createComparatorWrapper { o1: PsiElement, o2: PsiElement ->
if (o1 is PsiMethod && o2 is PsiMethod) comparator.compare(o1, o2) else 0
}
) {
@Suppress("DialogTitleCapitalization")
override fun getCaption(size: Int): String {
return if (myMethod.hasModifierProperty(PsiModifier.ABSTRACT))
DaemonBundle.message("navigation.title.implementation.method", myMethod.name, size)
else
DaemonBundle.message("navigation.title.overrider.method", myMethod.name, size)
}
override fun run(indicator: ProgressIndicator) {
super.run(indicator)
val processor = object : CommonProcessors.CollectProcessor<PsiMethod>() {
override fun process(psiMethod: PsiMethod): Boolean {
if (!updateComponent(psiMethod)) {
indicator.cancel()
}
indicator.checkCanceled()
return super.process(psiMethod)
}
}
myMethod.forEachOverridingMethod { processor.process(it) }
}
}
| 191 | null | 4372 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 9,924 | intellij-kotlin | Apache License 2.0 |
kanzankazuLibs/src/main/java/com/kanzankazu/kanzanwidget/viewpager/KanzanViewPagerBottomNavView.kt | kanzankazu | 552,512,175 | false | {"Kotlin": 545150, "Java": 59675} | @file:Suppress("MemberVisibilityCanBePrivate", "DEPRECATION")
package com.kanzankazu.kanzanwidget.viewpager
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.kanzankazu.kanzanwidget.viewpager.base.BaseFragmentPagerStateAdapter
import com.kanzankazu.kanzanwidget.viewpager.widget.NoSwipeViewPager
class KanzanViewPagerBottomNavView(
private val viewPager: ViewPager,
private val bottomNavigationView: BottomNavigationView,
private val baseFragmentPagerStateAdapter: BaseFragmentPagerStateAdapter,
) {
private var isPagingEnabled = false
init {
viewPager.adapter = baseFragmentPagerStateAdapter
setPagingEnabled(isPagingEnabled)
viewPager.offscreenPageLimit = baseFragmentPagerStateAdapter.count + 1
}
fun setPageData(fragments: ArrayList<Fragment>) {
baseFragmentPagerStateAdapter.addFragments(fragments)
}
fun setPagePosition(position: Int) {
bottomNavigationView.menu.getItem(position).isChecked = true
viewPager.currentItem = position
}
fun getPagePosition(): Int {
return viewPager.currentItem
}
fun setPagingEnabled(isPagingEnabled: Boolean) {
this.isPagingEnabled = isPagingEnabled
if (viewPager is NoSwipeViewPager) viewPager.setPagingEnabled(this.isPagingEnabled)
}
fun setOnNavigationItemSelectedListener(listener: BottomNavigationView.OnNavigationItemSelectedListener) {
bottomNavigationView.setOnNavigationItemSelectedListener(listener)
}
}
| 0 | Kotlin | 0 | 0 | c030e630ee085d99531b328416e7c8ae9d2b054b | 1,619 | Kanzan_Android_Libs | Apache License 2.0 |
test/src/test/kotlin/graphql/nadel/tests/hooks/ari-transforms.kt | atlassian-labs | 121,346,908 | false | null | package graphql.nadel.tests.hooks
import graphql.language.StringValue
import graphql.nadel.Service
import graphql.nadel.ServiceExecutionHydrationDetails
import graphql.nadel.ServiceExecutionResult
import graphql.nadel.engine.NadelExecutionContext
import graphql.nadel.engine.blueprint.NadelOverallExecutionBlueprint
import graphql.nadel.engine.transform.NadelTransform
import graphql.nadel.engine.transform.NadelTransformFieldResult
import graphql.nadel.engine.transform.query.NadelQueryTransformer
import graphql.nadel.engine.transform.result.NadelResultInstruction
import graphql.nadel.engine.transform.result.json.JsonNodes
import graphql.nadel.engine.util.getField
import graphql.nadel.engine.util.makeFieldCoordinates
import graphql.nadel.engine.util.strictAssociateBy
import graphql.nadel.engine.util.toBuilder
import graphql.nadel.engine.util.toMapStrictly
import graphql.nadel.tests.EngineTestHook
import graphql.nadel.tests.UseHook
import graphql.normalized.ExecutableNormalizedField
import graphql.normalized.NormalizedInputValue
private class AriTestTransform : NadelTransform<Set<String>> {
override suspend fun isApplicable(
executionContext: NadelExecutionContext,
executionBlueprint: NadelOverallExecutionBlueprint,
services: Map<String, Service>,
service: Service,
overallField: ExecutableNormalizedField,
hydrationDetails: ServiceExecutionHydrationDetails?,
): Set<String>? {
// Let's not bother with abstract types in a test
val fieldCoords = makeFieldCoordinates(overallField.objectTypeNames.single(), overallField.name)
val fieldDef = executionBlueprint.engineSchema.getField(fieldCoords)
?: error("Unable to fetch field definition")
val fieldArgDefs = fieldDef.arguments.strictAssociateBy { it.name }
return overallField.normalizedArguments.keys
.asSequence()
.filter {
fieldArgDefs[it]?.hasDirective("interpretAri") == true
}
.toSet()
.takeIf {
it.isNotEmpty()
}
}
override suspend fun transformField(
executionContext: NadelExecutionContext,
transformer: NadelQueryTransformer,
executionBlueprint: NadelOverallExecutionBlueprint,
service: Service,
field: ExecutableNormalizedField,
state: Set<String>,
): NadelTransformFieldResult {
val fieldsArgsToInterpret = state
return NadelTransformFieldResult(
newField = field.toBuilder()
.normalizedArguments(
field.normalizedArguments
.asSequence()
.map { (key, value) ->
if (key in fieldsArgsToInterpret) {
key to NormalizedInputValue(
value.typeName,
StringValue(
// Strips the ari:/… prefix
(value.value as StringValue).value.substringAfterLast("/"),
),
)
} else {
key to value
}
}
.toMapStrictly()
)
.build(),
)
}
override suspend fun getResultInstructions(
executionContext: NadelExecutionContext,
executionBlueprint: NadelOverallExecutionBlueprint,
service: Service,
overallField: ExecutableNormalizedField,
underlyingParentField: ExecutableNormalizedField?,
result: ServiceExecutionResult,
state: Set<String>,
nodes: JsonNodes,
): List<NadelResultInstruction> {
return emptyList()
}
}
@UseHook
class `ari-argument-transform` : EngineTestHook {
override val customTransforms: List<NadelTransform<out Any>> = listOf(
AriTestTransform(),
)
}
@UseHook
class `ari-argument-transform-on-renamed-field` : EngineTestHook {
override val customTransforms: List<NadelTransform<out Any>> = listOf(
AriTestTransform(),
)
}
| 27 | null | 23 | 157 | 89f7d257c01259467c8585fea1a857369eee81f8 | 4,251 | nadel | Apache License 2.0 |
src/test/kotlin/Tests.kt | michel-souza | 59,229,923 | true | {"Kotlin": 6955} | import com.zoltu.gradle.plugin.GitVersioning
import org.jetbrains.spek.api.Spek
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class Tests : Spek({
given("a semantic version with tags describe result") {
val describeResult = "v1.2.3-beta-4.5-2-g8885517"
on("tryGetSemanticVersionInfo") {
val versionInfo = GitVersioning().getVersionInfo(describeResult)
it("parses into expected VersionInfo") {
assertNotNull(versionInfo)
assertEquals("1", versionInfo.major)
assertEquals("2", versionInfo.minor)
assertEquals("3", versionInfo.patch)
assertEquals("2", versionInfo.commitCount)
assertEquals("8885517", versionInfo.sha)
assertEquals("beta-4.5", versionInfo.tags)
assertEquals("1.2.3-beta-4.5.2", versionInfo.toString())
}
}
}
given("a semantic version without tags describe result") {
val describeResult = "v1.2.3-5-gabcd1234"
on("tryGetSemanticVersionInfo") {
val versionInfo = GitVersioning().getVersionInfo(describeResult)
it("parses into expected VersionInfo") {
assertNotNull(versionInfo)
assertEquals("1", versionInfo.major)
assertEquals("2", versionInfo.minor)
assertEquals("3", versionInfo.patch)
assertEquals("5", versionInfo.commitCount)
assertEquals("abcd1234", versionInfo.sha)
assertEquals(null, versionInfo.tags)
assertEquals("1.2.3-5", versionInfo.toString())
}
}
}
given("a simple version with tags describe result") {
val describeResult = "v1.2-tag-1.tag2.4-3-gabcd1234"
on("tryGetSemanticVersionInfo") {
val versionInfo = GitVersioning().getVersionInfo(describeResult)
it("parses into expected VersionInfo") {
assertNotNull(versionInfo)
assertEquals("1", versionInfo.major)
assertEquals("2", versionInfo.minor)
assertEquals(null, versionInfo.patch)
assertEquals("3", versionInfo.commitCount)
assertEquals("abcd1234", versionInfo.sha)
assertEquals("tag-1.tag2.4", versionInfo.tags)
assertEquals("1.2.3-tag-1.tag2.4", versionInfo.toString())
}
}
}
given("a simple version describe result") {
val describeResult = "v1.2-3-gabcd1234"
on("tryGetSemanticVersionInfo") {
val versionInfo = GitVersioning().getVersionInfo(describeResult)
it("parses into expected VersionInfo") {
assertNotNull(versionInfo)
assertEquals("1", versionInfo.major)
assertEquals("2", versionInfo.minor)
assertEquals(null, versionInfo.patch)
assertEquals("3", versionInfo.commitCount)
assertEquals("abcd1234", versionInfo.sha)
assertEquals(null, versionInfo.tags)
assertEquals("1.2.3", versionInfo.toString())
}
}
}
}) {}
| 0 | Kotlin | 0 | 0 | da34cc877cea56490c3c0ea0adf4077a3b982a40 | 2,629 | Gradle.Plugin.Versioning | Creative Commons Zero v1.0 Universal |
raft/src/main/kotlin/raft/rpc/nio/InboundChannelGroup.kt | WyattJia | 287,940,061 | false | {"Kotlin": 268400} | package raft.rpc.nio
import io.netty.channel.ChannelFuture
import io.netty.channel.ChannelFutureListener
import org.slf4j.LoggerFactory
import raft.node.NodeId
import java.util.concurrent.CopyOnWriteArrayList
import javax.annotation.concurrent.ThreadSafe
@ThreadSafe
class InboundChannelGroup {
private val channels: MutableList<NioChannel> = CopyOnWriteArrayList<NioChannel>()
fun add(remoteId: NodeId?, channel: NioChannel) {
logger.debug("channel INBOUND-{} connected", remoteId)
channel.nettyChannel.closeFuture().addListener(ChannelFutureListener { future: ChannelFuture? ->
logger.debug("channel INBOUND-{} disconnected", remoteId)
remove(channel)
})
}
private fun remove(channel: NioChannel) {
channels.remove(channel)
}
fun closeAll() {
logger.debug("close all inbound channels")
for (channel in channels) {
channel.close()
}
}
companion object {
private val logger = LoggerFactory.getLogger(InboundChannelGroup::class.java)
}
}
| 0 | Kotlin | 9 | 44 | ce055b10d422177e01a9d32ad07a789599e8d7c1 | 1,080 | Kites | MIT License |
app/src/main/java/com/mendelin/tmdb_koin/data/room/ConverterIntList.kt | MadalinBalint | 478,475,208 | false | null | package com.mendelin.tmdb_koin.data.room
import androidx.room.TypeConverter
class ConverterIntList {
@TypeConverter
fun fromList(list: List<Int>): String = list.joinToString(",")
@TypeConverter
fun toList(s: String): List<Int> {
return s.split(",")
.map { it.toInt() }
}
} | 0 | Kotlin | 0 | 0 | adc3020a33eebc2ee438434b1ab303d6a4980007 | 315 | TmdbAppKoin | Apache License 2.0 |
android/src/main/java/com/reactnativeezvizview/EzvizviewPackage.kt | zgatrying | 353,553,357 | false | null | package com.reactnativeezvizview
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager
class EzvizviewPackage : ReactPackage {
override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
return listOf(EzvizviewModule(reactContext))
}
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
return listOf(EzvizViewManager(), EzvizPlaybackViewManager())
}
}
| 1 | null | 5 | 11 | 83dda6c73b7cf0fcfc9d79191cf6cb76cb439444 | 604 | react-native-ezvizview | MIT License |
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsaccreditedprogrammesapi/unit/domain/repository/CourseRepositoryTest.kt | ministryofjustice | 615,402,552 | false | {"Kotlin": 790722, "Shell": 3835, "Dockerfile": 1421} | package uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.unit.domain.repository
import io.kotest.matchers.collections.shouldContainExactly
import io.kotest.matchers.collections.shouldHaveSize
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe
import jakarta.persistence.EntityManager
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.ActiveProfiles
import org.springframework.transaction.annotation.Transactional
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.domain.entity.create.CourseEntity
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.domain.entity.create.OfferingEntity
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.unit.domain.entity.factory.CourseEntityFactory
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.unit.domain.entity.factory.OfferingEntityFactory
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.unit.domain.entity.factory.PrerequisiteEntityFactory
@SpringBootTest
@AutoConfigureTestDatabase
@Transactional
@ActiveProfiles("test")
class CourseRepositoryTest {
@Autowired
private lateinit var entityManager: EntityManager
@Test
fun `CourseRepository should save and retrieve CourseEntity objects`() {
var courseEntity = CourseEntityFactory().produce()
courseEntity = entityManager.merge(courseEntity)
val persistedCourse = entityManager.find(CourseEntity::class.java, courseEntity.id)
persistedCourse shouldBe courseEntity
}
@Test
fun `CourseRepository should persist a CourseEntity object with prerequisites`() {
val prerequisites = mutableSetOf(
PrerequisiteEntityFactory().withName("PR1").withDescription("PR1 D1").produce(),
PrerequisiteEntityFactory().withName("PR1").withDescription("PR1 D2").produce(),
PrerequisiteEntityFactory().withName("PR2").withDescription("PR2 D1").produce(),
)
var course = CourseEntityFactory()
.withPrerequisites(prerequisites)
.produce()
course = entityManager.merge(course)
val persistedCourse = entityManager.find(CourseEntity::class.java, course.id)
persistedCourse.prerequisites shouldContainExactly prerequisites
}
@Test
fun `CourseRepository should persist multiple OfferingEntity objects for multiple CourseEntity objects and verify ids`() {
var course = CourseEntityFactory().produce()
course = entityManager.merge(course)
val offering1 = OfferingEntityFactory().withOrganisationId("BWI").withContactEmail("[email protected]").produce()
val offering2 = OfferingEntityFactory().withOrganisationId("MDI").withContactEmail("[email protected]").produce()
val offering3 = OfferingEntityFactory().withOrganisationId("BXI").withContactEmail("[email protected]").produce()
offering1.course = course
offering2.course = course
offering3.course = course
entityManager.merge(offering1)
entityManager.merge(offering2)
entityManager.merge(offering3)
course.offerings.addAll(listOf(offering1, offering2, offering3))
course = entityManager.merge(course)
val persistedCourse = entityManager.find(CourseEntity::class.java, course.id)
persistedCourse.offerings shouldHaveSize 3
persistedCourse.offerings.forEach { it.id.shouldNotBeNull() }
}
@Test
fun `CourseRepository should retrieve CourseEntity objects by their associated offering id`() {
var course = CourseEntityFactory().produce()
course = entityManager.merge(course)
var offering = OfferingEntityFactory().withOrganisationId("BWI").withContactEmail("[email protected]").produce()
offering.course = course
offering = entityManager.merge(offering)
val persistedCourse = entityManager.find(CourseEntity::class.java, course.id)
val persistedOffering = entityManager.find(OfferingEntity::class.java, offering.id)
persistedCourse shouldBe course
persistedOffering shouldBe offering
}
}
| 2 | Kotlin | 0 | 0 | c2cd05bac80ed865893237b9a1e52568583ea428 | 4,121 | hmpps-accredited-programmes-api | MIT License |
GUI/src/main/kotlin/ui/components/diffScreen/SaveCollageButton.kt | amosproj | 705,002,381 | false | {"Kotlin": 224737, "Python": 2014, "Shell": 588} | package ui.components.diffScreen
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import frameNavigation.FrameNavigation
import models.AppState
import ui.components.general.openFileSaverAndGetPath
/**
* Button to save the collage
*
* @param navigator The navigator to use to create the collage
* @param modifier The modifier for the button
* @param state The state of the app
* @return [Unit]
*/
@Composable
fun SaveCollageButton(
navigator: FrameNavigation,
modifier: Modifier,
state: MutableState<AppState>,
) {
Button(
modifier = modifier.padding(8.dp).fillMaxSize(),
onClick = { openFileSaverAndGetPath(state.value.saveCollagePath) { path -> saveCollageCallback(navigator, path, state) } },
) {
Text(text = "Save Collage")
}
}
/**
* Callback for when the user selects a file to save.
* Saves the path and creates the collage.
* @param navigator The navigator to use to create the collage
* @param path The path to the file to save to
* @param state The state of the app
*/
fun saveCollageCallback(
navigator: FrameNavigation,
path: String,
state: MutableState<AppState>,
) {
// check path for suffix
var savePath = path
if (!savePath.endsWith(".png")) {
savePath = "$savePath.png"
}
state.value.saveCollagePath = savePath
navigator.createCollage(savePath)
}
| 63 | Kotlin | 2 | 6 | 7cce92e9f56ee60abcae9bab83f3fcdc6ff18d67 | 1,664 | amos2023ws03-gui-frame-diff | MIT License |
budget-binder-multiplatform-app/src/commonMain/kotlin/de/hsfl/budgetBinder/presentation/flow/DarkModeFlow.kt | choffmann | 473,508,779 | false | null | package de.hsfl.budgetBinder.presentation.flow
import de.hsfl.budgetBinder.domain.usecase.IsDarkThemeUseCase
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
class DarkModeFlow(private val isDarkThemeUseCase: IsDarkThemeUseCase) {
val mutableDarkThemeState = MutableSharedFlow<Boolean>(replay = 0)
val darkThemeState: SharedFlow<Boolean> = mutableDarkThemeState
suspend fun initDarkMode() {
mutableDarkThemeState.emit(isDarkThemeUseCase())
}
}
| 0 | Kotlin | 0 | 4 | 8ea4138ab5bb141da097f3e4241f8c42deccd7af | 513 | budget-binder | MIT License |
src/main/kotlin/collection/builder/collectors/StringCollector.kt | Chousik | 764,806,161 | false | {"Kotlin": 48844} | package org.chousik.collection.builder.collectors
import org.chousik.collection.validators.IValidator
import exeption.InvalidDataError
import exeption.ScriptExecutionError
import org.chousik.handlers.RunHandler
import java.util.*
import kotlin.system.exitProcess
class StringCollector : ICollector<String, String?> {
private val isScript = RunHandler.mode()
private val scanner: Scanner = RunHandler.getMainScanner()
override fun ask(name: String, validator: IValidator<String?>): String {
while (true) {
try {
if (!isScript) {
println("Введите $name")
print(System.getProperty("user.name") + "> ")
}
val namePerson = scanner.nextLine().trim { it <= ' ' }
validator.valid(namePerson)
return namePerson
} catch (e: InvalidDataError) {
if (isScript) {
throw ScriptExecutionError("Поле $name не может быть пустым.")
}
println("Поле $name не может быть пустым.")
} catch (e: NullPointerException) {
if (isScript) {
throw ScriptExecutionError("Поле $name не может быть null.")
}
println("Поле $name не может быть null.")
} catch (e: NoSuchElementException) {
if (isScript) {
throw ScriptExecutionError("Ошибка во время ввода данных коллекции из файла. Конец файла.")
}
println("Не нажимай Ctrl+D((((")
exitProcess(0)
} catch (e: Exception) {
if (isScript) {
throw ScriptExecutionError("Непредвиденная ошибка")
}
println("Непредвиденная ошибка")
exitProcess(0)
}
}
}
} | 0 | Kotlin | 0 | 0 | 7b7a59bcf366ec149a4f0ab0e4da7bd9e5c4dfde | 1,893 | Lab5_Kotlin | MIT License |
simplified-profiles-api/src/main/java/org/nypl/simplified/profiles/api/ProfileDeletionEvent.kt | ThePalaceProject | 367,082,997 | false | {"Kotlin": 3269830, "JavaScript": 853788, "Java": 374503, "CSS": 65407, "HTML": 49220, "Shell": 5017, "Ruby": 178} | package org.nypl.simplified.profiles.api
/**
* The type of events raised on profile deletion.
*/
sealed class ProfileDeletionEvent : ProfileEvent() {
/**
* The ID of the profile.
*/
abstract val profileID: ProfileID
/**
* A profile was deleted successfully.
*/
data class ProfileDeletionSucceeded(
override val profileID: ProfileID
) : ProfileDeletionEvent()
/**
* A profile could not be deleted.
*/
data class ProfileDeletionFailed(
override val profileID: ProfileID,
/**
* The exception raised.
*/
val exception: Exception
) : ProfileDeletionEvent()
}
| 1 | Kotlin | 4 | 8 | 330252fd69ba690962b87d5554f71f19a85df362 | 626 | android-core | Apache License 2.0 |
app/src/main/java/cc/sovellus/vrcaa/ui/components/misc/Description.kt | Nyabsi | 745,635,224 | false | null | package cc.sovellus.vrcaa.ui.components.misc
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import cc.sovellus.vrcaa.R
@Composable
fun Description(text: String?) {
Column(
modifier = Modifier
.padding(start = 12.dp, end = 12.dp, bottom = 4.dp).fillMaxWidth()
) {
Text(
text = if (text.isNullOrEmpty()) {
stringResource(R.string.profile_text_no_biography)
} else {
text
},
textAlign = TextAlign.Left,
fontWeight = FontWeight.SemiBold
)
}
} | 1 | null | 3 | 38 | b45497cd686df2583ceb7b9cdefdd7ac2ee39b14 | 1,087 | VRCAA | Apache License 2.0 |
src/jsMain/kotlin/com/palantir/blueprintjs/select/listItemsProps.module_@blueprintjs_select.kt | HoffiMuc | 322,618,517 | false | null | @file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS")
@file:JsModule("@blueprintjs/select")
@file:JsNonModule
package com.palantir.blueprintjs.select
import React.ChangeEventHandler
import org.w3c.dom.HTMLElement
import org.w3c.dom.HTMLInputElement
import org.w3c.dom.events.Event
external interface IListItemsProps<T> : IProps {
var activeItem: dynamic /* T? | ICreateNewItem? */
get() = definedExternally
set(value) = definedExternally
var items: Array<T>
var itemsEqual: dynamic /* ItemsEqualComparator<T>? | Any */
get() = definedExternally
set(value) = definedExternally
var itemDisabled: dynamic /* Any | ((item: T, index: Number) -> Boolean)? */
get() = definedExternally
set(value) = definedExternally
var itemListPredicate: ItemListPredicate<T>?
get() = definedExternally
set(value) = definedExternally
var itemPredicate: ItemPredicate<T>?
get() = definedExternally
set(value) = definedExternally
var itemRenderer: ItemRenderer<T>
var itemListRenderer: ItemListRenderer<T>?
get() = definedExternally
set(value) = definedExternally
var initialContent: Any?
get() = definedExternally
set(value) = definedExternally
var noResults: Any?
get() = definedExternally
set(value) = definedExternally
var onActiveItemChange: ((activeItem: T?, isCreateNewItem: Boolean) -> Unit)?
get() = definedExternally
set(value) = definedExternally
var onItemSelect: (item: T, event: Event) -> Unit
var onItemsPaste: ((items: Array<T>) -> Unit)?
get() = definedExternally
set(value) = definedExternally
var onQueryChange: ((query: String, event: ChangeEventHandler<HTMLInputElement>) -> Unit)?
get() = definedExternally
set(value) = definedExternally
var createNewItemFromQuery: ((query: String) -> T)?
get() = definedExternally
set(value) = definedExternally
var createNewItemRenderer: ((query: String, active: Boolean, handleClick: React.MouseEventHandler<HTMLElement>) -> dynamic)?
get() = definedExternally
set(value) = definedExternally
var createNewItemPosition: String? /* "first" | "last" */
get() = definedExternally
set(value) = definedExternally
var resetOnQuery: Boolean?
get() = definedExternally
set(value) = definedExternally
var resetOnSelect: Boolean?
get() = definedExternally
set(value) = definedExternally
var scrollToActiveItem: Boolean?
get() = definedExternally
set(value) = definedExternally
var query: String?
get() = definedExternally
set(value) = definedExternally
}
external interface IListItemsPropsPartial<T> : IProps {
}
external fun <T> executeItemsEqual(itemsEqualProp: ItemsEqualComparator<T>?, itemA: T?, itemB: T?): Boolean
external fun <T> executeItemsEqual(itemsEqualProp: Any, itemA: T?, itemB: T?): Boolean
| 0 | Kotlin | 0 | 0 | 45d2438e7b26e4124df70bf7ed08774ee3fb0cb8 | 3,087 | web-app-react-kotlin-js-gradle | Apache License 2.0 |
plugin-dotnet-agent/src/test/kotlin/jetbrains/buildServer/dotnet/test/dotnet/discovery/MSBuildRegistryAgentPropertiesProviderTest.kt | JetBrains | 49,584,664 | false | {"Kotlin": 2711266, "C#": 319161, "Java": 95520, "Dockerfile": 831, "CSS": 123} |
package jetbrains.buildServer.dotnet.test.dotnet.discovery
import io.mockk.MockKAnnotations
import io.mockk.clearAllMocks
import io.mockk.every
import io.mockk.impl.annotations.MockK
import jetbrains.buildServer.agent.*
import jetbrains.buildServer.agent.ToolInstanceType
import jetbrains.buildServer.dotnet.discovery.MSBuildRegistryAgentPropertiesProvider
import jetbrains.buildServer.dotnet.discovery.msbuild.MSBuildValidator
import org.testng.Assert
import org.testng.annotations.BeforeMethod
import org.testng.annotations.Test
import java.io.File
class MSBuildRegistryAgentPropertiesProviderTest {
@MockK private lateinit var _windowsRegistry: WindowsRegistry
@MockK private lateinit var _msuildValidator: MSBuildValidator
@BeforeMethod
fun setUp() {
MockKAnnotations.init(this)
clearAllMocks()
}
@Test
fun shouldProvideConfigParams() {
// Given
val rootKey = WindowsRegistryKey.create(
WindowsRegistryBitness.Bitness64,
WindowsRegistryHive.LOCAL_MACHINE,
"SOFTWARE",
"Microsoft",
"MSBuild",
"ToolsVersions")
val rootKey32 = WindowsRegistryKey.create(
WindowsRegistryBitness.Bitness32,
WindowsRegistryHive.LOCAL_MACHINE,
"SOFTWARE",
"Microsoft",
"MSBuild",
"ToolsVersions")
// When
val regItems = mutableListOf<Any>(
rootKey,
rootKey + "12.0",
WindowsRegistryValue(rootKey + "12.0" + "MSBuildToolsPath", WindowsRegistryValueType.Str, "msbuild12"),
rootKey + "13.0",
WindowsRegistryValue(rootKey + "13.0" + "MSBuildToolsPath", WindowsRegistryValueType.Str, "msbuild13"),
rootKey + "14.0",
WindowsRegistryValue(rootKey + "13.0" + "MSBuildToolsPath", WindowsRegistryValueType.Long, "msbuild14"),
WindowsRegistryValue(rootKey + "15.0" + "MSBuildToolsPath", WindowsRegistryValueType.Text, "msbuild15"),
rootKey + "16.0",
WindowsRegistryValue(rootKey + "16.0" + "MSBuildToolsPathAaa", WindowsRegistryValueType.Str, "msbuild16"),
WindowsRegistryValue(rootKey32 + "17.0" + "MSBuildToolsPath", WindowsRegistryValueType.Str, "msbuild17" + File.separator)
)
every { _windowsRegistry.accept(any<WindowsRegistryKey>(), any<WindowsRegistryVisitor>(), true) } answers {
val visitor = arg<WindowsRegistryVisitor>(1)
for (item in regItems) {
when (item) {
is WindowsRegistryValue -> visitor.visit(item)
is WindowsRegistryKey -> visitor.visit(item)
}
}
regItems.clear()
value
}
every { _msuildValidator.isValid(File("msbuild12")) } returns true
every { _msuildValidator.isValid(File("msbuild13")) } returns false
every { _msuildValidator.isValid(File("msbuild17" + File.separator)) } returns true
val propertiesProvider = createInstance()
// Then
Assert.assertEquals(propertiesProvider.desription, "MSBuild in registry")
Assert.assertEquals(
propertiesProvider.properties.toList(),
listOf(
AgentProperty(ToolInstanceType.MSBuildTool, "MSBuildTools12.0_x64_Path", "msbuild12"),
AgentProperty(ToolInstanceType.MSBuildTool, "MSBuildTools17.0_x86_Path", "msbuild17")))
}
private fun createInstance() =
MSBuildRegistryAgentPropertiesProvider(
_windowsRegistry,
_msuildValidator)
} | 3 | Kotlin | 25 | 94 | cdecbf2c7721a40265a031453262614809d5378d | 3,779 | teamcity-dotnet-plugin | Apache License 2.0 |
app/src/main/java/com/thoughtworks/carapp/device/di/CarManagerModule.kt | CarOS-Android | 619,481,490 | false | null | package com.thoughtworks.carapp.device.di
import android.car.Car
import android.car.hardware.property.CarPropertyManager
import android.content.Context
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
object CarManagerModule {
@Provides
fun provideCarPropertyManager(car: Car): CarPropertyManager =
car.getCarManager(Car.PROPERTY_SERVICE) as CarPropertyManager
@Provides
fun provideCar(
@ApplicationContext context: Context
): Car = Car.createCar(context)
}
| 0 | Kotlin | 0 | 0 | c5698e7121fa4e1c11170e2feab1319f4a83af76 | 674 | CarApp-team2 | Apache License 2.0 |
src/test/kotlin/com/gdetotut/kundo/TestUndoCommand.kt | ValeriusGC | 114,362,510 | false | null | package com.gdetotut.kundo
import org.junit.Assert.assertEquals
import org.junit.Test
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
class TestUndoCommand {
/**
* Tests method [UndoCommand.id]
*/
@Test
fun id() {
assertEquals(-1, UndoCommand("", null).id())
}
/**
* Tests method [UndoCommand.mergeWith]
*/
@Test
fun mergeWith() {
val cmd = UndoCommand("mergee", null)
assertFalse(UndoCommand("", null).mergeWith(cmd))
}
/**
* Tests method [UndoCommand.childCount]
*/
@Test
fun childCount() {
val cmd = UndoCommand("", null)
assertNotNull(cmd)
assertEquals(0, cmd.childCount())
val cmdChild = UndoCommand("sub", cmd)
assertNotNull(cmdChild)
assertEquals(1, cmd.childCount())
assertEquals(0, cmdChild.childCount())
}
/**
* Tests method [UndoCommand.child]
*/
@Test
fun child() {
val cmd = UndoCommand("", null)
assertNotNull(cmd)
assertEquals(null, cmd.child(-1))
assertEquals(null, cmd.child(0))
assertEquals(null, cmd.child(1))
val cmdChild = UndoCommand("sub", cmd)
assertNotNull(cmdChild)
assertEquals(cmdChild, cmd.child(0))
assertEquals(null, cmdChild.child(-1))
assertEquals(null, cmdChild.child(0))
assertEquals(null, cmdChild.child(1))
}
@Test
fun text() {
run {
val cmd = UndoCommand("", null)
assertEquals("", cmd.text)
cmd.text = "new"
assertEquals("new", cmd.text)
}
}
} | 0 | Kotlin | 1 | 1 | bfb318932f17ec01822ac5c2cfd9864943aaf6e6 | 1,659 | kundo | Apache License 2.0 |
app/src/main/java/com/naver/maps/map/compose/demo/MapSampleActivity.kt | fornewid | 492,204,824 | false | {"Kotlin": 431651, "Shell": 2924} | /*
* Copyright 2022 SOUP
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.naver.maps.map.compose.demo
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
class MapSampleActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
NaverMapTheme {
NavGraph()
}
}
}
}
| 8 | Kotlin | 6 | 99 | 2fcbd5f18a69d58717c84e8a7367f702531f4e24 | 1,000 | naver-map-compose | Apache License 2.0 |
publishing-sdk/src/main/java/com/ably/tracking/publisher/DefaultPublisher.kt | ably | 313,556,297 | false | null | package com.ably.tracking.publisher
import android.Manifest.permission.ACCESS_COARSE_LOCATION
import android.Manifest.permission.ACCESS_FINE_LOCATION
import android.annotation.SuppressLint
import androidx.annotation.RequiresPermission
import com.ably.tracking.LocationUpdate
import com.ably.tracking.Resolution
import com.ably.tracking.TrackableState
import com.ably.tracking.common.Ably
import com.ably.tracking.logging.LogHandler
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
@SuppressLint("LogConditional")
internal class DefaultPublisher
@RequiresPermission(anyOf = [ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION])
constructor(
ably: Ably,
mapbox: Mapbox,
resolutionPolicyFactory: ResolutionPolicy.Factory,
routingProfile: RoutingProfile,
logHandler: LogHandler?,
areRawLocationsEnabled: Boolean?,
sendResolutionEnabled: Boolean,
constantLocationEngineResolution: Resolution?,
) :
Publisher {
private val core: CorePublisher
override val active: Trackable?
get() = core.active
override var routingProfile: RoutingProfile
get() = core.routingProfile
set(value) = core.enqueue(ChangeRoutingProfileEvent(value))
override val locations: SharedFlow<LocationUpdate>
get() = core.locations
override val trackables: SharedFlow<Set<Trackable>>
get() = core.trackables
override val locationHistory: SharedFlow<LocationHistoryData>
get() = core.locationHistory
init {
core = createCorePublisher(
ably,
mapbox,
resolutionPolicyFactory,
routingProfile,
logHandler,
areRawLocationsEnabled,
sendResolutionEnabled,
constantLocationEngineResolution,
)
}
override suspend fun track(trackable: Trackable): StateFlow<TrackableState> {
return suspendCoroutine { continuation ->
core.request(
TrackTrackableEvent(trackable) {
try {
continuation.resume(it.getOrThrow())
} catch (exception: Exception) {
continuation.resumeWithException(exception)
}
}
)
}
}
override suspend fun add(trackable: Trackable): StateFlow<TrackableState> {
return suspendCoroutine { continuation ->
core.request(
AddTrackableEvent(trackable) {
try {
continuation.resume(it.getOrThrow())
} catch (exception: Exception) {
continuation.resumeWithException(exception)
}
}
)
}
}
override suspend fun remove(trackable: Trackable): Boolean {
return suspendCoroutine { continuation ->
core.request(
RemoveTrackableEvent(trackable) {
try {
continuation.resume(it.getOrThrow())
} catch (exception: Exception) {
continuation.resumeWithException(exception)
}
}
)
}
}
override suspend fun stop() {
suspendCoroutine<Unit> { continuation ->
core.request(
StopEvent {
try {
continuation.resume(it.getOrThrow())
} catch (exception: Exception) {
continuation.resumeWithException(exception)
}
}
)
}
}
override fun getTrackableState(trackableId: String): StateFlow<TrackableState>? = core.trackableStateFlows[trackableId]
}
| 83 | null | 2 | 4 | e30dc588ca13e8b4ceed2af79d833350ba423667 | 3,909 | ably-asset-tracking-android | Apache License 2.0 |
compiler/testData/diagnostics/tests/when/DuplicatedLabels.kt | JakeWharton | 99,388,807 | false | null | package test
const val four = 4
fun first(arg: Int) = when (arg) {
1 -> 2
2 -> 3
<!DUPLICATE_LABEL_IN_WHEN!>1<!> -> 4
4 -> 5
<!DUPLICATE_LABEL_IN_WHEN!>1<!> -> 6
<!DUPLICATE_LABEL_IN_WHEN!>2<!> -> 7
// Error should be here: see KT-11971
four -> 8
else -> 0
}
fun second(arg: String): Int {
when (arg) {
"ABC" -> return 0
"DEF" -> return 1
<!DUPLICATE_LABEL_IN_WHEN!>"ABC"<!> -> return -1
<!DUPLICATE_LABEL_IN_WHEN!>"DEF"<!> -> return -2
}
return 42
}
fun third(arg: Any?): Int {
when (arg) {
null -> return -1
is String -> return 0
is Double -> return 1
is <!DUPLICATE_LABEL_IN_WHEN!>Double<!> -> return 2
<!DUPLICATE_LABEL_IN_WHEN!>null<!> -> return 3
else -> return 5
}
}
enum class Color { RED, GREEN, BLUE }
fun fourth(arg: Color) = when (arg) {
Color.RED -> "RED"
Color.GREEN -> "GREEN"
<!DUPLICATE_LABEL_IN_WHEN!>Color.RED<!> -> "BLUE"
Color.BLUE -> "BLUE"
}
fun fifth(arg: Any?) = when (arg) {
is Any -> "Any"
<!ELSE_MISPLACED_IN_WHEN!>else<!> -> ""
<!UNREACHABLE_CODE!>else -> null<!>
}
| 181 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 1,166 | kotlin | Apache License 2.0 |
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/focus/FocusTargetNode.kt | androidx | 256,589,781 | false | null | /*
* Copyright 2023 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.compose.ui.focus
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusDirection.Companion.Exit
import androidx.compose.ui.focus.FocusRequester.Companion.Default
import androidx.compose.ui.focus.FocusStateImpl.Active
import androidx.compose.ui.focus.FocusStateImpl.ActiveParent
import androidx.compose.ui.focus.FocusStateImpl.Captured
import androidx.compose.ui.focus.FocusStateImpl.Inactive
import androidx.compose.ui.internal.checkPreconditionNotNull
import androidx.compose.ui.layout.BeyondBoundsLayout
import androidx.compose.ui.layout.ModifierLocalBeyondBoundsLayout
import androidx.compose.ui.modifier.ModifierLocalModifierNode
import androidx.compose.ui.node.CompositionLocalConsumerModifierNode
import androidx.compose.ui.node.ModifierNodeElement
import androidx.compose.ui.node.Nodes
import androidx.compose.ui.node.ObserverModifierNode
import androidx.compose.ui.node.observeReads
import androidx.compose.ui.node.requireOwner
import androidx.compose.ui.node.visitAncestors
import androidx.compose.ui.node.visitSelfAndAncestors
import androidx.compose.ui.node.visitSubtreeIf
import androidx.compose.ui.platform.InspectorInfo
internal class FocusTargetNode(
focusability: Focusability = Focusability.Always,
private val onFocusChange: ((previous: FocusState, current: FocusState) -> Unit)? = null
) :
CompositionLocalConsumerModifierNode,
FocusTargetModifierNode,
ObserverModifierNode,
ModifierLocalModifierNode,
Modifier.Node() {
private var isProcessingCustomExit = false
private var isProcessingCustomEnter = false
// During a transaction, changes to the state are stored as uncommitted focus state. At the
// end of the transaction, this state is stored as committed focus state.
private var committedFocusState: FocusStateImpl? = null
override val shouldAutoInvalidate = false
override var focusState: FocusStateImpl
get() =
focusTransactionManager?.run { uncommittedFocusState }
?: committedFocusState
?: Inactive
set(value) {
with(requireTransactionManager()) { uncommittedFocusState = value }
}
override fun requestFocus(): Boolean {
return requestFocus(FocusDirection.Enter) ?: false
}
override var focusability: Focusability = focusability
set(value) {
if (field != value) {
field = value
// Avoid invalidating if we have not been initialized yet: there is no need to
// invalidate since these property changes cannot affect anything.
if (isAttached && committedFocusState != null) {
// Invalidate focus if needed
onObservedReadsChanged()
}
}
}
var previouslyFocusedChildHash: Int = 0
val beyondBoundsLayoutParent: BeyondBoundsLayout?
get() = ModifierLocalBeyondBoundsLayout.current
override fun onObservedReadsChanged() {
val previousFocusState = focusState
invalidateFocus()
if (previousFocusState != focusState) dispatchFocusCallbacks()
}
/** Clears focus if this focus target has it. */
override fun onDetach() {
// Note: this is called after onEndApplyChanges, so we can't schedule any nodes for
// invalidation here. If we do, they will be run on the next onEndApplyChanges.
when (focusState) {
// Clear focus from the current FocusTarget.
// This currently clears focus from the entire hierarchy, but we can change the
// implementation so that focus is sent to the immediate focus parent.
Active,
Captured -> {
requireOwner()
.focusOwner
.clearFocus(
force = true,
refreshFocusEvents = true,
clearOwnerFocus = false,
focusDirection = Exit
)
// We don't clear the owner's focus yet, because this could trigger an initial
// focus scenario after the focus is cleared. Instead, we schedule invalidation
// after onApplyChanges. The FocusInvalidationManager contains the invalidation
// logic and calls clearFocus() on the owner after all the nodes in the hierarchy
// are invalidated.
invalidateFocusTarget()
}
// This node might be reused, so reset the state to Inactive.
ActiveParent -> requireTransactionManager().withNewTransaction { focusState = Inactive }
Inactive -> {}
}
// This node might be reused, so we reset its state.
committedFocusState = null
}
/**
* Visits parent [FocusPropertiesModifierNode]s and runs
* [FocusPropertiesModifierNode.applyFocusProperties] on each parent. This effectively collects
* an aggregated focus state.
*/
internal fun fetchFocusProperties(): FocusProperties {
val properties = FocusPropertiesImpl()
properties.canFocus = focusability.canFocus(this)
visitSelfAndAncestors(Nodes.FocusProperties, untilType = Nodes.FocusTarget) {
it.applyFocusProperties(properties)
}
return properties
}
/**
* Fetch custom enter destination associated with this [focusTarget].
*
* Custom focus enter properties are specified as a lambda. If the user runs code in this lambda
* that triggers a focus search, or some other focus change that causes focus to leave the
* sub-hierarchy associated with this node, we could end up in a loop as that operation will
* trigger another invocation of the lambda associated with the focus exit property. This
* function prevents that re-entrant scenario by ensuring there is only one concurrent
* invocation of this lambda.
*/
internal inline fun fetchCustomEnter(
focusDirection: FocusDirection,
block: (FocusRequester) -> Unit
) {
if (!isProcessingCustomEnter) {
isProcessingCustomEnter = true
try {
fetchFocusProperties().enter(focusDirection).also { if (it !== Default) block(it) }
} finally {
isProcessingCustomEnter = false
}
}
}
/**
* Fetch custom exit destination associated with this [focusTarget].
*
* Custom focus exit properties are specified as a lambda. If the user runs code in this lambda
* that triggers a focus search, or some other focus change that causes focus to leave the
* sub-hierarchy associated with this node, we could end up in a loop as that operation will
* trigger another invocation of the lambda associated with the focus exit property. This
* function prevents that re-entrant scenario by ensuring there is only one concurrent
* invocation of this lambda.
*/
internal inline fun fetchCustomExit(
focusDirection: FocusDirection,
block: (FocusRequester) -> Unit
) {
if (!isProcessingCustomExit) {
isProcessingCustomExit = true
try {
fetchFocusProperties().exit(focusDirection).also { if (it !== Default) block(it) }
} finally {
isProcessingCustomExit = false
}
}
}
internal fun commitFocusState() {
with(requireTransactionManager()) {
committedFocusState =
checkPreconditionNotNull(uncommittedFocusState) {
"committing a node that was not updated in the current transaction"
}
}
}
internal fun invalidateFocus() {
if (committedFocusState == null) initializeFocusState()
when (focusState) {
// Clear focus from the current FocusTarget.
// This currently clears focus from the entire hierarchy, but we can change the
// implementation so that focus is sent to the immediate focus parent.
Active,
Captured -> {
lateinit var focusProperties: FocusProperties
observeReads { focusProperties = fetchFocusProperties() }
if (!focusProperties.canFocus) {
requireOwner().focusOwner.clearFocus(force = true)
}
}
ActiveParent,
Inactive -> {}
}
}
/**
* Triggers [onFocusChange] and sends a "Focus Event" up the hierarchy that asks all
* [FocusEventModifierNode]s to recompute their observed focus state.
*/
internal fun dispatchFocusCallbacks() {
val previousOrInactive = committedFocusState ?: Inactive
val focusState = focusState
// Avoid invoking callback when we initialize the state (from `null` to Inactive) or
// if we are detached and go from Inactive to `null` - there isn't a conceptual focus
// state change here
if (previousOrInactive != focusState) {
onFocusChange?.invoke(previousOrInactive, focusState)
}
visitSelfAndAncestors(Nodes.FocusEvent, untilType = Nodes.FocusTarget) {
// TODO(251833873): Consider caching it.getFocusState().
it.onFocusEvent(it.getFocusState())
}
}
internal object FocusTargetElement : ModifierNodeElement<FocusTargetNode>() {
override fun create() = FocusTargetNode()
override fun update(node: FocusTargetNode) {}
override fun InspectorInfo.inspectableProperties() {
name = "focusTarget"
}
override fun hashCode() = "focusTarget".hashCode()
override fun equals(other: Any?) = other === this
}
private fun initializeFocusState() {
fun FocusTargetNode.isInitialized(): Boolean = committedFocusState != null
fun isInActiveSubTree(): Boolean {
visitAncestors(Nodes.FocusTarget) {
if (!it.isInitialized()) return@visitAncestors
return when (it.focusState) {
ActiveParent -> true
Active,
Captured,
Inactive -> false
}
}
return false
}
fun hasActiveChild(): Boolean {
visitSubtreeIf(Nodes.FocusTarget) {
if (!it.isInitialized()) return@visitSubtreeIf true
return when (it.focusState) {
Active,
ActiveParent,
Captured -> true
Inactive -> false
}
}
return false
}
check(!isInitialized()) { "Re-initializing focus target node." }
requireTransactionManager().withNewTransaction {
// Note: hasActiveChild() is expensive since it searches the entire subtree. So we only
// do this if we are part of the active subtree.
focusState = if (isInActiveSubTree() && hasActiveChild()) ActiveParent else Inactive
}
}
}
internal fun FocusTargetNode.requireTransactionManager(): FocusTransactionManager {
return requireOwner().focusOwner.focusTransactionManager
}
private val FocusTargetNode.focusTransactionManager: FocusTransactionManager?
get() = node.coordinator?.layoutNode?.owner?.focusOwner?.focusTransactionManager
internal fun FocusTargetNode.invalidateFocusTarget() {
requireOwner().focusOwner.scheduleInvalidation(this)
}
| 30 | null | 950 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 12,225 | androidx | Apache License 2.0 |
foundation/src/jvmMain/kotlin/mintlin/io/encryption/Cryptic.jvm.kt | Bruce0203 | 733,929,372 | false | {"Kotlin": 566170} | package mintlin.io.encryption
import java.security.Key
import java.security.KeyPairGenerator
import java.security.MessageDigest
import java.util.*
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
internal actual val rsaCipherFactory = object : RSACipherFactory {
override fun createCipher() = object : RSACipher {
val keypair = KeyPairGenerator.getInstance("RSA")
.also { it.initialize(2048) }.genKeyPair()
override val publicKey: ByteArray = keypair.public.encoded
override val privateKey: ByteArray = keypair.private.encoded
override val verifyToken: ByteArray = ByteArray(4).apply { SplittableRandom().nextBytes(this) }
override fun decrypt(data: ByteArray): ByteArray =
encrypt(Cipher.DECRYPT_MODE, keypair.private, data)
override fun encrypt(data: ByteArray) =
encrypt(Cipher.ENCRYPT_MODE, keypair.public, data)
private fun encrypt(mode: Int, key: Key, data: ByteArray) =
Cipher.getInstance("RSA/ECB/PKCS1Padding")
.also { it.init(mode, key) }.doFinal(data)
}
}
internal actual val aesCipherFactory = object : AESCipherFactory {
override fun createAESCipher() = object : AESCipher {
lateinit var javaSecretKey: JavaSecretKey
override fun setSecretKey(data: ByteArray) {
javaSecretKey = JavaSecretKey(data)
}
override fun decrypt(data: ByteArray) = javaSecretKey.decryptionKey.update(data)
override fun encrypt(data: ByteArray) = javaSecretKey.encryptionKey.update(data)
}
inner class JavaSecretKey(secretKey: ByteArray) {
val javaSecretKey = SecretKeySpec(secretKey, "AES")
val encryptionKey = getCipher(Cipher.ENCRYPT_MODE, javaSecretKey)
val decryptionKey = getCipher(Cipher.DECRYPT_MODE, javaSecretKey)
private fun getCipher(mode: Int, key: Key) =
Cipher.getInstance("AES/CFB8/NoPadding")
.apply { init(mode, key, IvParameterSpec(key.encoded)) }
}
}
actual val digester = object : Digester {
override fun digest(data: String, publicKey: ByteArray, secretKey: ByteArray): ByteArray? {
return try {
val digest = MessageDigest.getInstance("SHA-1")
digest.update(data.toByteArray(charset("ISO_8859_1")))
digest.update(secretKey)
digest.update(publicKey)
digest.digest()
} catch (_: Throwable) { null }
}
} | 1 | Kotlin | 0 | 8 | 32e28dd71b7357b74cb68fa9aa262b82da0441e2 | 2,529 | Mintlin | The Unlicense |
app/src/main/java/com/battlelancer/seriesguide/jobs/movies/MovieJob.kt | UweTrottmann | 1,990,682 | false | null | // Copyright 2023 <NAME>
// SPDX-License-Identifier: Apache-2.0
package com.battlelancer.seriesguide.jobs.movies
import android.content.Context
import com.battlelancer.seriesguide.jobs.BaseFlagJob
import com.battlelancer.seriesguide.jobs.SgJobInfo
import com.battlelancer.seriesguide.jobs.episodes.JobAction
import com.battlelancer.seriesguide.movies.tools.MovieTools.MovieChangedEvent
import com.google.flatbuffers.FlatBufferBuilder
import org.greenrobot.eventbus.EventBus
abstract class MovieJob(
action: JobAction,
private val movieTmdbId: Int,
private val plays: Int
) : BaseFlagJob(action) {
override fun supportsHexagon(): Boolean {
return true
}
override fun supportsTrakt(): Boolean {
return true
}
override fun applyLocalChanges(context: Context, requiresNetworkJob: Boolean): Boolean {
// prepare network job
var networkJobInfo: ByteArray? = null
if (requiresNetworkJob) {
networkJobInfo = prepareNetworkJob()
if (networkJobInfo == null) {
return false
}
}
if (!applyDatabaseUpdate(context, movieTmdbId)) {
return false
}
// persist network job after successful local updates
if (requiresNetworkJob) {
if (!persistNetworkJob(context, networkJobInfo!!)) {
return false
}
}
// post event to update button states
EventBus.getDefault().post(MovieChangedEvent(movieTmdbId))
return true
}
protected abstract fun applyDatabaseUpdate(context: Context, movieTmdbId: Int): Boolean
private fun prepareNetworkJob(): ByteArray? {
val builder = FlatBufferBuilder(0)
val jobInfo = SgJobInfo.createSgJobInfo(builder, 0, 0, movieTmdbId, plays, 0)
builder.finish(jobInfo)
return builder.sizedByteArray()
}
} | 56 | null | 403 | 1,966 | c7bc6445ecc58b841c1887a56146dc2d2f817007 | 1,909 | SeriesGuide | Apache License 2.0 |
source-code/final-project/app/src/main/java/com/droidcon/authenticate/di/FirebaseModule.kt | droidcon-academy | 611,559,196 | false | {"Kotlin": 149803} | package com.droidcon.authenticate.di
import com.droidcon.authenticate.data.AuthService
import com.droidcon.authenticate.data.FirebaseAuthService
import com.droidcon.authenticate.data.FirestoreUserDataSource
import com.droidcon.authenticate.data.UserDataSource
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object FirebaseModule {
@Singleton
@Provides
fun provideFirebaseAuth(): FirebaseAuth {
return FirebaseAuth.getInstance()
}
@Singleton
@Provides
fun provideFirebaseFirestore(): FirebaseFirestore {
return FirebaseFirestore.getInstance()
}
@Singleton
@Provides
fun provideFirebaseAuthService(firebaseAuth: FirebaseAuth): AuthService {
return FirebaseAuthService(firebaseAuth)
}
@Singleton
@Provides
fun provideUserDatasource(
firebaseFirestore: FirebaseFirestore,
firebaseAuth: FirebaseAuth
): UserDataSource {
return FirestoreUserDataSource(firebaseFirestore, firebaseAuth)
}
} | 0 | Kotlin | 0 | 0 | e630897e04481a54a9e73f2c7f013674c89ab0ff | 1,198 | android-firebase-authentication-study-materials | Apache License 2.0 |
translator/core/src/main/kotlin/RawString.kt | curinator | 207,578,255 | true | {"Kotlin": 3731711, "TypeScript": 587148, "HTML": 201325, "CSS": 60702, "JavaScript": 4142, "Shell": 2610} | /*
* Copyright (C) 2017 VSCT
*
* 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 fr.vsct.tock.translator
/**
* A raw string is a string that should not be translated.
*/
data class RawString(private val wrapped: CharSequence)
: CharSequence by wrapped {
override fun toString(): String {
return wrapped.toString()
}
override fun subSequence(startIndex: Int, endIndex: Int): CharSequence {
return RawString(wrapped.subSequence(startIndex, endIndex))
}
} | 0 | null | 0 | 1 | dd37ec79ba29b4f6aacff704ca3400b41df47efb | 1,011 | tock | Apache License 2.0 |
app/src/main/java/com/kcteam/features/stockAddCurrentStock/adapter/AdapterShowStockList.kt | DebashisINT | 558,234,039 | false | null | package com.breezesalesoriplast.features.stockAddCurrentStock.adapter
import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.breezesalesoriplast.R
import com.breezesalesoriplast.app.Pref
import com.breezesalesoriplast.app.domain.CurrentStockEntryModelEntity
import com.breezesalesoriplast.app.types.FragType
import com.breezesalesoriplast.features.dashboard.presentation.DashboardActivity
import com.breezesalesoriplast.features.stockAddCurrentStock.UpdateShopStockFragment
import com.breezesalesoriplast.features.stockAddCurrentStock.`interface`.ShowStockOnClick
import kotlinx.android.synthetic.main.row_show_stock_list.view.*
import kotlinx.android.synthetic.main.row_show_stock_list.view.stock_date_tv
import kotlinx.android.synthetic.main.row_show_stock_list.view.stock_qty_tv
import kotlinx.android.synthetic.main.row_show_stock_list.view.sync_status_iv
import kotlinx.android.synthetic.main.row_show_stock_list.view.tv_stock_view
import kotlinx.android.synthetic.main.row_view_competetor_stock_list.view.*
//1.0 Rev AdapterShowStockList AppV 4.0.8 saheli 12/05/2023 mantis 26102
class AdapterShowStockList(val context: Context, val stockList: List<CurrentStockEntryModelEntity>,val listner: ShowStockOnClick): RecyclerView.Adapter<AdapterShowStockList.ShowStockViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ShowStockViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.row_show_stock_list,parent,false)
return ShowStockViewHolder(view)
}
override fun getItemCount(): Int {
return stockList!!.size
}
override fun onBindViewHolder(holder: ShowStockViewHolder, position: Int) {
holder.tv_stock_date.text=stockList!!.get(position).visited_date
holder.tv_stock_qty.text=stockList!!.get(position).total_product_stock_qty
if(stockList.get(position).isUploaded!!){
holder.iv_sync.setImageResource(R.drawable.ic_registered_shop_sync)
}else{
holder.iv_sync.setImageResource(R.drawable.ic_registered_shop_not_sync)
}
holder.tv_stock_view.setOnClickListener { listner.stockListOnClick(stockList!!.get(position).stock_id!!) }
//1.0 start Rev AdapterShowStockList AppV 4.0.8 saheli 12/05/2023 mantis 26102
if(Pref.isCurrentStockEnable){
if(Pref.IsCurrentStockApplicableforAll){
if(Pref.IsAttachmentAvailableForCurrentStock){
holder.tv_attach.visibility = View.VISIBLE
}else{
holder.tv_attach.visibility = View.GONE
}
}else{
holder.tv_attach.visibility = View.GONE
}
}else{
holder.tv_attach.visibility = View.GONE
}
holder.tv_attach.setOnClickListener{listner.stockattachment(stockList!!.get(position).stock_id!!)}
//1.0 end Rev AdapterShowStockList AppV 4.0.8 saheli 12/05/2023 mantis 26102
}
inner class ShowStockViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
val tv_stock_date = itemView.stock_date_tv
val tv_stock_qty = itemView.stock_qty_tv
val tv_stock_view = itemView.tv_stock_view
val iv_sync=itemView.sync_status_iv
//1.0 start Rev AdapterShowStockList AppV 4.0.8 saheli 12/05/2023 mantis 26101
val tv_attach = itemView.iv_attach_row_shop_stock_list
//1.0 end Rev AdapterShowStockList AppV 4.0.8 saheli 12/05/2023 mantis 26101
}
} | 0 | null | 1 | 1 | e6114824d91cba2e70623631db7cbd9b4d9690ed | 3,636 | NationalPlastic | Apache License 2.0 |
tabler-icons/src/commonMain/kotlin/compose/icons/tablericons/DotsDiagonal.kt | DevSrSouza | 311,134,756 | false | null | 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.DotsDiagonal: ImageVector
get() {
if (_dotsDiagonal != null) {
return _dotsDiagonal!!
}
_dotsDiagonal = Builder(name = "DotsDiagonal", 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(7.0f, 17.0f)
moveToRelative(-1.0f, 0.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, false, 2.0f, 0.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, false, -2.0f, 0.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(12.0f, 12.0f)
moveToRelative(-1.0f, 0.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, false, 2.0f, 0.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, false, -2.0f, 0.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(17.0f, 7.0f)
moveToRelative(-1.0f, 0.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, false, 2.0f, 0.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, false, -2.0f, 0.0f)
}
}
.build()
return _dotsDiagonal!!
}
private var _dotsDiagonal: ImageVector? = null
| 17 | null | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 2,685 | compose-icons | MIT License |
app/src/main/java/com/tz/basicsmvp/mvp/base/BaseUIController.kt | yuchen931201 | 198,957,829 | false | null | package com.tz.basicsmvp.mvp.base
import android.app.Activity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import com.tz.basicsmvp.R
import com.tz.basicsmvp.mvp.base.BaseActivity.Companion.TYPE_FULL_SCREEN
import com.tz.basicsmvp.mvp.base.BaseActivity.Companion.TYPE_TITLE_MAIN
import com.tz.basicsmvp.mvp.base.BaseActivity.Companion.TYPE_TITLE_NORMAL
import com.tz.basicsmvp.mvp.view.widget.MultipleStatusView
import com.tz.basicsmvp.utils.core.strategy.loadImage
import com.tz.basicsmvp.utils.statusBar.StatusBarUtil
/**
* @ComputerCode: tianzhen
* @Author: TianZhen
* @QQ: 959699751
* @CreateTime: Created on 2019/8/2 16:30
* @Package: com.tz.basicsmvp.mvp.base
* @Description:
**/
class BaseUIController<T> constructor(t: T) : IBaseUIController where T : Activity, T : IBaseActivity {
private val activity: T by lazy { t }
private var statusView: MultipleStatusView? = null
private var iv_left: ImageView? =null
private var iv_right: ImageView? =null
private var line_view: View? =null
private var title_bar: View? =null
private var tv_title: TextView? =null
private var tool_bar: Toolbar? =null
override fun getRootView() :View{
val inflater = LayoutInflater.from(activity)
val v: View
when (activity.layoutType()) {
TYPE_TITLE_NORMAL -> {
v = inflater.inflate(R.layout.root_title_view, null)
iv_left = v.findViewById(R.id.iv_left)
loadImage(R.drawable.ic_left_black,iv_left)
title_bar = v.findViewById(R.id.title_bar)
iv_right = v.findViewById(R.id.iv_right)
tv_title = v.findViewById(R.id.tv_title)
tool_bar = v.findViewById(R.id.tool_bar)
iv_left?.setOnClickListener {
activity.finish()
}
}
TYPE_FULL_SCREEN -> {
v = inflater.inflate(R.layout.root_full_screen_view, null)
}
TYPE_TITLE_MAIN ->{
v = inflater.inflate(R.layout.root_title_view, null)
iv_left = v.findViewById(R.id.iv_left)
loadImage(R.drawable.ic_home_black_24dp,iv_left)
iv_right = v.findViewById(R.id.iv_right)
loadImage(R.drawable.ic_dehaze_black_24dp,iv_right)
title_bar = v.findViewById(R.id.title_bar)
line_view = v.findViewById(R.id.line_view)
tv_title = v.findViewById(R.id.tv_title)
tv_title?.text = "主页"
tool_bar = v.findViewById(R.id.tool_bar)
}
else -> {
v = inflater.inflate(R.layout.root_title_view, null)
}
}
statusView = v.findViewById(R.id.status_view)
val rootView: ViewGroup = v.findViewById(R.id.root_view)
rootView.addView(inflater.inflate(activity.layoutId(), null).apply {
layoutParams =
ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
})
initListener()
return v
}
override fun setTitle(s: String){
tv_title?.text = s
}
override fun setLeftImage(any: Any){
loadImage(any,iv_left)
}
override fun setLeftClick(click: View.OnClickListener){
iv_left?.setOnClickListener(click)
}
override fun setRightImage(any: Any){
loadImage(any,iv_right)
}
override fun setRightClick(click: View.OnClickListener){
iv_right?.setOnClickListener(click)
}
override fun setLineColor(color: Int){
line_view?.setBackgroundColor(color)
}
override fun setToolbarColor(color: Int) {
tool_bar?.setBackgroundColor(color)
}
override fun setTitleBarColor(color: Int) {
title_bar?.setBackgroundColor(color)
}
override fun setStatusBarFontDark(dark: Boolean) {
try {
StatusBarUtil.setStatusBarDarkTheme(activity,dark)
}catch (e: Exception){
e.printStackTrace()
}
}
override fun getStatusBarHeight(): Int {
var statusBarHeight = 0
val resourceId = activity.resources.getIdentifier("status_bar_height", "dimen", "android")
if (resourceId > 0) {
statusBarHeight = activity.resources.getDimensionPixelSize(resourceId)
}
return statusBarHeight
}
override fun getToolbar(): Toolbar?{
return tool_bar
}
override fun getStatusView(): MultipleStatusView? {
return statusView
}
private fun initListener() {
getStatusView()?.setOnClickListener(mRetryClickListener)//MultipleStatusView多种状态的 View 的切换
}
private val mRetryClickListener: View.OnClickListener = View.OnClickListener {
activity.doScene()
}
override fun onDestroy() {
// 做一些回收的操作
}
} | 1 | null | 1 | 3 | e9fc3b4d8a1b75e7213297c54fea036afebbe917 | 5,044 | BasicsMVP | Apache License 2.0 |
app/src/main/kotlin/net/primal/android/profile/details/ProfileDetailsContract.kt | PrimalHQ | 639,579,258 | false | null | package net.primal.android.profile.details
import androidx.paging.PagingData
import kotlinx.coroutines.flow.Flow
import net.primal.android.core.compose.feed.model.FeedPostUi
import net.primal.android.core.compose.feed.model.ZappingState
import net.primal.android.core.compose.profile.model.ProfileDetailsUi
import net.primal.android.core.compose.profile.model.ProfileStatsUi
import net.primal.android.profile.domain.ProfileFeedDirective
import net.primal.android.profile.report.ReportType
interface ProfileDetailsContract {
data class UiState(
val profileId: String,
val isActiveUser: Boolean,
val isProfileFollowed: Boolean = false,
val isProfileFollowingMe: Boolean = false,
val isProfileMuted: Boolean = false,
val isProfileFeedInActiveUserFeeds: Boolean = false,
val profileDetails: ProfileDetailsUi? = null,
val profileStats: ProfileStatsUi? = null,
val referencedProfilesData: Set<ProfileDetailsUi> = emptySet(),
val zappingState: ZappingState = ZappingState(),
val notes: Flow<PagingData<FeedPostUi>>,
val profileDirective: ProfileFeedDirective = ProfileFeedDirective.AuthoredNotes,
val error: ProfileError? = null,
) {
sealed class ProfileError {
data class MissingLightningAddress(val cause: Throwable) : ProfileError()
data class InvalidZapRequest(val cause: Throwable) : ProfileError()
data class FailedToPublishZapEvent(val cause: Throwable) : ProfileError()
data class FailedToPublishRepostEvent(val cause: Throwable) : ProfileError()
data class FailedToPublishLikeEvent(val cause: Throwable) : ProfileError()
data class MissingRelaysConfiguration(val cause: Throwable) : ProfileError()
data class FailedToFollowProfile(val cause: Throwable) : ProfileError()
data class FailedToUnfollowProfile(val cause: Throwable) : ProfileError()
data class FailedToAddToFeed(val cause: Throwable) : ProfileError()
data class FailedToRemoveFeed(val cause: Throwable) : ProfileError()
data class FailedToMuteProfile(val cause: Throwable) : ProfileError()
data class FailedToUnmuteProfile(val cause: Throwable) : ProfileError()
}
}
sealed class UiEvent {
data class PostLikeAction(val postId: String, val postAuthorId: String) : UiEvent()
data class RepostAction(
val postId: String,
val postAuthorId: String,
val postNostrEvent: String,
) : UiEvent()
data class ZapAction(
val postId: String,
val postAuthorId: String,
val zapAmount: ULong?,
val zapDescription: String?,
) : UiEvent()
data class FollowAction(val profileId: String) : UiEvent()
data class UnfollowAction(val profileId: String) : UiEvent()
data class AddUserFeedAction(val name: String, val directive: String) : UiEvent()
data class RemoveUserFeedAction(val directive: String) : UiEvent()
data class MuteAction(val profileId: String) : UiEvent()
data class UnmuteAction(val profileId: String) : UiEvent()
data class ChangeProfileFeed(val profileDirective: ProfileFeedDirective) : UiEvent()
data object RequestProfileUpdate : UiEvent()
data class ReportAbuse(
val reportType: ReportType,
val profileId: String,
val noteId: String? = null,
) : UiEvent()
data object DismissError : UiEvent()
}
}
| 56 | null | 6 | 98 | 438072af7f67762c71c5dceffa0c83dedd8e2e85 | 3,593 | primal-android-app | MIT License |
src/main/kotlin/com/turbomates/hoplite/PrefixRemovalPreprocessor.kt | turbomates | 501,400,869 | false | null | package com.turbomates.hoplite
import com.sksamuel.hoplite.ArrayNode
import com.sksamuel.hoplite.ConfigResult
import com.sksamuel.hoplite.MapNode
import com.sksamuel.hoplite.Node
import com.sksamuel.hoplite.PrimitiveNode
import com.sksamuel.hoplite.fp.valid
import com.sksamuel.hoplite.preprocessor.Preprocessor
class PrefixRemovalPreprocessor(private val prefix: String) : Preprocessor {
override fun process(node: Node): ConfigResult<Node> {
val newNode = when (node) {
is MapNode -> {
val prefixNode = node.map[prefix.lowercase()] ?: node.map[prefix.uppercase()]
val nodeMap = if (prefixNode is MapNode) node.map + prefixNode.map else node.map
MapNode(nodeMap.map { (k, v) -> k to process(v).getUnsafe() }.toMap(), node.pos, node.path, node.value)
}
is ArrayNode -> ArrayNode(node.elements.map { process(it).getUnsafe() }, node.pos, node.path)
is PrimitiveNode -> node
else -> node
}
return newNode.valid()
}
}
| 0 | Kotlin | 0 | 0 | 7e3c83de41ac1682d026687d22789733e176b716 | 1,058 | hoplite | MIT License |
src/test/kotlin/org/jetbrains/plugins/feature/suggester/suggesters/unwrap/UnwrapSuggesterKotlinTest.kt | JetBrains | 10,263,181 | false | null | package org.jetbrains.plugins.feature.suggester.suggesters.unwrap
import junit.framework.TestCase
import org.jetbrains.plugins.feature.suggester.NoSuggestion
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class UnwrapSuggesterKotlinTest : UnwrapSuggesterTest() {
override val testingCodeFileName = "KotlinCodeExample.kt"
@Test
override fun `testUnwrap IF statement and get suggestion`() {
moveCaretToLogicalPosition(11, 9)
deleteSymbolAtCaret()
selectBetweenLogicalPositions(lineStartIndex = 9, columnStartIndex = 42, lineEndIndex = 9, columnEndIndex = 3)
deleteSymbolAtCaret()
testInvokeLater {
assertSuggestedCorrectly()
}
}
@Test
override fun `testUnwrap one-line IF and get suggestion`() {
selectBetweenLogicalPositions(lineStartIndex = 31, columnStartIndex = 23, lineEndIndex = 31, columnEndIndex = 8)
deleteSymbolAtCaret()
moveCaretRelatively(6, 0)
deleteSymbolAtCaret()
testInvokeLater {
assertSuggestedCorrectly()
}
}
@Test
override fun `testUnwrap IF with deleting multiline selection and get suggestion`() {
selectBetweenLogicalPositions(lineStartIndex = 8, columnStartIndex = 23, lineEndIndex = 10, columnEndIndex = 5)
deleteSymbolAtCaret()
moveCaretToLogicalPosition(9, 9)
deleteSymbolAtCaret()
testInvokeLater {
assertSuggestedCorrectly()
}
}
@Test
override fun `testUnwrap FOR and get suggestion`() {
selectBetweenLogicalPositions(lineStartIndex = 22, columnStartIndex = 34, lineEndIndex = 22, columnEndIndex = 9)
deleteSymbolAtCaret()
moveCaretToLogicalPosition(25, 13)
deleteSymbolAtCaret()
testInvokeLater {
assertSuggestedCorrectly()
}
}
@Test
override fun `testUnwrap WHILE and get suggestion`() {
selectBetweenLogicalPositions(lineStartIndex = 27, columnStartIndex = 27, lineEndIndex = 27, columnEndIndex = 0)
deleteSymbolAtCaret()
moveCaretToLogicalPosition(30, 13)
deleteSymbolAtCaret()
testInvokeLater {
assertSuggestedCorrectly()
}
}
@Test
override fun `testUnwrap commented IF and don't get suggestion`() {
insertNewLineAt(21, 12)
type(
"""//if(true) {
|//i++; j--;
|//}""".trimMargin()
)
selectBetweenLogicalPositions(
lineStartIndex = 21,
columnStartIndex = 14,
lineEndIndex = 21,
columnEndIndex = 24
)
deleteSymbolAtCaret()
moveCaretToLogicalPosition(23, 15)
deleteSymbolAtCaret()
testInvokeLater {
TestCase.assertTrue(expectedSuggestion is NoSuggestion)
}
}
@Test
override fun `testUnwrap IF written in string block and don't get suggestion`() {
insertNewLineAt(21, 12)
type("val s = \"\"\"if(true) {\ni++\nj--\n}")
selectBetweenLogicalPositions(
lineStartIndex = 21,
columnStartIndex = 23,
lineEndIndex = 21,
columnEndIndex = 33
)
deleteSymbolAtCaret()
moveCaretToLogicalPosition(24, 18)
deleteSymbolAtCaret()
testInvokeLater {
TestCase.assertTrue(expectedSuggestion is NoSuggestion)
}
}
}
| 11 | null | 5 | 7 | 266934e25a8c277e3706ed5bcd00f6bf891b2426 | 3,498 | intellij-feature-suggester | Apache License 2.0 |
plugins/amazonq/chat/jetbrains-community/src/software/aws/toolkits/jetbrains/services/amazonq/gettingstarted/QGettingStartedEditorProvider.kt | aws | 91,485,909 | false | null | // Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.aws.toolkits.jetbrains.services.amazonq.gettingstarted
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.FileEditorPolicy
import com.intellij.openapi.fileEditor.FileEditorProvider
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
class QGettingStartedEditorProvider : FileEditorProvider, DumbAware {
override fun accept(project: Project, file: VirtualFile) = file is QGettingStartedVirtualFile
override fun createEditor(project: Project, file: VirtualFile): FileEditor {
file as QGettingStartedVirtualFile
return QGettingStartedEditor(project, file)
}
override fun getEditorTypeId() = EDITOR_TYPE
override fun getPolicy() = FileEditorPolicy.HIDE_DEFAULT_EDITOR
companion object {
const val EDITOR_TYPE = "QGettingStartedUxMainPanel"
}
}
| 519 | null | 220 | 757 | a81caf64a293b59056cef3f8a6f1c977be46937e | 1,050 | aws-toolkit-jetbrains | Apache License 2.0 |
form/src/main/java/cl/emilym/form/field/base/LabeledFormField.kt | emilymclean | 621,143,157 | false | {"Kotlin": 138002} | package cl.emilym.form.field.base
/**
* An interface representing a form field with a label for its value.
*
* @param T The type of value this form field can hold.
*/
interface LabeledFormField<T> {
/**
* Gets the label corresponding to the provided value.
*
* @param value The value for which the label is required.
* @return The label associated with the provided value, or null if no label is available.
*/
fun getLabel(value: T?): String?
} | 0 | Kotlin | 0 | 0 | 6d6eb8cbcd2ea2a6362a64d3ac61a8692a01fa32 | 484 | JetpackForms | MIT License |
app/src/main/java/com/guru/composecookbook/ui/learnwidgets/Layouts.kt | Gurupreet | 293,227,683 | false | null | package com.guru.composecookbook.ui.learnwidgets
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.Card
import androidx.compose.material.OutlinedButton
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import com.guru.composecookbook.theme.green200
import com.guru.composecookbook.theme.green500
import com.guru.composecookbook.theme.green700
import com.guru.composecookbook.theme.typography
import com.guru.composecookbook.ui.utils.TestTags
@Composable
fun Layouts() {
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
TypesOfRows()
TypeOfColumns()
TypeOfBoxs()
ConstraintLayouts()
}
}
@Composable
fun TypesOfRows() {
Text(text = "Rows", style = typography.h6, modifier = Modifier.padding(8.dp))
Text(
text = "Arrangement.Start ", style = typography.caption,
modifier = Modifier.padding(8.dp)
)
Row(
horizontalArrangement = Arrangement.Start,
modifier = Modifier
.padding(8.dp)
.fillMaxWidth()
.testTag(TestTags.HOME_LAYOUTS_ROW_START)
) {
MultipleTexts()
}
Text(
text = "Arrangement.End ", style = typography.caption,
modifier = Modifier.padding(8.dp)
)
Row(
horizontalArrangement = Arrangement.End, modifier = Modifier
.padding(8.dp)
.fillMaxWidth()
.testTag(TestTags.HOME_LAYOUTS_ROW_END)
) {
MultipleTexts()
}
Text(
text = "Arrangement.Center ", style = typography.caption,
modifier = Modifier.padding(8.dp)
)
Row(
horizontalArrangement = Arrangement.Center,
modifier = Modifier
.padding(8.dp)
.fillMaxWidth()
.testTag(TestTags.HOME_LAYOUTS_ROW_CENTER)
) {
MultipleTexts()
}
Text(
text = "Arrangement.SpaceAround ", style = typography.caption,
modifier = Modifier.padding(8.dp)
)
Row(
horizontalArrangement = Arrangement.SpaceAround,
modifier = Modifier
.padding(8.dp)
.fillMaxWidth()
.testTag(TestTags.HOME_LAYOUTS_ROW_SPACE_AROUND)
) {
MultipleTexts()
}
Text(
text = "Arrangement.SpaceBetween ", style = typography.caption,
modifier = Modifier.padding(8.dp)
)
Row(
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
.padding(8.dp)
.fillMaxWidth()
.testTag(TestTags.HOME_LAYOUTS_ROW_SPACE_BETWEEN)
) {
MultipleTexts()
}
Text(
text = "Arrangement.SpaceEvenly ", style = typography.caption,
modifier = Modifier.padding(8.dp)
)
Row(
horizontalArrangement = Arrangement.SpaceEvenly,
modifier = Modifier
.padding(8.dp)
.fillMaxWidth()
.testTag(TestTags.HOME_LAYOUTS_ROW_SPACE_EVENLY)
) {
MultipleTexts()
}
}
@Composable
fun TypeOfColumns() {
val columnModifier = Modifier
.padding(8.dp)
.fillMaxWidth()
.height(150.dp)
.background(Color.LightGray)
Text(text = "Column", style = typography.h6, modifier = Modifier.padding(8.dp))
Text(
text = "Arrangement.Top", style = typography.caption,
modifier = Modifier.padding(8.dp)
)
Column(
verticalArrangement = Arrangement.Top, modifier = columnModifier
.testTag(TestTags.HOME_LAYOUTS_COLUMN_TOP)
) {
MultipleTexts()
}
Text(
text = "Arrangement.Bottom", style = typography.caption,
modifier = Modifier.padding(8.dp)
)
Column(
verticalArrangement = Arrangement.Bottom,
modifier = columnModifier
.testTag(TestTags.HOME_LAYOUTS_COLUMN_BOTTOM)
) {
MultipleTexts()
}
Text(
text = "Arrangement.Center + Alignment.CenterHorizontally", style = typography.caption,
modifier = Modifier.padding(8.dp)
)
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = columnModifier
.testTag(TestTags.HOME_LAYOUTS_COLUMN_CENTER)
) {
MultipleTexts()
}
Text(
text = "Arrangement.SpaceAround", style = typography.caption,
modifier = Modifier.padding(8.dp)
)
Column(
verticalArrangement = Arrangement.SpaceAround,
modifier = columnModifier
.testTag(TestTags.HOME_LAYOUTS_COLUMN_SPACE_AROUND)
) {
MultipleTexts()
}
Text(
text = "Arrangement.SpaceEvenly", style = typography.caption,
modifier = Modifier.padding(8.dp)
)
Column(
verticalArrangement = Arrangement.SpaceEvenly,
modifier = columnModifier
.testTag(TestTags.HOME_LAYOUTS_COLUMN_SPACE_EVENLY)
) {
MultipleTexts()
}
Text(
text = "Arrangement.SpaceBetween", style = typography.caption,
modifier = Modifier.padding(8.dp)
)
Column(
verticalArrangement = Arrangement.SpaceBetween,
modifier = columnModifier
.testTag(TestTags.HOME_LAYOUTS_COLUMN_SPACE_BETWEEN)
) {
MultipleTexts()
}
}
@Composable
fun TypeOfBoxs() {
Text(text = "Box", style = typography.h6, modifier = Modifier.padding(8.dp))
val boxModifier = Modifier
.padding(8.dp)
.background(Color.LightGray)
.fillMaxWidth()
.height(250.dp)
Text(
text = "Children with no align", style = typography.caption,
modifier = Modifier.padding(8.dp)
)
Box(
modifier = boxModifier
.testTag(TestTags.HOME_LAYOUTS_BOX_NO_ALIGN)
) {
Card(
backgroundColor = green700,
elevation = 4.dp,
modifier = Modifier.size(200.dp)
) {}
Card(
backgroundColor = green500,
elevation = 4.dp,
modifier = Modifier.size(150.dp)
) {}
Card(
backgroundColor = green200,
elevation = 4.dp,
modifier = Modifier.size(100.dp)
) {}
}
Text(
text = "Children with Topstart, center & bottomEnd align", style = typography.caption,
modifier = Modifier.padding(8.dp)
)
Box(
modifier =
boxModifier
.testTag(TestTags.HOME_LAYOUTS_BOX_TOP_CENTER_AND_NO_ALIGN)
) {
Card(
backgroundColor = green700, elevation = 4.dp, modifier = Modifier
.size(
200
.dp
)
.align(Alignment.TopStart)
) {}
Card(
backgroundColor = green500, elevation = 4.dp, modifier = Modifier
.size(
150
.dp
)
.align(Alignment.Center)
) {}
Card(
backgroundColor = green200, elevation = 4.dp, modifier = Modifier
.size(
100
.dp
)
.align(Alignment.BottomEnd)
) {}
}
}
@Composable
fun ConstraintLayouts() {
Text(text = "ConstraintLayouts", style = typography.h6, modifier = Modifier.padding(8.dp))
ConstraintLayout(
modifier = Modifier
.background(Color.LightGray)
.fillMaxWidth()
.height(150.dp)
.testTag(TestTags.HOME_LAYOUTS_CONSTRAINT_LAYOUT)
) {
//refs creations
val (mainButton, mainText, seconderyText, outlineButton) = createRefs()
Button(
onClick = { },
modifier = Modifier.constrainAs(mainButton) {
top.linkTo(parent.top, margin = 16.dp)
}
) {
Text("Main button")
}
Text("Main Text", Modifier.constrainAs(mainText) {
top.linkTo(parent.top, margin = 16.dp)
absoluteLeft.linkTo(mainButton.end, margin = 16.dp)
})
Text("Secondary Text", Modifier.constrainAs(seconderyText) {
top.linkTo(mainText.bottom, margin = 16.dp)
absoluteLeft.linkTo(mainButton.end, margin = 16.dp)
})
OutlinedButton(
onClick = { /* Do something */ },
modifier = Modifier.constrainAs(outlineButton) {
top.linkTo(seconderyText.bottom, margin = 16.dp)
start.linkTo(seconderyText.end, margin = 16.dp)
}
) {
Text("Outline Button")
}
}
}
@Composable
fun MultipleTexts() {
Text(text = "First", modifier = Modifier.padding(8.dp))
Text(text = "Second", modifier = Modifier.padding(8.dp))
Text(text = "Third", modifier = Modifier.padding(8.dp))
}
@Preview
@Composable
fun PreviewLayouts() {
Layouts()
} | 13 | null | 8 | 6,057 | 1b82b0b990648b2ece5c890fef622d9bdb00e4d8 | 9,406 | ComposeCookBook | MIT License |
memento/src/test/java/com/alexstyl/specialdates/addevent/AddEventsPresenterTest.kt | alexstyl | 66,690,455 | false | null | package com.alexstyl.specialdates.addevent
import com.alexstyl.specialdates.JavaStrings
import com.alexstyl.specialdates.Optional
import com.alexstyl.specialdates.TestDateLabelCreator
import com.alexstyl.specialdates.addevent.operations.InsertContact
import com.alexstyl.specialdates.addevent.operations.InsertEvent
import com.alexstyl.specialdates.addevent.operations.UpdateContact
import com.alexstyl.specialdates.analytics.Analytics
import com.alexstyl.specialdates.contact.ContactFixture
import com.alexstyl.specialdates.date.ContactEvent
import com.alexstyl.specialdates.date.Date
import com.alexstyl.specialdates.date.Months
import com.alexstyl.specialdates.events.peopleevents.PeopleEventsProvider
import com.alexstyl.specialdates.events.peopleevents.PeopleEventsUpdater
import com.alexstyl.specialdates.events.peopleevents.StandardEventType
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import org.junit.Before
import org.junit.Test
import org.mockito.BDDMockito
import org.mockito.BDDMockito.given
import org.mockito.Mockito
import org.mockito.Mockito.mock
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
class AddEventsPresenterTest {
private lateinit var presenter: AddEventsPresenter
private val strings = JavaStrings()
private val viewModelFactory = AddEventViewModelFactory(TestDateLabelCreator.forUS(), JavaStrings(), JavaEventIcons())
private val mockView = Mockito.mock(AddEventView::class.java)
private val mockMessageDisplayer = mock(MessageDisplayer::class.java)
private val mockPeopleEventsProvider = Mockito.mock(PeopleEventsProvider::class.java)
private val mockExecutor = mock(ContactOperationsExecutor::class.java)
@Before
fun setUp() {
val mockPeopleEventsUpdater = mock(PeopleEventsUpdater::class.java)
// don't mind for updates
given(mockPeopleEventsUpdater.updateEvents()).willReturn(Observable.empty())
presenter = AddEventsPresenter(
mock(Analytics::class.java),
ContactOperations(),
mockMessageDisplayer,
mockExecutor,
strings,
mockPeopleEventsProvider,
viewModelFactory,
mockPeopleEventsUpdater,
Schedulers.trampoline(),
Schedulers.trampoline()
)
}
@Test
fun whenStartPresenting_thenAlwaysStartsWithEmptyViewModelsForStandardTypes() {
presenter.startPresentingInto(mockView)
val expectedViewModels = emptyModelsFor(StandardEventType.BIRTHDAY,
StandardEventType.ANNIVERSARY,
StandardEventType.OTHER)
Mockito.verify(mockView).display(expectedViewModels)
}
private fun emptyModelsFor(standardEventType: StandardEventType, vararg others: StandardEventType): List<AddEventContactEventViewModel> {
return (listOf(standardEventType) + others.toList())
.map { viewModelFactory.createViewModelFor(it) }
}
@Test
fun givenAContactWithoutEvents_thenEmptyViewModelsWillBePassedToTheView() {
presenter.startPresentingInto(mockView)
val contact = ContactFixture.aContactCalled("Martha")
BDDMockito.given(mockPeopleEventsProvider.fetchEventsFor(contact)).willReturn(emptyList())
presenter.presentContact(contact)
Mockito.verify(mockView, times(2)).display(emptyModelsFor(StandardEventType.BIRTHDAY, StandardEventType.ANNIVERSARY, StandardEventType.OTHER))
}
@Test
fun givenAContactWithAllEvents_thenTheViewModelsForThoseEventsArePassedIntoTheView() {
presenter.startPresentingInto(mockView)
val contact = ContactFixture.aContactCalled("Martha")
val birthday = ContactEvent(Optional.absent(), StandardEventType.BIRTHDAY, Date.today(), contact)
val anniversary = ContactEvent(Optional.absent(), StandardEventType.ANNIVERSARY, Date.today() + 1, contact)
val other = ContactEvent(Optional.absent(), StandardEventType.OTHER, Date.today() + 2, contact)
BDDMockito.given(mockPeopleEventsProvider.fetchEventsFor(contact)).willReturn(listOf(birthday, anniversary, other))
presenter.presentContact(contact)
val expectedViewModels = listOf(viewModelFactory.createViewModelFor(birthday), viewModelFactory.createViewModelFor(anniversary), viewModelFactory.createViewModelFor(other))
Mockito.verify(mockView).display(expectedViewModels)
}
@Test
fun givenAContactWithCustomEvents_thenTheViewModelsForThoseEventsButNoCustomArePassedIntoTheView() {
presenter.startPresentingInto(mockView)
val contact = ContactFixture.aContactCalled("Martha")
val nameday = ContactEvent(Optional.absent(), StandardEventType.NAMEDAY, Date.today() + 2, contact)
val custom = ContactEvent(Optional.absent(), StandardEventType.CUSTOM, Date.today() + 2, contact)
BDDMockito.given(mockPeopleEventsProvider.fetchEventsFor(contact)).willReturn(listOf(nameday, custom))
presenter.presentContact(contact)
val expectedViewModels = emptyModelsFor(StandardEventType.BIRTHDAY, StandardEventType.ANNIVERSARY, StandardEventType.OTHER)
Mockito.verify(mockView, times(2)).display(expectedViewModels)
}
@Test
fun givenADateAndEventIsSelected_thenTheViewModelsOfThatEventPlusAllOtherEmptyViewModelsArePassedToTheView() {
presenter.startPresentingInto(mockView)
Mockito.verify(mockView).display(emptyModelsFor(StandardEventType.BIRTHDAY, StandardEventType.ANNIVERSARY, StandardEventType.OTHER))
presenter.onEventDatePicked(StandardEventType.BIRTHDAY, Date.today())
val dateViewModel = viewModelFactory.createViewModelFor(StandardEventType.BIRTHDAY, Date.today())
Mockito.verify(mockView).display(listOf(dateViewModel) + emptyModelsFor(StandardEventType.ANNIVERSARY, StandardEventType.OTHER))
}
@Test
fun givenADateAndEventIsRemoved_thenTheViewModelsOfThatEventIsReturnedEmptyToTheView() {
presenter.startPresentingInto(mockView)
val contact = ContactFixture.aContactCalled("Martha")
val birthday = ContactEvent(Optional.absent(), StandardEventType.BIRTHDAY, Date.today(), contact)
val anniversary = ContactEvent(Optional.absent(), StandardEventType.ANNIVERSARY, Date.today() + 1, contact)
val other = ContactEvent(Optional.absent(), StandardEventType.OTHER, Date.today() + 2, contact)
BDDMockito.given(mockPeopleEventsProvider.fetchEventsFor(contact)).willReturn(listOf(birthday, anniversary, other))
presenter.presentContact(contact)
presenter.removeEvent(StandardEventType.BIRTHDAY)
val expectedViewModels = listOf(viewModelFactory.createViewModelFor(StandardEventType.BIRTHDAY),
viewModelFactory.createViewModelFor(anniversary),
viewModelFactory.createViewModelFor(other)
)
Mockito.verify(mockView).display(expectedViewModels)
}
@Test
fun whenStartPresenting_thenSaveIsDisabled() {
presenter.startPresentingInto(mockView)
verify(mockView).preventSave()
}
@Test
fun whenAContactIsSelected_thenSaveIsDisabled() {
presenter.startPresentingInto(mockView)
val contact = ContactFixture.aContactCalled("Rob")
presenter.presentContact(contact)
verify(mockView, times(2)).preventSave()
verify(mockView, times(0)).allowSave()
}
@Test(expected = UnsupportedOperationException::class)
fun givenAName_whenAContactIsSelected_thenThrowsException() {
presenter.startPresentingInto(mockView)
presenter.presentContact(ContactFixture.aContactCalled("Yoland"))
presenter.presentName("Yolanda")
}
@Test
fun whenAnEventIsSelected_givenAContactIsSelected_thenSaveIsEnabled() {
presenter.startPresentingInto(mockView)
presenter.presentName("Alex")
verify(mockView, times(2)).preventSave()
verify(mockView, times(0)).allowSave()
presenter.onEventDatePicked(StandardEventType.BIRTHDAY, Date.on(19, Months.DECEMBER, 1990))
verify(mockView, times(1)).allowSave()
}
@Test
fun whenAllEventsAreRemoved_givenAContact_thenSaveIsDisabled() {
presenter.startPresentingInto(mockView) // prevent save 1
val contact = ContactFixture.aContactCalled("Chrysa")
given(mockPeopleEventsProvider.fetchEventsFor(contact))
.willReturn(listOf(
ContactEvent(Optional.absent(), StandardEventType.BIRTHDAY, Date.today(), contact))
)
presenter.presentContact(contact) // prevent save 2
presenter.removeEvent(StandardEventType.BIRTHDAY) // prevent save 3
verify(mockView, times(3)).preventSave()
}
@Test
fun givenANameABirthday_thenAContactIsCreatedMessageIsShown() {
given(mockExecutor.execute(
listOf(
InsertContact("Alex"), InsertEvent(StandardEventType.BIRTHDAY, Date.on(19, Months.DECEMBER, 1990))
)
)).willReturn(true)
presenter.startPresentingInto(mockView)
presenter.presentName("Alex")
presenter.onEventDatePicked(StandardEventType.BIRTHDAY, Date.on(19, Months.DECEMBER, 1990))
presenter.saveChanges()
verify(mockMessageDisplayer).showMessage(strings.contactAdded())
}
@Test
fun givenANameABirthday_thenANewContactIsCreated() {
presenter.startPresentingInto(mockView)
presenter.presentName("Alex")
presenter.onEventDatePicked(StandardEventType.BIRTHDAY, Date.on(19, Months.DECEMBER, 1990))
presenter.saveChanges()
verify(mockExecutor).execute(
listOf(
InsertContact("Alex"),
InsertEvent(StandardEventType.BIRTHDAY, Date.on(19, Months.DECEMBER, 1990))
))
}
@Test
fun givenAContact_whenTheContactHasAnExistingBirthday_thenTheBirthdayWillBeUpdated() {
presenter.startPresentingInto(mockView)
val selectedContact = ContactFixture.aContactCalled("Joseph")
presenter.presentContact(selectedContact)
val existingBirthday = ContactEvent(Optional.absent(), StandardEventType.BIRTHDAY, Date.on(1, Months.JANUARY), selectedContact)
given(mockPeopleEventsProvider.fetchEventsFor(selectedContact)).willReturn(listOf(existingBirthday))
presenter.onEventDatePicked(StandardEventType.BIRTHDAY, Date.on(19, Months.DECEMBER, 1990))
presenter.saveChanges()
verify(mockExecutor).execute(
listOf(
UpdateContact(selectedContact),
InsertEvent(StandardEventType.BIRTHDAY, Date.on(19, Months.DECEMBER, 1990))
))
}
}
| 0 | Java | 49 | 211 | d224f0af53ee3d4ecadad5df0a2731e2c9031a23 | 10,862 | Memento-Calendar | MIT License |
timelineviewv2/src/main/java/ro/dobrescuandrei/timelineviewv2/model/WeeklyDateTimeInterval.kt | andob | 238,633,385 | false | null | package ro.dobrescuandrei.timelineviewv2.model
import android.annotation.SuppressLint
import android.content.res.Resources
import ro.dobrescuandrei.timelineviewv2.TimelineView
import ro.dobrescuandrei.timelineviewv2.recycler.adapter.WeeklyDateIntervalAdapter
import ro.dobrescuandrei.timelineviewv2.utils.atBeginningOfDay
import ro.dobrescuandrei.timelineviewv2.utils.atEndOfDay
import java.time.DayOfWeek
import java.time.LocalDateTime
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
class WeeklyDateTimeInterval : DateTimeInterval
{
constructor(referenceDateTime : ZonedDateTime) : super(
fromDateTime = referenceDateTime.with(DayOfWeek.MONDAY).atBeginningOfDay(),
toDateTime = referenceDateTime.with(DayOfWeek.SUNDAY).atEndOfDay())
constructor(referenceDateTime : LocalDateTime) : this(
referenceDateTime = referenceDateTime.atZone(defaultTimezone))
companion object
{
@JvmStatic
fun aroundToday() = WeeklyDateTimeInterval(
referenceDateTime = ZonedDateTime.now(defaultTimezone))
}
override fun getPreviousDateTimeInterval() =
WeeklyDateTimeInterval(referenceDateTime = fromDateTime.minusWeeks(1))
override fun getNextDateTimeInterval() =
WeeklyDateTimeInterval(referenceDateTime = fromDateTime.plusWeeks(1))
override fun getShiftedDateTimeInterval(amount : Long) =
WeeklyDateTimeInterval(referenceDateTime = fromDateTime.plusWeeks(amount))
@SuppressLint("SimpleDateFormat")
override fun toString(resources : Resources) : String
{
val now = ZonedDateTime.now(defaultTimezone)!!
val startDateTimeFormatter =
if (fromDateTime.monthValue!=toDateTime.monthValue)
DateTimeFormatter.ofPattern("dd MMM")!!
else DateTimeFormatter.ofPattern("dd")!!
val startDateStr = startDateTimeFormatter.format(fromDateTime)!!
val endDateTimeFormatter =
if (toDateTime.year!=now.year)
DateTimeFormatter.ofPattern("dd MMM yyyy")!!
else DateTimeFormatter.ofPattern("dd MMM")!!
val endDateStr = endDateTimeFormatter.format(toDateTime)!!
return "$startDateStr - $endDateStr"
}
override fun toRecyclerViewAdapter(timelineView : TimelineView) =
WeeklyDateIntervalAdapter(context = timelineView.context, timelineView = timelineView)
override fun clone() = WeeklyDateTimeInterval(referenceDateTime = fromDateTime)
}
| 1 | null | 2 | 11 | 7c13d7bace18ada32b463f8b57025cd39a155dae | 2,497 | timelineview-v2 | Apache License 2.0 |
uranium-swing/src/main/kotlin/pl/karol202/uranium/swing/control/button/SwingCheckBox.kt | karol-202 | 269,320,433 | false | null | package pl.karol202.uranium.swing.control.button
import pl.karol202.uranium.core.common.AutoKey
import pl.karol202.uranium.core.common.UProps
import pl.karol202.uranium.core.element.component
import pl.karol202.uranium.core.render.URenderScope
import pl.karol202.uranium.swing.*
import pl.karol202.uranium.swing.Builder
import pl.karol202.uranium.swing.component.SwingAbstractAppComponent
import pl.karol202.uranium.swing.component.SwingContainerComponent
import pl.karol202.uranium.swing.util.*
import javax.swing.JCheckBox
class SwingCheckBox(private val nativeComponent: JCheckBox,
initialProps: Props) : SwingAbstractAppComponent<SwingCheckBox.Props>(initialProps)
{
data class Props(override val key: Any = AutoKey,
override val toggleButtonProps: SwingToggleButton.Props = SwingToggleButton.Props(),
val borderPaintedFlat: Prop<Boolean> = Prop.NoValue) : UProps,
SwingContainerComponent.PropsProvider<Props>,
SwingAbstractButton.PropsProvider<Props>,
SwingToggleButton.PropsProvider<Props>,
PropsProvider<Props>
{
override val swingProps = toggleButtonProps.swingProps
override val abstractButtonProps = toggleButtonProps.abstractButtonProps
override val checkBoxProps = this
override fun withSwingProps(builder: Builder<SwingContainerComponent.Props>) =
copy(toggleButtonProps = toggleButtonProps.withSwingProps(builder))
override fun withAbstractButtonProps(builder: Builder<SwingAbstractButton.Props>) =
copy(toggleButtonProps = toggleButtonProps.withAbstractButtonProps(builder))
override fun withToggleButtonProps(builder: Builder<SwingToggleButton.Props>) =
copy(toggleButtonProps = toggleButtonProps.builder())
override fun withCheckBoxProps(builder: Builder<Props>) = builder()
}
interface PropsProvider<S : PropsProvider<S>> : UProps
{
val checkBoxProps: Props
fun withCheckBoxProps(builder: Builder<Props>): S
}
override fun URenderScope<Swing>.render() =
toggleButton(nativeComponent = { nativeComponent }, props = props.toggleButtonProps)
override fun onUpdate(previousProps: Props?) = nativeComponent.update {
props.borderPaintedFlat.ifPresent { isBorderPaintedFlat = it }
}
}
fun SwingRenderScope.checkBox(key: Any = AutoKey) = checkBox(props = SwingCheckBox.Props(key))
internal fun SwingRenderScope.checkBox(nativeComponent: () -> JCheckBox = ::JCheckBox,
props: SwingCheckBox.Props) =
component({ SwingCheckBox(nativeComponent(), it) }, props)
private typealias SCBProvider<P> = SwingCheckBox.PropsProvider<P>
fun <P : SCBProvider<P>> SwingElement<P>.withCheckBoxProps(builder: Builder<SwingCheckBox.Props>) = withProps { withCheckBoxProps(builder) }
fun <P : SCBProvider<P>> SwingElement<P>.borderPaintedFlat(flat: Boolean) = withCheckBoxProps { copy(borderPaintedFlat = flat.prop()) }
| 0 | Kotlin | 0 | 0 | d15bbc869a1dac11285d9329a49caee32345f63b | 3,156 | uranium-swing | MIT License |
platform/platform-impl/src/com/intellij/configurationStore/storageUtil.kt | androidports | 115,100,208 | false | null | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore
import com.intellij.notification.NotificationType
import com.intellij.notification.NotificationsManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.PathMacros
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.ComponentManager
import com.intellij.openapi.components.TrackingPathMacroSubstitutor
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.components.impl.stores.UnknownMacroNotification
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectBundle
import com.intellij.openapi.project.impl.ProjectMacrosUtil
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.io.createDirectories
import com.intellij.util.io.inputStream
import com.intellij.util.io.systemIndependentPath
import gnu.trove.THashSet
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import java.io.IOException
import java.nio.file.Path
import java.util.*
const val NOTIFICATION_GROUP_ID = "Load Error"
@TestOnly
var DEBUG_LOG: String? = null
@ApiStatus.Internal
fun doNotify(macros: MutableSet<String>, project: Project, substitutorToStore: Map<TrackingPathMacroSubstitutor, IComponentStore>) {
val productName = ApplicationNamesInfo.getInstance().productName
val content = "<p><i>${macros.joinToString(", ")}</i> ${if (macros.size == 1) "is" else "are"} undefined. <a href=\"define\">Fix it</a></p>" +
"<br>Path variables are used to substitute absolute paths in " + productName + " project files " +
"and allow project file sharing in version control systems.<br>" +
"Some of the files describing the current project settings contain unknown path variables " +
"and " + productName + " cannot restore those paths."
UnknownMacroNotification(NOTIFICATION_GROUP_ID, "Load error: undefined path variables", content, NotificationType.ERROR,
{ _, _ -> checkUnknownMacros(project, true, macros, substitutorToStore) }, macros)
.notify(project)
}
@ApiStatus.Internal
fun checkUnknownMacros(project: Project, notify: Boolean) {
// use linked set/map to get stable results
val unknownMacros = LinkedHashSet<String>()
val substitutorToStore = LinkedHashMap<TrackingPathMacroSubstitutor, IComponentStore>()
collect(project, unknownMacros, substitutorToStore)
for (module in ModuleManager.getInstance(project).modules) {
collect(module, unknownMacros, substitutorToStore)
}
if (unknownMacros.isEmpty()) {
return
}
if (notify) {
doNotify(unknownMacros, project, substitutorToStore)
return
}
checkUnknownMacros(project, false, unknownMacros, substitutorToStore)
}
private fun checkUnknownMacros(project: Project,
showDialog: Boolean,
unknownMacros: MutableSet<String>,
substitutorToStore: Map<TrackingPathMacroSubstitutor, IComponentStore>) {
if (unknownMacros.isEmpty() || (showDialog && !ProjectMacrosUtil.checkMacros(project, THashSet(unknownMacros)))) {
return
}
val pathMacros = PathMacros.getInstance()
unknownMacros.removeAll { pathMacros.getValue(it).isNullOrBlank() && !pathMacros.isIgnoredMacroName(it) }
if (unknownMacros.isEmpty()) {
return
}
val notificationManager = NotificationsManager.getNotificationsManager()
for ((substitutor, store) in substitutorToStore) {
val components = substitutor.getComponents(unknownMacros)
if (store.isReloadPossible(components)) {
substitutor.invalidateUnknownMacros(unknownMacros)
for (notification in notificationManager.getNotificationsOfType(UnknownMacroNotification::class.java, project)) {
if (unknownMacros.containsAll(notification.macros)) {
notification.expire()
}
}
store.reloadStates(components, project.messageBus)
}
else if (Messages.showYesNoDialog(project, "Component could not be reloaded. Reload project?", "Configuration Changed",
Messages.getQuestionIcon()) == Messages.YES) {
StoreReloadManager.getInstance().reloadProject(project)
}
}
}
private fun collect(componentManager: ComponentManager,
unknownMacros: MutableSet<String>,
substitutorToStore: MutableMap<TrackingPathMacroSubstitutor, IComponentStore>) {
val store = componentManager.stateStore
val substitutor = store.storageManager.macroSubstitutor as? TrackingPathMacroSubstitutor ?: return
val macros = substitutor.getUnknownMacros(null)
if (macros.isEmpty()) {
return
}
unknownMacros.addAll(macros)
substitutorToStore.put(substitutor, store)
}
@ApiStatus.Internal
fun getOrCreateVirtualFile(file: Path, requestor: StorageManagerFileWriteRequestor): VirtualFile {
var virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(file.systemIndependentPath)
if (virtualFile == null) {
val parentFile = file.parent
parentFile.createDirectories()
// need refresh if the directory has just been created
val parentVirtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(parentFile.systemIndependentPath)
?: throw IOException(ProjectBundle.message("project.configuration.save.file.not.found", parentFile))
virtualFile = runAsWriteActionIfNeeded {
parentVirtualFile.createChildData(requestor, file.fileName.toString())
}
}
// internal .xml files written with BOM can cause problems, see IDEA-219913
// (e.g. unable to backport them to 191/unwanted changed files when someone checks File Encodings|create new files with BOM)
// so we forcibly remove BOM from storage .xmls
if (virtualFile.bom != null) {
virtualFile.bom = null
}
return virtualFile
}
// runWriteAction itself cannot do such check because in general case any write action must be tracked regardless of current action
@ApiStatus.Internal
inline fun <T> runAsWriteActionIfNeeded(crossinline runnable: () -> T): T {
return when {
ApplicationManager.getApplication().isWriteAccessAllowed -> runnable()
else -> runWriteAction(runnable)
}
}
@Throws(IOException::class)
@ApiStatus.Internal
fun readProjectNameFile(nameFile: Path): String? {
return nameFile.inputStream().reader().useLines { line -> line.firstOrNull { !it.isEmpty() }?.trim() }
} | 6 | null | 1 | 4 | 6e4f7135c5843ed93c15a9782f29e4400df8b068 | 6,899 | intellij-community | Apache License 2.0 |
RetenoSdkCore/src/main/java/com/reteno/core/domain/controller/IamControllerImpl.kt | reteno-com | 545,381,514 | false | {"Kotlin": 1350127, "Java": 159488, "HTML": 17807, "Shell": 379} | package com.reteno.core.domain.controller
import androidx.annotation.VisibleForTesting
import com.reteno.core.data.local.mappers.toDomain
import com.reteno.core.data.remote.model.iam.displayrules.frequency.FrequencyRuleValidator
import com.reteno.core.data.remote.model.iam.displayrules.schedule.ScheduleRuleValidator
import com.reteno.core.data.remote.model.iam.displayrules.targeting.InAppWithEvent
import com.reteno.core.data.remote.model.iam.displayrules.targeting.InAppWithTime
import com.reteno.core.data.remote.model.iam.displayrules.targeting.RuleEventValidator
import com.reteno.core.data.remote.model.iam.displayrules.targeting.TargetingRule
import com.reteno.core.data.remote.model.iam.message.InAppMessage
import com.reteno.core.data.remote.model.iam.message.InAppMessageContent
import com.reteno.core.data.repository.IamRepository
import com.reteno.core.domain.ResultDomain
import com.reteno.core.domain.model.event.Event
import com.reteno.core.features.iam.IamJsEvent
import com.reteno.core.features.iam.InAppPauseBehaviour
import com.reteno.core.lifecycle.RetenoSessionHandler
import com.reteno.core.util.Logger
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.async
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import java.util.concurrent.atomic.AtomicBoolean
internal class IamControllerImpl(
private val iamRepository: IamRepository,
eventController: EventController,
private val sessionHandler: RetenoSessionHandler,
private val scope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
) : IamController {
private val isPausedInAppMessages = AtomicBoolean(false)
private var pauseBehaviour = InAppPauseBehaviour.POSTPONE_IN_APPS
private var interactionId: String? = null
private val _fullHtmlStateFlow: MutableStateFlow<ResultDomain<String>> =
MutableStateFlow(ResultDomain.Idle)
override val fullHtmlStateFlow: StateFlow<ResultDomain<String>> = _fullHtmlStateFlow
@VisibleForTesting
var inAppsWaitingForEvent: MutableList<InAppWithEvent>? = null
private set
private var htmlJob: Job? = null
private val _inAppMessage = MutableSharedFlow<InAppMessage>(
extraBufferCapacity = 10,
onBufferOverflow = BufferOverflow.DROP_OLDEST
)
private val postponedNotifications = mutableListOf<InAppMessage>()
override val inAppMessagesFlow: SharedFlow<InAppMessage> = _inAppMessage
init {
eventController.eventFlow
.onEach { notifyEventOccurred(it) }
.launchIn(scope)
preloadHtml()
}
override fun fetchIamFullHtml(interactionId: String) {
/*@formatter:off*/ Logger.i(TAG, "fetchIamFullHtml(): ", "widgetId = [", this.interactionId, "]")
/*@formatter:on*/
this.interactionId = interactionId
_fullHtmlStateFlow.value = ResultDomain.Loading
htmlJob = scope.launch {
try {
withTimeout(TIMEOUT) {
val baseHtml = async { iamRepository.getBaseHtml() }
val widget = async { iamRepository.getWidgetRemote(interactionId) }
val fullHtml = baseHtml.await().run {
widget.await().let { widgetModel ->
var text = this
widgetModel.model?.let {
text = text.replace(KEY_DOCUMENT_MODEL, it)
}
widgetModel.personalization?.let {
text = text.replace(KEY_PERSONALISATION, it)
}
text
}
}
_fullHtmlStateFlow.value = ResultDomain.Success(fullHtml)
}
} catch (e: TimeoutCancellationException) {
_fullHtmlStateFlow.value =
ResultDomain.Error("fetchIamFullHtml(): widgetId = [${[email protected]}] TIMEOUT")
}
}
}
override fun fetchIamFullHtml(messageContent: InAppMessageContent?) {
/*@formatter:off*/ Logger.i(TAG, "fetchIamFullHtml(): ", "widgetId = [", this.interactionId, "]")
/*@formatter:on*/
_fullHtmlStateFlow.value = ResultDomain.Loading
scope.launch {
try {
withTimeout(TIMEOUT) {
val baseHtml = iamRepository.getBaseHtml()
val widgetModel = messageContent?.model.toString()
var text = baseHtml
text = text.replace(KEY_DOCUMENT_MODEL, widgetModel)
text = text.replace(KEY_PERSONALISATION, "{}")
_fullHtmlStateFlow.value = ResultDomain.Success(text)
}
} catch (e: TimeoutCancellationException) {
_fullHtmlStateFlow.value =
ResultDomain.Error("fetchIamFullHtml(): widgetId = [${[email protected]}] TIMEOUT")
}
}
}
override fun widgetInitFailed(jsEvent: IamJsEvent) {
/*@formatter:off*/ Logger.i(TAG, "widgetInitFailed(): ", "widgetId = [", interactionId, "], jsEvent = [", jsEvent, "]")
/*@formatter:on*/
interactionId?.let {
iamRepository.widgetInitFailed(it, jsEvent)
}
}
override fun reset() {
_fullHtmlStateFlow.value = ResultDomain.Idle
interactionId = null
htmlJob?.cancel()
htmlJob = null
}
override fun getInAppMessages() {
scope.launch {
try {
val messageListModel = iamRepository.getInAppMessages()
val inAppMessages = messageListModel.messages
val messagesWithNoContent = inAppMessages.filter { it.content == null }
val contentIds = messagesWithNoContent.map { it.messageInstanceId }
val contentsDeferred = async { iamRepository.getInAppMessagesContent(contentIds) }
updateSegmentStatuses(
inAppMessages,
updateCacheOnSuccess = messageListModel.isFromRemote.not()
)
val contents = contentsDeferred.await()
messagesWithNoContent.forEach { message ->
message.content = contents.firstOrNull {
it.messageInstanceId == message.messageInstanceId
}
}
iamRepository.saveInAppMessages(messageListModel)
sortMessages(inAppMessages)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
override fun refreshSegmentation() {
scope.launch {
val messageListModel = iamRepository.getInAppMessages()
val inAppMessages = messageListModel.messages
updateSegmentStatuses(
inAppMessages,
updateCacheOnSuccess = messageListModel.isFromRemote.not()
)
}
}
private fun notifyEventOccurred(event: Event) {
val inapps = inAppsWaitingForEvent
if (inapps.isNullOrEmpty()) return
val inAppsWithCurrentEvent = inapps.filter { inapp ->
inapp.event.name == event.eventTypeKey
}
val validator = RuleEventValidator()
val inAppsMatchingEventParams = inAppsWithCurrentEvent.filter { inapp ->
validator.checkEventMatchesRules(inapp, event)
}
tryShowInAppFromList(inAppsMatchingEventParams.map { it.inApp }.toMutableList())
}
override fun pauseInAppMessages(isPaused: Boolean) {
val wasDisabled = isPausedInAppMessages.get()
isPausedInAppMessages.set(isPaused)
if (wasDisabled && !isPaused) {
showPostponedNotifications()
}
}
override fun updateInAppMessage(inAppMessage: InAppMessage) {
scope.launch {
withContext(Dispatchers.IO) {
iamRepository.updateInAppMessages(listOf(inAppMessage))
}
}
}
override fun setPauseBehaviour(behaviour: InAppPauseBehaviour) {
pauseBehaviour = behaviour
}
private fun showPostponedNotifications() {
when (pauseBehaviour) {
InAppPauseBehaviour.SKIP_IN_APPS -> postponedNotifications.clear()
InAppPauseBehaviour.POSTPONE_IN_APPS -> {
postponedNotifications.firstOrNull()?.let(::showInApp)
postponedNotifications.clear()
}
}
}
private fun sortMessages(inAppMessages: List<InAppMessage>) {
val inAppsWithEvents = mutableListOf<InAppWithEvent>()
val inAppsWithTimer = mutableListOf<InAppWithTime>()
val inAppsOnAppStart = mutableListOf<InAppMessage>()
inAppMessages.forEach { message ->
val includeRules = message.displayRules.targeting?.include
if (includeRules != null) {
includeRules.groups.forEach { includeGroup ->
includeGroup.conditions.forEach { rule ->
when (rule) {
is TargetingRule.TimeSpentInApp -> inAppsWithTimer.add(
InAppWithTime(
message,
rule.timeSpentMillis
)
)
is TargetingRule.Event -> inAppsWithEvents.add(
InAppWithEvent(
message,
rule
)
)
}
}
}
} else {
inAppsOnAppStart.add(message)
}
}
if (inAppsWithTimer.isNotEmpty()) {
sessionHandler.scheduleInAppMessages(inAppsWithTimer) { messagesToShow ->
tryShowInAppFromList(messagesToShow.toMutableList())
}
}
if (inAppsWithEvents.isNotEmpty()) {
inAppsWaitingForEvent = inAppsWithEvents
}
tryShowInAppFromList(inAppMessages = inAppsOnAppStart, showingOnAppStart = true)
}
private fun tryShowInAppFromList(
inAppMessages: MutableList<InAppMessage>,
showingOnAppStart: Boolean = false
) {
scope.launch {
if (!showingOnAppStart) {
updateSegmentStatuses(inAppMessages, updateCacheOnSuccess = true)
}
val frequencyValidator = FrequencyRuleValidator()
val scheduleValidator = ScheduleRuleValidator()
while (true) {
if (inAppMessages.isEmpty()) break
val inAppWithHighestId = inAppMessages.maxBy { it.messageId }
val showedInApp = tryShowInApp(
inAppMessage = inAppWithHighestId,
frequencyValidator = frequencyValidator,
scheduleValidator = scheduleValidator,
showingOnAppStart = showingOnAppStart
)
if (showedInApp) {
break
}
inAppMessages.remove(inAppWithHighestId)
}
}
}
private suspend fun updateSegmentStatuses(
inAppMessages: List<InAppMessage>,
updateCacheOnSuccess: Boolean = true
) {
val messagesWithSegments = inAppMessages.filter {
it.displayRules.async?.segment != null
}
val segmentIds =
messagesWithSegments.mapNotNull { it.displayRules.async?.segment?.segmentId }.distinct()
val segmentResponses = iamRepository.checkUserInSegments(segmentIds)
val updatedMessages = mutableListOf<InAppMessage>()
messagesWithSegments.forEach { message ->
val segment = message.displayRules.async?.segment
if (segment != null) {
val checkResult = segmentResponses.firstOrNull { result ->
result.segmentId == segment.segmentId
}
if (checkResult != null) {
segment.isInSegment = checkResult.checkResult ?: false
segment.retryParams = checkResult.error?.toDomain()
segment.lastCheckedTimestamp = System.currentTimeMillis()
updatedMessages.add(message)
}
}
}
if (updateCacheOnSuccess) {
iamRepository.updateInAppMessages(updatedMessages)
}
}
private fun tryShowInApp(
inAppMessage: InAppMessage,
frequencyValidator: FrequencyRuleValidator = FrequencyRuleValidator(),
scheduleValidator: ScheduleRuleValidator = ScheduleRuleValidator(),
showingOnAppStart: Boolean = false
): Boolean {
val content = inAppMessage.content
if (content == null || content.model.isJsonNull) {
return false
}
if (checkSegmentRuleMatches(inAppMessage).not()) {
return false
}
if (!frequencyValidator.checkInAppMatchesFrequencyRules(
inAppMessage = inAppMessage,
sessionStartTimestamp = sessionHandler.getSessionStartTimestamp(),
showingOnAppStart = showingOnAppStart
)
) {
return false
}
if (!scheduleValidator.checkInAppMatchesScheduleRules(inAppMessage)) {
return false
}
showInApp(inAppMessage)
return true
}
private fun showInApp(inAppMessage: InAppMessage) {
if (isPausedInAppMessages.get()) postponedNotifications.add(inAppMessage)
if (!canShowInApp()) return
scope.launch { _inAppMessage.emit(inAppMessage) }
}
private fun checkSegmentRuleMatches(inAppMessage: InAppMessage): Boolean {
return inAppMessage.displayRules.async?.segment?.isInSegment ?: true
}
private fun canShowInApp(): Boolean {
return isPausedInAppMessages.get().not() && _fullHtmlStateFlow.value == ResultDomain.Idle
}
private fun preloadHtml() = scope.launch {
iamRepository.getBaseHtml()
}
companion object {
private val TAG: String = IamControllerImpl::class.java.simpleName
internal const val TIMEOUT = 30_000L
const val KEY_DOCUMENT_MODEL = "\${documentModel}"
const val KEY_PERSONALISATION = "\${personalisation}"
}
} | 1 | Kotlin | 2 | 1 | f52fc040ae94f5830e874f0f41e36fba35e3a276 | 15,072 | reteno-mobile-android-sdk | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.