repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
hzsweers/CatchUp
libraries/base-ui/src/main/kotlin/io/sweers/catchup/base/ui/BaseActivity.kt
1
5106
/* * Copyright (C) 2019. Zac Sweers * * 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.sweers.catchup.base.ui import android.annotation.SuppressLint import android.os.Bundle import android.view.LayoutInflater import android.view.MenuItem import android.view.ViewGroup import androidx.annotation.CallSuper import androidx.annotation.CheckResult import androidx.appcompat.app.AppCompatActivity import androidx.core.app.NavUtils import androidx.viewbinding.ViewBinding import autodispose2.lifecycle.CorrespondingEventsFunction import autodispose2.lifecycle.LifecycleScopeProvider import com.jakewharton.rxrelay3.BehaviorRelay import dev.zacsweers.catchup.appconfig.AppConfig import io.reactivex.rxjava3.core.Observable import io.sweers.catchup.base.ui.ActivityEvent.CREATE import io.sweers.catchup.base.ui.ActivityEvent.DESTROY import io.sweers.catchup.base.ui.ActivityEvent.PAUSE import io.sweers.catchup.base.ui.ActivityEvent.RESUME import io.sweers.catchup.base.ui.ActivityEvent.START import io.sweers.catchup.base.ui.ActivityEvent.STOP abstract class BaseActivity : AppCompatActivity(), LifecycleScopeProvider<ActivityEvent> { private val lifecycleRelay = BehaviorRelay.create<ActivityEvent>() protected abstract val appConfig: AppConfig protected inline fun <T : Any, R : Any> Observable<T>.doOnCreate( r: R, crossinline action: R.() -> Unit ): Observable<T> = apply { doOnNext { if (it == CREATE) { r.action() } } } protected inline fun <T : Any, R : Any> Observable<T>.doOnStart( r: R, crossinline action: R.() -> Unit ): Observable<T> = apply { doOnNext { if (it == START) { r.action() } } } protected inline fun <T : Any, R : Any> Observable<T>.doOnResume( r: R, crossinline action: R.() -> Unit ): Observable<T> = apply { doOnNext { if (it == RESUME) { r.action() } } } protected inline fun <T : Any, R : Any> Observable<T>.doOnPause( r: R, crossinline action: R.() -> Unit ): Observable<T> = apply { doOnNext { if (it == PAUSE) { r.action() } } } protected inline fun <T : Any, R : Any> Observable<T>.doOnStop( r: R, crossinline action: R.() -> Unit ): Observable<T> = apply { doOnNext { if (it == STOP) { r.action() } } } protected inline fun <T : Any, R : Any> Observable<T>.doOnDestroy( r: R, crossinline action: R.() -> Unit ): Observable<T> = apply { doOnNext { if (it == DESTROY) { r.action() } } } @SuppressLint("AutoDispose") protected inline fun <T : Any> T.doOnDestroy(crossinline action: T.() -> Unit): T = apply { lifecycle().doOnDestroy(this) { action() }.subscribe() } @CheckResult protected inline fun <T : ViewBinding> ViewContainer.inflateBinding( inflate: (LayoutInflater, ViewGroup, Boolean) -> T ): T = inflate(layoutInflater, forActivity(this@BaseActivity), true) @CheckResult override fun lifecycle(): Observable<ActivityEvent> { return lifecycleRelay } final override fun correspondingEvents(): CorrespondingEventsFunction<ActivityEvent> { return ActivityEvent.LIFECYCLE } final override fun peekLifecycle(): ActivityEvent? { return lifecycleRelay.value } @CallSuper override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) lifecycleRelay.accept(CREATE) } @CallSuper override fun onStart() { super.onStart() lifecycleRelay.accept(START) } @CallSuper override fun onResume() { super.onResume() lifecycleRelay.accept(RESUME) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { NavUtils.navigateUpFromSameTask(this) } return super.onOptionsItemSelected(item) } @CallSuper override fun onPause() { lifecycleRelay.accept(PAUSE) super.onPause() } @CallSuper override fun onStop() { lifecycleRelay.accept(STOP) super.onStop() } @CallSuper override fun onDestroy() { lifecycleRelay.accept(DESTROY) super.onDestroy() } override fun onBackPressed() { supportFragmentManager.fragments.filterIsInstance<BackpressHandler>().forEach { if (it.onBackPressed()) { return } } if (appConfig.sdkInt == 29 && isTaskRoot) { // https://twitter.com/Piwai/status/1169274622614704129 // https://issuetracker.google.com/issues/139738913 finishAfterTransition() } else { super.onBackPressed() } } }
apache-2.0
e4a91480c97ca139e1696c5250c63568
25.732984
93
0.685468
4.104502
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/CopyWithoutNamedArgumentsInspection.kt
2
2368
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.IntentionWrapper import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.intentions.AddNamesToCallArgumentsIntention import org.jetbrains.kotlin.psi.KtNameReferenceExpression import org.jetbrains.kotlin.psi.callExpressionVisitor import org.jetbrains.kotlin.psi.psiUtil.referenceExpression import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.resolve.DataClassResolver class CopyWithoutNamedArgumentsInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return callExpressionVisitor(fun(expression) { val reference = expression.referenceExpression() as? KtNameReferenceExpression ?: return if (!DataClassResolver.isCopy(reference.getReferencedNameAsName())) return if (expression.valueArguments.all { it.isNamed() }) return val context = expression.analyze(BodyResolveMode.PARTIAL) val call = expression.getResolvedCall(context) ?: return val receiver = call.dispatchReceiver?.type?.constructor?.declarationDescriptor as? ClassDescriptor ?: return if (!receiver.isData) return if (call.candidateDescriptor != context[BindingContext.DATA_CLASS_COPY_FUNCTION, receiver]) return holder.registerProblem( expression.calleeExpression ?: return, KotlinBundle.message("copy.method.of.data.class.is.called.without.named.arguments"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, IntentionWrapper(AddNamesToCallArgumentsIntention()) ) }) } }
apache-2.0
83ee1518cb02d96cdb38f673ebee0f10
49.404255
120
0.772382
5.238938
false
false
false
false
GunoH/intellij-community
plugins/gradle/java/src/service/resolve/GradleProjectMembersContributor.kt
7
1762
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.gradle.service.resolve import com.intellij.psi.PsiElement import com.intellij.psi.PsiType import com.intellij.psi.ResolveState import com.intellij.psi.scope.PsiScopeProcessor import org.jetbrains.plugins.gradle.service.resolve.GradleCommonClassNames.GRADLE_API_PROJECT import org.jetbrains.plugins.gradle.service.resolve.GradleCommonClassNames.GRADLE_API_TASK_CONTAINER import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil.createType import org.jetbrains.plugins.groovy.lang.resolve.NonCodeMembersContributor import org.jetbrains.plugins.groovy.lang.resolve.processReceiverType class GradleProjectMembersContributor : NonCodeMembersContributor() { override fun unwrapMultiprocessor(): Boolean = false override fun getParentClassName(): String = GRADLE_API_PROJECT override fun processDynamicElements(qualifierType: PsiType, processor: PsiScopeProcessor, place: PsiElement, state: ResolveState) { val taskContainer = createType(GRADLE_API_TASK_CONTAINER, place) val delegate = if (qualifierType is GradleProjectAwareType) qualifierType.setType(taskContainer) else taskContainer if (!delegate.processReceiverType(processor, state.put(DELEGATED_TYPE, true), place)) { return } if (qualifierType !is GradleProjectAwareType) return val file = place.containingFile ?: return val extensionsData = GradleExtensionsContributor.getExtensionsFor(file) ?: return for (convention in extensionsData.conventions) { if (!createType(convention.typeFqn, file).processReceiverType(processor, state, place)) { return } } } }
apache-2.0
c5079aba45820541d3ffade77368b8b2
47.944444
133
0.799659
4.636842
false
false
false
false
kimar/space-from-outer-space
core/src/main/kotlin/io/kida/spacefromouterspace/model/Sounds.kt
1
615
package io.kida.spacefromouterspace.model import com.badlogic.gdx.Gdx import com.badlogic.gdx.audio.Sound /** * Created by kida on 5/01/2016. */ class Sounds { var missile: Sound? = null var explosion: Sound? = null var alien: Sound? = null fun load() { missile = Gdx.audio.newSound(Gdx.files.internal("sounds/missile.wav")) explosion = Gdx.audio.newSound(Gdx.files.internal("sounds/explosion.wav")) alien = Gdx.audio.newSound(Gdx.files.internal("sounds/alien.wav")) } fun unload() { missile = null explosion = null alien = null } }
mit
f876b75fb86641cba920fc6f76826774
22.692308
82
0.64065
3.435754
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/data/database/DbOpenCallback.kt
2
3665
package eu.kanade.tachiyomi.data.database import androidx.sqlite.db.SupportSQLiteDatabase import androidx.sqlite.db.SupportSQLiteOpenHelper import eu.kanade.tachiyomi.data.database.tables.CategoryTable import eu.kanade.tachiyomi.data.database.tables.ChapterTable import eu.kanade.tachiyomi.data.database.tables.HistoryTable import eu.kanade.tachiyomi.data.database.tables.MangaCategoryTable import eu.kanade.tachiyomi.data.database.tables.MangaTable import eu.kanade.tachiyomi.data.database.tables.TrackTable class DbOpenCallback : SupportSQLiteOpenHelper.Callback(DATABASE_VERSION) { companion object { /** * Name of the database file. */ const val DATABASE_NAME = "tachiyomi.db" /** * Version of the database. */ const val DATABASE_VERSION = 14 } override fun onCreate(db: SupportSQLiteDatabase) = with(db) { execSQL(MangaTable.createTableQuery) execSQL(ChapterTable.createTableQuery) execSQL(TrackTable.createTableQuery) execSQL(CategoryTable.createTableQuery) execSQL(MangaCategoryTable.createTableQuery) execSQL(HistoryTable.createTableQuery) // DB indexes execSQL(MangaTable.createUrlIndexQuery) execSQL(MangaTable.createLibraryIndexQuery) execSQL(ChapterTable.createMangaIdIndexQuery) execSQL(ChapterTable.createUnreadChaptersIndexQuery) execSQL(HistoryTable.createChapterIdIndexQuery) } override fun onUpgrade(db: SupportSQLiteDatabase, oldVersion: Int, newVersion: Int) { if (oldVersion < 2) { db.execSQL(ChapterTable.sourceOrderUpdateQuery) // Fix kissmanga covers after supporting cloudflare db.execSQL( """UPDATE mangas SET thumbnail_url = REPLACE(thumbnail_url, '93.174.95.110', 'kissmanga.com') WHERE source = 4""" ) } if (oldVersion < 3) { // Initialize history tables db.execSQL(HistoryTable.createTableQuery) db.execSQL(HistoryTable.createChapterIdIndexQuery) } if (oldVersion < 4) { db.execSQL(ChapterTable.bookmarkUpdateQuery) } if (oldVersion < 5) { db.execSQL(ChapterTable.addScanlator) } if (oldVersion < 6) { db.execSQL(TrackTable.addTrackingUrl) } if (oldVersion < 7) { db.execSQL(TrackTable.addLibraryId) } if (oldVersion < 8) { db.execSQL("DROP INDEX IF EXISTS mangas_favorite_index") db.execSQL(MangaTable.createLibraryIndexQuery) db.execSQL(ChapterTable.createUnreadChaptersIndexQuery) } if (oldVersion < 9) { db.execSQL(TrackTable.addStartDate) db.execSQL(TrackTable.addFinishDate) } if (oldVersion < 10) { db.execSQL(MangaTable.addCoverLastModified) } if (oldVersion < 11) { db.execSQL(MangaTable.addDateAdded) db.execSQL(MangaTable.backfillDateAdded) } if (oldVersion < 12) { db.execSQL(MangaTable.addNextUpdateCol) } if (oldVersion < 13) { db.execSQL(TrackTable.renameTableToTemp) db.execSQL(TrackTable.createTableQuery) db.execSQL(TrackTable.insertFromTempTable) db.execSQL(TrackTable.dropTempTable) } if (oldVersion < 14) { db.execSQL(ChapterTable.fixDateUploadIfNeeded) } } override fun onConfigure(db: SupportSQLiteDatabase) { db.setForeignKeyConstraintsEnabled(true) } }
apache-2.0
d1baf001aa06885fcfb70b0e92cf156f
34.931373
96
0.64693
4.586984
false
false
false
false
rs3vans/krypto
src/test/kotlin/com/github/rs3vans/krypto/testMessages.kt
1
2824
package com.github.rs3vans.krypto import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.Test private const val HMAC_KEY = "itjy6ug21s7YAcUAC5a/+g==" private const val MESSAGE = "Hello World!" private const val MESSAGE_PART_A = "Hello " private const val MESSAGE_PART_B = "World!" private const val HMAC_MESSAGE = "3aZ8watUQFJj5ViEJQlt7RUi4C8+ItnHkduwbt3W558=" private const val SHA256_MESSAGE = "f4OxZX/x/FO5LcGBSKHWXfwtSx+j1ncoSt3SABJtkGk=" private val key = importAesKey(HMAC_KEY.toBytesFromBase64()) class HmacCreateTests { @Test fun `it should create a SHA-256 HMAC digester from the given key`() { val digester = HmacDigester(key) assertThat(digester.algorithm, equalTo(HmacAlgorithms.SHA_256)) } @Test fun `it should create a SHA-1 HMAC digester from the given key`() { val digester = HmacDigester(key, algorithm = HmacAlgorithms.SHA_1) assertThat(digester.algorithm, equalTo(HmacAlgorithms.SHA_1)) } @Test fun `it should create a MD5 HMAC digester from the given key`() { val digester = HmacDigester(key, algorithm = HmacAlgorithms.MD5) assertThat(digester.algorithm, equalTo(HmacAlgorithms.MD5)) } } class HmacDigestTests { private val digester = HmacDigester(key) @Test fun `should digest message`() { val digested = digester.digest(MESSAGE.toBytes()) assertThat(digested.toBase64String(), equalTo(HMAC_MESSAGE)) } @Test fun `should digest message by parts`() { val digested = digester.digest(MESSAGE_PART_A.toBytes(), MESSAGE_PART_B.toBytes()) assertThat(digested.toBase64String(), equalTo(HMAC_MESSAGE)) } } class HashCreateTests { @Test fun `should create a SHA-256 hash digester`() { val digester = HashDigester() assertThat(digester.algorithm, equalTo(HashAlgorithms.SHA_256)) } @Test fun `should create a SHA-1 hash digester`() { val digester = HashDigester(algorithm = HashAlgorithms.SHA_1) assertThat(digester.algorithm, equalTo(HashAlgorithms.SHA_1)) } @Test fun `should create a MD5 hash digester`() { val digester = HashDigester(algorithm = HashAlgorithms.MD5) assertThat(digester.algorithm, equalTo(HashAlgorithms.MD5)) } } class HashDigestTests { private val digester = HashDigester() @Test fun `should digest message`() { val digested = digester.digest(MESSAGE.toBytes()) assertThat(digested.toBase64String(), equalTo(SHA256_MESSAGE)) } @Test fun `should digest message in parts`() { val digested = digester.digest(MESSAGE_PART_A.toBytes(), MESSAGE_PART_B.toBytes()) assertThat(digested.toBase64String(), equalTo(SHA256_MESSAGE)) } }
mit
fa74a14f5c088144fd5e223d0adfbfa8
26.696078
90
0.690864
3.745358
false
true
false
false
cascheberg/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/conversation/colors/ui/ChatColorSelectionState.kt
2
1279
package org.thoughtcrime.securesms.conversation.colors.ui import org.thoughtcrime.securesms.conversation.colors.ChatColors import org.thoughtcrime.securesms.conversation.colors.ChatColorsPalette import org.thoughtcrime.securesms.util.MappingModelList import org.thoughtcrime.securesms.wallpaper.ChatWallpaper data class ChatColorSelectionState( val wallpaper: ChatWallpaper? = null, val chatColors: ChatColors? = null, private val chatColorOptions: List<ChatColors> = listOf() ) { val chatColorModels: MappingModelList init { val models: List<ChatColorMappingModel> = chatColorOptions.map { chatColors -> ChatColorMappingModel( chatColors, chatColors == this.chatColors, false ) }.toList() val defaultModel: ChatColorMappingModel = if (wallpaper != null) { ChatColorMappingModel( wallpaper.autoChatColors, chatColors?.id == ChatColors.Id.Auto, true ) } else { ChatColorMappingModel( ChatColorsPalette.Bubbles.default.withId(ChatColors.Id.Auto), chatColors?.id == ChatColors.Id.Auto, true ) } chatColorModels = MappingModelList().apply { add(defaultModel) addAll(models) add(CustomColorMappingModel()) } } }
gpl-3.0
508627ea97b61d43be5750cd2b273c2e
27.422222
82
0.70602
4.472028
false
false
false
false
mdanielwork/intellij-community
plugins/github/src/org/jetbrains/plugins/github/api/requests/GithubRequestPagination.kt
5
469
// Copyright 2000-2018 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 org.jetbrains.plugins.github.api.requests class GithubRequestPagination @JvmOverloads constructor(val pageNumber: Int = 1, val pageSize: Int = DEFAULT_PAGE_SIZE) { override fun toString(): String { return "page=$pageNumber&per_page=$pageSize" } companion object { const val DEFAULT_PAGE_SIZE = 100 } }
apache-2.0
9a2f85216a696e9fb92cd556c8d16d47
38.083333
140
0.744136
4.008547
false
false
false
false
mdanielwork/intellij-community
platform/projectModel-api/src/com/intellij/util/containers/util.kt
4
4851
// Copyright 2000-2018 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.util.containers import com.intellij.util.SmartList import com.intellij.util.lang.CompoundRuntimeException import gnu.trove.THashSet import java.util.* import java.util.stream.Stream fun <K, V> MutableMap<K, MutableList<V>>.remove(key: K, value: V) { val list = get(key) if (list != null && list.remove(value) && list.isEmpty()) { remove(key) } } fun <K, V> MutableMap<K, MutableList<V>>.putValue(key: K, value: V) { val list = get(key) if (list == null) { put(key, SmartList<V>(value)) } else { list.add(value) } } fun Collection<*>?.isNullOrEmpty(): Boolean = this == null || isEmpty() inline fun <T, R> Iterator<T>.computeIfAny(processor: (T) -> R): R? { for (item in this) { val result = processor(item) if (result != null) { return result } } return null } inline fun <T, R> Array<T>.computeIfAny(processor: (T) -> R): R? { for (file in this) { val result = processor(file) if (result != null) { return result } } return null } inline fun <T, R> List<T>.computeIfAny(processor: (T) -> R): R? { for (item in this) { val result = processor(item) if (result != null) { return result } } return null } fun <T> List<T>?.nullize(): List<T>? = if (isNullOrEmpty()) null else this inline fun <T> Array<out T>.forEachGuaranteed(operation: (T) -> Unit) { var errors: MutableList<Throwable>? = null for (element in this) { try { operation(element) } catch (e: Throwable) { if (errors == null) { errors = SmartList() } errors.add(e) } } CompoundRuntimeException.throwIfNotEmpty(errors) } inline fun <T> Collection<T>.forEachGuaranteed(operation: (T) -> Unit) { var errors: MutableList<Throwable>? = null for (element in this) { try { operation(element) } catch (e: Throwable) { if (errors == null) { errors = SmartList() } errors.add(e) } } CompoundRuntimeException.throwIfNotEmpty(errors) } fun <T> Array<T>?.stream(): Stream<T> = if (this != null) Stream.of(*this) else Stream.empty() fun <T> Stream<T>?.isEmpty(): Boolean = this == null || !this.findAny().isPresent fun <T> Stream<T>?.notNullize(): Stream<T> = this ?: Stream.empty() fun <T> Stream<T>?.getIfSingle(): T? = this?.limit(2) ?.map { Optional.ofNullable(it) } ?.reduce(Optional.empty()) { a, b -> if (a.isPresent xor b.isPresent) b else Optional.empty() } ?.orElse(null) /** * There probably could be some performance issues if there is lots of streams to concat. See * http://mail.openjdk.java.net/pipermail/lambda-dev/2013-July/010659.html for some details. * * Also see [Stream.concat] documentation for other possible issues of concatenating large number of streams. */ fun <T> concat(vararg streams: Stream<T>): Stream<T> = Stream.of(*streams).reduce(Stream.empty()) { a, b -> Stream.concat(a, b) } inline fun MutableList<Throwable>.catch(runnable: () -> Unit) { try { runnable() } catch (e: Throwable) { add(e) } } inline fun <T, R> Array<out T>.mapSmart(transform: (T) -> R): List<R> { val size = size return when (size) { 1 -> SmartList(transform(this[0])) 0 -> SmartList() else -> mapTo(ArrayList(size), transform) } } inline fun <T, R> Collection<T>.mapSmart(transform: (T) -> R): List<R> { val size = size return when (size) { 1 -> SmartList(transform(first())) 0 -> emptyList() else -> mapTo(ArrayList(size), transform) } } /** * Not mutable set will be returned. */ inline fun <T, R> Collection<T>.mapSmartSet(transform: (T) -> R): Set<R> { val size = size return when (size) { 1 -> { val result = SmartHashSet<R>() result.add(transform(first())) result } 0 -> emptySet() else -> mapTo(THashSet(size), transform) } } inline fun <T, R : Any> Collection<T>.mapSmartNotNull(transform: (T) -> R?): List<R> { val size = size return if (size == 1) { transform(first())?.let { SmartList<R>(it) } ?: SmartList<R>() } else { mapNotNullTo(ArrayList(size), transform) } } fun <T> List<T>.toMutableSmartList(): MutableList<T> { return when (size) { 1 -> SmartList(first()) 0 -> SmartList() else -> ArrayList(this) } } inline fun <T> Collection<T>.filterSmart(predicate: (T) -> Boolean): List<T> { val result: MutableList<T> = when (size) { 1 -> SmartList() 0 -> return emptyList() else -> ArrayList() } filterTo(result, predicate) return result } inline fun <T> Collection<T>.filterSmartMutable(predicate: (T) -> Boolean): MutableList<T> { return filterTo(if (size <= 1) SmartList() else ArrayList(), predicate) }
apache-2.0
12a6cd187edf01d59eb28b59bd202a1c
25.086022
140
0.622758
3.378134
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/findUsages/KotlinFindUsagesProvider.kt
3
4044
// Copyright 2000-2021 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.findUsages import com.intellij.lang.cacheBuilder.WordsScanner import com.intellij.lang.findUsages.FindUsagesProvider import com.intellij.lang.java.JavaFindUsagesProvider import com.intellij.psi.* import org.jetbrains.kotlin.asJava.elements.KtLightElement import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.isPropertyParameter open class KotlinFindUsagesProviderBase : FindUsagesProvider { private val javaProvider by lazy { JavaFindUsagesProvider() } override fun canFindUsagesFor(psiElement: PsiElement): Boolean = psiElement is KtNamedDeclaration override fun getWordsScanner(): WordsScanner? = KotlinWordsScanner() override fun getHelpId(psiElement: PsiElement): String? = null override fun getType(element: PsiElement): String { return when (element) { is KtNamedFunction -> KotlinBundle.message("find.usages.function") is KtClass -> KotlinBundle.message("find.usages.class") is KtParameter -> KotlinBundle.message("find.usages.parameter") is KtProperty -> if (element.isLocal) KotlinBundle.message("find.usages.variable") else KotlinBundle.message("find.usages.property") is KtDestructuringDeclarationEntry -> KotlinBundle.message("find.usages.variable") is KtTypeParameter -> KotlinBundle.message("find.usages.type.parameter") is KtSecondaryConstructor -> KotlinBundle.message("find.usages.constructor") is KtObjectDeclaration -> KotlinBundle.message("find.usages.object") else -> "" } } val KtDeclaration.containerDescription: String? get() { containingClassOrObject?.let { return getDescriptiveName(it) } (parent as? KtFile)?.parent?.let { return getDescriptiveName(it) } return null } override fun getDescriptiveName(element: PsiElement): String { return when (element) { is PsiDirectory, is PsiPackage, is PsiFile -> javaProvider.getDescriptiveName(element) is KtClassOrObject -> { if (element is KtObjectDeclaration && element.isObjectLiteral()) return KotlinBundle.message("usage.provider.text.unnamed") run { @Suppress("HardCodedStringLiteral") element.fqName?.asString() } ?: element.name ?: KotlinBundle.message("usage.provider.text.unnamed") } is KtProperty -> { val name = element.name ?: "" element.containerDescription?.let { KotlinBundle.message("usage.provider.text.property.of.0", name, it) } ?: name } is KtFunction -> { //TODO: Correct FIR implementation return element.name?.let { "$it(...)" } ?: "" } is KtLabeledExpression -> { @Suppress("HardCodedStringLiteral") element.getLabelName() ?: "" } is KtImportAlias -> element.name ?: "" is KtLightElement<*, *> -> element.kotlinOrigin?.let { getDescriptiveName(it) } ?: "" is KtParameter -> { if (element.isPropertyParameter()) { val name = element.name ?: "" element.containerDescription?.let { KotlinBundle.message("usage.provider.text.property.of.0", name, it) } ?: name } else { element.name ?: "" } } is PsiNamedElement -> element.name ?: "" else -> "" } } override fun getNodeText(element: PsiElement, useFullName: Boolean): String = getDescriptiveName(element) }
apache-2.0
7257e5d7bbbebd613c3443803c288847
44.954545
158
0.630317
5.31406
false
false
false
false
richnou/ooxoo-core
gradle-ooxoo-plugin/src/main/kotlin/org/odfi/ooxoo/gradle/plugin/GeneratorFromModel.kt
1
3225
package org.odfi.ooxoo.gradle.plugin import com.idyria.osi.ooxoo.model.writers.FileWriters import org.gradle.workers.WorkAction import java.io.File abstract class GeneratorFromModel : WorkAction<XModelProducerParameters> { override fun execute() { TODO("Not yet implemented") // Compile //----------- /* println("Processing Model file (with reset): "+this.parameters.getModelFile()) val compiler = ModelCompiler() // ModelCompiler.resetCompiler() var modelInfos = ModelCompiler.compile(this.parameters.getModelFile()!!.get().asFile) var outputDir = this.parameters.getBuildOutput()!!.get().asFile // Get All Producers //--------- // Produce for all defined producers //--------------- modelInfos?.let { modelInfos -> modelInfos.producers()?.let { producersDef -> producersDef.value.forEach { producerAnnotation -> // Get Producer from def //-------------- var producer = producerAnnotation.value.primaryConstructor?.call()!! // Prepare output //----------- var producerOutputDir = File(outputDir,producer.outputType()) producerOutputDir.mkdirs() var out = FileWriters(producerOutputDir) // Produce //--------------- ModelCompiler.produce(modelInfos, producer, out) } } }*/ // EOF Something to produce // ModelCompiler.produce(modelInfos, producer, out) } companion object { fun produceModel(compiler: ModelCompiler, modelFile:File, outputDir:File) { // Compile //----------- println("Processing Model file: "+modelFile) var modelInfos = compiler.compile(modelFile) //var outputDir = this.parameters.getBuildOutput()!!.get().asFile // Get All Producers //--------- // Produce for all defined producers //--------------- modelInfos?.let { mif -> mif.producers()?.let { producersDef -> producersDef.value.forEach { producerAnnotation -> // Get Producer from def //-------------- var producer = producerAnnotation.value.java.getDeclaredConstructor().newInstance()!! // Prepare output //----------- var producerOutputDir = File(outputDir,producer.outputType()) producerOutputDir.mkdirs() var out = FileWriters(producerOutputDir) // Produce //--------------- compiler.produce(modelInfos, producer, out) //ModelCompiler.produce(modelInfos, producer, out) } } } } } }
agpl-3.0
aa4bdee80cd0536b18610420285df4b0
28.87037
109
0.477519
6.073446
false
false
false
false
dahlstrom-g/intellij-community
python/src/com/jetbrains/python/refactoring/suggested/PySuggestedRefactoringExecution.kt
12
3468
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.refactoring.suggested import com.intellij.refactoring.suggested.SuggestedChangeSignatureData import com.intellij.refactoring.suggested.SuggestedRefactoringExecution import com.intellij.refactoring.suggested.SuggestedRefactoringSupport.Parameter import com.jetbrains.python.psi.PyFunction import com.jetbrains.python.psi.impl.ParamHelper import com.jetbrains.python.refactoring.changeSignature.PyChangeSignatureProcessor import com.jetbrains.python.refactoring.changeSignature.PyParameterInfo internal class PySuggestedRefactoringExecution(support: PySuggestedRefactoringSupport) : SuggestedRefactoringExecution(support) { override fun prepareChangeSignature(data: SuggestedChangeSignatureData): Any? = null override fun performChangeSignature(data: SuggestedChangeSignatureData, newParameterValues: List<NewParameterValue>, preparedData: Any?) { val newParameterValuesIterator = newParameterValues.iterator() val parameterInfo = data.newSignature.parameters.map { newParameter -> val oldParameter = data.oldSignature.parameterById(newParameter.id) val oldIndex = if (oldParameter == null) -1 else data.oldSignature.parameterIndex(oldParameter) val oldName = oldParameter?.name ?: "" val newName = newParameter.name val (defaultValue, useValueInSignature) = defaultValueInfo(newParameter, oldParameter, newParameterValuesIterator) PyParameterInfo(oldIndex, oldName, defaultValue, useValueInSignature).apply { name = newName } } val function = data.declaration as PyFunction PyChangeSignatureProcessor(function.project, function, data.newSignature.name, parameterInfo.toTypedArray()).run() } private fun defaultValueInfo(newParameter: Parameter, oldParameter: Parameter?, newParametersValues: Iterator<NewParameterValue>): Pair<String?, Boolean> { if (!ParamHelper.couldHaveDefaultValue(newParameter.name)) return null to false val newDefaultValueInSignature = PySuggestedRefactoringSupport.defaultValue(newParameter) val defaultValue = defaultValueForProcessor( newDefaultValueInSignature, oldParameter?.let { PySuggestedRefactoringSupport.defaultValue(it) }, oldParameter == null, newParametersValues ) ?: return null to false return defaultValue to (newDefaultValueInSignature == defaultValue) } private fun defaultValueForProcessor(newDefaultValueInSignature: String?, oldDefaultValueInSignature: String?, added: Boolean, newParametersValues: Iterator<NewParameterValue>): String? { return if (added) { defaultValueOnCallSite(newParametersValues) ?: newDefaultValueInSignature } else if (newDefaultValueInSignature == null && oldDefaultValueInSignature != null) { defaultValueOnCallSite(newParametersValues) ?: oldDefaultValueInSignature } else { newDefaultValueInSignature ?: oldDefaultValueInSignature } } private fun defaultValueOnCallSite(newParametersValues: Iterator<NewParameterValue>): String? { val expression = newParametersValues.next() as? NewParameterValue.Expression ?: return null return expression.expression.text } }
apache-2.0
cf4976b14622873619f1d3f63728e9e2
47.180556
140
0.755767
5.657423
false
false
false
false
dahlstrom-g/intellij-community
python/src/com/jetbrains/python/codeInsight/typing/PyStubPackagesLoader.kt
8
6032
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.codeInsight.typing import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.projectRoots.Sdk import com.intellij.util.CatchingConsumer import com.intellij.webcore.packaging.PackageManagementService import com.intellij.webcore.packaging.RepoPackage import com.jetbrains.python.packaging.PyPIPackageUtil import com.jetbrains.python.packaging.PyPackage import java.util.* import java.util.function.BiConsumer fun loadStubPackagesForSources(sourcesToLoad: Set<String>, sourceToPackage: Map<String, String>, installedPackages: List<PyPackage>, availablePackages: List<RepoPackage>, packageManagementService: PackageManagementService, sdk: Sdk) { val sourceToStubPackagesAvailableToInstall = sourceToStubPackagesAvailableToInstall( sourceToInstalledRuntimeAndStubPackages(sourcesToLoad, sourceToPackage, installedPackages), availablePackages ) loadRequirementsAndExtraArgs( sourceToStubPackagesAvailableToInstall, packageManagementService, BiConsumer { source, stubPackagesForSource -> ApplicationManager.getApplication().getService(PyStubPackagesAdvertiserCache::class.java).forSdk(sdk).put(source, stubPackagesForSource) } ) } private fun sourceToInstalledRuntimeAndStubPackages(sourcesToLoad: Set<String>, sourceToPackage: Map<String, String>, installedPackages: List<PyPackage>): Map<String, List<Pair<PyPackage, PyPackage?>>> { val result = mutableMapOf<String, List<Pair<PyPackage, PyPackage?>>>() for (source in sourcesToLoad) { val pkgName = sourceToPackage[source] ?: continue installedRuntimeAndStubPackages(pkgName, installedPackages)?.let { result.put(source, listOf(it)) } } return result } private fun sourceToStubPackagesAvailableToInstall(sourceToInstalledRuntimeAndStubPkgs: Map<String, List<Pair<PyPackage, PyPackage?>>>, availablePackages: List<RepoPackage>): Map<String, Set<RepoPackage>> { if (sourceToInstalledRuntimeAndStubPkgs.isEmpty()) return emptyMap() val stubPkgsAvailableToInstall = mutableMapOf<String, RepoPackage>() availablePackages.forEach { if (it.name.endsWith(STUBS_SUFFIX)) stubPkgsAvailableToInstall[it.name] = it } val result = mutableMapOf<String, Set<RepoPackage>>() sourceToInstalledRuntimeAndStubPkgs.forEach { (source, runtimeAndStubPkgs) -> result[source] = runtimeAndStubPkgs .asSequence() .filter { it.second == null } .mapNotNull { stubPkgsAvailableToInstall["${it.first.name}$STUBS_SUFFIX"] } .toSet() } return result } private fun loadRequirementsAndExtraArgs(sourceToStubPackagesAvailableToInstall: Map<String, Set<RepoPackage>>, packageManagementService: PackageManagementService, consumer: BiConsumer<String, PyStubPackagesAdvertiserCache.Companion.StubPackagesForSource>) { val commonState = CommonState(packageManagementService, consumer) for ((source, stubPackages) in sourceToStubPackagesAvailableToInstall) { if (stubPackages.isNotEmpty()) { val queue = LinkedList(stubPackages) loadRequirementAndExtraArgsForPackageAndThenContinueForSource( SourcePackageState(source, queue.poll(), queue, mutableMapOf(), commonState) ) } } } private fun installedRuntimeAndStubPackages(pkgName: String, installedPackages: List<PyPackage>): Pair<PyPackage, PyPackage?>? { var runtime: PyPackage? = null var stub: PyPackage? = null val stubPkgName = "$pkgName$STUBS_SUFFIX" for (pkg in installedPackages) { val name = pkg.name if (name == pkgName) runtime = pkg if (name == stubPkgName) stub = pkg } return if (runtime == null) null else runtime to stub } private fun loadRequirementAndExtraArgsForPackageAndThenContinueForSource(state: SourcePackageState) { val commonState = state.commonState val name = state.pkg.name commonState.packageManagementService.fetchPackageVersions( name, object : CatchingConsumer<List<String>, Exception> { override fun consume(e: Exception?) = continueLoadingRequirementsAndExtraArgsForSource(state) override fun consume(t: List<String>?) { if (!t.isNullOrEmpty()) { val url = state.pkg.repoUrl val extraArgs = if (!url.isNullOrBlank() && !PyPIPackageUtil.isPyPIRepository(url)) { listOf("--extra-index-url", url) } else { emptyList() } state.result[name] = t.first() to extraArgs } continueLoadingRequirementsAndExtraArgsForSource(state) } } ) } private fun continueLoadingRequirementsAndExtraArgsForSource(state: SourcePackageState) { val nextState = state.moveToNextPackage() if (nextState != null) { loadRequirementAndExtraArgsForPackageAndThenContinueForSource(nextState) } else { state.commonState.sourceResultConsumer.accept( state.source, PyStubPackagesAdvertiserCache.Companion.StubPackagesForSource.create(state.result) ) } } private class SourcePackageState( val source: String, val pkg: RepoPackage, val queue: Queue<RepoPackage>, val result: MutableMap<String, Pair<String, List<String>>>, val commonState: CommonState ) { fun moveToNextPackage(): SourcePackageState? { return queue.poll()?.let { SourcePackageState(source, it, queue, result, commonState) } } } private class CommonState( val packageManagementService: PackageManagementService, val sourceResultConsumer: BiConsumer<String, PyStubPackagesAdvertiserCache.Companion.StubPackagesForSource> )
apache-2.0
4b37ad22e1b8a4cb9438b170d8d4b1c6
38.431373
142
0.712533
4.701481
false
false
false
false
dahlstrom-g/intellij-community
platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/CustomPackagingElementEntityImpl.kt
2
15544
package com.intellij.workspaceModel.storage.bridgeEntities.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableReferableWorkspaceEntity import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyChildren import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyParent import com.intellij.workspaceModel.storage.impl.extractOneToAbstractOneParent import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyChildrenOfParent import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild import com.intellij.workspaceModel.storage.impl.updateOneToAbstractOneParentOfChild import com.intellij.workspaceModel.storage.referrersx import com.intellij.workspaceModel.storage.url.VirtualFileUrl import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Abstract import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class CustomPackagingElementEntityImpl: CustomPackagingElementEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositePackagingElementEntity::class.java, PackagingElementEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true) internal val ARTIFACT_CONNECTION_ID: ConnectionId = ConnectionId.create(ArtifactEntity::class.java, CompositePackagingElementEntity::class.java, ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE, true) internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositePackagingElementEntity::class.java, PackagingElementEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, ARTIFACT_CONNECTION_ID, CHILDREN_CONNECTION_ID, ) } override val parentEntity: CompositePackagingElementEntity? get() = snapshot.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) override val artifact: ArtifactEntity? get() = snapshot.extractOneToAbstractOneParent(ARTIFACT_CONNECTION_ID, this) override val children: List<PackagingElementEntity> get() = snapshot.extractOneToAbstractManyChildren<PackagingElementEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() @JvmField var _typeId: String? = null override val typeId: String get() = _typeId!! @JvmField var _propertiesXmlTag: String? = null override val propertiesXmlTag: String get() = _propertiesXmlTag!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: CustomPackagingElementEntityData?): ModifiableWorkspaceEntityBase<CustomPackagingElementEntity>(), CustomPackagingElementEntity.Builder { constructor(): this(CustomPackagingElementEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity CustomPackagingElementEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) { error("Field CompositePackagingElementEntity#children should be initialized") } } else { if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) { error("Field CompositePackagingElementEntity#children should be initialized") } } if (!getEntityData().isTypeIdInitialized()) { error("Field CustomPackagingElementEntity#typeId should be initialized") } if (!getEntityData().isEntitySourceInitialized()) { error("Field CustomPackagingElementEntity#entitySource should be initialized") } if (!getEntityData().isPropertiesXmlTagInitialized()) { error("Field CustomPackagingElementEntity#propertiesXmlTag should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } override var parentEntity: CompositePackagingElementEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToAbstractManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } override var artifact: ArtifactEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractOneParent(ARTIFACT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, ARTIFACT_CONNECTION_ID)] as? ArtifactEntity } else { this.entityLinks[EntityLink(false, ARTIFACT_CONNECTION_ID)] as? ArtifactEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, ARTIFACT_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToAbstractOneParentOfChild(ARTIFACT_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, ARTIFACT_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, ARTIFACT_CONNECTION_ID)] = value } changedProperty.add("artifact") } override var children: List<PackagingElementEntity> get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractManyChildren<PackagingElementEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<PackagingElementEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as List<PackagingElementEntity> ?: emptyList() } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) { _diff.addEntity(item_value) } } _diff.updateOneToAbstractManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value.asSequence()) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*>) { item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value } changedProperty.add("children") } override var typeId: String get() = getEntityData().typeId set(value) { checkModificationAllowed() getEntityData().typeId = value changedProperty.add("typeId") } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var propertiesXmlTag: String get() = getEntityData().propertiesXmlTag set(value) { checkModificationAllowed() getEntityData().propertiesXmlTag = value changedProperty.add("propertiesXmlTag") } override fun getEntityData(): CustomPackagingElementEntityData = result ?: super.getEntityData() as CustomPackagingElementEntityData override fun getEntityClass(): Class<CustomPackagingElementEntity> = CustomPackagingElementEntity::class.java } } class CustomPackagingElementEntityData : WorkspaceEntityData<CustomPackagingElementEntity>() { lateinit var typeId: String lateinit var propertiesXmlTag: String fun isTypeIdInitialized(): Boolean = ::typeId.isInitialized fun isPropertiesXmlTagInitialized(): Boolean = ::propertiesXmlTag.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<CustomPackagingElementEntity> { val modifiable = CustomPackagingElementEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): CustomPackagingElementEntity { val entity = CustomPackagingElementEntityImpl() entity._typeId = typeId entity._propertiesXmlTag = propertiesXmlTag entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return CustomPackagingElementEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as CustomPackagingElementEntityData if (this.typeId != other.typeId) return false if (this.entitySource != other.entitySource) return false if (this.propertiesXmlTag != other.propertiesXmlTag) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as CustomPackagingElementEntityData if (this.typeId != other.typeId) return false if (this.propertiesXmlTag != other.propertiesXmlTag) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + typeId.hashCode() result = 31 * result + propertiesXmlTag.hashCode() return result } }
apache-2.0
32afd4383d451ccbefc3eb6b74a34880
46.978395
238
0.622234
6.252615
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/ecs/src/main/kotlin/com/kotlin/ecs/CreateCluster.kt
1
2238
// snippet-sourcedescription:[CreateCluster.kt demonstrates how to create a cluster for the Amazon Elastic Container Service (Amazon ECS) service.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[Amazon Elastic Container Service] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.ecs // snippet-start:[ecs.kotlin.create_cluster.import] import aws.sdk.kotlin.services.ecs.EcsClient import aws.sdk.kotlin.services.ecs.model.ClusterConfiguration import aws.sdk.kotlin.services.ecs.model.CreateClusterRequest import aws.sdk.kotlin.services.ecs.model.ExecuteCommandConfiguration import aws.sdk.kotlin.services.ecs.model.ExecuteCommandLogging import kotlin.system.exitProcess // snippet-end:[ecs.kotlin.create_cluster.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <clusterName> Where: clusterName - The name of the ECS cluster to create. """ if (args.size != 1) { println(usage) exitProcess(0) } val clusterName = args[0] val clusterArn = createGivenCluster(clusterName) println("The cluster ARN is $clusterArn") } // snippet-start:[ecs.kotlin.create_cluster.main] suspend fun createGivenCluster(clusterNameVal: String?): String? { val commandConfiguration = ExecuteCommandConfiguration { logging = ExecuteCommandLogging.Default } val clusterConfiguration = ClusterConfiguration { executeCommandConfiguration = commandConfiguration } val request = CreateClusterRequest { clusterName = clusterNameVal configuration = clusterConfiguration } EcsClient { region = "us-east-1" }.use { ecsClient -> val response = ecsClient.createCluster(request) return response.cluster?.clusterArn } } // snippet-end:[ecs.kotlin.create_cluster.main]
apache-2.0
2fd215d0f2e699e55c9025ef5e8016d3
29.083333
147
0.709562
4.198874
false
true
false
false
seratch/jslack
slack-api-model-kotlin-extension/src/main/kotlin/com/slack/api/model/kotlin_extension/block/element/UsersSelectElementBuilder.kt
1
2708
package com.slack.api.model.kotlin_extension.block.element import com.slack.api.model.block.composition.ConfirmationDialogObject import com.slack.api.model.block.composition.PlainTextObject import com.slack.api.model.block.element.UsersSelectElement import com.slack.api.model.kotlin_extension.block.BlockLayoutBuilder import com.slack.api.model.kotlin_extension.block.Builder import com.slack.api.model.kotlin_extension.block.composition.ConfirmationDialogObjectBuilder @BlockLayoutBuilder class UsersSelectElementBuilder : Builder<UsersSelectElement> { private var placeholder: PlainTextObject? = null private var actionId: String? = null private var initialUser: String? = null private var confirm: ConfirmationDialogObject? = null /** * Adds a plain text object to the placeholder field. * * The placeholder text shown on the menu. Maximum length for the text in this field is 150. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#users_select">Users select element documentation</a> */ fun placeholder(text: String, emoji: Boolean? = null) { placeholder = PlainTextObject(text, emoji) } /** * An identifier for the action triggered when a menu option is selected. You can use this when you receive an * interaction payload to identify the source of the action. Should be unique among all other action_ids used * elsewhere by your app. Maximum length for this field is 255 characters. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#users_select">Users select element documentation</a> */ fun actionId(id: String) { actionId = id } /** * The user ID of any valid user to be pre-selected when the menu loads. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#users_select">Users select element documentation</a> */ fun initialUser(user: String) { initialUser = user } /** * A confirm object that defines an optional confirmation dialog that appears after a menu item is selected. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#users_select">Users select element documentation</a> */ fun confirm(builder: ConfirmationDialogObjectBuilder.() -> Unit) { confirm = ConfirmationDialogObjectBuilder().apply(builder).build() } override fun build(): UsersSelectElement { return UsersSelectElement.builder() .placeholder(placeholder) .actionId(actionId) .initialUser(initialUser) .confirm(confirm) .build() } }
mit
df35fa6c5ccb463e78089a4a88bf0483
40.676923
130
0.700148
4.374798
false
false
false
false
PaulWoitaschek/MaterialAudiobookPlayer
data/src/main/java/de/ph1b/audiobook/data/repo/internals/BookSettingsDao.kt
1
889
package de.ph1b.audiobook.data.repo.internals import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Update import de.ph1b.audiobook.data.BookSettings import java.util.UUID @Dao interface BookSettingsDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(bookSettings: BookSettings) @Query("SELECT * FROM bookSettings") fun all(): List<BookSettings> @Query("UPDATE bookSettings SET active=:active WHERE id=:id") fun setActive(id: UUID, active: Boolean) @Delete fun delete(bookSettings: BookSettings) @Query("UPDATE bookSettings SET lastPlayedAtMillis = :lastPlayedAtMillis WHERE id = :id") fun updateLastPlayedAt(id: UUID, lastPlayedAtMillis: Long) @Update(onConflict = OnConflictStrategy.FAIL) fun update(settings: BookSettings) }
lgpl-3.0
5183fc9e6d4b47f40d8158f03e3a4388
26.78125
91
0.787402
3.951111
false
false
false
false
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/translations/sorting/template.kt
1
2798
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.translations.sorting import com.intellij.openapi.application.PathManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtil import com.intellij.project.stateStore import java.io.File sealed class TemplateElement data class Comment(val text: String) : TemplateElement() data class Key(val matcher: Regex) : TemplateElement() object EmptyLine : TemplateElement() data class Template(val elements: List<TemplateElement>) { companion object { fun parse(s: String): Template = Template( if (s.isNotEmpty()) { s.split('\n').map { when { it.isEmpty() -> EmptyLine it.startsWith('#') -> Comment(it.substring(1).trim()) else -> Key(parseKey(it.trim())) } } } else { listOf() } ) private val keyRegex = Regex("([?!]?[+*]?)([^+*!?]*)([?!]?[+*]?)") private fun parseKey(s: String) = keyRegex.findAll(s).map { parseQuantifier(it.groupValues[1]) + Regex.escape(it.groupValues[2]) + parseQuantifier(it.groupValues[3]) }.joinToString("", "^", "$").toRegex() private fun parseQuantifier(q: String?) = when (q) { "!" -> "([^.])" "!+" -> "([^.]+)" "!*" -> "([^.]*)" "?" -> "(.)" "?+" -> "(..+)" "+", "?*" -> "(.+)" "*" -> "(.*?)" else -> "" } } } object TemplateManager { private const val FILE_NAME = "minecraft_localization_template.lang" private fun globalFile(): File = File(PathManager.getConfigPath(), FILE_NAME) private fun projectFile(project: Project): File = File(FileUtil.toSystemDependentName(project.stateStore.getDirectoryStorePath(false)!!), FILE_NAME) fun getGlobalTemplateText() = if (globalFile().exists()) globalFile().readText() else "" fun getProjectTemplateText(project: Project) = projectFile(project).let { if (it.exists()) it.readText() else getGlobalTemplateText() } fun getGlobalTemplate() = Template.parse(getGlobalTemplateText()) fun getProjectTemplate(project: Project) = Template.parse(getProjectTemplateText(project)) fun writeGlobalTemplate(text: String) = globalFile().writeText(text) fun writeProjectTemplate(project: Project, text: String) = projectFile(project).writeText(text) }
mit
fadcc90be104609ea72ae1a7a2f58ec2
30.088889
106
0.551108
4.594417
false
false
false
false
google/intellij-community
platform/vcs-impl/src/com/intellij/vcs/commit/ShowNotificationCommitResultHandler.kt
2
3840
// 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.vcs.commit import com.intellij.notification.NotificationType import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.text.HtmlBuilder import com.intellij.openapi.util.text.HtmlChunk import com.intellij.openapi.util.text.StringUtil.isEmpty import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.VcsNotificationIdsHolder.Companion.COMMIT_CANCELED import com.intellij.openapi.vcs.VcsNotificationIdsHolder.Companion.COMMIT_FAILED import com.intellij.openapi.vcs.VcsNotificationIdsHolder.Companion.COMMIT_FINISHED import com.intellij.openapi.vcs.VcsNotificationIdsHolder.Companion.COMMIT_FINISHED_WITH_WARNINGS import com.intellij.openapi.vcs.VcsNotifier import com.intellij.vcs.commit.Committer.Companion.collectErrors import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls private fun hasOnlyWarnings(exceptions: List<VcsException>) = exceptions.all { it.isWarning } class ShowNotificationCommitResultHandler(private val committer: VcsCommitter) : CommitterResultHandler { private val notifier = VcsNotifier.getInstance(committer.project) override fun onSuccess() = reportResult() override fun onCancel() { notifier.notifyMinorWarning(COMMIT_CANCELED, "", message("vcs.commit.canceled")) } override fun onFailure() = reportResult() private fun reportResult() { val message = getCommitSummary() val allExceptions = committer.exceptions if (allExceptions.isEmpty()) { notifier.notifySuccess(COMMIT_FINISHED, "", message) return } val errors = collectErrors(allExceptions) val errorsSize = errors.size val warningsSize = allExceptions.size - errorsSize val notificationActions = allExceptions.filterIsInstance<CommitExceptionWithActions>().flatMap { it.actions } val title: @NlsContexts.NotificationTitle String val displayId: @NonNls String val notificationType: NotificationType if (errorsSize > 0) { displayId = COMMIT_FAILED title = message("message.text.commit.failed.with.error", errorsSize) notificationType = NotificationType.ERROR } else { displayId = COMMIT_FINISHED_WITH_WARNINGS title = message("message.text.commit.finished.with.warning", warningsSize) notificationType = NotificationType.WARNING } val notification = VcsNotifier.IMPORTANT_ERROR_NOTIFICATION.createNotification(title, message, notificationType) notification.setDisplayId(displayId) notificationActions.forEach { notification.addAction(it) } VcsNotifier.addShowDetailsAction(committer.project, notification) notification.notify(committer.project) } @NlsContexts.NotificationContent private fun getCommitSummary() = HtmlBuilder().apply { append(getFileSummaryReport()) val commitMessage = committer.commitMessage if (!isEmpty(commitMessage)) { append(": ").append(commitMessage) // NON-NLS } val feedback = committer.feedback if (feedback.isNotEmpty()) { br() appendWithSeparators(HtmlChunk.br(), feedback.map(HtmlChunk::text)) } val exceptions = committer.exceptions if (!hasOnlyWarnings(exceptions)) { br() appendWithSeparators(HtmlChunk.br(), exceptions.map { HtmlChunk.text(it.message) }) } }.toString() private fun getFileSummaryReport(): @Nls String { val failed = committer.failedToCommitChanges.size val committed = committer.changes.size - failed if (failed > 0) { return message("vcs.commit.files.committed.and.files.failed.to.commit", committed, failed) } return message("vcs.commit.files.committed", committed) } }
apache-2.0
5eaf95fd71e379414d197230b2cd5ae7
39.861702
140
0.763542
4.544379
false
false
false
false
physphil/UnitConverterUltimate-Studio
app/src/main/java/com/physphil/android/unitconverterultimate/models/Language.kt
1
2838
/* * Copyright 2017 Phil Shadlyn * * 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.physphil.android.unitconverterultimate.models import com.physphil.android.unitconverterultimate.R // ISO-639 Language codes private const val LANG_DEFAULT = "def" private const val LANG_CROATIAN = "hr" private const val LANG_ENGLISH = "en" private const val LANG_FARSI = "fa" private const val LANG_FRENCH = "fr" private const val LANG_GERMAN = "de" private const val LANG_HUNGARIAN = "hu" private const val LANG_ITALIAN = "it" private const val LANG_JAPANESE = "ja" private const val LANG_PORTUGUESE_BR = "pt_BR" private const val LANG_RUSSIAN = "ru" private const val LANG_SPANISH = "es" private const val LANG_TURKISH = "tr" /** * Represents a Language that a user can select to display the app in. * Copyright (c) 2017 Phil Shadlyn */ enum class Language(val id: String) { DEFAULT(LANG_DEFAULT), CROATIAN(LANG_CROATIAN), ENGLISH(LANG_ENGLISH), FARSI(LANG_FARSI), FRENCH(LANG_FRENCH), GERMAN(LANG_GERMAN), HUNGARIAN(LANG_HUNGARIAN), ITALIAN(LANG_ITALIAN), JAPANESE(LANG_JAPANESE), PORTUGUESE_BR(LANG_PORTUGUESE_BR), RUSSIAN(LANG_RUSSIAN), SPANISH(LANG_SPANISH), TURKISH(LANG_TURKISH); val displayStringId = when (id) { LANG_CROATIAN -> R.string.language_croatian LANG_ENGLISH -> R.string.language_english LANG_FARSI -> R.string.language_farsi LANG_FRENCH -> R.string.language_french LANG_GERMAN -> R.string.language_german LANG_HUNGARIAN -> R.string.language_hungarian LANG_ITALIAN -> R.string.language_italian LANG_JAPANESE -> R.string.language_japanese LANG_PORTUGUESE_BR -> R.string.language_portuguese_brazil LANG_RUSSIAN -> R.string.language_russian LANG_SPANISH -> R.string.language_spanish LANG_TURKISH -> R.string.language_turkish else -> R.string.language_default } companion object { /** * Get the Language corresponding to the given id. * @param id ISO-639 code for the Language value * @return the Language corresponding to the given id, or DEFAULT if the language id is not supported */ @JvmStatic fun fromId(id: String) = values().firstOrNull { it.id == id } ?: DEFAULT } }
gpl-3.0
130e8105d2838885b3966be3098edc0d
34.4875
109
0.692741
3.615287
false
false
false
false
google/intellij-community
platform/credential-store/src/kdbx/ProtectedValue.kt
6
4090
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.credentialStore.kdbx import com.intellij.configurationStore.JbXmlOutputter import com.intellij.credentialStore.OneTimeString import org.bouncycastle.crypto.SkippingStreamCipher import org.jdom.Element import org.jdom.Text import java.io.Writer import java.util.* internal interface SecureString { fun get(clearable: Boolean = true): OneTimeString } internal class ProtectedValue(private var encryptedValue: ByteArray, private var position: Int, private var streamCipher: SkippingStreamCipher) : Text(), SecureString { @Synchronized override fun get(clearable: Boolean): OneTimeString { val output = ByteArray(encryptedValue.size) decryptInto(output) return OneTimeString(output, clearable = clearable) } @Synchronized fun setNewStreamCipher(newStreamCipher: SkippingStreamCipher) { val value = encryptedValue decryptInto(value) position = newStreamCipher.position.toInt() newStreamCipher.processBytes(value, 0, value.size, value, 0) streamCipher = newStreamCipher } @Synchronized private fun decryptInto(out: ByteArray) { streamCipher.seekTo(position.toLong()) streamCipher.processBytes(encryptedValue, 0, encryptedValue.size, out, 0) } override fun getText() = throw IllegalStateException("encodeToBase64 must be used for serialization") fun encodeToBase64(): String { return when { encryptedValue.isEmpty() -> "" else -> Base64.getEncoder().encodeToString(encryptedValue) } } } internal class UnsavedProtectedValue(val secureString: StringProtectedByStreamCipher) : Text(), SecureString by secureString { override fun getText() = throw IllegalStateException("Must be converted to ProtectedValue for serialization") } internal class ProtectedXmlWriter(private val streamCipher: SkippingStreamCipher) : JbXmlOutputter(isForbidSensitiveData = false) { override fun writeContent(out: Writer, element: Element, level: Int): Boolean { if (element.name != KdbxEntryElementNames.value) { return super.writeContent(out, element, level) } val value = element.content.firstOrNull() if (value is SecureString) { val protectedValue: ProtectedValue if (value is ProtectedValue) { value.setNewStreamCipher(streamCipher) protectedValue = value } else { val bytes = (value as UnsavedProtectedValue).secureString.getAsByteArray() val position = streamCipher.position.toInt() streamCipher.processBytes(bytes, 0, bytes.size, bytes, 0) protectedValue = ProtectedValue(bytes, position, streamCipher) element.setContent(protectedValue) } out.write('>'.code) out.write(escapeElementEntities(protectedValue.encodeToBase64())) return true } return super.writeContent(out, element, level) } } internal fun isValueProtected(valueElement: Element): Boolean { return valueElement.getAttributeValue(KdbxAttributeNames.protected).equals("true", ignoreCase = true) } internal class XmlProtectedValueTransformer(private val streamCipher: SkippingStreamCipher) { private var position = 0 fun processEntries(parentElement: Element) { // we must process in exact order for (element in parentElement.content) { if (element !is Element) { continue } if (element.name == KdbxDbElementNames.group) { processEntries(element) } else if (element.name == KdbxDbElementNames.entry) { for (container in element.getChildren(KdbxEntryElementNames.string)) { val valueElement = container.getChild(KdbxEntryElementNames.value) ?: continue if (isValueProtected(valueElement)) { val value = Base64.getDecoder().decode(valueElement.text) valueElement.setContent(ProtectedValue(value, position, streamCipher)) position += value.size } } } } } }
apache-2.0
6ca485ee1ef903c061be022afdaf55cc
34.573913
131
0.717848
4.722864
false
false
false
false
allotria/intellij-community
platform/execution-impl/src/com/intellij/execution/stateWidget/StateWidgetChooserAdditionGroup.kt
2
1387
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.stateWidget import com.intellij.execution.Executor import com.intellij.execution.ExecutorRegistryImpl.ExecutorGroupActionGroup import com.intellij.execution.executors.ExecutorGroup import com.intellij.execution.segmentedRunDebugWidget.StateWidgetManager import com.intellij.execution.stateExecutionWidget.StateWidgetProcess import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent internal class StateWidgetChooserAdditionGroup(val executorGroup: ExecutorGroup<*>, process: StateWidgetProcess, childConverter: (Executor) -> AnAction) : ExecutorGroupActionGroup(executorGroup, childConverter) { var myProcess: StateWidgetProcess? = null init { myProcess = process val presentation = templatePresentation presentation.text = executorGroup.getStateWidgetChooserText() isPopup = true } override fun update(e: AnActionEvent) { super.update(e) e.project?.let { e.presentation.isEnabledAndVisible = StateWidgetManager.getInstance(it).getExecutionsCount() == 0 } } }
apache-2.0
1e36c3240be8d2fdd25d5f6f92d27399
45.266667
140
0.714492
5.099265
false
false
false
false
leafclick/intellij-community
platform/credential-store/test/CredentialStoreTest.kt
1
6463
// Copyright 2000-2018 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.credentialStore import com.intellij.credentialStore.keePass.InMemoryCredentialStore import com.intellij.openapi.util.SystemInfo import com.intellij.testFramework.UsefulTestCase import org.assertj.core.api.Assertions.assertThat import org.junit.AssumptionViolatedException import org.junit.Test import java.io.Closeable import java.util.* private val TEST_SERVICE_NAME = generateServiceName("Test", "test") inline fun macTest(task: () -> Unit) { if (SystemInfo.isMacIntel64 && !UsefulTestCase.IS_UNDER_TEAMCITY) { task() } } internal class CredentialStoreTest { @Test fun linux() { if (!SystemInfo.isLinux || UsefulTestCase.IS_UNDER_TEAMCITY) { return } val store = SecretCredentialStore.create("com.intellij.test") if (store == null) throw AssumptionViolatedException("No secret service") doTest(store) } @Test fun linuxKWallet() { if (!SystemInfo.isLinux || UsefulTestCase.IS_UNDER_TEAMCITY) { return } val kWallet = KWalletCredentialStore.create() if (kWallet == null) { throw AssumptionViolatedException("No KWallet") } doTest(kWallet) } @Test fun mac() { macTest { doTest(KeyChainCredentialStore()) } } @Test fun keePass() { doTest(InMemoryCredentialStore()) } @Test fun `mac - testEmptyAccountName`() { macTest { testEmptyAccountName(KeyChainCredentialStore()) } } @Test fun `mac - changedAccountName`() { macTest { testChangedAccountName(KeyChainCredentialStore()) } } @Test fun `linux - testEmptyAccountName`() { if (isLinuxSupported()) { val store = SecretCredentialStore.create("com.intellij.test") if (store != null) testEmptyAccountName(store) } } private fun isLinuxSupported() = SystemInfo.isLinux && !UsefulTestCase.IS_UNDER_TEAMCITY @Test fun `KeePass - testEmptyAccountName`() { testEmptyAccountName(InMemoryCredentialStore()) } @Test fun `KeePass - testEmptyStrAccountName`() { testEmptyStrAccountName(InMemoryCredentialStore()) } @Test fun `KeePass - changedAccountName`() { testChangedAccountName(InMemoryCredentialStore()) } @Test fun `KeePass - memoryOnlyPassword`() { memoryOnlyPassword(InMemoryCredentialStore()) } @Test fun `Keychain - memoryOnlyPassword`() { macTest { memoryOnlyPassword(KeyChainCredentialStore()) } } @Test fun `linux - memoryOnlyPassword`() { if (isLinuxSupported()) { val store = SecretCredentialStore.create("com.intellij.test") if (store != null) memoryOnlyPassword(store) } } private fun memoryOnlyPassword(store: CredentialStore) { val pass = randomString() val userName = randomString() val serviceName = randomString() store.set(CredentialAttributes(serviceName, userName, isPasswordMemoryOnly = true), Credentials(userName, pass)) val credentials = store.get(CredentialAttributes(serviceName, userName)) @Suppress("UsePropertyAccessSyntax") assertThat(credentials).isNotNull() assertThat(credentials!!.userName).isEqualTo(userName) assertThat(credentials.password).isNullOrEmpty() } private fun doTest(store: CredentialStore) { val pass = randomString() store.setPassword(CredentialAttributes(TEST_SERVICE_NAME, "test"), pass) assertThat(store.getPassword(CredentialAttributes(TEST_SERVICE_NAME, "test"))).isEqualTo(pass) store.set(CredentialAttributes(TEST_SERVICE_NAME, "test"), null) assertThat(store.get(CredentialAttributes(TEST_SERVICE_NAME, "test"))).isNull() val unicodePassword = "Gr\u00FCnwald" store.setPassword(CredentialAttributes(TEST_SERVICE_NAME, "test"), unicodePassword) assertThat(store.getPassword(CredentialAttributes(TEST_SERVICE_NAME, "test"))).isEqualTo(unicodePassword) val unicodeAttributes = CredentialAttributes(TEST_SERVICE_NAME, unicodePassword) store.setPassword(unicodeAttributes, pass) assertThat(store.getPassword(unicodeAttributes)).isEqualTo(pass) if (store is Closeable) store.close() } private fun testEmptyAccountName(store: CredentialStore) { val serviceNameOnlyAttributes = CredentialAttributes("Test IJ — ${randomString()}") try { val credentials = Credentials(randomString(), "pass") store.set(serviceNameOnlyAttributes, credentials) assertThat(store.get(serviceNameOnlyAttributes)).isEqualTo(credentials) } finally { store.set(serviceNameOnlyAttributes, null) } val userName = randomString() val attributes = CredentialAttributes("Test IJ — ${randomString()}", userName) try { store.set(attributes, Credentials(userName)) assertThat(store.get(attributes)).isEqualTo(Credentials(userName, if (store is KeyChainCredentialStore) "" else null)) } finally { store.set(attributes, null) } } private fun testEmptyStrAccountName(store: CredentialStore) { val attributes = CredentialAttributes("Test IJ — ${randomString()}", "") try { val credentials = Credentials("", "pass") store.set(attributes, credentials) assertThat(store.get(attributes)).isEqualTo(credentials) } finally { store.set(attributes, null) } assertThat(store.get(attributes)).isNull() } private fun testChangedAccountName(store: CredentialStore) { val serviceNameOnlyAttributes = CredentialAttributes("Test IJ — ${randomString()}") try { val credentials = Credentials(randomString(), "pass") var newUserName = randomString() val newPassword = randomString() store.set(serviceNameOnlyAttributes, credentials) assertThat(store.get(serviceNameOnlyAttributes)).isEqualTo(credentials) store.set(CredentialAttributes(serviceNameOnlyAttributes.serviceName, newUserName), Credentials(newUserName, newPassword)) assertThat(store.get(serviceNameOnlyAttributes)).isEqualTo(Credentials(newUserName, newPassword)) newUserName = randomString() store.set(CredentialAttributes(serviceNameOnlyAttributes.serviceName, newUserName), Credentials(newUserName, newPassword)) assertThat(store.get(serviceNameOnlyAttributes)!!.userName).isEqualTo(newUserName) } finally { store.set(serviceNameOnlyAttributes, null) } } } internal fun randomString() = UUID.randomUUID().toString()
apache-2.0
290704c193930911cdfdbc694f81e0b1
31.771574
140
0.724245
4.587775
false
true
false
false
zdary/intellij-community
platform/platform-impl/src/com/intellij/openapi/application/coroutines.kt
1
7098
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:ApiStatus.Experimental package com.intellij.openapi.application import com.intellij.openapi.application.constraints.ConstrainedExecution.ContextConstraint import com.intellij.openapi.application.ex.ApplicationEx import com.intellij.openapi.progress.JobProgress import com.intellij.openapi.progress.Progress import com.intellij.openapi.progress.util.ProgressIndicatorUtils.runActionAndCancelBeforeWrite import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import kotlinx.coroutines.* import org.jetbrains.annotations.ApiStatus import kotlin.coroutines.CoroutineContext import kotlin.coroutines.coroutineContext import kotlin.coroutines.resume /** * Runs given [action] under [read lock][com.intellij.openapi.application.Application.runReadAction] * except it doesn't affect any write actions. * * The function suspends if at the moment of calling it's not possible to acquire the read lock. * If the write action happens while the [action] is running, then the [action] is canceled, * and the function suspends until its possible to acquire the read lock, and then the [action] is tried again. * * Since the [action] might me executed several times, it must be idempotent. * The function returns when given [action] was completed fully. * [Progress] passed to the action must be used to check for cancellation inside the [action]. */ suspend fun <T> readAction(action: (progress: Progress) -> T): T { return constrainedReadAction(ReadConstraints.unconstrained(), action) } /** * Suspends until it's possible to obtain the read lock in smart mode and then runs the [action] holding the lock. * @see readAction */ suspend fun <T> smartReadAction(project: Project, action: (progress: Progress) -> T): T { return constrainedReadAction(ReadConstraints.inSmartMode(project), action) } /** * Suspends until it's possible to obtain the read lock with all [constraints] [satisfied][ContextConstraint.isCorrectContext] * and then runs the [action] holding the lock. * @see readAction */ suspend fun <T> constrainedReadAction(constraints: ReadConstraints, action: (progress: Progress) -> T): T { val application: ApplicationEx = ApplicationManager.getApplication() as ApplicationEx check(!application.isDispatchThread) { "Must not call from EDT" } if (application.isReadAccessAllowed) { val unsatisfiedConstraint = constraints.findUnsatisfiedConstraint() check(unsatisfiedConstraint == null) { "Cannot suspend until constraints are satisfied while holding read lock: $unsatisfiedConstraint" } return action(JobProgress(coroutineContext.job)) } return supervisorScope { readLoop(application, constraints, action) } } private suspend fun <T> readLoop(application: ApplicationEx, constraints: ReadConstraints, action: (progress: Progress) -> T): T { while (true) { coroutineContext.ensureActive() if (application.isWriteActionPending || application.isWriteActionInProgress) { yieldToPendingWriteActions() // Write actions are executed on the write thread => wait until write action is processed. } try { when (val readResult = tryReadAction(application, constraints, action)) { is ReadResult.Successful -> return readResult.value is ReadResult.UnsatisfiedConstraint -> readResult.waitForConstraint.join() } } catch (e: CancellationException) { continue // retry } } } private suspend fun <T> tryReadAction(application: ApplicationEx, constraints: ReadConstraints, action: (progress: Progress) -> T): ReadResult<T> { val loopContext = coroutineContext return withContext(CoroutineName("read action")) { val readJob: Job = [email protected] val cancellation = { readJob.cancel() } lateinit var result: ReadResult<T> runActionAndCancelBeforeWrite(application, cancellation) { readJob.ensureActive() application.tryRunReadAction { val unsatisfiedConstraint = constraints.findUnsatisfiedConstraint() result = if (unsatisfiedConstraint == null) { ReadResult.Successful(action(JobProgress(readJob))) } else { ReadResult.UnsatisfiedConstraint(waitForConstraint(loopContext, unsatisfiedConstraint)) } } } readJob.ensureActive() result } } private sealed class ReadResult<T> { class Successful<T>(val value: T) : ReadResult<T>() class UnsatisfiedConstraint<T>(val waitForConstraint: Job) : ReadResult<T>() } /** * Suspends the execution until the write thread queue is processed. */ private suspend fun yieldToPendingWriteActions() { // the runnable is executed on the write thread _after_ the current or pending write action yieldUntilRun(ApplicationManager.getApplication()::invokeLater) } private fun waitForConstraint(ctx: CoroutineContext, constraint: ContextConstraint): Job { return CoroutineScope(ctx).launch(Dispatchers.Unconfined + CoroutineName("waiting for constraint '$constraint'")) { check(ApplicationManager.getApplication().isReadAccessAllowed) // schedule while holding read lock yieldUntilRun(constraint::schedule) check(constraint.isCorrectContext()) // Job is finished, readLoop may continue the next attempt } } private suspend fun yieldUntilRun(schedule: (Runnable) -> Unit) { suspendCancellableCoroutine<Unit> { continuation -> schedule(ResumeContinuationRunnable(continuation)) } } private class ResumeContinuationRunnable(continuation: CancellableContinuation<Unit>) : Runnable { @Volatile private var myContinuation: CancellableContinuation<Unit>? = continuation init { continuation.invokeOnCancellation { myContinuation = null // it's not possible to unschedule the runnable, so we make it do nothing instead } } override fun run() { myContinuation?.resume(Unit) } } /** * Suspends until dumb mode is over and runs [action] in Smart Mode on EDT */ suspend fun <T> smartAction(project: Project, action: (ctx: CoroutineContext) -> T): T { return suspendCancellableCoroutine { continuation -> DumbService.getInstance(project).runWhenSmart(SmartRunnable(action, continuation)) } } private class SmartRunnable<T>(action: (ctx: CoroutineContext) -> T, continuation: CancellableContinuation<T>) : Runnable { @Volatile private var myAction: ((ctx: CoroutineContext) -> T)? = action @Volatile private var myContinuation: CancellableContinuation<T>? = continuation init { continuation.invokeOnCancellation { myAction = null myContinuation = null // it's not possible to unschedule the runnable, so we make it do nothing instead } } override fun run() { val continuation = myContinuation ?: return val action = myAction ?: return continuation.resumeWith(kotlin.runCatching { action.invoke(continuation.context) }) } }
apache-2.0
ebef9853a5a2e49d7b0c63d378c58d3c
37.79235
140
0.741899
4.716279
false
false
false
false
VREMSoftwareDevelopment/WiFiAnalyzer
app/src/main/kotlin/com/vrem/wifianalyzer/wifi/model/WiFiStandard.kt
1
2156
/* * WiFiAnalyzer * Copyright (C) 2015 - 2022 VREM Software Development <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.vrem.wifianalyzer.wifi.model import android.net.wifi.ScanResult import androidx.annotation.DrawableRes import androidx.annotation.StringRes import com.vrem.util.buildMinVersionR import com.vrem.wifianalyzer.R typealias WiFiStandardId = Int private val unknown: WiFiStandardId = if (buildMinVersionR()) ScanResult.WIFI_STANDARD_UNKNOWN else 0 private val legacy: WiFiStandardId = if (buildMinVersionR()) ScanResult.WIFI_STANDARD_LEGACY else 1 private val n: WiFiStandardId = if (buildMinVersionR()) ScanResult.WIFI_STANDARD_11N else 4 private val ac: WiFiStandardId = if (buildMinVersionR()) ScanResult.WIFI_STANDARD_11AC else 5 private val ax: WiFiStandardId = if (buildMinVersionR()) ScanResult.WIFI_STANDARD_11AX else 6 enum class WiFiStandard(val wiFiStandardId: WiFiStandardId, @StringRes val textResource: Int, @DrawableRes val imageResource: Int) { UNKNOWN(unknown, R.string.wifi_standard_unknown, R.drawable.ic_wifi_unknown), LEGACY(legacy, R.string.wifi_standard_legacy, R.drawable.ic_wifi_legacy), N(n, R.string.wifi_standard_n, R.drawable.ic_wifi_4), AC(ac, R.string.wifi_standard_ac, R.drawable.ic_wifi_5), AX(ax, R.string.wifi_standard_ax, R.drawable.ic_wifi_6); companion object { fun findOne(wiFiStandardId: WiFiStandardId): WiFiStandard = values().firstOrNull { it.wiFiStandardId == wiFiStandardId } ?: UNKNOWN } }
gpl-3.0
1d5ad9eb2d68b7346308b6c2c4a7153b
46.933333
132
0.762059
3.856887
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/multiDecl/forRange/int/MultiDeclForComponentMemberExtensionsInExtensionFunction.kt
5
307
class M { operator fun Int.component1() = this + 1 operator fun Int.component2() = this + 2 } fun M.doTest(): String { var s = "" for ((a, b) in 0..2) { s += "$a:$b;" } return s } fun box(): String { val s = M().doTest() return if (s == "1:2;2:3;3:4;") "OK" else "fail: $s" }
apache-2.0
719fcf319de7ab7d477bcad62c49bdc9
17.117647
54
0.495114
2.623932
false
true
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/reflection/properties/allVsDeclared.kt
1
733
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT import kotlin.reflect.full.* import kotlin.test.* open class Super { val a: Int = 1 val String.b: String get() = this } class Sub : Super() { val c: Double = 1.0 val Char.d: Char get() = this } fun box(): String { val sub = Sub::class assertEquals(listOf("a", "c"), sub.memberProperties.map { it.name }.sorted()) assertEquals(listOf("b", "d"), sub.memberExtensionProperties.map { it.name }.sorted()) assertEquals(listOf("c"), sub.declaredMemberProperties.map { it.name }) assertEquals(listOf("d"), sub.declaredMemberExtensionProperties.map { it.name }) return "OK" }
apache-2.0
6877b7fa0f10c0fd0e63927b533d41e2
25.178571
90
0.663029
3.610837
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/controlStructures/compareBoxedIntegerToZero.kt
5
196
fun box(): String { val x: Int? = 0 if (x != 0) return "Fail $x" if (0 != x) return "Fail $x" if (!(x == 0)) return "Fail $x" if (!(0 == x)) return "Fail $x" return "OK" }
apache-2.0
50b9d0c793a752679f5b4c6687d9ec78
23.5
35
0.44898
2.684932
false
false
false
false
JuliusKunze/kotlin-native
performance/src/main/kotlin/org/jetbrains/ring/ClassBaselineBenchmark.kt
2
2017
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.ring open class ClassBaselineBenchmark { //Benchmark fun consume() { for (item in 1..BENCHMARK_SIZE) { Blackhole.consume(Value(item)) } } //Benchmark fun consumeField() { val value = Value(0) for (item in 1..BENCHMARK_SIZE) { value.value = item Blackhole.consume(value) } } //Benchmark fun allocateList(): List<Value> { val list = ArrayList<Value>(BENCHMARK_SIZE) return list } //Benchmark fun allocateArray(): Array<Value?> { val list = arrayOfNulls<Value>(BENCHMARK_SIZE) return list } //Benchmark fun allocateListAndFill(): List<Value> { val list = ArrayList<Value>(BENCHMARK_SIZE) for (item in 1..BENCHMARK_SIZE) { list.add(Value(item)) } return list } //Benchmark fun allocateListAndWrite(): List<Value> { val value = Value(0) val list = ArrayList<Value>(BENCHMARK_SIZE) for (item in 1..BENCHMARK_SIZE) { list.add(value) } return list } //Benchmark fun allocateArrayAndFill(): Array<Value?> { val list = arrayOfNulls<Value>(BENCHMARK_SIZE) var index = 0 for (item in 1..BENCHMARK_SIZE) { list[index++] = Value(item) } return list } }
apache-2.0
9f40964cf5002732c57d7ebb0e870417
25.207792
75
0.603371
4.210856
false
false
false
false
AndroidX/androidx
glance/glance-appwidget/src/androidAndroidTest/kotlin/androidx/glance/appwidget/GlanceAppWidgetReceiverScreenshotTest.kt
3
25469
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.glance.appwidget import android.app.Activity import android.graphics.drawable.BitmapDrawable import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.glance.Button import androidx.glance.ButtonColors import androidx.glance.GlanceModifier import androidx.glance.Image import androidx.glance.ImageProvider import androidx.glance.LocalContext import androidx.glance.action.actionStartActivity import androidx.glance.appwidget.test.R import androidx.glance.background import androidx.glance.color.ColorProvider import androidx.glance.layout.Alignment import androidx.glance.layout.Box import androidx.glance.layout.Column import androidx.glance.layout.ContentScale import androidx.glance.layout.Row import androidx.glance.layout.fillMaxHeight import androidx.glance.layout.fillMaxSize import androidx.glance.layout.fillMaxWidth import androidx.glance.layout.height import androidx.glance.layout.padding import androidx.glance.layout.size import androidx.glance.layout.width import androidx.glance.layout.wrapContentSize import androidx.glance.text.FontStyle import androidx.glance.text.FontWeight import androidx.glance.text.Text import androidx.glance.text.TextAlign import androidx.glance.text.TextDecoration import androidx.glance.text.TextStyle import androidx.glance.unit.ColorProvider import androidx.test.filters.MediumTest import androidx.test.filters.SdkSuppress import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain import org.junit.rules.TestRule @SdkSuppress(minSdkVersion = 29) @MediumTest class GlanceAppWidgetReceiverScreenshotTest { private val mScreenshotRule = screenshotRule() private val mHostRule = AppWidgetHostRule() @Rule @JvmField val mRule: TestRule = RuleChain.outerRule(mHostRule).around(mScreenshotRule) .around(WithRtlRule) .around(WithNightModeRule) @Test fun createSimpleAppWidget() { TestGlanceAppWidget.uiDefinition = { Text( "text", style = TextStyle( textDecoration = TextDecoration.Underline, fontWeight = FontWeight.Medium, fontStyle = FontStyle.Italic, ) ) } mHostRule.startHost() mScreenshotRule.checkScreenshot(mHostRule.mHostView, "simpleAppWidget") } @Test fun createCheckBoxAppWidget() { TestGlanceAppWidget.uiDefinition = { CheckBoxScreenshotTest() } mHostRule.startHost() mScreenshotRule.checkScreenshot(mHostRule.mHostView, "checkBoxWidget") } @WithNightMode @Test fun createCheckBoxAppWidget_dark() { TestGlanceAppWidget.uiDefinition = { CheckBoxScreenshotTest() } mHostRule.startHost() mScreenshotRule.checkScreenshot(mHostRule.mHostView, "checkBoxWidget_dark") } @Test fun createCheckSwitchAppWidget() { TestGlanceAppWidget.uiDefinition = { SwitchTest() } mHostRule.startHost() mScreenshotRule.checkScreenshot(mHostRule.mHostView, "switchWidget") } @WithNightMode @Test fun createCheckSwitchAppWidget_dark() { TestGlanceAppWidget.uiDefinition = { SwitchTest() } mHostRule.startHost() mScreenshotRule.checkScreenshot(mHostRule.mHostView, "switchWidget_dark") } @Test fun createRadioButtonAppWidget() { TestGlanceAppWidget.uiDefinition = { RadioButtonScreenshotTest() } mHostRule.startHost() mScreenshotRule.checkScreenshot(mHostRule.mHostView, "radioButtonWidget") } @WithNightMode @Test fun createRadioButtonAppWidget_dark() { TestGlanceAppWidget.uiDefinition = { RadioButtonScreenshotTest() } mHostRule.startHost() mScreenshotRule.checkScreenshot(mHostRule.mHostView, "radioButtonWidget_dark") } @Test fun createRowWidget() { TestGlanceAppWidget.uiDefinition = { RowTest() } mHostRule.startHost() mScreenshotRule.checkScreenshot(mHostRule.mHostView, "rowWidget") } @WithRtl @Test fun createRowWidget_rtl() { TestGlanceAppWidget.uiDefinition = { RowTest() } mHostRule.startHost() mScreenshotRule.checkScreenshot(mHostRule.mHostView, "rowWidget_rtl") } @Test fun checkTextAlignment() { TestGlanceAppWidget.uiDefinition = { TextAlignmentTest() } mHostRule.startHost() mScreenshotRule.checkScreenshot(mHostRule.mHostView, "textAlignment") } @WithRtl @Test fun checkTextAlignment_rtl() { TestGlanceAppWidget.uiDefinition = { TextAlignmentTest() } mHostRule.startHost() mScreenshotRule.checkScreenshot(mHostRule.mHostView, "textAlignment_rtl") } @Test fun checkBackgroundColor_light() { TestGlanceAppWidget.uiDefinition = { BackgroundTest() } mHostRule.startHost() mScreenshotRule.checkScreenshot(mHostRule.mHostView, "backgroundColor") } @Test @WithNightMode fun checkBackgroundColor_dark() { TestGlanceAppWidget.uiDefinition = { BackgroundTest() } mHostRule.startHost() mScreenshotRule.checkScreenshot(mHostRule.mHostView, "backgroundColor_dark") } @Test fun checkTextColor_light() { TestGlanceAppWidget.uiDefinition = { TextColorTest() } mHostRule.startHost() mScreenshotRule.checkScreenshot(mHostRule.mHostView, "textColor") } @Test @WithNightMode fun checkTextColor_dark() { TestGlanceAppWidget.uiDefinition = { TextColorTest() } mHostRule.startHost() mScreenshotRule.checkScreenshot(mHostRule.mHostView, "textColor_dark") } @Test fun checkButtonTextAlignment() { TestGlanceAppWidget.uiDefinition = { Column(modifier = GlanceModifier.fillMaxSize()) { Row(modifier = GlanceModifier.defaultWeight().fillMaxWidth()) { Button( "Start", onClick = actionStartActivity<Activity>(), modifier = GlanceModifier.defaultWeight().fillMaxHeight(), colors = ButtonColors( backgroundColor = ColorProvider(Color.Transparent), contentColor = ColorProvider(Color.DarkGray) ), style = TextStyle(textAlign = TextAlign.Start) ) Button( "End", onClick = actionStartActivity<Activity>(), modifier = GlanceModifier.defaultWeight().fillMaxHeight(), colors = ButtonColors( backgroundColor = ColorProvider(Color.Transparent), contentColor = ColorProvider(Color.DarkGray) ), style = TextStyle(textAlign = TextAlign.End) ) } Row(modifier = GlanceModifier.defaultWeight().fillMaxWidth()) { CheckBox( checked = false, onCheckedChange = null, text = "Start", modifier = GlanceModifier.defaultWeight().fillMaxHeight(), style = TextStyle(textAlign = TextAlign.Start) ) CheckBox( checked = true, onCheckedChange = null, text = "End", modifier = GlanceModifier.defaultWeight().fillMaxHeight(), style = TextStyle(textAlign = TextAlign.End) ) } Row(modifier = GlanceModifier.defaultWeight().fillMaxWidth()) { Switch( checked = false, onCheckedChange = null, text = "Start", modifier = GlanceModifier.defaultWeight().fillMaxHeight(), style = TextStyle(textAlign = TextAlign.Start) ) Switch( checked = true, onCheckedChange = null, text = "End", modifier = GlanceModifier.defaultWeight().fillMaxHeight(), style = TextStyle(textAlign = TextAlign.End) ) } Row(modifier = GlanceModifier.defaultWeight().fillMaxWidth()) { RadioButton( checked = false, onClick = null, text = "Start", modifier = GlanceModifier.defaultWeight().fillMaxHeight(), style = TextStyle(textAlign = TextAlign.Start) ) RadioButton( checked = true, onClick = null, text = "End", modifier = GlanceModifier.defaultWeight().fillMaxHeight(), style = TextStyle(textAlign = TextAlign.End) ) } } } mHostRule.setSizes(DpSize(300.dp, 400.dp)) mHostRule.startHost() mScreenshotRule.checkScreenshot(mHostRule.mHostView, "button_text_align") } @Test fun checkFixTopLevelSize() { TestGlanceAppWidget.uiDefinition = { Column( modifier = GlanceModifier.size(100.dp) .background(Color.DarkGray), horizontalAlignment = Alignment.End, ) { Text( "Upper half", modifier = GlanceModifier.defaultWeight().fillMaxWidth() .background(Color.Green) ) Text( "Lower right half", modifier = GlanceModifier.defaultWeight().width(50.dp) .background(Color.Cyan) ) } } mHostRule.startHost() mScreenshotRule.checkScreenshot(mHostRule.mHostView, "fixed_top_level_size") } @Test fun checkTopLevelFill() { TestGlanceAppWidget.uiDefinition = { Column( modifier = GlanceModifier.fillMaxSize() .background(Color.DarkGray), horizontalAlignment = Alignment.End, ) { Text( "Upper half", modifier = GlanceModifier.defaultWeight().fillMaxWidth() .background(Color.Green) ) Text( "Lower right half", modifier = GlanceModifier.defaultWeight().width(50.dp) .background(Color.Cyan) ) } } mHostRule.startHost() mScreenshotRule.checkScreenshot(mHostRule.mHostView, "fill_top_level_size") } @Test fun checkTopLevelWrap() { TestGlanceAppWidget.uiDefinition = { Column( modifier = GlanceModifier.wrapContentSize() .background(Color.DarkGray), horizontalAlignment = Alignment.CenterHorizontally, ) { Text( "Above", modifier = GlanceModifier.background(Color.Green) ) Text( "Larger below", modifier = GlanceModifier.background(Color.Cyan) ) } } mHostRule.startHost() mScreenshotRule.checkScreenshot(mHostRule.mHostView, "wrap_top_level_size") } @Test fun drawableBackground() { TestGlanceAppWidget.uiDefinition = { Box( modifier = GlanceModifier.fillMaxSize().background(Color.Green).padding(8.dp), contentAlignment = Alignment.Center ) { Text( "Some useful text", modifier = GlanceModifier.fillMaxWidth().height(220.dp) .background(ImageProvider(R.drawable.filled_oval)) ) } } mHostRule.startHost() mScreenshotRule.checkScreenshot(mHostRule.mHostView, "drawable_background") } @Test fun drawableFitBackground() { TestGlanceAppWidget.uiDefinition = { Box( modifier = GlanceModifier.fillMaxSize().background(Color.Green).padding(8.dp), contentAlignment = Alignment.Center ) { Text( "Some useful text", modifier = GlanceModifier.fillMaxWidth().height(220.dp) .background( ImageProvider(R.drawable.filled_oval), contentScale = ContentScale.Fit ) ) } } mHostRule.startHost() mScreenshotRule.checkScreenshot(mHostRule.mHostView, "drawable_fit_background") } @Test fun bitmapBackground() { TestGlanceAppWidget.uiDefinition = { val context = LocalContext.current val bitmap = context.resources.getDrawable(R.drawable.compose, null) as BitmapDrawable Box( modifier = GlanceModifier.fillMaxSize().background(Color.Green).padding(8.dp), contentAlignment = Alignment.Center ) { Text( "Some useful text", modifier = GlanceModifier.fillMaxWidth().height(220.dp) .background(ImageProvider(bitmap.bitmap!!)) ) } } mHostRule.startHost() mScreenshotRule.checkScreenshot(mHostRule.mHostView, "bitmap_background") } @Test fun alignment() { TestGlanceAppWidget.uiDefinition = { Row( modifier = GlanceModifier.fillMaxSize(), horizontalAlignment = Alignment.End, verticalAlignment = Alignment.Bottom, ) { Text("##") Column( horizontalAlignment = Alignment.CenterHorizontally, verticalAlignment = Alignment.CenterVertically, modifier = GlanceModifier.fillMaxHeight(), ) { Box( contentAlignment = Alignment.Center, modifier = GlanceModifier.height(80.dp), ) { Text("Center") } Box( contentAlignment = Alignment.Center, modifier = GlanceModifier.height(80.dp), ) { Text("BottomCenter") } Box( contentAlignment = Alignment.Center, modifier = GlanceModifier.height(80.dp), ) { Text("CenterStart") } } Column( horizontalAlignment = Alignment.CenterHorizontally, verticalAlignment = Alignment.CenterVertically, modifier = GlanceModifier.fillMaxHeight(), ) { Box(contentAlignment = Alignment.Center) { Image( ImageProvider(R.drawable.compose), "Compose", modifier = GlanceModifier.size(80.dp), ) Text("OXO", style = TextStyle(fontSize = 18.sp)) } Box(contentAlignment = Alignment.BottomCenter) { Image( ImageProvider(R.drawable.compose), "Compose", modifier = GlanceModifier.size(80.dp), ) Text("OXO", style = TextStyle(fontSize = 18.sp)) } Box(contentAlignment = Alignment.CenterStart) { Image( ImageProvider(R.drawable.compose), "Compose", modifier = GlanceModifier.size(80.dp), ) Text("OXO", style = TextStyle(fontSize = 18.sp)) } } } } mHostRule.startHost() mScreenshotRule.checkScreenshot(mHostRule.mHostView, "alignment") } } @Composable private fun TextAlignmentTest() { Column(modifier = GlanceModifier.fillMaxWidth()) { Text( "Center", style = TextStyle(textAlign = TextAlign.Center), modifier = GlanceModifier.fillMaxWidth() ) Text( "Left", style = TextStyle(textAlign = TextAlign.Left), modifier = GlanceModifier.fillMaxWidth() ) Text( "Right", style = TextStyle(textAlign = TextAlign.Right), modifier = GlanceModifier.fillMaxWidth() ) Text( "Start", style = TextStyle(textAlign = TextAlign.Start), modifier = GlanceModifier.fillMaxWidth() ) Text( "End", style = TextStyle(textAlign = TextAlign.End), modifier = GlanceModifier.fillMaxWidth() ) } } @Composable private fun RowTest() { Row(modifier = GlanceModifier.fillMaxWidth()) { Text( "Start", style = TextStyle(textAlign = TextAlign.Start), modifier = GlanceModifier.defaultWeight() ) Text( "Center", style = TextStyle(textAlign = TextAlign.Center), modifier = GlanceModifier.defaultWeight() ) Text( "End", style = TextStyle(textAlign = TextAlign.End), modifier = GlanceModifier.defaultWeight() ) } } @Composable private fun BackgroundTest() { Column(modifier = GlanceModifier.background(R.color.background_color)) { Text( "100x50 and cyan", modifier = GlanceModifier.width(100.dp).height(50.dp).background(Color.Cyan) ) Text( "Transparent background", modifier = GlanceModifier.height(50.dp).background(Color.Transparent) ) Text( "wrapx30 and red (light), yellow (dark)", modifier = GlanceModifier .height(30.dp) .background(day = Color.Red, night = Color.Yellow) ) Text("Below this should be 4 color boxes") Row(modifier = GlanceModifier.padding(8.dp)) { Box( modifier = GlanceModifier .width(32.dp) .height(32.dp) .background(day = Color.Black, night = Color.White) ) {} val colors = listOf(Color.Red, Color.Green, Color.Blue) repeat(3) { Box(modifier = GlanceModifier.width(8.dp).height(1.dp)) {} Box( modifier = GlanceModifier.width(32.dp).height(32.dp).background(colors[it]) ) {} } } } } @Composable private fun TextColorTest() { Column(modifier = GlanceModifier.background(R.color.background_color)) { Text("Cyan", style = TextStyle(color = ColorProvider(Color.Cyan))) Text( "Red (light) or yellow (dark)", style = TextStyle(color = ColorProvider(day = Color.Red, night = Color.Yellow)) ) Text( "Resource (inverse of background color)", style = TextStyle(color = ColorProvider(R.color.text_color)) ) } } @Composable private fun CheckBoxScreenshotTest() { Column(modifier = GlanceModifier.background(day = Color.White, night = Color.Black)) { CheckBox( checked = true, onCheckedChange = null, text = "Hello Checked Checkbox (text: day=black, night=white| box: day=magenta, " + "night=yellow)", style = TextStyle( color = ColorProvider(day = Color.Black, night = Color.White), fontWeight = FontWeight.Bold, fontStyle = FontStyle.Normal, ), colors = checkBoxColors( checkedColor = ColorProvider(day = Color.Magenta, night = Color.Yellow), uncheckedColor = ColorProvider(day = Color.Black, night = Color.Gray) ) ) CheckBox( checked = false, onCheckedChange = null, text = "Hello Unchecked Checkbox (text: day=dark gray, night=light gray, green box)", style = TextStyle( color = ColorProvider(day = Color.DarkGray, night = Color.LightGray), textDecoration = TextDecoration.Underline, fontWeight = FontWeight.Medium, fontStyle = FontStyle.Italic, ), colors = checkBoxColors(checkedColor = Color.Red, uncheckedColor = Color.Green) ) } } @Composable private fun SwitchTest() { Column(modifier = GlanceModifier.background(day = Color.White, night = Color.Black)) { Switch( checked = true, onCheckedChange = null, text = "Hello Checked Switch (day: Blue/Green, night: Red/Yellow)", style = TextStyle( color = ColorProvider(day = Color.Black, night = Color.White), fontWeight = FontWeight.Bold, fontStyle = FontStyle.Normal, ), colors = switchColors( checkedThumbColor = ColorProvider(day = Color.Blue, night = Color.Red), uncheckedThumbColor = ColorProvider(Color.Magenta), checkedTrackColor = ColorProvider(day = Color.Green, night = Color.Yellow), uncheckedTrackColor = ColorProvider(Color.Magenta) ) ) Switch( checked = false, onCheckedChange = null, text = "Hello Unchecked Switch. day: thumb magenta / track cyan, night: thumb cyan", style = TextStyle( color = ColorProvider(day = Color.Black, night = Color.White), textDecoration = TextDecoration.Underline, fontWeight = FontWeight.Medium, fontStyle = FontStyle.Italic, ), colors = switchColors( checkedThumbColor = ColorProvider(Color.Blue), uncheckedThumbColor = ColorProvider(day = Color.Magenta, night = Color.Cyan), checkedTrackColor = ColorProvider(Color.Blue), uncheckedTrackColor = ColorProvider(day = Color.Cyan, night = Color.Magenta) ) ) } } @Composable private fun RadioButtonScreenshotTest() { Column( modifier = GlanceModifier.background(day = Color.White, night = Color.Black) ) { RadioButton( checked = true, onClick = null, text = "Hello Checked Radio (text: day=black, night=white| radio: day=magenta, " + "night=yellow)", style = TextStyle( color = ColorProvider(day = Color.Black, night = Color.White), fontWeight = FontWeight.Bold, fontStyle = FontStyle.Normal, ), colors = radioButtonColors( checkedColor = ColorProvider(day = Color.Magenta, night = Color.Yellow), uncheckedColor = ColorProvider(day = Color.Yellow, night = Color.Magenta) ) ) RadioButton( checked = false, onClick = null, text = "Hello Unchecked Radio (text: day=dark gray, night=light gray| radio: green)", style = TextStyle( color = ColorProvider(day = Color.DarkGray, night = Color.LightGray), textDecoration = TextDecoration.Underline, fontWeight = FontWeight.Medium, fontStyle = FontStyle.Italic, ), colors = radioButtonColors(checkedColor = Color.Red, uncheckedColor = Color.Green) ) } }
apache-2.0
bce05b86106dceac2cc450a8c4931f6f
33.69891
98
0.550512
5.402843
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/NamedArgumentCompletion.kt
1
9701
// Copyright 2000-2021 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.completion import com.intellij.codeInsight.completion.InsertHandler import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiWhiteSpace import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.core.ArgumentPositionData import org.jetbrains.kotlin.idea.core.ExpectedInfo import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.util.CallType import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.renderer.render import org.jetbrains.kotlin.resolve.calls.callUtil.getParameterForArgument import org.jetbrains.kotlin.resolve.calls.components.isVararg import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull object NamedArgumentCompletion { fun isOnlyNamedArgumentExpected(nameExpression: KtSimpleNameExpression, resolutionFacade: ResolutionFacade): Boolean { val thisArgument = nameExpression.parent as? KtValueArgument ?: return false if (thisArgument.isNamed()) return false val resolvedCall = thisArgument.getStrictParentOfType<KtCallElement>()?.resolveToCall(resolutionFacade) ?: return false return !thisArgument.canBeUsedWithoutNameInCall(resolvedCall) } fun complete(collector: LookupElementsCollector, expectedInfos: Collection<ExpectedInfo>, callType: CallType<*>) { if (callType != CallType.DEFAULT) return val nameToParameterType = HashMap<Name, MutableSet<KotlinType>>() for (expectedInfo in expectedInfos) { val argumentData = expectedInfo.additionalData as? ArgumentPositionData.Positional ?: continue for (parameter in argumentData.namedArgumentCandidates) { nameToParameterType.getOrPut(parameter.name) { HashSet() }.add(parameter.type) } } for ((name, types) in nameToParameterType) { val typeText = types.singleOrNull()?.let { BasicLookupElementFactory.SHORT_NAMES_RENDERER.renderType(it) } ?: "..." val nameString = name.asString() val lookupElement = LookupElementBuilder.create("$nameString =") .withPresentableText("$nameString =") .withTailText(" $typeText") .withIcon(KotlinIcons.PARAMETER) .withInsertHandler(NamedArgumentInsertHandler(name)) lookupElement.putUserData(SmartCompletionInBasicWeigher.NAMED_ARGUMENT_KEY, Unit) collector.addElement(lookupElement) } } private class NamedArgumentInsertHandler(private val parameterName: Name) : InsertHandler<LookupElement> { override fun handleInsert(context: InsertionContext, item: LookupElement) { val editor = context.editor val (textAfterCompletionArea, doNeedTrailingSpace) = context.file.findElementAt(context.tailOffset).let { psi -> psi?.siblings()?.firstOrNull { it !is PsiWhiteSpace }?.text to (psi !is PsiWhiteSpace) } var text: String var caretOffset: Int if (textAfterCompletionArea == "=") { // User tries to manually rename existing named argument. We shouldn't add trailing `=` in such case text = parameterName.render() caretOffset = text.length } else { // For complicated cases let's try to normalize the document firstly in order to avoid parsing errors due to incomplete code editor.document.replaceString(context.startOffset, context.tailOffset, "") PsiDocumentManager.getInstance(context.project).commitDocument(editor.document) val nextArgument = context.file.findElementAt(context.startOffset)?.siblings() ?.firstOrNull { it !is PsiWhiteSpace }?.parentsWithSelf?.takeWhile { it !is KtValueArgumentList } ?.firstIsInstanceOrNull<KtValueArgument>() if (nextArgument?.isNamed() == true) { if (doNeedTrailingSpace) { text = "${parameterName.render()} = , " caretOffset = text.length - 2 } else { text = "${parameterName.render()} = ," caretOffset = text.length - 1 } } else { text = "${parameterName.render()} = " caretOffset = text.length } } if (context.file.findElementAt(context.startOffset - 1)?.let { it !is PsiWhiteSpace && it.text != "(" } == true) { text = " $text" caretOffset++ } editor.document.replaceString(context.startOffset, context.tailOffset, text) editor.caretModel.moveToOffset(context.startOffset + caretOffset) } } } /** * Checks whether argument in the [resolvedCall] can be used without its name (as positional argument). */ fun KtValueArgument.canBeUsedWithoutNameInCall(resolvedCall: ResolvedCall<out CallableDescriptor>): Boolean { if (resolvedCall.resultingDescriptor.valueParameters.isEmpty()) return true val argumentsThatCanBeUsedWithoutName = collectAllArgumentsThatCanBeUsedWithoutName(resolvedCall).map { it.argument } if (argumentsThatCanBeUsedWithoutName.isEmpty() || argumentsThatCanBeUsedWithoutName.none { it == this }) return false val argumentsBeforeThis = argumentsThatCanBeUsedWithoutName.takeWhile { it != this } return if (languageVersionSettings.supportsFeature(LanguageFeature.MixedNamedArgumentsInTheirOwnPosition)) { argumentsBeforeThis.none { it.isNamed() && !it.placedOnItsOwnPositionInCall(resolvedCall) } } else { argumentsBeforeThis.none { it.isNamed() } } } data class ArgumentThatCanBeUsedWithoutName( val argument: KtValueArgument, /** * When we didn't manage to map an argument to the appropriate parameter then the parameter is `null`. It's useful for cases when we * want to analyze possibility for the argument to be used without name even when appropriate parameter doesn't yet exist * (it may start existing when user will create the parameter from usage with "Add parameter to function" refactoring) */ val parameter: ValueParameterDescriptor? ) fun collectAllArgumentsThatCanBeUsedWithoutName( resolvedCall: ResolvedCall<out CallableDescriptor>, ): List<ArgumentThatCanBeUsedWithoutName> { val arguments = resolvedCall.call.valueArguments.filterIsInstance<KtValueArgument>() val argumentAndParameters = arguments.map { argument -> val parameter = resolvedCall.getParameterForArgument(argument) argument to parameter }.sortedBy { (_, parameter) -> parameter?.index ?: Int.MAX_VALUE } val firstVarargArgumentIndex = argumentAndParameters.indexOfFirst { (_, parameter) -> parameter?.isVararg ?: false } val lastVarargArgumentIndex = argumentAndParameters.indexOfLast { (_, parameter) -> parameter?.isVararg ?: false } return argumentAndParameters .asSequence() .mapIndexed { argumentIndex, (argument, parameter) -> val parameterIndex = parameter?.index ?: argumentIndex val isAfterVararg = lastVarargArgumentIndex != -1 && argumentIndex > lastVarargArgumentIndex val isVarargArg = argumentIndex in firstVarargArgumentIndex..lastVarargArgumentIndex if (!isVarargArg && argumentIndex != parameterIndex || isAfterVararg || isVarargArg && argumentAndParameters.drop(lastVarargArgumentIndex + 1).any { (argument, _) -> !argument.isNamed() } ) { null } else { ArgumentThatCanBeUsedWithoutName(argument, parameter) } } .takeWhile { it != null } // When any argument can't be used without a name then all subsequent arguments must have a name too! .map { it ?: error("It cannot be null because of the previous takeWhile in the chain") } .toList() } /** * Checks whether argument in the [resolvedCall] is on the same position as it listed in the callable definition. * * It is always true for the positional arguments, but may be untrue for the named arguments. * * ``` * fun foo(a: Int, b: Int, c: Int, d: Int) {} * * foo( * 10, // true * b = 10, // true, possible since Kotlin 1.4 with `MixedNamedArgumentsInTheirOwnPosition` feature * d = 30, // false, 3 vs 4 * c = 40 // false, 4 vs 3 * ) * ``` */ fun ValueArgument.placedOnItsOwnPositionInCall(resolvedCall: ResolvedCall<out CallableDescriptor>): Boolean { return resolvedCall.getParameterForArgument(this)?.index == resolvedCall.call.valueArguments.indexOf(this) }
apache-2.0
69b1b67456e7b278b537c6217b3e96d1
49.790576
158
0.696835
5.327293
false
false
false
false
smmribeiro/intellij-community
plugins/gradle/src/org/jetbrains/plugins/gradle/statistics/GradleSettingsCollector.kt
5
4399
// Copyright 2000-2018 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 org.jetbrains.plugins.gradle.statistics import com.intellij.internal.statistic.beans.MetricEvent import com.intellij.internal.statistic.beans.newBooleanMetric import com.intellij.internal.statistic.beans.newMetric import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector import com.intellij.openapi.externalSystem.model.ConfigurationDataImpl import com.intellij.openapi.externalSystem.model.ProjectKeys import com.intellij.openapi.externalSystem.service.project.ProjectDataManager import com.intellij.openapi.externalSystem.statistics.ExternalSystemUsagesCollector import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.project.Project import com.intellij.openapi.util.Version import org.gradle.util.GradleVersion import org.jetbrains.plugins.gradle.settings.GradleProjectSettings import org.jetbrains.plugins.gradle.settings.GradleSettings import org.jetbrains.plugins.gradle.util.GradleConstants class GradleSettingsCollector : ProjectUsagesCollector() { override fun getGroupId() = "build.gradle.state" override fun getMetrics(project: Project): Set<MetricEvent> { val gradleSettings = GradleSettings.getInstance(project) val projectsSettings = gradleSettings.linkedProjectsSettings if (projectsSettings.isEmpty()) { return emptySet() } val usages = mutableSetOf<MetricEvent>() // to have a total users base line to calculate pertentages of settings usages.add(newBooleanMetric("hasGradleProject", true)) // global settings usages.add(newBooleanMetric("offlineWork", gradleSettings.isOfflineWork)) usages.add(newBooleanMetric("hasCustomServiceDirectoryPath", !gradleSettings.serviceDirectoryPath.isNullOrBlank())) usages.add(newBooleanMetric("hasCustomGradleVmOptions", !gradleSettings.gradleVmOptions.isNullOrBlank())) usages.add(newBooleanMetric("showSelectiveImportDialogOnInitialImport", gradleSettings.showSelectiveImportDialogOnInitialImport())) usages.add(newBooleanMetric("storeProjectFilesExternally", gradleSettings.storeProjectFilesExternally)) // project settings for (setting in gradleSettings.linkedProjectsSettings) { val projectPath = setting.externalProjectPath usages.add(newBooleanMetric("isUseQualifiedModuleNames", setting.isUseQualifiedModuleNames)) usages.add(newBooleanMetric("createModulePerSourceSet", setting.isResolveModulePerSourceSet)) usages.add(newMetric("distributionType", setting.distributionType)) usages.add(newBooleanMetric("isCompositeBuilds", setting.compositeBuild != null)) usages.add(newBooleanMetric("disableWrapperSourceDistributionNotification", setting.isDisableWrapperSourceDistributionNotification)) usages.add(ExternalSystemUsagesCollector.getJRETypeUsage("gradleJvmType", setting.gradleJvm)) usages.add(ExternalSystemUsagesCollector.getJREVersionUsage(project, "gradleJvmVersion", setting.gradleJvm)) val gradleVersion = setting.resolveGradleVersion() if(gradleVersion.isSnapshot) { usages.add(newMetric("gradleVersion", anonymizeGradleVersion(gradleVersion.baseVersion) + ".SNAPSHOT")) } else { usages.add(newMetric("gradleVersion", anonymizeGradleVersion(gradleVersion))) } usages.add(newBooleanMetric("delegateBuildRun", GradleProjectSettings.isDelegatedBuildEnabled(project, projectPath))) usages.add(newMetric("preferredTestRunner", GradleProjectSettings.getTestRunner(project, projectPath))) val hasNonEmptyIntellijConfig = ProjectDataManager .getInstance() .getExternalProjectData(project, GradleConstants.SYSTEM_ID, projectPath) ?.externalProjectStructure ?.let { dataNode -> ExternalSystemApiUtil.findFirstRecursively(dataNode) { it.key == ProjectKeys.CONFIGURATION } } ?.let { it.data as? ConfigurationDataImpl } ?.let { it.jsonString.length > 2 } ?: false usages.add(newBooleanMetric("ideaSpecificConfigurationUsed", hasNonEmptyIntellijConfig)) } return usages } private fun anonymizeGradleVersion(version : GradleVersion) : String { return Version.parseVersion(version.version)?.toCompactString() ?: "unknown" } override fun getVersion(): Int = 2 }
apache-2.0
2f72561c7075309ae5b6c7201152fb28
52.646341
140
0.79609
5.243147
false
true
false
false
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/authentication/ui/AddGHAccountAction.kt
4
1894
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.authentication.ui import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformCoreDataKeys.CONTEXT_COMPONENT import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.util.ui.JBUI.Panels.simplePanel import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.api.GithubServerPath import org.jetbrains.plugins.github.i18n.GithubBundle.message import java.awt.Component import javax.swing.Action import javax.swing.JComponent class AddGHAccountAction : DumbAwareAction() { override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = e.getData(GHAccountsHost.KEY) != null } override fun actionPerformed(e: AnActionEvent) { val accountsHost = e.getData(GHAccountsHost.KEY)!! val dialog = GHOAuthLoginDialog(e.project, e.getData(CONTEXT_COMPONENT), accountsHost::isAccountUnique) dialog.setServer(GithubServerPath.DEFAULT_HOST, false) if (dialog.showAndGet()) { accountsHost.addAccount(dialog.server, dialog.login, dialog.token) } } } internal class GHOAuthLoginDialog(project: Project?, parent: Component?, isAccountUnique: UniqueLoginPredicate) : BaseLoginDialog(project, parent, GithubApiRequestExecutor.Factory.getInstance(), isAccountUnique) { init { title = message("login.to.github") loginPanel.setOAuthUi() init() } override fun createActions(): Array<Action> = arrayOf(cancelAction) override fun show() { doOKAction() super.show() } override fun createCenterPanel(): JComponent = simplePanel(loginPanel) .withPreferredWidth(200) .setPaddingCompensated() }
apache-2.0
a0c1c439900c8c788c879b1812f8c9ae
35.442308
140
0.779303
4.314351
false
false
false
false
kickstarter/android-oss
app/src/test/java/com/kickstarter/viewmodels/SurveyResponseViewModelTest.kt
1
3648
package com.kickstarter.viewmodels import android.content.Intent import com.kickstarter.KSRobolectricTestCase import com.kickstarter.libs.Environment import com.kickstarter.mock.factories.SurveyResponseFactory.surveyResponse import com.kickstarter.models.SurveyResponse import com.kickstarter.ui.IntentKey import okhttp3.Request import org.junit.Test import rx.observers.TestSubscriber class SurveyResponseViewModelTest : KSRobolectricTestCase() { private lateinit var vm: SurveyResponseViewModel.ViewModel private val goBack = TestSubscriber<Void>() private val showConfirmationDialog = TestSubscriber<Void>() private val webViewUrl = TestSubscriber<String?>() protected fun setUpEnvironment(environment: Environment) { vm = SurveyResponseViewModel.ViewModel(environment) vm.outputs.goBack().subscribe(goBack) vm.outputs.showConfirmationDialog().subscribe(showConfirmationDialog) vm.outputs.webViewUrl().subscribe(webViewUrl) } @Test fun testGoBack() { setUpEnvironment(environment()) vm.inputs.okButtonClicked() goBack.assertValueCount(1) } @Test fun testSubmitSuccessful_Redirect_ShowConfirmationDialog() { val surveyUrl = "https://kck.str/projects/param/heyo/surveys/123" val urlsEnvelope = SurveyResponse.Urls.builder() .web(SurveyResponse.Urls.Web.builder().survey(surveyUrl).build()) .build() val surveyResponse = surveyResponse() .toBuilder() .urls(urlsEnvelope) .build() val projectSurveyRequest: Request = Request.Builder() .url(surveyUrl) .build() val projectRequest: Request = Request.Builder() .url("https://kck.str/projects/param/heyo") .tag(projectSurveyRequest) .build() setUpEnvironment(environment()) vm.intent(Intent().putExtra(IntentKey.SURVEY_RESPONSE, surveyResponse)) // Survey loads. Successful submit redirects to project uri. vm.inputs.projectSurveyUriRequest(projectSurveyRequest) vm.inputs.projectUriRequest(projectRequest) // Success confirmation dialog is shown. showConfirmationDialog.assertValueCount(1) } @Test fun testSubmitSuccessful_NullTag_ShowConfirmationDialog() { val surveyUrl = "https://kck.str/projects/param/heyo/surveys/123" val urlsEnvelope = SurveyResponse.Urls.builder() .web(SurveyResponse.Urls.Web.builder().survey(surveyUrl).build()) .build() val surveyResponse = surveyResponse() .toBuilder() .urls(urlsEnvelope) .build() val projectSurveyRequest: Request = Request.Builder() .url(surveyUrl) .build() val projectRequest: Request = Request.Builder() .url("https://kck.str/projects/param/heyo") .build() setUpEnvironment(environment()) vm.intent(Intent().putExtra(IntentKey.SURVEY_RESPONSE, surveyResponse)) // Survey loads. Successful submit redirects to project uri. vm.inputs.projectSurveyUriRequest(projectSurveyRequest) vm.inputs.projectUriRequest(projectRequest) // Success confirmation dialog is shown. showConfirmationDialog.assertValueCount(1) } @Test fun testWebViewUrl() { val surveyResponse = surveyResponse() setUpEnvironment(environment()) vm.intent(Intent().putExtra(IntentKey.SURVEY_RESPONSE, surveyResponse)) webViewUrl.assertValues(surveyResponse.urls()?.web()?.survey()) } }
apache-2.0
c2ddaa0fc560a16304bb9e1f18917e3f
32.777778
79
0.680373
4.857523
false
true
false
false
Pattonville-App-Development-Team/Android-App
app/src/main/java/org/pattonvillecs/pattonvilleapp/view/ui/calendar/month/CalendarMonthFragment.kt
1
9883
/* * Copyright (C) 2017 - 2018 Mitchell Skaggs, Keturah Gadson, Ethan Holtgrieve, Nathan Skelton, Pattonville School District * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.pattonvillecs.pattonvilleapp.view.ui.calendar.month import android.content.res.Configuration import android.os.Bundle import android.support.annotation.ColorInt import android.support.v4.app.Fragment import android.support.v4.content.ContextCompat import android.support.v4.widget.NestedScrollView import android.util.Log import android.view.* import com.google.common.collect.Multiset import com.google.firebase.crash.FirebaseCrash import com.prolificinteractive.materialcalendarview.CalendarDay import com.prolificinteractive.materialcalendarview.DayViewDecorator import com.prolificinteractive.materialcalendarview.DayViewFacade import dagger.android.support.DaggerFragment import eu.davidea.flexibleadapter.common.FlexibleItemDecoration import eu.davidea.flexibleadapter.common.SmoothScrollLinearLayoutManager import kotlinx.android.synthetic.main.fragment_calendar_month.* import org.pattonvillecs.pattonvilleapp.R import org.pattonvillecs.pattonvilleapp.service.repository.calendar.CalendarRepository import org.pattonvillecs.pattonvilleapp.view.adapter.calendar.CalendarEventFlexibleAdapter import org.pattonvillecs.pattonvilleapp.view.ui.calendar.IFlexibleHasStartDate import org.pattonvillecs.pattonvilleapp.view.ui.spotlight.SpotlightHelper import org.pattonvillecs.pattonvilleapp.view.ui.spotlight.showSpotlightOnMenuItem import org.pattonvillecs.pattonvilleapp.viewmodel.calendar.month.CalendarMonthFragmentViewModel import org.pattonvillecs.pattonvilleapp.viewmodel.getViewModel import org.threeten.bp.LocalDate import org.threeten.bp.LocalDateTime import javax.inject.Inject /** * A simple [Fragment] subclass. * Use the [CalendarMonthFragment.newInstance] factory method to * create an instance of this fragment. * * @since 1.0.0 * @author Mitchell Skaggs */ class CalendarMonthFragment : DaggerFragment() { @Inject lateinit var calendarRepository: CalendarRepository private var nestedScrollView: NestedScrollView? = null private lateinit var viewModel: CalendarMonthFragmentViewModel private lateinit var eventAdapter: CalendarEventFlexibleAdapter //Minimum radius of 5 private val dotRadius: Float get() { return if (calendarView != null) { if (calendarView.width == 0 || calendarView.height == 0) FirebaseCrash.logcat(Log.WARN, TAG, "Width and height are ${calendarView.width}, ${calendarView.height}! This method was called before the final layout pass!") (Math.min(calendarView.width, calendarView.height) / 125f).coerceAtLeast(5f) } else { FirebaseCrash.logcat(Log.WARN, TAG, "calendarView is null!") 10f } } @delegate:ColorInt private val dotColor: Int by lazy { ContextCompat.getColor(context!!, R.color.colorPrimary) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) viewModel = getViewModel() viewModel.calendarRepository = calendarRepository } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.fragment_calendar_action_bar_menu_goto_today, menu) activity?.showSpotlightOnMenuItem(R.id.action_goto_today, "CalendarMonthFragment_MenuButtonGoToCurrentDay", "Tap here to return to the current day.", "Today") } override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) { R.id.action_goto_today -> { calendarView.onDateClickedMoveMonth(LocalDateTime.now().toLocalDate().toCalendarDay(), true) true } else -> super.onOptionsItemSelected(item) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = inflater.inflate(R.layout.fragment_calendar_month, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) showSpotlight() eventAdapter = CalendarEventFlexibleAdapter(stableIds = true, calendarRepository = calendarRepository) event_recycler_view.layoutManager = SmoothScrollLinearLayoutManager(context!!) event_recycler_view.addItemDecoration( FlexibleItemDecoration(context!!) .withDefaultDivider(R.layout.calendar_dateless_event_list_item) .withDrawDividerOnLastItem(true)) event_recycler_view.isNestedScrollingEnabled = false event_recycler_view.adapter = eventAdapter calendarView.selectedDate = LocalDateTime.now().toLocalDate().toCalendarDay() calendarView.addOnLayoutChangeListener { _, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom -> Log.d(TAG, "MCV New layout: $left $top $right $bottom; Old layout: $oldLeft $oldTop $oldRight $oldBottom") Log.d(TAG, "MCV tile height: ${calendarView.tileHeight}") if (left != oldLeft || top != oldTop || right != oldRight || bottom != oldBottom) calendarView.post { calendarView.invalidateDecorators() } } calendarView.setOnDateChangedListener { _, date, _ -> viewModel.setDate(date.toLocalDate()) } viewModel.dateMultiset.observe(this::getLifecycle) { dates -> if (dates != null) { calendarView.removeDecorators() calendarView.addDecorators( DotDayDecorator(dates, dotRadius, dotColor, EnhancedDotSpan.DotType.SINGLE), DotDayDecorator(dates, dotRadius, dotColor, EnhancedDotSpan.DotType.DOUBLE), DotDayDecorator(dates, dotRadius, dotColor, EnhancedDotSpan.DotType.TRIPLE), DotDayDecorator(dates, dotRadius, dotColor, EnhancedDotSpan.DotType.TRIPLE_PLUS)) } } viewModel.currentDateEventItems.observe(this::getLifecycle) { if (it != null) eventAdapter.updateDataSet(it.map { it as IFlexibleHasStartDate<*> }, true) } } private fun showSpotlight() { val spotlightPadding: Int when (resources.configuration.orientation) { Configuration.ORIENTATION_PORTRAIT -> { spotlightPadding = 20 nestedScrollView = view as NestedScrollView? nestedScrollView!!.isSmoothScrollingEnabled = true } Configuration.ORIENTATION_LANDSCAPE -> { spotlightPadding = -250 nestedScrollView = null } else -> throw IllegalStateException("Why would this ever happen?") } SpotlightHelper.showSpotlight(activity, view, spotlightPadding, "CalendarMonthFragment_SelectedDayEventList", "Events occurring on the selected day are shown here.", "Events") } companion object { val TAG = "CalendarMonthFragment" /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @return A new instance of fragment CalendarMonthFragment. */ @JvmStatic fun newInstance(): CalendarMonthFragment { Log.i(TAG, "New instance created...") return CalendarMonthFragment() } } } class DotDayDecorator(private val dates: Multiset<LocalDate>, private val dotRadius: Float, private val dotColor: Int, private val dotType: EnhancedDotSpan.DotType, private val testFunction: (Int) -> Boolean) : DayViewDecorator { constructor(dates: Multiset<LocalDate>, dotRadius: Float, dotColor: Int, dotType: EnhancedDotSpan.DotType) : this(dates, dotRadius, dotColor, dotType, dotType.defaultTestFunction) override fun shouldDecorate(day: CalendarDay): Boolean = testFunction(dates.count(day.toLocalDate())) override fun decorate(view: DayViewFacade) { when (dotType) { EnhancedDotSpan.DotType.SINGLE -> EnhancedDotSpan.createSingle(dotRadius, dotColor) EnhancedDotSpan.DotType.DOUBLE -> EnhancedDotSpan.createDouble(dotRadius, dotColor, dotColor) EnhancedDotSpan.DotType.TRIPLE -> EnhancedDotSpan.createTriple(dotRadius, dotColor, dotColor, dotColor) EnhancedDotSpan.DotType.TRIPLE_PLUS -> EnhancedDotSpan.createTripleWithPlus(dotRadius, dotColor, dotColor, dotColor) }.forEach { view.addSpan(it) } } } private fun CalendarDay.toLocalDate(): LocalDate = LocalDate.of(year, month + 1, day) private fun LocalDate.toCalendarDay(): CalendarDay = CalendarDay.from(this.year, this.monthValue - 1, this.dayOfMonth)
gpl-3.0
34e67db4731bd1d9c0d1642877551f57
42.346491
179
0.686128
4.921813
false
false
false
false
devjn/GithubSearch
ios/src/main/kotlin/com/github/devjn/githubsearch/ui/UserDetailsController.kt
1
10049
package com.github.devjn.githubsearch.ui import GetPinnedReposQuery import android.util.Log import apple.coregraphics.c.CoreGraphics import apple.foundation.NSBundle import apple.foundation.NSCoder import apple.foundation.NSIndexPath import apple.foundation.NSURL import apple.uikit.* import apple.uikit.enums.UIActivityIndicatorViewStyle import apple.uikit.enums.UIBarButtonItemStyle import apple.uikit.protocol.UITableViewDataSource import apple.uikit.protocol.UITableViewDelegate import com.github.devjn.githubsearch.Main import com.github.devjn.githubsearch.model.db.DataSource import com.github.devjn.githubsearch.service.GitHubApi import com.github.devjn.githubsearch.service.GithubGraphQL import com.github.devjn.githubsearch.service.GithubService import com.github.devjn.githubsearch.model.entities.User import io.reactivex.disposables.CompositeDisposable import io.reactivex.ios.schedulers.IOSSchedulers import io.reactivex.schedulers.Schedulers import org.moe.bindings.RepoViewCell import org.moe.bindings.category.UIImageViewExt import org.moe.natj.general.NatJ import org.moe.natj.general.Pointer import org.moe.natj.general.ann.NInt import org.moe.natj.general.ann.Owned import org.moe.natj.general.ann.RegisterOnStartup import org.moe.natj.general.ann.Runtime import org.moe.natj.objc.ObjCRuntime import org.moe.natj.objc.SEL import org.moe.natj.objc.ann.IBOutlet import org.moe.natj.objc.ann.ObjCClassName import org.moe.natj.objc.ann.Property import org.moe.natj.objc.ann.Selector /** * Created by @author Jahongir on 13-May-17 * [email protected] * UserDetailsController */ @Runtime(ObjCRuntime::class) @ObjCClassName("UserDetailsController") @RegisterOnStartup class UserDetailsController protected constructor(peer: Pointer) : UIViewController(peer), UITableViewDelegate, UITableViewDataSource { @Selector("init") external override fun init(): UserDetailsController @Selector("initWithCoder:") external override fun initWithCoder(aDecoder: NSCoder): UserDetailsController @Selector("initWithNibName:bundle:") external override fun initWithNibNameBundle( nibNameOrNil: String, nibBundleOrNil: NSBundle): UserDetailsController @Selector("setImageView:") external fun setImageView(value: UIImageView) @Selector("setTextLogin:") external fun setTextLogin(value: UITextView) @Selector("imageView") @Property @IBOutlet external fun imageView(): UIImageView @Selector("infoView") @Property @IBOutlet external fun infoView(): UIStackView @Selector("textLogin") @Property @IBOutlet external fun textLogin(): UITextView @Selector("textName") @Property @IBOutlet external fun textName(): UITextView @Selector("textBio") @Property @IBOutlet external fun textBio(): UITextView @Selector("textCompany") @Property @IBOutlet external fun textCompany(): UITextView @Selector("textLocation") @Property @IBOutlet external fun textLocation(): UITextView @Selector("textEmail") @Property @IBOutlet external fun textEmail(): UITextView @Selector("textBlog") @Property @IBOutlet external fun textBlog(): UITextView @Selector("textEmpty") @Property @IBOutlet external fun textEmpty(): UITextView @Selector("tableView") @Property @IBOutlet external fun tableView(): UITableView private val disposables = CompositeDisposable() private val repos: ArrayList<GetPinnedReposQuery.Node?> = ArrayList() private var source: DataSource = Main.dataSource private var isBookmarked = false var mUser: User? = null override fun viewDidLoad() { super.viewDidLoad() // This view controller will provide the delegate methods and row data for the table view. this.tableView().setDelegate(this) this.tableView().setDataSource(this) mUser?.let { textLogin().setText(it.login) val url = NSURL.URLWithString(it.avatar_url) UIImageViewExt.sd_setImageWithURLPlaceholderImage(this.imageView(), url, UIImage.imageNamed("User")) val gitHubApi = GithubService.createService(GitHubApi::class.java) gitHubApi.getUser(it.login).subscribeOn(Schedulers.io()) .observeOn(IOSSchedulers.mainThread()) .subscribe({ user -> user.isDetailed = true if (user != null) { mUser = user setupUser(user) } }, { e -> Log.e(TAG, "Error while getting data", e) }) disposables.add(GithubGraphQL.getPinnedRepos(it.login) .subscribeOn(Schedulers.io()) .observeOn(IOSSchedulers.mainThread()) .map { t -> ArrayList<GetPinnedReposQuery.Node?>(t.size).apply { t.forEach { this.add(it.node()) } } } .subscribe({ list -> if (list.isNotEmpty()) { repos.addAll(list) this.tableView().reloadData() Log.i(TAG, "Loaded repos: " + list.size) } }, { e -> Log.e(TAG, "Error while getting data", e) })) } ?: println("mUser is null") if (source.getUserById(mUser!!.id) != null) isBookmarked = true val image = UIImage.imageNamed(if (isBookmarked) "Bookmark" else "NonBookmark") val button = UIBarButtonItem.alloc().initWithImageStyleTargetAction(image, UIBarButtonItemStyle.Plain, this, SEL("bookmark:")) navigationItem().setRightBarButtonItem(button) setupActivityIndicator() showProgress(true) } override fun viewDidUnload() { super.viewDidUnload() disposables.dispose() } private fun setupUser(user: User) { textName().setText(user.name) val toHide = ArrayList<UIView>() user.bio?.let { textBio().setText(it) } ?: run { toHide.add(textBio()) } user.company?.let { textCompany().setText(it) } ?: run { toHide.add(textCompany()) } user.location?.let { textLocation().setText(it) } ?: run { toHide.add(textLocation()) } user.email?.let { textEmail().setText(it) } ?: run { toHide.add(textEmail()) } user.blog?.let { textBlog().setText(it) } ?: run { toHide.add(textBlog()) } if (user.hasExtra()) toHide.add(textEmpty()) toHide.forEach { it.isHidden = true } infoView().setNeedsUpdateConstraints() infoView().updateConstraintsIfNeeded() infoView().setNeedsLayout() infoView().layoutIfNeeded() UIView.animateWithDurationAnimations(1.0) { infoView().isHidden = false showProgress(false) } } private var indicator = UIActivityIndicatorView.alloc() private fun setupActivityIndicator() { indicator.initWithFrame(CoreGraphics.CGRectMake(0.0, 0.0, 48.0, 48.0)) indicator.setActivityIndicatorViewStyle(UIActivityIndicatorViewStyle.Gray) indicator.setCenter(this.view().center()) this.view().addSubview(indicator) } private fun showProgress(show: Boolean) { if (show) { indicator.startAnimating() indicator.setBackgroundColor(UIColor.whiteColor()) } else { indicator.stopAnimating() indicator.setHidesWhenStopped(true) } } private fun addToBookmarks() { source.createUser(mUser!!) isBookmarked = true navigationItem().rightBarButtonItem().setImage(UIImage.imageNamed("Bookmark")) Log.i(TAG, "adding mUser to bookmarks: $mUser") } private fun removeFromBookmarks() { source.deleteUser(mUser!!.id.toInt()) isBookmarked = false navigationItem().rightBarButtonItem().setImage(UIImage.imageNamed("NonBookmark")) Log.i(TAG, "removing mUser from bookmarks: $mUser") } @Selector("bookmark:") fun bookmark() { if (!isBookmarked) addToBookmarks() else removeFromBookmarks() } override fun tableViewCellForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): UITableViewCell { val cell = tableView.dequeueReusableCellWithIdentifierForIndexPath(CELL_IDENTIFIER, indexPath) as RepoViewCell val repo = repos[indexPath.item().toInt()] cell.titleLabel().setText(repo?.name()) cell.descriptionLabel().setText(repo?.description()) cell.langLabel().setText(repo?.primaryLanguage()?.name()) cell.contentView().layer().setBorderWidth(1.0) cell.contentView().layer().setBorderColor(UIColor.blackColor().CGColor()) println("cell is build " + indexPath.item()) return cell } override fun tableViewNumberOfRowsInSection(tableView: UITableView, @NInt section: Long): Long { println("tableViewNumberOfRowsInSection " + repos.size.toLong()) val size = repos.size.toLong() if (size > 0 && tableView().isHidden) { UIView.animateWithDurationAnimations(1.0) { tableView().isHidden = false showProgress(false) } } return size } override fun tableViewHeightForRowAtIndexPath(tableView: UITableView?, indexPath: NSIndexPath?): Double { return 96.0 } override fun numberOfSectionsInTableView(tableView: UITableView?): Long { return 1 } companion object { private const val CELL_IDENTIFIER = "RepoCell" val TAG = UserDetailsController::class.java.simpleName!! init { NatJ.register() } @Owned @Selector("alloc") @JvmStatic external fun alloc(): UserDetailsController @Selector("initialize") external fun initialize() } }
apache-2.0
c9c5f6dc3a110ac1faedaaf00038bf17
32.385382
134
0.653299
4.472185
false
false
false
false
mdaniel/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/tables/actions/column/TableColumnAlignmentActionsGroup.kt
2
1325
// Copyright 2000-2021 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.intellij.plugins.markdown.editor.tables.actions.column import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DefaultActionGroup import org.intellij.plugins.markdown.editor.tables.TableModificationUtils.hasCorrectBorders internal class TableColumnAlignmentActionsGroup: DefaultActionGroup() { override fun update(event: AnActionEvent) { val editor = event.getData(CommonDataKeys.EDITOR) val file = event.getData(CommonDataKeys.PSI_FILE) val offset = event.getData(CommonDataKeys.CARET)?.offset if (editor == null || file == null || offset == null) { event.presentation.isEnabledAndVisible = false return } val document = editor.document val (table, columnIndex) = ColumnBasedTableAction.findTableAndIndex(event, file, document, offset) event.presentation.isEnabledAndVisible = table != null && columnIndex != null && table.hasCorrectBorders() } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } }
apache-2.0
3967238933cdf44f07a9feed1cc3a45d
48.074074
158
0.783396
4.835766
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/secondStep/modulesEditor/ModulesEditorComponent.kt
1
4393
// Copyright 2000-2021 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.tools.projectWizard.wizard.ui.secondStep.modulesEditor import com.intellij.ui.JBColor import com.intellij.ui.ScrollPaneFactory import com.intellij.util.ui.JBUI import org.jetbrains.kotlin.idea.statistics.WizardStatsService.UiEditorUsageStats import org.jetbrains.kotlin.tools.projectWizard.core.Context import org.jetbrains.kotlin.tools.projectWizard.core.entity.ValidationResult import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.ListSettingType import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.reference import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.KotlinPlugin import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ProjectKind import org.jetbrains.kotlin.tools.projectWizard.settings.DisplayableSettingItem import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Module import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.customPanel import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.SettingComponent import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.ValidationIndicator import java.awt.BorderLayout import java.awt.Dimension import javax.swing.BorderFactory import javax.swing.JComponent class ModulesEditorComponent( context: Context, uiEditorUsagesStats: UiEditorUsageStats?, needBorder: Boolean, private val editable: Boolean, oneEntrySelected: (data: DisplayableSettingItem?) -> Unit ) : SettingComponent<List<Module>, ListSettingType<Module>>(KotlinPlugin.modules.reference, context) { private val tree: ModulesEditorTree = ModulesEditorTree( onSelected = { oneEntrySelected(it) }, context = context, isTreeEditable = editable, addModule = { component -> val isMppProject = KotlinPlugin.projectKind.reference.value == ProjectKind.Singleplatform moduleCreator.create( target = null, // The empty tree case allowMultiplatform = isMppProject, allowSinglePlatformJsBrowser = isMppProject, allowSinglePlatformJsNode = isMppProject, allowAndroid = isMppProject, allowIos = isMppProject, allModules = value ?: emptyList(), createModule = model::add )?.showInCenterOf(component) } ).apply { if (editable) { border = JBUI.Borders.emptyRight(10) } } private val model = TargetsModel(tree, ::value, context, uiEditorUsagesStats) override fun onInit() { super.onInit() updateModel() if (editable) { value?.firstOrNull()?.let(tree::selectModule) } } fun updateModel() { model.update() } override fun navigateTo(error: ValidationResult.ValidationError) { val targetModule = error.target as? Module ?: return tree.selectModule(targetModule) } private val moduleCreator = NewModuleCreator() private val toolbarDecorator = if (editable) ModulesEditorToolbarDecorator( tree = tree, moduleCreator = moduleCreator, model = model, getModules = { value ?: emptyList() }, isMultiplatformProject = { KotlinPlugin.projectKind.reference.value != ProjectKind.Singleplatform } ) else null override val component: JComponent by lazy(LazyThreadSafetyMode.NONE) { customPanel { if (needBorder) { border = BorderFactory.createLineBorder(JBColor.border()) } add(createEditorComponent(), BorderLayout.CENTER) } } private fun createEditorComponent() = when { editable -> toolbarDecorator!!.createToolPanel() else -> ScrollPaneFactory.createScrollPane(tree, true).apply { viewport.background = JBColor.PanelBackground } }.apply { preferredSize = Dimension(TREE_WIDTH, preferredSize.height) } override val validationIndicator: ValidationIndicator? = null companion object { private const val TREE_WIDTH = 260 } }
apache-2.0
5a479ddcdcd2684e6e9dd98c2afe9848
39.675926
158
0.687002
4.958239
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-meta/src/main/kotlin/slatekit/meta/Schema.kt
1
3073
package slatekit.meta import slatekit.common.data.DataType import slatekit.meta.models.* import kotlin.reflect.KClass import kotlin.reflect.KProperty import kotlin.reflect.KType open class Schema<TId, T>(val idType:KClass<*>, val enType:KClass<*>, val table:String = enType.simpleName!!) where TId : Comparable<TId>, T: Any { private var _model: Model = Model(enType, table) val model: Model get() = _model /** * Builds an id field using property reference to extract type information */ fun id( prop: KProperty<*>, name: String? = null, type: DataType? = null, min: Int = -1, max: Int = -1, defaultValue: Any? = null, tags: List<String> = listOf() ): ModelField { val raw = field(prop, name, "", type, min, max, defaultValue, false, true, FieldCategory.Id, tags) val field = raw.copy(isUnique = true, isIndexed = true, isUpdatable = false) return field } /** * Builds a normal field using property reference to extract type information */ fun field( prop: KProperty<*>, name: String? = null, desc: String = "", type: DataType? = null, min: Int = -1, max: Int = -1, defaultValue: Any? = null, encrypt: Boolean = false, indexed: Boolean = false, category: FieldCategory = FieldCategory.Data, tags: List<String> = listOf() ): ModelField { val finalName = name ?: prop.name val finalType = prop.returnType val finalKClas = finalType.classifier as KClass<*> val required = !finalType.isMarkedNullable val fieldType = type ?: ModelUtils.getFieldType(finalType) val field = ModelField.build( prop, finalName, desc, finalKClas, fieldType, required, false, indexed, true, min, max, null, defaultValue, encrypt, tags, category ) _model = _model.add(field) return field } /** * Builds a normal field using property reference to extract type information */ fun field( name: String, type: KType, required:Boolean, desc: String = "", min: Int = -1, max: Int = -1, defaultValue: Any? = null, encrypt: Boolean = false, indexed: Boolean = false, category: FieldCategory = FieldCategory.Data, tags: List<String> = listOf() ): ModelField { val finalName = name val finalType = type val finalKClas = finalType.classifier as KClass<*> val fieldType = ModelUtils.getFieldType(finalType) val field = ModelField.build( null, finalName, desc, finalKClas, fieldType, required, false, indexed, true, min, max, null, defaultValue, encrypt, tags, category ) _model = _model.add(field) return field } }
apache-2.0
633207131e13104010f0535fcba07117
32.413043
147
0.564269
4.447178
false
false
false
false
siosio/intellij-community
platform/statistics/devkit/src/com/intellij/internal/statistic/actions/CollectFUStatisticsAction.kt
1
6737
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistic.actions import com.google.common.collect.HashMultiset import com.google.gson.GsonBuilder import com.intellij.BundleBase import com.intellij.ide.actions.GotoActionBase import com.intellij.ide.util.gotoByName.ChooseByNameItem import com.intellij.ide.util.gotoByName.ChooseByNamePopup import com.intellij.ide.util.gotoByName.ChooseByNamePopupComponent import com.intellij.ide.util.gotoByName.ListChooseByNameModel import com.intellij.internal.statistic.StatisticsDevKitUtil import com.intellij.internal.statistic.eventLog.LogEventSerializer import com.intellij.internal.statistic.eventLog.newLogEvent import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector import com.intellij.internal.statistic.service.fus.collectors.FUStateUsagesLogger import com.intellij.internal.statistic.service.fus.collectors.FeatureUsagesCollector import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector import com.intellij.internal.statistic.utils.StatisticsRecorderUtil import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.runBackgroundableTask import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.testFramework.LightVirtualFile import com.intellij.util.containers.ContainerUtil import org.jetbrains.concurrency.resolvedPromise internal class CollectFUStatisticsAction : GotoActionBase() { override fun update(e: AnActionEvent) { super.update(e) if (e.presentation.isEnabled) { e.presentation.isEnabled = StatisticsRecorderUtil.isTestModeEnabled(StatisticsDevKitUtil.DEFAULT_RECORDER) } } override fun gotoActionPerformed(e: AnActionEvent) { val project = e.project ?: return val projectCollectors = ExtensionPointName.create<Any>("com.intellij.statistics.projectUsagesCollector").extensionList val applicationCollectors = ExtensionPointName.create<Any>("com.intellij.statistics.applicationUsagesCollector").extensionList val collectors = (projectCollectors + applicationCollectors).filterIsInstance(FeatureUsagesCollector::class.java) val ids = collectors.mapTo(HashMultiset.create()) { it.groupId } val items = collectors .map { collector -> val groupId = collector.groupId val className = StringUtil.nullize(collector.javaClass.simpleName, true) Item(collector, groupId, className, ids.count(groupId) > 1) } ContainerUtil.sort(items, Comparator.comparing<Item, String> { it.groupId }) val model = MyChooseByNameModel(project, items) val popup = ChooseByNamePopup.createPopup(project, model, getPsiContext(e)) popup.setShowListForEmptyPattern(true) popup.invoke(object : ChooseByNamePopupComponent.Callback() { override fun onClose() { if ([email protected] == myInAction) myInAction = null } override fun elementChosen(element: Any) { runBackgroundableTask("Collecting statistics", project, true) { indicator -> indicator.isIndeterminate = true indicator.text2 = (element as Item).usagesCollector.javaClass.simpleName showCollectorUsages(project, element, model.useExtendedPresentation, indicator) } } }, ModalityState.current(), false) } private fun showCollectorUsages(project: Project, item: Item, useExtendedPresentation: Boolean, indicator: ProgressIndicator) { if (project.isDisposed) { return } val collector = item.usagesCollector val metricsPromise = when (collector) { is ApplicationUsagesCollector -> resolvedPromise(collector.metrics) is ProjectUsagesCollector -> collector.getMetrics(project, indicator) else -> throw IllegalArgumentException("Unsupported collector: $collector") } val gson = GsonBuilder().setPrettyPrinting().create() val result = StringBuilder() metricsPromise.onSuccess { metrics -> if (useExtendedPresentation) { result.append("[\n") for (metric in metrics) { val metricData = FUStateUsagesLogger.mergeWithEventData(null, metric.data)!!.build() val event = newLogEvent("test.session", "build", "bucket", System.currentTimeMillis(), collector.groupId, collector.version.toString(), "recorder.version", "event.id", true) for (datum in metricData) { event.event.addData(datum.key, datum.value) } val presentation = LogEventSerializer.toString(event) result.append(presentation) result.append(",\n") } result.append("]") } else { result.append("{") for (metric in metrics) { result.append("\"") result.append(metric.eventId) result.append("\" : ") val presentation = gson.toJsonTree(metric.data.build()) result.append(presentation) result.append(",\n") } result.append("}") } val fileType = FileTypeManager.getInstance().getStdFileType("JSON") val file = LightVirtualFile(item.groupId, fileType, result.toString()) ApplicationManager.getApplication().invokeLater { FileEditorManager.getInstance(project).openFile(file, true) } } } private class Item(val usagesCollector: FeatureUsagesCollector, val groupId: String, val className: String?, val nonUniqueId: Boolean) : ChooseByNameItem { override fun getName(): String = groupId + if (nonUniqueId) " ($className)" else "" override fun getDescription(): String? = className } private class MyChooseByNameModel(project: Project, items: List<Item>) : ListChooseByNameModel<Item>(project, "Enter usage collector group id", "No collectors found", items) { var useExtendedPresentation: Boolean = false override fun getCheckBoxName(): String? = BundleBase.replaceMnemonicAmpersand("&Extended presentation") override fun loadInitialCheckBoxState(): Boolean = false override fun saveInitialCheckBoxState(state: Boolean) { useExtendedPresentation = state } override fun useMiddleMatching(): Boolean = true } }
apache-2.0
e3e507dd6cc2fda5bee4231a5454f8db
43.92
140
0.737123
4.91035
false
false
false
false
jwren/intellij-community
plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/KotlinBuildScriptManipulator.kt
1
28618
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.gradleJava.configuration import com.intellij.openapi.module.Module import com.intellij.openapi.roots.DependencyScope import com.intellij.openapi.roots.ExternalLibraryDescriptor import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.cli.common.arguments.CliArgumentStringBuilder.buildArgumentString import org.jetbrains.kotlin.cli.common.arguments.CliArgumentStringBuilder.replaceLanguageFeature import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion import org.jetbrains.kotlin.idea.configuration.* import org.jetbrains.kotlin.idea.extensions.gradle.* import org.jetbrains.kotlin.idea.gradleJava.KotlinGradleFacadeImpl import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.util.module import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getChildrenOfType import org.jetbrains.kotlin.resolve.ImportPath import org.jetbrains.kotlin.utils.addToStdlib.cast class KotlinBuildScriptManipulator( override val scriptFile: KtFile, override val preferNewSyntax: Boolean, private val versionProvider: GradleVersionProvider ) : GradleBuildScriptManipulator<KtFile> { override fun isApplicable(file: PsiFile): Boolean = file is KtFile private val gradleVersion = versionProvider.fetchGradleVersion(scriptFile) override fun isConfiguredWithOldSyntax(kotlinPluginName: String) = runReadAction { scriptFile.containsApplyKotlinPlugin(kotlinPluginName) && scriptFile.containsCompileStdLib() } override fun isConfigured(kotlinPluginExpression: String): Boolean = runReadAction { scriptFile.containsKotlinPluginInPluginsGroup(kotlinPluginExpression) && scriptFile.containsCompileStdLib() } override fun configureProjectBuildScript(kotlinPluginName: String, version: IdeKotlinVersion): Boolean { if (useNewSyntax(kotlinPluginName, gradleVersion, versionProvider)) return false val originalText = scriptFile.text scriptFile.getBuildScriptBlock()?.apply { addDeclarationIfMissing("var $GSK_KOTLIN_VERSION_PROPERTY_NAME: String by extra", true).also { addExpressionAfterIfMissing("$GSK_KOTLIN_VERSION_PROPERTY_NAME = \"$version\"", it) } getRepositoriesBlock()?.apply { addRepositoryIfMissing(version) addMavenCentralIfMissing() } getDependenciesBlock()?.addPluginToClassPathIfMissing() } return originalText != scriptFile.text } override fun configureModuleBuildScript( kotlinPluginName: String, kotlinPluginExpression: String, stdlibArtifactName: String, version: IdeKotlinVersion, jvmTarget: String? ): Boolean { val originalText = scriptFile.text val useNewSyntax = useNewSyntax(kotlinPluginName, gradleVersion, versionProvider) scriptFile.apply { if (useNewSyntax) { createPluginInPluginsGroupIfMissing(kotlinPluginExpression, version) getDependenciesBlock()?.addNoVersionCompileStdlibIfMissing(stdlibArtifactName) getRepositoriesBlock()?.apply { val repository = getRepositoryForVersion(version) if (repository != null) { scriptFile.module?.getBuildScriptSettingsPsiFile()?.let { with(KotlinGradleFacadeImpl.getManipulator(it)) { addPluginRepository(repository) addMavenCentralPluginRepository() addPluginRepository(DEFAULT_GRADLE_PLUGIN_REPOSITORY) } } } } } else { script?.blockExpression?.addDeclarationIfMissing("val $GSK_KOTLIN_VERSION_PROPERTY_NAME: String by extra", true) getApplyBlock()?.createPluginIfMissing(kotlinPluginName) getDependenciesBlock()?.addCompileStdlibIfMissing(stdlibArtifactName) } getRepositoriesBlock()?.apply { addRepositoryIfMissing(version) addMavenCentralIfMissing() } jvmTarget?.let { changeKotlinTaskParameter("jvmTarget", it, forTests = false) changeKotlinTaskParameter("jvmTarget", it, forTests = true) } } return originalText != scriptFile.text } override fun changeLanguageFeatureConfiguration( feature: LanguageFeature, state: LanguageFeature.State, forTests: Boolean ): PsiElement? = scriptFile.changeLanguageFeatureConfiguration(feature, state, forTests) override fun changeLanguageVersion(version: String, forTests: Boolean): PsiElement? = scriptFile.changeKotlinTaskParameter("languageVersion", version, forTests) override fun changeApiVersion(version: String, forTests: Boolean): PsiElement? = scriptFile.changeKotlinTaskParameter("apiVersion", version, forTests) override fun addKotlinLibraryToModuleBuildScript( targetModule: Module?, scope: DependencyScope, libraryDescriptor: ExternalLibraryDescriptor ) { val dependencyText = getCompileDependencySnippet( libraryDescriptor.libraryGroupId, libraryDescriptor.libraryArtifactId, libraryDescriptor.maxVersion, scope.toGradleCompileScope(scriptFile.module?.getBuildSystemType() == BuildSystemType.AndroidGradle) ) if (targetModule != null && usesNewMultiplatform()) { val findOrCreateTargetSourceSet = scriptFile .getKotlinBlock() ?.getSourceSetsBlock() ?.findOrCreateTargetSourceSet(targetModule.name.takeLastWhile { it != '.' }) val dependenciesBlock = findOrCreateTargetSourceSet?.getDependenciesBlock() dependenciesBlock?.addExpressionIfMissing(dependencyText) } else { scriptFile.getDependenciesBlock()?.addExpressionIfMissing(dependencyText) } } private fun KtBlockExpression.findOrCreateTargetSourceSet(moduleName: String) = findTargetSourceSet(moduleName) ?: createTargetSourceSet(moduleName) private fun KtBlockExpression.findTargetSourceSet(moduleName: String): KtBlockExpression? = statements.find { it.isTargetSourceSetDeclaration(moduleName) }?.getOrCreateBlock() private fun KtExpression.getOrCreateBlock(): KtBlockExpression? = when (this) { is KtCallExpression -> getBlock() ?: addBlock() is KtReferenceExpression -> replace(KtPsiFactory(project).createExpression("$text {\n}")).cast<KtCallExpression>().getBlock() is KtProperty -> delegateExpressionOrInitializer?.getOrCreateBlock() else -> error("Impossible create block for $this") } private fun KtCallExpression.addBlock(): KtBlockExpression? = parent.addAfter( KtPsiFactory(project).createEmptyBody(), this ) as? KtBlockExpression private fun KtBlockExpression.createTargetSourceSet(moduleName: String) = addExpressionIfMissing("getByName(\"$moduleName\") {\n}") .cast<KtCallExpression>() .getBlock() override fun getKotlinStdlibVersion(): String? = scriptFile.getKotlinStdlibVersion() private fun KtBlockExpression.addCompileStdlibIfMissing(stdlibArtifactName: String): KtCallExpression? = findStdLibDependency() ?: addExpressionIfMissing( getCompileDependencySnippet( KOTLIN_GROUP_ID, stdlibArtifactName, version = "\$$GSK_KOTLIN_VERSION_PROPERTY_NAME" ) ) as? KtCallExpression private fun addPluginRepositoryExpression(expression: String) { scriptFile.getPluginManagementBlock()?.findOrCreateBlock("repositories")?.addExpressionIfMissing(expression) } override fun addMavenCentralPluginRepository() { addPluginRepositoryExpression("mavenCentral()") } override fun addPluginRepository(repository: RepositoryDescription) { addPluginRepositoryExpression(repository.toKotlinRepositorySnippet()) } override fun addResolutionStrategy(pluginId: String) { scriptFile .getPluginManagementBlock() ?.findOrCreateBlock("resolutionStrategy") ?.findOrCreateBlock("eachPlugin") ?.addExpressionIfMissing( """ if (requested.id.id == "$pluginId") { useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:${'$'}{requested.version}") } """.trimIndent() ) } private fun KtBlockExpression.addNoVersionCompileStdlibIfMissing(stdlibArtifactName: String): KtCallExpression? = findStdLibDependency() ?: addExpressionIfMissing( "implementation(${getKotlinModuleDependencySnippet( stdlibArtifactName, null )})" ) as? KtCallExpression private fun KtFile.containsCompileStdLib(): Boolean = findScriptInitializer("dependencies")?.getBlock()?.findStdLibDependency() != null private fun KtFile.containsApplyKotlinPlugin(pluginName: String): Boolean = findScriptInitializer("apply")?.getBlock()?.findPlugin(pluginName) != null private fun KtFile.containsKotlinPluginInPluginsGroup(pluginName: String): Boolean = findScriptInitializer("plugins")?.getBlock()?.findPluginInPluginsGroup(pluginName) != null private fun KtBlockExpression.findPlugin(pluginName: String): KtCallExpression? { return PsiTreeUtil.getChildrenOfType(this, KtCallExpression::class.java)?.find { it.calleeExpression?.text == "plugin" && it.valueArguments.firstOrNull()?.text == "\"$pluginName\"" } } private fun KtBlockExpression.findClassPathDependencyVersion(pluginName: String): String? { return PsiTreeUtil.getChildrenOfAnyType(this, KtCallExpression::class.java).mapNotNull { if (it?.calleeExpression?.text == "classpath") { val dependencyName = it.valueArguments.firstOrNull()?.text?.removeSurrounding("\"") if (dependencyName?.startsWith(pluginName) == true) dependencyName.substringAfter("$pluginName:") else null } else null }.singleOrNull() } private fun getPluginInfoFromBuildScript( operatorName: String?, pluginVersion: KtExpression?, receiverCalleeExpression: KtCallExpression? ): Pair<String, String>? { val receiverCalleeExpressionText = receiverCalleeExpression?.calleeExpression?.text?.trim() val receivedPluginName = when { receiverCalleeExpressionText == "id" -> receiverCalleeExpression.valueArguments.firstOrNull()?.text?.trim()?.removeSurrounding("\"") operatorName == "version" -> receiverCalleeExpressionText else -> null } val pluginVersionText = pluginVersion?.text?.trim()?.removeSurrounding("\"") ?: return null return receivedPluginName?.to(pluginVersionText) } private fun KtBlockExpression.findPluginVersionInPluginGroup(pluginName: String): String? { val versionsToPluginNames = PsiTreeUtil.getChildrenOfAnyType(this, KtBinaryExpression::class.java, KtDotQualifiedExpression::class.java).mapNotNull { when (it) { is KtBinaryExpression -> getPluginInfoFromBuildScript( it.operationReference.text, it.right, it.left as? KtCallExpression ) is KtDotQualifiedExpression -> (it.selectorExpression as? KtCallExpression)?.run { getPluginInfoFromBuildScript( calleeExpression?.text, valueArguments.firstOrNull()?.getArgumentExpression(), it.receiverExpression as? KtCallExpression ) } else -> null } }.toMap() return versionsToPluginNames.getOrDefault(pluginName, null) } private fun KtBlockExpression.findPluginInPluginsGroup(pluginName: String): KtCallExpression? { return PsiTreeUtil.getChildrenOfAnyType( this, KtCallExpression::class.java, KtBinaryExpression::class.java, KtDotQualifiedExpression::class.java ).mapNotNull { when (it) { is KtCallExpression -> it is KtBinaryExpression -> { if (it.operationReference.text == "version") it.left as? KtCallExpression else null } is KtDotQualifiedExpression -> { if ((it.selectorExpression as? KtCallExpression)?.calleeExpression?.text == "version") { it.receiverExpression as? KtCallExpression } else null } else -> null } }.find { "${it.calleeExpression?.text?.trim() ?: ""}(${it.valueArguments.firstOrNull()?.text ?: ""})" == pluginName } } private fun KtFile.findScriptInitializer(startsWith: String): KtScriptInitializer? = PsiTreeUtil.findChildrenOfType(this, KtScriptInitializer::class.java).find { it.text.startsWith(startsWith) } private fun KtBlockExpression.findBlock(name: String): KtBlockExpression? { return getChildrenOfType<KtCallExpression>().find { it.calleeExpression?.text == name && it.valueArguments.singleOrNull()?.getArgumentExpression() is KtLambdaExpression }?.getBlock() } private fun KtScriptInitializer.getBlock(): KtBlockExpression? = PsiTreeUtil.findChildOfType(this, KtCallExpression::class.java)?.getBlock() private fun KtCallExpression.getBlock(): KtBlockExpression? = (valueArguments.singleOrNull()?.getArgumentExpression() as? KtLambdaExpression)?.bodyExpression ?: lambdaArguments.lastOrNull()?.getLambdaExpression()?.bodyExpression private fun KtFile.getKotlinStdlibVersion(): String? { return findScriptInitializer("dependencies")?.getBlock()?.let { when (val expression = it.findStdLibDependency()?.valueArguments?.firstOrNull()?.getArgumentExpression()) { is KtCallExpression -> expression.valueArguments.getOrNull(1)?.text?.trim('\"') is KtStringTemplateExpression -> expression.text?.trim('\"')?.substringAfterLast(":")?.removePrefix("$") else -> null } } } private fun KtBlockExpression.findStdLibDependency(): KtCallExpression? { return PsiTreeUtil.getChildrenOfType(this, KtCallExpression::class.java)?.find { val calleeText = it.calleeExpression?.text calleeText in SCRIPT_PRODUCTION_DEPENDENCY_STATEMENTS && (it.valueArguments.firstOrNull()?.getArgumentExpression()?.isKotlinStdLib() ?: false) } } private fun KtExpression.isKotlinStdLib(): Boolean = when (this) { is KtCallExpression -> { val calleeText = calleeExpression?.text (calleeText == "kotlinModule" || calleeText == "kotlin") && valueArguments.firstOrNull()?.getArgumentExpression()?.text?.startsWith("\"stdlib") ?: false } is KtStringTemplateExpression -> text.startsWith("\"$STDLIB_ARTIFACT_PREFIX") else -> false } private fun KtFile.getPluginManagementBlock(): KtBlockExpression? = findOrCreateScriptInitializer("pluginManagement", true) private fun KtFile.getKotlinBlock(): KtBlockExpression? = findOrCreateScriptInitializer("kotlin") private fun KtBlockExpression.getSourceSetsBlock(): KtBlockExpression? = findOrCreateBlock("sourceSets") private fun KtFile.getRepositoriesBlock(): KtBlockExpression? = findOrCreateScriptInitializer("repositories") private fun KtFile.getDependenciesBlock(): KtBlockExpression? = findOrCreateScriptInitializer("dependencies") private fun KtFile.getPluginsBlock(): KtBlockExpression? = findOrCreateScriptInitializer("plugins", true) private fun KtFile.createPluginInPluginsGroupIfMissing(pluginName: String, version: IdeKotlinVersion): KtCallExpression? = getPluginsBlock()?.let { it.findPluginInPluginsGroup(pluginName) ?: it.addExpressionIfMissing("$pluginName version \"${version.rawVersion}\"") as? KtCallExpression } private fun KtFile.createApplyBlock(): KtBlockExpression? { val apply = psiFactory.createScriptInitializer("apply {\n}") val plugins = findScriptInitializer("plugins") val addedElement = plugins?.addSibling(apply) ?: addToScriptBlock(apply) addedElement?.addNewLinesIfNeeded() return (addedElement as? KtScriptInitializer)?.getBlock() } private fun KtFile.getApplyBlock(): KtBlockExpression? = findScriptInitializer("apply")?.getBlock() ?: createApplyBlock() private fun KtBlockExpression.createPluginIfMissing(pluginName: String): KtCallExpression? = findPlugin(pluginName) ?: addExpressionIfMissing("plugin(\"$pluginName\")") as? KtCallExpression private fun KtFile.changeCoroutineConfiguration(coroutineOption: String): PsiElement? { val snippet = "experimental.coroutines = Coroutines.${coroutineOption.toUpperCase()}" val kotlinBlock = getKotlinBlock() ?: return null addImportIfMissing("org.jetbrains.kotlin.gradle.dsl.Coroutines") val statement = kotlinBlock.statements.find { it.text.startsWith("experimental.coroutines") } return if (statement != null) { statement.replace(psiFactory.createExpression(snippet)) } else { kotlinBlock.add(psiFactory.createExpression(snippet)).apply { addNewLinesIfNeeded() } } } private fun KtFile.changeLanguageFeatureConfiguration( feature: LanguageFeature, state: LanguageFeature.State, forTests: Boolean ): PsiElement? { if (usesNewMultiplatform()) { state.assertApplicableInMultiplatform() return getKotlinBlock() ?.findOrCreateBlock("sourceSets") ?.findOrCreateBlock("all") ?.addExpressionIfMissing("languageSettings.enableLanguageFeature(\"${feature.name}\")") } val pluginsBlock = findScriptInitializer("plugins")?.getBlock() val rawKotlinVersion = pluginsBlock?.findPluginVersionInPluginGroup("kotlin") ?: pluginsBlock?.findPluginVersionInPluginGroup("org.jetbrains.kotlin.jvm") ?: findScriptInitializer("buildscript")?.getBlock()?.findBlock("dependencies")?.findClassPathDependencyVersion("org.jetbrains.kotlin:kotlin-gradle-plugin") val kotlinVersion = rawKotlinVersion?.let(IdeKotlinVersion::opt) val featureArgumentString = feature.buildArgumentString(state, kotlinVersion) val parameterName = "freeCompilerArgs" return addOrReplaceKotlinTaskParameter( parameterName, "listOf(\"$featureArgumentString\")", forTests ) { val newText = text.replaceLanguageFeature( feature, state, kotlinVersion, prefix = "$parameterName = listOf(", postfix = ")" ) replace(psiFactory.createExpression(newText)) } } private fun KtFile.addOrReplaceKotlinTaskParameter( parameterName: String, defaultValue: String, forTests: Boolean, replaceIt: KtExpression.() -> PsiElement ): PsiElement? { val taskName = if (forTests) "compileTestKotlin" else "compileKotlin" val optionsBlock = findScriptInitializer("$taskName.kotlinOptions")?.getBlock() return if (optionsBlock != null) { val assignment = optionsBlock.statements.find { (it as? KtBinaryExpression)?.left?.text == parameterName } assignment?.replaceIt() ?: optionsBlock.addExpressionIfMissing("$parameterName = $defaultValue") } else { addImportIfMissing("org.jetbrains.kotlin.gradle.tasks.KotlinCompile") script?.blockExpression?.addDeclarationIfMissing("val $taskName: KotlinCompile by tasks") addTopLevelBlock("$taskName.kotlinOptions")?.addExpressionIfMissing("$parameterName = $defaultValue") } } private fun KtFile.changeKotlinTaskParameter(parameterName: String, parameterValue: String, forTests: Boolean): PsiElement? { return addOrReplaceKotlinTaskParameter(parameterName, "\"$parameterValue\"", forTests) { replace(psiFactory.createExpression("$parameterName = \"$parameterValue\"")) } } private fun KtBlockExpression.getRepositorySnippet(version: IdeKotlinVersion): String? { val repository = getRepositoryForVersion(version) return when { repository != null -> repository.toKotlinRepositorySnippet() !isRepositoryConfigured(text) -> MAVEN_CENTRAL else -> null } } private fun KtFile.getBuildScriptBlock(): KtBlockExpression? = findOrCreateScriptInitializer("buildscript", true) private fun KtFile.findOrCreateScriptInitializer(name: String, first: Boolean = false): KtBlockExpression? = findScriptInitializer(name)?.getBlock() ?: addTopLevelBlock(name, first) private fun KtBlockExpression.getRepositoriesBlock(): KtBlockExpression? = findOrCreateBlock("repositories") private fun KtBlockExpression.getDependenciesBlock(): KtBlockExpression? = findOrCreateBlock("dependencies") private fun KtBlockExpression.addRepositoryIfMissing(version: IdeKotlinVersion): KtCallExpression? { val snippet = getRepositorySnippet(version) ?: return null return addExpressionIfMissing(snippet) as? KtCallExpression } private fun KtBlockExpression.addMavenCentralIfMissing(): KtCallExpression? = if (!isRepositoryConfigured(text)) addExpressionIfMissing(MAVEN_CENTRAL) as? KtCallExpression else null private fun KtBlockExpression.findOrCreateBlock(name: String, first: Boolean = false) = findBlock(name) ?: addBlock(name, first) private fun KtBlockExpression.addPluginToClassPathIfMissing(): KtCallExpression? = addExpressionIfMissing(getKotlinGradlePluginClassPathSnippet()) as? KtCallExpression private fun KtBlockExpression.addBlock(name: String, first: Boolean = false): KtBlockExpression? { return psiFactory.createExpression("$name {\n}") .let { if (first) addAfter(it, null) else add(it) } ?.apply { addNewLinesIfNeeded() } ?.cast<KtCallExpression>() ?.getBlock() } private fun KtFile.addTopLevelBlock(name: String, first: Boolean = false): KtBlockExpression? { val scriptInitializer = psiFactory.createScriptInitializer("$name {\n}") val addedElement = addToScriptBlock(scriptInitializer, first) as? KtScriptInitializer addedElement?.addNewLinesIfNeeded() return addedElement?.getBlock() } private fun PsiElement.addSibling(element: PsiElement): PsiElement = parent.addAfter(element, this) private fun PsiElement.addNewLineBefore(lineBreaks: Int = 1) { parent.addBefore(psiFactory.createNewLine(lineBreaks), this) } private fun PsiElement.addNewLineAfter(lineBreaks: Int = 1) { parent.addAfter(psiFactory.createNewLine(lineBreaks), this) } private fun PsiElement.addNewLinesIfNeeded(lineBreaks: Int = 1) { if (prevSibling != null && prevSibling.text.isNotBlank()) { addNewLineBefore(lineBreaks) } if (nextSibling != null && nextSibling.text.isNotBlank()) { addNewLineAfter(lineBreaks) } } private fun KtFile.addToScriptBlock(element: PsiElement, first: Boolean = false): PsiElement? = if (first) script?.blockExpression?.addAfter(element, null) else script?.blockExpression?.add(element) private fun KtFile.addImportIfMissing(path: String): KtImportDirective = importDirectives.find { it.importPath?.pathStr == path } ?: importList?.add( psiFactory.createImportDirective( ImportPath.fromString( path ) ) ) as KtImportDirective private fun KtBlockExpression.addExpressionAfterIfMissing(text: String, after: PsiElement): KtExpression = addStatementIfMissing(text) { addAfter(psiFactory.createExpression(it), after) } private fun KtBlockExpression.addExpressionIfMissing(text: String, first: Boolean = false): KtExpression = addStatementIfMissing(text) { psiFactory.createExpression(it).let { created -> if (first) addAfter(created, null) else add(created) } } private fun KtBlockExpression.addDeclarationIfMissing(text: String, first: Boolean = false): KtDeclaration = addStatementIfMissing(text) { psiFactory.createDeclaration<KtDeclaration>(it).let { created -> if (first) addAfter(created, null) else add(created) } } private inline fun <reified T : PsiElement> KtBlockExpression.addStatementIfMissing( text: String, crossinline factory: (String) -> PsiElement ): T { statements.find { StringUtil.equalsIgnoreWhitespaces(it.text, text) }?.let { return it as T } return factory(text).apply { addNewLinesIfNeeded() } as T } private fun KtPsiFactory.createScriptInitializer(text: String): KtScriptInitializer = createFile("dummy.kts", text).script?.blockExpression?.firstChild as KtScriptInitializer private val PsiElement.psiFactory: KtPsiFactory get() = KtPsiFactory(this) private fun getCompileDependencySnippet( groupId: String, artifactId: String, version: String?, compileScope: String = "implementation" ): String { if (groupId != KOTLIN_GROUP_ID) { return "$compileScope(\"$groupId:$artifactId:$version\")" } val kotlinPluginName = if (scriptFile.module?.getBuildSystemType() == BuildSystemType.AndroidGradle) { "kotlin-android" } else { KotlinGradleModuleConfigurator.KOTLIN } if (useNewSyntax(kotlinPluginName, gradleVersion, versionProvider)) { return "$compileScope(${getKotlinModuleDependencySnippet(artifactId)})" } val libraryVersion = if (version == GSK_KOTLIN_VERSION_PROPERTY_NAME) "\$$version" else version return "$compileScope(${getKotlinModuleDependencySnippet(artifactId, libraryVersion)})" } companion object { private const val STDLIB_ARTIFACT_PREFIX = "org.jetbrains.kotlin:kotlin-stdlib" const val GSK_KOTLIN_VERSION_PROPERTY_NAME = "kotlin_version" fun getKotlinGradlePluginClassPathSnippet(): String = "classpath(${getKotlinModuleDependencySnippet("gradle-plugin", "\$$GSK_KOTLIN_VERSION_PROPERTY_NAME")})" fun getKotlinModuleDependencySnippet(artifactId: String, version: String? = null): String { val moduleName = artifactId.removePrefix("kotlin-") return when (version) { null -> "kotlin(\"$moduleName\")" "\$$GSK_KOTLIN_VERSION_PROPERTY_NAME" -> "kotlinModule(\"$moduleName\", $GSK_KOTLIN_VERSION_PROPERTY_NAME)" else -> "kotlinModule(\"$moduleName\", ${"\"$version\""})" } } } } private fun KtExpression.isTargetSourceSetDeclaration(moduleName: String): Boolean = with(text) { when (this@isTargetSourceSetDeclaration) { is KtProperty -> startsWith("val $moduleName by") || initializer?.isTargetSourceSetDeclaration(moduleName) == true is KtCallExpression -> startsWith("getByName(\"$moduleName\")") else -> false } }
apache-2.0
d7f12e8cc4a0446a0c16a97736e391eb
45.837971
167
0.671046
5.839216
false
false
false
false
jwren/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/actions/ResumeIndexingAction.kt
7
3833
// 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.vcs.log.ui.actions import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.vfs.VirtualFile import com.intellij.vcs.log.VcsLogBundle import com.intellij.vcs.log.data.index.VcsLogBigRepositoriesList import com.intellij.vcs.log.data.index.VcsLogIndex import com.intellij.vcs.log.data.index.VcsLogModifiableIndex import com.intellij.vcs.log.data.index.VcsLogPersistentIndex import com.intellij.vcs.log.impl.VcsLogSharedSettings import com.intellij.vcs.log.statistics.VcsLogUsageTriggerCollector import com.intellij.vcs.log.ui.VcsLogInternalDataKeys import com.intellij.vcs.log.util.VcsLogUtil class ResumeIndexingAction : DumbAwareAction() { override fun update(e: AnActionEvent) { val data = e.getData(VcsLogInternalDataKeys.LOG_DATA) val project = e.project if (data == null || project == null || !VcsLogSharedSettings.isIndexSwitchedOn(project)) { e.presentation.isEnabledAndVisible = false return } val rootsForIndexing = VcsLogPersistentIndex.getRootsForIndexing(data.logProviders) if (rootsForIndexing.isEmpty()) { e.presentation.isEnabledAndVisible = false return } val scheduledForIndexing = rootsForIndexing.filter { it.isScheduledForIndexing(data.index) } val bigRepositories = rootsForIndexing.filter { it.isBig() } e.presentation.isEnabledAndVisible = (bigRepositories.isNotEmpty() || scheduledForIndexing.isNotEmpty()) val vcsDisplayName = VcsLogUtil.getVcsDisplayName(project, rootsForIndexing.map { data.getLogProvider(it) }) if (scheduledForIndexing.isNotEmpty()) { e.presentation.text = VcsLogBundle.message("action.title.pause.indexing", vcsDisplayName) e.presentation.description = VcsLogBundle.message("action.description.is.scheduled", getText(scheduledForIndexing)) e.presentation.icon = AllIcons.Process.ProgressPauseSmall } else { e.presentation.text = VcsLogBundle.message("action.title.resume.indexing", vcsDisplayName) e.presentation.description = VcsLogBundle.message("action.description.was.paused", getText(bigRepositories)) e.presentation.icon = AllIcons.Process.ProgressResumeSmall } } private fun getText(repositories: List<VirtualFile>): String { val repositoriesLimit = 3 val result = repositories.map { it.name }.sorted().take(repositoriesLimit).joinToString(", ") { "'$it'" } if (repositories.size > repositoriesLimit) { return "$result, ..." } return result } override fun actionPerformed(e: AnActionEvent) { VcsLogUsageTriggerCollector.triggerUsage(e, this) val data = e.getRequiredData(VcsLogInternalDataKeys.LOG_DATA) val rootsForIndexing = VcsLogPersistentIndex.getRootsForIndexing(data.logProviders) if (rootsForIndexing.isEmpty()) return if (rootsForIndexing.any { it.isScheduledForIndexing(data.index) }) { rootsForIndexing.filter { !it.isBig() }.forEach { VcsLogBigRepositoriesList.getInstance().addRepository(it) } } else { var resumed = false for (root in rootsForIndexing.filter { it.isBig() }) { resumed = resumed or VcsLogBigRepositoriesList.getInstance().removeRepository(root) } if (resumed) (data.index as? VcsLogModifiableIndex)?.scheduleIndex(false) } } private fun VirtualFile.isBig(): Boolean = VcsLogBigRepositoriesList.getInstance().isBig(this) private fun VirtualFile.isScheduledForIndexing(index: VcsLogIndex): Boolean = index.isIndexingEnabled(this) && !index.isIndexed(this) }
apache-2.0
1d034e5f1d511e9e697222d69cd0dab4
46.925
140
0.745369
4.467366
false
false
false
false
androidx/androidx
core/core-ktx/src/androidTest/java/androidx/core/graphics/PorterDuffTest.kt
3
1660
/* * Copyright (C) 2018 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.core.graphics import android.graphics.Paint import android.graphics.PorterDuff import androidx.test.filters.SmallTest import org.junit.Assert.assertEquals import org.junit.Test @SmallTest class PorterDuffTest { @Test fun xfermode() { val p = createBitmap(1, 1).applyCanvas { val p = Paint().apply { color = 0xffffffff.toInt() } drawRect(0f, 0f, 1f, 1f, p) p.color = 0x7f00ff00 p.xfermode = PorterDuff.Mode.SRC.toXfermode() drawRect(0f, 0f, 1f, 1f, p) }.getPixel(0, 0) assertEquals(0x7f00ff00, p) } @Test fun colorFilter() { val p = createBitmap(1, 1).applyCanvas { val p = Paint().apply { color = 0xffffffff.toInt() } drawRect(0f, 0f, 1f, 1f, p) p.color = 0xff000000.toInt() p.colorFilter = PorterDuff.Mode.SRC.toColorFilter(0xff00ff00.toInt()) drawRect(0f, 0f, 1f, 1f, p) }.getPixel(0, 0) assertEquals(0xff00ff00.toInt(), p) } }
apache-2.0
724206cd8960c8da0f630ab22729042a
30.923077
81
0.651205
3.688889
false
true
false
false
GunoH/intellij-community
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/dotnet/DotnetIconSync.kt
2
4729
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.intellij.build.images.sync.dotnet import org.jetbrains.intellij.build.images.generateIconsClasses import org.jetbrains.intellij.build.images.isImage import org.jetbrains.intellij.build.images.shutdownAppScheduledExecutorService import org.jetbrains.intellij.build.images.sync.* import java.util.* import kotlin.io.path.name object DotnetIconSync { @JvmStatic fun main(args: Array<String>) = sync() private class SyncPath(val iconsPath: String, val devPath: String) private const val riderIconsRelativePath = "Rider/Frontend/rider/icons" private val syncPaths = listOf( SyncPath("rider", "$riderIconsRelativePath/resources/rider"), SyncPath("net", "$riderIconsRelativePath/resources/resharper") ) private val committer by lazy(::triggeredBy) private val context = Context().apply { iconFilter = { file -> // need to filter designers' icons using developers' icon-robots.txt iconRepoDir.relativize(file) .let(devRepoDir::resolve) .let(IconRobotsDataReader::isSyncSkipped) .not() } } private val targetWaveNumber by lazy { val prop = "icons.sync.dotnet.wave.number" System.getProperty(prop) ?: error("Specify property $prop") } private val branchForMerge by lazy { val randomPart = UUID.randomUUID().toString().substring(1..4) "net$targetWaveNumber-icons-sync-$randomPart" } private val mergeRobotBuildConfiguration by lazy { val prop = "icons.sync.dotnet.merge.robot.build.conf" System.getProperty(prop) ?: error("Specify property $prop") } private fun step(msg: String) = println("\n** $msg") fun sync() { try { transformIconsToIdeaFormat() syncPaths.forEach(this::sync) generateClasses() RiderIconsJsonGenerator.generate(context.devRepoRoot.resolve(riderIconsRelativePath)) if (stageChanges().isEmpty()) { println("Nothing to commit") } else if (isUnderTeamCity()) { createBranchForMerge() commitChanges() pushBranchForMerge() triggerMerge() } println("Done.") } finally { shutdownAppScheduledExecutorService() cleanup(context.iconRepo) } } private fun transformIconsToIdeaFormat() { step("Transforming icons from Dotnet to Idea format..") syncPaths.forEach { val path = context.iconRepo.resolve(it.iconsPath) DotnetIconsTransformation.transformToIdeaFormat(path) } } private fun sync(path: SyncPath) { step("Syncing icons for ${path.devPath}..") context.devRepoDir = context.devRepoRoot.resolve(path.devPath) context.iconRepoDir = context.iconRepo.resolve(path.iconsPath) context.devRepoDir.toFile().walkTopDown().forEach { if (isImage(it)) { it.delete() || error("Unable to delete $it") } } context.iconRepoDir.toFile().walkTopDown().forEach { if (isImage(it) && context.iconFilter(it.toPath())) { val target = context.devRepoDir.resolve(context.iconRepoDir.relativize(it.toPath())) it.copyTo(target.toFile(), overwrite = true) } } } private fun generateClasses() { step("Generating classes..") generateIconsClasses(dbFile = null, config = DotnetIconsClasses(context.devRepoDir.toAbsolutePath().toString())) } private fun stageChanges(): Collection<String> { step("Staging changes..") val changes = gitStatus(context.devRepoRoot, includeUntracked = true).all().filter { val file = context.devRepoRoot.resolve(it) isImage(file) || file.toString().endsWith(".java") || file.name == RiderIconsJsonGenerator.GENERATED_FILE_NAME } if (changes.isNotEmpty()) { stageFiles(changes, context.devRepoRoot) } return changes } private fun commitChanges() { step("Committing changes..") commit(context.devRepoRoot, "Synced from ${getOriginUrl(context.iconRepo)}", committer.name, committer.email) val commit = commitInfo(context.devRepoRoot) ?: error("Unable to perform commit") println("Committed ${commit.hash} '${commit.subject}'") } private fun createBranchForMerge() { step("Creating branch $branchForMerge..") execute(context.devRepoRoot, GIT, "checkout", "-B", branchForMerge) } private fun pushBranchForMerge() { step("Pushing $branchForMerge..") push(context.devRepoRoot, branchForMerge) } private fun triggerMerge() { step("Triggering merge with $mergeRobotBuildConfiguration..") val response = triggerBuild(mergeRobotBuildConfiguration, branchForMerge) println("Response is $response") } }
apache-2.0
cef377b9f61df0eb38b492bc2c6674dc
33.275362
140
0.700148
4.101474
false
false
false
false
GunoH/intellij-community
plugins/kotlin/performance-tests/test/org/jetbrains/kotlin/idea/perf/profilers/PhaseProfiler.kt
4
939
// 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.perf.profilers interface PhaseProfiler { fun start() fun stop() } object DummyPhaseProfiler : PhaseProfiler { override fun start() {} override fun stop() {} } class ActualPhaseProfiler( private val profilerHandler: ProfilerHandler ) : PhaseProfiler { private var attempt: Int = 1 override fun start() { profilerHandler.startProfiling() } override fun stop() { profilerHandler.stopProfiling(attempt) attempt++ } } data class ProfilerConfig( var enabled: Boolean = false, var path: String = "", var name: String = "", var tracing: Boolean = false, var options: List<String> = emptyList(), var warmup: Boolean = false, var dryRun: Boolean = false )
apache-2.0
eb08266d5fce7620616ac8a091575499
22.5
158
0.675186
4.210762
false
false
false
false
GunoH/intellij-community
plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/scripting/roots/GradleBuildRootIndex.kt
4
3622
// 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.gradleJava.scripting.roots import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.gradle.scripting.settings.StandaloneScriptsStorage class GradleBuildRootIndex(private val project: Project) : StandaloneScriptsUpdater { private val log = logger<GradleBuildRootIndex>() private inner class StandaloneScriptRootsCache { private val standaloneScripts: MutableSet<String> get() = StandaloneScriptsStorage.getInstance(project)?.files ?: hashSetOf() private val standaloneScriptRoots = mutableMapOf<String, GradleBuildRoot?>() init { standaloneScripts.forEach(::updateRootsCache) } fun all(): List<String> = standaloneScripts.toList() fun get(path: String): GradleBuildRoot? = standaloneScriptRoots[path] fun add(path: String) { standaloneScripts.add(path) updateRootsCache(path) } fun remove(path: String): GradleBuildRoot? { standaloneScripts.remove(path) return standaloneScriptRoots.remove(path) } fun updateRootsCache(path: String) { standaloneScriptRoots[path] = findNearestRoot(path) } } private val standaloneScriptRoots by lazy { StandaloneScriptRootsCache() } private val byWorkingDir = HashMap<String, GradleBuildRoot>() private val byProjectDir = HashMap<String, GradleBuildRoot>() val list: Collection<GradleBuildRoot> get() = byWorkingDir.values @Synchronized fun rebuildProjectRoots() { byProjectDir.clear() byWorkingDir.values.forEach { buildRoot -> buildRoot.projectRoots.forEach { byProjectDir[it] = buildRoot } } standaloneScriptRoots.all().forEach(standaloneScriptRoots::updateRootsCache) } @Synchronized fun getBuildByRootDir(dir: String) = byWorkingDir[dir] @Synchronized fun findNearestRoot(path: String): GradleBuildRoot? { var max: Pair<String, GradleBuildRoot>? = null byWorkingDir.entries.forEach { if (path.startsWith(it.key) && (max == null || it.key.length > max!!.first.length)) { max = it.key to it.value } } return max?.second } @Synchronized fun getBuildByProjectDir(projectDir: String) = byProjectDir[projectDir] @Synchronized fun isStandaloneScript(path: String) = path in standaloneScriptRoots.all() @Synchronized fun getStandaloneScriptRoot(path: String) = standaloneScriptRoots.get(path) @Synchronized fun add(value: GradleBuildRoot): GradleBuildRoot? { val prefix = value.pathPrefix val old = byWorkingDir.put(prefix, value) rebuildProjectRoots() log.info("$prefix: $old -> $value") return old } @Synchronized fun remove(prefix: String) = byWorkingDir.remove(prefix)?.also { rebuildProjectRoots() log.info("$prefix: removed") } @Synchronized override fun addStandaloneScript(path: String) { standaloneScriptRoots.add(path) } @Synchronized override fun removeStandaloneScript(path: String): GradleBuildRoot? { return standaloneScriptRoots.remove(path) } override val standaloneScripts: Collection<String> @Synchronized get() = standaloneScriptRoots.all() }
apache-2.0
215c88fa2d0f6ef867d68e35e4488eb2
31.936364
158
0.675594
4.747051
false
false
false
false
GunoH/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/google/authorization/GoogleOAuthService.kt
9
3107
// Copyright 2000-2021 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.intellij.plugins.markdown.google.authorization import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.PropertyNamingStrategies import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.intellij.collaboration.async.CompletableFutureUtil.submitIOTask import com.intellij.collaboration.auth.services.OAuthCredentialsAcquirerHttp import com.intellij.collaboration.auth.services.OAuthServiceBase import com.intellij.collaboration.auth.services.OAuthServiceWithRefresh import com.intellij.openapi.components.Service import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressManager import org.apache.commons.lang.time.DateUtils import org.intellij.plugins.markdown.google.utils.GoogleAccountsUtils import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.CompletableFuture @Service class GoogleOAuthService : OAuthServiceBase<GoogleCredentials>(), OAuthServiceWithRefresh<GoogleCredentials> { companion object { val jacksonMapper: ObjectMapper get() = jacksonObjectMapper() fun getLocalDateTime(responseDate: String): Date = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US).apply { timeZone = TimeZone.getTimeZone("GMT") }.parse(responseDate) } override val name: String get() = "google/oauth" // TODO: fix case when some updateAccessToken are started or auth flow is started before override fun updateAccessToken(refreshTokenRequest: OAuthServiceWithRefresh.RefreshTokenRequest): CompletableFuture<GoogleCredentials> = ProgressManager.getInstance().submitIOTask(EmptyProgressIndicator()) { val response = OAuthCredentialsAcquirerHttp.requestToken(refreshTokenRequest.refreshTokenUrlWithParameters) val responseDateTime = getLocalDateTime(response.headers().firstValue("date").get()) if (response.statusCode() == 200) { val responseData = with(GoogleAccountsUtils.jacksonMapper) { propertyNamingStrategy = PropertyNamingStrategies.SnakeCaseStrategy() readValue(response.body(), RefreshResponseData::class.java) } GoogleCredentials( responseData.accessToken, refreshTokenRequest.refreshToken, responseData.expiresIn, responseData.tokenType, responseData.scope, DateUtils.addSeconds(responseDateTime, responseData.expiresIn.toInt()) ) } else { throw RuntimeException(response.body().ifEmpty { "No token provided" }) } } override fun revokeToken(token: String) { TODO("Not yet implemented") } private data class RefreshResponseData(val accessToken: String, val expiresIn: Long, val scope: String, val tokenType: String, val idToken: String) }
apache-2.0
a1f9f2ef39947550587a42335ebe2aeb
46.075758
158
0.737045
5.16113
false
false
false
false
siosio/intellij-community
platform/lang-impl/src/com/intellij/ide/bookmarks/actions/BookmarkContext.kt
1
3760
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.bookmarks.actions import com.intellij.ide.bookmark.BookmarkType import com.intellij.ide.bookmarks.Bookmark import com.intellij.ide.bookmarks.BookmarkManager import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.editor.ex.EditorGutterComponentEx import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiCompiledElement import com.intellij.psi.util.PsiUtilCore import com.intellij.testFramework.LightVirtualFile import com.intellij.ui.awt.RelativePoint import java.awt.Component internal data class BookmarkContext(val project: Project, val file: VirtualFile, val editor: Editor?, val line: Int) { val manager: BookmarkManager by lazy { BookmarkManager.getInstance(project) } val bookmark: Bookmark? get() = manager.findBookmark(file, line) fun setType(type: BookmarkType) { val bookmark = manager.findBookmark(file, line) when { bookmark == null -> { when (editor != null) { true -> manager.addEditorBookmark(editor, line) else -> manager.addTextBookmark(file, line, "") } manager.findBookmark(file, line)?.let { if (BookmarkType.DEFAULT != type) { manager.setMnemonic(it, type.mnemonic) } } } bookmark.mnemonic == type.mnemonic -> manager.removeBookmark(bookmark) else -> manager.setMnemonic(bookmark, type.mnemonic) } } internal fun getPointOnGutter(component: Component?) = if (editor == null || line < 0) null else getGutter(component)?.let { RelativePoint(it, editor.logicalPositionToXY(LogicalPosition(line, 0)).apply { x = it.iconAreaOffset y += editor.lineHeight }) } private fun getGutter(component: Component?) = component as? EditorGutterComponentEx ?: when (Registry.`is`("ide.bookmark.mnemonic.chooser.always.above.gutter")) { true -> editor?.gutter as? EditorGutterComponentEx else -> null } } internal val DataContext.context: BookmarkContext? get() { val project = getData(CommonDataKeys.PROJECT) ?: return null val editor = getData(CommonDataKeys.EDITOR) ?: getData(CommonDataKeys.EDITOR_EVEN_IF_INACTIVE) if (editor != null) { if (editor.isOneLineMode) return null val line = getData(EditorGutterComponentEx.LOGICAL_LINE_AT_CURSOR) ?: editor.caretModel.logicalPosition.line val file = FileDocumentManager.getInstance().getFile(editor.document) ?: return null return if (file is LightVirtualFile) null else BookmarkContext(project, file, editor, line) } val psiElement = getData(PlatformDataKeys.PSI_ELEMENT) val elementFile = PsiUtilCore.getVirtualFile(psiElement?.containingFile) if (psiElement != null && psiElement !is PsiCompiledElement && elementFile != null) { if (elementFile is LightVirtualFile) return null val line = FileDocumentManager.getInstance().getDocument(elementFile) ?.getLineNumber(psiElement.textOffset) ?: -1 return BookmarkContext(project, elementFile, null, line) } val file = getData(PlatformDataKeys.VIRTUAL_FILE) if (file != null && file !is LightVirtualFile) { return BookmarkContext(project, file, null, -1) } return null }
apache-2.0
c54943df0546475b8d7b4b6795b554eb
42.218391
140
0.729521
4.470868
false
false
false
false
siosio/intellij-community
plugins/ide-features-trainer/src/training/statistic/ActionIdRuleValidator.kt
2
956
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package training.statistic import com.intellij.internal.statistic.eventLog.validator.ValidationResultType import com.intellij.internal.statistic.eventLog.validator.rules.EventContext import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule import com.intellij.openapi.actionSystem.ActionManager import training.statistic.FeatureUsageStatisticConsts.ACTION_ID private class ActionIdRuleValidator : CustomValidationRule() { override fun acceptRuleId(ruleId: String?): Boolean = (ACTION_ID == ruleId) override fun doValidate(data: String, context: EventContext): ValidationResultType { val anAction = ActionManager.getInstance().getActionOrStub(data) if (anAction != null) { return ValidationResultType.ACCEPTED } return ValidationResultType.REJECTED } }
apache-2.0
0b7eba750f442787370dc2a94acfd06d
46.85
140
0.808577
4.78
false
false
false
false
jwren/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ResolveUtil.kt
1
8506
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("LoopToCallChain") package org.jetbrains.plugins.groovy.lang.resolve import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.Key import com.intellij.psi.* import com.intellij.psi.scope.ElementClassHint import com.intellij.psi.scope.ElementClassHint.DeclarationKind import com.intellij.psi.scope.NameHint import com.intellij.psi.scope.PsiScopeProcessor import com.intellij.psi.util.CachedValueProvider.Result import com.intellij.psi.util.CachedValuesManager.getCachedValue import com.intellij.util.castSafelyTo import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement import org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.DefaultConstructor import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrBindingVariable import org.jetbrains.plugins.groovy.lang.psi.util.skipSameTypeParents import org.jetbrains.plugins.groovy.lang.resolve.api.GroovyProperty import org.jetbrains.plugins.groovy.lang.resolve.imports.importedNameKey import org.jetbrains.plugins.groovy.lang.resolve.processors.DynamicMembersHint import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyResolveKind val log: Logger = Logger.getInstance("#org.jetbrains.plugins.groovy.lang.resolve") @JvmField val NON_CODE: Key<Boolean?> = Key.create("groovy.process.non.code.members") @JvmField val sorryCannotKnowElementKind: Key<Boolean> = Key.create("groovy.skip.kind.check.please") fun initialState(processNonCodeMembers: Boolean): ResolveState = ResolveState.initial().put(NON_CODE, processNonCodeMembers) fun ResolveState.processNonCodeMembers(): Boolean = get(NON_CODE).let { it == null || it } fun treeWalkUp(place: PsiElement, processor: PsiScopeProcessor, state: ResolveState): Boolean { return ResolveUtil.treeWalkUp(place, place, processor, state) } fun GrStatementOwner.processStatements(lastParent: PsiElement?, processor: (GrStatement) -> Boolean): Boolean { var run = if (lastParent == null) lastChild else lastParent.prevSibling while (run != null) { if (run is GrStatement && !processor(run)) return false run = run.prevSibling } return true } fun GrStatementOwner.processLocals(processor: PsiScopeProcessor, state: ResolveState, lastParent: PsiElement?, place: PsiElement): Boolean { return !processor.shouldProcessLocals() || processStatements(lastParent) { it.processDeclarations(processor, state, null, place) } } fun PsiScopeProcessor.checkName(name: String, state: ResolveState): Boolean { val expectedName = getName(state) ?: return true return expectedName == name } fun PsiScopeProcessor.getName(state: ResolveState): String? = getHint(NameHint.KEY)?.getName(state) fun shouldProcessDynamicMethods(processor: PsiScopeProcessor): Boolean { return processor.getHint(DynamicMembersHint.KEY)?.shouldProcessMethods() ?: false } fun PsiScopeProcessor.shouldProcessDynamicProperties(): Boolean { return getHint(DynamicMembersHint.KEY)?.shouldProcessProperties() ?: false } fun PsiScopeProcessor.shouldProcessLocals(): Boolean = shouldProcess(GroovyResolveKind.VARIABLE) fun PsiScopeProcessor.shouldProcessFields(): Boolean = shouldProcess(GroovyResolveKind.FIELD) fun PsiScopeProcessor.shouldProcessMethods(): Boolean = shouldProcess(GroovyResolveKind.METHOD) fun PsiScopeProcessor.shouldProcessProperties(): Boolean = shouldProcess(GroovyResolveKind.PROPERTY) fun PsiScopeProcessor.shouldProcessClasses(): Boolean { return ResolveUtil.shouldProcessClasses(getHint(ElementClassHint.KEY)) } fun PsiScopeProcessor.shouldProcessMembers(): Boolean { val hint = getHint(ElementClassHint.KEY) ?: return true return hint.shouldProcess(DeclarationKind.CLASS) || hint.shouldProcess(DeclarationKind.FIELD) || hint.shouldProcess(DeclarationKind.METHOD) } fun PsiScopeProcessor.shouldProcessTypeParameters(): Boolean { if (shouldProcessClasses()) return true val groovyKindHint = getHint(GroovyResolveKind.HINT_KEY) ?: return true return groovyKindHint.shouldProcess(GroovyResolveKind.TYPE_PARAMETER) } private fun PsiScopeProcessor.shouldProcess(kind: GroovyResolveKind): Boolean { val resolveKindHint = getHint(GroovyResolveKind.HINT_KEY) if (resolveKindHint != null) return resolveKindHint.shouldProcess(kind) val elementClassHint = getHint(ElementClassHint.KEY) ?: return true return kind.declarationKinds.any(elementClassHint::shouldProcess) } fun getDefaultConstructor(clazz: PsiClass): PsiMethod { return getCachedValue(clazz) { Result.create(DefaultConstructor(clazz), clazz) } } fun GroovyFileBase.processClassesInFile(processor: PsiScopeProcessor, state: ResolveState): Boolean { if (!processor.shouldProcessClasses()) return true val scriptClass = scriptClass if (scriptClass != null && !ResolveUtil.processElement(processor, scriptClass, state)) return false for (definition in typeDefinitions) { if (!ResolveUtil.processElement(processor, definition, state)) return false } return true } fun GroovyFileBase.processClassesInPackage(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement = this): Boolean { if (!processor.shouldProcessClasses()) return true val aPackage = JavaPsiFacade.getInstance(project).findPackage(packageName) ?: return true return aPackage.processDeclarations(PackageSkippingProcessor(processor), state, null, place) } val PsiScopeProcessor.annotationHint: AnnotationHint? get() = getHint(AnnotationHint.HINT_KEY) fun PsiScopeProcessor.isAnnotationResolve(): Boolean { val hint = annotationHint ?: return false return hint.isAnnotationResolve } fun PsiScopeProcessor.isNonAnnotationResolve(): Boolean { val hint = annotationHint ?: return false return !hint.isAnnotationResolve } fun GrCodeReferenceElement.isAnnotationReference(): Boolean { val (possibleAnnotation, _) = skipSameTypeParents() return possibleAnnotation is GrAnnotation } fun getName(state: ResolveState, element: PsiElement): String? { return state[importedNameKey] ?: element.castSafelyTo<PsiNamedElement>()?.name ?: element.castSafelyTo<GrReferenceElement<*>>()?.referenceName } fun <T : GroovyResolveResult> valid(allCandidates: Collection<T>): List<T> = allCandidates.filter { it.isValidResult } fun singleOrValid(allCandidates: List<GroovyResolveResult>): List<GroovyResolveResult> { return if (allCandidates.size <= 1) allCandidates else valid(allCandidates) } fun getResolveKind(element: PsiElement): GroovyResolveKind? { return when (element) { is PsiClass -> GroovyResolveKind.CLASS is PsiPackage -> GroovyResolveKind.PACKAGE is PsiMethod -> GroovyResolveKind.METHOD is PsiField -> GroovyResolveKind.FIELD is GrBindingVariable -> GroovyResolveKind.BINDING is PsiVariable -> GroovyResolveKind.VARIABLE is GroovyProperty -> GroovyResolveKind.PROPERTY is GrReferenceElement<*> -> GroovyResolveKind.PROPERTY else -> null } } fun GroovyResolveResult?.asJavaClassResult(): PsiClassType.ClassResolveResult { if (this == null) return PsiClassType.ClassResolveResult.EMPTY val clazz = element as? PsiClass ?: return PsiClassType.ClassResolveResult.EMPTY return object : PsiClassType.ClassResolveResult { override fun getElement(): PsiClass? = clazz override fun getSubstitutor(): PsiSubstitutor = [email protected] override fun isPackagePrefixPackageReference(): Boolean = false override fun isAccessible(): Boolean = true override fun isStaticsScopeCorrect(): Boolean = true override fun getCurrentFileResolveScope(): PsiElement? = null override fun isValidResult(): Boolean = true } } fun markAsReferenceResolveTarget(refExpr: GrReferenceElement<*>) { refExpr.putUserData(REFERENCE_RESOLVE_TARGET, Unit) } internal fun isReferenceResolveTarget(refExpr: GrReferenceElement<*>) : Boolean { return refExpr.getUserData(REFERENCE_RESOLVE_TARGET) != null } private val REFERENCE_RESOLVE_TARGET : Key<Unit> = Key.create("Reference resolve target")
apache-2.0
76a8fbe80c5ce8deecc6704b42728f7f
42.397959
144
0.799788
4.650629
false
false
false
false
tomatrocho/insapp-material
app/src/main/java/fr/insapp/insapp/fragments/NotificationsFragment.kt
2
3270
package fr.insapp.insapp.fragments import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import com.bumptech.glide.Glide import com.google.android.material.snackbar.Snackbar import fr.insapp.insapp.R import fr.insapp.insapp.adapters.NotificationRecyclerViewAdapter import fr.insapp.insapp.http.ServiceGenerator import fr.insapp.insapp.models.Notifications import fr.insapp.insapp.utility.Utils import kotlinx.android.synthetic.main.fragment_notifications.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response /** * Created by thomas on 27/10/2016. */ class NotificationsFragment : Fragment() { private lateinit var adapter: NotificationRecyclerViewAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) this.adapter = NotificationRecyclerViewAdapter(mutableListOf(), Glide.with(this)) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { generateNotifications() return inflater.inflate(R.layout.fragment_notifications, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) recyclerview_notifications.setHasFixedSize(true) recyclerview_notifications.isNestedScrollingEnabled = false recyclerview_notifications.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) recyclerview_notifications.adapter = adapter } private fun generateNotifications() { no_network?.visibility = View.GONE val user = Utils.user if (user != null) { val call = ServiceGenerator.client.getNotificationsForUser(user.id) call.enqueue(object : Callback<Notifications> { override fun onResponse(call: Call<Notifications>, response: Response<Notifications>) { val results = response.body() if (response.isSuccessful && results?.notifications != null) { for (notification in results.notifications) { adapter.addItem(notification) } } else if (recyclerview_notifications != null) { Snackbar.make(recyclerview_notifications, R.string.connectivity_issue, Snackbar.LENGTH_LONG).show() } } override fun onFailure(call: Call<Notifications>, t: Throwable) { if (adapter.itemCount == 0) { no_network?.visibility = View.VISIBLE } else if (recyclerview_notifications != null) { Snackbar.make(recyclerview_notifications, R.string.connectivity_issue, Snackbar.LENGTH_LONG).show() } } }) } else { Log.d(TAG, "Couldn't fetch notifications: user is null") } } companion object { const val TAG = "NotificationsFragment" } }
mit
af098647a54e5e94e60e2dfb28e53011
37.034884
123
0.669113
5.18225
false
false
false
false
ThiagoGarciaAlves/intellij-community
platform/configuration-store-impl/src/SchemeManagerImpl.kt
2
31370
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.concurrency.ConcurrentCollectionFactory import com.intellij.configurationStore.schemeManager.* import com.intellij.openapi.application.ex.DecodeDefaultsUtil import com.intellij.openapi.application.runUndoTransparentWriteAction import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil.DEFAULT_EXT import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.extensions.AbstractExtensionPointBean import com.intellij.openapi.options.NonLazySchemeProcessor import com.intellij.openapi.options.SchemeProcessor import com.intellij.openapi.options.SchemeState import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.util.Condition import com.intellij.openapi.util.WriteExternalException import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.text.StringUtilRt import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.SafeWriteRequestor import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.newvfs.BulkFileListener import com.intellij.openapi.vfs.newvfs.NewVirtualFile import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.util.* import com.intellij.util.containers.ConcurrentList import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.catch import com.intellij.util.io.* import com.intellij.util.messages.MessageBus import com.intellij.util.text.UniqueNameGenerator import gnu.trove.THashSet import org.jdom.Document import org.jdom.Element import org.xmlpull.v1.XmlPullParser import java.io.File import java.io.IOException import java.io.InputStream import java.nio.file.Path import java.util.* import java.util.concurrent.atomic.AtomicBoolean import java.util.function.Function class SchemeManagerImpl<T : Any, in MUTABLE_SCHEME : T>(val fileSpec: String, processor: SchemeProcessor<T, MUTABLE_SCHEME>, private val provider: StreamProvider?, private val ioDirectory: Path, val roamingType: RoamingType = RoamingType.DEFAULT, val presentableName: String? = null, private val schemeNameToFileName: SchemeNameToFileName = CURRENT_NAME_CONVERTER, private val messageBus: MessageBus? = null) : SchemeManagerBase<T, MUTABLE_SCHEME>(processor), SafeWriteRequestor { private val isOldSchemeNaming = schemeNameToFileName == OLD_NAME_CONVERTER private val isLoadingSchemes = AtomicBoolean() private val schemeListManager = SchemeListManager(this) private val schemes: ConcurrentList<T> get() = schemeListManager.schemes private var cachedVirtualDirectory: VirtualFile? = null private val schemeExtension: String private val updateExtension: Boolean internal val filesToDelete = ContainerUtil.newConcurrentSet<String>() // scheme could be changed - so, hashcode will be changed - we must use identity hashing strategy internal val schemeToInfo = ConcurrentCollectionFactory.createMap<T, ExternalInfo>(ContainerUtil.identityStrategy()) private val useVfs = messageBus != null init { if (processor is SchemeExtensionProvider) { schemeExtension = processor.schemeExtension updateExtension = true } else { schemeExtension = FileStorageCoreUtil.DEFAULT_EXT updateExtension = false } if (useVfs && (provider == null || !provider.isApplicable(fileSpec, roamingType))) { LOG.runAndLogException { refreshVirtualDirectoryAndAddListener() } } } override val rootDirectory: File get() = ioDirectory.toFile() override val allSchemeNames: Collection<String> get() = schemes.let { if (it.isEmpty()) emptyList() else it.map { processor.getSchemeKey(it) } } override val allSchemes: List<T> get() = Collections.unmodifiableList(schemes) override val isEmpty: Boolean get() = schemes.isEmpty() private inner class SchemeFileTracker : BulkFileListener { private fun isMy(file: VirtualFile) = canRead(file.nameSequence) private fun isMyDirectory(parent: VirtualFile) = cachedVirtualDirectory.let { if (it == null) ioDirectory.systemIndependentPath == parent.path else it == parent } override fun after(events: MutableList<out VFileEvent>) { eventLoop@ for (event in events) { if (event.requestor is SchemeManagerImpl<*, *>) { continue } when (event) { is VFileContentChangeEvent -> { val fileName = event.file.name if (!canRead(fileName) || !isMyDirectory(event.file.parent)) { continue@eventLoop } val oldCurrentScheme = activeScheme val changedScheme = findExternalizableSchemeByFileName(fileName) if (callSchemeContentChangedIfSupported(changedScheme, fileName, event.file)) { continue@eventLoop } changedScheme?.let { removeScheme(it) processor.onSchemeDeleted(it) } updateCurrentScheme(oldCurrentScheme, readSchemeFromFile(event.file, schemes)?.let { processor.initScheme(it) processor.onSchemeAdded(it) it }) } is VFileCreateEvent -> { if (canRead(event.childName)) { if (isMyDirectory(event.parent)) { event.file?.let { schemeCreatedExternally(it) } } } else if (event.file?.isDirectory == true) { val dir = virtualDirectory if (event.file == dir) { for (file in dir!!.children) { if (isMy(file)) { schemeCreatedExternally(file) } } } } } is VFileDeleteEvent -> { val oldCurrentScheme = activeScheme if (event.file.isDirectory) { val dir = virtualDirectory if (event.file == dir) { cachedVirtualDirectory = null removeExternalizableSchemes() } } else if (isMy(event.file) && isMyDirectory(event.file.parent)) { val scheme = findExternalizableSchemeByFileName(event.file.name) ?: continue@eventLoop removeScheme(scheme) processor.onSchemeDeleted(scheme) } updateCurrentScheme(oldCurrentScheme) } } } } private fun callSchemeContentChangedIfSupported(changedScheme: MUTABLE_SCHEME?, fileName: String, file: VirtualFile): Boolean { if (changedScheme == null || processor !is SchemeContentChangedHandler<*> || processor !is LazySchemeProcessor) { return false } // unrealistic case, but who knows val externalInfo = schemeToInfo.get(changedScheme) ?: return false catchAndLog(fileName) { val bytes = file.contentsToByteArray() lazyPreloadScheme(bytes, isOldSchemeNaming) { name, parser -> val attributeProvider = Function<String, String?> { parser.getAttributeValue(null, it) } val schemeName = name ?: processor.getSchemeKey(attributeProvider, FileUtilRt.getNameWithoutExtension(fileName)) ?: throw RuntimeException("Name is missed:\n${bytes.toString(Charsets.UTF_8)}") val dataHolder = SchemeDataHolderImpl(bytes, externalInfo) @Suppress("UNCHECKED_CAST") (processor as SchemeContentChangedHandler<MUTABLE_SCHEME>).schemeContentChanged(changedScheme, schemeName, dataHolder) } return true } return false } private fun schemeCreatedExternally(file: VirtualFile) { val newSchemes = SmartList<T>() val readScheme = readSchemeFromFile(file, newSchemes) if (readScheme != null) { val readSchemeKey = processor.getSchemeKey(readScheme) val existingScheme = findSchemeByName(readSchemeKey) @Suppress("SuspiciousEqualsCombination") if (existingScheme != null && schemeListManager.readOnlyExternalizableSchemes.get(processor.getSchemeKey(existingScheme)) !== existingScheme) { LOG.warn("Ignore incorrect VFS create scheme event: schema ${readSchemeKey} is already exists") return } schemes.addAll(newSchemes) processor.initScheme(readScheme) processor.onSchemeAdded(readScheme) } } private fun updateCurrentScheme(oldScheme: T?, newScheme: T? = null) { if (activeScheme != null) { return } if (oldScheme != activeScheme) { val scheme = newScheme ?: schemes.firstOrNull() currentPendingSchemeName = null activeScheme = scheme // must be equals by reference if (oldScheme !== scheme) { processor.onCurrentSchemeSwitched(oldScheme, scheme) } } else if (newScheme != null) { processPendingCurrentSchemeName(newScheme) } } } private fun refreshVirtualDirectoryAndAddListener() { // store refreshes root directory, so, we don't need to use refreshAndFindFile val directory = LocalFileSystem.getInstance().findFileByPath(ioDirectory.systemIndependentPath) ?: return this.cachedVirtualDirectory = directory directory.children if (directory is NewVirtualFile) { directory.markDirty() } directory.refresh(true, false) } override fun loadBundledScheme(resourceName: String, requestor: Any) { try { val url = if (requestor is AbstractExtensionPointBean) requestor.loaderForClass.getResource(resourceName) else DecodeDefaultsUtil.getDefaults(requestor, resourceName) if (url == null) { LOG.error("Cannot read scheme from $resourceName") return } val bytes = URLUtil.openStream(url).readBytes() lazyPreloadScheme(bytes, isOldSchemeNaming) { name, parser -> val attributeProvider = Function<String, String?> { parser.getAttributeValue(null, it) } val fileName = PathUtilRt.getFileName(url.path) val extension = getFileExtension(fileName, true) val externalInfo = ExternalInfo(fileName.substring(0, fileName.length - extension.length), extension) val schemeKey = name ?: (processor as LazySchemeProcessor).getSchemeKey(attributeProvider, externalInfo.fileNameWithoutExtension) ?: throw RuntimeException("Name is missed:\n${bytes.toString(Charsets.UTF_8)}") externalInfo.schemeKey = schemeKey val scheme = (processor as LazySchemeProcessor).createScheme(SchemeDataHolderImpl(bytes, externalInfo), schemeKey, attributeProvider, true) val oldInfo = schemeToInfo.put(scheme, externalInfo) LOG.assertTrue(oldInfo == null) val oldScheme = schemeListManager.readOnlyExternalizableSchemes.put(schemeKey, scheme) if (oldScheme != null) { LOG.warn("Duplicated scheme ${schemeKey} - old: $oldScheme, new $scheme") } schemes.add(scheme) } } catch (e: ProcessCanceledException) { throw e } catch (e: Throwable) { LOG.error("Cannot read scheme from $resourceName", e) } } private fun getFileExtension(fileName: CharSequence, allowAny: Boolean): String { return when { StringUtilRt.endsWithIgnoreCase(fileName, schemeExtension) -> schemeExtension StringUtilRt.endsWithIgnoreCase(fileName, DEFAULT_EXT) -> DEFAULT_EXT allowAny -> PathUtil.getFileExtension(fileName.toString())!! else -> throw IllegalStateException("Scheme file extension $fileName is unknown, must be filtered out") } } override fun loadSchemes(): Collection<T> { if (!isLoadingSchemes.compareAndSet(false, true)) { throw IllegalStateException("loadSchemes is already called") } try { val filesToDelete = THashSet<String>() val oldSchemes = schemes val schemes = oldSchemes.toMutableList() val newSchemesOffset = schemes.size if (provider != null && provider.processChildren(fileSpec, roamingType, { canRead(it) }) { name, input, readOnly -> catchAndLog(name) { val scheme = loadScheme(name, input, schemes, filesToDelete) if (readOnly && scheme != null) { schemeListManager.readOnlyExternalizableSchemes.put(processor.getSchemeKey(scheme), scheme) } } true }) { } else { ioDirectory.directoryStreamIfExists({ canRead(it.fileName.toString()) }) { for (file in it) { if (file.isDirectory()) { continue } catchAndLog(file.fileName.toString()) { filename -> file.inputStream().use { loadScheme(filename, it, schemes, filesToDelete) } } } } } this.filesToDelete.addAll(filesToDelete) schemeListManager.replaceSchemeList(oldSchemes, schemes) @Suppress("UNCHECKED_CAST") for (i in newSchemesOffset until schemes.size) { val scheme = schemes.get(i) as MUTABLE_SCHEME processor.initScheme(scheme) @Suppress("UNCHECKED_CAST") processPendingCurrentSchemeName(scheme) } messageBus?.connect()?.subscribe(VirtualFileManager.VFS_CHANGES, SchemeFileTracker()) return schemes.subList(newSchemesOffset, schemes.size) } finally { isLoadingSchemes.set(false) } } override fun reload() { processor.beforeReloaded(this) // we must not remove non-persistent (e.g. predefined) schemes, because we cannot load it (obviously) removeExternalizableSchemes() processor.reloaded(this, loadSchemes()) } private fun removeExternalizableSchemes() { // todo check is bundled/read-only schemes correctly handled val iterator = schemes.iterator() for (scheme in iterator) { if ((scheme as? SerializableScheme)?.schemeState ?: processor.getState(scheme) == SchemeState.NON_PERSISTENT) { continue } activeScheme?.let { if (scheme === it) { currentPendingSchemeName = processor.getSchemeKey(it) activeScheme = null } } iterator.remove() @Suppress("UNCHECKED_CAST") processor.onSchemeDeleted(scheme as MUTABLE_SCHEME) } retainExternalInfo() } @Suppress("UNCHECKED_CAST") private fun findExternalizableSchemeByFileName(fileName: String) = schemes.firstOrNull { fileName == "${it.fileName}$schemeExtension" } as MUTABLE_SCHEME? private fun isOverwriteOnLoad(existingScheme: T): Boolean { val info = schemeToInfo.get(existingScheme) // scheme from file with old extension, so, we must ignore it return info != null && schemeExtension != info.fileExtension } private inner class SchemeDataHolderImpl(private val bytes: ByteArray, private val externalInfo: ExternalInfo) : SchemeDataHolder<MUTABLE_SCHEME> { override fun read(): Element = loadElement(bytes.inputStream()) override fun updateDigest(scheme: MUTABLE_SCHEME) { try { updateDigest(processor.writeScheme(scheme) as Element) } catch (e: WriteExternalException) { LOG.error("Cannot update digest", e) } } override fun updateDigest(data: Element) { externalInfo.digest = data.digest() } } private fun loadScheme(fileName: String, input: InputStream, schemes: MutableList<T>, filesToDelete: MutableSet<String>? = null): MUTABLE_SCHEME? { val extension = getFileExtension(fileName, false) if (filesToDelete != null && filesToDelete.contains(fileName)) { LOG.warn("Scheme file \"$fileName\" is not loaded because marked to delete") return null } val fileNameWithoutExtension = fileName.substring(0, fileName.length - extension.length) fun checkExisting(schemeName: String): Boolean { if (filesToDelete == null) { return true } schemes.firstOrNull({ processor.getSchemeKey(it) == schemeName})?.let { existingScheme -> if (schemeListManager.readOnlyExternalizableSchemes.get(processor.getSchemeKey(existingScheme)) === existingScheme) { // so, bundled scheme is shadowed schemeListManager.removeFirstScheme(schemes, scheduleDelete = false) { it === existingScheme } return true } else if (processor.isExternalizable(existingScheme) && isOverwriteOnLoad(existingScheme)) { schemeListManager.removeFirstScheme(schemes) { it === existingScheme } } else { if (schemeExtension != extension && schemeToInfo.get(existingScheme)?.fileNameWithoutExtension == fileNameWithoutExtension) { // 1.oldExt is loading after 1.newExt - we should delete 1.oldExt filesToDelete.add(fileName) } else { // We don't load scheme with duplicated name - if we generate unique name for it, it will be saved then with new name. // It is not what all can expect. Such situation in most cases indicates error on previous level, so, we just warn about it. LOG.warn("Scheme file \"$fileName\" is not loaded because defines duplicated name \"$schemeName\"") } return false } } return true } fun createInfo(schemeName: String, element: Element?): ExternalInfo { val info = ExternalInfo(fileNameWithoutExtension, extension) element?.let { info.digest = it.digest() } info.schemeKey = schemeName return info } val duringLoad = filesToDelete != null var scheme: MUTABLE_SCHEME? = null if (processor is LazySchemeProcessor) { val bytes = input.readBytes() lazyPreloadScheme(bytes, isOldSchemeNaming) { name, parser -> val attributeProvider = Function<String, String?> { if (parser.eventType == XmlPullParser.START_TAG) { parser.getAttributeValue(null, it) } else { null } } val schemeName = name ?: processor.getSchemeKey(attributeProvider, fileNameWithoutExtension) if (schemeName == null) { throw RuntimeException("Name is missed:\n${bytes.toString(Charsets.UTF_8)}") } if (!checkExisting(schemeName)) { return null } val externalInfo = createInfo(schemeName, null) scheme = processor.createScheme(SchemeDataHolderImpl(bytes, externalInfo), schemeName, attributeProvider) schemeToInfo.put(scheme, externalInfo) this.filesToDelete.remove(fileName) } } else { val element = loadElement(input) scheme = (processor as NonLazySchemeProcessor).readScheme(element, duringLoad) ?: return null val schemeKey = processor.getSchemeKey(scheme!!) if (!checkExisting(schemeKey)) { return null } schemeToInfo.put(scheme, createInfo(schemeKey, element)) this.filesToDelete.remove(fileName) } if (schemes === this.schemes) { @Suppress("UNCHECKED_CAST") addScheme(scheme as T, true) } else { @Suppress("UNCHECKED_CAST") schemes.add(scheme as T) } return scheme } private val T.fileName: String? get() = schemeToInfo.get(this)?.fileNameWithoutExtension fun canRead(name: CharSequence) = (updateExtension && name.endsWith(DEFAULT_EXT, true) || name.endsWith(schemeExtension, ignoreCase = true)) && (processor !is LazySchemeProcessor || processor.isSchemeFile(name)) private fun readSchemeFromFile(file: VirtualFile, schemes: MutableList<T>): MUTABLE_SCHEME? { val fileName = file.name if (file.isDirectory || !canRead(fileName)) { return null } catchAndLog(fileName) { return file.inputStream.use { loadScheme(fileName, it, schemes) } } return null } override fun save(errors: MutableList<Throwable>) { if (isLoadingSchemes.get()) { LOG.warn("Skip save - schemes are loading") } var hasSchemes = false val nameGenerator = UniqueNameGenerator() val changedSchemes = SmartList<MUTABLE_SCHEME>() for (scheme in schemes) { val state = (scheme as? SerializableScheme)?.schemeState ?: processor.getState(scheme) if (state == SchemeState.NON_PERSISTENT) { continue } hasSchemes = true if (state != SchemeState.UNCHANGED) { @Suppress("UNCHECKED_CAST") changedSchemes.add(scheme as MUTABLE_SCHEME) } val fileName = scheme.fileName if (fileName != null && !isRenamed(scheme)) { nameGenerator.addExistingName(fileName) } } for (scheme in changedSchemes) { try { saveScheme(scheme, nameGenerator) } catch (e: Throwable) { errors.add(RuntimeException("Cannot save scheme $fileSpec/$scheme", e)) } } val filesToDelete = THashSet(filesToDelete) if (!filesToDelete.isEmpty) { this.filesToDelete.removeAll(filesToDelete) deleteFiles(errors, filesToDelete) // remove empty directory only if some file was deleted - avoid check on each save if (!hasSchemes && (provider == null || !provider.isApplicable(fileSpec, roamingType))) { removeDirectoryIfEmpty(errors) } } } private fun removeDirectoryIfEmpty(errors: MutableList<Throwable>) { ioDirectory.directoryStreamIfExists { for (file in it) { if (!file.isHidden()) { LOG.info("Directory ${ioDirectory.fileName} is not deleted: at least one file ${file.fileName} exists") return@removeDirectoryIfEmpty } } } LOG.info("Remove schemes directory ${ioDirectory.fileName}") cachedVirtualDirectory = null var deleteUsingIo = !useVfs if (!deleteUsingIo) { virtualDirectory?.let { runUndoTransparentWriteAction { try { it.delete(this) } catch (e: IOException) { deleteUsingIo = true errors.add(e) } } } } if (deleteUsingIo) { errors.catch { ioDirectory.delete() } } } private fun saveScheme(scheme: MUTABLE_SCHEME, nameGenerator: UniqueNameGenerator) { var externalInfo: ExternalInfo? = schemeToInfo.get(scheme) val currentFileNameWithoutExtension = externalInfo?.fileNameWithoutExtension val parent = processor.writeScheme(scheme) val element = parent as? Element ?: (parent as Document).detachRootElement() if (element.isEmpty()) { externalInfo?.scheduleDelete() return } var fileNameWithoutExtension = currentFileNameWithoutExtension if (fileNameWithoutExtension == null || isRenamed(scheme)) { fileNameWithoutExtension = nameGenerator.generateUniqueName(schemeNameToFileName.schemeNameToFileName(processor.getSchemeKey(scheme))) } val newDigest = element!!.digest() when { externalInfo != null && currentFileNameWithoutExtension === fileNameWithoutExtension && externalInfo.isDigestEquals(newDigest) -> return isEqualToBundledScheme(externalInfo, newDigest, scheme) -> return // we must check it only here to avoid delete old scheme just because it is empty (old idea save -> new idea delete on open) processor is LazySchemeProcessor && processor.isSchemeDefault(scheme, newDigest) -> { externalInfo?.scheduleDelete() return } } val fileName = fileNameWithoutExtension!! + schemeExtension // file will be overwritten, so, we don't need to delete it filesToDelete.remove(fileName) // stream provider always use LF separator val byteOut = element.toBufferExposingByteArray() var providerPath: String? if (provider != null && provider.enabled) { providerPath = "$fileSpec/$fileName" if (!provider.isApplicable(providerPath, roamingType)) { providerPath = null } } else { providerPath = null } // if another new scheme uses old name of this scheme, we must not delete it (as part of rename operation) @Suppress("SuspiciousEqualsCombination") val renamed = externalInfo != null && fileNameWithoutExtension !== currentFileNameWithoutExtension && currentFileNameWithoutExtension != null && nameGenerator.isUnique(currentFileNameWithoutExtension) if (providerPath == null) { if (useVfs) { var file: VirtualFile? = null var dir = virtualDirectory if (dir == null || !dir.isValid) { dir = createDir(ioDirectory, this) cachedVirtualDirectory = dir } if (renamed) { val oldFile = dir.findChild(externalInfo!!.fileName) if (oldFile != null) { // VFS doesn't allow to rename to existing file, so, check it if (dir.findChild(fileName) == null) { runUndoTransparentWriteAction { oldFile.rename(this, fileName) } file = oldFile } else { externalInfo.scheduleDelete() } } } if (file == null) { file = dir.getOrCreateChild(fileName, this) } runUndoTransparentWriteAction { file!!.getOutputStream(this).use { byteOut.writeTo(it) } } } else { if (renamed) { externalInfo!!.scheduleDelete() } ioDirectory.resolve(fileName).write(byteOut.internalBuffer, 0, byteOut.size()) } } else { if (renamed) { externalInfo!!.scheduleDelete() } provider!!.write(providerPath, byteOut.internalBuffer, byteOut.size(), roamingType) } if (externalInfo == null) { externalInfo = ExternalInfo(fileNameWithoutExtension, schemeExtension) schemeToInfo.put(scheme, externalInfo) } else { externalInfo.setFileNameWithoutExtension(fileNameWithoutExtension, schemeExtension) } externalInfo.digest = newDigest externalInfo.schemeKey = processor.getSchemeKey(scheme) } private fun isEqualToBundledScheme(externalInfo: ExternalInfo?, newDigest: ByteArray, scheme: MUTABLE_SCHEME): Boolean { fun serializeIfPossible(scheme: T): Element? { LOG.runAndLogException { @Suppress("UNCHECKED_CAST") val bundledAsMutable = scheme as? MUTABLE_SCHEME ?: return null return processor.writeScheme(bundledAsMutable) as Element } return null } val bundledScheme = schemeListManager.readOnlyExternalizableSchemes.get(processor.getSchemeKey(scheme)) if (bundledScheme == null) { if ((processor as? LazySchemeProcessor)?.isSchemeEqualToBundled(scheme) == true) { externalInfo?.scheduleDelete() return true } return false } val bundledExternalInfo = schemeToInfo.get(bundledScheme) ?: return false if (bundledExternalInfo.digest == null) { serializeIfPossible(bundledScheme)?.let { bundledExternalInfo.digest = it.digest() } ?: return false } if (bundledExternalInfo.isDigestEquals(newDigest)) { externalInfo?.scheduleDelete() return true } return false } private fun ExternalInfo.scheduleDelete() { filesToDelete.add(fileName) } internal fun scheduleDelete(info: ExternalInfo) { info.scheduleDelete() } private fun isRenamed(scheme: T): Boolean { val info = schemeToInfo.get(scheme) return info != null && processor.getSchemeKey(scheme) != info.schemeKey } private fun deleteFiles(errors: MutableList<Throwable>, filesToDelete: MutableSet<String>) { if (provider != null) { val iterator = filesToDelete.iterator() for (name in iterator) { errors.catch { val spec = "$fileSpec/$name" if (provider.delete(spec, roamingType)) { iterator.remove() } } } } if (filesToDelete.isEmpty()) { return } if (useVfs) { virtualDirectory?.let { val childrenToDelete = it.children.filter { filesToDelete.contains(it.name) } if (childrenToDelete.isNotEmpty()) { runUndoTransparentWriteAction { childrenToDelete.forEach { file -> errors.catch { file.delete(this) } } } } return } } for (name in filesToDelete) { errors.catch { ioDirectory.resolve(name).delete() } } } private val virtualDirectory: VirtualFile? get() { var result = cachedVirtualDirectory if (result == null) { result = LocalFileSystem.getInstance().findFileByPath(ioDirectory.systemIndependentPath) cachedVirtualDirectory = result } return result } override fun setSchemes(newSchemes: List<T>, newCurrentScheme: T?, removeCondition: Condition<T>?) = schemeListManager.setSchemes(newSchemes, newCurrentScheme, removeCondition) internal fun retainExternalInfo() { if (schemeToInfo.isEmpty()) { return } val iterator = schemeToInfo.entries.iterator() l@ for ((scheme, info) in iterator) { if (schemeListManager.readOnlyExternalizableSchemes.get(processor.getSchemeKey(scheme)) == scheme) { continue } for (s in schemes) { if (s === scheme) { filesToDelete.remove(info.fileName) continue@l } } iterator.remove() info.scheduleDelete() } } override fun addScheme(scheme: T, replaceExisting: Boolean) = schemeListManager.addScheme(scheme, replaceExisting) override fun findSchemeByName(schemeName: String) = schemes.firstOrNull { processor.getSchemeKey(it) == schemeName } override fun removeScheme(name: String) = schemeListManager.removeFirstScheme(schemes) {processor.getSchemeKey(it) == name } override fun removeScheme(scheme: T) = schemeListManager.removeFirstScheme(schemes) { it == scheme } != null override fun isMetadataEditable(scheme: T) = !schemeListManager.readOnlyExternalizableSchemes.containsKey(processor.getSchemeKey(scheme)) override fun toString() = fileSpec }
apache-2.0
17005df321b7a6817cb221a1270591b6
35.477907
213
0.662958
5.045031
false
false
false
false
twbarber/cash-register
cash-register-public/src/main/kotlin/com/twbarber/register/public/cli/CashRegisterCliRunner.kt
1
1872
package com.twbarber.register.public.cli import com.twbarber.register.public.CashRegister import com.twbarber.register.public.data.Balance import java.util.* class CashRegisterCliRunner { val READY = "ready" val SHOW_REGEX = "show" val TAKE_REGEX = "take (\\d+ ){4}\\d+" val PUT_REGEX = "put (\\d+ ){4}\\d+" val CHANGE_REGEX = "change \\d+" val QUIT_REGEX = "quit" private val register = CashRegister() private val input = Scanner(System.`in`) companion object { @JvmStatic fun main(args: Array<String>) { CashRegisterCliRunner().run() } } fun run() { System.out.println(READY) while (true) { try { val input = input.nextLine().toLowerCase() if (input.matches(Regex(SHOW_REGEX))) print(register.show()) else if (input.matches(Regex(TAKE_REGEX))) print(register.take(parseTransaction(input)).show()) else if (input.matches(Regex(PUT_REGEX))) print(register.put(parseTransaction(input)).show()) else if (input.matches(Regex(CHANGE_REGEX))) print(register.change(parseChange(input))) else if (input.matches(Regex(QUIT_REGEX))) { print("Bye") System.exit(0) } else (print("Unsupported Operation.")) } catch (e : Exception) { print(e.message + "\n") } } } fun parseTransaction(input : String): Balance { val bills = input.split(" ") return Balance(bills[1].toInt(), bills[2].toInt(), bills[3].toInt(), bills[4].toInt(), bills[5].toInt()) } fun parseChange(input : String): Int { return input.split(" ")[1].toInt() } fun print(output : String) { System.out.println(output) } }
mit
ce40042550d1a244ff07b590be423e29
31.275862
111
0.559295
3.957717
false
false
false
false
dreampany/framework
frame/src/main/kotlin/com/dreampany/framework/ui/fragment/BaseStateFragment.kt
1
3870
package com.dreampany.framework.ui.fragment import android.os.Bundle import androidx.viewpager.widget.ViewPager import com.google.android.material.tabs.TabLayout import com.dreampany.framework.R import com.dreampany.framework.data.model.Task import com.dreampany.framework.misc.Constants import com.dreampany.framework.ui.adapter.SmartPagerAdapter import com.dreampany.framework.util.ColorUtil import timber.log.Timber /** * Created by Hawladar Roman on 5/25/2018. * BJIT Group * [email protected] */ abstract class BaseStateFragment<T : BaseFragment> : BaseMenuFragment() { private var adapter: SmartPagerAdapter<T>? = null protected abstract fun pageTitles(): Array<String> protected abstract fun pageClasses(): Array<Class<T>> protected abstract fun pageTasks(): Array<Task<*>>? override fun getLayoutId(): Int { return R.layout.fragment_tabpager } open fun getViewPagerId(): Int { return R.id.view_pager } open fun getTabLayoutId(): Int { return R.id.tab_layout } open fun hasAllPages(): Boolean { return false } open fun hasTabColor(): Boolean { return false } override fun onActivityCreated(savedInstanceState: Bundle?) { fireOnStartUi = false super.onActivityCreated(savedInstanceState) initPager() onStartUi(savedInstanceState) getApp()?.throwAnalytics(Constants.Event.FRAGMENT, getScreen()) } override fun getCurrentFragment(): BaseFragment? { val viewPager = findViewById<ViewPager>(getViewPagerId()) if (viewPager != null && adapter != null) { val fragment = adapter?.getFragment(viewPager.getCurrentItem()) if (fragment != null) { return fragment.getCurrentFragment() } } return null } fun getFragments(): List<BaseFragment>? { return adapter?.currentFragments } internal fun initPager() { val pageTitles = pageTitles() val pageClasses = pageClasses() val pageTasks = pageTasks() val viewPager = findViewById<ViewPager>(getViewPagerId()) val tabLayout = findViewById<TabLayout>(getTabLayoutId()) if (pageTitles.isEmpty() || pageClasses.isEmpty() || viewPager == null || tabLayout == null) { return } if (hasTabColor()) { if (hasColor() && applyColor()) { tabLayout.setBackgroundColor( ColorUtil.getColor( context!!, color!!.primaryId ) ) tabLayout.setSelectedTabIndicatorColor( ColorUtil.getColor(context!!, R.color.material_white) ) tabLayout.setTabTextColors( ColorUtil.getColor(context!!, R.color.material_grey200), ColorUtil.getColor(context!!, R.color.material_white) ) } } //if (adapter == null) { adapter = SmartPagerAdapter<T>(childFragmentManager) //} viewPager.setAdapter(adapter) tabLayout.setupWithViewPager(viewPager) //fragmentAdapter.removeAll(); if (hasAllPages()) { Timber.v("Pages %d", pageClasses.size) viewPager.setOffscreenPageLimit(pageClasses.size) } else { //viewPager.setOffscreenPageLimit(pageClasses.length); } val pagerRunnable = { for (index in pageClasses.indices) { var task: Task<*>? = null pageTasks?.let { task = it[index] } adapter?.addPage(pageTitles[index], pageClasses[index], task) } } ex.postToUi(Runnable{pagerRunnable}) } }
apache-2.0
a0313c615163999cf955d765bc3c5f76
28.549618
102
0.599742
4.929936
false
false
false
false
gallonyin/clockoff
app/src/main/java/org/caworks/clockoff/activity/MainActivity.kt
1
1693
package org.caworks.clockoff.activity import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentPagerAdapter import android.support.v4.view.ViewPager import android.view.Menu import org.caworks.library.base.BaseFragment import org.caworks.clockoff.Base.MineFragment import org.caworks.clockoff.R import org.caworks.library.base.BaseActivity import java.util.ArrayList class MainActivity : BaseActivity() { val fragments = ArrayList<BaseFragment>() companion object { /** * 进入 MainActivity 的入口 */ fun enterActivity(context: Context) { val intent = Intent(context, MainActivity::class.java) context.startActivity(intent) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initView() } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_main, menu) return true } private fun initView() { // val toolbar = findViewById(R.id.toolbar) as Toolbar // setSupportActionBar(toolbar) fragments.add(MineFragment()) val vp_container = findViewById(R.id.vp_container) as ViewPager vp_container.adapter = object: FragmentPagerAdapter(supportFragmentManager) { override fun getItem(position: Int): Fragment { return fragments[position] } override fun getCount(): Int { return fragments.size } } } }
apache-2.0
b2d1f8c7dd6b591297eda378f94ee8ee
28.526316
85
0.673203
4.428947
false
false
false
false
chiken88/passnotes
app/src/main/kotlin/com/ivanovsky/passnotes/presentation/note/NoteViewModel.kt
1
7232
package com.ivanovsky.passnotes.presentation.note import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.github.terrakok.cicerone.Router import com.ivanovsky.passnotes.R import com.ivanovsky.passnotes.data.ObserverBus import com.ivanovsky.passnotes.data.entity.Note import com.ivanovsky.passnotes.domain.LocaleProvider import com.ivanovsky.passnotes.domain.ResourceProvider import com.ivanovsky.passnotes.domain.entity.DatabaseStatus import com.ivanovsky.passnotes.domain.entity.PropertyFilter import com.ivanovsky.passnotes.domain.interactor.ErrorInteractor import com.ivanovsky.passnotes.domain.interactor.note.NoteInteractor import com.ivanovsky.passnotes.presentation.Screens import com.ivanovsky.passnotes.presentation.Screens.MainSettingsScreen import com.ivanovsky.passnotes.presentation.Screens.NoteEditorScreen import com.ivanovsky.passnotes.presentation.Screens.SearchScreen import com.ivanovsky.passnotes.presentation.Screens.UnlockScreen import com.ivanovsky.passnotes.presentation.core.BaseScreenViewModel import com.ivanovsky.passnotes.presentation.core.DefaultScreenStateHandler import com.ivanovsky.passnotes.presentation.core.ScreenState import com.ivanovsky.passnotes.presentation.core.ViewModelTypes import com.ivanovsky.passnotes.presentation.core.event.SingleLiveEvent import com.ivanovsky.passnotes.presentation.core.factory.DatabaseStatusCellModelFactory import com.ivanovsky.passnotes.presentation.core.viewmodel.DatabaseStatusCellViewModel import com.ivanovsky.passnotes.presentation.core.viewmodel.NotePropertyCellViewModel import com.ivanovsky.passnotes.presentation.note.factory.NoteCellModelFactory import com.ivanovsky.passnotes.presentation.note.factory.NoteCellViewModelFactory import com.ivanovsky.passnotes.presentation.note_editor.LaunchMode import com.ivanovsky.passnotes.presentation.note_editor.NoteEditorArgs import com.ivanovsky.passnotes.util.StringUtils.EMPTY import com.ivanovsky.passnotes.util.formatAccordingLocale import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.util.* class NoteViewModel( private val interactor: NoteInteractor, private val errorInteractor: ErrorInteractor, private val resourceProvider: ResourceProvider, private val localeProvider: LocaleProvider, private val observerBus: ObserverBus, private val cellModelFactory: NoteCellModelFactory, private val cellViewModelFactory: NoteCellViewModelFactory, private val router: Router, private val statusCellModelFactory: DatabaseStatusCellModelFactory ) : BaseScreenViewModel(), ObserverBus.NoteContentObserver, ObserverBus.DatabaseStatusObserver { val viewTypes = ViewModelTypes() .add(NotePropertyCellViewModel::class, R.layout.cell_note_property) val screenStateHandler = DefaultScreenStateHandler() val screenState = MutableLiveData(ScreenState.notInitialized()) val actionBarTitle = MutableLiveData<String>() val modifiedText = MutableLiveData<String>() val showSnackbarMessageEvent = SingleLiveEvent<String>() val isMenuVisible = MutableLiveData(false) val statusViewModel = MutableLiveData( cellViewModelFactory.createCellViewModel( model = statusCellModelFactory.createDefaultStatusCellModel(), eventProvider = eventProvider ) as DatabaseStatusCellViewModel ) private var note: Note? = null private var noteUid: UUID? = null init { observerBus.register(this) subscribeToCellEvents() } override fun onDatabaseStatusChanged(status: DatabaseStatus) { updateStatusViewModel(status) } override fun onCleared() { super.onCleared() observerBus.unregister(this) } fun start(noteUid: UUID) { this.noteUid = noteUid loadData() } fun onFabButtonClicked() { val note = this.note ?: return router.navigateTo( NoteEditorScreen( NoteEditorArgs( launchMode = LaunchMode.EDIT, noteUid = note.uid, title = note.title ) ) ) } override fun onNoteContentChanged(groupUid: UUID, oldNoteUid: UUID, newNoteUid: UUID) { if (oldNoteUid == noteUid) { noteUid = newNoteUid loadData() } } fun onLockButtonClicked() { interactor.lockDatabase() router.backTo(UnlockScreen()) } fun onSearchButtonClicked() { router.navigateTo(SearchScreen()) } fun navigateBack() = router.exit() fun onSettingsButtonClicked() = router.navigateTo(MainSettingsScreen()) private fun loadData() { val noteUid = this.noteUid ?: return isMenuVisible.value = false viewModelScope.launch { val result = withContext(Dispatchers.Default) { interactor.getNoteByUid(noteUid) } val status = interactor.getDatabaseStatus() if (result.isSucceededOrDeferred) { val note = result.obj [email protected] = note actionBarTitle.value = note.title modifiedText.value = note.modified.formatAccordingLocale(localeProvider.getSystemLocale()) val filter = PropertyFilter.Builder() .visible() .notEmpty() .sortedByType() .build() val models = cellModelFactory.createCellModels(filter.apply(note.properties)) setCellElements(cellViewModelFactory.createCellViewModels(models, eventProvider)) if (status.isSucceededOrDeferred) { updateStatusViewModel(status.obj) } isMenuVisible.value = true screenState.value = ScreenState.data() } else { val message = errorInteractor.processAndGetMessage(result.error) screenState.value = ScreenState.error(message) } } } private fun subscribeToCellEvents() { eventProvider.subscribe(this) { event -> if (event.containsKey(NotePropertyCellViewModel.COPY_BUTTON_CLICK_EVENT)) { val text = event.getString(NotePropertyCellViewModel.COPY_BUTTON_CLICK_EVENT) ?: EMPTY onCopyButtonClicked(text) } } } private fun onCopyButtonClicked(text: String) { interactor.copyToClipboardWithTimeout(text) val delayInSeconds = interactor.getTimeoutValueInMillis() / 1000L val message = resourceProvider.getString( R.string.copied_clipboard_will_be_cleared_in_seconds, delayInSeconds ) showSnackbarMessageEvent.call(message) } private fun updateStatusViewModel(status: DatabaseStatus) { statusViewModel.value = cellViewModelFactory.createCellViewModel( model = statusCellModelFactory.createStatusCellModel(status), eventProvider = eventProvider ) as DatabaseStatusCellViewModel } }
gpl-2.0
7b5ee767c8a9c00700871d3d77913af5
35.165
97
0.70589
5.125443
false
false
false
false
breadwallet/breadwallet-android
app-core/src/main/java/com/breadwallet/app/Conversion.kt
1
3513
/** * BreadWallet * * Created by Ahsan Butt <[email protected]> on 7/22/2020. * Copyright (c) 2020 breadwallet LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.breadwallet.app import com.breadwallet.breadbox.hashString import com.breadwallet.breadbox.toBigDecimal import com.breadwallet.crypto.Transfer import com.breadwallet.crypto.TransferState import java.util.Date private const val PREFIX_DELIMITER = "-" private const val BUY_CLASS_PREFIX = "buy" private const val TRADE_CLASS_PREFIX = "trade" sealed class Conversion { abstract val currencyCode: String abstract fun isTriggered(transfer: Transfer): Boolean abstract fun serialize(): String companion object { fun deserialize(value: String): Conversion { return when (value.substringBefore(PREFIX_DELIMITER)) { BUY_CLASS_PREFIX -> Buy.deserialize(value) TRADE_CLASS_PREFIX -> Trade.deserialize(value) else -> throw IllegalStateException("Unknown Type") } } } } data class Buy(override val currencyCode: String, val amount: Double, val timestamp: Long) : Conversion() { override fun isTriggered(transfer: Transfer) = transfer.amount.toBigDecimal().toDouble() == amount && transfer.state.type == TransferState.Type.INCLUDED && transfer.confirmation.get().confirmationTime.after(Date(timestamp)) && transfer.wallet.currency.code.equals(currencyCode, true) override fun serialize() = "$BUY_CLASS_PREFIX$PREFIX_DELIMITER$currencyCode;$amount;$timestamp" companion object { fun deserialize(value: String): Buy { val (currencyCode, amount, timestamp) = value.substringAfter(PREFIX_DELIMITER).split(";") return Buy(currencyCode, amount.toDouble(), timestamp.toLong()) } } } data class Trade(override val currencyCode: String, val hashString: String) : Conversion() { override fun isTriggered(transfer: Transfer) = transfer.hashString().equals(hashString, true) && transfer.state.type == TransferState.Type.INCLUDED override fun serialize() = "$TRADE_CLASS_PREFIX$PREFIX_DELIMITER$currencyCode;$hashString" companion object { fun deserialize(value: String): Trade { val (currencyCode, hashString) = value.substringAfter(PREFIX_DELIMITER).split(";") return Trade(currencyCode, hashString) } } }
mit
3c6a5d20ea04963087043242ba424a13
40.341176
99
0.706803
4.610236
false
false
false
false
breadwallet/breadwallet-android
app/src/main/java/com/platform/RequestBuilder.kt
1
2497
/** * BreadWallet * * Created by Pablo Budelli <[email protected]> on 8/21/19. * Copyright (c) 2019 breadwallet LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.platform import com.breadwallet.tools.util.BRConstants import com.breadwallet.ui.browser.BrdNativeJs import okhttp3.Request import okhttp3.RequestBody import okhttp3.RequestBody.Companion.toRequestBody import java.util.* /** * Build a signed request. */ @JvmOverloads fun buildSignedRequest( url: String, body: String, method: String, target: String, contentType: String = BRConstants.CONTENT_TYPE_JSON_CHARSET_UTF8 ): Request { var contentDigest = "" if (BRConstants.GET != method) { contentDigest = BrdNativeJs.sha256(body) } val requestDateString = Date().time.toString() val signature = BrdNativeJs.sign( method, contentDigest, contentType, requestDateString, target ) val builder = Request.Builder() .url(url) .addHeader(BrdNativeJs.SIGNATURE_HEADER, signature) .addHeader(BrdNativeJs.DATE_HEADER, requestDateString) .header("content-type", contentType) when (method) { "POST" -> builder.post(body.toRequestBody(null)) "PUT" -> builder.put(body.toRequestBody(null)) "PATH" -> builder.patch(body.toRequestBody(null)) } return builder.build() }
mit
6dc148e4198c750689798d7dab693858
34.671429
80
0.700441
4.342609
false
false
false
false
x2bool/kuery
sqlite/src/tel/egram/kuery/sqlite/SQLiteDialect.kt
1
16765
package tel.egram.kuery.sqlite import tel.egram.kuery.* import tel.egram.kuery.ddl.CreateTableStatement import tel.egram.kuery.ddl.DropTableStatement import tel.egram.kuery.dml.* object SQLiteDialect : Dialect { override fun <T : Table> build(statement: CreateTableStatement<T>): String { val builder = StringBuilder() builder.append("CREATE TABLE ") appendTableName(builder, statement.subject.table) builder.append('(') var delim = "" for (definition in statement.definitions) { builder.append(delim) delim = ", " appendShortColumnName(builder, definition.column) builder.append(' ') builder.append(definition.type) if (definition is SQLiteDefinition) { if (definition.meta.primaryKeyConstraint != null) { builder.append(" PRIMARY KEY") if (definition.meta.primaryKeyConstraint.autoIncrement) builder.append(" AUTOINCREMENT") } if (definition.meta.foreignKeyConstraint != null) { builder.append(" REFERENCES ") appendFullColumnName(builder, definition.meta.foreignKeyConstraint.references) } if (definition.meta.uniqueConstraint != null) { builder.append(" UNIQUE") } if (definition.meta.notNullConstraint != null) { builder.append(" NOT NULL") } } } builder.append(')') return builder.toString() } override fun <T : Table> build(statement: DropTableStatement<T>): String { return "DROP TABLE \"${statement.subject.table}\"" } override fun <T : Table> build(statement: SelectStatement<T>): String { val builder = StringBuilder() builder.append("SELECT ") appendProjection(builder, statement.projection, false) builder.append(" FROM ") appendTableName(builder, statement.subject.table) val where = statement.whereClause if (where != null) { builder.append(" WHERE ") appendPredicate(builder, where.predicate, false) } val group = statement.groupClause if (group != null) { builder.append(" GROUP BY ") appendProjection(builder, group.projection, false) } val having = statement.havingClause if (having != null) { builder.append(" HAVING ") appendPredicate(builder, having.predicate, false) } val order = statement.orderClause if (order != null) { builder.append(" ORDER BY ") appendOrdering(builder, order.orderings, false) } val limit = statement.limitClause if (limit != null) { builder.append(" LIMIT ") builder.append(limit.limit) } val offset = statement.offsetClause if (offset != null) { builder.append(" OFFSET ") builder.append(offset.offset) } return builder.toString() } override fun <T : Table, T2 : Table> build(statement: Select2Statement<T, T2>): String { val builder = StringBuilder() builder.append("SELECT ") appendProjection(builder, statement.projection, true) builder.append(" FROM ") appendTableName(builder, statement.joinOn2Clause.subject.table) if (statement.joinOn2Clause.type == JoinType.OUTER) builder.append(" OUTER") builder.append(" JOIN ") appendTableName(builder, statement.joinOn2Clause.table2) builder.append(" ON ") appendPredicate(builder, statement.joinOn2Clause.condition, true) val where = statement.where2Clause if (where != null) { builder.append(" WHERE ") appendPredicate(builder, where.predicate, true) } val group = statement.group2Clause if (group != null) { builder.append(" GROUP BY ") appendProjection(builder, group.projection, true) } val having = statement.having2Clause if (having != null) { builder.append(" HAVING ") appendPredicate(builder, having.predicate, true) } val order = statement.order2Clause if (order != null) { builder.append(" ORDER BY ") appendOrdering(builder, order.orderings, true) } val limit = statement.limit2Clause if (limit != null) { builder.append(" LIMIT ") builder.append(limit.limit) } val offset = statement.offset2Clause if (offset != null) { builder.append(" OFFSET ") builder.append(offset.offset) } return builder.toString() } override fun <T : Table, T2 : Table, T3 : Table> build(statement: Select3Statement<T, T2, T3>): String { val builder = StringBuilder() builder.append("SELECT ") appendProjection(builder, statement.projection, true) builder.append(" FROM ") appendTableName(builder, statement.joinOn3Clause.joinOn2Clause.subject.table) if (statement.joinOn3Clause.joinOn2Clause.type == JoinType.OUTER) builder.append(" OUTER") builder.append(" JOIN ") appendTableName(builder, statement.joinOn3Clause.joinOn2Clause.table2) builder.append(" ON ") appendPredicate(builder, statement.joinOn3Clause.joinOn2Clause.condition, true) if (statement.joinOn3Clause.type == JoinType.OUTER) builder.append(" OUTER") builder.append(" JOIN ") appendTableName(builder, statement.joinOn3Clause.table3) builder.append(" ON ") appendPredicate(builder, statement.joinOn3Clause.condition, true) val where = statement.where3Clause if (where != null) { builder.append(" WHERE ") appendPredicate(builder, where.predicate, true) } val group = statement.group3Clause if (group != null) { builder.append(" GROUP BY ") appendProjection(builder, group.projection, true) } val having = statement.having3Clause if (having != null) { builder.append(" HAVING ") appendPredicate(builder, having.predicate, true) } val order = statement.order3Clause if (order != null) { builder.append(" ORDER BY ") appendOrdering(builder, order.orderings, true) } val limit = statement.limit3Clause if (limit != null) { builder.append(" LIMIT ") builder.append(limit.limit) } val offset = statement.offset3Clause if (offset != null) { builder.append(" OFFSET ") builder.append(offset.offset) } return builder.toString() } override fun <T : Table, T2 : Table, T3 : Table, T4 : Table> build(statement: Select4Statement<T, T2, T3, T4>): String { val builder = StringBuilder() builder.append("SELECT ") appendProjection(builder, statement.projection, true) builder.append(" FROM ") appendTableName(builder, statement.joinOn4Clause.joinOn3Clause.joinOn2Clause.subject.table) if (statement.joinOn4Clause.joinOn3Clause.joinOn2Clause.type == JoinType.OUTER) builder.append(" OUTER") builder.append(" JOIN ") appendTableName(builder, statement.joinOn4Clause.joinOn3Clause.joinOn2Clause.table2) builder.append(" ON ") appendPredicate(builder, statement.joinOn4Clause.joinOn3Clause.joinOn2Clause.condition, true) if (statement.joinOn4Clause.joinOn3Clause.type == JoinType.OUTER) builder.append(" OUTER") builder.append(" JOIN ") appendTableName(builder, statement.joinOn4Clause.joinOn3Clause.table3) builder.append(" ON ") appendPredicate(builder, statement.joinOn4Clause.joinOn3Clause.condition, true) if (statement.joinOn4Clause.type == JoinType.OUTER) builder.append(" OUTER") builder.append(" JOIN ") appendTableName(builder, statement.joinOn4Clause.table4) builder.append(" ON ") appendPredicate(builder, statement.joinOn4Clause.condition, true) val where = statement.where4Clause if (where != null) { builder.append(" WHERE ") appendPredicate(builder, where.predicate, true) } val group = statement.group4Clause if (group != null) { builder.append(" GROUP BY ") appendProjection(builder, group.projection, true) } val having = statement.having4Clause if (having != null) { builder.append(" HAVING ") appendPredicate(builder, having.predicate, true) } val order = statement.order4Clause if (order != null) { builder.append(" ORDER BY ") appendOrdering(builder, order.orderings, true) } val limit = statement.limit4Clause if (limit != null) { builder.append(" LIMIT ") builder.append(limit.limit) } val offset = statement.offset4Clause if (offset != null) { builder.append(" OFFSET ") builder.append(offset.offset) } return builder.toString() } override fun <T : Table> build(statement: InsertStatement<T>): String { val builder = StringBuilder() builder.append("INSERT INTO ") appendTableName(builder, statement.subject.table) builder.append(" (") var delim = "" for (assign in statement.assignments) { builder.append(delim) delim = ", " appendShortColumnName(builder, assign.column) } builder.append(") VALUES (") delim = "" for (assign in statement.assignments) { builder.append(delim) delim = ", " appendValue(builder, assign.value) } builder.append(")") return builder.toString() } override fun <T : Table> build(statement: UpdateStatement<T>): String { val builder = StringBuilder() builder.append("UPDATE ") appendTableName(builder, statement.subject.table) builder.append(" SET ") var delim = "" for (assign in statement.assignments) { builder.append(delim) delim = ", " appendShortColumnName(builder, assign.column) builder.append(" = ") appendValue(builder, assign.value) } val where = statement.whereClause if (where != null) { builder.append(" WHERE ") appendPredicate(builder, where.predicate, false) } return builder.toString() } override fun <T : Table> build(statement: DeleteStatement<T>): String { val builder = StringBuilder() builder.append("DELETE FROM ") appendTableName(builder, statement.subject.table) val where = statement.whereClause if (where != null) { builder.append(" WHERE ") appendPredicate(builder, where.predicate, false) } return builder.toString() } private fun appendPredicate(builder: StringBuilder, value: Any?, fullFormat: Boolean = true) { when (value) { is Table.Column -> if (fullFormat) appendFullColumnName(builder, value) else appendShortColumnName(builder, value) is NotExpression -> { builder.append("(NOT ") appendPredicate(builder, value.param, fullFormat) builder.append(")") } is AndExpression -> { builder.append('(') appendPredicate(builder, value.left, fullFormat) builder.append(" AND ") appendPredicate(builder, value.right, fullFormat) builder.append(')') } is OrExpression -> { builder.append('(') appendPredicate(builder, value.left, fullFormat) builder.append(" OR ") appendPredicate(builder, value.right, fullFormat) builder.append(')') } is EqExpression -> { builder.append('(') if (value.right != null) { appendPredicate(builder, value.left, fullFormat) builder.append(" = ") appendPredicate(builder, value.right, fullFormat) } else { appendPredicate(builder, value.left, fullFormat) builder.append(" IS NULL") } builder.append(')') } is NeExpression -> { builder.append('(') if (value.right != null) { appendPredicate(builder, value.left, fullFormat) builder.append(" != ") appendPredicate(builder, value.right, fullFormat) } else { appendPredicate(builder, value.left, fullFormat) builder.append(" IS NOT NULL") } builder.append(')') } is LtExpression -> { builder.append('(') appendPredicate(builder, value.left, fullFormat) builder.append(" < ") appendPredicate(builder, value.right, fullFormat) builder.append(')') } is LteExpression -> { builder.append('(') appendPredicate(builder, value.left, fullFormat) builder.append(" <= ") appendPredicate(builder, value.right, fullFormat) builder.append(')') } is GtExpression -> { builder.append('(') appendPredicate(builder, value.left, fullFormat) builder.append(" > ") appendPredicate(builder, value.right, fullFormat) builder.append(')') } is GteExpression -> { builder.append('(') appendPredicate(builder, value.left, fullFormat) builder.append(" >= ") appendPredicate(builder, value.right, fullFormat) builder.append(')') } else -> appendValue(builder, value) } } private fun appendProjection(builder: StringBuilder, projection: Iterable<Projection>, fullFormat: Boolean) { if ("SELECT".contentEquals(builder.toString().trim()) and projection.none()) { builder.append("*") } else { var delim = "" for (proj in projection) { builder.append(delim) delim = ", " if (proj is Table.Column) { if (fullFormat) { appendFullColumnName(builder, proj) } else { appendShortColumnName(builder, proj) } } else { builder.append(proj) } } } } private fun appendOrdering(builder: StringBuilder, orderings: Iterable<Ordering>, fullFormat: Boolean) { var delim = "" for (order in orderings) { builder.append(delim) delim = ", " if (order.key is Table.Column) { if (fullFormat) { appendFullColumnName(builder, order.key as Table.Column) } else { appendShortColumnName(builder, order.key as Table.Column) } } else { builder.append(order.key) } builder.append(if (order.asc) " ASC" else " DESC") } } private fun appendTableName(builder: StringBuilder, table: Table) { builder.append("\"$table\"") } private fun appendShortColumnName(builder: StringBuilder, column: Table.Column) { builder.append("\"$column\"") } private fun appendFullColumnName(builder: StringBuilder, column: Table.Column) { builder.append("\"${column.table}\".\"$column\"") } private fun appendValue(builder: StringBuilder, value: Any?) { value?.let { builder.append((value as? String)?.escapedSQLString() ?: value) } ?: builder.append("NULL") } private fun String.escapedSQLString(): String = "\'${this.replace("'", "''")}\'" }
mit
0b18b8ec5c0d5836f092d2013c884e37
32.398406
126
0.560036
4.825849
false
false
false
false
EMResearch/EvoMaster
core/src/test/kotlin/org/evomaster/core/database/extract/postgres/EnumeratedTypesTest.kt
1
1422
package org.evomaster.core.database.extract.postgres import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType import org.evomaster.client.java.controller.db.SqlScriptRunner import org.evomaster.client.java.controller.internal.db.SchemaExtractor import org.evomaster.core.database.DbActionTransformer import org.evomaster.core.database.SqlInsertBuilder import org.evomaster.core.search.gene.collection.EnumGene import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test /** * Created by jgaleotti on 07-May-19. */ class EnumeratedTypesTest : ExtractTestBasePostgres() { override fun getSchemaLocation() = "/sql_schema/postgres_enumerated_types.sql" @Test fun testEnumeratedTypes() { val schema = SchemaExtractor.extract(connection) assertNotNull(schema) assertEquals("public", schema.name.lowercase()) assertEquals(DatabaseType.POSTGRES, schema.databaseType) val builder = SqlInsertBuilder(schema) val actions = builder.createSqlInsertionAction( "EnumeratedTypes", setOf( "enumColumn" ) ) val genes = actions[0].seeTopGenes() assertEquals(1, genes.size) assertTrue(genes[0] is EnumGene<*>) val dbCommandDto = DbActionTransformer.transform(actions) SqlScriptRunner.execInsert(connection, dbCommandDto.insertions) } }
lgpl-3.0
d926036fc3d1a99f502dbd5b3ff012ae
29.934783
82
0.728551
4.557692
false
true
false
false
dmitryustimov/weather-kotlin
app/src/main/java/ru/ustimov/weather/content/impl/local/Database.kt
1
1052
package ru.ustimov.weather.content.impl.local import android.arch.persistence.room.Database import android.arch.persistence.room.RoomDatabase import ru.ustimov.weather.content.impl.local.dao.CitiesDao import ru.ustimov.weather.content.impl.local.dao.CountriesDao import ru.ustimov.weather.content.impl.local.dao.SearchHistoryDao import ru.ustimov.weather.content.impl.local.data.RoomCity import ru.ustimov.weather.content.impl.local.data.RoomCountry import ru.ustimov.weather.content.impl.local.data.RoomSearchHistory @Database(entities = arrayOf(RoomCity::class, RoomCountry::class, RoomSearchHistory::class), version = 1) internal abstract class Database : RoomDatabase() { internal companion object Tables { internal const val CITIES = "cities" internal const val COUNTRIES = "countries" internal const val SEARCH_HISTORY = "search_history" } internal abstract fun cities(): CitiesDao internal abstract fun countries(): CountriesDao internal abstract fun searchHistory(): SearchHistoryDao }
apache-2.0
ad5d2f8cdb90f2b099e0a3a6c91ba5c8
36.607143
92
0.782319
4.191235
false
false
false
false
google/taqo-paco
taqo_client/plugins/time/android/src/main/kotlin/com/taqo/survey/taqo_time_plugin/TaqoTimePlugin.kt
1
2593
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.taqo.survey.taqo_time_plugin import android.content.Context import androidx.annotation.NonNull import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.MethodChannel.MethodCallHandler import io.flutter.plugin.common.MethodChannel.Result import org.json.JSONArray private const val channelName = "taqo_time_plugin" private const val initialize = "initialize" private const val cancel = "cancel" /** TaqoTimePlugin */ class TaqoTimePlugin: FlutterPlugin, MethodCallHandler { private lateinit var context: Context /// The MethodChannel that will the communication between Flutter and native Android /// /// This local reference serves to register the plugin with the Flutter Engine and unregister it /// when the Flutter Engine is detached from the Activity private lateinit var channel : MethodChannel override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { context = flutterPluginBinding.applicationContext channel = MethodChannel(flutterPluginBinding.binaryMessenger, channelName) channel.setMethodCallHandler(this) } override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) { when (call.method) { initialize -> { val args = JSONArray(call.arguments as Collection<*>) val bgCallbackHandle = args.getLong(0) val callbackHandle = args.getLong(1) FlutterBackgroundExecutor.setCallbackDispatcher(context, bgCallbackHandle, callbackHandle) TimeChangedReceiver.startBackgroundIsolate(context, bgCallbackHandle) result.success(true) } cancel -> { TimeChangedReceiver.cancel() result.success(true) } else -> result.notImplemented() } } override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { channel.setMethodCallHandler(null) } }
apache-2.0
4b8739781e95e9453b5cc1927119b7fd
38.287879
102
0.76128
4.581272
false
false
false
false
frendyxzc/KotlinNews
model/src/main/java/vip/frendy/model/net/RequestCommon.kt
1
877
package vip.frendy.model.net import vip.frendy.model.data.Constants import java.net.URL /** * Created by iiMedia on 2017/6/2. */ class RequestCommon(val url: String) { companion object { val BASE_URL = "http://www.myxianwen.cn/newsapp/index.action?" val BASE_URL_2 = "http://api.myxianwen.cn/1" val INIT_URL = BASE_URL + Constants.APP_INFO + "&action=init&equip_type=0&params="; val GET_CHANNEL = BASE_URL_2 + "/user/getchannellist?" + Constants.APP_INFO + "&equip_type=0&version=3.6.2" val GET_NEWS_LIST = BASE_URL_2 + "/news/getlist?" + Constants.APP_INFO + "&equip_type=0&updown=0&version=3.6.2" val GET_VIDEO_LIST = BASE_URL_2 + "/news/getvediolist?" + Constants.APP_INFO + "&equip_type=0&updown=0&version=3.6.2" } fun run(): String { val jsonStr = URL(url).readText() return jsonStr } }
mit
3f7bdef823a9475fd5be7ca335d2d413
35.583333
125
0.6374
2.942953
false
false
false
false
pie-flavor/Kludge
src/main/kotlin/flavor/pie/kludge/builders.kt
1
20392
@file:Suppress("UNCHECKED_CAST", "FunctionName") package flavor.pie.kludge import org.spongepowered.api.advancement.Advancement import org.spongepowered.api.advancement.AdvancementTree import org.spongepowered.api.advancement.DisplayInfo import org.spongepowered.api.advancement.criteria.AdvancementCriterion import org.spongepowered.api.advancement.criteria.ScoreAdvancementCriterion import org.spongepowered.api.advancement.criteria.trigger.FilteredTrigger import org.spongepowered.api.advancement.criteria.trigger.FilteredTriggerConfiguration import org.spongepowered.api.advancement.criteria.trigger.Trigger import org.spongepowered.api.block.BlockSnapshot import org.spongepowered.api.block.BlockState import org.spongepowered.api.block.tileentity.TileEntityArchetype import org.spongepowered.api.boss.ServerBossBar import org.spongepowered.api.command.CommandResult import org.spongepowered.api.command.args.CommandElement import org.spongepowered.api.command.args.CommandFlags import org.spongepowered.api.command.args.GenericArguments import org.spongepowered.api.command.spec.CommandSpec import org.spongepowered.api.data.DataRegistration import org.spongepowered.api.data.key.Key import org.spongepowered.api.data.manipulator.DataManipulator import org.spongepowered.api.data.manipulator.ImmutableDataManipulator import org.spongepowered.api.data.meta.PatternLayer import org.spongepowered.api.data.value.BaseValue import org.spongepowered.api.effect.particle.ParticleEffect import org.spongepowered.api.effect.potion.PotionEffect import org.spongepowered.api.effect.sound.SoundType import org.spongepowered.api.entity.EntityArchetype import org.spongepowered.api.entity.EntitySnapshot import org.spongepowered.api.entity.ai.task.builtin.LookIdleAITask import org.spongepowered.api.entity.ai.task.builtin.SwimmingAITask import org.spongepowered.api.entity.ai.task.builtin.WatchClosestAITask import org.spongepowered.api.entity.ai.task.builtin.creature.AttackLivingAITask import org.spongepowered.api.entity.ai.task.builtin.creature.AvoidEntityAITask import org.spongepowered.api.entity.ai.task.builtin.creature.RangeAgentAITask import org.spongepowered.api.entity.ai.task.builtin.creature.WanderAITask import org.spongepowered.api.entity.ai.task.builtin.creature.horse.RunAroundLikeCrazyAITask import org.spongepowered.api.entity.ai.task.builtin.creature.target.FindNearestAttackableTargetAITask import org.spongepowered.api.entity.living.Agent import org.spongepowered.api.entity.living.Creature import org.spongepowered.api.entity.living.Ranger import org.spongepowered.api.entity.living.animal.RideableHorse import org.spongepowered.api.entity.living.player.tab.TabListEntry import org.spongepowered.api.event.cause.Cause import org.spongepowered.api.event.cause.EventContext import org.spongepowered.api.event.cause.EventContextKey import org.spongepowered.api.event.cause.entity.damage.source.BlockDamageSource import org.spongepowered.api.event.cause.entity.damage.source.DamageSource import org.spongepowered.api.event.cause.entity.damage.source.EntityDamageSource import org.spongepowered.api.event.cause.entity.damage.source.FallingBlockDamageSource import org.spongepowered.api.event.cause.entity.damage.source.IndirectEntityDamageSource import org.spongepowered.api.event.cause.entity.health.source.BlockHealingSource import org.spongepowered.api.event.cause.entity.health.source.EntityHealingSource import org.spongepowered.api.event.cause.entity.health.source.HealingSource import org.spongepowered.api.event.cause.entity.health.source.IndirectEntityHealingSource import org.spongepowered.api.extra.fluid.FluidStack import org.spongepowered.api.extra.fluid.FluidStackSnapshot import org.spongepowered.api.item.FireworkEffect import org.spongepowered.api.item.enchantment.Enchantment import org.spongepowered.api.item.inventory.Inventory import org.spongepowered.api.item.inventory.InventoryArchetype import org.spongepowered.api.item.inventory.ItemStack import org.spongepowered.api.item.inventory.ItemStackGenerator import org.spongepowered.api.item.merchant.TradeOffer import org.spongepowered.api.item.merchant.TradeOfferGenerator import org.spongepowered.api.item.recipe.crafting.Ingredient import org.spongepowered.api.plugin.PluginContainer import org.spongepowered.api.scheduler.Task import org.spongepowered.api.scoreboard.Scoreboard import org.spongepowered.api.scoreboard.Team import org.spongepowered.api.scoreboard.objective.Objective import org.spongepowered.api.service.pagination.PaginationList import org.spongepowered.api.text.selector.Selector import org.spongepowered.api.util.ban.Ban import org.spongepowered.api.world.ChunkPreGenerate import org.spongepowered.api.world.LocatableBlock import org.spongepowered.api.world.World import org.spongepowered.api.world.WorldArchetype import org.spongepowered.api.world.WorldBorder import org.spongepowered.api.world.biome.BiomeGenerationSettings import org.spongepowered.api.world.biome.VirtualBiomeType import org.spongepowered.api.world.explosion.Explosion import org.spongepowered.api.world.gen.populator.BigMushroom import org.spongepowered.api.world.gen.populator.BlockBlob import org.spongepowered.api.world.gen.populator.Cactus import org.spongepowered.api.world.gen.populator.ChorusFlower import org.spongepowered.api.world.gen.populator.DeadBush import org.spongepowered.api.world.gen.populator.DesertWell import org.spongepowered.api.world.gen.populator.DoublePlant import org.spongepowered.api.world.gen.populator.Dungeon import org.spongepowered.api.world.gen.populator.EndIsland import org.spongepowered.api.world.gen.populator.Flower import org.spongepowered.api.world.gen.populator.Forest import org.spongepowered.api.world.gen.populator.Fossil import org.spongepowered.api.world.gen.populator.Glowstone import org.spongepowered.api.world.gen.populator.IcePath import org.spongepowered.api.world.gen.populator.IceSpike import org.spongepowered.api.world.gen.populator.Lake import org.spongepowered.api.world.gen.populator.Melon import org.spongepowered.api.world.gen.populator.Mushroom import org.spongepowered.api.world.gen.populator.NetherFire import org.spongepowered.api.world.gen.populator.Ore import org.spongepowered.api.world.gen.populator.Pumpkin import org.spongepowered.api.world.gen.populator.RandomBlock import org.spongepowered.api.world.gen.populator.RandomObject import org.spongepowered.api.world.gen.populator.Reed import org.spongepowered.api.world.gen.populator.SeaFloor import org.spongepowered.api.world.gen.populator.Shrub import org.spongepowered.api.world.gen.populator.Vine import org.spongepowered.api.world.gen.populator.WaterLily import org.spongepowered.api.world.schematic.Schematic inline fun advancementOf(fn: Advancement.Builder.() -> Unit): Advancement = Advancement.builder().apply(fn).build() inline fun advancementCriterionOf(fn: AdvancementCriterion.Builder.() -> Unit): AdvancementCriterion = AdvancementCriterion.builder().apply(fn).build() inline fun advancementTreeOf(fn: AdvancementTree.Builder.() -> Unit): AdvancementTree = AdvancementTree.builder().apply(fn).build() inline fun attackLivingAITaskOf(owner: Creature, fn: AttackLivingAITask.Builder.() -> Unit): AttackLivingAITask = AttackLivingAITask.builder().apply(fn).build(owner) inline fun avoidEntityAITaskOf(owner: Creature, fn: AvoidEntityAITask.Builder.() -> Unit): AvoidEntityAITask = AvoidEntityAITask.builder().apply(fn).build(owner) inline fun banOf(fn: Ban.Builder.() -> Unit): Ban = Ban.builder().apply(fn).build() inline fun bigMushroomOf(fn: BigMushroom.Builder.() -> Unit): BigMushroom = BigMushroom.builder().apply(fn).build() inline fun biomeGenerationSettingsOf(fn: BiomeGenerationSettings.Builder.() -> Unit): BiomeGenerationSettings = BiomeGenerationSettings.builder().apply(fn).build() inline fun blockBlobOf(fn: BlockBlob.Builder.() -> Unit): BlockBlob = BlockBlob.builder().apply(fn).build() inline fun blockDamageSourceOf(fn: BlockDamageSource.Builder.() -> Unit): BlockDamageSource = BlockDamageSource.builder().apply(fn).build() inline fun blockHealingSourceOf(fn: BlockHealingSource.Builder.() -> Unit): BlockHealingSource = BlockHealingSource.builder().apply(fn).build() inline fun blockSnapshotOf(fn: BlockSnapshot.Builder.() -> Unit): BlockSnapshot = BlockSnapshot.builder().apply(fn).build() inline fun blockStateOf(fn: BlockState.Builder.() -> Unit): BlockState = BlockState.builder().apply(fn).build() inline fun causeOf(context: EventContext, fn: Cause.Builder.() -> Unit): Cause = Cause.builder().apply(fn).build(context) inline fun cactusOf(fn: Cactus.Builder.() -> Unit): Cactus = Cactus.builder().apply(fn).build() inline fun chorusFlowerOf(fn: ChorusFlower.Builder.() -> Unit): ChorusFlower = ChorusFlower.builder().apply(fn).build() inline fun WorldBorder.newChunkPreGenerate(world: World, fn: ChunkPreGenerate.Builder.() -> Unit): ChunkPreGenerate = this.newChunkPreGenerate(world).apply(fn).start() inline fun commandFlagsOf(vararg args: CommandElement, fn: CommandFlags.Builder.() -> Unit): CommandElement = GenericArguments.flags().apply(fn).buildWith(GenericArguments.seq(*args)) inline fun commandFlagsOf(fn: CommandFlags.Builder.() -> Unit): CommandElement = GenericArguments.flags().apply(fn).build() inline fun commandResultOf(fn: CommandResult.Builder.() -> Unit): CommandResult = CommandResult.builder().apply(fn).build() inline fun commandSpecOf(fn: CommandSpec.Builder.() -> Unit): CommandSpec = CommandSpec.builder().apply(fn).build() inline fun damageSourceOf(fn: DamageSource.Builder.() -> Unit): DamageSource = DamageSource.builder().apply(fn).build() inline fun <reified M : DataManipulator<M, I>, reified I : ImmutableDataManipulator<I, M>> dataRegistrationOf( plugin: PluginContainer, fn: DataRegistration.Builder<M, I>.() -> Unit ): DataRegistration<M, I> = (DataRegistration.builder() as DataRegistration.Builder<M, I>).apply(fn).dataClass(M::class.java).immutableClass(I::class.java) .buildAndRegister(plugin) inline fun <reified M : DataManipulator<M, I>, reified I : ImmutableDataManipulator<I, M>> dataRegistrationOf(fn: DataRegistration.Builder<M, I>.() -> Unit): DataRegistration<M, I> = (DataRegistration.builder() as DataRegistration.Builder<M, I>).apply(fn).dataClass(M::class.java).immutableClass(I::class.java) .buildAndRegister(PluginManager.fromInstance(plugin).get()) inline fun deadBushOf(fn: DeadBush.Builder.() -> Unit): DeadBush = DeadBush.builder().apply(fn).build() inline fun desertWellOf(fn: DesertWell.Builder.() -> Unit): DesertWell = DesertWell.builder().apply(fn).build() inline fun displayInfoOf(fn: DisplayInfo.Builder.() -> Unit): DisplayInfo = DisplayInfo.builder().apply(fn).build() inline fun doublePlantOf(fn: DoublePlant.Builder.() -> Unit): DoublePlant = DoublePlant.builder().apply(fn).build() inline fun dungeonOf(fn: Dungeon.Builder.() -> Unit): Dungeon = Dungeon.builder().apply(fn).build() inline fun enchantmentOf(fn: Enchantment.Builder.() -> Unit): Enchantment = Enchantment.builder().apply(fn).build() inline fun endIslandOf(fn: EndIsland.Builder.() -> Unit): EndIsland = EndIsland.builder().apply(fn).build() inline fun entityArchetypeOf(fn: EntityArchetype.Builder.() -> Unit): EntityArchetype = EntityArchetype.builder().apply(fn).build() inline fun entityDamageSourceOf(fn: EntityDamageSource.Builder.() -> Unit): EntityDamageSource = EntityDamageSource.builder().apply(fn).build() inline fun entityHealingSourceOf(fn: EntityHealingSource.Builder.() -> Unit): EntityHealingSource = EntityHealingSource.builder().apply(fn).build() inline fun entitySnapshotOf(fn: EntitySnapshot.Builder.() -> Unit): EntitySnapshot = EntitySnapshot.builder().apply(fn).build() inline fun <reified T> eventContextKeyOf(fn: EventContextKey.Builder<T>.() -> Unit): EventContextKey<T> = EventContextKey.builder(T::class.java).apply(fn).build() inline fun explosionOf(fn: Explosion.Builder.() -> Unit): Explosion = Explosion.builder().apply(fn).build() inline fun fallingBlockDamageSourceOf(fn: FallingBlockDamageSource.Builder.() -> Unit): FallingBlockDamageSource = FallingBlockDamageSource.builder().apply(fn).build() inline fun <T : FilteredTriggerConfiguration> filteredTriggerOf(fn: FilteredTrigger.Builder<T>.() -> Unit): FilteredTrigger<T> = (FilteredTrigger.builder() as FilteredTrigger.Builder<T>).apply(fn).build() inline fun findNearestAttackableTargetAITaskOf( owner: Creature, fn: FindNearestAttackableTargetAITask.Builder.() -> Unit ): FindNearestAttackableTargetAITask = FindNearestAttackableTargetAITask.builder().apply(fn).build(owner) inline fun fireworkEffectOf(fn: FireworkEffect.Builder.() -> Unit): FireworkEffect = FireworkEffect.builder().apply(fn).build() inline fun flowerOf(fn: Flower.Builder.() -> Unit): Flower = Flower.builder().apply(fn).build() inline fun fluidStackOf(fn: FluidStack.Builder.() -> Unit): FluidStack = FluidStack.builder().apply(fn).build() inline fun fluidStackSnapshotOf(fn: FluidStackSnapshot.Builder.() -> Unit): FluidStackSnapshot = FluidStackSnapshot.builder().apply(fn).build() inline fun forestOf(fn: Forest.Builder.() -> Unit): Forest = Forest.builder().apply(fn).build() inline fun fossilOf(fn: Fossil.Builder.() -> Unit): Fossil = Fossil.builder().apply(fn).build() inline fun glowstoneOf(fn: Glowstone.Builder.() -> Unit): Glowstone = Glowstone.builder().apply(fn).build() inline fun healingSourceOf(fn: HealingSource.Builder.() -> Unit): HealingSource = HealingSource.builder().apply(fn).build() inline fun icePathOf(fn: IcePath.Builder.() -> Unit): IcePath = IcePath.builder().apply(fn).build() inline fun iceSpikeOf(fn: IceSpike.Builder.() -> Unit): IceSpike = IceSpike.builder().apply(fn).build() inline fun indirectEntityDamageSourceOf(fn: IndirectEntityDamageSource.Builder.() -> Unit): IndirectEntityDamageSource = IndirectEntityDamageSource.builder().apply(fn).build() inline fun indirectEntityHealingSourceOf(fn: IndirectEntityHealingSource.Builder.() -> Unit): IndirectEntityHealingSource = IndirectEntityHealingSource.builder().apply(fn).build() inline fun ingredientOf(fn: Ingredient.Builder.() -> Unit): Ingredient = Ingredient.builder().apply(fn).build() inline fun inventoryOf(plugin: Any, fn: Inventory.Builder.() -> Unit): Inventory = Inventory.builder().apply(fn).build(plugin) inline fun inventoryOf(fn: Inventory.Builder.() -> Unit): Inventory = Inventory.builder().apply(fn).build(plugin) inline fun inventoryArchetypeOf( id: String, name: String, fn: InventoryArchetype.Builder.() -> Unit ): InventoryArchetype = InventoryArchetype.builder().apply(fn).build(id, name) inline fun itemStackOf(fn: ItemStack.Builder.() -> Unit): ItemStack = ItemStack.builder().apply(fn).build() inline fun itemStackGeneratorOf(fn: ItemStackGenerator.Builder.() -> Unit): ItemStackGenerator = ItemStackGenerator.builder().apply(fn).build() inline fun <E, V : BaseValue<E>> keyOf(fn: Key.Builder<E, V>.() -> Unit): Key<V> = (Key.builder() as Key.Builder<E, V>).apply(fn).build() inline fun lakeOf(fn: Lake.Builder.() -> Unit): Lake = Lake.builder().apply(fn).build() inline fun locatableBlockOf(fn: LocatableBlock.Builder.() -> Unit): LocatableBlock = LocatableBlock.builder().apply(fn).build() inline fun lookIdleAITaskOf(owner: Agent, fn: LookIdleAITask.Builder.() -> Unit): LookIdleAITask = LookIdleAITask.builder().apply(fn).build(owner) inline fun melonOf(fn: Melon.Builder.() -> Unit): Melon = Melon.builder().apply(fn).build() inline fun mushroomOf(fn: Mushroom.Builder.() -> Unit): Mushroom = Mushroom.builder().apply(fn).build() inline fun netherFireOf(fn: NetherFire.Builder.() -> Unit): NetherFire = NetherFire.builder().apply(fn).build() inline fun objectiveOf(fn: Objective.Builder.() -> Unit): Objective = Objective.builder().apply(fn).build() inline fun oreOf(fn: Ore.Builder.() -> Unit): Ore = Ore.builder().apply(fn).build() inline fun paginationListOf(fn: PaginationList.Builder.() -> Unit): PaginationList = PaginationList.builder().apply(fn).build() inline fun particleEffectOf(fn: ParticleEffect.Builder.() -> Unit): ParticleEffect = ParticleEffect.builder().apply(fn).build() inline fun patternLayerOf(fn: PatternLayer.Builder.() -> Unit): PatternLayer = GameRegistry.createBuilder(PatternLayer.Builder::class.java).apply(fn).build() inline fun potionEffectOf(fn: PotionEffect.Builder.() -> Unit): PotionEffect = PotionEffect.builder().apply(fn).build() inline fun pumpkinOf(fn: Pumpkin.Builder.() -> Unit): Pumpkin = Pumpkin.builder().apply(fn).build() inline fun randomBlockOf(fn: RandomBlock.Builder.() -> Unit): RandomBlock = RandomBlock.builder().apply(fn).build() inline fun randomObjectOf(fn: RandomObject.Builder.() -> Unit): RandomObject = RandomObject.builder().apply(fn).build() inline fun rangeAgentAITaskOf(owner: Ranger, fn: RangeAgentAITask.Builder.() -> Unit): RangeAgentAITask = RangeAgentAITask.builder().apply(fn).build(owner) inline fun reedOf(fn: Reed.Builder.() -> Unit): Reed = Reed.builder().apply(fn).build() inline fun runAroundLikeCrazyAITaskOf( owner: RideableHorse, fn: RunAroundLikeCrazyAITask.Builder.() -> Unit ): RunAroundLikeCrazyAITask = RunAroundLikeCrazyAITask.builder().apply(fn).build(owner) inline fun schematicOf(fn: Schematic.Builder.() -> Unit): Schematic = Schematic.builder().apply(fn).build() inline fun scoreAdvancementCriterionOf(fn: ScoreAdvancementCriterion.Builder.() -> Unit): ScoreAdvancementCriterion = ScoreAdvancementCriterion.builder().apply(fn).build() inline fun scoreboardOf(fn: Scoreboard.Builder.() -> Unit): Scoreboard = Scoreboard.builder().apply(fn).build() inline fun seaFloorOf(fn: SeaFloor.Builder.() -> Unit): SeaFloor = SeaFloor.builder().apply(fn).build() inline fun selectorOf(fn: Selector.Builder.() -> Unit): Selector = Selector.builder().apply(fn).build() inline fun serverBossBarOf(fn: ServerBossBar.Builder.() -> Unit): ServerBossBar = ServerBossBar.builder().apply(fn).build() inline fun shrubOf(fn: Shrub.Builder.() -> Unit): Shrub = Shrub.builder().apply(fn).build() inline fun soundTypeOf(id: String, fn: SoundType.Builder.() -> Unit): SoundType = SoundType.builder().apply(fn).build(id) inline fun swimmingAITaskOf(owner: Agent, fn: SwimmingAITask.Builder.() -> Unit): SwimmingAITask = SwimmingAITask.builder().apply(fn).build(owner) inline fun tabListEntryOf(fn: TabListEntry.Builder.() -> Unit): TabListEntry = TabListEntry.builder().apply(fn).build() inline fun taskOf(plugin: Any, fn: Task.Builder.() -> Unit): Task = Task.builder().apply(fn).submit(plugin) inline fun taskof(fn: Task.Builder.() -> Unit): Task = Task.builder().apply(fn).submit(plugin) inline fun teamOf(fn: Team.Builder.() -> Unit): Team = Team.builder().apply(fn).build() inline fun tileEntityArchetypeOf(fn: TileEntityArchetype.Builder.() -> Unit): TileEntityArchetype = TileEntityArchetype.builder().apply(fn).build() inline fun tradeOfferOf(fn: TradeOffer.Builder.() -> Unit): TradeOffer = TradeOffer.builder().apply(fn).build() inline fun tradeOfferGeneratorOf(fn: TradeOfferGenerator.Builder.() -> Unit): TradeOfferGenerator = TradeOfferGenerator.builder().apply(fn).build() inline fun <C : FilteredTriggerConfiguration> triggerOf(fn: Trigger.Builder<C>.() -> Unit): Trigger<C> = (Trigger.builder() as Trigger.Builder<C>).apply(fn).build() inline fun vineOf(fn: Vine.Builder.() -> Unit): Vine = Vine.builder().apply(fn).build() inline fun virtualBiomeTypeOf(id: String, fn: VirtualBiomeType.Builder.() -> Unit): VirtualBiomeType = VirtualBiomeType.builder().apply(fn).build(id) inline fun wanderAITaskOf(owner: Creature, fn: WanderAITask.Builder.() -> Unit): WanderAITask = WanderAITask.builder().apply(fn).build(owner) inline fun watchClosestAITaskOf(owner: Agent, fn: WatchClosestAITask.Builder.() -> Unit): WatchClosestAITask = WatchClosestAITask.builder().apply(fn).build(owner) inline fun waterLilyOf(fn: WaterLily.Builder.() -> Unit): WaterLily = WaterLily.builder().apply(fn).build() inline fun worldArchetypeOf(id: String, name: String, fn: WorldArchetype.Builder.() -> Unit): WorldArchetype = WorldArchetype.builder().apply(fn).build(id, name) inline fun worldBorderOf(fn: WorldBorder.Builder.() -> Unit): WorldBorder = WorldBorder.builder().apply(fn).build()
mit
6d53ff5254cc724bd04bcce395b4c131
61.170732
182
0.786191
3.788222
false
false
false
false
ajalt/clikt
samples/json/src/main/kotlin/com/github/ajalt/clikt/samples/json/JsonValueSource.kt
1
2146
package com.github.ajalt.clikt.samples.json import com.github.ajalt.clikt.core.Context import com.github.ajalt.clikt.core.InvalidFileFormat import com.github.ajalt.clikt.parameters.options.Option import com.github.ajalt.clikt.sources.ValueSource import kotlinx.serialization.SerializationException import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import java.io.File /** * A [ValueSource] that uses Kotlin serialization to parse JSON files */ class JsonValueSource( private val root: JsonObject, ) : ValueSource { override fun getValues(context: Context, option: Option): List<ValueSource.Invocation> { var cursor: JsonElement? = root val parts = option.valueSourceKey?.split(".") ?: context.commandNameWithParents().drop(1) + ValueSource.name(option) for (part in parts) { if (cursor !is JsonObject) return emptyList() cursor = cursor[part] } if (cursor == null) return emptyList() // This implementation interprets a list as multiple invocations, but you could also // implement it as a single invocation with multiple values. if (cursor is JsonArray) return cursor.map { ValueSource.Invocation.value(it) } return ValueSource.Invocation.just(cursor) } companion object { fun from(file: File, requireValid: Boolean = false): JsonValueSource { if (!file.isFile) return JsonValueSource(JsonObject(emptyMap())) val json = try { Json.parseToJsonElement(file.readText()) as? JsonObject ?: throw InvalidFileFormat(file.path, "object expected", 1) } catch (e: SerializationException) { if (requireValid) throw InvalidFileFormat(file.name, e.message ?: "could not read file") JsonObject(emptyMap()) } return JsonValueSource(json) } fun from(file: String, requireValid: Boolean = false): JsonValueSource = from(File(file), requireValid) } }
apache-2.0
2ab1353d4e3de61a7a39573ceed17f9e
40.269231
111
0.684529
4.655098
false
false
false
false
luhaoaimama1/AndroidZone
JavaTest_Zone/src/kt/强制刷新问题/Main.kt
2
616
package kt.强制刷新问题 /** * Created by fuzhipeng on 2018/11/28. */ fun main(args: Array<String>) { for (i in 0..2) { method1(i,i+1) } } private fun method1(firstValue:Int,secondValue:Int) { var a = firstValue GO().go(object : Callback { var tempA = a override fun doWhat() { println("a:$a======tempA:$tempA") } }) a = secondValue } interface Callback { fun doWhat() } class GO { fun go(callback: Callback?) { Thread(Runnable { Thread.sleep(1000) callback?.doWhat() }).start() } }
epl-1.0
3f8aa1efecdcc545e6225179a656c080
15.351351
53
0.52649
3.300546
false
false
false
false
quarck/CalendarNotification
app/src/main/java/com/github/quarck/calnotify/calendareditor/CalendarChangeManager.kt
1
10424
// // Calendar Notifications Plus // Copyright (C) 2017 Sergey Parshin ([email protected]) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // package com.github.quarck.calnotify.calendareditor import android.content.Context import com.github.quarck.calnotify.Consts import com.github.quarck.calnotify.app.ApplicationController import com.github.quarck.calnotify.calendar.* import com.github.quarck.calnotify.calendareditor.storage.* import com.github.quarck.calnotify.logs.DevLog import com.github.quarck.calnotify.permissions.PermissionsManager class CalendarChangeManager(val provider: CalendarProviderInterface): CalendarChangeManagerInterface { override fun createEvent(context: Context, calendarId: Long, calendarOwnerAccount: String, details: CalendarEventDetails): Long { var eventId = -1L DevLog.info(LOG_TAG, "Request to create an event") if (!PermissionsManager.hasAllCalendarPermissions(context)) { DevLog.error(LOG_TAG, "createEvent: no permissions"); return -1L; } val event = CalendarChangeRequest( id = -1L, type = EventChangeRequestType.AddNewEvent, calendarOwnerAccount = calendarOwnerAccount, eventId = -1L, calendarId = calendarId, details = details, oldDetails = CalendarEventDetails.createEmpty() ) CalendarChangeRequestsStorage(context).use { db -> db.add(event) DevLog.info(LOG_TAG, "Event creation request logged") eventId = provider.createEvent(context, event.calendarId, event.calendarOwnerAccount, event.details) if (eventId != -1L) { DevLog.info(LOG_TAG, "Created new event, id $eventId") event.eventId = eventId db.update(event) } else { DevLog.info(LOG_TAG, "Failed to create a new event, will retry later") } } if (eventId != -1L) { ApplicationController.CalendarMonitor.onEventEditedByUs(context, eventId); } return eventId } override fun moveEvent(context: Context, event: EventAlertRecord, addTimeMillis: Long): Boolean { var ret = false if (!PermissionsManager.hasAllCalendarPermissions(context)) { DevLog.error(LOG_TAG, "moveEvent: no permissions"); return false; } CalendarChangeRequestsStorage(context).use { db -> db.deleteForEventId(event.eventId) // Get full event details from the provider, if failed - construct a failback version val oldDetails = provider.getEvent(context, event.eventId)?.details ?: CalendarEventDetails( title = event.title, desc = "", location = event.location, timezone = "", startTime = event.startTime, endTime = event.endTime, isAllDay = event.isAllDay, reminders = listOf<EventReminderRecord>(EventReminderRecord.minutes(15)), color = event.color ) val newStartTime: Long val newEndTime: Long val currentTime = System.currentTimeMillis() val numSecondsInThePast = currentTime + Consts.ALARM_THRESHOLD - event.startTime if (numSecondsInThePast > 0) { val addUnits = numSecondsInThePast / addTimeMillis + 1 newStartTime = event.startTime + addTimeMillis * addUnits newEndTime = event.endTime + addTimeMillis * addUnits DevLog.warn(LOG_TAG, "Requested time is already in the past, total added time: ${addTimeMillis * addUnits}") } else { newStartTime = event.startTime + addTimeMillis newEndTime = event.endTime + addTimeMillis } DevLog.info(LOG_TAG, "Moving event ${event.eventId} from ${event.startTime} / ${event.endTime} to $newStartTime / $newEndTime") ret = provider.moveEvent(context, event.eventId, newStartTime, newEndTime) event.startTime = newStartTime event.endTime = newEndTime DevLog.info(LOG_TAG, "Provider move event for ${event.eventId} result: $ret") val newDetails = oldDetails.copy(startTime = newStartTime, endTime = newEndTime) DevLog.info(LOG_TAG, "Adding move request into DB: move: ${event.eventId} ${oldDetails.startTime} / ${oldDetails.endTime} -> ${newDetails.startTime} / ${newDetails.endTime}") db.add( CalendarChangeRequest( id = -1L, type = EventChangeRequestType.MoveExistingEvent, eventId = event.eventId, calendarId = event.calendarId, calendarOwnerAccount = "", status = EventChangeStatus.Dirty, details = newDetails, oldDetails = oldDetails ) ) } if (event.eventId != -1L) { ApplicationController.CalendarMonitor.onEventEditedByUs(context, event.eventId); } return ret } override fun moveRepeatingAsCopy(context: Context, calendar: CalendarRecord, event: EventAlertRecord, addTimeMillis: Long): Long { if (!PermissionsManager.hasAllCalendarPermissions(context)) { DevLog.error(LOG_TAG, "moveRepeatingAsCopy: no permissions"); return -1L } // Get full event details from the provider, if failed - construct a failback version val oldEvent = provider.getEvent(context, event.eventId) ?: return -1L val newStartTime: Long val newEndTime: Long val currentTime = System.currentTimeMillis() val numSecondsInThePast = currentTime + Consts.ALARM_THRESHOLD - event.instanceStartTime if (numSecondsInThePast > 0) { val addUnits = numSecondsInThePast / addTimeMillis + 1 newStartTime = event.instanceStartTime + addTimeMillis * addUnits newEndTime = event.instanceEndTime + addTimeMillis * addUnits DevLog.warn(LOG_TAG, "Requested time is already in the past, total added time: ${addTimeMillis * addUnits}") } else { newStartTime = event.instanceStartTime + addTimeMillis newEndTime = event.instanceEndTime + addTimeMillis } DevLog.info(LOG_TAG, "Moving event ${event.eventId} from ${event.startTime} / ${event.endTime} to $newStartTime / $newEndTime") val details = oldEvent.details.copy( startTime = newStartTime, endTime = newEndTime, repeatingRule = "", repeatingRDate = "", repeatingExRule = "", repeatingExRDate = "" ) val ret = createEvent(context, calendar.calendarId, calendar.owner, details) if (ret != -1L) { event.startTime = newStartTime event.endTime = newEndTime } return ret } override fun updateEvent(context: Context, eventToEdit: EventRecord, details: CalendarEventDetails): Boolean { if (!PermissionsManager.hasAllCalendarPermissions(context)) { DevLog.error(LOG_TAG, "updateEvent: no permissions"); return false; } var ret = false CalendarChangeRequestsStorage(context).use { db -> db.deleteForEventId(eventToEdit.eventId) ret = provider.updateEvent(context, eventToEdit, details) if (ret) { DevLog.info(LOG_TAG, "Successfully updated provider, event ${eventToEdit.eventId}") } else { DevLog.error(LOG_TAG, "Failed to updated provider, event ${eventToEdit.eventId}") } DevLog.info(LOG_TAG, "Adding edit request into DB: ${eventToEdit.eventId} ") db.add( CalendarChangeRequest( id = -1L, type = EventChangeRequestType.EditExistingEvent, eventId = eventToEdit.eventId, calendarId = eventToEdit.calendarId, calendarOwnerAccount = "", status = EventChangeStatus.Dirty, details = details, oldDetails = eventToEdit.details ) ) } if (ret && (eventToEdit.startTime != details.startTime)) { DevLog.info(LOG_TAG, "Event ${eventToEdit.eventId} was moved, ${eventToEdit.startTime} != ${details.startTime}, checking for notification auto-dismissal") val newEvent = provider.getEvent(context, eventToEdit.eventId) if (newEvent != null) { ApplicationController.onCalendarEventMovedWithinApp( context, eventToEdit, newEvent ) } } if (eventToEdit.eventId != -1L) { ApplicationController.CalendarMonitor.onEventEditedByUs(context, eventToEdit.eventId); } return ret } companion object { const val LOG_TAG = "CalendarChangeMonitor" } }
gpl-3.0
42e12e537bfcee122535889f99da59c7
36.909091
186
0.585092
5.102301
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/economy/SonhosTopLocalCommand.kt
1
2289
package net.perfectdreams.loritta.morenitta.commands.vanilla.economy import net.perfectdreams.loritta.morenitta.tables.GuildProfiles import net.perfectdreams.loritta.morenitta.tables.Profiles import net.perfectdreams.loritta.morenitta.utils.Constants import net.perfectdreams.loritta.morenitta.messages.LorittaReply import net.perfectdreams.loritta.common.utils.image.JVMImage import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.platform.discord.legacy.commands.DiscordAbstractCommandBase import net.perfectdreams.loritta.morenitta.utils.OutdatedCommandUtils import net.perfectdreams.loritta.morenitta.utils.RankingGenerator import org.jetbrains.exposed.sql.* class SonhosTopLocalCommand(loritta: LorittaBot) : DiscordAbstractCommandBase(loritta, listOf("sonhos top local", "atm top local"), net.perfectdreams.loritta.common.commands.CommandCategory.ECONOMY) { override fun command() = create { localizedDescription("commands.command.sonhostoplocal.description") executesDiscord { OutdatedCommandUtils.sendOutdatedCommandMessage(this, locale, "sonhos rank") var page = args.getOrNull(0)?.toLongOrNull() if (page != null && !RankingGenerator.isValidRankingPage(page)) { reply( LorittaReply( locale["commands.invalidRankingPage"], Constants.ERROR ) ) return@executesDiscord } if (page != null) page -= 1 if (page == null) page = 0 val userData = loritta.newSuspendedTransaction { Profiles.innerJoin(GuildProfiles, { Profiles.id }, { GuildProfiles.userId }) .select { GuildProfiles.guildId eq guild.idLong and (GuildProfiles.isInGuild eq true) }.orderBy(Profiles.money, SortOrder.DESC).limit(5, page * 5) .toList() } sendImage( JVMImage( RankingGenerator.generateRanking( loritta, guild.name, guild.iconUrl, userData.map { RankingGenerator.UserRankInformation( it[Profiles.id].value, "${it[Profiles.money]} sonhos" ) } ) { loritta.newSuspendedTransaction { GuildProfiles.update({ GuildProfiles.id eq it and (GuildProfiles.guildId eq guild.idLong) }) { it[isInGuild] = false } } null } ), "rank.png" ) } } }
agpl-3.0
42f4f0411f13b2581a435284bee80f68
30.805556
200
0.725644
4.015789
false
false
false
false
MaibornWolff/codecharta
analysis/filter/StructureModifier/src/main/kotlin/de/maibornwolff/codecharta/filter/structuremodifier/ParserDialog.kt
1
2141
package de.maibornwolff.codecharta.filter.structuremodifier import com.github.kinquirer.KInquirer import com.github.kinquirer.components.promptInput import com.github.kinquirer.components.promptInputNumber import de.maibornwolff.codecharta.tools.interactiveparser.ParserDialogInterface import java.math.BigDecimal class ParserDialog { companion object : ParserDialogInterface { override fun collectParserArgs(): List<String> { val inputFolderName = KInquirer.promptInput(message = "What is the cc.json file that has to be modified?") val outputFileName: String = KInquirer.promptInput( message = "What is the name of the output file?" ) val setRoot: String = KInquirer.promptInput(message = "What path within project to be extracted? (Optional)", default = "") val printLevels: BigDecimal = KInquirer.promptInputNumber(message = "How many print levels do you want to print? (Optional)", default = "0", hint = "0") val moveFrom: String = KInquirer.promptInput( message = "What are the nodes to be moved? (Optional)" ) var moveTo: String = "" if (moveFrom.isNotBlank()) { moveTo = KInquirer.promptInput( message = "Where to move them?" ) } val remove: String = KInquirer.promptInput( message = "What are the nodes to be removed? (Optional)" ) return listOfNotNull( inputFolderName, "--output-file=$outputFileName", if (printLevels.toInt() != 0) "--print-levels=$printLevels" else null, if (setRoot.isNotBlank()) "--set-root=$setRoot" else null, if (moveFrom.isNotBlank()) "--move-from=$moveFrom" else null, if (moveFrom.isNotBlank()) "--move-to=$moveTo" else null, if (remove.isNotBlank()) "--remove=$remove" else null, ) } } }
bsd-3-clause
8b3d46f3699f1dca9b32a695d9ca23ae
42.693878
142
0.579636
5.184019
false
false
false
false
proxer/ProxerAndroid
src/main/kotlin/me/proxer/app/info/translatorgroup/TranslatorGroupActivity.kt
1
3368
package me.proxer.app.info.translatorgroup import android.app.Activity import android.view.Menu import android.view.MenuItem import androidx.core.app.ShareCompat import androidx.viewpager2.adapter.FragmentStateAdapter import com.google.android.material.tabs.TabLayout import com.google.android.material.tabs.TabLayoutMediator import com.mikepenz.iconics.utils.IconicsMenuInflaterUtil import me.proxer.app.R import me.proxer.app.base.ImageTabsActivity import me.proxer.app.util.extension.getSafeStringExtra import me.proxer.app.util.extension.startActivity import me.proxer.app.util.extension.unsafeLazy import me.proxer.library.util.ProxerUrls import okhttp3.HttpUrl /** * @author Ruben Gees */ class TranslatorGroupActivity : ImageTabsActivity() { companion object { private const val ID_EXTRA = "id" private const val NAME_EXTRA = "name" fun navigateTo(context: Activity, id: String, name: String? = null) { context.startActivity<TranslatorGroupActivity>( ID_EXTRA to id, NAME_EXTRA to name ) } } val id: String get() = intent.getSafeStringExtra(ID_EXTRA) var name: String? get() = intent.getStringExtra(NAME_EXTRA) set(value) { intent.putExtra(NAME_EXTRA, value) title = value } override val headerImageUrl: HttpUrl by unsafeLazy { ProxerUrls.translatorGroupImage(id) } override val sectionsPagerAdapter: FragmentStateAdapter by unsafeLazy { SectionsPagerAdapter() } override val sectionsTabCallback: TabLayoutMediator.TabConfigurationStrategy by unsafeLazy { SectionsTabCallback() } override fun onCreateOptionsMenu(menu: Menu): Boolean { IconicsMenuInflaterUtil.inflate(menuInflater, this, R.menu.activity_share, menu, true) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_share -> name?.let { ShareCompat.IntentBuilder(this) .setText(getString(R.string.share_translator_group, it, ProxerUrls.translatorGroupWeb(id))) .setType("text/plain") .setChooserTitle(getString(R.string.share_title)) .startChooser() } } return super.onOptionsItemSelected(item) } override fun setupToolbar() { super.setupToolbar() title = name } private inner class SectionsPagerAdapter : FragmentStateAdapter(supportFragmentManager, lifecycle) { override fun getItemCount() = 2 override fun createFragment(position: Int) = when (position) { 0 -> TranslatorGroupInfoFragment.newInstance() 1 -> TranslatorGroupProjectFragment.newInstance() else -> error("Unknown index passed: $position") } } private inner class SectionsTabCallback : TabLayoutMediator.TabConfigurationStrategy { override fun onConfigureTab(tab: TabLayout.Tab, position: Int) { tab.text = when (position) { 0 -> getString(R.string.section_translator_group_info) 1 -> getString(R.string.section_translator_group_projects) else -> error("Unknown index passed: $position") } } } }
gpl-3.0
ead88f9cf1666dc8ac51e76029cc0447
33.367347
120
0.671912
4.757062
false
false
false
false
nt-ca-aqe/library-app
library-service/src/test/kotlin/library/service/api/books/BooksControllerIntTest.kt
1
50692
package library.service.api.books import io.mockk.every import io.mockk.mockk import library.service.business.books.BookCollection import library.service.business.books.BookDataStore import library.service.business.books.BookIdGenerator import library.service.business.books.domain.BookRecord import library.service.business.books.domain.composites.Book import library.service.business.books.domain.types.Author import library.service.business.books.domain.types.BookId import library.service.business.books.domain.types.Borrower import library.service.correlation.CorrelationIdHolder import library.service.security.UserContext import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest import org.springframework.boot.test.context.TestConfiguration import org.springframework.context.annotation.Bean import org.springframework.hateoas.MediaTypes.HAL_JSON import org.springframework.http.MediaType.APPLICATION_JSON import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.* import org.springframework.test.web.servlet.result.MockMvcResultHandlers import org.springframework.test.web.servlet.result.MockMvcResultMatchers.content import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status import utils.Books import utils.MutableClock import utils.ResetMocksAfterEachTest import utils.classification.IntegrationTest import java.time.Clock import java.time.OffsetDateTime import java.util.* @IntegrationTest @ResetMocksAfterEachTest @WebMvcTest(BooksController::class) internal class BooksControllerIntTest( @Autowired val bookDataStore: BookDataStore, @Autowired val bookIdGenerator: BookIdGenerator, @Autowired val mockMvc: MockMvc, @Autowired val clock: MutableClock, @Autowired val userContext: UserContext ) { @TestConfiguration class AdditionalBeans { @Bean fun correlationIdHolder() = CorrelationIdHolder() @Bean fun userContenxt() = mockk<UserContext>() @Bean fun bookResourceAssembler(userContext: UserContext) = BookResourceAssembler(userContext) @Bean fun bookCollection(clock: Clock) = BookCollection( clock = clock, dataStore = bookDataStore(), idGenerator = bookIdGenerator(), eventDispatcher = mockk(relaxed = true) ) @Bean fun bookDataStore(): BookDataStore = mockk() @Bean fun bookIdGenerator(): BookIdGenerator = mockk() } val correlationId = UUID.randomUUID().toString() @BeforeEach fun setTime() { clock.setFixedTime("2017-08-20T12:34:56.789Z") } @BeforeEach fun initMocks() { every { bookDataStore.findById(any()) } returns null every { bookDataStore.createOrUpdate(any()) } answers { firstArg() } every { userContext.isCurator() } returns true } @DisplayName("/api/books") @Nested inner class BooksEndpoint { @DisplayName("GET") @Nested inner class GetMethod { @Test fun `when there are no books, the response only contains a self link`() { every { bookDataStore.findAll() } returns emptyList() val request = get("/api/books") val expectedResponse = """ { "_links": { "self": { "href": "http://localhost/api/books" } } } """ mockMvc.perform(request) .andExpect(status().isOk) .andExpect(content().contentType(HAL_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `when there are books, the response contains them with all relevant links`() { val availableBook = availableBook( id = BookId.from("883a2931-325b-4482-8972-8cb6f7d33816"), book = Books.CLEAN_CODE ) val borrowedBook = borrowedBook( id = BookId.from("53397dc0-932d-4198-801a-3e00b2742ba7"), book = Books.CLEAN_CODER, borrowedBy = "Uncle Bob", borrowedOn = "2017-08-20T12:34:56.789Z" ) every { bookDataStore.findAll() } returns listOf(availableBook, borrowedBook) val request = get("/api/books") val expectedResponse = """ { "_embedded": { "books": [ { "isbn": "${Books.CLEAN_CODE.isbn}", "title": "${Books.CLEAN_CODE.title}", "authors": ${Books.CLEAN_CODE.authors.toJson()}, "numberOfPages": ${Books.CLEAN_CODE.numberOfPages}, "_links": { "self": { "href": "http://localhost/api/books/883a2931-325b-4482-8972-8cb6f7d33816" }, "delete": { "href": "http://localhost/api/books/883a2931-325b-4482-8972-8cb6f7d33816" }, "borrow": { "href": "http://localhost/api/books/883a2931-325b-4482-8972-8cb6f7d33816/borrow" } } }, { "isbn": "${Books.CLEAN_CODER.isbn}", "title": "${Books.CLEAN_CODER.title}", "authors": ${Books.CLEAN_CODER.authors.toJson()}, "numberOfPages": ${Books.CLEAN_CODER.numberOfPages}, "borrowed": { "by": "Uncle Bob", "on": "2017-08-20T12:34:56.789Z" }, "_links": { "self": { "href": "http://localhost/api/books/53397dc0-932d-4198-801a-3e00b2742ba7" }, "delete": { "href": "http://localhost/api/books/53397dc0-932d-4198-801a-3e00b2742ba7" }, "return": { "href": "http://localhost/api/books/53397dc0-932d-4198-801a-3e00b2742ba7/return" } } } ] }, "_links": { "self": { "href": "http://localhost/api/books" } } } """ mockMvc.perform(request) .andDo(MockMvcResultHandlers.print()) .andExpect(status().isOk) .andExpect(content().contentType(HAL_JSON)) .andExpect(content().json(expectedResponse, true)) } } @DisplayName("POST") @Nested inner class PostMethod { @Test fun `creates a book and responds with its resource representation`() { val bookId = BookId.generate() every { bookIdGenerator.generate() } returns bookId val requestBody = """ { "isbn": "9780132350884", "title": "Clean Code: A Handbook of Agile Software Craftsmanship" } """ val request = post("/api/books") .contentType(APPLICATION_JSON) .content(requestBody) val expectedResponse = """ { "isbn": "9780132350884", "title": "Clean Code: A Handbook of Agile Software Craftsmanship", "authors": [], "_links": { "self": { "href": "http://localhost/api/books/$bookId" }, "delete": { "href": "http://localhost/api/books/$bookId" }, "borrow": { "href": "http://localhost/api/books/$bookId/borrow" } } } """ mockMvc.perform(request) .andExpect(status().isCreated) .andExpect(content().contentType(HAL_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `400 BAD REQUEST for invalid ISBN`() { val requestBody = """ { "isbn": "abcdefghij", "title": "Clean Code: A Handbook of Agile Software Craftsmanship" } """ val request = post("/api/books") .header("X-Correlation-ID", correlationId) .contentType(APPLICATION_JSON) .content(requestBody) val expectedResponse = """ { "status": 400, "error": "Bad Request", "timestamp": "2017-08-20T12:34:56.789Z", "correlationId": "$correlationId", "message": "The request's body is invalid. See details...", "details": ["The field 'isbn' must match \"(\\d{3}-?)?\\d{10}\"."] } """ mockMvc.perform(request) .andExpect(status().isBadRequest) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `400 BAD REQUEST for missing required properties`() { val request = post("/api/books") .header("X-Correlation-ID", correlationId) .contentType(APPLICATION_JSON) .content(" { } ") val expectedResponse = """ { "status": 400, "error": "Bad Request", "timestamp": "2017-08-20T12:34:56.789Z", "correlationId": "$correlationId", "message": "The request's body is invalid. See details...", "details": [ "The field 'isbn' must not be blank.", "The field 'title' must not be blank." ] } """ mockMvc.perform(request) .andExpect(status().isBadRequest) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `400 BAD REQUEST for malformed request`() { val request = post("/api/books") .header("X-Correlation-ID", correlationId) val expectedResponse = """ { "status": 400, "error": "Bad Request", "timestamp": "2017-08-20T12:34:56.789Z", "correlationId": "$correlationId", "message": "The request's body could not be read. It is either empty or malformed." } """ mockMvc.perform(request) .andExpect(status().isBadRequest) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(content().json(expectedResponse, true)) } } @DisplayName("/api/books/{id}") @Nested inner class BookByIdEndpoint { val id = BookId.generate() val book = Books.CLEAN_CODE val availableBookRecord = availableBook(id, book) val borrowedBookRecord = borrowedBook(id, book, "Uncle Bob", "2017-08-20T12:34:56.789Z") @DisplayName("GET") @Nested inner class GetMethod { @Test fun `responds with book's resource representation for existing available book`() { every { bookDataStore.findById(id) } returns availableBookRecord val request = get("/api/books/$id") val expectedResponse = """ { "isbn": "${Books.CLEAN_CODE.isbn}", "title": "${Books.CLEAN_CODE.title}", "authors": ${Books.CLEAN_CODE.authors.toJson()}, "numberOfPages": ${Books.CLEAN_CODE.numberOfPages}, "_links": { "self": { "href": "http://localhost/api/books/$id" }, "delete": { "href": "http://localhost/api/books/$id" }, "borrow": { "href": "http://localhost/api/books/$id/borrow" } } } """ mockMvc.perform(request) .andExpect(status().isOk) .andExpect(content().contentType(HAL_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `responds with book's resource representation for existing borrowed book`() { every { bookDataStore.findById(id) } returns borrowedBookRecord val request = get("/api/books/$id") val expectedResponse = """ { "isbn": "${Books.CLEAN_CODE.isbn}", "title": "${Books.CLEAN_CODE.title}", "authors": ${Books.CLEAN_CODE.authors.toJson()}, "numberOfPages": ${Books.CLEAN_CODE.numberOfPages}, "borrowed": { "by": "Uncle Bob", "on": "2017-08-20T12:34:56.789Z" }, "_links": { "self": { "href": "http://localhost/api/books/$id" }, "delete": { "href": "http://localhost/api/books/$id" }, "return": { "href": "http://localhost/api/books/$id/return" } } } """ mockMvc.perform(request) .andExpect(status().isOk) .andExpect(content().contentType(HAL_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `404 NOT FOUND for non-existing book`() { val request = get("/api/books/$id") .header("X-Correlation-ID", correlationId) val expectedResponse = """ { "status": 404, "error": "Not Found", "timestamp": "2017-08-20T12:34:56.789Z", "correlationId": "$correlationId", "message": "The book with ID: $id does not exist!" } """ mockMvc.perform(request) .andExpect(status().isNotFound) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `400 BAD REQUEST for malformed ID`() { val request = get("/api/books/malformed-id") .header("X-Correlation-ID", correlationId) val expectedResponse = """ { "status": 400, "error": "Bad Request", "timestamp": "2017-08-20T12:34:56.789Z", "correlationId": "$correlationId", "message": "The request's 'id' parameter is malformed." } """ mockMvc.perform(request) .andExpect(status().isBadRequest) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(content().json(expectedResponse, true)) } } @DisplayName("DELETE") @Nested inner class DeleteMethod { @Test fun `existing book is deleted and response is empty 204 NO CONTENT`() { every { bookDataStore.findById(id) } returns availableBookRecord every { bookDataStore.delete(availableBookRecord) } returns Unit mockMvc.perform(delete("/api/books/$id")) .andExpect(status().isNoContent) } @Test fun `404 NOT FOUND for non-existing book`() { val request = delete("/api/books/$id") .header("X-Correlation-ID", correlationId) val expectedResponse = """ { "status": 404, "error": "Not Found", "timestamp": "2017-08-20T12:34:56.789Z", "correlationId": "$correlationId", "message": "The book with ID: $id does not exist!" } """ mockMvc.perform(request) .andExpect(status().isNotFound) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `400 BAD REQUEST for malformed ID`() { val request = delete("/api/books/malformed-id") .header("X-Correlation-ID", correlationId) val expectedResponse = """ { "status": 400, "error": "Bad Request", "timestamp": "2017-08-20T12:34:56.789Z", "correlationId": "$correlationId", "message": "The request's 'id' parameter is malformed." } """ mockMvc.perform(request) .andExpect(status().isBadRequest) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(content().json(expectedResponse, true)) } } @DisplayName("/api/books/{id}/authors") @Nested inner class BookByIdAuthorsEndpoint { @DisplayName("PUT") @Nested inner class PutMethod { @Test fun `replaces authors of book and responds with its resource representation`() { every { bookDataStore.findById(id) } returns availableBookRecord val request = put("/api/books/$id/authors") .contentType(APPLICATION_JSON) .content(""" { "authors": ["Foo", "Bar"] } """) val expectedResponse = """ { "isbn": "${book.isbn}", "title": "${book.title}", "authors": ["Foo", "Bar"], "numberOfPages": ${book.numberOfPages}, "_links": { "self": { "href": "http://localhost/api/books/$id" }, "delete": { "href": "http://localhost/api/books/$id" }, "borrow": { "href": "http://localhost/api/books/$id/borrow" } } } """ mockMvc.perform(request) .andExpect(status().isOk) .andExpect(content().contentType(HAL_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `404 NOT FOUND for non-existing book`() { val request = put("/api/books/$id/authors") .header("X-Correlation-ID", correlationId) .contentType(APPLICATION_JSON) .content(""" { "authors": ["Foo", "Bar"] } """) val expectedResponse = """ { "status": 404, "error": "Not Found", "timestamp": "2017-08-20T12:34:56.789Z", "correlationId": "$correlationId", "message": "The book with ID: $id does not exist!" } """ mockMvc.perform(request) .andExpect(status().isNotFound) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `400 BAD REQUEST for missing required properties`() { val request = put("/api/books/$id/authors") .header("X-Correlation-ID", correlationId) .contentType(APPLICATION_JSON) .content(" { } ") val expectedResponse = """ { "status": 400, "error": "Bad Request", "timestamp": "2017-08-20T12:34:56.789Z", "correlationId": "$correlationId", "message": "The request's body is invalid. See details...", "details": [ "The field 'authors' must not be empty." ] } """ mockMvc.perform(request) .andExpect(status().isBadRequest) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(content().json(expectedResponse, true)) } } @DisplayName("DELETE") @Nested inner class DeleteMethod { @Test fun `removes authors from book and responds with its resource representation`() { every { bookDataStore.findById(id) } returns availableBookRecord val request = delete("/api/books/$id/authors") val expectedResponse = """ { "isbn": "${book.isbn}", "title": "${book.title}", "authors": [], "numberOfPages": ${book.numberOfPages}, "_links": { "self": { "href": "http://localhost/api/books/$id" }, "delete": { "href": "http://localhost/api/books/$id" }, "borrow": { "href": "http://localhost/api/books/$id/borrow" } } } """ mockMvc.perform(request) .andExpect(status().isOk) .andExpect(content().contentType(HAL_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `404 NOT FOUND for non-existing book`() { val request = delete("/api/books/$id/authors") .header("X-Correlation-ID", correlationId) val expectedResponse = """ { "status": 404, "error": "Not Found", "timestamp": "2017-08-20T12:34:56.789Z", "correlationId": "$correlationId", "message": "The book with ID: $id does not exist!" } """ mockMvc.perform(request) .andExpect(status().isNotFound) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(content().json(expectedResponse, true)) } } } @DisplayName("/api/books/{id}/borrow") @Nested inner class BookByIdBorrowEndpoint { @DisplayName("POST") @Nested inner class PostMethod { @Test fun `borrows book and responds with its updated resource representation`() { every { bookDataStore.findById(id) } returns availableBookRecord val request = post("/api/books/$id/borrow") .contentType(APPLICATION_JSON) .content(""" { "borrower": "Uncle Bob" } """) val expectedResponse = """ { "isbn": "${Books.CLEAN_CODE.isbn}", "title": "${Books.CLEAN_CODE.title}", "authors": ${Books.CLEAN_CODE.authors.toJson()}, "numberOfPages": ${Books.CLEAN_CODE.numberOfPages}, "borrowed": { "by": "Uncle Bob", "on": "2017-08-20T12:34:56.789Z" }, "_links": { "self": { "href": "http://localhost/api/books/$id" }, "delete": { "href": "http://localhost/api/books/$id" }, "return": { "href": "http://localhost/api/books/$id/return" } } } """ mockMvc.perform(request) .andExpect(status().isOk) .andExpect(content().contentType(HAL_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `409 CONFLICT for already borrowed book`() { every { bookDataStore.findById(id) } returns borrowedBookRecord val request = post("/api/books/$id/borrow") .header("X-Correlation-ID", correlationId) .contentType(APPLICATION_JSON) .content(""" { "borrower": "Uncle Bob" } """) val expectedResponse = """ { "status": 409, "error": "Conflict", "timestamp": "2017-08-20T12:34:56.789Z", "correlationId": "$correlationId", "message": "The book with ID: $id is already borrowed!" } """ mockMvc.perform(request) .andExpect(status().isConflict) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `404 NOT FOUND for non-existing book`() { val request = post("/api/books/$id/borrow") .header("X-Correlation-ID", correlationId) .contentType(APPLICATION_JSON) .content(""" { "borrower": "Uncle Bob" } """) val expectedResponse = """ { "status": 404, "error": "Not Found", "timestamp": "2017-08-20T12:34:56.789Z", "correlationId": "$correlationId", "message": "The book with ID: $id does not exist!" } """ mockMvc.perform(request) .andExpect(status().isNotFound) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `400 BAD REQUEST for missing required properties`() { val request = post("/api/books/$id/borrow") .header("X-Correlation-ID", correlationId) .contentType(APPLICATION_JSON) .content(" { } ") val expectedResponse = """ { "status": 400, "error": "Bad Request", "timestamp": "2017-08-20T12:34:56.789Z", "correlationId": "$correlationId", "message": "The request's body is invalid. See details...", "details": [ "The field 'borrower' must not be null." ] } """ mockMvc.perform(request) .andExpect(status().isBadRequest) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `400 BAD REQUEST for malformed request`() { val request = post("/api/books/$id/borrow") .header("X-Correlation-ID", correlationId) val expectedResponse = """ { "status": 400, "error": "Bad Request", "timestamp": "2017-08-20T12:34:56.789Z", "correlationId": "$correlationId", "message": "The request's body could not be read. It is either empty or malformed." } """ mockMvc.perform(request) .andExpect(status().isBadRequest) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `400 BAD REQUEST for malformed ID`() { val request = post("/api/books/malformed-id/borrow") .header("X-Correlation-ID", correlationId) val expectedResponse = """ { "status": 400, "error": "Bad Request", "timestamp": "2017-08-20T12:34:56.789Z", "correlationId": "$correlationId", "message": "The request's 'id' parameter is malformed." } """ mockMvc.perform(request) .andExpect(status().isBadRequest) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(content().json(expectedResponse, true)) } } } @DisplayName("/api/books/{id}/numberOfPages") @Nested inner class BookByIdNumberOfPagesEndpoint { @DisplayName("PUT") @Nested inner class PutMethod { @Test fun `replaces number of pages of book and responds with its resource representation`() { every { bookDataStore.findById(id) } returns availableBookRecord val request = put("/api/books/$id/numberOfPages") .contentType(APPLICATION_JSON) .content(""" { "numberOfPages": 128 } """) val expectedResponse = """ { "isbn": "${book.isbn}", "title": "${book.title}", "authors": ${book.authors.toJson()}, "numberOfPages": 128, "_links": { "self": { "href": "http://localhost/api/books/$id" }, "delete": { "href": "http://localhost/api/books/$id" }, "borrow": { "href": "http://localhost/api/books/$id/borrow" } } } """ mockMvc.perform(request) .andExpect(status().isOk) .andExpect(content().contentType(HAL_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `404 NOT FOUND for non-existing book`() { val request = put("/api/books/$id/numberOfPages") .header("X-Correlation-ID", correlationId) .contentType(APPLICATION_JSON) .content(""" { "numberOfPages": 128 } """) val expectedResponse = """ { "status": 404, "error": "Not Found", "timestamp": "2017-08-20T12:34:56.789Z", "correlationId": "$correlationId", "message": "The book with ID: $id does not exist!" } """ mockMvc.perform(request) .andExpect(status().isNotFound) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `400 BAD REQUEST for missing required properties`() { val idValue = BookId.generate().toString() val request = put("/api/books/$idValue/numberOfPages") .header("X-Correlation-ID", correlationId) .contentType(APPLICATION_JSON) .content(" { } ") val expectedResponse = """ { "status": 400, "error": "Bad Request", "timestamp": "2017-08-20T12:34:56.789Z", "correlationId": "$correlationId", "message": "The request's body is invalid. See details...", "details": [ "The field 'numberOfPages' must not be null." ] } """ mockMvc.perform(request) .andExpect(status().isBadRequest) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(content().json(expectedResponse, true)) } } @DisplayName("DELETE") @Nested inner class DeleteMethod { @Test fun `removes number of pages from book and responds with its resource representation`() { every { bookDataStore.findById(id) } returns availableBookRecord val request = delete("/api/books/$id/numberOfPages") val expectedResponse = """ { "isbn": "${book.isbn}", "title": "${book.title}", "authors": ${book.authors.toJson()}, "_links": { "self": { "href": "http://localhost/api/books/$id" }, "delete": { "href": "http://localhost/api/books/$id" }, "borrow": { "href": "http://localhost/api/books/$id/borrow" } } } """ mockMvc.perform(request) .andExpect(status().isOk) .andExpect(content().contentType(HAL_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `404 NOT FOUND for non-existing book`() { val request = delete("/api/books/$id/numberOfPages") .header("X-Correlation-ID", correlationId) val expectedResponse = """ { "status": 404, "error": "Not Found", "timestamp": "2017-08-20T12:34:56.789Z", "correlationId": "$correlationId", "message": "The book with ID: $id does not exist!" } """ mockMvc.perform(request) .andExpect(status().isNotFound) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(content().json(expectedResponse, true)) } } } @DisplayName("/api/books/{id}/return") @Nested inner class BookByIdReturnEndpoint { @DisplayName("POST") @Nested inner class PostMethod { @Test fun `returns book and responds with its updated resource representation`() { every { bookDataStore.findById(id) } returns borrowedBookRecord val request = post("/api/books/$id/return") val expectedResponse = """ { "isbn": "${Books.CLEAN_CODE.isbn}", "title": "${Books.CLEAN_CODE.title}", "authors": ${Books.CLEAN_CODE.authors.toJson()}, "numberOfPages": ${Books.CLEAN_CODE.numberOfPages}, "_links": { "self": { "href": "http://localhost/api/books/$id" }, "delete": { "href": "http://localhost/api/books/$id" }, "borrow": { "href": "http://localhost/api/books/$id/borrow" } } } """ mockMvc.perform(request) .andExpect(status().isOk) .andExpect(content().contentType(HAL_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `409 CONFLICT for already returned book`() { every { bookDataStore.findById(id) } returns availableBookRecord val request = post("/api/books/$id/return") .header("X-Correlation-ID", correlationId) val expectedResponse = """ { "status": 409, "error": "Conflict", "timestamp": "2017-08-20T12:34:56.789Z", "correlationId": "$correlationId", "message": "The book with ID: $id was already returned!" } """ mockMvc.perform(request) .andExpect(status().isConflict) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `404 NOT FOUND for non-existing book`() { val request = post("/api/books/$id/return") .header("X-Correlation-ID", correlationId) val expectedResponse = """ { "status": 404, "error": "Not Found", "timestamp": "2017-08-20T12:34:56.789Z", "correlationId": "$correlationId", "message": "The book with ID: $id does not exist!" } """ mockMvc.perform(request) .andExpect(status().isNotFound) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `400 BAD REQUEST for malformed ID`() { val request = post("/api/books/malformed-id/return") .header("X-Correlation-ID", correlationId) val expectedResponse = """ { "status": 400, "error": "Bad Request", "timestamp": "2017-08-20T12:34:56.789Z", "correlationId": "$correlationId", "message": "The request's 'id' parameter is malformed." } """ mockMvc.perform(request) .andExpect(status().isBadRequest) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(content().json(expectedResponse, true)) } } } @DisplayName("/api/books/{id}/title") @Nested inner class BookByIdTitleEndpoint { @DisplayName("PUT") @Nested inner class PutMethod { @Test fun `replaces title of book and responds with its resource representation`() { every { bookDataStore.findById(id) } returns availableBookRecord val request = put("/api/books/$id/title") .contentType(APPLICATION_JSON) .content(""" { "title": "New Title" } """) val expectedResponse = """ { "isbn": "${book.isbn}", "title": "New Title", "authors": ${book.authors.toJson()}, "numberOfPages": ${book.numberOfPages}, "_links": { "self": { "href": "http://localhost/api/books/$id" }, "delete": { "href": "http://localhost/api/books/$id" }, "borrow": { "href": "http://localhost/api/books/$id/borrow" } } } """ mockMvc.perform(request) .andExpect(status().isOk) .andExpect(content().contentType(HAL_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `404 NOT FOUND for non-existing book`() { val request = put("/api/books/$id/title") .header("X-Correlation-ID", correlationId) .contentType(APPLICATION_JSON) .content(""" { "title": "New Title" } """) val expectedResponse = """ { "status": 404, "error": "Not Found", "timestamp": "2017-08-20T12:34:56.789Z", "correlationId": "$correlationId", "message": "The book with ID: $id does not exist!" } """ mockMvc.perform(request) .andExpect(status().isNotFound) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(content().json(expectedResponse, true)) } @Test fun `400 BAD REQUEST for missing required properties`() { val idValue = BookId.generate().toString() val request = put("/api/books/$idValue/title") .header("X-Correlation-ID", correlationId) .contentType(APPLICATION_JSON) .content(" { } ") val expectedResponse = """ { "status": 400, "error": "Bad Request", "timestamp": "2017-08-20T12:34:56.789Z", "correlationId": "$correlationId", "message": "The request's body is invalid. See details...", "details": [ "The field 'title' must not be blank." ] } """ mockMvc.perform(request) .andExpect(status().isBadRequest) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(content().json(expectedResponse, true)) } } } } } private fun availableBook(id: BookId, book: Book) = BookRecord(id, book) private fun borrowedBook(id: BookId, book: Book, borrowedBy: String, borrowedOn: String) = availableBook(id, book) .borrow(Borrower(borrowedBy), OffsetDateTime.parse(borrowedOn)) private fun List<Author>.toJson() = joinToString(separator = "\", \"", prefix = "[\"", postfix = "\"]") }
apache-2.0
821eb9333844be40a58e8f2751e00a34
44.669369
118
0.39669
6.008297
false
false
false
false
christophpickl/kpotpourri
common4k/src/test/kotlin/com/github/christophpickl/kpotpourri/common/random/RandomListTest.kt
1
1806
package com.github.christophpickl.kpotpourri.common.random import com.github.christophpickl.kpotpourri.common.isBetween import com.github.christophpickl.kpotpourri.test4k.assertThrown import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.testng.annotations.Test @Test class RandomListTest { fun `Given single element When random Then return it`() { val list = randomListOf("a" to 100) assertThat(list.randomElement(), equalTo("a")) } fun `Given two elements one is bigger When random Then return mostly one`() { val list = randomListOf("a" to 90, "b" to 10) val randoms = randomSample(list) assertThat(randoms["a"], isBetween(70, 100)) assertThat(randoms["b"], isBetween(0, 30)) } fun `Given two elements both are same When random Then return both equally`() { val list = randomListOf("a" to 50, "b" to 50) val randoms = randomSample(list) assertThat(randoms["a"], isBetween(30, 70)) assertThat(randoms["b"], isBetween(30, 70)) } fun `When too less percentage Then fail`() { assertThrown<IllegalArgumentException> { randomListOf("a" to 0) } } fun `When too much percentage Then fail`() { assertThrown<IllegalArgumentException> { randomListOf("a" to 110) } } private val timesHundred = 100 private fun <E> randomSample(list: RandomList<E>) = (1..(100 * timesHundred)).map { list.randomElement() }.groupingBy { it }.eachCount().mapValues { it.value / timesHundred }.toMutableMap().fillMissing(list) private fun <K> MutableMap<K, Int>.fillMissing(list: RandomList<K>) = apply { list.filter { !containsKey(it) }.forEach { put(it, 0) } } }
apache-2.0
80e43aa58891afb4119d9a324f5101df
30.684211
106
0.6567
4.022272
false
true
false
false
ansman/kotshi
tests/src/main/kotlin/se/ansman/kotshi/QualifierWithArguments.kt
1
3566
package se.ansman.kotshi import com.squareup.moshi.JsonQualifier import kotlin.reflect.KClass @JsonQualifier @OptIn(ExperimentalUnsignedTypes::class) annotation class QualifierWithArguments( vararg val vararg: String, val booleanArg: Boolean, val byteArg: Byte, val ubyteArg: UByte, val charArg: Char, val shortArg: Short, val ushortArg: UShort, val intArg: Int, val uintArg: UInt, val longArg: Long, val ulongArg: ULong, val floatArg: Float, val doubleArg: Double, val stringArg: String, val emptyArray: BooleanArray, val booleanArrayArg: BooleanArray, val byteArrayArg: ByteArray, val ubyteArrayArg: UByteArray, val charArrayArg: CharArray, val shortArrayArg: ShortArray, val ushortArrayArg: UShortArray, val intArrayArg: IntArray, val uintArrayArg: UIntArray, val longArrayArg: LongArray, val ulongArrayArg: ULongArray, val floatArrayArg: FloatArray, val doubleArrayArg: DoubleArray, val stringArrayArg: Array<String>, val classArg: KClass<*>, val nestedArg: Nested, val enumArg: SomeEnum ) { annotation class Nested(val arg: String) } @OptIn(ExperimentalUnsignedTypes::class) @JsonSerializable data class ClassWithQualifierWithArguments( @QualifierWithArguments( "vararg", booleanArg = true, byteArg = 124, ubyteArg = 254u, shortArg = 10_000, ushortArg = 32_768u, charArg = 'K', intArg = 100_000, uintArg = 2147483648u, longArg = 100_000_000_000_000, ulongArg = 9_223_372_036_854_775_808u, floatArg = 1f, doubleArg = 2.0, stringArg = "string", emptyArray = [], booleanArrayArg = [true], byteArrayArg = [124], ubyteArrayArg = [254u], shortArrayArg = [10_000], ushortArrayArg = [32_768u], charArrayArg = ['K'], intArrayArg = [100_000], uintArrayArg = [2147483648u], longArrayArg = [100_000_000_000_000], ulongArrayArg = [9_223_372_036_854_775_808u], floatArrayArg = [47.11f], doubleArrayArg = [13.37], stringArrayArg = ["string"], classArg = QualifierWithArguments::class, nestedArg = QualifierWithArguments.Nested("nested"), enumArg = SomeEnum.VALUE3 ) val foo: String ) @OptIn(ExperimentalUnsignedTypes::class) @JsonSerializable data class ClassWithQualifierWithEscapedArguments( @QualifierWithArguments( "\"\"", booleanArg = true, byteArg = 124, ubyteArg = 254u, shortArg = 10_000, ushortArg = 32_768u, charArg = '\'', intArg = 100_000, uintArg = 2147483648u, longArg = 100_000_000_000_000, ulongArg = 9_223_372_036_854_775_808u, floatArg = 1f, doubleArg = 2.0, stringArg = "\"\"", emptyArray = [], booleanArrayArg = [true], byteArrayArg = [124], ubyteArrayArg = [254u], shortArrayArg = [10_000], ushortArrayArg = [32_768u], charArrayArg = ['\''], intArrayArg = [100_000], uintArrayArg = [2147483648u], longArrayArg = [100_000_000_000_000], ulongArrayArg = [9_223_372_036_854_775_808u], floatArrayArg = [47.11f], doubleArrayArg = [13.37], stringArrayArg = ["\"\""], classArg = QualifierWithArguments::class, nestedArg = QualifierWithArguments.Nested("\"\""), enumArg = SomeEnum.VALUE3 ) val foo: String )
apache-2.0
d346f1ef5962786fb2c83737188cecfa
28.446281
60
0.615665
3.773305
false
false
false
false
allen-garvey/photog-spark
src/main/kotlin/controllers/SqliteController.kt
1
23815
package controllers import models.* import java.sql.Connection import java.sql.SQLException import java.sql.DriverManager import java.io.File import java.sql.Timestamp /** * Created by allen on 3/29/17. */ /* * select name, albumType, albumSubclass from RKAlbum limit 1; select modelId, fileName, imagePath, imageDate from RKMaster order by modelId desc limit 1; -- select albums that an image is in select name from RKalbum where modelId in (select albumId from RKAlbumVersion where versionId in (select modelid from RKVersion where masterid = 13249)); --select images in album select imagePath from RKMaster where modelId in (select masterid from RKVersion where modelId in (select versionid from RKAlbumVersion where albumId = 3239)); -- select all albums select name from RKAlbum where name is not null and name != "" order by modelId desc; select rkalbum.modelId, rkalbum.name, rkmaster.modelid, rkmaster.imagepath from RKAlbum inner join rkversion on rkalbum.posterversionuuid = rkversion.uuid inner join rkmaster on rkversion.masterid = rkmaster.modelId where rkalbum.name is not null and rkalbum.name != "" order by rkalbum.modelId desc; --select cover photo for album select modelid, imagepath from rkmaster where modelid in (select masterid from rkversion where uuid in (select posterversionuuid from rkalbum where modelid = "3571")); --select folders select rkfolder.uuid, rkfolder.name from rkfolder where rkfolder.uuid in (select folderuuid from rkalbum where modelid in (select albumid from rkalbumversion)) and rkfolder.name is not "" order by rkfolder.name; --select cover image versions for person (need to convert rkversion.uuid to rkmaster.id) select rkperson.modelid as person_id, rkface.imageid as cover_image_version_uuid from rkperson inner join rkface on rkperson.representativeFaceId = rkface.modelid; * */ object SqliteController{ val ALBUM_TABLE = "RKAlbum" val VERSION_TABLE = "RKVersion" val MASTER_TABLE = "RKMaster" val ALBUM_VERSION_TABLE = "RKAlbumVersion" val THUMBNAIL_TABLE = "RKImageProxyState" val FOLDER_TABLE = "RKFolder" val PERSON_TABLE = "RKPerson" var FACE_TABLE = "RKFace" val PERSON_VERSION_TABLE = "RKPersonVersion" val CUSTOM_SORT_ORDER_TABLE = "RKCustomSortOrder" val IMPORT_TABLE = "RKImportGroup" val DATABASE_FOLDER = "data" val DATABASE_FILENAME_LIBRARY = "Library.apdb" val DATABASE_FILENAME_THUMBNAILS = "ImageProxies.apdb" val DATABASE_FILENAME_PERSON = "Person.db" var databaseRoot: String = System.getProperty("user.home") + "/Documents/Mac-Photos-Database" fun databasePathFor(databaseFilename: String): String{ return File(databaseRoot, databaseFilename).toString() } fun getConnection(databaseFilename: String): Connection? { val databasePath: String = databasePathFor(databaseFilename) try { // db parameters val url = "jdbc:sqlite:" + databasePath // create a connection to the database val conn = DriverManager.getConnection(url) return conn } catch (e: Exception) { println(e.message) return null } } fun executeOperation(databaseFilename: String, databaseOperation: (Connection)-> Unit) { val conn: Connection = getConnection(databaseFilename) ?: return try { databaseOperation(conn) } catch (e: SQLException) { println(e.message) } finally { try { conn.close() } catch (ex: SQLException) { println(ex.message) } } } fun selectAllAlbums() : MutableList<Album> { val albums : MutableList<Album> = mutableListOf() val sql = "select ${ALBUM_TABLE}.modelId as album_id, ${ALBUM_TABLE}.name as album_name, ${ALBUM_TABLE}.folderUuid as album_folder_uuid, ${MASTER_TABLE}.modelid as coverimage_id, ${VERSION_TABLE}.modelid as coverimage_version_id, ${MASTER_TABLE}.imagepath as coverimage_path, (SELECT ${CUSTOM_SORT_ORDER_TABLE}.orderNumber FROM ${CUSTOM_SORT_ORDER_TABLE} WHERE ${CUSTOM_SORT_ORDER_TABLE}.containerUuid = ${ALBUM_TABLE}.folderUuid AND ${CUSTOM_SORT_ORDER_TABLE}.objectUuid = ${ALBUM_TABLE}.uuid limit 1) AS folder_order, strftime('%s', datetime(${ALBUM_TABLE}.createdate, 'unixepoch', '+372 months')) AS album_timestamp FROM ${ALBUM_TABLE} inner join ${VERSION_TABLE} on ${ALBUM_TABLE}.posterversionuuid = ${VERSION_TABLE}.uuid inner join ${MASTER_TABLE} on ${VERSION_TABLE}.masterid = ${MASTER_TABLE}.modelId where ${ALBUM_TABLE}.name is not null and ${ALBUM_TABLE}.name != \"\" order by ${ALBUM_TABLE}.modelId desc" executeOperation(DATABASE_FILENAME_LIBRARY, { it -> val stmt = it.createStatement() val rs = stmt.executeQuery(sql) while (rs.next()) { albums.add( Album( rs.getString("album_id"), rs.getString("album_name"), rs.getString("album_folder_uuid"), Image( rs.getString("coverimage_id"), rs.getString("coverimage_version_id"), rs.getString("coverimage_path"), null, null, importUuid = null), rs.getInt("folder_order"), Timestamp(rs.getString("album_timestamp").toLong() * 1000) ) ) } }) val thumbnailSql = "SELECT minithumbnailpath, thumbnailpath FROM ${THUMBNAIL_TABLE} WHERE versionId = ?" albums.forEach { val album = it if(album.coverImage != null) { executeOperation(DATABASE_FILENAME_THUMBNAILS, { it -> val stmt = it.prepareStatement(thumbnailSql) stmt.setString(1, album.coverImage.versionId) val rs = stmt.executeQuery() while (rs.next()) { album.coverImage.thumbnail = Thumbnail(rs.getString("thumbnailpath"), rs.getString("minithumbnailpath")) } }) } } return albums } fun selectAlbum(albumId: String): Album?{ var album: Album? = null val sql = "select ${ALBUM_TABLE}.modelId as album_id, ${ALBUM_TABLE}.name as album_name, ${ALBUM_TABLE}.folderUuid as album_folder_uuid from ${ALBUM_TABLE} where album_id = ?" executeOperation(DATABASE_FILENAME_LIBRARY, { it -> val stmt = it.prepareStatement(sql) stmt.setString(1, albumId) val rs = stmt.executeQuery() while (rs.next()) { album = Album(rs.getString("album_id"), rs.getString("album_name"), rs.getString("album_folder_uuid"), null) } }) return album } fun imagesForAlbum(albumId: String): MutableList<Image>{ val images: MutableList<Image> = mutableListOf() val sql = "SELECT ${MASTER_TABLE}.modelId as master_id, ${VERSION_TABLE}.modelid as version_id, ${VERSION_TABLE}.isFavorite as is_favorite, ${MASTER_TABLE}.imagepath as master_imagepath, strftime('%s', datetime(${MASTER_TABLE}.imagedate, 'unixepoch', '+372 months', ${MASTER_TABLE}.imageTimeZoneOffsetSeconds || ' seconds')) AS master_timestamp, (SELECT ${CUSTOM_SORT_ORDER_TABLE}.orderNumber FROM ${CUSTOM_SORT_ORDER_TABLE} WHERE ${CUSTOM_SORT_ORDER_TABLE}.containerUuid = (SELECT ${ALBUM_TABLE}.Uuid from ${ALBUM_TABLE} WHERE ${ALBUM_TABLE}.modelId = ?) AND ${CUSTOM_SORT_ORDER_TABLE}.objectUuid = ${VERSION_TABLE}.uuid) AS sort_order FROM ${ALBUM_VERSION_TABLE} INNER JOIN ${VERSION_TABLE} ON ${VERSION_TABLE}.modelid = ${ALBUM_VERSION_TABLE}.versionid INNER JOIN ${MASTER_TABLE} ON ${MASTER_TABLE}.modelId = ${VERSION_TABLE}.masterid WHERE ${ALBUM_VERSION_TABLE}.albumId = ? ORDER BY sort_order" executeOperation(DATABASE_FILENAME_LIBRARY,{ it -> val stmt = it.prepareStatement(sql) stmt.setString(1, albumId) stmt.setString(2, albumId) val rs = stmt.executeQuery() while (rs.next()) { images.add(Image(rs.getString("master_id"), rs.getString("version_id"), rs.getString("master_imagepath"), Timestamp(rs.getString("master_timestamp").toLong() * 1000), null, rs.getBoolean("is_favorite"), importUuid = null)) } }) images.forEach { it.thumbnail = thumbnailForImage(it) } return images } fun thumbnailForImage(image: Image): Thumbnail{ var thumbnail: Thumbnail = Thumbnail("", "") val thumbnailSql = "SELECT minithumbnailpath, thumbnailpath FROM ${THUMBNAIL_TABLE} WHERE versionId = ?" executeOperation(DATABASE_FILENAME_THUMBNAILS, { it -> val stmt = it.prepareStatement(thumbnailSql) stmt.setString(1, image.versionId) val rs = stmt.executeQuery() while (rs.next()) { thumbnail = Thumbnail(rs.getString("thumbnailpath"), rs.getString("minithumbnailpath")) } }) return thumbnail } fun selectImage(imageId: String): Image?{ var image: Image? = null val sql = "SELECT ${MASTER_TABLE}.modelId as master_id, ${VERSION_TABLE}.modelid as version_id, ${VERSION_TABLE}.isFavorite as is_favorite, ${MASTER_TABLE}.imagepath as master_imagepath, strftime('%s', datetime(${MASTER_TABLE}.imagedate, 'unixepoch', '+372 months', ${MASTER_TABLE}.imageTimeZoneOffsetSeconds || ' seconds')) AS master_timestamp FROM ${MASTER_TABLE} INNER JOIN ${VERSION_TABLE} ON ${VERSION_TABLE}.masterId = ${MASTER_TABLE}.modelId WHERE master_id = ?" executeOperation(DATABASE_FILENAME_LIBRARY,{ it -> val stmt = it.prepareStatement(sql) stmt.setString(1, imageId) val rs = stmt.executeQuery() while (rs.next()) { image = Image(rs.getString("master_id"), rs.getString("version_id"), rs.getString("master_imagepath"), Timestamp(rs.getString("master_timestamp").toLong() * 1000), null, rs.getBoolean("is_favorite"), importUuid = null) } }) //compiler complains if we just check for null val safeImage: Image = image ?: return null safeImage.thumbnail = thumbnailForImage(safeImage) return safeImage } fun selectAllImages(): MutableList<Image>{ val images : MutableList<Image> = mutableListOf() val sql = "SELECT ${MASTER_TABLE}.modelId as master_id, ${VERSION_TABLE}.modelid as version_id, ${MASTER_TABLE}.importGroupUuid as import_uuid, ${VERSION_TABLE}.isFavorite as is_favorite, ${MASTER_TABLE}.imagepath as master_imagepath, strftime('%s', datetime(${MASTER_TABLE}.imagedate, 'unixepoch', '+372 months', ${MASTER_TABLE}.imageTimeZoneOffsetSeconds || ' seconds')) AS master_timestamp FROM ${MASTER_TABLE} INNER JOIN ${VERSION_TABLE} ON ${VERSION_TABLE}.masterId = ${MASTER_TABLE}.modelId ORDER BY master_id" executeOperation(DATABASE_FILENAME_LIBRARY,{ it -> val stmt = it.prepareStatement(sql) val rs = stmt.executeQuery() while (rs.next()) { val image = Image(rs.getString("master_id"), rs.getString("version_id"), rs.getString("master_imagepath"), Timestamp(rs.getString("master_timestamp").toLong() * 1000), null, rs.getBoolean("is_favorite"), rs.getString("import_uuid")) image.thumbnail = thumbnailForImage(image) images.add(image) } }) return images } fun albumsForImage(imageId: String): MutableList<Album>{ val albums: MutableList<Album> = mutableListOf() val sql = "select ${ALBUM_TABLE}.modelId as album_id, ${ALBUM_TABLE}.name as album_name, ${ALBUM_TABLE}.folderUuid as album_folder_uuid FROM ${ALBUM_TABLE} WHERE album_id IN (SELECT albumId from ${ALBUM_VERSION_TABLE} WHERE versionId IN (SELECT modelId from ${VERSION_TABLE} WHERE masterId = ?))" executeOperation(DATABASE_FILENAME_LIBRARY,{ it -> val stmt = it.prepareStatement(sql) stmt.setString(1, imageId) val rs = stmt.executeQuery() while (rs.next()) { albums.add(Album(rs.getString("album_id"), rs.getString("album_name"), rs.getString("album_folder_uuid"), null, null, null)) } }) return albums } fun selectFolder(folderUuid: String): Folder?{ var folder: Folder? = null val sql = "SELECT ${FOLDER_TABLE}.uuid as folder_uuid, ${FOLDER_TABLE}.name as folder_name FROM ${FOLDER_TABLE} WHERE folder_uuid is ? AND ${FOLDER_TABLE}.uuid in (SELECT folderuuid from ${ALBUM_TABLE} WHERE modelid in (select albumid from ${ALBUM_VERSION_TABLE})) and ${FOLDER_TABLE}.name is not \"\"" executeOperation(DATABASE_FILENAME_LIBRARY, { it -> val stmt = it.prepareStatement(sql) stmt.setString(1, folderUuid) val rs = stmt.executeQuery() while (rs.next()) { folder = Folder(rs.getString("folder_uuid"), rs.getString("folder_name")) } }) return folder } fun selectAllFolders() : MutableList<Folder> { val folders : MutableList<Folder> = mutableListOf() val sql = "SELECT ${FOLDER_TABLE}.uuid as folder_uuid, ${FOLDER_TABLE}.name as folder_name from ${FOLDER_TABLE} where ${FOLDER_TABLE}.uuid in (select folderuuid from ${ALBUM_TABLE} where modelid in (select albumid from ${ALBUM_VERSION_TABLE})) and ${FOLDER_TABLE}.name is not \"\" order by ${FOLDER_TABLE}.name" executeOperation(DATABASE_FILENAME_LIBRARY, { it -> val stmt = it.createStatement() val rs = stmt.executeQuery(sql) while (rs.next()) { folders.add(Folder(rs.getString("folder_uuid"), rs.getString("folder_name"))) } }) return folders } fun albumsForFolder(folderUuid: String): MutableList<Album>{ val albums : MutableList<Album> = mutableListOf() val sql = "SELECT ${ALBUM_TABLE}.modelId AS album_id, ${ALBUM_TABLE}.name AS album_name, ${MASTER_TABLE}.modelid AS coverimage_id, ${VERSION_TABLE}.modelid AS coverimage_version_id, ${MASTER_TABLE}.imagepath AS coverimage_path, (SELECT ${CUSTOM_SORT_ORDER_TABLE}.orderNumber FROM ${CUSTOM_SORT_ORDER_TABLE} WHERE ${CUSTOM_SORT_ORDER_TABLE}.containerUuid = ? AND ${CUSTOM_SORT_ORDER_TABLE}.objectUuid = ${ALBUM_TABLE}.uuid) AS sort_order FROM ${ALBUM_TABLE} INNER JOIN ${VERSION_TABLE} ON ${ALBUM_TABLE}.posterversionuuid = ${VERSION_TABLE}.uuid INNER JOIN ${MASTER_TABLE} ON ${VERSION_TABLE}.masterid = ${MASTER_TABLE}.modelId WHERE ${ALBUM_TABLE}.name IS NOT NULL AND ${ALBUM_TABLE}.name != \"\" AND ${ALBUM_TABLE}.folderUuid IS ? ORDER BY sort_order, ${ALBUM_TABLE}.modelId DESC" executeOperation(DATABASE_FILENAME_LIBRARY, { it -> val stmt = it.prepareStatement(sql) stmt.setString(1, folderUuid) stmt.setString(2, folderUuid) val rs = stmt.executeQuery() while (rs.next()) { albums.add(Album(rs.getString("album_id"), rs.getString("album_name"), folderUuid, Image(rs.getString("coverimage_id"), rs.getString("coverimage_version_id"), rs.getString("coverimage_path"), null, null, importUuid = null))) } }) val thumbnailSql = "SELECT minithumbnailpath, thumbnailpath FROM ${THUMBNAIL_TABLE} WHERE versionId = ?" albums.forEach { val album = it if(album.coverImage != null) { executeOperation(DATABASE_FILENAME_THUMBNAILS, { it -> val stmt = it.prepareStatement(thumbnailSql) stmt.setString(1, album.coverImage.versionId) val rs = stmt.executeQuery() while (rs.next()) { album.coverImage.thumbnail = Thumbnail(rs.getString("thumbnailpath"), rs.getString("minithumbnailpath")) } }) } } return albums } fun selectPerson(personId: String): Person?{ var person: Person? = null val sql = "SELECT ${PERSON_TABLE}.modelid as person_id, ${PERSON_TABLE}.name as person_name from ${PERSON_TABLE} where person_id = ?" executeOperation(DATABASE_FILENAME_PERSON, { it -> val stmt = it.prepareStatement(sql) stmt.setString(1, personId) val rs = stmt.executeQuery() while (rs.next()) { person = Person(rs.getString("person_id"), rs.getString("person_name")) } }) return person } fun selectAllPeople() : MutableList<Person> { val people : MutableList<Person> = mutableListOf() val sql = "SELECT ${PERSON_TABLE}.modelid AS person_id, ${PERSON_TABLE}.name AS person_name, ${FACE_TABLE}.imageid as cover_version_uuid FROM ${PERSON_TABLE} INNER JOIN ${FACE_TABLE} ON ${FACE_TABLE}.modelid = ${PERSON_TABLE}.representativeFaceId WHERE person_id IN (SELECT personid FROM ${PERSON_VERSION_TABLE}) ORDER BY ${PERSON_TABLE}.name" executeOperation(DATABASE_FILENAME_PERSON, { it -> val stmt = it.createStatement() val rs = stmt.executeQuery(sql) while (rs.next()) { people.add(Person(rs.getString("person_id"), rs.getString("person_name"), rs.getString("cover_version_uuid"))) } }) //translate rkversion.uuid to rkimage.modelId val versionSql = "SELECT ${MASTER_TABLE}.modelId as master_id, ${VERSION_TABLE}.uuid as version_uuid FROM ${VERSION_TABLE} INNER JOIN ${MASTER_TABLE} ON master_id = ${VERSION_TABLE}.masterid WHERE version_uuid = ?" executeOperation(DATABASE_FILENAME_LIBRARY,{ it -> val stmt = it.prepareStatement(versionSql) people.forEach { stmt.setString(1, it.coverImageId) val rs = stmt.executeQuery() while (rs.next()) { it.coverImageId = rs.getString("master_id") } } }) return people } fun imagesForPerson(personId: String): MutableList<Image>{ val versionIds: MutableList<String> = mutableListOf() val versionSql = "SELECT ${PERSON_VERSION_TABLE}.versionId AS version_id FROM ${PERSON_VERSION_TABLE} WHERE ${PERSON_VERSION_TABLE}.personId is ?" executeOperation(DATABASE_FILENAME_PERSON, { it -> val stmt = it.prepareStatement(versionSql) stmt.setString(1, personId) val rs = stmt.executeQuery() while (rs.next()) { versionIds.add(rs.getString("version_id")) } }) val versionIdsString: String = versionIds.map { "'${it}'" }.joinToString(",") val images: MutableList<Image> = mutableListOf() val sql = "SELECT ${MASTER_TABLE}.modelId as master_id, ${VERSION_TABLE}.modelid as version_id, ${VERSION_TABLE}.isFavorite as is_favorite, ${MASTER_TABLE}.imagepath as master_imagepath, strftime('%s', datetime(${MASTER_TABLE}.imagedate, 'unixepoch', '+372 months', ${MASTER_TABLE}.imageTimeZoneOffsetSeconds || ' seconds')) AS master_timestamp FROM ${VERSION_TABLE} INNER JOIN ${MASTER_TABLE} ON ${MASTER_TABLE}.modelId = ${VERSION_TABLE}.masterid WHERE ${VERSION_TABLE}.modelId IN (${versionIdsString})" executeOperation(DATABASE_FILENAME_LIBRARY,{ it -> val stmt = it.createStatement() val rs = stmt.executeQuery(sql) while (rs.next()) { images.add(Image(rs.getString("master_id"), rs.getString("version_id"), rs.getString("master_imagepath"), Timestamp(rs.getString("master_timestamp").toLong() * 1000), null, rs.getBoolean("is_favorite"), importUuid = null)) } }) images.forEach { it.thumbnail = thumbnailForImage(it) } return images } fun selectAllPersonImages(): MutableList<PersonImage>{ val personVersions: MutableList<PersonVersion> = mutableListOf() val versionSql = "SELECT ${PERSON_VERSION_TABLE}.personId as person_id, ${PERSON_VERSION_TABLE}.versionId AS version_id FROM ${PERSON_VERSION_TABLE}" executeOperation(DATABASE_FILENAME_PERSON, { it -> val stmt = it.prepareStatement(versionSql) val rs = stmt.executeQuery() while (rs.next()) { personVersions.add(PersonVersion(rs.getString("person_id"), rs.getString("version_id"))) } }) val personImages: MutableList<PersonImage> = mutableListOf() val sql = "SELECT ${MASTER_TABLE}.modelId as master_id, ${VERSION_TABLE}.modelid as version_id FROM ${VERSION_TABLE} INNER JOIN ${MASTER_TABLE} ON master_id = ${VERSION_TABLE}.masterid WHERE version_id = ?" executeOperation(DATABASE_FILENAME_LIBRARY,{ it -> val stmt = it.prepareStatement(sql) personVersions.forEach { stmt.setString(1, it.versionId) val rs = stmt.executeQuery() while (rs.next()) { personImages.add(PersonImage(it.personId, rs.getString("master_id"))) } } }) return personImages } fun selectAllAlbumImages(): MutableList<AlbumImage>{ val albumImages: MutableList<AlbumImage> = mutableListOf() val sql = "SELECT ${MASTER_TABLE}.modelId as master_id, ${ALBUM_VERSION_TABLE}.albumId as album_id, ${ALBUM_VERSION_TABLE}.versionId as version_id, ${VERSION_TABLE}.uuid as version_uuid, ${ALBUM_TABLE}.Uuid as album_uuid, (SELECT ${CUSTOM_SORT_ORDER_TABLE}.orderNumber FROM ${CUSTOM_SORT_ORDER_TABLE} WHERE ${CUSTOM_SORT_ORDER_TABLE}.containerUuid = ${ALBUM_TABLE}.Uuid AND ${CUSTOM_SORT_ORDER_TABLE}.objectUuid = ${VERSION_TABLE}.uuid limit 1) AS sort_order FROM ${ALBUM_VERSION_TABLE} INNER JOIN ${VERSION_TABLE} ON ${VERSION_TABLE}.modelid = ${ALBUM_VERSION_TABLE}.versionid INNER JOIN ${MASTER_TABLE} ON ${MASTER_TABLE}.modelId = ${VERSION_TABLE}.masterid INNER JOIN ${ALBUM_TABLE} ON ${ALBUM_TABLE}.modelid = ${ALBUM_VERSION_TABLE}.albumid ORDER BY album_id, sort_order" executeOperation(DATABASE_FILENAME_LIBRARY, { it -> val stmt = it.prepareStatement(sql) val rs = stmt.executeQuery() while (rs.next()) { albumImages.add(AlbumImage(rs.getString("album_id"), rs.getString("master_id"), rs.getInt("sort_order"))) } }) return albumImages } fun selectAllImports(): MutableList<Import>{ val imports : MutableList<Import> = mutableListOf() val sql = "SELECT ${IMPORT_TABLE}.uuid as import_uuid, ${IMPORT_TABLE}.importDate as import_timestamp FROM ${IMPORT_TABLE} ORDER BY ${IMPORT_TABLE}.modelId" executeOperation(DATABASE_FILENAME_LIBRARY,{ it -> val stmt = it.prepareStatement(sql) val rs = stmt.executeQuery() while (rs.next()) { val rawTimestamp = rs.getLong("import_timestamp") * 1000 //milliseconds since unix epoch for 2001-01-01 00:00:00 EST time, when timestamps start val timestampOffset = 978307200000 val importTimestamp = Timestamp(rawTimestamp + timestampOffset) val import = Import(rs.getString("import_uuid"), importTimestamp) imports.add(import) } }) return imports } }
mit
ca7b015bebaa3c6e99eaf51738facd87
49.455508
925
0.628889
4.186149
false
false
false
false
jitsi/jitsi-videobridge
jitsi-media-transform/src/test/kotlin/org/jitsi/nlj/module_tests/RtpSenderHarness.kt
1
2204
/* * Copyright @ 2018 - Present, 8x8 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 org.jitsi.nlj.module_tests import org.jitsi.nlj.PacketInfo import org.jitsi.nlj.RtpSender import org.jitsi.nlj.util.safeShutdown import org.jitsi.rtp.extensions.looksLikeRtp import org.jitsi.rtp.rtcp.RtcpPacket import org.jitsi.rtp.rtp.RtpPacket import org.jitsi.test_utils.Pcaps import org.jitsi.utils.secs import java.util.concurrent.Executors import kotlin.system.measureTimeMillis fun main() { val pcap = Pcaps.Outgoing.ONE_PARITICPANT_RTP_AND_RTCP_DECRYPTED val producer = PcapPacketProducer(pcap.filePath) val senderExecutor = Executors.newSingleThreadExecutor() val backgroundExecutor = Executors.newSingleThreadScheduledExecutor() val numSenders = 1 val senders = mutableListOf<RtpSender>() repeat(numSenders) { val sender = SenderFactory.createSender( senderExecutor, backgroundExecutor, pcap.srtpData, pcap.payloadTypes, pcap.headerExtensions, pcap.ssrcAssociations ) senders.add(sender) } producer.subscribe { pkt -> val packetInfo = when { pkt.looksLikeRtp() -> PacketInfo(RtpPacket(pkt.buffer, pkt.offset, pkt.length)) else -> PacketInfo(RtcpPacket.parse(pkt.buffer, pkt.offset, pkt.length)) } senders.forEach { it.processPacket(packetInfo.clone()) } } val time = measureTimeMillis { producer.run() } println("took $time ms") senders.forEach(RtpSender::stop) senderExecutor.safeShutdown(10.secs) backgroundExecutor.safeShutdown(10.secs) senders.forEach { println(it.getNodeStats().prettyPrint()) } }
apache-2.0
9f86bd9e1b823714ed3eb2f1e13492da
33.984127
91
0.721416
4
false
false
false
false
episode6/mockspresso
mockspresso-mockito/src/main/java/com/episode6/hackit/mockspresso/mockito/MockitoPluginsExt.kt
1
1741
@file:Suppress("DEPRECATION") package com.episode6.hackit.mockspresso.mockito import com.episode6.hackit.mockspresso.Mockspresso import com.episode6.hackit.mockspresso.api.MockspressoPlugin import kotlin.reflect.KClass /** * Kotlin extension methods for mockspresso's mockito plugins */ /** * Applies the [com.episode6.hackit.mockspresso.api.MockerConfig] to support mockito */ @JvmSynthetic fun Mockspresso.Builder.mockByMockito(): Mockspresso.Builder = mocker(MockitoMockerConfig()) /** * Applies special object handling for the provided factory classes. The * applicable objects will be mocked by mockito, but with a default answer * that returns objects from mockspresso's dependency map (similar to how * the javax() injector automatically binds Providers, but applied to any * factory class, including generics). */ @JvmSynthetic fun Mockspresso.Builder.automaticFactories(vararg classes: Class<*>): Mockspresso.Builder = specialObjectMaker(MockitoAutoFactoryMaker.create(*classes)) /** * Convenience function to call [automaticFactories] using kotlin KClasses instead of java Classes */ @JvmSynthetic fun Mockspresso.Builder.automaticFactories(vararg classes: KClass<*>): Mockspresso.Builder = automaticFactories(*classes.map { it.java }.toTypedArray()) /** * Expose the extension methods defined here as [MockspressoPlugin]s for consumption by java tests */ @Suppress("NEWER_VERSION_IN_SINCE_KOTLIN") @SinceKotlin("9999.0") object MockspressoMockitoPluginsJavaSupport { @JvmStatic fun mockByMockito(): MockspressoPlugin = MockspressoPlugin { it.mockByMockito() } @JvmStatic fun automaticFactories(vararg classes: Class<*>): MockspressoPlugin = MockspressoPlugin { it.automaticFactories(*classes) } }
mit
d22480f6f9fdde95ea2eccc82b65a5f4
37.688889
136
0.789202
4.320099
false
false
false
false
ejeinc/Meganekko
library/src/main/java/org/meganekkovr/xml/GeometryHandler.kt
1
1291
package org.meganekkovr.xml import android.content.Context import org.meganekkovr.Entity import org.meganekkovr.GeometryComponent /** * Define `geometry` attribute. */ internal class GeometryHandler : XmlAttributeParser.XmlAttributeHandler { override val attributeName = "geometry" override fun parse(entity: Entity, rawValue: String, context: Context) { val map = XmlAttributeParser.parseInlineValue(rawValue) val primitive = map["primitive"] ?: return val geometryComponent = GeometryComponent() when (primitive) { "plane" -> { val width = map["width"]?.toFloatOrNull() ?: 0.0f val height = map["height"]?.toFloatOrNull() ?: 0.0f geometryComponent.buildQuad(width, height) } "globe" -> { geometryComponent.buildGlobe() } "dome" -> { val lat = map["lat"]?.toFloatOrNull() ?: 0.0f geometryComponent.buildDome(Math.toRadians(lat.toDouble()).toFloat()) } "spherePatch" -> { val fov = map["fov"]?.toFloatOrNull() ?: 0.0f geometryComponent.buildSpherePatch(fov) } } entity.add(geometryComponent) } }
apache-2.0
a31604d0c3826bde6dd12d8ad5a795e2
29.023256
85
0.579396
4.610714
false
false
false
false
world-federation-of-advertisers/common-jvm
src/test/kotlin/org/wfanet/measurement/common/graphviz/DotTest.kt
1
1589
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.common.graphviz import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class DotTest { @Test fun renderGraph() { val graph = digraph("Foo") { attributes { set("splines" to "ortho") } subgraph { edge("A" to "B") edge("B" to "C") { set("label" to "some-label") } } scope { attributes { set("rank" to "same") } node("X") node("Y") { set("foo" to "bar") } } edge("X" to "Y") } val expected = """ digraph Foo { splines="ortho" subgraph { A -> B B -> C [label="some-label"] } { rank="same" X Y [foo="bar"] } X -> Y } """ .trimIndent() assertThat(graph.trim()).isEqualTo(expected) } }
apache-2.0
6cc7c83fe001ff69f761be6974e350a4
24.629032
75
0.585274
3.894608
false
false
false
false
halawata13/ArtichForAndroid
app/src/main/java/net/halawata/artich/model/mute/MediaMute.kt
2
3388
package net.halawata.artich.model.mute import android.content.ContentValues import android.database.Cursor import android.database.sqlite.SQLiteOpenHelper import net.halawata.artich.entity.ListItem import net.halawata.artich.enum.Media import java.lang.Exception abstract class MediaMute(val helper: SQLiteOpenHelper) : MediaMuteInterface { protected fun fetch(mediaType: Media): ArrayList<ListItem> { val result: ArrayList<ListItem> = arrayListOf() val db = helper.readableDatabase var cursor: Cursor? = null try { cursor = db.query(getTableName(mediaType), arrayOf("id", "name"), null, null, null, null, null, null) var eol = cursor.moveToFirst() while (eol) { result.add(ListItem(cursor.getLong(0), cursor.getString(1))) eol = cursor.moveToNext() } } catch (ex: Exception) { ex.printStackTrace() throw ex } finally { cursor?.close() db.close() } return result } protected fun update(mediaType: Media, data: ArrayList<ListItem>) { val db = helper.writableDatabase db.beginTransaction() try { db.delete(getTableName(mediaType), null, null) var id = 1 data.forEach { item -> val values = ContentValues() values.put("id", id) values.put("name", item.title) db.insert(getTableName(mediaType), null, values) id += 1 } db.setTransactionSuccessful() } catch (ex: Exception) { ex.printStackTrace() throw ex } finally { db.endTransaction() db.close() } } protected fun insert(mediaType: Media, name: String) { val data = fetch(mediaType) val db = helper.writableDatabase db.beginTransaction() try { val values = ContentValues() val id = if (data.isEmpty()) 1 else data.last().id + 1 values.put("id", id) values.put("name", name) db.insert(getTableName(mediaType), null, values) db.setTransactionSuccessful() } catch (ex: Exception) { ex.printStackTrace() throw ex } finally { db.endTransaction() db.close() } } protected fun delete(mediaType: Media, id: Int) { val db = helper.writableDatabase db.beginTransaction() try { db.delete(getTableName(mediaType), "id = ?", arrayOf(id.toString())) db.setTransactionSuccessful() } catch (ex: Exception) { ex.printStackTrace() throw ex } finally { db.endTransaction() db.close() } } fun getMuteList(): ArrayList<String> { val list = ArrayList<String>() get().forEach { item -> list.add(item.title) } return list } private fun getTableName(mediaType: Media): String { when (mediaType) { Media.COMMON -> return "t_mute_common" Media.HATENA -> return "t_mute_hatena" Media.QIITA -> return "t_mute_qiita" Media.GNEWS -> return "t_mute_gnews" } } }
mit
60b82df403b774bf2fbd7b3ddebd1b52
25.263566
113
0.543388
4.699029
false
false
false
false
mallowigi/a-file-icon-idea
common/src/main/java/com/mallowigi/tree/arrows/NoneArrowsStyle.kt
1
1682
/* * The MIT License (MIT) * * Copyright (c) 2015-2022 Elior "Mallowigi" Boukhobza * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * */ package com.mallowigi.tree.arrows import com.intellij.icons.AllIcons import com.intellij.util.ui.EmptyIcon import javax.swing.Icon /** * No arrows style * */ class NoneArrowsStyle : ArrowsStyle { private val emptyIcon = EmptyIcon.create(AllIcons.General.ArrowUp) override val expandIcon: Icon get() = emptyIcon override val collapseIcon: Icon get() = emptyIcon override val selectedExpandIcon: Icon get() = emptyIcon override val selectedCollapseIcon: Icon get() = emptyIcon }
mit
e2807c73fc231f9a7e003929356e3d3d
33.326531
81
0.750297
4.335052
false
false
false
false
nestlabs/connectedhomeip
src/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/OpCredClientFragment.kt
2
3940
package com.google.chip.chiptool.clusterclient import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import chip.devicecontroller.ChipClusters import chip.devicecontroller.ChipDeviceController import com.google.chip.chiptool.ChipClient import com.google.chip.chiptool.GenericChipDeviceListener import com.google.chip.chiptool.R import kotlinx.android.synthetic.main.op_cred_client_fragment.opCredClusterCommandStatus import kotlinx.android.synthetic.main.op_cred_client_fragment.view.readCommissionedFabricBtn import kotlinx.android.synthetic.main.op_cred_client_fragment.view.readSupportedFabricBtn import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch class OpCredClientFragment : Fragment() { private val deviceController: ChipDeviceController get() = ChipClient.getDeviceController(requireContext()) private lateinit var scope: CoroutineScope private lateinit var addressUpdateFragment: AddressUpdateFragment override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { scope = viewLifecycleOwner.lifecycleScope return inflater.inflate(R.layout.op_cred_client_fragment, container, false).apply { deviceController.setCompletionListener(ChipControllerCallback()) addressUpdateFragment = childFragmentManager.findFragmentById(R.id.addressUpdateFragment) as AddressUpdateFragment readSupportedFabricBtn.setOnClickListener { scope.launch { sendReadOpCredSupportedFabricAttrClick() } } readCommissionedFabricBtn.setOnClickListener { scope.launch { sendReadOpCredCommissionedFabricAttrClick() } } } } inner class ChipControllerCallback : GenericChipDeviceListener() { override fun onConnectDeviceComplete() {} override fun onCommissioningComplete(nodeId: Long, errorCode: Int) { Log.d(TAG, "onCommissioningComplete for nodeId $nodeId: $errorCode") } override fun onNotifyChipConnectionClosed() { Log.d(TAG, "onNotifyChipConnectionClosed") } override fun onCloseBleComplete() { Log.d(TAG, "onCloseBleComplete") } override fun onError(error: Throwable?) { Log.d(TAG, "onError: $error") } } private suspend fun sendReadOpCredSupportedFabricAttrClick() { getOpCredClusterForDevice().readSupportedFabricsAttribute(object : ChipClusters.IntegerAttributeCallback { override fun onSuccess(value: Int) { Log.v(TAG, "OpCred supported Fabric attribute value: $value") showMessage("OpCred supported Fabric attribute value: $value") } override fun onError(ex: Exception) { Log.e(TAG, "Error reading OpCred supported Fabric attribute", ex) } }) } private suspend fun sendReadOpCredCommissionedFabricAttrClick() { getOpCredClusterForDevice().readCommissionedFabricsAttribute(object : ChipClusters.IntegerAttributeCallback { override fun onSuccess(value: Int) { Log.v(TAG, "OpCred Commissioned Fabric attribute value: $value") showMessage("OpCred Commissioned Fabric attribute value: $value") } override fun onError(ex: Exception) { Log.e(TAG, "Error reading OpCred Commissioned Fabric attribute", ex) } }) } private fun showMessage(msg: String) { requireActivity().runOnUiThread { opCredClusterCommandStatus.text = msg } } private suspend fun getOpCredClusterForDevice(): ChipClusters.OperationalCredentialsCluster { return ChipClusters.OperationalCredentialsCluster( ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId), 0 ) } companion object { private const val TAG = "OpCredClientFragment" fun newInstance(): OpCredClientFragment = OpCredClientFragment() } }
apache-2.0
d4ced48180a2cc10d62d8f749356f299
35.146789
115
0.765736
4.629847
false
false
false
false
gravidence/gravifon
gravifon/src/main/kotlin/org/gravidence/gravifon/ui/PlaybackInformationComposable.kt
1
4610
package org.gravidence.gravifon.ui import androidx.compose.foundation.layout.* import androidx.compose.material.Divider import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import org.gravidence.gravifon.GravifonContext import org.gravidence.gravifon.domain.track.VirtualTrack import org.gravidence.gravifon.playback.PlaybackStatus import org.gravidence.gravifon.util.DurationUtil import kotlin.time.Duration class PlaybackInformationState( val playbackStatus: PlaybackStatus, val artistInformation: String, val trackInformation: String, val trackExtraInformation: String, val albumInformation: String, ) { companion object { fun renderArtistInformation(track: VirtualTrack?): String { return track?.getArtist() ?: "<unknown artist>" } fun renderTrackInformation(track: VirtualTrack?): String { return track?.getTitle() ?: "<unknown title>" } fun renderTrackExtraInformation(trackLength: Duration): String { return "(" + DurationUtil.formatShortHours(trackLength) + ")" } fun renderAlbumInformation(track: VirtualTrack?): String { val album = track?.getAlbum() ?: "<unknown album>" val date = track?.getDate() val albumArtist = track?.getAlbumArtist() val builder = StringBuilder(album) if (date != null) { builder.append(" ($date)") } if (albumArtist != null) { builder.append(" by $albumArtist") } return builder.toString() } } } @Composable fun rememberPlaybackInformationState( activeTrack: VirtualTrack? = GravifonContext.activeTrack.value, playbackStatus: PlaybackStatus = GravifonContext.playbackStatusState.value, trackLength: Duration = GravifonContext.playbackPositionState.value.endingPosition, ) = remember(activeTrack, playbackStatus, trackLength) { PlaybackInformationState( playbackStatus = playbackStatus, artistInformation = PlaybackInformationState.renderArtistInformation(activeTrack), trackInformation = PlaybackInformationState.renderTrackInformation(activeTrack), trackExtraInformation = PlaybackInformationState.renderTrackExtraInformation(trackLength), albumInformation = PlaybackInformationState.renderAlbumInformation(activeTrack), ) } @Composable fun PlaybackInformationComposable(playbackInformationState: PlaybackInformationState) { Box( modifier = Modifier .height(90.dp) .padding(5.dp) ) { Column( verticalArrangement = Arrangement.SpaceEvenly, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxSize() ) { if (playbackInformationState.playbackStatus == PlaybackStatus.STOPPED) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, modifier = Modifier .fillMaxSize() ) { Text(text = "Idle...", fontWeight = FontWeight.ExtraLight) } } else { Row( horizontalArrangement = Arrangement.spacedBy(5.dp), ) { Text(text = playbackInformationState.artistInformation, fontWeight = FontWeight.ExtraBold) } Divider(color = Color.Transparent, thickness = 1.dp) Row( horizontalArrangement = Arrangement.spacedBy(5.dp), ) { Text(text = playbackInformationState.trackInformation, fontWeight = FontWeight.Bold) Text(text = playbackInformationState.trackExtraInformation, fontWeight = FontWeight.Light) } Divider(color = Color.Transparent, thickness = 1.dp) Row( horizontalArrangement = Arrangement.spacedBy(5.dp), ) { Text(text = playbackInformationState.albumInformation, fontWeight = FontWeight.Medium, fontStyle = FontStyle.Italic) } } } } }
mit
66cb7ad764dff8f1ef35285fdea2de6c
37.425
136
0.644469
5.323326
false
false
false
false
JavaEden/OrchidCore
OrchidCore/src/main/kotlin/com/eden/orchid/utilities/StreamUtils.kt
1
1794
package com.eden.orchid.utilities import com.caseyjbrooks.clog.Clog import java.io.BufferedReader import java.io.InputStream import java.io.InputStreamReader import java.io.OutputStream import java.io.PipedInputStream import java.io.PipedOutputStream import java.nio.charset.Charset class InputStreamCollector(private val inputStream: InputStream) : Runnable { var output = StringBuffer() override fun run() { output = StringBuffer() BufferedReader(InputStreamReader(inputStream, Charset.forName("UTF-8"))).lines().forEach { output.append(it + "\n") } } override fun toString(): String { return output.toString() } } class InputStreamPrinter @JvmOverloads constructor( private val inputStream: InputStream, val tag: String? = null, val transform: ((String)->String)? = null ) : Runnable { override fun run() { BufferedReader(InputStreamReader(inputStream, Charset.forName("UTF-8"))).lines().forEach { val actualMessage = transform?.invoke(it) ?: it if (tag != null) { Clog.tag(tag).log(actualMessage) } else { Clog.noTag().log(actualMessage) } } } } class InputStreamIgnorer(private val inputStream: InputStream) : Runnable { override fun run() { BufferedReader(InputStreamReader(inputStream, Charset.forName("UTF-8"))).lines().forEach { // do nothing with it } } } fun convertOutputStream(writer: (OutputStream) -> Unit): InputStream { val pipedInputStreamPrinter = PipedInputStream() val pipedOutputStream = PipedOutputStream(pipedInputStreamPrinter) Thread { pipedOutputStream.use(writer) }.start() return pipedInputStreamPrinter }
mit
2c02355ac9d1930ebba1a7eebcb3aed9
27.03125
125
0.666667
4.576531
false
false
false
false
xfournet/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/HintRenderer.kt
1
6239
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.daemon.impl import com.intellij.ide.ui.AntialiasingType import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorCustomElementRenderer import com.intellij.openapi.editor.colors.EditorFontType import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.editor.impl.FontInfo import com.intellij.openapi.editor.markup.EffectType import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.openapi.util.Key import com.intellij.ui.paint.EffectPainter import com.intellij.util.ui.GraphicsUtil import java.awt.* import java.awt.font.FontRenderContext import javax.swing.UIManager /** * @author egor */ open class HintRenderer(var text: String?) : EditorCustomElementRenderer { override fun calcWidthInPixels(editor: Editor): Int { return doCalcWidth(text, getFontMetrics(editor).metrics) } protected open fun getTextAttributes(editor: Editor): TextAttributes? { return editor.colorsScheme.getAttributes(DefaultLanguageHighlighterColors.INLINE_PARAMETER_HINT) } override fun paint(editor: Editor, g: Graphics, r: Rectangle, textAttributes: TextAttributes) { if (editor !is EditorImpl) return val ascent = editor.ascent val descent = editor.descent val g2d = g as Graphics2D val attributes = getTextAttributes(editor) if (text != null && attributes != null) { val fontMetrics = getFontMetrics(editor) val gap = if (r.height < fontMetrics.lineHeight + 2) 1 else 2 val backgroundColor = attributes.backgroundColor if (backgroundColor != null) { val config = GraphicsUtil.setupAAPainting(g) GraphicsUtil.paintWithAlpha(g, BACKGROUND_ALPHA) g.setColor(backgroundColor) g.fillRoundRect(r.x + 2, r.y + gap, r.width - 4, r.height - gap * 2, 8, 8) config.restore() } val foregroundColor = attributes.foregroundColor if (foregroundColor != null) { val savedHint = g2d.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING) val savedClip = g.getClip() g.setColor(foregroundColor) g.setFont(getFont(editor)) g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, AntialiasingType.getKeyForCurrentScope(false)) g.clipRect(r.x + 3, r.y + 2, r.width - 6, r.height - 4) val metrics = fontMetrics.metrics g.drawString(text, r.x + 7, r.y + Math.max(ascent, (r.height + metrics.ascent - metrics.descent) / 2) - 1) g.setClip(savedClip) g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, savedHint) } } val effectColor = textAttributes.effectColor val effectType = textAttributes.effectType if (effectColor != null) { g.setColor(effectColor) val xStart = r.x val xEnd = r.x + r.width val y = r.y + ascent val font = editor.getColorsScheme().getFont(EditorFontType.PLAIN) if (effectType == EffectType.LINE_UNDERSCORE) { EffectPainter.LINE_UNDERSCORE.paint(g2d, xStart, y, xEnd - xStart, descent, font) } else if (effectType == EffectType.BOLD_LINE_UNDERSCORE) { EffectPainter.BOLD_LINE_UNDERSCORE.paint(g2d, xStart, y, xEnd - xStart, descent, font) } else if (effectType == EffectType.STRIKEOUT) { EffectPainter.STRIKE_THROUGH.paint(g2d, xStart, y, xEnd - xStart, editor.charHeight, font) } else if (effectType == EffectType.WAVE_UNDERSCORE) { EffectPainter.WAVE_UNDERSCORE.paint(g2d, xStart, y, xEnd - xStart, descent, font) } else if (effectType == EffectType.BOLD_DOTTED_LINE) { EffectPainter.BOLD_DOTTED_UNDERSCORE.paint(g2d, xStart, y, xEnd - xStart, descent, font) } } } protected class MyFontMetrics constructor(editor: Editor, familyName: String, size: Int) { val metrics: FontMetrics val lineHeight: Int val font: Font get() = metrics.font init { val font = Font(familyName, Font.PLAIN, size) val context = getCurrentContext(editor) metrics = FontInfo.getFontMetrics(font, context) // We assume this will be a better approximation to a real line height for a given font lineHeight = Math.ceil(font.createGlyphVector(context, "Ap").visualBounds.height).toInt() } fun isActual(editor: Editor, familyName: String, size: Int): Boolean { val font = metrics.font if (familyName != font.family || size != font.size) return false val currentContext = getCurrentContext(editor) return currentContext.equals(metrics.fontRenderContext) } private fun getCurrentContext(editor: Editor): FontRenderContext { val editorContext = FontInfo.getFontRenderContext(editor.contentComponent) return FontRenderContext(editorContext.transform, AntialiasingType.getKeyForCurrentScope(false), if (editor is EditorImpl) editor.myFractionalMetricsHintValue else RenderingHints.VALUE_FRACTIONALMETRICS_OFF) } } protected fun getFontMetrics(editor: Editor): MyFontMetrics { val familyName = UIManager.getFont("Label.font").family val size = Math.max(1, editor.colorsScheme.editorFontSize - 1) var metrics = editor.getUserData(HINT_FONT_METRICS) if (metrics != null && !metrics.isActual(editor, familyName, size)) { metrics = null } if (metrics == null) { metrics = MyFontMetrics(editor, familyName, size) editor.putUserData(HINT_FONT_METRICS, metrics) } return metrics } private fun getFont(editor: Editor): Font { return getFontMetrics(editor).font } protected fun doCalcWidth(text: String?, fontMetrics: FontMetrics): Int { return if (text == null) 0 else fontMetrics.stringWidth(text) + 14 } companion object { private val HINT_FONT_METRICS = Key.create<MyFontMetrics>("ParameterHintFontMetrics") private val BACKGROUND_ALPHA = 0.55f } }
apache-2.0
56c15e15f7481ff2666596ffa01f737b
40.046053
140
0.694823
4.167669
false
false
false
false
wordpress-mobile/WordPress-FluxC-Android
fluxc/src/main/java/org/wordpress/android/fluxc/network/rest/wpcom/account/DomainContactResponse.kt
2
518
package org.wordpress.android.fluxc.network.rest.wpcom.account @Suppress("VariableNaming") class DomainContactResponse { var first_name: String? = null var last_name: String? = null var organization: String? = null var address_1: String? = null var address_2: String? = null var postal_code: String? = null var city: String? = null var state: String? = null var country_code: String? = null var email: String? = null var phone: String? = null var fax: String? = null }
gpl-2.0
7f1f9780b1c203d4b4907372545b9ca8
29.470588
62
0.667954
3.673759
false
false
false
false
xfournet/intellij-community
python/src/com/jetbrains/python/run/PyVirtualEnvReader.kt
3
3505
// Copyright 2000-2017 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.jetbrains.python.run import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.SystemInfo import com.intellij.util.EnvironmentUtil import com.intellij.util.containers.ContainerUtil import com.jetbrains.python.sdk.PythonSdkType import java.io.File /** * @author traff */ class PyVirtualEnvReader(val virtualEnvSdkPath: String) : EnvironmentUtil.ShellEnvReader() { private val LOG = Logger.getInstance("#com.jetbrains.python.run.PyVirtualEnvReader") companion object { val virtualEnvVars = listOf("PATH", "PS1", "VIRTUAL_ENV", "PYTHONHOME", "PROMPT", "_OLD_VIRTUAL_PROMPT", "_OLD_VIRTUAL_PYTHONHOME", "_OLD_VIRTUAL_PATH") } // in case of Conda we need to pass an argument to an activate script that tells which exactly environment to activate val activate: Pair<String, String?>? = findActivateScript(virtualEnvSdkPath, shell) override fun getShell(): String? { if (File("/bin/bash").exists()) { return "/bin/bash"; } else if (File("/bin/sh").exists()) { return "/bin/sh"; } else { return super.getShell(); } } fun readPythonEnv(): MutableMap<String, String> { try { if (SystemInfo.isUnix) { // pass shell environment for correct virtualenv environment setup (virtualenv expects to be executed from the terminal) return super.readShellEnv(EnvironmentUtil.getEnvironmentMap()) } else { if (activate != null) { return readBatEnv(File(activate.first), ContainerUtil.createMaybeSingletonList(activate.second)) } else { LOG.error("Can't find activate script for $virtualEnvSdkPath") } } } catch (e: Exception) { LOG.warn("Couldn't read shell environment: ${e.message}") } return mutableMapOf() } override fun getShellProcessCommand(): MutableList<String> { val shellPath = shell if (shellPath == null || !File(shellPath).canExecute()) { throw Exception("shell:" + shellPath) } return if (activate != null) { val activateArg = if (activate.second != null) "'${activate.first}' '${activate.second}'" else "'${activate.first}'" mutableListOf(shellPath, "-c", ". $activateArg") } else super.getShellProcessCommand() } } fun findActivateScript(path: String?, shellPath: String?): Pair<String, String?>? { val shellName = if (shellPath != null) File(shellPath).name else null val activate = if (SystemInfo.isWindows) findActivateOnWindows(path) else if (shellName == "fish" || shellName == "csh") File(File(path).parentFile, "activate." + shellName) else File(File(path).parentFile, "activate") return if (activate != null && activate.exists()) { val sdk = PythonSdkType.findSdkByPath(path) if (sdk != null && PythonSdkType.isCondaVirtualEnv(sdk)) Pair(activate.absolutePath, condaEnvFolder(path)) else Pair(activate.absolutePath, null) } else null } private fun condaEnvFolder(path: String?) = if (SystemInfo.isWindows) File(path).parent else File(path).parentFile.parent private fun findActivateOnWindows(path: String?): File? { for (location in arrayListOf("activate.bat", "Scripts/activate.bat")) { val file = File(File(path).parentFile, location) if (file.exists()) { return file } } return null }
apache-2.0
ae418044baed03c0d32ccdf6bfff2fcb
33.372549
140
0.678174
4.075581
false
false
false
false
yyued/CodeX-UIKit-Android
library/src/main/java/com/yy/codex/uikit/UIScrollView_Scroller.kt
1
10929
package com.yy.codex.uikit import com.yy.codex.foundation.lets /** * Created by cuiminghui on 2017/3/7. */ private val FINGER_VELOCITY = 300.0 internal fun UIScrollView._initScroller() { _windowSizePoint = CGPoint(0.0, 0.0) _panGestureRecognizer = UIPanGestureRecognizer(this, "handlePan:") _panGestureRecognizer?.stealer = true _panGestureRecognizer?.let { addGestureRecognizer(it) } } internal fun UIScrollView._scrollerTouchBegan() { if (!scrollEnabled) { return } _deceleratingCancelled = decelerating _currentAnimationY?.let(UIViewAnimation::cancel) _currentAnimationY = null _currentAnimationX?.let(UIViewAnimation::cancel) _currentAnimationX = null tracking = true decelerating = false if (_deceleratingCancelled) { _showScrollIndicator() } } internal fun UIScrollView._scrollerTouchEnded() { if (!scrollEnabled) { return } if (_deceleratingCancelled && _checkOutOfBounds()) { _setContentOffsetWithSpring(_requestBoundsPoint(contentOffset)) } else if (_deceleratingCancelled && !dragging && !decelerating) { _hideScrollIndicator() } } internal fun UIScrollView._scrollerHandlePan(panGestureRecognizer: UIPanGestureRecognizer) { if (!scrollEnabled) { return } val originY = -panGestureRecognizer.translation().y val originX = -panGestureRecognizer.translation().x if (!dragging) { /* Began */ dragging = true _trackingPoint = CGPoint(originX, originY) panGestureRecognizer.setTranslation(contentOffset) delegate?.let { it.willBeginDragging(this) } _showScrollIndicator() } else if (dragging && panGestureRecognizer.state == UIGestureRecognizerState.Changed) { /* Move */ val offset = _computeMovePoint(CGPoint(originX, originY), pagingEnabled) lets(_trackingPoint, _windowSizePoint) { trackingPoint, windowSizePoint -> _verticalMoveDistance = originY + Math.abs(trackingPoint.y) - windowSizePoint.y _horizontalMoveDistance = originX + Math.abs(trackingPoint.x) - windowSizePoint.x } setContentOffset(offset) } else if (panGestureRecognizer.state == UIGestureRecognizerState.Ended) { /* Ended */ dragging = false tracking = false delegate?.let { it.didEndDragging(this, false) } val velocity = panGestureRecognizer.velocity() if (pagingEnabled) { _computeScrollPagingPoint(velocity) _windowSizePoint?.let { _setContentOffsetWithSpring(it) } } else { decelerating = true _currentAnimationX?.let { it.cancel() } _currentAnimationY?.let { it.cancel() } val xOptions = UIViewAnimator.UIViewAnimationDecayBoundsOptions() xOptions.allowBounds = bounces xOptions.alwaysBounds = alwaysBounceHorizontal xOptions.fromValue = contentOffset.x xOptions.velocity = -velocity.x / 1000.0 if (Math.abs(xOptions.velocity) < 0.1) { xOptions.velocity = 0.0 } xOptions.topBounds = 0.0 xOptions.bottomBounds = contentSize.width - frame.size.width xOptions.viewBounds = frame.size.width _currentAnimationX = UIViewAnimator.decayBounds(this, "contentOffset.x", xOptions, null) val yOptions = UIViewAnimator.UIViewAnimationDecayBoundsOptions() yOptions.allowBounds = bounces yOptions.alwaysBounds = alwaysBounceVertical yOptions.fromValue = contentOffset.y yOptions.velocity = -velocity.y / 1000.0 if (Math.abs(yOptions.velocity) < 0.1) { yOptions.velocity = 0.0 } yOptions.topBounds = 0.0 yOptions.bottomBounds = contentSize.height + contentInset.bottom - frame.size.height yOptions.viewBounds = frame.size.height _currentAnimationY = UIViewAnimator.decayBounds(this, "contentOffset.y", yOptions, Runnable { decelerating = false _hideScrollIndicator() }) } _horizontalMoveDistance = 0.0 _verticalMoveDistance = 0.0 } } internal fun UIScrollView._setContentOffset(contentOffset: CGPoint, animated: Boolean = false) { val oldValue = this.contentOffset val self = this this.contentOffset = contentOffset if (animated) { _currentAnimationX?.let { it.cancel() } _currentAnimationY?.let { it.cancel() } _currentAnimationX = UIViewAnimator.linear(0.25, Runnable { UIViewAnimator.addAnimationState(self, "contentOffset.x", oldValue.x, this.contentOffset.x) UIViewAnimator.addAnimationState(self, "contentOffset.y", oldValue.y, this.contentOffset.y) }, null) _currentAnimationY = _currentAnimationX } else { scrollTo((this.contentOffset.x * UIScreen.mainScreen.scale()).toInt(), (this.contentOffset.y * UIScreen.mainScreen.scale() - contentInset.top).toInt()) delegate?.let { it.didScroll(this) } UIViewAnimator.addAnimationState(self, "contentOffset.x", oldValue.x, this.contentOffset.x) UIViewAnimator.addAnimationState(self, "contentOffset.y", oldValue.y, this.contentOffset.y) _updateScrollIndicator() } } internal fun UIScrollView._scrollToVisible(visibleRect: CGRect, animated: Boolean) { val leftVisible = visibleRect.x < contentOffset.x + frame.width val topVisible = visibleRect.y < contentOffset.y + frame.height var computedOffsetX = contentOffset.x var computedOffsetY = contentOffset.y if (!leftVisible) { computedOffsetX = if (visibleRect.width < frame.width) visibleRect.x + visibleRect.width - frame.width else visibleRect.x } if (!topVisible) { computedOffsetY = if (visibleRect.height < frame.height) visibleRect.y + visibleRect.height - frame.height else visibleRect.y } if (!leftVisible || !topVisible) { setContentOffset(CGPoint(computedOffsetX, computedOffsetY), animated) } } internal fun UIScrollView._setContentOffsetWithSpring(contentOffset: CGPoint) { _currentAnimationX?.let { it.cancel() } _currentAnimationY?.let { it.cancel() } _currentAnimationX = UIViewAnimator.springWithOptions(120.0, 20.0, Runnable { setContentOffset(contentOffset, false) }, null) _currentAnimationY = _currentAnimationX } private fun UIScrollView._checkOutOfBounds(): Boolean { if (contentOffset.x < 0.0 || contentOffset.y < 0.0) { return true } else if (contentOffset.x > contentSize.width - frame.size.width && contentSize.width > 0 || contentOffset.y > contentSize.height - frame.size.height && contentSize.height > 0) { return true } return false } private fun UIScrollView._computeScrollPagingPoint(velocity: CGPoint) { var verticalPageCurrentIndex = Math.round((_windowSizePoint?.y ?: 0.0) / frame.size.height).toInt() var horizontalPageCurrentIndex = Math.round((_windowSizePoint?.x ?: 0.0) / frame.size.width).toInt() var moveOffsetX = horizontalPageCurrentIndex * frame.size.width var moveOffsetY = verticalPageCurrentIndex * frame.size.height if (Math.abs(_horizontalMoveDistance) > _fingerHorizontalMoveDistance || Math.abs(_verticalMoveDistance) > _fingerVerticalMoveDistance || Math.abs(velocity.x) > FINGER_VELOCITY || Math.abs(velocity.y) > FINGER_VELOCITY) { verticalPageCurrentIndex = if (_verticalMoveDistance > 0) ++verticalPageCurrentIndex else --verticalPageCurrentIndex horizontalPageCurrentIndex = if (_horizontalMoveDistance > 0) ++horizontalPageCurrentIndex else --horizontalPageCurrentIndex if (verticalPageCurrentIndex < 0) { verticalPageCurrentIndex = 0 } if (horizontalPageCurrentIndex < 0) { horizontalPageCurrentIndex = 0 } moveOffsetX = horizontalPageCurrentIndex * frame.size.width moveOffsetY = verticalPageCurrentIndex * frame.size.height } val offset = _computeMovePoint(CGPoint(moveOffsetX, moveOffsetY), pagingEnabled) _windowSizePoint = offset } private fun UIScrollView._computeMovePoint(point: CGPoint, pagingEnabled: Boolean): CGPoint { val y = _computeY(point.y) val x = _computeX(point.x) return CGPoint(x, y) } private fun UIScrollView._computeY(y: Double): Double { return _computeXY(y, false) } private fun UIScrollView._computeX(x: Double): Double { return _computeXY(x, true) } private fun UIScrollView._computeXY(xOry: Double, isX: Boolean): Double { val contentSizeWidth = contentSize.width val contentSizeHeight = contentSize.height val thisWidth = frame.size.width val thisHeight = frame.size.height val calculateContentSizeValue = if (isX) contentSizeWidth else contentSizeHeight val calculateThisValue = if (isX) thisWidth else thisHeight val mAlwaysBounceOrientation = if (isX) alwaysBounceHorizontal else alwaysBounceVertical var retValue = xOry val deltaBottom = calculateContentSizeValue + contentInset.bottom + contentInset.top - calculateThisValue val over = xOry - deltaBottom if (calculateContentSizeValue < calculateThisValue) { retValue = 0.0 if (bounces && mAlwaysBounceOrientation) { retValue = xOry / 3.0// add } } else { // out of top if (xOry < 0.0) { retValue = 0.0 if (bounces) { // can Bounces retValue = xOry / 3.0 } } //out of bottom if (xOry > Math.abs(calculateContentSizeValue + contentInset.bottom + contentInset.top - calculateThisValue)) { retValue = deltaBottom if (bounces) { // can Bounces retValue = deltaBottom + over / 3.0 } } } return retValue } private fun UIScrollView._requestBoundsPoint(point: CGPoint): CGPoint { return CGPoint(_requestBoundsX(point.x), _requestBoundsY(point.y)) } private fun UIScrollView._requestBoundsX(x: Double): Double { if (x < 0.0) { return 0.0 } else if (contentSize.width < frame.width) { return 0.0 } else if (x > contentSize.width - frame.size.width && contentSize.width > 0) { return contentSize.width - frame.size.width } else { return 0.0 } } private fun UIScrollView._requestBoundsY(y: Double): Double { if (y < 0.0) { return 0.0 } else if (contentSize.height < frame.height) { return 0.0 } else if (y > contentSize.height - frame.size.height && contentSize.height > 0) { return contentSize.height - frame.size.height } else { return 0.0 } }
gpl-3.0
86cae05f42c4a95d9fe626cddb470749
36.689655
225
0.658249
4.209938
false
false
false
false
jaymell/ip-mapper
src/main/kotlin/com/jaymell/ipmapper/MaxmindGeolocator.kt
1
1579
package com.jaymell.ipmapper import com.maxmind.geoip2.WebServiceClient import mu.KLogging import org.springframework.beans.factory.annotation.Autowired import java.net.InetAddress class MaxmindGeolocator(val maxmindAccountId: Int, val maxmindKey: String) : Geolocator { companion object : KLogging() @Autowired override lateinit var cache: IpLocationCache val client = WebServiceClient.Builder(maxmindAccountId, maxmindKey).build() override fun geolocate(ip: String): IpLocation { try { val ipAddress = InetAddress.getByName(ip) if (!org.apache.commons.validator.routines.InetAddressValidator().isValid(ip)) { throw InvalidIpLocationException("invalid ip address") } var cachedIpLocation: IpLocation? try { cachedIpLocation = cache.get(ip) } catch (e: Exception) { logger.error("Failed to query cache") throw e } if (cachedIpLocation != null) return cachedIpLocation // else query maxmind: val resp = client.insights(ipAddress) val respIpLocation = resp.toIpLocation(ip) try { cache.put(respIpLocation) } catch (e: Exception) { logger.error("Unable to insert record into cache") throw e } return respIpLocation } catch (e: java.net.UnknownHostException) { throw InvalidIpLocationException("invalid ip address") } } }
gpl-3.0
045fa690ef61326eaf896c4166053dd7
31.244898
92
0.614313
4.699405
false
false
false
false
JimSeker/ui
Dialogs/DialogViewModelDemo_kt/app/src/main/java/edu/cs4730/dialogviewmodeldemo_kt/CustomFragment.kt
1
4663
package edu.cs4730.dialogviewmodeldemo_kt import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.appcompat.view.ContextThemeWrapper import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider /** * This shows how to use the dialog that have been extended. Note the listeners are implemented * in the mainActivity and call the displaylog method at the bottom of this fragment. * This may not be the way you want to implements your listeners. It was easier for communication of * the fragments. Sometimes you want to the listeners om the dialog itself, if you have access to the * necessary functions and data. */ class CustomFragment : Fragment() { var TAG = "CustomFragment" lateinit var mViewModel: DataViewModel var logger: TextView? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val myView = inflater.inflate(R.layout.fragment_custom, container, false) logger = myView.findViewById(R.id.logger_custom) //note, I'm not setting up an observer here, but you could do here instead, but mainactivty "could" change the fragment //based on data, so for this example it's in main activity, but honesty doesn't need to be. mViewModel = ViewModelProvider(requireActivity())[DataViewModel::class.java] myView.findViewById<View>(R.id.btn_alert1).setOnClickListener { val newDialog = myDialogFragment.newInstance(myDialogFragment.DIALOG_TYPE_ID) newDialog.show(requireActivity().supportFragmentManager, "myDialog") } myView.findViewById<View>(R.id.btn_alert2).setOnClickListener { val newDialog = myDialogFragment.newInstance(myDialogFragment.DIALOG_GAMEOVER_ID) newDialog.show(requireActivity().supportFragmentManager, "myDialog") } myView.findViewById<View>(R.id.btn_alert3).setOnClickListener { val newDialog = myAlertDialogFragment.newInstance(R.string.alert_dialog_two_buttons_title) newDialog.show(requireActivity().supportFragmentManager, "myAlertDialog") } myView.findViewById<View>(R.id.btn_edit).setOnClickListener { val newDialog = myEditNameDialogFrag() newDialog.show(requireActivity().supportFragmentManager, "myEditDialog") } myView.findViewById<View>(R.id.inline_button).setOnClickListener { showInputDialog( "Inline Fragment" ) } myView.findViewById<View>(R.id.mutli_input_btn).setOnClickListener { val newDialog = MultiInputDialogFragment.newInstance("Jim", null) newDialog.show(requireActivity().supportFragmentManager, "myMultiInputDialog") } return myView } /** * simple method to display data to the logger textview. */ fun displaylog(item: String) { Log.v(TAG, item) if (logger != null) //this is called from the oncreate before logger exists, one time, so got to check.. logger!!.append(item + "\n") } /** * We are going to add data * setup a dialog fragment to ask the user for the new item data or category. */ fun showInputDialog(title: String?) { val inflater = LayoutInflater.from(activity) val textenter = inflater.inflate(R.layout.layout_custom_dialog, null) val userinput = textenter.findViewById<View>(R.id.item_added) as EditText val builder = AlertDialog.Builder( ContextThemeWrapper( activity, R.style.AppTheme_Dialog //androidx.appcompat.R.style.ThemeOverlay_AppCompat_Dialog ) ) builder.setView(textenter).setTitle(title) builder.setPositiveButton( "Add" ) { dialog, id -> mViewModel.setItem1("data is " + userinput.text.toString()) //Toast.makeText(getBaseContext(), userinput.getText().toString(), Toast.LENGTH_LONG).show(); } .setNegativeButton( "Cancel" ) { dialog, id -> mViewModel.setYesNo(false) dialog.cancel() } //you can create the dialog or just use the now method in the builder. //AlertDialog dialog = builder.create(); //dialog.show(); builder.show() } }
apache-2.0
8bd7a7c424468cfa61d45475efa17e10
42.990566
127
0.668883
4.630586
false
false
false
false
italoag/qksms
data/src/main/java/com/moez/QKSMS/mapper/CursorToRecipientImpl.kt
3
1873
/* * Copyright (C) 2017 Moez Bhatti <[email protected]> * * This file is part of QKSMS. * * QKSMS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QKSMS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with QKSMS. If not, see <http://www.gnu.org/licenses/>. */ package com.moez.QKSMS.mapper import android.content.Context import android.database.Cursor import android.net.Uri import com.moez.QKSMS.manager.PermissionManager import com.moez.QKSMS.model.Recipient import javax.inject.Inject class CursorToRecipientImpl @Inject constructor( private val context: Context, private val permissionManager: PermissionManager ) : CursorToRecipient { companion object { val URI = Uri.parse("content://mms-sms/canonical-addresses") const val COLUMN_ID = 0 const val COLUMN_ADDRESS = 1 } override fun map(from: Cursor) = Recipient( id = from.getLong(COLUMN_ID), address = from.getString(COLUMN_ADDRESS), lastUpdate = System.currentTimeMillis()) override fun getRecipientCursor(): Cursor? { return when (permissionManager.hasReadSms()) { true -> context.contentResolver.query(URI, null, null, null, null) false -> null } } override fun getRecipientCursor(id: Long): Cursor? { return context.contentResolver.query(URI, null, "_id = ?", arrayOf(id.toString()), null) } }
gpl-3.0
ab617d319327b36984280a6a76be2f43
32.464286
96
0.698345
4.227991
false
false
false
false
requery/requery
requery-android/src/main/java/io/requery/android/sqlite/SqliteStatement.kt
1
2862
/* * Copyright 2018 requery.io * * 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.requery.android.sqlite import android.annotation.SuppressLint import java.sql.ResultSet import java.sql.SQLException import java.sql.Statement /** * [java.sql.Statement] implementation using Android's local SQLite database. * * @author Nikhil Purushe */ internal class SqliteStatement(protected val sqliteConnection: SqliteConnection) : BaseStatement(sqliteConnection) { @Throws(SQLException::class) override fun execute(sql: String, autoGeneratedKeys: Int): Boolean { try { sqliteConnection.database.compileStatement(sql).use({ statement -> if (autoGeneratedKeys == Statement.RETURN_GENERATED_KEYS) { val rowId = statement.executeInsert() insertResult = SingleResultSet(this, rowId) return true } else { statement.execute() } }) } catch (e: android.database.SQLException) { BaseConnection.throwSQLException(e) } return false } @Throws(SQLException::class) override fun executeQuery(sql: String): ResultSet? { throwIfClosed() try { @SuppressLint("Recycle") // released with the queryResult val cursor = sqliteConnection.database.rawQuery(sql, null) queryResult = CursorResultSet(this, cursor, true) return queryResult } catch (e: android.database.SQLException) { BaseConnection.throwSQLException(e) } return null } @Throws(SQLException::class) override fun executeUpdate(sql: String, autoGeneratedKeys: Int): Int { try { sqliteConnection.database.compileStatement(sql).use({ statement -> if (autoGeneratedKeys == Statement.RETURN_GENERATED_KEYS) { val rowId = statement.executeInsert() insertResult = SingleResultSet(this, rowId) updateCount = 1 } else { updateCount = statement.executeUpdateDelete() } }) } catch (e: android.database.SQLException) { BaseConnection.throwSQLException(e) } return updateCount } }
apache-2.0
db97ca06db1695f988482a36a08aed82
33.071429
80
0.628581
4.951557
false
false
false
false
orbit/orbit
src/orbit-server/src/main/kotlin/orbit/server/mesh/AddressableManager.kt
1
4878
/* Copyright (C) 2015 - 2019 Electronic Arts Inc. All rights reserved. This file is part of the Orbit Project <https://www.orbit.cloud>. See license in LICENSE. */ package orbit.server.mesh import io.micrometer.core.instrument.Metrics import orbit.server.OrbitServerConfig import orbit.server.service.Meters import orbit.shared.addressable.AddressableLease import orbit.shared.addressable.AddressableReference import orbit.shared.addressable.NamespacedAddressableReference import orbit.shared.exception.PlacementFailedException import orbit.shared.mesh.Namespace import orbit.shared.mesh.NodeId import orbit.shared.mesh.NodeStatus import orbit.util.instrumentation.recordSuspended import orbit.util.misc.attempt import orbit.util.time.Clock import orbit.util.time.toTimestamp class AddressableManager( private val addressableDirectory: AddressableDirectory, private val clusterManager: ClusterManager, private val clock: Clock, config: OrbitServerConfig ) { private val leaseExpiration = config.addressableLeaseDuration private val placementTimer = Metrics.timer(Meters.Names.PlacementTimer) suspend fun locateOrPlace( namespace: Namespace, addressableReference: AddressableReference, ineligibleNodes: List<NodeId> = emptyList() ): NodeId = NamespacedAddressableReference(namespace, addressableReference).let { key -> addressableDirectory.getOrPut(key) { createNewEntry(key, ineligibleNodes) }.let { val invalidNode = clusterManager.getNode(it.nodeId) == null || (ineligibleNodes.contains(it.nodeId) == true) val expired = clock.inPast(it.expiresAt) if (expired || invalidNode) { val newEntry = createNewEntry(key, ineligibleNodes.plus(it.nodeId)) if (addressableDirectory.compareAndSet(key, it, newEntry)) { newEntry.nodeId } else { locateOrPlace(namespace, addressableReference, ineligibleNodes.plus(it.nodeId)) } } else { it.nodeId } } } // TODO: We need to take the expiry time suspend fun renewLease(addressableReference: AddressableReference, nodeId: NodeId): AddressableLease = addressableDirectory.manipulate( NamespacedAddressableReference( nodeId.namespace, addressableReference ) ) { initialValue -> if (initialValue == null || initialValue.nodeId != nodeId || clock.inPast(initialValue.expiresAt)) { throw PlacementFailedException("Could not renew lease for $addressableReference") } initialValue.copy( expiresAt = clock.now().plus(leaseExpiration.expiresIn).toTimestamp(), renewAt = clock.now().plus(leaseExpiration.renewIn).toTimestamp() ) }!! suspend fun abandonLease(addressableReference: AddressableReference, nodeId: NodeId): Boolean { val key = NamespacedAddressableReference(nodeId.namespace, addressableReference) val currentLease = addressableDirectory.get(key) if (currentLease != null && currentLease.nodeId == nodeId && clock.inFuture(currentLease.expiresAt)) { return addressableDirectory.compareAndSet(key, currentLease, null) } return false } private suspend fun createNewEntry(reference: NamespacedAddressableReference, invalidNodes: List<NodeId>) = AddressableLease( nodeId = place(reference, invalidNodes), reference = reference.addressableReference, expiresAt = clock.now().plus(leaseExpiration.expiresIn).toTimestamp(), renewAt = clock.now().plus(leaseExpiration.renewIn).toTimestamp() ) private suspend fun place(reference: NamespacedAddressableReference, invalidNodes: List<NodeId>): NodeId = runCatching { placementTimer.recordSuspended { attempt( maxAttempts = 5, initialDelay = 1000 ) { val allNodes = clusterManager.getAllNodes() val potentialNodes = allNodes .filter { !invalidNodes.contains(it.id) } .filter { it.id.namespace == reference.namespace } .filter { it.nodeStatus == NodeStatus.ACTIVE } .filter { it.capabilities.addressableTypes.contains(reference.addressableReference.type) } potentialNodes.random().id } } }.fold( { it }, { throw PlacementFailedException("Could not find node capable of hosting $reference") }) }
bsd-3-clause
6a2c77e3b486312aa4fc744342c2a16f
42.176991
114
0.642271
5.194888
false
false
false
false
RyotaMurohoshi/KotLinq
src/main/kotlin/com/muhron/kotlinq/firstOrDefault.kt
1
1127
package com.muhron.kotlinq // firstOrDefault fun <TSource> Sequence<TSource>.firstOrDefault(): TSource? = firstOrNull() fun <TSource> Iterable<TSource>.firstOrDefault(): TSource? = asSequence().firstOrDefault() fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.firstOrDefault(): Map.Entry<TSourceK, TSourceV>? = asSequence().firstOrDefault() fun <TSource> Array<TSource>.firstOrDefault(): TSource? = asSequence().firstOrDefault() // firstOrDefault with predicate inline fun <TSource> Sequence<TSource>.firstOrDefault(predicate: (TSource) -> Boolean): TSource? = firstOrNull(predicate) inline fun <TSource> Iterable<TSource>.firstOrDefault(predicate: (TSource) -> Boolean): TSource? = asSequence().firstOrDefault(predicate) inline fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.firstOrDefault(predicate: (Map.Entry<TSourceK, TSourceV>) -> Boolean): Map.Entry<TSourceK, TSourceV>? = asSequence().firstOrDefault(predicate) inline fun <TSource> Array<TSource>.firstOrDefault(predicate: (TSource) -> Boolean): TSource? = asSequence().firstOrDefault(predicate)
mit
57d5cce58ad890d60d62a413e33172e2
40.777778
159
0.728483
4.402344
false
false
false
false
encircled/jPut
jput-core/src/main/java/cz/encircled/jput/model/PerfTestConfiguration.kt
1
3322
package cz.encircled.jput.model /** * Performance test configuration of a single junit test method * * @author Vlad on 20-May-17. */ data class PerfTestConfiguration( /** * Unique test id, used to distinguish different tests. Default to `testClassName#testMethodName` */ val testId: String, /** * Count of warm up test executions */ val warmUp: Int = 0, /** * Test execution repeats count */ val repeats: Int = 1, /** * TODO */ val runTime: Long = 0L, /** * Delay between test repeats, in ms */ val delay: Long = 0L, /** * Upper limit for test execution time in milliseconds */ val maxTimeLimit: Long = 0L, /** * Upper limit for average execution time when using **repeats > 1**, in milliseconds */ val avgTimeLimit: Long = 0L, /** * Upper limits for test execution time in milliseconds within defined percentiles. Defining multiple percentiles allows * to have multiple validation constraints, for instance [200ms for 75%] and [500ms for 95%]. * * Map is rank to maxTime */ val percentiles: Map<Double, Long> = emptyMap(), /** * Count of maximum parallel executions (e.g. java threads in case of base executor or coroutines/reactive executions) */ val parallelCount: Int = 1, /** * Ramp-up in milliseconds. If parallel is 100, and the ramp-up period is 100000 (100 seconds), * then JPut will take 100 seconds to get all 100 threads running, i.e. 1 second delay after each new thread */ val rampUp: Long = 0, val isReactive: Boolean = false, /** * Unit test will be marked as failed, if catched exceptions count is greater than this parameter */ val maxAllowedExceptionsCount: Long = Long.MAX_VALUE, /** * TODO implement: reactive * * If true, jput will catch runtime exceptions and save errored repeats with result code "500" and corresponding error message. */ val continueOnException: Boolean = true, /** * Performance trend analyzing */ val trendConfiguration: TrendTestConfiguration? = null ) { fun valid(): PerfTestConfiguration { check(warmUp >= 0L) { "WarmUp count must be > 0" } check(repeats >= 1L) { "Repeats count must be > 1" } check(trendConfiguration == null || trendConfiguration.sampleSize >= 1) { "Sample size must be > 0" } percentiles.forEach { check(it.key in 0.0..1.0) { "Percentiles must be within 0..100" } check(it.value > 0L) { "Time limit for percentiles must be > 0" } } return this } override fun toString(): String { return "PerfTestConfiguration{" + "testId=$testId" + ", warmUp=$warmUp ms" + ", repeats=$repeats ms" + ", maxTimeLimit=$maxTimeLimit ms" + ", avgTimeLimit=$avgTimeLimit ms }" + ", percentiles=${percentiles.entries.joinToString()}" } }
apache-2.0
e796be21f4f902e1dd48ec98d4044220
29.477064
135
0.560506
4.646154
false
true
false
false
valich/intellij-markdown
src/commonMain/kotlin/org/intellij/markdown/ast/impl/ListCompositeNode.kt
1
1688
package org.intellij.markdown.ast.impl import org.intellij.markdown.IElementType import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.MarkdownTokenTypes import org.intellij.markdown.ast.ASTNode import org.intellij.markdown.ast.CompositeASTNode class ListCompositeNode(type: IElementType, children: List<ASTNode>) : CompositeASTNode(type, children) { val loose: Boolean by lazy(LazyThreadSafetyMode.NONE) { isLoose() } private fun isLoose(): Boolean { if (hasLooseContent(this)) { return true } for (child in children) { if (child.type == MarkdownElementTypes.LIST_ITEM && hasLooseContent(child)) { return true } } return false } companion object { private fun hasLooseContent(node: ASTNode): Boolean { var newlines = 0 var seenNonWhitespace = false for (child in node.children) { when (child.type) { MarkdownTokenTypes.EOL -> { ++newlines } MarkdownTokenTypes.LIST_BULLET, MarkdownTokenTypes.LIST_NUMBER, MarkdownTokenTypes.WHITE_SPACE -> { // do nothing; } else -> { if (seenNonWhitespace && newlines > 1) { return true } seenNonWhitespace = true newlines = 0 } } } return false } } }
apache-2.0
b1afefe405aaf1f2a43224b731d721a5
31.480769
105
0.510664
5.607973
false
false
false
false
envoyproxy/envoy
mobile/library/kotlin/io/envoyproxy/envoymobile/HeadersContainer.kt
2
4628
package io.envoyproxy.envoymobile /** * The container that manages the underlying headers map. * It maintains the original casing of passed header names. * It treats headers names as case-insensitive for the purpose * of header lookups and header name conflict resolutions. */ open class HeadersContainer { protected val headers: MutableMap<String, Header> /** * Represents a header name together with all of its values. * It preserves the original casing of the header name. * * @param name The name of the header. Its casing is preserved. * @param value The value associated with a given header. */ data class Header(val name: String, var value: MutableList<String>) { constructor(name: String) : this(name, mutableListOf()) /** * Add values. * * @param values The list of values to add. */ fun add(values: List<String>) { this.value.addAll(values) } /** * Add a value. * * @param value The value to add. */ fun add(value: String) { this.value.add(value) } } /** * Instantiate a new instance of the receiver using the provided headers map * * @param headers The headers to start with. */ internal constructor(headers: Map<String, MutableList<String>>) { var underlyingHeaders = mutableMapOf<String, Header>() /** * Dictionaries are unordered collections. Process headers with names * that are the same when lowercased in an alphabetical order to avoid a situation * in which the result of the initialization is non-derministic i.e., we want * mapOf("A" to listOf("1"), "a" to listOf("2")) headers to be always converted to * mapOf("A" to listOf("1", "2")) and never to mapOf("a" to listOf("2", "1")). * * If a given header name already exists in the processed headers map, check * if the currently processed header name is before the existing header name as * determined by an alphabetical order. */ headers.forEach { val lowercased = it.key.lowercase() val existing = underlyingHeaders[lowercased] if (existing == null) { underlyingHeaders[lowercased] = Header(it.key, it.value) } else if (existing.name > it.key) { underlyingHeaders[lowercased] = Header(it.key, (it.value + existing.value).toMutableList()) } else { underlyingHeaders[lowercased]?.add(it.value) } } this.headers = underlyingHeaders } companion object { /** * Create a new instance of the receiver using a provider headers map. * Not implemented as a constructor due to conflicting JVM signatures with * other constructors. * * @param headers The headers to create the container with. */ fun create(headers: Map<String, List<String>>) : HeadersContainer { return HeadersContainer(headers.mapValues { it.value.toMutableList() }) } } /** * Add a value to a header with a given name. * * @param name The name of the header. For the purpose of headers lookup * and header name conflict resolution, the name of the header * is considered to be case-insensitive. * @param value The value to add. */ fun add(name: String, value: String) { val lowercased = name.lowercase() headers[lowercased]?.let { it.add(value) } ?: run { headers.put(lowercased, Header(name, mutableListOf(value))) } } /** * Set the value of a given header. * * @param name The name of the header. * @param value The value to set the header value to. */ fun set(name: String, value: List<String>) { headers[name.lowercase()] = Header(name, value.toMutableList()) } /** * Remove a given header. * * @param name The name of the header to remove. */ fun remove(name: String) { headers.remove(name.lowercase()) } /** * Get the value for the provided header name. * * @param name The case-insensitive header name for which to * get the current value. * @return The value associated with a given header. */ fun value(name: String): List<String>? { return headers[name.lowercase()]?.value } /** * Accessor for all underlying case-sensitive headers. When possible, * use case-insensitive accessors instead. * * @return The underlying headers. */ fun caseSensitiveHeaders(): Map<String, List<String>> { var caseSensitiveHeaders = mutableMapOf<String, List<String>>() headers.forEach { caseSensitiveHeaders.put(it.value.name, it.value.value) } return caseSensitiveHeaders } }
apache-2.0
b5189c0582b0ef066e4460ca86beabd1
30.27027
99
0.65363
4.139535
false
false
false
false
breizhcamp/tools
src/main/java/org/breizhcamp/video/uploader/dto/VideoMetadata.kt
1
617
package org.breizhcamp.video.uploader.dto import com.fasterxml.jackson.annotation.JsonInclude import java.math.BigDecimal /** * JSON file stored aside of the video file to keep record of the current status */ @JsonInclude(JsonInclude.Include.NON_NULL) class VideoMetadata { var status: VideoInfo.Status? = null var progression: BigDecimal? = null var youtubeId: String? = null constructor() {} constructor(status: VideoInfo.Status, progression: BigDecimal, youtubeId: String) { this.status = status this.progression = progression this.youtubeId = youtubeId } }
mit
b0a307a8d591475fda5f95dae7c698f4
24.708333
87
0.719611
4.168919
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/analytics/UsageAnalytics.kt
1
18076
/**************************************************************************************** * Copyright (c) 2018 Mike Hardy <[email protected]> * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 3 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ package com.ichi2.anki.analytics import android.content.Context import android.content.SharedPreferences import android.os.Build import android.webkit.WebSettings import androidx.annotation.VisibleForTesting import androidx.core.content.edit import com.brsanthu.googleanalytics.GoogleAnalytics import com.brsanthu.googleanalytics.GoogleAnalyticsConfig import com.brsanthu.googleanalytics.httpclient.OkHttpClientImpl import com.brsanthu.googleanalytics.request.DefaultRequest import com.ichi2.anki.AnkiDroidApp import com.ichi2.anki.BuildConfig import com.ichi2.anki.R import com.ichi2.utils.DisplayUtils import com.ichi2.utils.KotlinCleanup import com.ichi2.utils.WebViewDebugging.hasSetDataDirectory import org.acra.ACRA import org.acra.util.Installation import timber.log.Timber @KotlinCleanup("see if we can make variables lazy, or properties without the `s` prefix") object UsageAnalytics { const val ANALYTICS_OPTIN_KEY = "analyticsOptIn" @KotlinCleanup("lateinit") private var sAnalytics: GoogleAnalytics? = null private var sOriginalUncaughtExceptionHandler: Thread.UncaughtExceptionHandler? = null private var sOptIn = false private var sAnalyticsTrackingId: String? = null private var sAnalyticsSamplePercentage = -1 /** * Initialize the analytics provider - must be called prior to sending anything. * Usage after that is static * Note: may need to implement sampling strategy internally to limit hits, or not track Reviewer... * * @param context required to look up the analytics codes for the app */ @Synchronized fun initialize(context: Context): GoogleAnalytics? { Timber.i("initialize()") if (sAnalytics == null) { Timber.d("App tracking id 'tid' = %s", getAnalyticsTag(context)) val gaConfig = GoogleAnalyticsConfig() .setBatchingEnabled(true) .setSamplePercentage(getAnalyticsSamplePercentage(context)) .setBatchSize(1) // until this handles application termination we will lose hits if batch>1 sAnalytics = GoogleAnalytics.builder() .withTrackingId(getAnalyticsTag(context)) .withConfig(gaConfig) .withDefaultRequest( AndroidDefaultRequest() .setAndroidRequestParameters(context) .applicationName(context.getString(R.string.app_name)) .applicationVersion(Integer.toString(BuildConfig.VERSION_CODE)) .applicationId(BuildConfig.APPLICATION_ID) .trackingId(getAnalyticsTag(context)) .clientId(Installation.id(context)) .anonymizeIp(context.resources.getBoolean(R.bool.ga_anonymizeIp)) ) .withHttpClient(OkHttpClientImpl(gaConfig)) .build() } installDefaultExceptionHandler() val userPrefs = AnkiDroidApp.getSharedPrefs(context) optIn = userPrefs.getBoolean(ANALYTICS_OPTIN_KEY, false) userPrefs.registerOnSharedPreferenceChangeListener { sharedPreferences: SharedPreferences, key: String -> if (key == ANALYTICS_OPTIN_KEY) { val newValue = sharedPreferences.getBoolean(key, false) Timber.i("Setting analytics opt-in to: %b", newValue) optIn = newValue } } return sAnalytics } private fun getAnalyticsTag(context: Context): String? { if (sAnalyticsTrackingId == null) { sAnalyticsTrackingId = context.getString(R.string.ga_trackingId) } return sAnalyticsTrackingId } private fun getAnalyticsSamplePercentage(context: Context): Int { if (sAnalyticsSamplePercentage == -1) { sAnalyticsSamplePercentage = context.resources.getInteger(R.integer.ga_sampleFrequency) } return sAnalyticsSamplePercentage } fun setDevMode() { Timber.d("setDevMode() re-configuring for development analytics tagging") sAnalyticsTrackingId = "UA-125800786-2" sAnalyticsSamplePercentage = 100 reInitialize() } /** * We want to send an analytics hit on any exception, then chain to other handlers (e.g., ACRA) */ @Synchronized private fun installDefaultExceptionHandler() { sOriginalUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler() Thread.setDefaultUncaughtExceptionHandler { thread: Thread?, throwable: Throwable -> sendAnalyticsException(throwable, true) if (thread == null) { Timber.w("unexpected: thread was null") return@setDefaultUncaughtExceptionHandler } sOriginalUncaughtExceptionHandler!!.uncaughtException(thread, throwable) } } /** * Reset the default exception handler */ @Synchronized private fun unInstallDefaultExceptionHandler() { Thread.setDefaultUncaughtExceptionHandler(sOriginalUncaughtExceptionHandler) sOriginalUncaughtExceptionHandler = null } /** * Determine whether we are disabled or not */ /** * Allow users to enable or disable analytics * * @param optIn true allows collection of analytics information */ @set:Synchronized private var optIn: Boolean get() { Timber.d("getOptIn() status: %s", sOptIn) return sOptIn } private set(optIn) { Timber.i("setOptIn(): from %s to %s", sOptIn, optIn) sOptIn = optIn sAnalytics!!.flush() sAnalytics!!.config.isEnabled = optIn sAnalytics!!.performSamplingElection() Timber.d("setOptIn() optIn / sAnalytics.config().enabled(): %s/%s", sOptIn, sAnalytics!!.config.isEnabled) } /** * Set the analytics up to log things, goes to hit validator. Experimental. * * @param dryRun set to true if you want to log analytics hit but not dispatch */ @Synchronized fun setDryRun(dryRun: Boolean) { Timber.i("setDryRun(): %s, warning dryRun is experimental", dryRun) } /** * Re-Initialize the analytics provider */ @Synchronized fun reInitialize() { // send any pending async hits, re-chain default exception handlers and re-init Timber.i("reInitialize()") sAnalytics!!.flush() sAnalytics = null unInstallDefaultExceptionHandler() initialize(AnkiDroidApp.instance.applicationContext) } /** * Submit a screen for aggregation / analysis. * Intended for use to determine if / how features are being used * * @param object the result of Object.getClass().getSimpleName() will be used as the screen tag */ @KotlinCleanup("rename object") fun sendAnalyticsScreenView(`object`: Any) { sendAnalyticsScreenView(`object`.javaClass.simpleName) } /** * Submit a screen display with a synthetic name for aggregation / analysis * Intended for use if your class handles multiple screens you want to track separately * * @param screenName screenName the name to show in analysis reports */ fun sendAnalyticsScreenView(screenName: String) { Timber.d("sendAnalyticsScreenView(): %s", screenName) if (!optIn) { return } sAnalytics!!.screenView().screenName(screenName).sendAsync() } /** * Send an arbitrary analytics event - these should be noun/verb pairs, e.g. "text to speech", "enabled" * * @param category the category of event, make your own but use a constant so reporting is good * @param action the action the user performed */ @KotlinCleanup("remove when all callers are Kotlin") fun sendAnalyticsEvent(category: String, action: String) { sendAnalyticsEvent(category, action, Integer.MIN_VALUE, null) } /** * Send a detailed arbitrary analytics event, with noun/verb pairs and extra data if needed * * @param category the category of event, make your own but use a constant so reporting is good * @param action the action the user performed * @param value A value for the event, Integer.MIN_VALUE signifies caller shouldn't send the value * @param label A label for the event, may be null */ fun sendAnalyticsEvent(category: String, action: String, value: Int = Int.MIN_VALUE, label: String? = null) { Timber.d("sendAnalyticsEvent() category/action/value/label: %s/%s/%s/%s", category, action, value, label) if (!optIn) { return } val event = sAnalytics!!.event().eventCategory(category).eventAction(action) if (label != null) { event.eventLabel(label) } if (value > Int.MIN_VALUE) { event.eventValue(value) } event.sendAsync() } /** * Send an exception event out for aggregation/analysis, parsed from the exception information * * @param t Throwable to send for analysis * @param fatal whether it was fatal or not */ fun sendAnalyticsException(t: Throwable, fatal: Boolean) { sendAnalyticsException(getCause(t).toString(), fatal) } @KotlinCleanup("convert to sequence") fun getCause(t: Throwable): Throwable { var cause: Throwable? var result = t while (null != result.cause.also { cause = it } && result != cause) { result = cause!! } return result } /** * Send an exception event out for aggregation/analysis * * @param description API limited to 100 characters, truncated here to 100 if needed * @param fatal whether it was fatal or not */ fun sendAnalyticsException(description: String, fatal: Boolean) { Timber.d("sendAnalyticsException() description/fatal: %s/%s", description, fatal) if (!sOptIn) { return } sAnalytics!!.exception().exceptionDescription(description).exceptionFatal(fatal).sendAsync() } internal fun canGetDefaultUserAgent(): Boolean { // #5502 - getDefaultUserAgent starts a WebView. We can't have two WebViews with the same data directory. // But ACRA starts an :acra process which does not terminate when AnkiDroid is restarted. https://crbug.com/558377 // if we're not under the ACRA process then we're fine to initialize a WebView return if (!ACRA.isACRASenderServiceProcess()) { true } else hasSetDataDirectory() // If we have a custom data directory, then the crash will not occur. } // A listener on this preference handles the rest var isEnabled: Boolean get() { val userPrefs = AnkiDroidApp.getSharedPrefs(AnkiDroidApp.instance) return userPrefs.getBoolean(ANALYTICS_OPTIN_KEY, false) } set(value) { // A listener on this preference handles the rest AnkiDroidApp.getSharedPrefs(AnkiDroidApp.instance).edit { putBoolean(ANALYTICS_OPTIN_KEY, value) } } @VisibleForTesting(otherwise = VisibleForTesting.NONE) fun resetForTests() { sAnalytics = null } /** * An Android-specific device config generator. Without this it's "Desktop" and unknown for all hardware. * It is interesting to us what devices people use though (for instance: is Amazon Kindle support worth it? * Is anyone still using e-ink devices? How many people are on tablets? ChromeOS?) */ private class AndroidDefaultRequest : DefaultRequest() { fun setAndroidRequestParameters(context: Context): DefaultRequest { // Are we running on really large screens or small screens? Send raw screen size try { val size = DisplayUtils.getDisplayDimensions(context) this.screenResolution(size.x.toString() + "x" + size.y) } catch (e: RuntimeException) { Timber.w(e) // nothing much to do here, it means we couldn't get WindowManager } // We can have up to 20 of these - there might be other things we want to know // but simply seeing what hardware we are running on should be useful this.customDimension(1, Build.VERSION.RELEASE) // systemVersion, e.g. "7.1.1" for Android 7.1.1 this.customDimension(2, Build.BRAND) // brand e.g. "OnePlus" this.customDimension(3, Build.MODEL) // model e.g. "ONEPLUS A6013" for the 6T this.customDimension(4, Build.BOARD) // deviceId e.g. "sdm845" for the 6T // This is important for google to auto-fingerprint us for default reporting // It is not possible to set operating system explicitly, there is no API or analytics parameter for it // Instead they respond that they auto-parse User-Agent strings for analytics attribution // For maximum analytics built-in report compatibility we will send the official WebView User-Agent string try { if (canGetDefaultUserAgent()) { this.userAgent(WebSettings.getDefaultUserAgent(context)) } else { this.userAgent(System.getProperty("http.agent")) } } catch (e: RuntimeException) { Timber.w(e) // Catch RuntimeException as WebView initialization blows up in unpredictable ways // but analytics should never be a show-stopper this.userAgent(System.getProperty("http.agent")) } return this } } object Category { const val SYNC = "Sync" const val LINK_CLICKED = "LinkClicked" } /** * These Strings must not be changed as they are used for analytic comparisons between AnkiDroid versions. * If a new string is added here then the respective changes must also be made in AnalyticsConstantsTest.java * All the constant strings added here must be annotated with @AnalyticsConstant. */ object Actions { /* Analytics actions used in Help Dialog*/ @AnalyticsConstant val OPENED_HELPDIALOG = "Opened HelpDialogBox" @AnalyticsConstant val OPENED_USING_ANKIDROID = "Opened Using AnkiDroid" @AnalyticsConstant val OPENED_GET_HELP = "Opened Get Help" @AnalyticsConstant val OPENED_SUPPORT_ANKIDROID = "Opened Support AnkiDroid" @AnalyticsConstant val OPENED_COMMUNITY = "Opened Community" @AnalyticsConstant val OPENED_PRIVACY = "Opened Privacy" @AnalyticsConstant val OPENED_ANKIWEB_TERMS_AND_CONDITIONS = "Opened AnkiWeb Terms and Conditions" @AnalyticsConstant val OPENED_ANKIDROID_PRIVACY_POLICY = "Opened AnkiDroid Privacy Policy" @AnalyticsConstant val OPENED_ANKIWEB_PRIVACY_POLICY = "Opened AnkiWeb Privacy Policy" @AnalyticsConstant val OPENED_ANKIDROID_MANUAL = "Opened AnkiDroid Manual" @AnalyticsConstant val OPENED_ANKI_MANUAL = "Opened Anki Manual" @AnalyticsConstant val OPENED_ANKIDROID_FAQ = "Opened AnkiDroid FAQ" @AnalyticsConstant val OPENED_MAILING_LIST = "Opened Mailing List" @AnalyticsConstant val OPENED_REPORT_BUG = "Opened Report a Bug" @AnalyticsConstant val OPENED_DONATE = "Opened Donate" @AnalyticsConstant val OPENED_TRANSLATE = "Opened Translate" @AnalyticsConstant val OPENED_DEVELOP = "Opened Develop" @AnalyticsConstant val OPENED_RATE = "Opened Rate" @AnalyticsConstant val OPENED_OTHER = "Opened Other" @AnalyticsConstant val OPENED_SEND_FEEDBACK = "Opened Send Feedback" @AnalyticsConstant val OPENED_ANKI_FORUMS = "Opened Anki Forums" @AnalyticsConstant val OPENED_REDDIT = "Opened Reddit" @AnalyticsConstant val OPENED_DISCORD = "Opened Discord" @AnalyticsConstant val OPENED_FACEBOOK = "Opened Facebook" @AnalyticsConstant val OPENED_TWITTER = "Opened Twitter" @AnalyticsConstant val EXCEPTION_REPORT = "Exception Report" @AnalyticsConstant val IMPORT_APKG_FILE = "Import APKG" @AnalyticsConstant val IMPORT_COLPKG_FILE = "Import COLPKG" @AnalyticsConstant val IMPORT_CSV_FILE = "Import CSV" } }
gpl-3.0
3bab51eea7ed4b6342f06db7552de2f4
38.99115
122
0.626853
4.87618
false
false
false
false
davidwhitman/Tir
GoodreadsApiSdk/src/main/kotlin/com/thunderclouddev/goodreadsapisdk/api/FriendUpdatesResponse.kt
1
402
package com.thunderclouddev.goodreadsapisdk.api import org.simpleframework.xml.Element import org.simpleframework.xml.Root /** * @author David Whitman on 16 Mar, 2017. */ @Root(name = "GoodreadsResponse") internal data class FriendUpdatesResponse( @field:Element(name = "Request") var request: Request = Request(), @field:Element(name = "updates") var updates: Updates = Updates() )
gpl-3.0
4e157764cd172fa5fa01caf58d4a3a84
30
74
0.731343
3.902913
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/service/SyncBuddiesList.kt
1
2700
package com.boardgamegeek.service import android.content.SyncResult import com.boardgamegeek.BggApplication import com.boardgamegeek.R import com.boardgamegeek.extensions.PREFERENCES_KEY_SYNC_BUDDIES import com.boardgamegeek.extensions.get import com.boardgamegeek.extensions.isOlderThan import com.boardgamegeek.io.BggService import com.boardgamegeek.pref.getBuddiesTimestamp import com.boardgamegeek.pref.setBuddiesTimestamp import com.boardgamegeek.repository.UserRepository import com.boardgamegeek.util.RemoteConfig import kotlinx.coroutines.runBlocking import retrofit2.HttpException import timber.log.Timber import java.util.concurrent.TimeUnit /** * Syncs the list of buddies. Only runs every few days. */ class SyncBuddiesList(application: BggApplication, service: BggService, syncResult: SyncResult) : SyncTask(application, service, syncResult) { private val repository = UserRepository(application) override val syncType = SyncService.FLAG_SYNC_BUDDIES override val notificationSummaryMessageId = R.string.sync_notification_buddies_list private val fetchIntervalInDays = RemoteConfig.getInt(RemoteConfig.KEY_SYNC_BUDDIES_FETCH_INTERVAL_DAYS) override fun execute() { Timber.i("Syncing list of buddies...") try { if (prefs[PREFERENCES_KEY_SYNC_BUDDIES, false] != true) { Timber.i("...buddies not set to sync") return } val lastCompleteSync = syncPrefs.getBuddiesTimestamp() if (lastCompleteSync >= 0 && !lastCompleteSync.isOlderThan(fetchIntervalInDays, TimeUnit.DAYS)) { Timber.i("...skipping; we synced already within the last $fetchIntervalInDays days") return } runBlocking { val updateTimestamp = System.currentTimeMillis() val (upsertedCount, deletedCount) = repository.refreshBuddies(updateTimestamp) syncResult.stats.numEntries += upsertedCount Timber.i("Upserted %,d buddies", upsertedCount) syncResult.stats.numDeletes += deletedCount Timber.i("Pruned %,d users who are no longer buddies", deletedCount) syncPrefs.setBuddiesTimestamp(updateTimestamp) } } catch (e: Exception) { if (e is HttpException) { showError(context.getString(notificationSummaryMessageId), e.code()) } else { showError(context.getString(notificationSummaryMessageId), e) } syncResult.stats.numIoExceptions++ cancel() } finally { Timber.i("...complete!") } } }
gpl-3.0
5f09a1c30377ca7dbac42f9bf691d4f5
36.5
109
0.680741
4.83871
false
false
false
false