repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
leafclick/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/dataFlow/readWrite/ReadBeforeWriteState.kt | 1 | 535 | // 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 org.jetbrains.plugins.groovy.lang.psi.dataFlow.readWrite
import java.util.*
class ReadBeforeWriteState(
val writes: BitSet = BitSet(),
val reads: BitSet = BitSet()
) : Cloneable {
public override fun clone(): ReadBeforeWriteState = ReadBeforeWriteState(writes.clone() as BitSet, reads.clone() as BitSet)
override fun toString(): String = "(writes=$writes, reads=$reads)"
}
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/Versions.kt | 1 | 1915 | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.tools.projectWizard
import org.jetbrains.kotlin.tools.projectWizard.settings.version.Version
@Suppress("ClassName", "SpellCheckingInspection")
object Versions {
val KOTLIN = version("1.4.10") // used as fallback version
val GRADLE = version("6.6.1")
val KTOR = version("1.5.2")
val JUNIT = version("4.13")
val JUNIT5 = version("5.6.0")
val JETBRAINS_COMPOSE = version("0.4.0")
val KOTLIN_VERSION_FOR_COMPOSE = version("1.5.10")
val GRADLE_VERSION_FOR_COMPOSE = version("6.9")
object COMPOSE {
val ANDROID_ACTIVITY_COMPOSE = version("1.3.0-alpha03")
}
object ANDROID {
val ANDROID_MATERIAL = version("1.2.1")
val ANDROIDX_APPCOMPAT = version("1.2.0")
val ANDROIDX_CONSTRAINTLAYOUT = version("2.0.2")
val ANDROIDX_KTX = version("1.3.1")
}
object KOTLINX {
val KOTLINX_HTML = version("0.7.2")
val KOTLINX_NODEJS: Version = version("0.0.7")
}
object JS_WRAPPERS {
val KOTLIN_REACT = wrapperVersion("17.0.2")
val KOTLIN_REACT_DOM = KOTLIN_REACT
val KOTLIN_STYLED = wrapperVersion("5.3.0")
val KOTLIN_REACT_ROUTER_DOM = wrapperVersion("5.2.0")
val KOTLIN_REDUX = wrapperVersion("4.0.5")
val KOTLIN_REACT_REDUX = wrapperVersion("7.2.3")
private fun wrapperVersion(version: String): Version =
version("$version-pre.206-kotlin-1.5.10")
}
object GRADLE_PLUGINS {
val ANDROID = version("4.0.2")
}
object MAVEN_PLUGINS {
val SUREFIRE = version("2.22.2")
val FAILSAFE = SUREFIRE
}
}
private fun version(version: String) = Version.fromString(version)
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/HasPlatformTypeInspection.kt | 1 | 2627 | // 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.inspections
import com.intellij.codeInspection.IntentionWrapper
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.intentions.SpecifyTypeExplicitlyIntention
import org.jetbrains.kotlin.idea.intentions.isFlexibleRecursive
import org.jetbrains.kotlin.idea.quickfix.AddExclExclCallFix
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import org.jetbrains.kotlin.psi.psiUtil.getNextSiblingIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.types.TypeUtils
import javax.swing.JComponent
class HasPlatformTypeInspection(
@JvmField var publicAPIOnly: Boolean = true,
@JvmField var reportPlatformArguments: Boolean = false
) : AbstractImplicitTypeInspection(
{ element, inspection ->
with(inspection as HasPlatformTypeInspection) {
SpecifyTypeExplicitlyIntention.dangerousFlexibleTypeOrNull(
element,
this.publicAPIOnly,
this.reportPlatformArguments
) != null
}
}
) {
override val problemText = KotlinBundle.message(
"declaration.has.type.inferred.from.a.platform.call.which.can.lead.to.unchecked.nullability.issues"
)
override fun additionalFixes(element: KtCallableDeclaration): List<LocalQuickFix>? {
val type = SpecifyTypeExplicitlyIntention.dangerousFlexibleTypeOrNull(
element, publicAPIOnly, reportPlatformArguments
) ?: return null
if (TypeUtils.isNullableType(type)) {
val expression = element.node.findChildByType(KtTokens.EQ)?.psi?.getNextSiblingIgnoringWhitespaceAndComments()
if (expression != null &&
(!reportPlatformArguments || !TypeUtils.makeNotNullable(type).isFlexibleRecursive())
) {
return listOf(IntentionWrapper(AddExclExclCallFix(expression), element.containingFile))
}
}
return null
}
override fun createOptionsPanel(): JComponent? {
val panel = MultipleCheckboxOptionsPanel(this)
panel.addCheckbox(KotlinBundle.message("apply.only.to.public.or.protected.members"), "publicAPIOnly")
panel.addCheckbox(KotlinBundle.message("report.for.types.with.platform.arguments"), "reportPlatformArguments")
return panel
}
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/intentions/conventionNameCalls/replaceContains/notContains.kt | 4 | 155 | fun test() {
class Test{
operator fun contains(a: Int) : Boolean = true
}
val test = Test()
if (!test.<caret>contains(1)) return
}
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/intentions/destructuringVariables/hasShadowedVariable.kt | 5 | 155 | // WITH_RUNTIME
fun main() {
data class A(var x: Int)
val <caret>a = A(0)
val x = a.x
run {
val x = 1
val z = a.x
}
} | apache-2.0 |
mseroczynski/CityBikes | app/src/main/kotlin/pl/ches/citybikes/domain/common/diagnostic/CrashlyticsTree.kt | 1 | 1015 | package pl.ches.citybikes.domain.common.diagnostic
import android.util.Log
import pl.ches.citybikes.di.scope.AppScope
import timber.log.Timber
import javax.inject.Inject
/**
* @author Michał Seroczyński <[email protected]>
*/
@AppScope
class CrashlyticsTree
@Inject
constructor() : Timber.Tree() {
override fun log(priority: Int, tag: String?, message: String?, t: Throwable?) {
if (priority == Log.VERBOSE || priority == Log.DEBUG || priority == Log.INFO) {
return
}
// TODO Crashlytics
// Crashlytics.setInt(CRASHLYTICS_KEY_PRIORITY, priority)
// Crashlytics.setString(CRASHLYTICS_KEY_TAG, tag)
// Crashlytics.setString(CRASHLYTICS_KEY_MESSAGE, message)
if (t == null) {
// Crashlytics.logException(Exception(message))
} else {
// Crashlytics.logException(t)
}
}
companion object {
private val CRASHLYTICS_KEY_PRIORITY = "priority"
private val CRASHLYTICS_KEY_TAG = "tag"
private val CRASHLYTICS_KEY_MESSAGE = "message"
}
} | gpl-3.0 |
JetBrains/xodus | environment/src/main/kotlin/jetbrains/exodus/log/BlockSet.kt | 1 | 4331 | /**
* Copyright 2010 - 2022 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.log
import jetbrains.exodus.core.dataStructures.hash.LongIterator
import jetbrains.exodus.core.dataStructures.persistent.PersistentBitTreeLongMap
import jetbrains.exodus.core.dataStructures.persistent.PersistentLongMap
import jetbrains.exodus.io.Block
// block key is aligned block address, i.e. block address divided by blockSize
sealed class BlockSet(val blockSize: Long, val set: PersistentLongMap<Block>) {
protected abstract val current: PersistentLongMap.ImmutableMap<Block>
fun size() = current.size()
val isEmpty get() = current.isEmpty
val minimum: Long? get() = current.iterator().let { if (it.hasNext()) it.next().key.keyToAddress else null }
val maximum: Long? get() = current.reverseIterator().let { if (it.hasNext()) it.next().key.keyToAddress else null }
/**
* Array of blocks' addresses in reverse order: the newer blocks first
*/
val array: LongArray
get() = getFiles(reversed = true)
@JvmOverloads
fun getFiles(reversed: Boolean = false): LongArray {
val current = current
val result = LongArray(current.size())
val it = if (reversed) {
current.reverseIterator()
} else {
current.iterator()
}
for (i in 0 until result.size) {
result[i] = it.next().key.keyToAddress
}
return result
}
fun contains(blockAddress: Long) = current.containsKey(blockAddress.addressToKey)
fun getBlock(blockAddress: Long): Block = current.get(blockAddress.addressToKey) ?: EmptyBlock(blockAddress)
// if address is inside of a block, the block containing it must be included as well if present
fun getFilesFrom(blockAddress: Long = 0L): LongIterator = object : LongIterator {
val it = if (blockAddress == 0L) current.iterator() else current.tailEntryIterator(blockAddress.addressToKey)
override fun next() = nextLong()
override fun hasNext() = it.hasNext()
override fun nextLong() = it.next().key.keyToAddress
override fun remove() = throw UnsupportedOperationException()
}
fun beginWrite() = Mutable(blockSize, set.clone)
protected val Long.keyToAddress: Long get() = this * blockSize
protected val Long.addressToKey: Long get() = this / blockSize
class Immutable @JvmOverloads constructor(
blockSize: Long,
map: PersistentLongMap<Block> = PersistentBitTreeLongMap()
) : BlockSet(blockSize, map) {
private val immutable: PersistentLongMap.ImmutableMap<Block> = map.beginRead()
public override val current: PersistentLongMap.ImmutableMap<Block>
get() = immutable
}
class Mutable(blockSize: Long, map: PersistentLongMap<Block>) : BlockSet(blockSize, map) {
private val mutable: PersistentLongMap.MutableMap<Block> = set.beginWrite()
override val current: PersistentLongMap.ImmutableMap<Block>
get() = mutable
fun clear() = mutable.clear()
fun add(blockAddress: Long, block: Block) = mutable.put(blockAddress.addressToKey, block)
fun remove(blockAddress: Long) = mutable.remove(blockAddress.addressToKey) != null
fun endWrite(): Immutable {
if (!mutable.endWrite()) {
throw IllegalStateException("File set can't be updated")
}
return Immutable(blockSize, set.clone)
}
}
private inner class EmptyBlock(private val address: Long) : Block {
override fun getAddress() = address
override fun length() = 0L
override fun read(output: ByteArray, position: Long, offset: Int, count: Int) = 0
override fun refresh() = this
}
}
| apache-2.0 |
jwren/intellij-community | plugins/toml/json/src/main/kotlin/org/toml/ide/json/TomlJsonSchemaCompletionContributor.kt | 5 | 7804 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.toml.ide.json
import com.intellij.codeInsight.completion.CompletionContributor
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.icons.AllIcons
import com.intellij.openapi.editor.EditorModificationUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.util.parentOfType
import com.intellij.util.Consumer
import com.intellij.util.ThreeState
import com.jetbrains.jsonSchema.extension.JsonLikePsiWalker
import com.jetbrains.jsonSchema.extension.adapters.JsonPropertyAdapter
import com.jetbrains.jsonSchema.ide.JsonSchemaService
import com.jetbrains.jsonSchema.impl.JsonSchemaDocumentationProvider
import com.jetbrains.jsonSchema.impl.JsonSchemaObject
import com.jetbrains.jsonSchema.impl.JsonSchemaResolver
import com.jetbrains.jsonSchema.impl.JsonSchemaType
import org.toml.ide.experiments.TomlExperiments
import org.toml.lang.psi.TomlLiteral
import org.toml.lang.psi.TomlTableHeader
import org.toml.lang.psi.ext.TomlLiteralKind
import org.toml.lang.psi.ext.kind
class TomlJsonSchemaCompletionContributor : CompletionContributor() {
override fun fillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet) {
if (!TomlExperiments.isJsonSchemaEnabled) return
val position = parameters.position
val jsonSchemaService = JsonSchemaService.Impl.get(position.project)
val jsonSchemaObject = jsonSchemaService.getSchemaObject(parameters.originalFile)
if (jsonSchemaObject != null) {
val completionPosition = parameters.originalPosition ?: parameters.position
val worker = Worker(jsonSchemaObject, parameters.position, completionPosition, result)
worker.work()
}
}
private class Worker(
private val rootSchema: JsonSchemaObject,
private val position: PsiElement,
private val originalPosition: PsiElement,
private val resultConsumer: Consumer<LookupElement?>
) {
val variants: MutableSet<LookupElement> = mutableSetOf()
private val walker: JsonLikePsiWalker? = JsonLikePsiWalker.getWalker(position, rootSchema)
private val project: Project = originalPosition.project
fun work() {
val checkable = walker?.findElementToCheck(position) ?: return
val isName = walker.isName(checkable)
val pointerPosition = walker.findPosition(checkable, isName == ThreeState.NO)
if (pointerPosition == null || pointerPosition.isEmpty && isName == ThreeState.NO) return
val schemas = JsonSchemaResolver(project, rootSchema, pointerPosition).resolve()
val knownNames = hashSetOf<String>()
for (schema in schemas) {
if (isName != ThreeState.NO) {
val properties = walker.getPropertyNamesOfParentObject(originalPosition, position)
val adapter = walker.getParentPropertyAdapter(checkable)
val schemaProperties = schema.properties
addAllPropertyVariants(properties, adapter, schemaProperties, knownNames, originalPosition)
}
if (isName != ThreeState.YES) {
suggestValues(schema, isName == ThreeState.NO)
}
}
for (variant in variants) {
resultConsumer.consume(variant)
}
}
private fun addAllPropertyVariants(
properties: Collection<String>,
adapter: JsonPropertyAdapter?,
schemaProperties: Map<String, JsonSchemaObject>,
knownNames: MutableSet<String>,
originalPosition: PsiElement
) {
val variants = schemaProperties.keys.filter { name ->
!properties.contains(name) && !knownNames.contains(name) || name == adapter?.name
}
for (variant in variants) {
knownNames.add(variant)
val jsonSchemaObject = schemaProperties[variant]
if (jsonSchemaObject != null) {
// skip basic types keys as they can't be in the table header
val isTomlHeader = originalPosition.parentOfType<TomlTableHeader>() != null
if (isTomlHeader && jsonSchemaObject.guessType() !in JSON_COMPOUND_TYPES) continue
addPropertyVariant(variant, jsonSchemaObject)
}
}
}
@Suppress("NAME_SHADOWING")
private fun addPropertyVariant(key: String, jsonSchemaObject: JsonSchemaObject) {
val currentVariants = JsonSchemaResolver(project, jsonSchemaObject).resolve()
val jsonSchemaObject = currentVariants.firstOrNull() ?: jsonSchemaObject
var description = JsonSchemaDocumentationProvider.getBestDocumentation(true, jsonSchemaObject)
if (description.isNullOrBlank()) {
description = jsonSchemaObject.getTypeDescription(true).orEmpty()
}
val lookupElement = LookupElementBuilder.create(key)
.withTypeText(description)
.withIcon(getIconForType(jsonSchemaObject.guessType()))
variants.add(lookupElement)
}
private val isInsideStringLiteral: Boolean
get() = (position.parent as? TomlLiteral)?.kind is TomlLiteralKind.String
private fun suggestValues(schema: JsonSchemaObject, isSurelyValue: Boolean) {
val enumVariants = schema.enum
if (enumVariants != null) {
for (o in enumVariants) {
if (isInsideStringLiteral && o !is String) continue
val variant = if (isInsideStringLiteral) {
StringUtil.unquoteString(o.toString())
} else {
o.toString()
}
variants.add(LookupElementBuilder.create(variant))
}
} else if (isSurelyValue) {
variants.addAll(suggestValuesByType(schema.guessType()))
}
}
private fun suggestValuesByType(type: JsonSchemaType?): List<LookupElement> = when (type) {
JsonSchemaType._object -> listOf(buildPairLookupElement("{}"))
JsonSchemaType._array -> listOf(buildPairLookupElement("[]"))
JsonSchemaType._string -> if (isInsideStringLiteral) {
emptyList()
} else {
listOf(buildPairLookupElement("\"\""))
}
JsonSchemaType._boolean -> listOf("true", "false").map { LookupElementBuilder.create(it) }
else -> emptyList()
}
private fun buildPairLookupElement(element: String): LookupElementBuilder =
LookupElementBuilder.create(element)
.withInsertHandler { context, _ ->
EditorModificationUtil.moveCaretRelatively(context.editor, -1)
}
private fun getIconForType(type: JsonSchemaType?) = when (type) {
JsonSchemaType._object -> AllIcons.Json.Object
JsonSchemaType._array -> AllIcons.Json.Array
else -> AllIcons.Nodes.Property
}
}
companion object {
private val JSON_COMPOUND_TYPES = listOf(
JsonSchemaType._array, JsonSchemaType._object,
JsonSchemaType._any, null // type is uncertain
)
}
}
| apache-2.0 |
jwren/intellij-community | plugins/kotlin/completion/tests/testData/handlers/basic/callableReference/NonEmptyQualifier.kt | 8 | 163 | // FIR_IDENTICAL
// FIR_COMPARISON
class C {
fun foo() {
val v = D::<caret>
}
}
class D {
fun memberFun(s: String){}
}
// ELEMENT: memberFun
| apache-2.0 |
jwren/intellij-community | platform/workspaceModel/jps/src/com/intellij/workspaceModel/ide/impl/jps/serialization/JpsProjectSerializersImpl.kt | 1 | 46220 | // 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.workspaceModel.ide.impl.jps.serialization
import com.intellij.diagnostic.AttachmentFactory
import com.intellij.openapi.components.ExpandMacroToPathMap
import com.intellij.openapi.components.PathMacroManager
import com.intellij.openapi.components.impl.ModulePathMacroManager
import com.intellij.openapi.components.impl.ProjectPathMacroManager
import com.intellij.openapi.diagnostic.Attachment
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.diagnostic.trace
import com.intellij.openapi.module.impl.ModulePath
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.projectModel.ProjectModelBundle
import com.intellij.util.Function
import com.intellij.util.PathUtil
import com.intellij.util.containers.BidirectionalMap
import com.intellij.util.containers.BidirectionalMultiMap
import com.intellij.util.text.UniqueNameGenerator
import com.intellij.workspaceModel.ide.*
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.bridgeEntities.*
import com.intellij.workspaceModel.storage.impl.reportErrorAndAttachStorage
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap
import org.jdom.Element
import org.jdom.JDOMException
import org.jetbrains.annotations.TestOnly
import org.jetbrains.jps.util.JpsPathUtil
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import java.util.concurrent.Callable
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ForkJoinTask
import java.util.function.Supplier
import kotlin.streams.toList
class JpsProjectSerializersImpl(directorySerializersFactories: List<JpsDirectoryEntitiesSerializerFactory<*>>,
moduleListSerializers: List<JpsModuleListSerializer>,
reader: JpsFileContentReader,
private val entityTypeSerializers: List<JpsFileEntityTypeSerializer<*>>,
private val configLocation: JpsProjectConfigLocation,
private val externalStorageMapping: JpsExternalStorageMapping,
private val enableExternalStorage: Boolean,
private val virtualFileManager: VirtualFileUrlManager,
fileInDirectorySourceNames: FileInDirectorySourceNames) : JpsProjectSerializers {
private val lock = Any()
val moduleSerializers = BidirectionalMap<JpsFileEntitiesSerializer<*>, JpsModuleListSerializer>()
internal val serializerToDirectoryFactory = BidirectionalMap<JpsFileEntitiesSerializer<*>, JpsDirectoryEntitiesSerializerFactory<*>>()
private val internalSourceToExternal = HashMap<JpsFileEntitySource, JpsFileEntitySource>()
internal val fileSerializersByUrl = BidirectionalMultiMap<String, JpsFileEntitiesSerializer<*>>()
internal val fileIdToFileName = Int2ObjectOpenHashMap<String>()
// Map of module serializer to boolean that defines whenever modules.xml is external or not
private val moduleSerializerToExternalSourceBool = mutableMapOf<JpsFileEntitiesSerializer<*>, Boolean>()
init {
synchronized(lock) {
for (factory in directorySerializersFactories) {
createDirectorySerializers(factory, fileInDirectorySourceNames).associateWithTo(serializerToDirectoryFactory) { factory }
}
val enabledModuleListSerializers = moduleListSerializers.filter { enableExternalStorage || !it.isExternalStorage }
val moduleFiles = enabledModuleListSerializers.flatMap { ser ->
ser.loadFileList(reader, virtualFileManager).map {
Triple(it.first, it.second, ser.isExternalStorage)
}
}
for ((moduleFile, moduleGroup, isOriginallyExternal) in moduleFiles) {
val directoryUrl = virtualFileManager.getParentVirtualUrl(moduleFile)!!
val internalSource =
bindExistingSource(fileInDirectorySourceNames, ModuleEntity::class.java, moduleFile.fileName, directoryUrl) ?:
createFileInDirectorySource(directoryUrl, moduleFile.fileName)
for (moduleListSerializer in enabledModuleListSerializers) {
val moduleSerializer = moduleListSerializer.createSerializer(internalSource, moduleFile, moduleGroup)
moduleSerializers[moduleSerializer] = moduleListSerializer
moduleSerializerToExternalSourceBool[moduleSerializer] = isOriginallyExternal
}
}
val allFileSerializers = entityTypeSerializers.filter { enableExternalStorage || !it.isExternalStorage } +
serializerToDirectoryFactory.keys + moduleSerializers.keys
allFileSerializers.forEach {
fileSerializersByUrl.put(it.fileUrl.url, it)
}
}
}
internal val directorySerializerFactoriesByUrl = directorySerializersFactories.associateBy { it.directoryUrl }
val moduleListSerializersByUrl = moduleListSerializers.associateBy { it.fileUrl }
private fun createFileInDirectorySource(directoryUrl: VirtualFileUrl, fileName: String): JpsFileEntitySource.FileInDirectory {
val source = JpsFileEntitySource.FileInDirectory(directoryUrl, configLocation)
// Don't convert to links[key] = ... because it *may* became autoboxing
@Suppress("ReplacePutWithAssignment")
fileIdToFileName.put(source.fileNameId, fileName)
LOG.debug { "createFileInDirectorySource: ${source.fileNameId}=$fileName" }
return source
}
private fun createDirectorySerializers(factory: JpsDirectoryEntitiesSerializerFactory<*>,
fileInDirectorySourceNames: FileInDirectorySourceNames): List<JpsFileEntitiesSerializer<*>> {
val osPath = JpsPathUtil.urlToOsPath(factory.directoryUrl)
val libPath = Paths.get(osPath)
val files = when {
Files.isDirectory(libPath) -> Files.list(libPath).use { stream ->
stream.filter { path: Path -> PathUtil.getFileExtension(path.toString()) == "xml" && Files.isRegularFile(path) }
.toList()
}
else -> emptyList()
}
return files.map {
val fileName = it.fileName.toString()
val directoryUrl = virtualFileManager.fromUrl(factory.directoryUrl)
val entitySource =
bindExistingSource(fileInDirectorySourceNames, factory.entityClass, fileName, directoryUrl) ?:
createFileInDirectorySource(directoryUrl, fileName)
factory.createSerializer("${factory.directoryUrl}/$fileName", entitySource, virtualFileManager)
}
}
private fun bindExistingSource(fileInDirectorySourceNames: FileInDirectorySourceNames,
entityType: Class<out WorkspaceEntity>,
fileName: String,
directoryUrl: VirtualFileUrl): JpsFileEntitySource.FileInDirectory? {
val source = fileInDirectorySourceNames.findSource(entityType, fileName)
if (source == null || source.directory != directoryUrl) return null
@Suppress("ReplacePutWithAssignment")
fileIdToFileName.put(source.fileNameId, fileName)
LOG.debug { "bindExistingSource: ${source.fileNameId}=$fileName" }
return source
}
fun findModuleSerializer(modulePath: ModulePath): JpsFileEntitiesSerializer<*>? {
synchronized(lock) {
return fileSerializersByUrl.getValues(VfsUtilCore.pathToUrl(modulePath.path)).first()
}
}
override fun reloadFromChangedFiles(change: JpsConfigurationFilesChange,
reader: JpsFileContentReader,
errorReporter: ErrorReporter): Pair<Set<EntitySource>, WorkspaceEntityStorageBuilder> {
val obsoleteSerializers = ArrayList<JpsFileEntitiesSerializer<*>>()
val newFileSerializers = ArrayList<JpsFileEntitiesSerializer<*>>()
val addedFileUrls = change.addedFileUrls.flatMap {
val file = JpsPathUtil.urlToFile(it)
if (file.isDirectory) {
file.list()?.map { fileName -> "$it/$fileName" } ?: emptyList()
} else listOf(it)
}.toSet()
val affectedFileLoaders: LinkedHashSet<JpsFileEntitiesSerializer<*>>
val changedSources = HashSet<JpsFileEntitySource>()
synchronized(lock) {
for (addedFileUrl in addedFileUrls) {
// The file may already be processed during class initialization
if (fileSerializersByUrl.containsKey(addedFileUrl)) continue
val factory = directorySerializerFactoriesByUrl[PathUtil.getParentPath(addedFileUrl)]
val newFileSerializer = factory?.createSerializer(addedFileUrl, createFileInDirectorySource(
virtualFileManager.fromUrl(factory.directoryUrl), PathUtil.getFileName(addedFileUrl)), virtualFileManager)
if (newFileSerializer != null) {
newFileSerializers.add(newFileSerializer)
serializerToDirectoryFactory[newFileSerializer] = factory
}
}
for (changedUrl in change.changedFileUrls) {
val serializerFactory = moduleListSerializersByUrl[changedUrl]
if (serializerFactory != null) {
val newFileUrls = serializerFactory.loadFileList(reader, virtualFileManager)
val oldSerializers: List<JpsFileEntitiesSerializer<*>> = moduleSerializers.getKeysByValue(serializerFactory) ?: emptyList()
val oldFileUrls = oldSerializers.mapTo(HashSet()) { it.fileUrl }
val newFileUrlsSet = newFileUrls.mapTo(HashSet()) { it.first }
val obsoleteSerializersForFactory = oldSerializers.filter { it.fileUrl !in newFileUrlsSet }
obsoleteSerializersForFactory.forEach {
moduleSerializers.remove(it, serializerFactory)
moduleSerializerToExternalSourceBool.remove(it)
}
val newFileSerializersForFactory = newFileUrls.filter { it.first !in oldFileUrls }.map {
serializerFactory.createSerializer(createFileInDirectorySource(virtualFileManager.getParentVirtualUrl(it.first)!!,
it.first.fileName), it.first, it.second)
}
newFileSerializersForFactory.associateWithTo(moduleSerializerToExternalSourceBool) { serializerFactory.isExternalStorage }
newFileSerializersForFactory.associateWithTo(moduleSerializers) { serializerFactory }
obsoleteSerializers.addAll(obsoleteSerializersForFactory)
newFileSerializers.addAll(newFileSerializersForFactory)
}
}
for (newSerializer in newFileSerializers) {
fileSerializersByUrl.put(newSerializer.fileUrl.url, newSerializer)
}
for (obsoleteSerializer in obsoleteSerializers) {
fileSerializersByUrl.remove(obsoleteSerializer.fileUrl.url, obsoleteSerializer)
}
affectedFileLoaders = LinkedHashSet(newFileSerializers)
addedFileUrls.flatMapTo(affectedFileLoaders) { fileSerializersByUrl.getValues(it) }
change.changedFileUrls.flatMapTo(affectedFileLoaders) { fileSerializersByUrl.getValues(it) }
affectedFileLoaders.mapTo(changedSources) { it.internalEntitySource }
for (fileUrl in change.removedFileUrls) {
val directorySerializer = directorySerializerFactoriesByUrl[fileUrl]
if (directorySerializer != null) {
val serializers = serializerToDirectoryFactory.getKeysByValue(directorySerializer)?.toList() ?: emptyList()
for (serializer in serializers) {
fileSerializersByUrl.removeValue(serializer)
obsoleteSerializers.add(serializer)
serializerToDirectoryFactory.remove(serializer, directorySerializer)
}
} else {
val obsolete = fileSerializersByUrl.getValues(fileUrl)
fileSerializersByUrl.removeKey(fileUrl)
obsoleteSerializers.addAll(obsolete)
obsolete.forEach {
serializerToDirectoryFactory.remove(it)
}
}
}
obsoleteSerializers.mapTo(changedSources) { it.internalEntitySource }
obsoleteSerializers.asSequence().map { it.internalEntitySource }.filterIsInstance(JpsFileEntitySource.FileInDirectory::class.java).forEach {
fileIdToFileName.remove(it.fileNameId)
LOG.debug { "remove association for ${it.fileNameId}" }
}
}
val builder = WorkspaceEntityStorageBuilder.create()
affectedFileLoaders.forEach {
loadEntitiesAndReportExceptions(it, builder, reader, errorReporter)
}
return Pair(changedSources, builder)
}
override fun loadAll(reader: JpsFileContentReader,
builder: WorkspaceEntityStorageBuilder,
errorReporter: ErrorReporter,
project: Project?): List<EntitySource> {
val serializers = synchronized(lock) { fileSerializersByUrl.values.toList() }
val tasks = serializers.map { serializer ->
ForkJoinTask.adapt(Callable {
val myBuilder = WorkspaceEntityStorageBuilder.create()
loadEntitiesAndReportExceptions(serializer, myBuilder, reader, errorReporter)
myBuilder
})
}
ForkJoinTask.invokeAll(tasks)
val builders = tasks.mapNotNull { it.rawResult }
val sourcesToUpdate = removeDuplicatingEntities(builders, serializers, project)
val squashedBuilder = squash(builders)
builder.addDiff(squashedBuilder)
return sourcesToUpdate
}
private fun loadEntitiesAndReportExceptions(serializer: JpsFileEntitiesSerializer<*>,
builder: WorkspaceEntityStorageBuilder,
reader: JpsFileContentReader,
errorReporter: ErrorReporter) {
fun reportError(e: Exception, url: VirtualFileUrl) {
errorReporter.reportError(ProjectModelBundle.message("module.cannot.load.error", url.presentableUrl, e.localizedMessage), url)
}
try {
serializer.loadEntities(builder, reader, errorReporter, virtualFileManager)
}
catch (e: JDOMException) {
reportError(e, serializer.fileUrl)
}
catch (e: IOException) {
reportError(e, serializer.fileUrl)
}
}
// Check if the same module is loaded from different source. This may happen in case of two `modules.xml` with the same module.
// See IDEA-257175
// This code may be removed if we'll get rid of storing modules.xml and friends in external storage (cache/external_build_system)
private fun removeDuplicatingEntities(builders: List<WorkspaceEntityStorageBuilder>, serializers: List<JpsFileEntitiesSerializer<*>>, project: Project?): List<EntitySource> {
if (project == null) return emptyList()
val modules = mutableMapOf<String, MutableList<Triple<ModuleId, WorkspaceEntityStorageBuilder, JpsFileEntitiesSerializer<*>>>>()
val libraries = mutableMapOf<LibraryId, MutableList<Pair<WorkspaceEntityStorageBuilder, JpsFileEntitiesSerializer<*>>>>()
val artifacts = mutableMapOf<ArtifactId, MutableList<Pair<WorkspaceEntityStorageBuilder, JpsFileEntitiesSerializer<*>>>>()
builders.forEachIndexed { i, builder ->
if (enableExternalStorage) {
builder.entities(ModuleEntity::class.java).forEach { module ->
val moduleId = module.persistentId()
modules.getOrPut(moduleId.name.toLowerCase(Locale.US)) { ArrayList() }.add(Triple(moduleId, builder, serializers[i]))
}
}
builder.entities(LibraryEntity::class.java).filter { it.tableId == LibraryTableId.ProjectLibraryTableId }.forEach { library ->
libraries.getOrPut(library.persistentId()) { ArrayList() }.add(builder to serializers[i])
}
builder.entities(ArtifactEntity::class.java).forEach { artifact ->
artifacts.getOrPut(artifact.persistentId()) { ArrayList() }.add(builder to serializers[i])
}
}
val sourcesToUpdate = mutableListOf<EntitySource>()
for ((_, buildersWithModule) in modules) {
if (buildersWithModule.size <= 1) continue
var correctModuleFound = false
var leftModuleId = 0
// Leave only first module with "correct" entity source
// If there is no such module, leave the last one
buildersWithModule.forEachIndexed { index, (moduleId, builder, ser) ->
val originalExternal = moduleSerializerToExternalSourceBool[ser] ?: return@forEachIndexed
val moduleEntity = builder.resolve(moduleId)!!
if (index != buildersWithModule.lastIndex) {
if (!correctModuleFound && originalExternal) {
correctModuleFound = true
leftModuleId = index
}
else {
sourcesToUpdate += moduleEntity.entitySource
builder.removeEntity(moduleEntity)
}
}
else {
if (correctModuleFound) {
sourcesToUpdate += moduleEntity.entitySource
builder.removeEntity(moduleEntity)
}
else {
leftModuleId = index
}
}
}
reportIssue(project, buildersWithModule.mapTo(HashSet()) { it.first }, buildersWithModule.map { it.third }, leftModuleId)
}
for ((libraryId, buildersWithSerializers) in libraries) {
if (buildersWithSerializers.size <= 1) continue
val defaultFileName = FileUtil.sanitizeFileName(libraryId.name) + ".xml"
val hasImportedEntity = buildersWithSerializers.any { (builder, _) ->
builder.resolve(libraryId)!!.entitySource is JpsImportedEntitySource
}
val entitiesToRemove = buildersWithSerializers.mapNotNull { (builder, serializer) ->
val library = builder.resolve(libraryId)!!
val entitySource = library.entitySource
if (entitySource !is JpsFileEntitySource.FileInDirectory) return@mapNotNull null
val fileName = serializer.fileUrl.fileName
if (fileName != defaultFileName || enableExternalStorage && hasImportedEntity) Triple(builder, library, fileName) else null
}
LOG.warn("Multiple configuration files were found for '${libraryId.name}' library.")
if (entitiesToRemove.isNotEmpty() && entitiesToRemove.size < buildersWithSerializers.size) {
for ((builder, entity) in entitiesToRemove) {
sourcesToUpdate.add(entity.entitySource)
builder.removeEntity(entity)
}
LOG.warn("Libraries defined in ${entitiesToRemove.joinToString { it.third }} files will ignored and these files will be removed.")
}
else {
LOG.warn("Cannot determine which configuration file should be ignored: ${buildersWithSerializers.map { it.second }}")
}
}
for ((artifactId, buildersWithSerializers) in artifacts) {
if (buildersWithSerializers.size <= 1) continue
val defaultFileName = FileUtil.sanitizeFileName(artifactId.name) + ".xml"
val hasImportedEntity = buildersWithSerializers.any { (builder, _) ->
builder.resolve(artifactId)!!.entitySource is JpsImportedEntitySource
}
val entitiesToRemove = buildersWithSerializers.mapNotNull { (builder, serializer) ->
val artifact = builder.resolve(artifactId)!!
val entitySource = artifact.entitySource
if (entitySource !is JpsFileEntitySource.FileInDirectory) return@mapNotNull null
val fileName = serializer.fileUrl.fileName
if (fileName != defaultFileName || enableExternalStorage && hasImportedEntity) Triple(builder, artifact, fileName) else null
}
LOG.warn("Multiple configuration files were found for '${artifactId.name}' artifact.")
if (entitiesToRemove.isNotEmpty() && entitiesToRemove.size < buildersWithSerializers.size) {
for ((builder, entity) in entitiesToRemove) {
sourcesToUpdate.add(entity.entitySource)
builder.removeEntity(entity)
}
LOG.warn("Artifacts defined in ${entitiesToRemove.joinToString { it.third }} files will ignored and these files will be removed.")
}
else {
LOG.warn("Cannot determine which configuration file should be ignored: ${buildersWithSerializers.map { it.second }}")
}
}
return sourcesToUpdate
}
private fun reportIssue(project: Project, moduleIds: Set<ModuleId>, serializers: List<JpsFileEntitiesSerializer<*>>, leftModuleId: Int) {
var serializerCounter = -1
val attachments = mutableMapOf<String, Attachment>()
val serializersInfo = serializers.joinToString(separator = "\n\n") {
serializerCounter++
it as ModuleImlFileEntitiesSerializer
val externalFileUrl = it.let {
it.externalModuleListSerializer?.createSerializer(it.internalEntitySource, it.fileUrl, it.modulePath.group)
}?.fileUrl
val fileUrl = it.fileUrl
val internalModuleListSerializerUrl = it.internalModuleListSerializer?.fileUrl
val externalModuleListSerializerUrl = it.externalModuleListSerializer?.fileUrl
if (externalFileUrl != null && FileUtil.exists(JpsPathUtil.urlToPath(externalFileUrl.url))) {
attachments[externalFileUrl.url] = AttachmentFactory.createAttachment(externalFileUrl.toPath(), false)
}
if (FileUtil.exists(JpsPathUtil.urlToPath(fileUrl.url))) {
attachments[fileUrl.url] = AttachmentFactory.createAttachment(fileUrl.toPath(), false)
}
if (internalModuleListSerializerUrl != null && FileUtil.exists(JpsPathUtil.urlToPath(internalModuleListSerializerUrl))) {
attachments[internalModuleListSerializerUrl] = AttachmentFactory.createAttachment(
Path.of(JpsPathUtil.urlToPath(internalModuleListSerializerUrl)
), false)
}
if (externalModuleListSerializerUrl != null && FileUtil.exists(JpsPathUtil.urlToPath(externalModuleListSerializerUrl))) {
attachments[externalModuleListSerializerUrl] = AttachmentFactory.createAttachment(
Path.of(JpsPathUtil.urlToPath(externalModuleListSerializerUrl)), false
)
}
"""
Serializer info #$serializerCounter:
Is external: ${moduleSerializerToExternalSourceBool[it]}
fileUrl: ${fileUrl.presentableUrl}
externalFileUrl: ${externalFileUrl?.presentableUrl}
internal modules.xml: $internalModuleListSerializerUrl
external modules.xml: $externalModuleListSerializerUrl
""".trimIndent()
}
val text = """
|Trying to load multiple modules with the same name.
|
|Project: ${project.name}
|Module: ${moduleIds.map { it.name }}
|Amount of modules: ${serializers.size}
|Leave module of nth serializer: $leftModuleId
|
|$serializersInfo
""".trimMargin()
LOG.error(text, *attachments.values.toTypedArray())
}
private fun squash(builders: List<WorkspaceEntityStorageBuilder>): WorkspaceEntityStorageBuilder {
var result = builders
while (result.size > 1) {
result = result.chunked(2) { list ->
val res = list.first()
if (list.size == 2) res.addDiff(list.last())
res
}
}
return result.singleOrNull() ?: WorkspaceEntityStorageBuilder.create() }
@TestOnly
override fun saveAllEntities(storage: WorkspaceEntityStorage, writer: JpsFileContentWriter) {
moduleListSerializersByUrl.values.forEach {
saveModulesList(it, storage, writer)
}
val allSources = storage.entitiesBySource { true }.keys
saveEntities(storage, allSources, writer)
}
internal fun getActualFileUrl(source: EntitySource): String? {
val actualFileSource = getActualFileSource(source) ?: return null
return when (actualFileSource) {
is JpsFileEntitySource.ExactFile -> actualFileSource.file.url
is JpsFileEntitySource.FileInDirectory -> {
val fileName = fileIdToFileName.get(actualFileSource.fileNameId) ?: run {
// We have a situations when we don't have an association at for `fileIdToFileName` entity source returned from `getActualFileSource`
// but we have it for the original `JpsImportedEntitySource.internalFile` and base on it we try to calculate actual file url
if (source is JpsImportedEntitySource && source.internalFile is JpsFileEntitySource.FileInDirectory && source.storedExternally) {
fileIdToFileName.get((source.internalFile as JpsFileEntitySource.FileInDirectory).fileNameId)?.substringBeforeLast(".")?.let { "$it.xml" }
} else null
}
if (fileName != null) actualFileSource.directory.url + "/" + fileName else null
}
else -> error("Unexpected implementation of JpsFileEntitySource: ${actualFileSource.javaClass}")
}
}
private fun getActualFileSource(source: EntitySource): JpsFileEntitySource? {
return when (source) {
is JpsImportedEntitySource -> {
if (source.storedExternally) {
//todo remove obsolete entries
internalSourceToExternal.getOrPut(source.internalFile) { externalStorageMapping.getExternalSource(source.internalFile) }
}
else {
source.internalFile
}
}
else -> getInternalFileSource(source)
}
}
override fun getAllModulePaths(): List<ModulePath> {
synchronized(lock) {
return fileSerializersByUrl.values.filterIsInstance<ModuleImlFileEntitiesSerializer>().mapTo(LinkedHashSet()) { it.modulePath }.toList()
}
}
override fun saveEntities(storage: WorkspaceEntityStorage, affectedSources: Set<EntitySource>, writer: JpsFileContentWriter) {
val affectedModuleListSerializers = HashSet<JpsModuleListSerializer>()
val serializersToRun = HashMap<JpsFileEntitiesSerializer<*>, MutableMap<Class<out WorkspaceEntity>, MutableSet<WorkspaceEntity>>>()
synchronized(lock) {
if (LOG.isTraceEnabled) {
LOG.trace("save entities; current serializers (${fileSerializersByUrl.values.size}):")
fileSerializersByUrl.values.forEach {
LOG.trace(it.toString())
}
}
val affectedEntityTypeSerializers = HashSet<JpsFileEntityTypeSerializer<*>>()
fun processObsoleteSource(fileUrl: String, deleteModuleFile: Boolean) {
val obsoleteSerializers = fileSerializersByUrl.getValues(fileUrl)
fileSerializersByUrl.removeKey(fileUrl)
LOG.trace { "processing obsolete source $fileUrl: serializers = $obsoleteSerializers" }
obsoleteSerializers.forEach {
// Clean up module files content
val moduleListSerializer = moduleSerializers.remove(it)
if (moduleListSerializer != null) {
if (deleteModuleFile) {
moduleListSerializer.deleteObsoleteFile(fileUrl, writer)
}
LOG.trace { "affected module list: $moduleListSerializer" }
affectedModuleListSerializers.add(moduleListSerializer)
}
// Remove libraries under `.idea/libraries` folder
val directoryFactory = serializerToDirectoryFactory.remove(it)
if (directoryFactory != null) {
writer.saveComponent(fileUrl, directoryFactory.componentName, null)
}
// Remove libraries under `external_build_system/libraries` folder
if (it in entityTypeSerializers) {
if (getFilteredEntitiesForSerializer(it as JpsFileEntityTypeSerializer, storage).isEmpty()) {
it.deleteObsoleteFile(fileUrl, writer)
}
else {
affectedEntityTypeSerializers.add(it)
}
}
}
}
val sourcesStoredInternally = affectedSources.asSequence().filterIsInstance<JpsImportedEntitySource>()
.filter { !it.storedExternally }
.associateBy { it.internalFile }
val internalSourcesOfCustomModuleEntitySources = affectedSources.mapNotNullTo(HashSet()) { (it as? CustomModuleEntitySource)?.internalSource }
/* Entities added via JPS and imported entities stored in internal storage must be passed to serializers together, otherwise incomplete
data will be stored.
It isn't necessary to save entities stored in external storage when their internal parts are affected, but add them to the list
to ensure that obsolete *.iml files will be removed if their modules are stored in external storage.
*/
val entitiesToSave = storage.entitiesBySource { source ->
source in affectedSources
|| source in sourcesStoredInternally
|| source is JpsImportedEntitySource && source.internalFile in affectedSources
|| source in internalSourcesOfCustomModuleEntitySources
|| source is CustomModuleEntitySource && source.internalSource in affectedSources
}
if (LOG.isTraceEnabled) {
LOG.trace("Affected sources: $affectedSources")
LOG.trace("Entities to save:")
for ((source, entities) in entitiesToSave) {
LOG.trace(" $source: $entities")
}
}
val internalSourceConvertedToImported = affectedSources.filterIsInstance<JpsImportedEntitySource>().mapTo(HashSet()) {
it.internalFile
}
val sourcesStoredExternally = entitiesToSave.keys.asSequence().filterIsInstance<JpsImportedEntitySource>()
.filter { it.storedExternally }
.associateBy { it.internalFile }
val obsoleteSources = affectedSources - entitiesToSave.keys
LOG.trace { "Obsolete sources: $obsoleteSources" }
for (source in obsoleteSources) {
val fileUrl = getActualFileUrl(source)
if (fileUrl != null) {
val affectedImportedSourceStoredExternally = when {
source is JpsImportedEntitySource && source.storedExternally -> sourcesStoredInternally[source.internalFile]
source is JpsImportedEntitySource && !source.storedExternally -> sourcesStoredExternally[source.internalFile]
source is JpsFileEntitySource -> sourcesStoredExternally[source]
else -> null
}
// When user removes module from project we don't delete corresponding *.iml file located under project directory by default
// (because it may be included in other projects). However we do remove the module file if module actually wasn't removed, just
// its storage has been changed, e.g. if module was marked as imported from external system, or the place where module imported
// from external system was changed, or part of a module configuration is imported from external system and data stored in *.iml
// file was removed.
val deleteObsoleteFile = source in internalSourceConvertedToImported || (affectedImportedSourceStoredExternally != null &&
affectedImportedSourceStoredExternally !in obsoleteSources)
processObsoleteSource(fileUrl, deleteObsoleteFile)
val actualSource = if (source is JpsImportedEntitySource && !source.storedExternally) source.internalFile else source
if (actualSource is JpsFileEntitySource.FileInDirectory) {
fileIdToFileName.remove(actualSource.fileNameId)
LOG.debug { "remove association for obsolete source $actualSource" }
}
}
}
fun processNewlyAddedDirectoryEntities(entitiesMap: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>) {
directorySerializerFactoriesByUrl.values.forEach { factory ->
val added = entitiesMap[factory.entityClass]
if (added != null) {
val newSerializers = createSerializersForDirectoryEntities(factory, added)
newSerializers.forEach {
serializerToDirectoryFactory[it.key] = factory
fileSerializersByUrl.put(it.key.fileUrl.url, it.key)
}
newSerializers.forEach { (serializer, entitiesMap) -> mergeSerializerEntitiesMap(serializersToRun, serializer, entitiesMap) }
}
}
}
entitiesToSave.forEach { (source, entities) ->
val actualFileSource = getActualFileSource(source)
if (actualFileSource is JpsFileEntitySource.FileInDirectory) {
val fileNameByEntity = calculateFileNameForEntity(actualFileSource, source, entities)
val oldFileName = fileIdToFileName.get(actualFileSource.fileNameId)
if (oldFileName != fileNameByEntity) {
// Don't convert to links[key] = ... because it *may* became autoboxing
@Suppress("ReplacePutWithAssignment")
fileIdToFileName.put(actualFileSource.fileNameId, fileNameByEntity)
LOG.debug { "update association for ${actualFileSource.fileNameId} to $fileNameByEntity (was $oldFileName)" }
if (oldFileName != null) {
processObsoleteSource("${actualFileSource.directory.url}/$oldFileName", true)
}
val existingSerializers = fileSerializersByUrl.getValues("${actualFileSource.directory.url}/$fileNameByEntity").filter {
it in serializerToDirectoryFactory
}
if (existingSerializers.isNotEmpty()) {
val existingSources = existingSerializers.map { it.internalEntitySource }
val entitiesWithOldSource = storage.entitiesBySource { it in existingSources }
val entitiesPersistentIds = entitiesWithOldSource.values
.flatMap { it.values }
.flatten()
.filterIsInstance<WorkspaceEntityWithPersistentId>()
.joinToString(separator = "||") { "$it (PersistentId: ${it.persistentId()})" }
//technically this is not an error, but cases when different entities have the same default file name are rare so let's report this
// as error for now to find real cause of IDEA-265327
val message = """
|Cannot save entities to $fileNameByEntity because it's already used for other entities;
|Current entity source: $actualFileSource
|Old file name: $oldFileName
|Existing serializers: $existingSerializers
|Their entity sources: $existingSources
|Entities with these sources in the storage: ${entitiesWithOldSource.mapValues { (_, value) -> value.values }}
|Entities with persistent ids: $entitiesPersistentIds
|Original entities to save: ${entities.values.flatten().joinToString(separator = "||") { "$it (Persistent Id: ${(it as? WorkspaceEntityWithPersistentId)?.persistentId()})" }}
""".trimMargin()
reportErrorAndAttachStorage(message, storage)
}
if (existingSerializers.isEmpty() || existingSerializers.any { it.internalEntitySource != actualFileSource }) {
processNewlyAddedDirectoryEntities(entities)
}
}
}
val url = getActualFileUrl(source)
val internalSource = getInternalFileSource(source)
if (url != null && internalSource != null
&& (ModuleEntity::class.java in entities || FacetEntity::class.java in entities || ModuleGroupPathEntity::class.java in entities)) {
val existingSerializers = fileSerializersByUrl.getValues(url)
val moduleGroup = (entities[ModuleGroupPathEntity::class.java]?.first() as? ModuleGroupPathEntity)?.path?.joinToString("/")
if (existingSerializers.isEmpty() || existingSerializers.any { it is ModuleImlFileEntitiesSerializer && it.modulePath.group != moduleGroup }) {
moduleListSerializersByUrl.values.forEach { moduleListSerializer ->
if (moduleListSerializer.entitySourceFilter(source)) {
if (existingSerializers.isNotEmpty()) {
existingSerializers.forEach {
if (it is ModuleImlFileEntitiesSerializer) {
moduleSerializers.remove(it)
fileSerializersByUrl.remove(url, it)
}
}
}
val newSerializer = moduleListSerializer.createSerializer(internalSource, virtualFileManager.fromUrl(url), moduleGroup)
fileSerializersByUrl.put(url, newSerializer)
moduleSerializers[newSerializer] = moduleListSerializer
affectedModuleListSerializers.add(moduleListSerializer)
}
}
}
for (serializer in existingSerializers) {
val moduleListSerializer = moduleSerializers[serializer]
val storedExternally = moduleSerializerToExternalSourceBool[serializer]
if (moduleListSerializer != null && storedExternally != null &&
(moduleListSerializer.isExternalStorage == storedExternally && !moduleListSerializer.entitySourceFilter(source)
|| moduleListSerializer.isExternalStorage != storedExternally && moduleListSerializer.entitySourceFilter(source))) {
moduleSerializerToExternalSourceBool[serializer] = !storedExternally
affectedModuleListSerializers.add(moduleListSerializer)
}
}
}
}
entitiesToSave.forEach { (source, entities) ->
val serializers = fileSerializersByUrl.getValues(getActualFileUrl(source))
serializers.filter { it !is JpsFileEntityTypeSerializer }.forEach { serializer ->
mergeSerializerEntitiesMap(serializersToRun, serializer, entities)
}
}
for (serializer in entityTypeSerializers) {
if (entitiesToSave.any { serializer.mainEntityClass in it.value } || serializer in affectedEntityTypeSerializers) {
val entitiesMap = mutableMapOf(serializer.mainEntityClass to getFilteredEntitiesForSerializer(serializer, storage))
serializer.additionalEntityTypes.associateWithTo(entitiesMap) {
storage.entities(it).toList()
}
fileSerializersByUrl.put(serializer.fileUrl.url, serializer)
mergeSerializerEntitiesMap(serializersToRun, serializer, entitiesMap)
}
}
}
if (affectedModuleListSerializers.isNotEmpty()) {
moduleListSerializersByUrl.values.forEach {
saveModulesList(it, storage, writer)
}
}
serializersToRun.forEach {
saveEntitiesBySerializer(it.key, it.value.mapValues { entitiesMapEntry -> entitiesMapEntry.value.toList() }, storage, writer)
}
}
override fun changeEntitySourcesToDirectoryBasedFormat(builder: WorkspaceEntityStorageBuilder) {
for (factory in directorySerializerFactoriesByUrl.values) {
factory.changeEntitySourcesToDirectoryBasedFormat(builder, configLocation)
}
}
private fun mergeSerializerEntitiesMap(existingSerializer2EntitiesMap: HashMap<JpsFileEntitiesSerializer<*>, MutableMap<Class<out WorkspaceEntity>, MutableSet<WorkspaceEntity>>>,
serializer: JpsFileEntitiesSerializer<*>,
entitiesMap: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>) {
val existingEntitiesMap = existingSerializer2EntitiesMap.getOrPut(serializer) { HashMap() }
entitiesMap.forEach { (type, entity) ->
val existingEntities = existingEntitiesMap.getOrPut(type) { HashSet() }
existingEntities.addAll(entity)
}
}
private fun calculateFileNameForEntity(source: JpsFileEntitySource.FileInDirectory,
originalSource: EntitySource,
entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>): String? {
val directoryFactory = directorySerializerFactoriesByUrl[source.directory.url]
if (directoryFactory != null) {
return getDefaultFileNameForEntity(directoryFactory, entities)
}
if (ModuleEntity::class.java in entities || FacetEntity::class.java in entities) {
val moduleListSerializer = moduleListSerializersByUrl.values.find {
it.entitySourceFilter(originalSource)
}
if (moduleListSerializer != null) {
return getFileNameForModuleEntity(moduleListSerializer, entities)
}
}
return null
}
private fun <E : WorkspaceEntity> getDefaultFileNameForEntity(directoryFactory: JpsDirectoryEntitiesSerializerFactory<E>,
entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>): String? {
@Suppress("UNCHECKED_CAST") val entity = entities[directoryFactory.entityClass]?.singleOrNull() as? E ?: return null
return FileUtil.sanitizeFileName(directoryFactory.getDefaultFileName(entity)) + ".xml"
}
private fun getFileNameForModuleEntity(moduleListSerializer: JpsModuleListSerializer,
entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>): String? {
val entity = entities[ModuleEntity::class.java]?.singleOrNull() as? ModuleEntity
if (entity != null) {
return moduleListSerializer.getFileName(entity)
}
val additionalEntity = entities[FacetEntity::class.java]?.firstOrNull() as? FacetEntity ?: return null
return moduleListSerializer.getFileName(additionalEntity.module)
}
private fun <E : WorkspaceEntity> getFilteredEntitiesForSerializer(serializer: JpsFileEntityTypeSerializer<E>,
storage: WorkspaceEntityStorage): List<E> {
return storage.entities(serializer.mainEntityClass).filter(serializer.entityFilter).toList()
}
private fun <E : WorkspaceEntity> saveEntitiesBySerializer(serializer: JpsFileEntitiesSerializer<E>,
entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>,
storage: WorkspaceEntityStorage,
writer: JpsFileContentWriter) {
@Suppress("UNCHECKED_CAST")
serializer.saveEntities(entities[serializer.mainEntityClass] as? Collection<E> ?: emptyList(), entities, storage, writer)
}
private fun <E : WorkspaceEntity> createSerializersForDirectoryEntities(factory: JpsDirectoryEntitiesSerializerFactory<E>,
entities: List<WorkspaceEntity>)
: Map<JpsFileEntitiesSerializer<*>, Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>> {
val serializers = serializerToDirectoryFactory.getKeysByValue(factory) ?: emptyList()
val nameGenerator = UniqueNameGenerator(serializers, Function {
PathUtil.getFileName(it.fileUrl.url)
})
return entities.asSequence()
.filter { @Suppress("UNCHECKED_CAST") factory.entityFilter(it as E) }
.associate { entity ->
@Suppress("UNCHECKED_CAST")
val defaultFileName = FileUtil.sanitizeFileName(factory.getDefaultFileName(entity as E))
val fileName = nameGenerator.generateUniqueName(defaultFileName, "", ".xml")
val entityMap = mapOf<Class<out WorkspaceEntity>, List<WorkspaceEntity>>(factory.entityClass to listOf(entity))
val currentSource = entity.entitySource as? JpsFileEntitySource.FileInDirectory
val source =
if (currentSource != null && fileIdToFileName.get(currentSource.fileNameId) == fileName) currentSource
else createFileInDirectorySource(virtualFileManager.fromUrl(factory.directoryUrl), fileName)
factory.createSerializer("${factory.directoryUrl}/$fileName", source, virtualFileManager) to entityMap
}
}
private fun saveModulesList(it: JpsModuleListSerializer, storage: WorkspaceEntityStorage, writer: JpsFileContentWriter) {
LOG.trace("saving modules list")
it.saveEntitiesList(storage.entities(ModuleEntity::class.java), writer)
}
companion object {
private val LOG = logger<JpsProjectSerializersImpl>()
}
}
class CachingJpsFileContentReader(private val configLocation: JpsProjectConfigLocation) : JpsFileContentReader {
private val projectPathMacroManager = ProjectPathMacroManager.createInstance(
configLocation::projectFilePath,
{ JpsPathUtil.urlToPath(configLocation.baseDirectoryUrlString) },
null
)
private val fileContentCache = ConcurrentHashMap<String, Map<String, Element>>()
override fun loadComponent(fileUrl: String, componentName: String, customModuleFilePath: String?): Element? {
val content = fileContentCache.computeIfAbsent(fileUrl + customModuleFilePath) {
loadComponents(fileUrl, customModuleFilePath)
}
return content[componentName]
}
override fun getExpandMacroMap(fileUrl: String): ExpandMacroToPathMap {
return getMacroManager(fileUrl, null).expandMacroMap
}
private fun loadComponents(fileUrl: String, customModuleFilePath: String?): Map<String, Element> {
val macroManager = getMacroManager(fileUrl, customModuleFilePath)
val file = Paths.get(JpsPathUtil.urlToPath(fileUrl))
return if (Files.isRegularFile(file)) loadStorageFile(file, macroManager) else emptyMap()
}
private fun getMacroManager(fileUrl: String,
customModuleFilePath: String?): PathMacroManager {
val path = JpsPathUtil.urlToPath(fileUrl)
return if (FileUtil.extensionEquals(fileUrl, "iml") || isExternalModuleFile(path)) {
ModulePathMacroManager.createInstance(configLocation::projectFilePath, Supplier { customModuleFilePath ?: path })
}
else {
projectPathMacroManager
}
}
}
internal fun Element.getAttributeValueStrict(name: String): String =
getAttributeValue(name) ?: throw JDOMException("Expected attribute $name under ${this.name} element")
fun isExternalModuleFile(filePath: String): Boolean {
val parentPath = PathUtil.getParentPath(filePath)
return FileUtil.extensionEquals(filePath, "xml") && PathUtil.getFileName(parentPath) == "modules"
&& PathUtil.getFileName(PathUtil.getParentPath(parentPath)) != ".idea"
}
internal fun getInternalFileSource(source: EntitySource) = when (source) {
is JpsFileDependentEntitySource -> source.originalSource
is CustomModuleEntitySource -> source.internalSource
is JpsFileEntitySource -> source
else -> null
}
| apache-2.0 |
dahlstrom-g/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/exceptions/PersistentIdAlreadyExistsException.kt | 10 | 405 | // 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.workspaceModel.storage.impl.exceptions
import com.intellij.workspaceModel.storage.PersistentEntityId
class PersistentIdAlreadyExistsException(val id: PersistentEntityId<*>) : RuntimeException(("Entity with persistentId: $id already exist"))
| apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/quickfix/RemoveRedundantSpreadOperatorFix.kt | 3 | 1568 | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
class RemoveRedundantSpreadOperatorFix(argument: KtExpression) : KotlinPsiOnlyQuickFixAction<KtExpression>(argument) {
override fun getText(): String = KotlinBundle.message("fix.remove.redundant.star.text")
override fun getFamilyName(): String = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val argument = element?.getParentOfType<KtValueArgument>(false) ?: return
val spreadElement = argument.getSpreadElement() ?: return
spreadElement.delete()
}
companion object : QuickFixesPsiBasedFactory<PsiElement>(PsiElement::class, PsiElementSuitabilityCheckers.ALWAYS_SUITABLE) {
override fun doCreateQuickFix(psiElement: PsiElement): List<IntentionAction> {
val element = psiElement as? KtExpression ?: return emptyList()
return listOf(RemoveRedundantSpreadOperatorFix(element))
}
}
} | apache-2.0 |
stefanocasazza/FrameworkBenchmarks | frameworks/Kotlin/hexagon/src/test/kotlin/com/hexagonkt/BenchmarkTest.kt | 2 | 6163 | package com.hexagonkt
import com.hexagonkt.serialization.parse
import com.hexagonkt.http.client.Client
import com.hexagonkt.serialization.Json
import com.hexagonkt.serialization.parseObjects
import com.hexagonkt.http.Method.GET
import com.hexagonkt.http.server.jetty.JettyServletAdapter
import org.asynchttpclient.Response
import org.testng.annotations.AfterClass
import org.testng.annotations.BeforeClass
import org.testng.annotations.Test
import java.lang.IllegalStateException
import java.lang.System.setProperty
@Test class BenchmarkJettyMongoDbTest : BenchmarkTestBase("jetty", "mongodb")
@Test class BenchmarkJettyPostgreSqlTest : BenchmarkTestBase("jetty", "postgresql")
@Test abstract class BenchmarkTestBase(
private val webEngine: String,
private val databaseEngine: String,
private val templateEngine: String = "pebble"
) {
private val client by lazy { Client("http://localhost:${benchmarkServer.runtimePort}") }
@BeforeClass fun startUp() {
setProperty("WEBENGINE", webEngine)
main()
}
@AfterClass fun shutDown() {
benchmarkStores[databaseEngine]?.close()
benchmarkServer.stop()
}
@Test fun `Empty server code creates a Jetty Servlet Adapter`() {
System.clearProperty("WEBENGINE")
createEngine()
assert(engine is JettyServletAdapter)
}
@Test(expectedExceptions = [ IllegalStateException::class ])
fun `Invalid server code throws an exception`() {
setProperty("WEBENGINE", "invalid")
createEngine()
}
@Test fun web() {
val web = Web()
val webRoutes = web.serverRouter.requestHandlers
.map { it.route.methods.first() to it.route.path.path }
val benchmarkRoutes = listOf(
GET to "/plaintext",
GET to "/json",
GET to "/$databaseEngine/$templateEngine/fortunes",
GET to "/$databaseEngine/db",
GET to "/$databaseEngine/query",
GET to "/$databaseEngine/update"
)
assert(webRoutes.containsAll(benchmarkRoutes))
}
@Test fun json() {
val response = client.get("/json")
val content = response.responseBody
checkResponse(response, Json.contentType)
assert("Hello, World!" == content.parse<Message>().message)
}
@Test fun plaintext() {
val response = client.get("/plaintext")
val content = response.responseBody
checkResponse(response, "text/plain")
assert("Hello, World!" == content)
}
@Test fun fortunes() {
val response = client.get("/$databaseEngine/$templateEngine/fortunes")
val content = response.responseBody
checkResponse(response, "text/html;charset=utf-8")
assert(content.contains("<td><script>alert("This should not be"))
assert(content.contains(" displayed in a browser alert box.");</script></td>"))
assert(content.contains("<td>フレームワークのベンチマーク</td>"))
}
@Test fun `no query parameter`() {
val response = client.get("/$databaseEngine/db")
val body = response.responseBody
checkResponse(response, Json.contentType)
val bodyMap = body.parse(Map::class)
assert(bodyMap.containsKey(World::id.name))
assert(bodyMap.containsKey(World::randomNumber.name))
}
@Test fun `no updates parameter`() {
val response = client.get("/$databaseEngine/update")
val body = response.responseBody
checkResponse(response, Json.contentType)
val bodyMap = body.parseObjects(Map::class).first()
assert(bodyMap.containsKey(World::id.name))
assert(bodyMap.containsKey(World::randomNumber.name))
}
@Test fun `empty query parameter`() = checkDbRequest("/$databaseEngine/query?queries", 1)
@Test fun `text query parameter`() = checkDbRequest("/$databaseEngine/query?queries=text", 1)
@Test fun `zero queries`() = checkDbRequest("/$databaseEngine/query?queries=0", 1)
@Test fun `one thousand queries`() = checkDbRequest("/$databaseEngine/query?queries=1000", 500)
@Test fun `one query`() = checkDbRequest("/$databaseEngine/query?queries=1", 1)
@Test fun `ten queries`() = checkDbRequest("/$databaseEngine/query?queries=10", 10)
@Test fun `one hundred queries`() = checkDbRequest("/$databaseEngine/query?queries=100", 100)
@Test fun `five hundred queries`() = checkDbRequest("/$databaseEngine/query?queries=500", 500)
@Test fun `empty updates parameter`() = checkDbRequest("/$databaseEngine/update?queries", 1)
@Test fun `text updates parameter`() = checkDbRequest("/$databaseEngine/update?queries=text", 1)
@Test fun `zero updates`() = checkDbRequest("/$databaseEngine/update?queries=0", 1)
@Test fun `one thousand updates`() = checkDbRequest("/$databaseEngine/update?queries=1000", 500)
@Test fun `one update`() = checkDbRequest("/$databaseEngine/update?queries=1", 1)
@Test fun `ten updates`() = checkDbRequest("/$databaseEngine/update?queries=10", 10)
@Test fun `one hundred updates`() = checkDbRequest("/$databaseEngine/update?queries=100", 100)
@Test fun `five hundred updates`() = checkDbRequest("/$databaseEngine/update?queries=500", 500)
private fun checkDbRequest(path: String, itemsCount: Int) {
val response = client.get(path)
val content = response.responseBody
checkResponse(response, Json.contentType)
val resultsList = content.parse(List::class)
assert(itemsCount == resultsList.size)
(1..itemsCount).forEach {
val r = resultsList[it - 1] as Map<*, *>
assert(r.containsKey(World::id.name) && r.containsKey(World::randomNumber.name))
assert(!r.containsKey(World::_id.name))
assert((r[World::id.name] as Int) in 1..10000)
}
}
private fun checkResponse(res: Response, contentType: String) {
assert(res.headers ["Date"] != null)
assert(res.headers ["Server"] != null)
assert(res.headers ["Transfer-Encoding"] != null)
assert(res.headers ["Content-Type"] == contentType)
}
}
| bsd-3-clause |
androidx/androidx | compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/font/FontStyle.kt | 3 | 1408 | /*
* Copyright 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.compose.ui.text.font
/**
* Defines whether the font is [Italic] or [Normal].
*
* @see Font
* @see FontFamily
*/
// TODO(b/205312869) This constructor should not be public as it leads to FontStyle([cursor]) in AS
@kotlin.jvm.JvmInline
value class FontStyle(val value: Int) {
override fun toString(): String {
return when (this) {
Normal -> "Normal"
Italic -> "Italic"
else -> "Invalid"
}
}
companion object {
/** Use the upright glyphs */
val Normal = FontStyle(0)
/** Use glyphs designed for slanting */
val Italic = FontStyle(1)
/** Returns a list of possible values of [FontStyle]. */
fun values(): List<FontStyle> = listOf(Normal, Italic)
}
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/code-insight/inspections-k2/tests/testData/inspectionsLocal/replaceSizeZeroCheckWithIsEmpty/extensionReceiver.kt | 2 | 76 | // WITH_STDLIB
fun String.test(): Boolean {
return 0 == <caret>length
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/PerFileAnalysisCache.kt | 2 | 25924 | // 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.caches.resolve
import com.google.common.collect.ImmutableMap
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicatorProvider
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ModificationTracker
import com.intellij.psi.PsiElement
import com.intellij.psi.util.findParentInFile
import com.intellij.psi.util.findTopmostParentInFile
import com.intellij.psi.util.findTopmostParentOfType
import org.jetbrains.kotlin.analyzer.AnalysisResult
import org.jetbrains.kotlin.cfg.ControlFlowInformationProviderImpl
import org.jetbrains.kotlin.container.ComponentProvider
import org.jetbrains.kotlin.container.get
import org.jetbrains.kotlin.context.GlobalContext
import org.jetbrains.kotlin.context.withModule
import org.jetbrains.kotlin.context.withProject
import org.jetbrains.kotlin.descriptors.InvalidModuleException
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactoryWithPsiElement
import org.jetbrains.kotlin.diagnostics.DiagnosticSink
import org.jetbrains.kotlin.diagnostics.DiagnosticUtils
import org.jetbrains.kotlin.diagnostics.PositioningStrategies.DECLARATION_WITH_BODY
import org.jetbrains.kotlin.frontend.di.createContainerForLazyBodyResolve
import org.jetbrains.kotlin.idea.base.projectStructure.compositeAnalysis.findAnalyzerServices
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo
import org.jetbrains.kotlin.idea.caches.trackers.clearInBlockModifications
import org.jetbrains.kotlin.idea.caches.trackers.inBlockModifications
import org.jetbrains.kotlin.idea.compiler.IdeMainFunctionDetectorFactory
import org.jetbrains.kotlin.idea.compiler.IdeSealedClassInheritorsProvider
import org.jetbrains.kotlin.idea.project.IdeaModuleStructureOracle
import org.jetbrains.kotlin.idea.util.application.withPsiAttachment
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.*
import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics
import org.jetbrains.kotlin.resolve.diagnostics.DiagnosticsElementsCache
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.lazy.ResolveSession
import org.jetbrains.kotlin.storage.CancellableSimpleLock
import org.jetbrains.kotlin.storage.guarded
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.util.slicedMap.ReadOnlySlice
import org.jetbrains.kotlin.util.slicedMap.WritableSlice
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.kotlin.utils.checkWithAttachment
import java.util.concurrent.locks.ReentrantLock
internal class PerFileAnalysisCache(val file: KtFile, componentProvider: ComponentProvider) {
private val globalContext = componentProvider.get<GlobalContext>()
private val moduleDescriptor = componentProvider.get<ModuleDescriptor>()
private val resolveSession = componentProvider.get<ResolveSession>()
private val codeFragmentAnalyzer = componentProvider.get<CodeFragmentAnalyzer>()
private val bodyResolveCache = componentProvider.get<BodyResolveCache>()
private val cache = HashMap<PsiElement, AnalysisResult>()
private var fileResult: AnalysisResult? = null
private val lock = ReentrantLock()
private val guardLock = CancellableSimpleLock(lock,
checkCancelled = {
ProgressIndicatorProvider.checkCanceled()
},
interruptedExceptionHandler = { throw ProcessCanceledException(it) })
private fun check(element: KtElement) {
checkWithAttachment(element.containingFile == file, {
"Expected $file, but was ${element.containingFile} for ${if (element.isValid) "valid" else "invalid"} $element "
}) {
it.withPsiAttachment("element.kt", element)
it.withPsiAttachment("file.kt", element.containingFile)
it.withPsiAttachment("original.kt", file)
}
}
internal val isValid: Boolean get() = moduleDescriptor.isValid
internal fun fetchAnalysisResults(element: KtElement): AnalysisResult? {
check(element)
if (lock.tryLock()) {
try {
updateFileResultFromCache()
return fileResult?.takeIf { file.inBlockModifications.isEmpty() }
} finally {
lock.unlock()
}
}
return null
}
internal fun getAnalysisResults(element: KtElement, callback: DiagnosticSink.DiagnosticsCallback? = null): AnalysisResult {
check(element)
val analyzableParent = KotlinResolveDataProvider.findAnalyzableParent(element) ?: return AnalysisResult.EMPTY
fun handleResult(result: AnalysisResult, callback: DiagnosticSink.DiagnosticsCallback?): AnalysisResult {
callback?.let { result.bindingContext.diagnostics.forEach(it::callback) }
return result
}
return guardLock.guarded {
// step 1: perform incremental analysis IF it is applicable
getIncrementalAnalysisResult(callback)?.let {
return@guarded handleResult(it, callback)
}
// cache does not contain AnalysisResult per each kt/psi element
// instead it looks up analysis for its parents - see lookUp(analyzableElement)
// step 2: return result if it is cached
lookUp(analyzableParent)?.let {
return@guarded handleResult(it, callback)
}
val localDiagnostics = mutableSetOf<Diagnostic>()
val localCallback = if (callback != null) { d: Diagnostic ->
localDiagnostics.add(d)
callback.callback(d)
} else null
// step 3: perform analyze of analyzableParent as nothing has been cached yet
val result = try {
analyze(analyzableParent, null, localCallback)
} catch (e: Throwable) {
e.throwAsInvalidModuleException {
ProcessCanceledException(it)
}
throw e
}
// some diagnostics could be not handled with a callback - send out the rest
callback?.let { c ->
result.bindingContext.diagnostics.filterNot { it in localDiagnostics }.forEach(c::callback)
}
cache[analyzableParent] = result
return@guarded result
}
}
private fun getIncrementalAnalysisResult(callback: DiagnosticSink.DiagnosticsCallback?): AnalysisResult? {
updateFileResultFromCache()
val inBlockModifications = file.inBlockModifications
if (inBlockModifications.isNotEmpty()) {
try {
// IF there is a cached result for ktFile and there are inBlockModifications
fileResult = fileResult?.let { result ->
var analysisResult = result
// Force full analysis when existed is erroneous
if (analysisResult.isError()) return@let null
for (inBlockModification in inBlockModifications) {
val resultCtx = analysisResult.bindingContext
val stackedCtx =
if (resultCtx is StackedCompositeBindingContextTrace.StackedCompositeBindingContext) resultCtx else null
// no incremental analysis IF it is not applicable
if (stackedCtx?.isIncrementalAnalysisApplicable() == false) return@let null
val trace: StackedCompositeBindingContextTrace =
if (stackedCtx != null && stackedCtx.element() == inBlockModification) {
val trace = stackedCtx.bindingTrace()
trace.clear()
trace
} else {
// to reflect a depth of stacked binding context
val depth = (stackedCtx?.depth() ?: 0) + 1
StackedCompositeBindingContextTrace(
depth,
element = inBlockModification,
resolveContext = resolveSession.bindingContext,
parentContext = resultCtx
)
}
callback?.let { trace.parentDiagnosticsApartElement.forEach(it::callback) }
val newResult = analyze(inBlockModification, trace, callback)
analysisResult = wrapResult(result, newResult, trace)
}
file.clearInBlockModifications()
analysisResult
}
} catch (e: Throwable) {
e.throwAsInvalidModuleException {
clearFileResultCache()
ProcessCanceledException(it)
}
if (e !is ControlFlowException) {
clearFileResultCache()
}
throw e
}
}
if (fileResult == null) {
file.clearInBlockModifications()
}
return fileResult
}
private fun updateFileResultFromCache() {
// move fileResult from cache if it is stored there
if (fileResult == null && cache.containsKey(file)) {
fileResult = cache[file]
// drop existed results for entire cache:
// if incremental analysis is applicable it will produce a single value for file
// otherwise those results are potentially stale
cache.clear()
}
}
private fun lookUp(analyzableElement: KtElement): AnalysisResult? {
// Looking for parent elements that are already analyzed
// Also removing all elements whose parents are already analyzed, to guarantee consistency
val descendantsOfCurrent = arrayListOf<PsiElement>()
val toRemove = hashSetOf<PsiElement>()
var result: AnalysisResult? = null
for (current in analyzableElement.parentsWithSelf) {
val cached = cache[current]
if (cached != null) {
result = cached
toRemove.addAll(descendantsOfCurrent)
descendantsOfCurrent.clear()
}
descendantsOfCurrent.add(current)
}
cache.keys.removeAll(toRemove)
return result
}
private fun wrapResult(
oldResult: AnalysisResult,
newResult: AnalysisResult,
elementBindingTrace: StackedCompositeBindingContextTrace
): AnalysisResult {
val newBindingCtx = elementBindingTrace.stackedContext
return when {
oldResult.isError() -> {
oldResult.error.throwAsInvalidModuleException()
AnalysisResult.internalError(newBindingCtx, oldResult.error)
}
newResult.isError() -> {
newResult.error.throwAsInvalidModuleException()
AnalysisResult.internalError(newBindingCtx, newResult.error)
}
else -> {
AnalysisResult.success(
newBindingCtx,
oldResult.moduleDescriptor,
oldResult.shouldGenerateCode
)
}
}
}
private fun analyze(
analyzableElement: KtElement,
bindingTrace: BindingTrace?,
callback: DiagnosticSink.DiagnosticsCallback?
): AnalysisResult {
ProgressIndicatorProvider.checkCanceled()
val project = analyzableElement.project
if (DumbService.isDumb(project)) {
return AnalysisResult.EMPTY
}
moduleDescriptor.assertValid()
try {
return KotlinResolveDataProvider.analyze(
project,
globalContext,
moduleDescriptor,
resolveSession,
codeFragmentAnalyzer,
bodyResolveCache,
analyzableElement,
bindingTrace,
callback
)
} catch (e: ProcessCanceledException) {
throw e
} catch (e: IndexNotReadyException) {
throw e
} catch (e: Throwable) {
e.throwAsInvalidModuleException()
DiagnosticUtils.throwIfRunningOnServer(e)
LOG.warn(e)
return AnalysisResult.internalError(BindingContext.EMPTY, e)
}
}
private fun clearFileResultCache() {
file.clearInBlockModifications()
fileResult = null
}
}
private fun Throwable.asInvalidModuleException(): InvalidModuleException? {
return when (this) {
is InvalidModuleException -> this
is AssertionError ->
// temporary workaround till 1.6.0 / KT-48977
if (message?.contains("contained in his own dependencies, this is probably a misconfiguration") == true)
InvalidModuleException(message!!)
else null
else -> cause?.takeIf { it != this }?.asInvalidModuleException()
}
}
private inline fun Throwable.throwAsInvalidModuleException(crossinline action: (InvalidModuleException) -> Throwable = { it }) {
asInvalidModuleException()?.let {
throw action(it)
}
}
private class MergedDiagnostics(
val diagnostics: Collection<Diagnostic>,
val noSuppressionDiagnostics: Collection<Diagnostic>,
override val modificationTracker: ModificationTracker
) : Diagnostics {
private val elementsCache = DiagnosticsElementsCache(this) { true }
override fun all() = diagnostics
override fun forElement(psiElement: PsiElement): MutableCollection<Diagnostic> = elementsCache.getDiagnostics(psiElement)
override fun noSuppression() = if (noSuppressionDiagnostics.isEmpty()) {
this
} else {
MergedDiagnostics(noSuppressionDiagnostics, emptyList(), modificationTracker)
}
}
/**
* Keep in mind: trace fallbacks to [resolveContext] (is used during resolve) that does not have any
* traces of earlier resolve for this [element]
*
* When trace turned into [BindingContext] it fallbacks to [parentContext]:
* It is expected that all slices specific to [element] (and its descendants) are stored in this binding context
* and for the rest elements it falls back to [parentContext].
*/
private class StackedCompositeBindingContextTrace(
val depth: Int, // depth of stack over original ktFile bindingContext
val element: KtElement,
val resolveContext: BindingContext,
val parentContext: BindingContext
) : DelegatingBindingTrace(
resolveContext,
"Stacked trace for resolution of $element",
allowSliceRewrite = true
) {
/**
* Effectively StackedCompositeBindingContext holds up-to-date and partially outdated contexts (parentContext)
*
* The most up-to-date results for element are stored here (in a DelegatingBindingTrace#map)
*
* Note: It does not delete outdated results rather hide it therefore there is some extra memory footprint.
*
* Note: stackedContext differs from DelegatingBindingTrace#bindingContext:
* if result is not present in this context it goes to parentContext rather to resolveContext
* diagnostics are aggregated from this context and parentContext
*/
val stackedContext = StackedCompositeBindingContext()
/**
* All diagnostics from parentContext apart this diagnostics this belongs to the element or its descendants
*/
val parentDiagnosticsApartElement: Collection<Diagnostic> =
(resolveContext.diagnostics.all() + parentContext.diagnostics.all()).filterApartElement()
val parentDiagnosticsNoSuppressionApartElement: Collection<Diagnostic> =
(resolveContext.diagnostics.noSuppression() + parentContext.diagnostics.noSuppression()).filterApartElement()
private fun Collection<Diagnostic>.filterApartElement() =
toSet().let { s ->
s.filter { it.psiElement == element && selfDiagnosticToHold(it) } +
s.filter { it.psiElement.parentsWithSelf.none { e -> e == element } }
}
inner class StackedCompositeBindingContext : BindingContext {
var cachedDiagnostics: Diagnostics? = null
fun bindingTrace(): StackedCompositeBindingContextTrace = this@StackedCompositeBindingContextTrace
fun element(): KtElement = [email protected]
fun depth(): Int = [email protected]
// to prevent too deep stacked binding context
fun isIncrementalAnalysisApplicable(): Boolean = [email protected] < 16
override fun getDiagnostics(): Diagnostics {
if (cachedDiagnostics == null) {
val mergedDiagnostics = mutableSetOf<Diagnostic>()
mergedDiagnostics.addAll(parentDiagnosticsApartElement)
[email protected]?.all()?.let {
mergedDiagnostics.addAll(it)
}
val mergedNoSuppressionDiagnostics = mutableSetOf<Diagnostic>()
mergedNoSuppressionDiagnostics += parentDiagnosticsNoSuppressionApartElement
[email protected]?.noSuppression()?.let {
mergedNoSuppressionDiagnostics.addAll(it)
}
cachedDiagnostics = MergedDiagnostics(mergedDiagnostics, mergedNoSuppressionDiagnostics, parentContext.diagnostics.modificationTracker)
}
return cachedDiagnostics!!
}
override fun <K : Any?, V : Any?> get(slice: ReadOnlySlice<K, V>, key: K): V? {
return selfGet(slice, key) ?: parentContext.get(slice, key)
}
override fun getType(expression: KtExpression): KotlinType? {
val typeInfo = get(BindingContext.EXPRESSION_TYPE_INFO, expression)
return typeInfo?.type
}
override fun <K, V> getKeys(slice: WritableSlice<K, V>): Collection<K> {
val keys = map.getKeys(slice)
val fromParent = parentContext.getKeys(slice)
if (keys.isEmpty()) return fromParent
if (fromParent.isEmpty()) return keys
return keys + fromParent
}
override fun <K : Any?, V : Any?> getSliceContents(slice: ReadOnlySlice<K, V>): ImmutableMap<K, V> {
return ImmutableMap.copyOf(parentContext.getSliceContents(slice) + map.getSliceContents(slice))
}
override fun addOwnDataTo(trace: BindingTrace, commitDiagnostics: Boolean) = throw UnsupportedOperationException()
}
override fun <K : Any?, V : Any?> get(slice: ReadOnlySlice<K, V>, key: K): V? =
if (slice == BindingContext.ANNOTATION) {
selfGet(slice, key) ?: parentContext.get(slice, key)
} else {
super.get(slice, key)
}
override fun clear() {
super.clear()
stackedContext.cachedDiagnostics = null
}
companion object {
private fun selfDiagnosticToHold(d: Diagnostic): Boolean {
@Suppress("MoveVariableDeclarationIntoWhen")
val positioningStrategy = d.factory.safeAs<DiagnosticFactoryWithPsiElement<*, *>>()?.positioningStrategy
return when (positioningStrategy) {
DECLARATION_WITH_BODY -> false
else -> true
}
}
}
}
private object KotlinResolveDataProvider {
fun findAnalyzableParent(element: KtElement): KtElement? {
if (element is KtFile) return element
val topmostElement = element.findTopmostParentInFile {
it is KtNamedFunction ||
it is KtAnonymousInitializer ||
it is KtProperty ||
it is KtImportDirective ||
it is KtPackageDirective ||
it is KtCodeFragment ||
// TODO: Non-analyzable so far, add more granular analysis
it is KtAnnotationEntry ||
it is KtTypeConstraint ||
it is KtSuperTypeList ||
it is KtTypeParameter ||
it is KtParameter ||
it is KtTypeAlias
} as KtElement?
// parameters and supertype lists are not analyzable by themselves, but if we don't count them as topmost, we'll stop inside, say,
// object expressions inside arguments of super constructors of classes (note that classes themselves are not topmost elements)
val analyzableElement = when (topmostElement) {
is KtAnnotationEntry,
is KtTypeConstraint,
is KtSuperTypeList,
is KtTypeParameter,
is KtParameter -> topmostElement.findParentInFile { it is KtClassOrObject || it is KtCallableDeclaration } as? KtElement?
else -> topmostElement
}
// Primary constructor should never be returned
if (analyzableElement is KtPrimaryConstructor) return analyzableElement.getContainingClassOrObject()
// Class initializer should be replaced by containing class to provide full analysis
if (analyzableElement is KtClassInitializer) return analyzableElement.containingDeclaration
return analyzableElement
// if none of the above worked, take the outermost declaration
?: element.findTopmostParentOfType<KtDeclaration>()
// if even that didn't work, take the whole file
?: element.containingFile as? KtFile
}
fun analyze(
project: Project,
globalContext: GlobalContext,
moduleDescriptor: ModuleDescriptor,
resolveSession: ResolveSession,
codeFragmentAnalyzer: CodeFragmentAnalyzer,
bodyResolveCache: BodyResolveCache,
analyzableElement: KtElement,
bindingTrace: BindingTrace?,
callback: DiagnosticSink.DiagnosticsCallback?
): AnalysisResult {
try {
if (analyzableElement is KtCodeFragment) {
val bodyResolveMode = BodyResolveMode.PARTIAL_FOR_COMPLETION
val trace: BindingTrace = codeFragmentAnalyzer.analyzeCodeFragment(analyzableElement, bodyResolveMode)
val bindingContext = trace.bindingContext
return AnalysisResult.success(bindingContext, moduleDescriptor)
}
val trace = bindingTrace ?: BindingTraceForBodyResolve(
resolveSession.bindingContext,
"Trace for resolution of $analyzableElement"
)
val moduleInfo = analyzableElement.containingKtFile.moduleInfo
val targetPlatform = moduleInfo.platform
var callbackSet = false
try {
callbackSet = callback?.let(trace::setCallbackIfNotSet) ?: false
/*
Note that currently we *have* to re-create LazyTopDownAnalyzer with custom trace in order to disallow resolution of
bodies in top-level trace (trace from DI-container).
Resolving bodies in top-level trace may lead to memory leaks and incorrect resolution, because top-level
trace isn't invalidated on in-block modifications (while body resolution surely does)
Also note that for function bodies, we'll create DelegatingBindingTrace in ResolveElementCache anyways
(see 'functionAdditionalResolve'). However, this trace is still needed, because we have other
codepaths for other KtDeclarationWithBodies (like property accessors/secondary constructors/class initializers)
*/
val lazyTopDownAnalyzer = createContainerForLazyBodyResolve(
//TODO: should get ModuleContext
globalContext.withProject(project).withModule(moduleDescriptor),
resolveSession,
trace,
targetPlatform,
bodyResolveCache,
targetPlatform.findAnalyzerServices(project),
analyzableElement.languageVersionSettings,
IdeaModuleStructureOracle(),
IdeMainFunctionDetectorFactory(),
IdeSealedClassInheritorsProvider,
ControlFlowInformationProviderImpl.Factory,
).get<LazyTopDownAnalyzer>()
lazyTopDownAnalyzer.analyzeDeclarations(TopDownAnalysisMode.TopLevelDeclarations, listOf(analyzableElement))
} finally {
if (callbackSet) {
trace.resetCallback()
}
}
return AnalysisResult.success(trace.bindingContext, moduleDescriptor)
} catch (e: ProcessCanceledException) {
throw e
} catch (e: IndexNotReadyException) {
throw e
} catch (e: Throwable) {
e.throwAsInvalidModuleException()
DiagnosticUtils.throwIfRunningOnServer(e)
LOG.warn(e)
return AnalysisResult.internalError(BindingContext.EMPTY, e)
}
}
}
| apache-2.0 |
GunoH/intellij-community | platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/WithNullsEntityTest.kt | 7 | 1091 | // 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.workspaceModel.storage
import com.intellij.workspaceModel.storage.entities.test.api.*
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class WithNullsEntityTest {
@Test
fun `add parent and then child nullable`() {
val parent = ParentWithNulls("Parent", MySource) {
}
val builder = MutableEntityStorage.create()
builder.addEntity(parent)
val child = ChildWithNulls("data", MySource) {
this.parentEntity = parent
}
assertEquals("Parent", child.parentEntity!!.child!!.parentEntity!!.parentData)
}
@Test
fun `add parent and then child nullable 1`() {
val child = ChildWithNulls("data", MySource) {
}
val builder = MutableEntityStorage.create()
builder.addEntity(child)
builder.modifyEntity(child) {
this.parentEntity = ParentWithNulls("Parent", MySource) {
}
}
assertEquals("Parent", child.parentEntity!!.child!!.parentEntity!!.parentData)
}
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/intentions/convertLambdaToReference/defaultArgument5.kt | 9 | 173 | // AFTER-WARNING: Parameter 'f' is never used
fun Int.foo(x: Int, y: Int = 42) = x + y
fun bar(f: (Int, Int) -> Int) {}
fun test() {
bar <caret>{ i, x -> i.foo(x) }
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/java/StreamExCallChecker.kt | 4 | 1668 | // 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.debugger.sequence.psi.java
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.idea.debugger.sequence.psi.CallCheckerWithNameHeuristics
import org.jetbrains.kotlin.idea.debugger.sequence.psi.StreamCallChecker
class StreamExCallChecker(nestedChecker: StreamCallChecker) : CallCheckerWithNameHeuristics(nestedChecker) {
private companion object {
@NonNls
val TERMINATION_CALLS: Set<String> = setOf(
"forEach", "toArray", "reduce", "collect", "min", "max", "count", "sum", "anyMatch", "allMatch", "noneMatch", "findFirst",
"findAny", "forEachOrdered", "average", "summaryStatistics", "toList", "toSet", "toCollection", "toListAndThen", "toSetAndThen",
"toImmutableList", "toImmutableSet", "toMap", "toSortedMap", "toNavigableMap", "toImmutableMap", "toMapAndThen", "toCustomMap",
"partitioningBy", "partitioningTo", "groupingBy", "groupingTo", "grouping", "joining", "toFlatList", "toFlatCollection",
"maxBy", "maxByInt", "maxByLong", "maxByDouble", "minBy", "minByInt", "minByLong", "minByDouble", "has", "indexOf", "foldLeft",
"foldRight", "scanLeft", "scanRight", "toByteArray", "toCharArray", "toShortArray", "toBitSet", "toFloatArray", "charsToString",
"codePointsToString", "forPairs", "forKeyValue", "asByteInputStream", "into"
)
}
override fun isTerminalCallName(callName: String): Boolean = TERMINATION_CALLS.contains(callName)
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/j2k/new/tests/testData/newJ2k/assignmentExpression/ktij-16986.kt | 8 | 149 | object Test {
@JvmStatic
fun main(args: Array<String>) {
val a = longArrayOf(0)
val b = 0
a[0] += b.toLong()
}
}
| apache-2.0 |
shogo4405/HaishinKit.java | app/src/main/java/com/haishinkit/studio/Preference.kt | 1 | 286 | package com.haishinkit.studio
data class Preference(var rtmpURL: String, var streamName: String) {
companion object {
var shared = Preference(
"rtmp://test:[email protected]/live",
"live"
)
var useSurfaceView: Boolean = true
}
}
| bsd-3-clause |
siosio/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ui/completion/AbstractTextCompletionContributor.kt | 2 | 731 | // 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.openapi.externalSystem.service.ui.completion
import java.util.concurrent.CopyOnWriteArrayList
import javax.swing.JComponent
abstract class AbstractTextCompletionContributor<C : JComponent> : TextCompletionContributor<C> {
private val chooseListeners = CopyOnWriteArrayList<(C, TextCompletionInfo) -> Unit>()
final override fun fireVariantChosen(owner: C, variant: TextCompletionInfo) {
chooseListeners.forEach { it(owner, variant) }
}
final override fun whenVariantChosen(action: (C, TextCompletionInfo) -> Unit) {
chooseListeners.add(action)
}
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/impl/PackageBasedCallChecker.kt | 1 | 1733 | // 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.debugger.sequence.psi.impl
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.kotlin.idea.debugger.sequence.psi.KotlinPsiUtil
import org.jetbrains.kotlin.idea.debugger.sequence.psi.StreamCallChecker
import org.jetbrains.kotlin.idea.core.receiverType
import org.jetbrains.kotlin.idea.core.resolveType
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.types.KotlinType
class PackageBasedCallChecker(private val supportedPackage: String) : StreamCallChecker {
override fun isIntermediateCall(expression: KtCallExpression): Boolean {
return checkReceiverSupported(expression) && checkResultSupported(expression, true)
}
override fun isTerminationCall(expression: KtCallExpression): Boolean {
return checkReceiverSupported(expression) && checkResultSupported(expression, false)
}
private fun checkResultSupported(
expression: KtCallExpression,
shouldSupportResult: Boolean
): Boolean {
val resultType = expression.resolveType()
return shouldSupportResult == isSupportedType(resultType)
}
private fun checkReceiverSupported(expression: KtCallExpression): Boolean {
val receiverType = expression.receiverType()
return receiverType != null && isSupportedType(receiverType)
}
private fun isSupportedType(type: KotlinType): Boolean {
val typeName = KotlinPsiUtil.getTypeWithoutTypeParameters(type)
return StringUtil.getPackageName(typeName).startsWith(supportedPackage)
}
} | apache-2.0 |
chemickypes/Glitchy | glitchappcore/src/main/java/me/bemind/glitchappcore/app/Interfaces.kt | 1 | 859 | package me.bemind.glitchappcore.app
import android.content.res.Configuration
import android.os.Bundle
import me.bemind.glitchappcore.EffectState
import me.bemind.glitchappcore.GlitchyBaseActivity
import me.bemind.glitchappcore.State
/**
* Created by angelomoroni on 18/04/17.
*/
interface IAppView {
fun updateState(state: State)
fun restoreView(effectState: EffectState?,emptyImageView: Boolean)
}
interface IAppPresenter {
var modState : State
var appView : IAppView?
var emptyImageView: Boolean
var effectState : EffectState?
fun saveInstanceState(activity: GlitchyBaseActivity, outState: Bundle?)
fun restoreInstanceState(activity: GlitchyBaseActivity, savedInstanceState: Bundle?)
fun onBackPressed() :Boolean
fun onConfigurationChanged(newConfig: Configuration?)
fun onResume()
}
interface IAppLogic
| apache-2.0 |
jwren/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/mpp/getCompilations.kt | 4 | 1961 | // 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.gradleJava.configuration.mpp
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.kotlin.idea.gradle.configuration.kotlinSourceSetData
import org.jetbrains.kotlin.idea.gradleJava.configuration.KotlinMPPGradleProjectResolver
import org.jetbrains.kotlin.idea.gradleJava.configuration.utils.KotlinModuleUtils.getKotlinModuleId
import org.jetbrains.kotlin.idea.gradleTooling.KotlinMPPGradleModel
import org.jetbrains.kotlin.idea.projectModel.KotlinCompilation
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext
internal fun KotlinMPPGradleProjectResolver.Companion.getCompilations(
gradleModule: IdeaModule,
mppModel: KotlinMPPGradleModel,
ideModule: DataNode<ModuleData>,
resolverCtx: ProjectResolverContext
): Sequence<Pair<DataNode<GradleSourceSetData>, KotlinCompilation>> {
val sourceSetsMap = HashMap<String, DataNode<GradleSourceSetData>>()
for (dataNode in ExternalSystemApiUtil.findAll(ideModule, GradleSourceSetData.KEY)) {
if (dataNode.kotlinSourceSetData?.sourceSetInfo != null) {
sourceSetsMap[dataNode.data.id] = dataNode
}
}
return sequence {
for (target in mppModel.targets) {
for (compilation in target.compilations) {
val moduleId = getKotlinModuleId(gradleModule, compilation, resolverCtx)
val moduleDataNode = sourceSetsMap[moduleId] ?: continue
yield(moduleDataNode to compilation)
}
}
}
}
| apache-2.0 |
zielu/GitToolBox | src/main/kotlin/zielu/intellij/util/ZDateFormatUtil.kt | 1 | 3298 | package zielu.intellij.util
import com.intellij.util.text.SyncDateFormat
import java.time.Duration
import java.time.Instant
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.time.temporal.ChronoUnit
import java.util.Date
internal object ZDateFormatUtil {
/**
* Formats relative date-time in following way:
* 1. under 1 minutes - moments ago
* 2. 1 minutes to 1 hour - x minutes, one hour ago
* 3. over 1 hour - today, yesterday, according to date format
*/
fun formatPrettyDateTime(
date: ZonedDateTime,
now: ZonedDateTime,
dateFormat: SyncDateFormat
): String {
if (now < date) {
return ZResBundle.na()
}
val nowInstant = now.toInstant()
val dateInstant = date.toInstant()
val duration = Duration.between(dateInstant, nowInstant)
return if (duration < HOUR_AND_MINUTE) {
formatPrettyUntilOneHour(duration)
} else {
formatOverOneHour(dateInstant, nowInstant, dateFormat)
}
}
private fun formatPrettyUntilOneHour(duration: Duration): String {
return if (duration < MINUTE) {
ZResBundle.message("date.format.minutes.ago", 0)
} else ZResBundle.message("date.format.minutes.ago", duration.dividedBy(60).seconds)
}
private fun formatOverOneHour(date: Instant, now: Instant, dateFormat: SyncDateFormat): String {
val nowDate = now.atZone(ZoneOffset.UTC).toLocalDate()
val referenceDate = date.atZone(ZoneOffset.UTC).toLocalDate()
return when {
nowDate == referenceDate -> {
ZResBundle.message("date.format.today")
}
nowDate.minusDays(1) == referenceDate -> {
ZResBundle.message("date.format.yesterday")
}
else -> {
dateFormat.format(Date.from(date))
}
}
}
fun formatBetweenDates(date1: ZonedDateTime, date2: ZonedDateTime): String {
val duration = Duration.between(date1, date2)
return if (duration.isNegative) {
// TODO: should handle future - in a x minutes
ZResBundle.na()
} else {
formatRelativePastDuration(duration)
}
}
private fun formatRelativePastDuration(duration: Duration): String {
return when {
duration < MINUTE -> {
ZResBundle.message("date.format.moments.ago")
}
duration < HOUR -> {
ZResBundle.message("date.format.n.minutes.ago", duration.dividedBy(MINUTE))
}
duration < DAY -> {
ZResBundle.message("date.format.n.hours.ago", duration.dividedBy(HOUR))
}
duration < WEEK -> {
ZResBundle.message("date.format.n.days.ago", duration.dividedBy(DAY))
}
duration < MONTH -> {
ZResBundle.message("date.format.n.weeks.ago", duration.dividedBy(WEEK))
}
duration < YEAR -> {
ZResBundle.message("date.format.n.months.ago", duration.dividedBy(MONTH))
}
else -> {
ZResBundle.message("date.format.n.years.ago", duration.dividedBy(YEAR))
}
}
}
}
private val MINUTE = Duration.ofSeconds(60)
private val HOUR = Duration.of(1, ChronoUnit.HOURS)
private val HOUR_AND_MINUTE = HOUR.plusSeconds(1)
private val DAY = Duration.of(1, ChronoUnit.DAYS)
private val WEEK = Duration.of(7, ChronoUnit.DAYS)
private val MONTH = Duration.of(30, ChronoUnit.DAYS)
private val YEAR = Duration.of(365, ChronoUnit.DAYS)
| apache-2.0 |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/ide/actions/CloseAllProjectsAction.kt | 7 | 905 | // 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.actions
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.ui.IdeUICustomization
/**
* @author Konstantin Bulenkov
*/
class CloseAllProjectsAction : CloseProjectsActionBase() {
init {
templatePresentation.setText { IdeUICustomization.getInstance().projectMessage("action.close.all.projects.text") }
templatePresentation.setDescription { IdeUICustomization.getInstance().projectMessage("action.close.all.projects.description") }
}
override fun canClose(project: Project, currentProject: Project) = true
override fun shouldShow(e: AnActionEvent) = ProjectManager.getInstance().openProjects.size > 1
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/MoveTypeAliasToTopLevelFix.kt | 5 | 1471 | // 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.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtTypeAlias
import org.jetbrains.kotlin.psi.psiUtil.parents
class MoveTypeAliasToTopLevelFix(element: KtTypeAlias) : KotlinQuickFixAction<KtTypeAlias>(element) {
override fun getText() = KotlinBundle.message("fix.move.typealias.to.top.level")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val typeAlias = element ?: return
val parents = typeAlias.parents.toList().reversed()
val containingFile = parents.firstOrNull() as? KtFile ?: return
val target = parents.getOrNull(1) ?: return
containingFile.addAfter(typeAlias, target)
containingFile.addAfter(KtPsiFactory(typeAlias).createNewLine(2), target)
typeAlias.delete()
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic) = (diagnostic.psiElement as? KtTypeAlias)?.let { MoveTypeAliasToTopLevelFix(it) }
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCallChain/joinToStringOnHashMap.kt | 9 | 157 | // PROBLEM: none
// WITH_STDLIB
fun test(data: HashMap<String, String>) {
val result = data.<caret>map { "${it.key}: ${it.value}" }.joinToString("\n")
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspections/naming/objectProperty/test.kt | 10 | 404 | val Foo: String = ""
var FOO_BAR: Int = 0
var _FOO: Int = 0
const val THREE = 3
val xyzzy = 1
fun foo() {
val XYZZY = 1
val BAR_BAZ = 2
}
object Foo {
val Foo: String = ""
var FOO_BAR: Int = 0
var _FOO: Int = 0
}
class D {
private val _foo: String
private val FOO_BAR: String
companion object {
val Foo: String = ""
var FOO_BAR: Int = 0
}
} | apache-2.0 |
LouisCAD/Splitties | modules/permissions/src/androidMain/kotlin/splitties/permissions/internal/PermissionRequestDialogFragment.kt | 1 | 3302 | /*
* Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
package splitties.permissions.internal
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.annotation.RequiresApi
import androidx.fragment.app.DialogFragment
import kotlinx.coroutines.CompletableDeferred
import splitties.experimental.ExperimentalSplittiesApi
import splitties.intents.intent
import splitties.lifecycle.coroutines.createJob
import splitties.permissions.PermissionRequestResult
@RequiresApi(23)
internal class PermissionRequestDialogFragment : DialogFragment() {
var permissionNames: Array<out String>? = null
suspend fun awaitResult(): PermissionRequestResult = try {
asyncGrant.await()
} finally {
runCatching { dismissAllowingStateLoss() } // Activity may be detached, so we catch.
}
@OptIn(ExperimentalSplittiesApi::class)
private val asyncGrant = CompletableDeferred<PermissionRequestResult>(lifecycle.createJob())
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
permissionNames?.also {
@Suppress("Deprecation") // We don't need the ActivityResultContract APIs.
requestPermissions(it, 1)
} ?: dismissAllowingStateLoss()
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
handleGrantResult(grantResults)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
checkNotNull(data) // data is always provided from PermissionRequestFallbackActivity result.
val extras = data.extras!! // and its result always contains the grantResult extra.
handleGrantResult(extras.get(PermissionRequestFallbackActivity.GRANT_RESULT) as IntArray)
}
private fun handleGrantResult(grantResults: IntArray) {
val permissions = permissionNames ?: return
if (grantResults.isEmpty()) {
fallbackRequestFromTransparentActivity(permissions)
return
}
try {
val indexOfFirstNotGranted = grantResults.indexOfFirst {
it != PackageManager.PERMISSION_GRANTED
}
val result = if (indexOfFirstNotGranted == -1) {
PermissionRequestResult.Granted
} else permissions[indexOfFirstNotGranted].let { firstDeniedPermission ->
if (shouldShowRequestPermissionRationale(firstDeniedPermission)) {
PermissionRequestResult.Denied.MayAskAgain(firstDeniedPermission)
} else {
PermissionRequestResult.Denied.DoNotAskAgain(firstDeniedPermission)
}
}
asyncGrant.complete(result)
} finally {
dismissAllowingStateLoss()
}
}
private fun fallbackRequestFromTransparentActivity(permissions: Array<out String>) {
@Suppress("Deprecation") // We don't need the ActivityResultContract APIs.
startActivityForResult(PermissionRequestFallbackActivity.intent { _, extrasSpec ->
extrasSpec.permissionNames = permissions
}, 1)
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromReferenceExpressionActionFactory.kt | 2 | 6010 | // 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.quickfix.createFromUsage.createClass
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.caches.resolve.analyzeAndGetResult
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.callUtil.getCall
import org.jetbrains.kotlin.utils.ifEmpty
import java.util.*
object CreateClassFromReferenceExpressionActionFactory : CreateClassFromUsageFactory<KtSimpleNameExpression>() {
override fun getElementOfInterest(diagnostic: Diagnostic): KtSimpleNameExpression? {
val refExpr = diagnostic.psiElement as? KtSimpleNameExpression ?: return null
if (refExpr.getNonStrictParentOfType<KtTypeReference>() != null) return null
return refExpr
}
private fun getFullCallExpression(element: KtSimpleNameExpression): KtExpression? {
return element.parent.let {
when {
it is KtCallExpression && it.calleeExpression == element -> return null
it is KtQualifiedExpression && it.selectorExpression == element -> it
else -> element
}
}
}
private fun isQualifierExpected(element: KtSimpleNameExpression) =
element.isDotReceiver() || ((element.parent as? KtDotQualifiedExpression)?.isDotReceiver() ?: false)
override fun getPossibleClassKinds(element: KtSimpleNameExpression, diagnostic: Diagnostic): List<ClassKind> {
fun isEnum(element: PsiElement): Boolean {
return when (element) {
is KtClass -> element.isEnum()
is PsiClass -> element.isEnum
else -> false
}
}
val name = element.getReferencedName()
val (context, moduleDescriptor) = element.analyzeAndGetResult()
val fullCallExpr = getFullCallExpression(element) ?: return Collections.emptyList()
val inImport = element.getNonStrictParentOfType<KtImportDirective>() != null
if (inImport || isQualifierExpected(element)) {
val receiverSelector =
(fullCallExpr as? KtQualifiedExpression)?.receiverExpression?.getQualifiedElementSelector() as? KtReferenceExpression
val qualifierDescriptor = receiverSelector?.let { context[BindingContext.REFERENCE_TARGET, it] }
val targetParents = getTargetParentsByQualifier(element, receiverSelector != null, qualifierDescriptor)
.ifEmpty { return emptyList() }
targetParents.forEach {
if (element.getCreatePackageFixIfApplicable(it) != null) return emptyList()
}
if (!name.checkClassName()) return emptyList()
return ClassKind.values().filter {
when (it) {
ClassKind.ANNOTATION_CLASS -> inImport
ClassKind.ENUM_ENTRY -> inImport && targetParents.any { isEnum(it) }
else -> true
}
}
}
val parent = element.parent
if (parent is KtClassLiteralExpression && parent.receiverExpression == element) {
return listOf(ClassKind.PLAIN_CLASS, ClassKind.ENUM_CLASS, ClassKind.INTERFACE, ClassKind.ANNOTATION_CLASS, ClassKind.OBJECT)
}
if (fullCallExpr.getAssignmentByLHS() != null) return Collections.emptyList()
val call = element.getCall(context) ?: return Collections.emptyList()
val targetParents = getTargetParentsByCall(call, context).ifEmpty { return emptyList() }
if (isInnerClassExpected(call)) return Collections.emptyList()
val allKinds = listOf(ClassKind.OBJECT, ClassKind.ENUM_ENTRY)
val expectedType = fullCallExpr.guessTypeForClass(context, moduleDescriptor)
return allKinds.filter { classKind ->
targetParents.any { targetParent ->
(expectedType == null || getClassKindFilter(expectedType, targetParent)(classKind)) && when (classKind) {
ClassKind.OBJECT -> expectedType == null || !isEnum(targetParent)
ClassKind.ENUM_ENTRY -> isEnum(targetParent)
else -> false
}
}
}
}
override fun extractFixData(element: KtSimpleNameExpression, diagnostic: Diagnostic): ClassInfo? {
val name = element.getReferencedName()
val (context, moduleDescriptor) = element.analyzeAndGetResult()
val fullCallExpr = getFullCallExpression(element) ?: return null
if (element.isInImportDirective() || isQualifierExpected(element)) {
val receiverSelector =
(fullCallExpr as? KtQualifiedExpression)?.receiverExpression?.getQualifiedElementSelector() as? KtReferenceExpression
val qualifierDescriptor = receiverSelector?.let { context[BindingContext.REFERENCE_TARGET, it] }
val targetParents = getTargetParentsByQualifier(element, receiverSelector != null, qualifierDescriptor)
.ifEmpty { return null }
return ClassInfo(
name = name,
targetParents = targetParents,
expectedTypeInfo = TypeInfo.Empty
)
}
val call = element.getCall(context) ?: return null
val targetParents = getTargetParentsByCall(call, context).ifEmpty { return null }
val expectedTypeInfo = fullCallExpr.guessTypeForClass(context, moduleDescriptor)?.toClassTypeInfo() ?: TypeInfo.Empty
return ClassInfo(
name = name,
targetParents = targetParents,
expectedTypeInfo = expectedTypeInfo
)
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/references/KtIdeReferenceProviderService.kt | 2 | 4536 | // 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.references
import com.intellij.openapi.components.service
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.psi.ContributedReferenceHost
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.PsiReferenceService
import com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistry
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.util.containers.ConcurrentFactoryMap
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.psi.KotlinReferenceProvidersService
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.utils.SmartList
interface KotlinPsiReferenceProvider {
fun getReferencesByElement(element: PsiElement): Array<PsiReference>
}
interface KotlinReferenceProviderContributor {
fun registerReferenceProviders(registrar: KotlinPsiReferenceRegistrar)
companion object {
fun getInstance(): KotlinReferenceProviderContributor = service()
}
}
class KotlinPsiReferenceRegistrar {
val providers: MultiMap<Class<out PsiElement>, KotlinPsiReferenceProvider> = MultiMap.create()
inline fun <reified E : KtElement> registerProvider(crossinline factory: (E) -> PsiReference?) {
registerMultiProvider<E> { element ->
factory(element)?.let { reference -> arrayOf(reference) } ?: PsiReference.EMPTY_ARRAY
}
}
inline fun <reified E : KtElement> registerMultiProvider(crossinline factory: (E) -> Array<PsiReference>) {
val provider: KotlinPsiReferenceProvider = object : KotlinPsiReferenceProvider {
override fun getReferencesByElement(element: PsiElement): Array<PsiReference> {
return factory(element as E)
}
}
registerMultiProvider(E::class.java, provider)
}
fun registerMultiProvider(klass: Class<out PsiElement>, provider: KotlinPsiReferenceProvider) {
providers.putValue(klass, provider)
}
}
class KtIdeReferenceProviderService : KotlinReferenceProvidersService() {
private val originalProvidersBinding: MultiMap<Class<out PsiElement>, KotlinPsiReferenceProvider>
private val providersBindingCache: Map<Class<out PsiElement>, List<KotlinPsiReferenceProvider>>
init {
val registrar = KotlinPsiReferenceRegistrar()
KotlinReferenceProviderContributor.getInstance().registerReferenceProviders(registrar)
originalProvidersBinding = registrar.providers
providersBindingCache = ConcurrentFactoryMap.createMap<Class<out PsiElement>, List<KotlinPsiReferenceProvider>> { klass ->
val result = SmartList<KotlinPsiReferenceProvider>()
for (bindingClass in originalProvidersBinding.keySet()) {
if (bindingClass.isAssignableFrom(klass)) {
result.addAll(originalProvidersBinding.get(bindingClass))
}
}
result
}
}
private fun doGetKotlinReferencesFromProviders(context: PsiElement): Array<PsiReference> {
val providers: List<KotlinPsiReferenceProvider>? = providersBindingCache[context.javaClass]
if (providers.isNullOrEmpty()) return PsiReference.EMPTY_ARRAY
val result = SmartList<PsiReference>()
for (provider in providers) {
try {
result.addAll(provider.getReferencesByElement(context))
} catch (ignored: IndexNotReadyException) {
// Ignore and continue to next provider
}
}
if (result.isEmpty()) {
return PsiReference.EMPTY_ARRAY
}
return result.toTypedArray()
}
override fun getReferences(psiElement: PsiElement): Array<PsiReference> {
if (psiElement is ContributedReferenceHost) {
return ReferenceProvidersRegistry.getReferencesFromProviders(psiElement, PsiReferenceService.Hints.NO_HINTS)
}
return CachedValuesManager.getCachedValue(psiElement) {
CachedValueProvider.Result.create(
doGetKotlinReferencesFromProviders(psiElement),
PsiModificationTracker.MODIFICATION_COUNT
)
}
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/intentions/branched/ifWhen/ifToWhen/combinedIf.kt | 13 | 247 | fun bar(arg: Int): String {
<caret>if (arg == 1) return "One"
else if (arg == 2) return "Two"
if (arg == 0) return "Zero"
if (arg == -1) return "Minus One"
else if (arg == -2) return "Minus Two"
return "Something Complex"
} | apache-2.0 |
Keniobyte/PoliceReportsMobile | app/src/main/java/com/keniobyte/bruino/minsegapp/utils/view_presenter/Presenter.kt | 1 | 206 | package com.keniobyte.bruino.minsegapp.utils.view_presenter
/**
* @author bruino
* @version 19/05/17.
*/
interface Presenter<T: View> {
var view: T?
fun onDestroy(){
view = null
}
} | gpl-3.0 |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/execute/ExecuteViewState.kt | 1 | 196 | package ch.rmy.android.http_shortcuts.activities.execute
import ch.rmy.android.framework.viewmodel.viewstate.DialogState
data class ExecuteViewState(
val dialogState: DialogState? = null,
)
| mit |
spring-projects/spring-security | config/src/test/kotlin/org/springframework/security/config/web/server/ServerReferrerPolicyDslTests.kt | 1 | 3670 | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.web.server
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity
import org.springframework.security.config.test.SpringTestContext
import org.springframework.security.config.test.SpringTestContextExtension
import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter
import org.springframework.security.web.server.SecurityWebFilterChain
import org.springframework.security.web.server.header.ReferrerPolicyServerHttpHeadersWriter
import org.springframework.test.web.reactive.server.WebTestClient
import org.springframework.web.reactive.config.EnableWebFlux
/**
* Tests for [ServerReferrerPolicyDsl]
*
* @author Eleftheria Stein
*/
@ExtendWith(SpringTestContextExtension::class)
class ServerReferrerPolicyDslTests {
@JvmField
val spring = SpringTestContext(this)
private lateinit var client: WebTestClient
@Autowired
fun setup(context: ApplicationContext) {
this.client = WebTestClient
.bindToApplicationContext(context)
.configureClient()
.build()
}
@Test
fun `request when referrer policy configured then referrer policy header in response`() {
this.spring.register(ReferrerPolicyConfig::class.java).autowire()
this.client.get()
.uri("/")
.exchange()
.expectHeader().valueEquals("Referrer-Policy", ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER.policy)
}
@Configuration
@EnableWebFluxSecurity
@EnableWebFlux
open class ReferrerPolicyConfig {
@Bean
open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
headers {
referrerPolicy { }
}
}
}
}
@Test
fun `request when custom policy configured then custom policy in response header`() {
this.spring.register(CustomPolicyConfig::class.java).autowire()
this.client.get()
.uri("/")
.exchange()
.expectHeader().valueEquals("Referrer-Policy", ReferrerPolicyServerHttpHeadersWriter.ReferrerPolicy.SAME_ORIGIN.policy)
}
@Configuration
@EnableWebFluxSecurity
@EnableWebFlux
open class CustomPolicyConfig {
@Bean
open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
headers {
referrerPolicy {
policy = ReferrerPolicyServerHttpHeadersWriter.ReferrerPolicy.SAME_ORIGIN
}
}
}
}
}
}
| apache-2.0 |
mapzen/eraser-map | app/src/test/kotlin/com/mapzen/erasermap/view/TestSpeakerbox.kt | 1 | 948 | @file:JvmName("TestSpeakerbox")
package com.mapzen.erasermap.view
import android.app.Activity
class TestSpeakerbox : Speaker {
var finishOnSpeak: Boolean = false
var errorOnSpeak: Boolean = false
override fun play(text: String, onStart: Runnable, onDone: Runnable, onError: Runnable) {
onStart?.run()
if (finishOnSpeak) {
onDone?.run()
}
if (errorOnSpeak) {
onError?.run()
}
}
override fun stop() {
}
override fun mute() {
}
override fun unmute() {
}
override fun isMuted(): Boolean {
return false
}
override fun enableVolumeControl(activity: Activity) {
}
override fun disableVolumeControl(activity: Activity) {
}
override fun setQueueMode(queueMode: Int) {
}
override fun requestAudioFocus() {
}
override fun abandonAudioFocus() {
}
override fun shutdown() {
}
}
| gpl-3.0 |
sg26565/hott-transmitter-config | HoTT-Model/src/main/kotlin/de/treichels/hott/model/enums/MixerType.kt | 1 | 996 | /**
* HoTT Transmitter Config Copyright (C) 2013 Oliver Treichel
*
* 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:></http:>//www.gnu.org/licenses/>.
*/
package de.treichels.hott.model.enums
import de.treichels.hott.util.get
import java.util.*
/**
* @author Oliver Treichel <[email protected]>
*/
enum class MixerType {
Curve, Dual, Linear;
override fun toString(): String = ResourceBundle.getBundle(javaClass.name)[name]
}
| lgpl-3.0 |
aosp-mirror/platform_frameworks_support | room/compiler/src/main/kotlin/androidx/room/vo/CallType.kt | 1 | 710 | /*
* Copyright (C) 2016 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.room.vo
enum class CallType {
FIELD,
METHOD,
CONSTRUCTOR
}
| apache-2.0 |
kerubistan/kerub | src/main/kotlin/com/github/kerubistan/kerub/model/dynamic/VirtualStorageFsAllocation.kt | 2 | 1307 | package com.github.kerubistan.kerub.model.dynamic
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonTypeName
import com.github.kerubistan.kerub.model.FsStorageCapability
import com.github.kerubistan.kerub.model.io.VirtualDiskFormat
import com.github.kerubistan.kerub.utils.validateSize
import java.math.BigInteger
import java.util.UUID
@JsonTypeName("fs-allocation")
data class VirtualStorageFsAllocation(
override val hostId: UUID,
override val capabilityId: UUID,
override val actualSize: BigInteger,
val mountPoint: String,
override val type: VirtualDiskFormat,
val fileName: String,
val backingFile: String? = null
) : VirtualStorageAllocation {
init {
actualSize.validateSize("actualSize")
require(fileName.startsWith(mountPoint)) {
"The file name ($fileName) must be a full path starting with the mount point ($mountPoint)"
}
require(fileName.endsWith(type.name)) {
"the file name ($fileName) must be postfixed by the file type ($type)"
}
}
override fun getRedundancyLevel(): Byte = 0
@JsonIgnore
override fun requires() = FsStorageCapability::class
override fun resize(newSize: BigInteger): VirtualStorageAllocation = this.copy(actualSize = newSize)
override fun getPath(id: UUID) =
"$mountPoint/$id.$type"
} | apache-2.0 |
MaTriXy/gradle-play-publisher-1 | play/plugin/src/main/kotlin/com/github/triplet/gradle/play/internal/Plugins.kt | 1 | 3927 | package com.github.triplet.gradle.play.internal
import com.android.build.api.variant.ApplicationVariant
import com.android.build.api.variant.ApplicationVariantProperties
import com.github.triplet.gradle.common.utils.PLUGIN_GROUP
import com.github.triplet.gradle.common.utils.nullOrFull
import com.github.triplet.gradle.play.PlayPublisherExtension
import com.github.triplet.gradle.play.tasks.CommitEdit
import com.github.triplet.gradle.play.tasks.GenerateEdit
import com.github.triplet.gradle.play.tasks.internal.EditTaskBase
import org.gradle.api.InvalidUserDataException
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.tasks.TaskProvider
import org.gradle.kotlin.dsl.register
internal val ApplicationVariantProperties.flavorNameOrDefault
get() = flavorName.nullOrFull() ?: "main"
internal val ApplicationVariantProperties.playPath get() = "$RESOURCES_OUTPUT_PATH/$name/$PLAY_PATH"
internal fun Project.newTask(
name: String,
description: String? = null,
block: Task.() -> Unit = {}
) = newTask(name, description, emptyArray(), block)
internal inline fun <reified T : Task> Project.newTask(
name: String,
description: String? = null,
constructorArgs: Array<Any> = emptyArray(),
noinline block: T.() -> Unit = {}
): TaskProvider<T> {
val config: T.() -> Unit = {
this.description = description
this.group = PLUGIN_GROUP.takeUnless { description.isNullOrBlank() }
block()
}
return tasks.register<T>(name, *constructorArgs).apply { configure(config) }
}
internal fun Project.getGenEditTask(
appId: String,
extension: PlayPublisherExtension
) = rootProject.getOrRegisterEditTask<GenerateEdit>("generateEditFor", extension, appId)
internal fun Project.getCommitEditTask(
appId: String,
extension: PlayPublisherExtension
) = rootProject.getOrRegisterEditTask<CommitEdit>("commitEditFor", extension, appId)
internal fun ApplicationVariant<ApplicationVariantProperties>.buildExtension(
extensionContainer: NamedDomainObjectContainer<PlayPublisherExtension>,
baseExtension: PlayPublisherExtension,
cliOptionsExtension: PlayPublisherExtension
): PlayPublisherExtension = buildExtensionInternal(
this,
extensionContainer,
baseExtension,
cliOptionsExtension
)
private fun buildExtensionInternal(
variant: ApplicationVariant<ApplicationVariantProperties>,
extensionContainer: NamedDomainObjectContainer<PlayPublisherExtension>,
baseExtension: PlayPublisherExtension,
cliOptionsExtension: PlayPublisherExtension
): PlayPublisherExtension {
val variantExtension = extensionContainer.findByName(variant.name)
val flavorExtension = variant.productFlavors.mapNotNull { (_, flavor) ->
extensionContainer.findByName(flavor)
}.singleOrNull()
val buildTypeExtension = variant.buildType?.let { extensionContainer.findByName(it) }
val extensions = listOfNotNull(
cliOptionsExtension,
variantExtension,
flavorExtension,
buildTypeExtension,
baseExtension
).distinctBy {
it.name
}
return mergeExtensions(extensions)
}
private inline fun <reified T : EditTaskBase> Project.getOrRegisterEditTask(
baseName: String,
extension: PlayPublisherExtension,
appId: String
): TaskProvider<T> {
val taskName = baseName + appId.split(".").joinToString("Dot") { it.capitalize() }
return try {
tasks.register<T>(taskName, extension).apply {
configure {
editIdFile.set(layout.buildDirectory.file("$OUTPUT_PATH/$appId.txt"))
}
}
} catch (e: InvalidUserDataException) {
@Suppress("UNCHECKED_CAST")
tasks.named(taskName) as TaskProvider<T>
}
}
| mit |
chiken88/passnotes | app/src/main/kotlin/com/ivanovsky/passnotes/domain/interactor/search/SearchInteractor.kt | 1 | 2841 | package com.ivanovsky.passnotes.domain.interactor.search
import com.ivanovsky.passnotes.data.entity.Group
import com.ivanovsky.passnotes.data.entity.Note
import com.ivanovsky.passnotes.data.entity.OperationResult
import com.ivanovsky.passnotes.data.repository.EncryptedDatabaseRepository
import com.ivanovsky.passnotes.domain.DispatcherProvider
import com.ivanovsky.passnotes.domain.usecases.GetDatabaseUseCase
import com.ivanovsky.passnotes.domain.usecases.LockDatabaseUseCase
import kotlinx.coroutines.withContext
class SearchInteractor(
private val dbRepo: EncryptedDatabaseRepository,
private val dispatchers: DispatcherProvider,
private val getDbUseCase: GetDatabaseUseCase,
private val lockUseCase: LockDatabaseUseCase
) {
suspend fun find(query: String): OperationResult<List<Item>> {
return withContext(dispatchers.IO) {
val dbResult = getDbUseCase.getDatabase()
if (dbResult.isFailed) {
return@withContext dbResult.takeError()
}
val db = dbResult.obj
val notesResult = db.noteRepository.find(query)
if (notesResult.isFailed) {
return@withContext notesResult.takeError()
}
val groupsResult = db.groupRepository.find(query)
if (groupsResult.isFailed) {
return@withContext groupsResult.takeError()
}
val notes = notesResult.obj
val groups = groupsResult.obj
val items = mutableListOf<Item>()
for (group in groups) {
val noteCountResult = dbRepo.noteRepository.getNoteCountByGroupUid(group.uid)
if (noteCountResult.isFailed) {
return@withContext noteCountResult.takeError()
}
val childGroupCountResult = dbRepo.groupRepository.getChildGroupsCount(group.uid)
if (childGroupCountResult.isFailed) {
return@withContext childGroupCountResult.takeError()
}
val noteCount = noteCountResult.obj
val childGroupCount = childGroupCountResult.obj
items.add(
Item.GroupItem(
group = group,
noteCount = noteCount,
childGroupCount = childGroupCount
)
)
}
items.addAll(notes.map { Item.NoteItem(it) })
OperationResult.success(items)
}
}
fun lockDatabase() {
lockUseCase.lockIfNeed()
}
sealed class Item {
data class NoteItem(val note: Note) : Item()
data class GroupItem(
val group: Group,
val noteCount: Int,
val childGroupCount: Int
) : Item()
}
} | gpl-2.0 |
hazuki0x0/YuzuBrowser | module/ui/src/main/java/jp/hazuki/yuzubrowser/ui/widget/progress/MaterialProgressDrawable.kt | 1 | 790 | /*
* Copyright (C) 2017-2019 Hazuki
*
* 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.
*/
/*
* Copyright (c) 2017 Zhang Hai <[email protected]>
* All Rights Reserved.
*/
package jp.hazuki.yuzubrowser.ui.widget.progress
internal interface MaterialProgressDrawable
| apache-2.0 |
seventhroot/elysium | bukkit/rpk-professions-bukkit/src/main/kotlin/com/rpkit/professions/bukkit/database/table/RPKProfessionHiddenTable.kt | 1 | 6280 | /*
* Copyright 2019 Ren Binden
*
* 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.rpkit.professions.bukkit.database.table
import com.rpkit.characters.bukkit.character.RPKCharacter
import com.rpkit.characters.bukkit.character.RPKCharacterProvider
import com.rpkit.core.database.Database
import com.rpkit.core.database.Table
import com.rpkit.professions.bukkit.RPKProfessionsBukkit
import com.rpkit.professions.bukkit.character.RPKProfessionHidden
import com.rpkit.professions.bukkit.database.jooq.rpkit.Tables.RPKIT_PROFESSION_HIDDEN
import org.ehcache.config.builders.CacheConfigurationBuilder
import org.ehcache.config.builders.ResourcePoolsBuilder
import org.jooq.impl.DSL.constraint
import org.jooq.impl.SQLDataType
class RPKProfessionHiddenTable(
database: Database,
val plugin: RPKProfessionsBukkit
): Table<RPKProfessionHidden>(database, RPKProfessionHidden::class) {
private val cache = if (plugin.config.getBoolean("caching.rpkit_profession_hidden.id.enabled")) {
database.cacheManager.createCache("rpk-professions-bukkit.rpkit_profession_hidden.id", CacheConfigurationBuilder
.newCacheConfigurationBuilder(Int::class.javaObjectType, RPKProfessionHidden::class.java,
ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_profession_hidden.id.size"))).build())
} else {
null
}
private val characterCache = if (plugin.config.getBoolean("caching.rpkit_profession_hidden.character_id.enabled")) {
database.cacheManager.createCache("rpk-professions-bukkit.rpkit_profession_hidden.character_id", CacheConfigurationBuilder
.newCacheConfigurationBuilder(Int::class.javaObjectType, RPKProfessionHidden::class.java,
ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_profession_hidden.character_id.size"))).build())
} else {
null
}
override fun create() {
database.create
.createTableIfNotExists(RPKIT_PROFESSION_HIDDEN)
.column(RPKIT_PROFESSION_HIDDEN.ID, SQLDataType.INTEGER.identity(true))
.column(RPKIT_PROFESSION_HIDDEN.CHARACTER_ID, SQLDataType.INTEGER)
.constraints(
constraint("pk_rpkit_profession_hidden").primaryKey(RPKIT_PROFESSION_HIDDEN.ID)
)
.execute()
}
override fun applyMigrations() {
if (database.getTableVersion(this) == null) {
database.setTableVersion(this, "1.7.0")
}
}
override fun insert(entity: RPKProfessionHidden): Int {
database.create
.insertInto(
RPKIT_PROFESSION_HIDDEN,
RPKIT_PROFESSION_HIDDEN.CHARACTER_ID
)
.values(
entity.character.id
)
.execute()
val id = database.create.lastID().toInt()
entity.id = id
cache?.put(id, entity)
characterCache?.put(entity.character.id, entity)
return id
}
override fun update(entity: RPKProfessionHidden) {
database.create
.update(RPKIT_PROFESSION_HIDDEN)
.set(RPKIT_PROFESSION_HIDDEN.CHARACTER_ID, entity.character.id)
.where(RPKIT_PROFESSION_HIDDEN.ID.eq(entity.id))
.execute()
cache?.put(entity.id, entity)
characterCache?.put(entity.character.id, entity)
}
override fun get(id: Int): RPKProfessionHidden? {
if (cache?.containsKey(id) == true) {
return cache[id]
}
val result = database.create
.select(RPKIT_PROFESSION_HIDDEN.CHARACTER_ID)
.from(RPKIT_PROFESSION_HIDDEN)
.where(RPKIT_PROFESSION_HIDDEN.ID.eq(id))
.fetchOne() ?: return null
val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class)
val character = characterProvider.getCharacter(result[RPKIT_PROFESSION_HIDDEN.CHARACTER_ID])
if (character == null) {
database.create
.deleteFrom(RPKIT_PROFESSION_HIDDEN)
.where(RPKIT_PROFESSION_HIDDEN.ID.eq(id))
.execute()
cache?.remove(id)
characterCache?.remove(result[RPKIT_PROFESSION_HIDDEN.CHARACTER_ID])
return null
}
val professionHidden = RPKProfessionHidden(
id,
character
)
cache?.put(id, professionHidden)
characterCache?.put(professionHidden.character.id, professionHidden)
return professionHidden
}
fun get(character: RPKCharacter): RPKProfessionHidden? {
if (characterCache?.containsKey(character.id) == true) {
return characterCache[character.id]
}
val result = database.create
.select(RPKIT_PROFESSION_HIDDEN.ID)
.from(RPKIT_PROFESSION_HIDDEN)
.where(RPKIT_PROFESSION_HIDDEN.CHARACTER_ID.eq(character.id))
.fetchOne() ?: return null
val professionHidden = RPKProfessionHidden(
result[RPKIT_PROFESSION_HIDDEN.ID],
character
)
cache?.put(professionHidden.id, professionHidden)
characterCache?.put(character.id, professionHidden)
return professionHidden
}
override fun delete(entity: RPKProfessionHidden) {
database.create
.deleteFrom(RPKIT_PROFESSION_HIDDEN)
.where(RPKIT_PROFESSION_HIDDEN.ID.eq(entity.id))
.execute()
cache?.remove(entity.id)
characterCache?.remove(entity.character.id)
}
} | apache-2.0 |
hazuki0x0/YuzuBrowser | legacy/src/test/java/jp/hazuki/yuzubrowser/legacy/action/item/FinishSingleActionTest.kt | 1 | 1909 | /*
* Copyright (C) 2017-2019 Hazuki
*
* 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 jp.hazuki.yuzubrowser.legacy.action.item
import assertk.assertThat
import assertk.assertions.isEqualTo
import com.squareup.moshi.JsonReader
import jp.hazuki.yuzubrowser.legacy.action.SingleAction
import okio.buffer
import okio.source
import org.junit.Test
import java.io.ByteArrayInputStream
class FinishSingleActionTest {
@Test
fun testTrueDecode() {
val fiftyJson = """{"0":true, "1":true}"""
val trueReader = JsonReader.of(ByteArrayInputStream(fiftyJson.toByteArray()).source().buffer())
val trueAction = FinishSingleAction(SingleAction.PAGE_AUTO_SCROLL, trueReader)
assertThat(trueAction.isCloseTab).isEqualTo(true)
assertThat(trueAction.isShowAlert).isEqualTo(true)
assertThat(trueReader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT)
}
@Test
fun testFalseDecode() {
val fiftyJson = """{"0":false, "1":false}"""
val trueReader = JsonReader.of(ByteArrayInputStream(fiftyJson.toByteArray()).source().buffer())
val trueAction = FinishSingleAction(SingleAction.PAGE_AUTO_SCROLL, trueReader)
assertThat(trueAction.isCloseTab).isEqualTo(false)
assertThat(trueAction.isShowAlert).isEqualTo(false)
assertThat(trueReader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT)
}
} | apache-2.0 |
seventhroot/elysium | bukkit/rpk-class-lib-bukkit/src/main/kotlin/com/rpkit/classes/bukkit/classes/RPKClassProvider.kt | 1 | 678 | package com.rpkit.classes.bukkit.classes
import com.rpkit.characters.bukkit.character.RPKCharacter
import com.rpkit.core.service.ServiceProvider
interface RPKClassProvider: ServiceProvider {
val classes: List<RPKClass>
fun getClass(name: String): RPKClass?
fun getClass(character: RPKCharacter): RPKClass?
fun setClass(character: RPKCharacter, `class`: RPKClass)
fun getLevel(character: RPKCharacter, `class`: RPKClass): Int
fun setLevel(character: RPKCharacter, `class`: RPKClass, level: Int)
fun getExperience(character: RPKCharacter, `class`: RPKClass): Int
fun setExperience(character: RPKCharacter, `class`: RPKClass, experience: Int)
} | apache-2.0 |
Litote/kmongo | kmongo-core/src/main/kotlin/org/litote/kmongo/ChangeStreamIterables.kt | 1 | 1758 | /*
* Copyright (C) 2016/2022 Litote
*
* 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.litote.kmongo
import com.mongodb.client.ChangeStreamIterable
import com.mongodb.client.model.changestream.ChangeStreamDocument
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
/**
* Listens change stream in an other thread.
*
* @param executor the executor service for the thread instantiation - default is [Executors.newSingleThreadExecutor]
* @param delay the delay the executor is waiting before submitting the task
* @param unit the unit of the [delay]
* @param listener to listen changes
*/
fun <T> ChangeStreamIterable<T>.listen(
executor: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor(),
delay: Long = 500,
unit: TimeUnit = TimeUnit.MILLISECONDS,
listener: (ChangeStreamDocument<T>) -> Unit
) {
//need to listen the iterator from the original thread
val cursor = iterator()
executor.schedule(
{
cursor.use { cursor ->
while (cursor.hasNext()) {
listener(cursor.next())
}
}
},
delay,
unit
)
} | apache-2.0 |
EMResearch/EvoMaster | e2e-tests/spring-graphql/src/main/kotlin/com/foo/graphql/interfaces/DataRepository.kt | 1 | 450 | package com.foo.graphql.interfaces
import com.foo.graphql.interfaces.type.FlowerStore
import com.foo.graphql.interfaces.type.PotStore
import com.foo.graphql.interfaces.type.Store
import org.springframework.stereotype.Component
@Component
open class DataRepository {
fun getStores(): List<Store> {
return listOf(
FlowerStore(0, "flowerStore0"),
PotStore(1, "potStore1", "BlimBlim")
)
}
} | lgpl-3.0 |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/problem/rest/service/ResourceSampler.kt | 1 | 9891 | package org.evomaster.core.problem.rest.service
import com.google.inject.Inject
import org.evomaster.client.java.controller.api.dto.SutInfoDto
import org.evomaster.core.database.SqlInsertBuilder
import org.evomaster.core.problem.rest.*
import org.evomaster.core.problem.httpws.service.auth.NoAuth
import org.evomaster.core.problem.rest.resource.RestResourceCalls
import org.evomaster.core.problem.rest.resource.SamplerSpecification
import org.evomaster.core.search.ActionFilter
import org.evomaster.core.search.EvaluatedIndividual
import org.evomaster.core.search.service.Randomness
import org.evomaster.core.search.tracer.Traceable
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* resource-based sampler
* the sampler handles resource-based rest individual
*/
open class ResourceSampler : AbstractRestSampler() {
companion object {
val log: Logger = LoggerFactory.getLogger(ResourceSampler::class.java)
}
@Inject
private lateinit var ssc : ResourceSampleMethodController
@Inject
private lateinit var rm : ResourceManageService
@Inject
private lateinit var dm : ResourceDepManageService
override fun initSqlInfo(infoDto: SutInfoDto) {
//when ResourceDependency is enabled, SQL info is required to identify dependency
if (infoDto.sqlSchemaDto != null && (configuration.shouldGenerateSqlData() || config.isEnabledResourceDependency())) {
sqlInsertBuilder = SqlInsertBuilder(infoDto.sqlSchemaDto, rc)
existingSqlData = sqlInsertBuilder!!.extractExistingPKs()
}
}
override fun customizeAdHocInitialIndividuals() {
rm.initResourceNodes(actionCluster, sqlInsertBuilder)
rm.initExcludedResourceNode(getExcludedActions())
adHocInitialIndividuals.clear()
rm.createAdHocIndividuals(NoAuth(),adHocInitialIndividuals, getMaxTestSizeDuringSampler())
authentications.forEach { auth ->
rm.createAdHocIndividuals(auth, adHocInitialIndividuals, getMaxTestSizeDuringSampler())
}
}
override fun postInits() {
ssc.initialize()
}
override fun sampleAtRandom() : RestIndividual {
return sampleAtRandom(randomness.nextInt(1, getMaxTestSizeDuringSampler()))
}
private fun sampleAtRandom(size : Int): RestIndividual {
assert(size <= getMaxTestSizeDuringSampler())
val restCalls = mutableListOf<RestResourceCalls>()
val n = randomness.nextInt(1, getMaxTestSizeDuringSampler())
var left = n
while(left > 0){
val call = sampleRandomResourceAction(0.05, left)
left -= call.seeActionSize(ActionFilter.MAIN_EXECUTABLE)
restCalls.add(call)
}
val ind = RestIndividual(
resourceCalls = restCalls, sampleType = SampleType.RANDOM, dbInitialization = mutableListOf(), trackOperator = this, index = time.evaluatedIndividuals)
ind.doGlobalInitialize(searchGlobalState)
return ind
}
private fun sampleRandomResourceAction(noAuthP: Double, left: Int) : RestResourceCalls{
val r = randomness.choose(rm.getResourceCluster().filter { it.value.isAnyAction() })
val rc = if (randomness.nextBoolean()){
r.sampleOneAction(null, randomness)
} else{
r.randomRestResourceCalls(randomness,left)
}
rc.seeActions(ActionFilter.MAIN_EXECUTABLE).forEach {
(it as RestCallAction).auth = getRandomAuth(noAuthP)
}
return rc
}
override fun smartSample(): RestIndividual {
/*
At the beginning, sampleAll from this set, until it is empty
*/
val ind = if (adHocInitialIndividuals.isNotEmpty()) {
adHocInitialIndividuals.removeAt(0)
} else {
val withDependency = config.probOfEnablingResourceDependencyHeuristics > 0.0
&& dm.isDependencyNotEmpty()
&& randomness.nextBoolean(config.probOfEnablingResourceDependencyHeuristics)
val method = ssc.getSampleStrategy()
sampleWithMethodAndDependencyOption(method, withDependency)
?: return sampleAtRandom()
}
ind.doGlobalInitialize(searchGlobalState)
return ind
}
fun sampleWithMethodAndDependencyOption(sampleMethod : ResourceSamplingMethod, withDependency: Boolean) : RestIndividual?{
val restCalls = mutableListOf<RestResourceCalls>()
when(sampleMethod){
ResourceSamplingMethod.S1iR -> sampleIndependentAction(restCalls)
ResourceSamplingMethod.S1dR -> sampleOneResource(restCalls)
ResourceSamplingMethod.S2dR -> sampleComResource(restCalls, withDependency)
ResourceSamplingMethod.SMdR -> sampleManyResources(restCalls, withDependency)
}
//auth management
val auth = if(authentications.isNotEmpty()){
getRandomAuth(0.0)
}else{
NoAuth()
}
restCalls.flatMap { it.seeActions(ActionFilter.MAIN_EXECUTABLE) }.forEach {
(it as RestCallAction).auth = auth
}
if (restCalls.isNotEmpty()) {
val individual = RestIndividual(restCalls, SampleType.SMART_RESOURCE, sampleSpec = SamplerSpecification(sampleMethod.toString(), withDependency),
trackOperator = if(config.trackingEnabled()) this else null, index = if (config.trackingEnabled()) time.evaluatedIndividuals else -1)
if (withDependency)
dm.sampleResourceWithRelatedDbActions(individual, rm.getMaxNumOfResourceSizeHandling())
individual.cleanBrokenBindingReference()
return individual
}
return null
}
private fun sampleIndependentAction(resourceCalls: MutableList<RestResourceCalls>){
val key = randomness.choose(rm.getResourceCluster().filter { it.value.hasIndependentAction() }.keys)
rm.sampleCall(key, false, resourceCalls, getMaxTestSizeDuringSampler())
}
private fun sampleOneResource(resourceCalls: MutableList<RestResourceCalls>){
val key = selectAIndResourceHasNonInd(randomness)
rm.sampleCall(key, true, resourceCalls, getMaxTestSizeDuringSampler())
}
private fun sampleComResource(resourceCalls: MutableList<RestResourceCalls>, withDependency : Boolean){
if(withDependency){
dm.sampleRelatedResources(resourceCalls, 2, getMaxTestSizeDuringSampler())
}else{
sampleRandomComResource(resourceCalls)
}
}
private fun sampleManyResources(resourceCalls: MutableList<RestResourceCalls>, withDependency: Boolean){
if(withDependency){
val num = randomness.nextInt(3, getMaxTestSizeDuringSampler())
dm.sampleRelatedResources(resourceCalls, num, getMaxTestSizeDuringSampler())
}else{
sampleManyResources(resourceCalls)
}
}
private fun selectAIndResourceHasNonInd(randomness: Randomness) : String{
return randomness.choose(rm.getResourceCluster().filter { r -> r.value.isAnyAction() && !r.value.isIndependent() }.keys)
}
override fun feedback(evi : EvaluatedIndividual<RestIndividual>) {
if(config.resourceSampleStrategy.requiredArchive && evi.hasImprovement)
evi.individual.sampleSpec?.let { ssc.reportImprovement(it) }
}
private fun sampleRandomComResource(resourceCalls: MutableList<RestResourceCalls>){
val candidates = rm.getResourceCluster().filter { !it.value.isIndependent() }.keys
assert(candidates.size > 1)
val keys = randomness.choose(candidates, 2)
var size = getMaxTestSizeDuringSampler()
keys.forEach {
rm.sampleCall(it, true, resourceCalls, size)
size -= resourceCalls.last().seeActionSize(ActionFilter.NO_SQL)
}
}
private fun sampleManyResources(resourceCalls: MutableList<RestResourceCalls>){
val executed = mutableListOf<String>()
val depCand = rm.getResourceCluster().filter { r -> !r.value.isIndependent() }
var resourceSize = randomness.nextInt(3, if(config.maxResourceSize > 0) config.maxResourceSize else 5)
if(resourceSize > depCand.size) resourceSize = depCand.size + 1
var size = getMaxTestSizeDuringSampler()
val candR = rm.getResourceCluster().filter { r -> r.value.isAnyAction() }
while(size > 1 && executed.size < resourceSize){
val key = if(executed.size < resourceSize-1 && size > 2)
randomness.choose(depCand.keys.filter { !executed.contains(it) })
else if (candR.keys.any { !executed.contains(it) })
randomness.choose(candR.keys.filter { !executed.contains(it) })
else
randomness.choose(candR.keys)
rm.sampleCall(key, true, resourceCalls, size)
size -= resourceCalls.last().seeActionSize(ActionFilter.NO_SQL)
executed.add(key)
}
}
override fun createIndividual(restCalls: MutableList<RestCallAction>): RestIndividual {
val resourceCalls = restCalls.map {
val node = rm.getResourceNodeFromCluster(it.path.toString())
RestResourceCalls(
template = node.getTemplate(it.verb.toString()),
node = node,
actions = mutableListOf(it),
dbActions = listOf()
)
}.toMutableList()
val ind = RestIndividual(
resourceCalls=resourceCalls,
sampleType = SampleType.SMART_RESOURCE,
trackOperator = if (config.trackingEnabled()) this else null,
index = if (config.trackingEnabled()) time.evaluatedIndividuals else Traceable.DEFAULT_INDEX)
ind.doGlobalInitialize(searchGlobalState)
return ind
}
} | lgpl-3.0 |
EMResearch/EvoMaster | e2e-tests/spring-graphql/src/test/kotlin/org/evomaster/e2etests/spring/graphql/interfaces/GQLInterfacesEMTest.kt | 1 | 1105 | package org.evomaster.e2etests.spring.graphql.interfaces
import com.foo.graphql.interfaces.InterfacesController
import org.evomaster.core.EMConfig
import org.evomaster.e2etests.spring.graphql.SpringTestBase
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
class GQLInterfacesEMTest : SpringTestBase() {
companion object {
@BeforeAll
@JvmStatic
fun init() {
initClass(InterfacesController())
}
}
@Test
fun testRunEM() {
runTestHandlingFlakyAndCompilation(
"GQL_InterfacesEM",
"org.foo.graphql.InterfacesEM",
20
) { args: MutableList<String> ->
args.add("--problemType")
args.add(EMConfig.ProblemType.GRAPHQL.toString())
val solution = initAndRun(args)
Assertions.assertTrue(solution.individuals.size >= 1)
assertHasAtLeastOneResponseWithData(solution)
assertNoneWithErrors(solution)
}
}
} | lgpl-3.0 |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/problem/rest/RestIndividual.kt | 1 | 14070 | package org.evomaster.core.problem.rest
import org.evomaster.core.database.DbAction
import org.evomaster.core.database.DbActionUtils
import org.evomaster.core.problem.api.service.ApiWsIndividual
import org.evomaster.core.problem.external.service.ApiExternalServiceAction
import org.evomaster.core.problem.rest.resource.RestResourceCalls
import org.evomaster.core.problem.rest.resource.SamplerSpecification
import org.evomaster.core.search.*
import org.evomaster.core.search.ActionFilter.*
import org.evomaster.core.search.gene.*
import org.evomaster.core.search.tracer.Traceable
import org.evomaster.core.search.tracer.TraceableElementCopyFilter
import org.evomaster.core.search.tracer.TrackOperator
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import kotlin.math.max
/**
*
* @property trackOperator indicates which operator create this individual.
* @property index indicates when the individual is created, ie, using num of evaluated individual.
*/
class RestIndividual(
val sampleType: SampleType,
val sampleSpec: SamplerSpecification? = null,
trackOperator: TrackOperator? = null,
index : Int = -1,
allActions : MutableList<out ActionComponent>,
mainSize : Int = allActions.size,
dbSize: Int = 0,
groups : GroupsOfChildren<StructuralElement> = getEnterpriseTopGroups(allActions,mainSize,dbSize)
): ApiWsIndividual(trackOperator, index, allActions,
childTypeVerifier = {
RestResourceCalls::class.java.isAssignableFrom(it)
|| DbAction::class.java.isAssignableFrom(it)
}, groups) {
companion object{
private val log: Logger = LoggerFactory.getLogger(RestIndividual::class.java)
}
constructor(
resourceCalls: MutableList<RestResourceCalls>,
sampleType: SampleType,
sampleSpec: SamplerSpecification? = null,
dbInitialization: MutableList<DbAction> = mutableListOf(),
trackOperator: TrackOperator? = null,
index : Int = -1
) : this(sampleType, sampleSpec, trackOperator, index, mutableListOf<ActionComponent>().apply {
addAll(dbInitialization); addAll(resourceCalls)
}, resourceCalls.size, dbInitialization.size)
constructor(
actions: MutableList<out Action>,
sampleType: SampleType,
dbInitialization: MutableList<DbAction> = mutableListOf(),
trackOperator: TrackOperator? = null,
index : Int = Traceable.DEFAULT_INDEX
) : this(
actions.map {RestResourceCalls(actions= listOf(it as RestCallAction), dbActions = listOf())}.toMutableList(),
sampleType,
null,
dbInitialization,
trackOperator,
index
)
override fun copyContent(): Individual {
return RestIndividual(
sampleType,
sampleSpec?.copy(),
trackOperator,
index,
children.map { it.copy() }.toMutableList() as MutableList<out ActionComponent>,
mainSize = groupsView()!!.sizeOfGroup(GroupsOfChildren.MAIN),
dbSize = groupsView()!!.sizeOfGroup(GroupsOfChildren.INITIALIZATION_SQL)
)
}
override fun canMutateStructure(): Boolean {
return sampleType == SampleType.RANDOM ||
sampleType == SampleType.SMART_GET_COLLECTION ||
sampleType == SampleType.SMART_RESOURCE
}
/**
* Note that if resource-mio is enabled, [dbInitialization] of a RestIndividual is always empty, since DbActions are created
* for initializing an resource for a set of actions on the same resource.
* TODO is this no longer the case?
*
* This effects on a configuration with respect to [EMConfig.geneMutationStrategy] is ONE_OVER_N when resource-mio is enabled.
*
* In another word, if resource-mio is enabled, whatever [EMConfig.geneMutationStrategy] is, it always follows "GeneMutationStrategy.ONE_OVER_N_BIASED_SQL"
* strategy.
*
*/
override fun seeGenes(filter: GeneFilter): List<out Gene> {
return when (filter) {
GeneFilter.ALL -> seeAllActions().flatMap(Action::seeTopGenes)
GeneFilter.NO_SQL -> seeActions(ActionFilter.NO_SQL).flatMap(Action::seeTopGenes)
GeneFilter.ONLY_SQL -> seeDbActions().flatMap(DbAction::seeTopGenes)
GeneFilter.ONLY_EXTERNAL_SERVICE -> seeExternalServiceActions().flatMap(ApiExternalServiceAction::seeTopGenes)
}
}
enum class ResourceFilter { ALL, NO_SQL, ONLY_SQL, ONLY_SQL_INSERTION, ONLY_SQL_EXISTING }
/**
* @return involved resources in [this] RestIndividual
* for all [resourceCalls], we return their resource keys to represent the resource
* for dbActions, we employ their table names to represent the resource
*
* NOTE that for [RestResourceCalls], there might exist DbAction as well.
* But since the dbaction is to prepare resource for the endpoint whose goal is equivalent with POST here,
* we do not consider such dbactions as separated resources from the endpoint.
*/
fun seeResource(filter: ResourceFilter) : List<String>{
return when(filter){
ResourceFilter.ALL -> seeInitializingActions().filterIsInstance<DbAction>().map { it.table.name }.plus(
getResourceCalls().map { it.getResourceKey() }
)
ResourceFilter.NO_SQL -> getResourceCalls().map { it.getResourceKey() }
ResourceFilter.ONLY_SQL -> seeInitializingActions().filterIsInstance<DbAction>().map { it.table.name }
ResourceFilter.ONLY_SQL_EXISTING -> seeInitializingActions().filterIsInstance<DbAction>().filter { it.representExistingData }.map { it.table.name }
ResourceFilter.ONLY_SQL_INSERTION -> seeInitializingActions().filterIsInstance<DbAction>().filterNot { it.representExistingData }.map { it.table.name }
}
}
override fun size() = seeMainExecutableActions().size
//FIXME refactor
override fun verifyInitializationActions(): Boolean {
return DbActionUtils.verifyActions(seeInitializingActions().filterIsInstance<DbAction>())
}
override fun copy(copyFilter: TraceableElementCopyFilter): RestIndividual {
val copy = copy() as RestIndividual
when(copyFilter){
TraceableElementCopyFilter.NONE-> {}
TraceableElementCopyFilter.WITH_TRACK, TraceableElementCopyFilter.DEEP_TRACK ->{
copy.wrapWithTracking(null, tracking!!.copy())
}else -> throw IllegalStateException("${copyFilter.name} is not implemented!")
}
return copy
}
/**
* for each call, there exist db actions for preparing resources.
* however, the db action might refer to a db action which is not in the same call.
* In this case, we need to repair the fk of db actions among calls.
*
* Note: this is ignoring the DB Actions in the initialization of the individual, as we
* are building dependencies among resources here.
*
* TODO not sure whether build binding between fk and pk
*/
fun repairDbActionsInCalls(){
val previous = mutableListOf<DbAction>()
getResourceCalls().forEach { c->
c.repairFK(previous)
previous.addAll(c.seeActions(ONLY_SQL) as List<DbAction>)
}
}
/**
* @return all groups of actions for resource handling
*/
fun getResourceCalls() : List<RestResourceCalls> = children.filterIsInstance<RestResourceCalls>()
/**
* return all the resource calls in this individual, with their index in the children list
* @param isRelative indicates whether to return the relative index by only considering a list of resource calls
*/
fun getIndexedResourceCalls(isRelative: Boolean = true) : Map<Int,RestResourceCalls> = getIndexedChildren(RestResourceCalls::class.java).run {
if (isRelative)
this.map { it.key - getFirstIndexOfRestResourceCalls() to it.value }.toMap()
else
this
}
/****************************** manipulate resource call in an individual *******************************************/
/**
* remove the resource at [position]
*/
fun removeResourceCall(position : Int) {
if(!getIndexedResourceCalls().keys.contains(position))
throw IllegalArgumentException("position is out of range of list")
val removed = killChildByIndex(getFirstIndexOfRestResourceCalls() + position) as RestResourceCalls
removed.removeThisFromItsBindingGenes()
}
fun removeResourceCall(remove: List<RestResourceCalls>) {
if(!getResourceCalls().containsAll(remove))
throw IllegalArgumentException("specified rest calls are not part of this individual")
killChildren(remove)
remove.forEach { it.removeThisFromItsBindingGenes() }
}
/**
* add [restCalls] at [position], if [position] == -1, append the [restCalls] at the end
*/
fun addResourceCall(position: Int = -1, restCalls : RestResourceCalls) {
if (position == -1){
addChildToGroup(restCalls, GroupsOfChildren.MAIN)
}else{
if(position > children.size)
throw IllegalArgumentException("position is out of range of list")
addChildToGroup(getFirstIndexOfRestResourceCalls() + position, restCalls, GroupsOfChildren.MAIN)
}
}
private fun getFirstIndexOfRestResourceCalls() = max(0, max(children.indexOfLast { it is DbAction }+1, children.indexOfFirst { it is RestResourceCalls }))
/**
* replace the resourceCall at [position] with [resourceCalls]
*/
fun replaceResourceCall(position: Int, restCalls: RestResourceCalls){
if(!getIndexedResourceCalls().keys.contains(position))
throw IllegalArgumentException("position is out of range of list")
removeResourceCall(position)
addResourceCall(position, restCalls)
}
/**
* switch the resourceCall at [position1] and the resourceCall at [position2]
*/
fun swapResourceCall(position1: Int, position2: Int){
val valid = getIndexedResourceCalls().keys
if(!valid.contains(position1) || !valid.contains(position2))
throw IllegalArgumentException("position is out of range of list")
if(position1 == position2)
throw IllegalArgumentException("It is not necessary to swap two same position on the resource call list")
swapChildren(getFirstIndexOfRestResourceCalls() + position1, getFirstIndexOfRestResourceCalls() + position2)
}
fun getFixedActionIndexes(resourcePosition: Int)
= getIndexedResourceCalls()[resourcePosition]!!.seeActions(ALL).filter { seeMainExecutableActions().contains(it) }.map {
seeFixedMainActions().indexOf(it)
}
fun getDynamicActionLocalIds(resourcePosition: Int) =
getIndexedResourceCalls()[resourcePosition]!!.seeActions(ALL).filter { seeDynamicMainActions().contains(it) }.map { it.getLocalId() }
private fun validateSwap(first : Int, second : Int) : Boolean{
//TODO need update, although currently not in use
val position = getResourceCalls()[first].shouldBefore.map { r ->
getResourceCalls().indexOfFirst { it.getResourceNodeKey() == r }
}
if(!position.none { it > second }) return false
getResourceCalls().subList(0, second).find { it.shouldBefore.contains(getResourceCalls()[second].getResourceNodeKey()) }?.let {
return getResourceCalls().indexOf(it) < first
}
return true
}
/**
* @return movable position
*/
fun getMovablePosition(position: Int) : List<Int>{
return (getResourceCalls().indices)
.filter {
if(it < position) validateSwap(it, position) else if(it > position) validateSwap(position, it) else false
}
}
/**
* @return whether the call at the position is movable
*/
fun isMovable(position: Int) : Boolean{
return (getResourceCalls().indices)
.any {
if(it < position) validateSwap(it, position) else if(it > position) validateSwap(position, it) else false
}
}
/**
* @return possible swap positions of calls in this individual
*/
fun extractSwapCandidates(): Map<Int, Set<Int>>{
return getIndexedResourceCalls().map {
val range = handleSwapCandidates(this, it.key)
it.key to range
}.filterNot { it.second.isEmpty() }.toMap()
}
private fun handleSwapCandidates(ind: RestIndividual, indexToSwap: Int): Set<Int>{
val swapTo = handleSwapTo(ind, indexToSwap)
return swapTo.filter { t -> handleSwapTo(ind, t).contains(indexToSwap) }.toSet()
}
private fun handleSwapTo(ind: RestIndividual, indexToSwap: Int): Set<Int>{
val indexed = ind.getIndexedResourceCalls()
val toSwap = indexed[indexToSwap]!!
val before : Int = toSwap.shouldBefore.map { t ->
indexed.filter { it.value.getResourceNodeKey() == t }
.minByOrNull { it.key }?.key ?: (indexed.keys.maxOrNull()!! + 1)
}.minOrNull() ?: (indexed.keys.maxOrNull()!! + 1)
val after : Int = toSwap.depends.map { t->
indexed.filter { it.value.getResourceNodeKey() == t }
.maxByOrNull { it.key }?.key ?: 0
}.maxOrNull() ?: 0
if (after >= before) return emptySet()
return indexed.keys.filter { it >= after && it < before && it != indexToSwap }.toSet()
}
override fun getInsertTableNames(): List<String> {
return seeDbActions().filterNot { it.representExistingData }.map { it.table.name }
}
override fun seeMainExecutableActions(): List<RestCallAction> {
return super.seeMainExecutableActions() as List<RestCallAction>
}
} | lgpl-3.0 |
CyroPCJr/Kotlin-Koans | src/test/kotlin/properties/LazyProperty.kt | 1 | 770 | package properties
import org.junit.Assert
import org.junit.Test
class LazyPropertyTest {
@Test
fun testLazy() {
var initialized = false
val lazyProperty = LazyProperty({ initialized = true; 42 })
Assert.assertFalse("Property shouldn't be initialized before access", initialized)
val result: Int = lazyProperty.lazy
Assert.assertTrue("Property should be initialized after access", initialized)
Assert.assertEquals(42, result)
}
@Test
fun initializedOnce() {
var initialized = 0
val lazyProperty = LazyProperty({ initialized++; 42 })
lazyProperty.lazy
lazyProperty.lazy
Assert.assertEquals("Lazy property should be initialized once", 1, initialized)
}
}
| apache-2.0 |
BlueBoxWare/LibGDXPlugin | src/test/testdata/annotators/colorAnnotator/KotlinToJava.kt | 1 | 270 | import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.Colors
const val constC = "#ffff00"
val s = "ff00ff"
val c1 = "#ff0000"
class C {
val c2 = Color(25667)
val c3 = Colors.get("RED")
fun f() {
Colors.put("foobar", Color.YELLOW)
}
}
| apache-2.0 |
KrenVpravo/CheckReaction | app/src/main/java/com/two_two/checkreaction/domain/science/ScienceTargetGenerator.kt | 1 | 546 | package com.two_two.checkreaction.domain.science
import com.two_two.checkreaction.domain.science.colors.ColourProvider
import com.two_two.checkreaction.utils.Constants
import java.util.*
/**
* @author Dmitry Borodin on 2017-01-29.
*/
object ScienceTargetGenerator {
val excludedElement = 1
var chosenColorIndex = pickRandomColourIndex()
fun regenerate() {
chosenColorIndex = pickRandomColourIndex()
}
private fun pickRandomColourIndex() = Random().nextInt(Constants.COLOURS_AVAILABLE_SCIENCE + excludedElement)
} | mit |
firebase/quickstart-android | admob/app/src/main/java/com/google/samples/quickstart/admobexample/kotlin/SecondFragment.kt | 1 | 503 | package com.google.samples.quickstart.admobexample.kotlin
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.google.samples.quickstart.admobexample.R
class SecondFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_second, container, false)
}
} | apache-2.0 |
RocketChat/Rocket.Chat.Android | draw/src/main/java/chat/rocket/android/draw/dagger/AppComponent.kt | 2 | 532 | package chat.rocket.android.draw.dagger
import chat.rocket.android.draw.dagger.module.ActivityBuilderModule
import dagger.Component
import dagger.android.AndroidInjector
import dagger.android.support.AndroidSupportInjectionModule
import dagger.android.support.DaggerApplication
@Component(modules = [AndroidSupportInjectionModule::class, ActivityBuilderModule::class])
interface AppComponent : AndroidInjector<DaggerApplication> {
@Component.Builder
abstract class Builder : AndroidInjector.Builder<DaggerApplication>()
} | mit |
firebase/quickstart-android | firestore/app/src/main/java/com/google/firebase/example/fireeats/kotlin/RatingDialogFragment.kt | 1 | 2227 | package com.google.firebase.example.fireeats.kotlin
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import com.google.firebase.auth.ktx.auth
import com.google.firebase.example.fireeats.databinding.DialogRatingBinding
import com.google.firebase.example.fireeats.kotlin.model.Rating
import com.google.firebase.ktx.Firebase
/**
* Dialog Fragment containing rating form.
*/
class RatingDialogFragment : DialogFragment() {
private var _binding: DialogRatingBinding? = null
private val binding get() = _binding!!
private var ratingListener: RatingListener? = null
internal interface RatingListener {
fun onRating(rating: Rating)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = DialogRatingBinding.inflate(inflater, container, false)
binding.restaurantFormButton.setOnClickListener { onSubmitClicked() }
binding.restaurantFormCancel.setOnClickListener { onCancelClicked() }
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (parentFragment is RatingListener) {
ratingListener = parentFragment as RatingListener
}
}
override fun onResume() {
super.onResume()
dialog?.window?.setLayout(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
}
private fun onSubmitClicked() {
val user = Firebase.auth.currentUser
user?.let {
val rating = Rating(
it,
binding.restaurantFormRating.rating.toDouble(),
binding.restaurantFormText.text.toString())
ratingListener?.onRating(rating)
}
dismiss()
}
private fun onCancelClicked() {
dismiss()
}
companion object {
const val TAG = "RatingDialog"
}
}
| apache-2.0 |
google/private-compute-libraries | java/com/google/android/libraries/pcc/chronicle/util/TypedMap.kt | 1 | 3054 | /*
* Copyright 2022 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.google.android.libraries.pcc.chronicle.util
/**
* A [MutableTypedMap] is a mutable, type-safe map that allows for heterogeneously typed values.
*
* This map is keyed using implementations of the [Key] interface. A [Key] implementation will
* specify the class type of a corresponding value to be stored in the map.
*
* Example:
*
* ```kotlin
* object NameKey : Key<String>
* object IdKey : Key<Int>
*
* map[NameKey] = "First Last"
* map[IdKey] = 123
* ```
*/
class MutableTypedMap(val map: MutableMap<Key<Any>, Any> = mutableMapOf()) {
/** Set a value of type T for the given key */
operator fun <T : Any> set(key: Key<T>, value: T) {
@Suppress("UNCHECKED_CAST")
map[key as Key<Any>] = value
}
/** Get object of type T or null if not present */
operator fun <T> get(key: Key<T>): T? {
@Suppress("UNCHECKED_CAST") return map[key as Key<Any>] as T
}
/** Get immutable version of this [MutableTypedMap] */
fun toTypedMap() = TypedMap(this)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is MutableTypedMap) return false
if (map != other.map) return false
return true
}
override fun hashCode(): Int {
return map.hashCode()
}
}
/**
* Keying structure for the [TypedMap] that can be associated with a value of type T, where T is a
* basic type (https://kotlinlang.org/docs/basic-types.html)
*
* Non-basic types are not recommended, since deep copies are currently not supported.
*
* Example usage of a [Key] for a String value:
* ```kotlin
* object Name : Key<String>
*
* // Set Name
* mutableTypedMap[Name] = "First Last"
* typedMap = TypedMap(mutableTypedMap)
*
* // Get Name
* val myName = typedMap[Name]
* ```
*/
interface Key<T>
/**
* A [TypedMap] is an immutable, type-safe map that allows for heterogeneously typed values. It
* copies in the current state of a provided [MutableTypedMap].
*/
class TypedMap(mutableTypedMap: MutableTypedMap = MutableTypedMap()) {
private val map: MutableTypedMap = MutableTypedMap(mutableTypedMap.map.toMutableMap())
/** Get object of type T or null if not present */
operator fun <T> get(key: Key<T>): T? = map[key]
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is TypedMap) return false
if (map != other.map) return false
return true
}
override fun hashCode(): Int {
return map.hashCode()
}
}
| apache-2.0 |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/backend/CloudSetupFragment.kt | 1 | 15054 | package com.battlelancer.seriesguide.backend
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.isGone
import androidx.fragment.app.Fragment
import com.battlelancer.seriesguide.R
import com.battlelancer.seriesguide.SgApp
import com.battlelancer.seriesguide.backend.settings.HexagonSettings
import com.battlelancer.seriesguide.databinding.FragmentCloudSetupBinding
import com.battlelancer.seriesguide.sync.SgSyncAdapter
import com.battlelancer.seriesguide.sync.SyncProgress
import com.battlelancer.seriesguide.traktapi.ConnectTraktActivity
import com.battlelancer.seriesguide.ui.SeriesGuidePreferences
import com.battlelancer.seriesguide.util.Errors
import com.battlelancer.seriesguide.util.Utils
import com.battlelancer.seriesguide.util.safeShow
import com.firebase.ui.auth.AuthUI
import com.firebase.ui.auth.ErrorCodes
import com.firebase.ui.auth.IdpResponse
import com.google.android.gms.tasks.Task
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.auth.AuthResult
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import timber.log.Timber
/**
* Manages signing in and out with Cloud and account removal.
* Tries to silent sign-in when started. Enables Cloud on sign-in.
* If Cloud is still enabled, but the account requires validation
* enables to retry sign-in or to sign out (actually just disable Cloud).
*/
class CloudSetupFragment : Fragment() {
private var binding: FragmentCloudSetupBinding? = null
private var snackbar: Snackbar? = null
private var signInAccount: FirebaseUser? = null
private lateinit var hexagonTools: HexagonTools
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
hexagonTools = SgApp.getServicesComponent(requireContext()).hexagonTools()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return FragmentCloudSetupBinding.inflate(inflater, container, false).also {
binding = it
}.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding!!.apply {
buttonCloudSignIn.setOnClickListener {
// restrict access to supporters
if (Utils.hasAccessToX(activity)) {
startHexagonSetup()
} else {
Utils.advertiseSubscription(activity)
}
}
buttonCloudSignOut.setOnClickListener { signOut() }
textViewCloudWarnings.setOnClickListener {
// link to trakt account activity which has details about disabled features
startActivity(Intent(context, ConnectTraktActivity::class.java))
}
buttonCloudRemoveAccount.setOnClickListener {
if (RemoveCloudAccountDialogFragment().safeShow(
parentFragmentManager,
"remove-cloud-account"
)) {
setProgressVisible(true)
}
}
updateViews()
setProgressVisible(true)
syncStatusCloud.visibility = View.GONE
}
}
override fun onStart() {
super.onStart()
trySilentSignIn()
}
override fun onResume() {
super.onResume()
EventBus.getDefault().register(this)
}
override fun onPause() {
super.onPause()
EventBus.getDefault().unregister(this)
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onEventMainThread(@Suppress("UNUSED_PARAMETER") event: RemoveCloudAccountDialogFragment.CanceledEvent) {
setProgressVisible(false)
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onEventMainThread(event: RemoveCloudAccountDialogFragment.AccountRemovedEvent) {
event.handle(requireContext())
setProgressVisible(false)
updateViews()
}
@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
fun onEvent(event: SyncProgress.SyncEvent) {
binding?.syncStatusCloud?.setProgress(event)
}
private fun trySilentSignIn() {
val firebaseUser = FirebaseAuth.getInstance().currentUser
if (firebaseUser != null) {
changeAccount(firebaseUser, null)
return
}
// check if the user is still signed in
val signInTask = AuthUI.getInstance()
.silentSignIn(requireContext(), hexagonTools.firebaseSignInProviders)
if (signInTask.isSuccessful) {
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Timber.d("Got cached sign-in")
handleSilentSignInResult(signInTask)
} else {
// If the user has not previously signed in on this device or the sign-in has expired,
// this asynchronous branch will attempt to sign in the user silently. Cross-device
// single sign-on will occur in this branch.
Timber.d("Trying async sign-in")
signInTask.addOnCompleteListener { task ->
if (isAdded) {
handleSilentSignInResult(task)
}
}
}
}
/**
* @param task A completed sign-in task.
*/
private fun handleSilentSignInResult(task: Task<AuthResult>) {
val account = if (task.isSuccessful) {
task.result?.user
} else {
null
}
// Note: Do not show error message if silent sign-in fails, just update UI.
changeAccount(account, null)
}
/**
* If the Firebase account is not null, saves it and auto-starts setup if Cloud is not
* enabled or the account needs validation.
* On sign-in failure with error message (so was not canceled) sets should validate account flag.
*/
private fun changeAccount(account: FirebaseUser?, errorIfNull: String?) {
val signedIn = account != null
if (signedIn) {
Timber.i("Signed in to Cloud.")
signInAccount = account
} else {
signInAccount = null
errorIfNull?.let {
HexagonSettings.shouldValidateAccount(requireContext(), true)
showSnackbar(getString(R.string.hexagon_signin_fail_format, it))
}
}
setProgressVisible(false)
updateViews()
if (signedIn && Utils.hasAccessToX(requireContext())) {
if (!HexagonSettings.isEnabled(requireContext())
|| HexagonSettings.shouldValidateAccount(requireContext())) {
Timber.i("Auto-start Cloud setup.")
startHexagonSetup()
}
}
}
private val signInWithFirebase =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) {
changeAccount(FirebaseAuth.getInstance().currentUser, null)
} else {
val response = IdpResponse.fromResultIntent(result.data)
if (response == null) {
// user chose not to sign in or add account, show no error message
changeAccount(null, null)
} else {
val errorMessage: String?
val ex = response.error
if (ex != null) {
when (ex.errorCode) {
ErrorCodes.NO_NETWORK -> {
errorMessage = getString(R.string.offline)
}
ErrorCodes.PLAY_SERVICES_UPDATE_CANCELLED -> {
// user cancelled, show no error message
errorMessage = null
}
else -> {
if (ex.errorCode == ErrorCodes.DEVELOPER_ERROR
&& !hexagonTools.isGoogleSignInAvailable) {
// Note: If trying to sign-in with email already used with
// Google Sign-In on other device, fails to fall back to
// Google Sign-In because Play Services is not available.
errorMessage = getString(R.string.hexagon_signin_google_only)
} else {
errorMessage = ex.message
Errors.logAndReportHexagonAuthError(
HexagonAuthError.build(ACTION_SIGN_IN, ex)
)
}
}
}
} else {
errorMessage = "Unknown error"
Errors.logAndReportHexagonAuthError(
HexagonAuthError(ACTION_SIGN_IN, errorMessage)
)
}
changeAccount(null, errorMessage)
}
}
}
private fun signIn() {
// Create and launch sign-in intent
val intent = AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(hexagonTools.firebaseSignInProviders)
.setIsSmartLockEnabled(hexagonTools.isGoogleSignInAvailable)
.setTheme(SeriesGuidePreferences.THEME)
.build()
signInWithFirebase.launch(intent)
}
private fun signOut() {
if (HexagonSettings.shouldValidateAccount(requireContext())) {
// Account needs to be repaired, so can't sign out, just disable Cloud
hexagonTools.removeAccountAndSetDisabled()
updateViews()
} else {
setProgressVisible(true)
AuthUI.getInstance().signOut(requireContext()).addOnCompleteListener {
Timber.i("Signed out.")
signInAccount = null
hexagonTools.removeAccountAndSetDisabled()
if ([email protected]) {
setProgressVisible(false)
updateViews()
}
}
}
}
private fun updateViews() {
if (HexagonSettings.isEnabled(requireContext())) {
// hexagon enabled...
binding?.textViewCloudUser?.text = HexagonSettings.getAccountName(requireContext())
if (HexagonSettings.shouldValidateAccount(requireContext())) {
// ...but account needs to be repaired
binding?.textViewCloudDescription?.setText(R.string.hexagon_signed_out)
setButtonsVisible(
signInVisible = true,
signOutVisible = true,
removeVisible = false
)
} else {
// ...and account is fine
binding?.textViewCloudDescription?.setText(R.string.hexagon_description)
setButtonsVisible(
signInVisible = false,
signOutVisible = true,
removeVisible = true
)
}
} else {
// did try to setup, but failed?
if (!HexagonSettings.hasCompletedSetup(requireContext())) {
// show error message
binding?.textViewCloudDescription?.setText(R.string.hexagon_setup_incomplete)
} else {
binding?.textViewCloudDescription?.setText(R.string.hexagon_description)
}
binding?.textViewCloudUser?.text = null
setButtonsVisible(
signInVisible = true,
signOutVisible = false,
removeVisible = false
)
}
}
private fun setButtonsVisible(
signInVisible: Boolean,
signOutVisible: Boolean,
removeVisible: Boolean
) {
binding?.apply {
buttonCloudSignIn.isGone = !signInVisible
buttonCloudSignOut.isGone = !signOutVisible
buttonCloudRemoveAccount.isGone = !removeVisible
}
}
/**
* Disables buttons and shows a progress bar.
*/
private fun setProgressVisible(isVisible: Boolean) {
binding?.apply {
progressBarCloudAccount.visibility = if (isVisible) View.VISIBLE else View.GONE
buttonCloudSignIn.isEnabled = !isVisible
buttonCloudSignOut.isEnabled = !isVisible
buttonCloudRemoveAccount.isEnabled = !isVisible
}
}
private fun showSnackbar(message: CharSequence) {
dismissSnackbar()
snackbar = Snackbar.make(requireView(), message, Snackbar.LENGTH_INDEFINITE).also {
it.show()
}
}
private fun dismissSnackbar() {
snackbar?.dismiss()
}
private fun startHexagonSetup() {
dismissSnackbar()
setProgressVisible(true)
val signInAccountOrNull = signInAccount
if (signInAccountOrNull == null) {
signIn()
} else {
Timber.i("Setting up Hexagon...")
// set setup incomplete flag
HexagonSettings.setSetupIncomplete(requireContext())
// validate account data
if (signInAccountOrNull.email.isNullOrEmpty()) {
Timber.d("Setting up Hexagon...FAILURE_AUTH")
// show setup incomplete message + error toast
view?.let {
Snackbar.make(it, R.string.hexagon_setup_fail_auth, Snackbar.LENGTH_LONG)
.show()
}
} else if (hexagonTools.setAccountAndEnabled(signInAccountOrNull)) {
// schedule full sync
Timber.d("Setting up Hexagon...SUCCESS_SYNC_REQUIRED")
SgSyncAdapter.requestSyncFullImmediate(requireContext(), false)
HexagonSettings.setSetupCompleted(requireContext())
} else {
// Do not set completed, will show setup incomplete message.
Timber.d("Setting up Hexagon...FAILURE")
}
setProgressVisible(false)
updateViews()
}
}
companion object {
private const val ACTION_SIGN_IN = "sign-in"
}
}
| apache-2.0 |
jayrave/falkon | falkon-dao/src/main/kotlin/com/jayrave/falkon/dao/query/lenient/QueryBuilderExtn.kt | 1 | 782 | package com.jayrave.falkon.dao.query.lenient
import com.jayrave.falkon.mapper.ReadOnlyColumnOfTable
import java.sql.SQLException
/**
* A convenience function to select multiple columns in one go
*
* @param [columns] to be selected
* @param [aliaser] used to compute the alias to be used for the selected columns
*
* @throws [SQLException] if [columns] is empty
*/
fun <Z : AdderOrEnder<Z>> AdderOrEnder<Z>.select(
columns: Iterable<ReadOnlyColumnOfTable<*, *>>,
aliaser: ((ReadOnlyColumnOfTable<*, *>) -> String)? = null): Z {
var result: Z? = null
columns.forEach { column ->
result = select(column, aliaser?.invoke(column))
}
if (result == null) {
throw SQLException("Columns can't be empty")
}
return result!!
} | apache-2.0 |
rostyslav-y/android-clean-architecture-boilerplate | data/src/main/java/org/buffer/android/boilerplate/data/model/BufferooEntity.kt | 1 | 225 | package org.buffer.android.boilerplate.data.model
/**
* Representation for a [BufferooEntity] fetched from an external layer data source
*/
data class BufferooEntity(val name: String, val title: String, val avatar: String) | mit |
INRIX-Iurii-Okhmat/SCDAssist | Android/wear/src/main/java/com/iuriio/apps/scdassist/MainActivity.kt | 1 | 579 | package com.iuriio.apps.scdassist
import android.app.Activity
import android.os.Bundle
import android.support.wearable.view.WatchViewStub
import android.widget.TextView
class MainActivity : Activity() {
private var text: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.setContentView(R.layout.activity_main)
val stub = findViewById(R.id.watch_view_stub) as WatchViewStub
stub.setOnLayoutInflatedListener { stub -> text = stub.findViewById(R.id.text) as TextView }
}
}
| gpl-2.0 |
AdamLuisSean/Picasa-Gallery-Android | app/src/main/kotlin/io/shtanko/picasagallery/ui/photo/PhotosAdapterDelegateImpl.kt | 1 | 1295 | /*
* Copyright 2017 Alexey Shtanko
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.shtanko.picasagallery.ui.photo
import android.support.v7.widget.RecyclerView.ViewHolder
import android.view.ViewGroup
import io.shtanko.picasagallery.R
import io.shtanko.picasagallery.extensions.inflate
import io.shtanko.picasagallery.ui.delegate.ViewType
import io.shtanko.picasagallery.ui.delegate.ViewTypeAdapterDelegate
class PhotosAdapterDelegateImpl : ViewTypeAdapterDelegate {
override fun onCreateViewHolder(parent: ViewGroup?): ViewHolder {
val view = parent?.inflate(R.layout.album_item)
return PhotosViewHolder(view)
}
override fun onBindViewHolder(
holder: ViewHolder,
item: ViewType
) {
holder as PhotosViewHolder
holder.bind(item)
}
} | apache-2.0 |
duftler/orca | orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/metrics/MetricsTagHelper.kt | 1 | 2059 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.metrics
import com.netflix.spectator.api.BasicTag
import com.netflix.spinnaker.orca.ExecutionStatus
import com.netflix.spinnaker.orca.clouddriver.utils.CloudProviderAware
import com.netflix.spinnaker.orca.pipeline.model.Stage
class MetricsTagHelper : CloudProviderAware {
companion object {
private val helper = MetricsTagHelper()
fun commonTags(stage: Stage, taskModel: com.netflix.spinnaker.orca.pipeline.model.Task, status: ExecutionStatus): Iterable<BasicTag> =
arrayListOf(
BasicTag("status", status.toString()),
BasicTag("executionType", stage.execution.type.name.capitalize()),
BasicTag("isComplete", status.isComplete.toString()),
BasicTag("cloudProvider", helper.getCloudProvider(stage).valueOrNa())
)
fun detailedTaskTags(stage: Stage, taskModel: com.netflix.spinnaker.orca.pipeline.model.Task, status: ExecutionStatus): Iterable<BasicTag> =
arrayListOf(
BasicTag("taskType", taskModel.implementingClass),
BasicTag("account", helper.getCredentials(stage).valueOrNa()),
// sorting regions to reduce the metrics cardinality
BasicTag("region", helper.getRegions(stage).let {
if (it.isEmpty()) { "n_a" } else { it.sorted().joinToString(",") }
}))
private fun String?.valueOrNa(): String {
return if (this == null || isBlank()) {
"n_a"
} else {
this
}
}
}
}
| apache-2.0 |
summerlly/Quiet | app/src/main/java/tech/summerly/quiet/data/netease/result/MvDetailResultBean.kt | 1 | 2262 | package tech.summerly.quiet.data.netease.result
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
/**
* author : SUMMERLY
* e-mail : [email protected]
* time : 2017/9/8
* desc :
*/
class MvDetailResultBean(
@SerializedName("data")
@Expose
val data: Data? = null,
@SerializedName("code")
@Expose
val code: Int
) {
data class Brs(
@SerializedName("1080")
@Expose
val _1080: String? = null,
@SerializedName("720")
@Expose
val _720: String? = null,
@SerializedName("480")
@Expose
val _480: String? = null,
@SerializedName("240")
@Expose
val _240: String? = null
)
data class Data(
@SerializedName("id")
@Expose
val id: Long,
@SerializedName("title")
@Expose
val name: String? = null,
@SerializedName("artistId")
@Expose
val artistId: Long? = null,
@SerializedName("artistName")
@Expose
val artistName: String? = null,
@SerializedName("cover")
@Expose
val cover: String? = null,
@SerializedName("playCount")
@Expose
val playCount: Long? = null,
@SerializedName("subCount")
@Expose
val subCount: Long? = null,
@SerializedName("shareCount")
@Expose
val shareCount: Long? = null,
@SerializedName("likeCount")
@Expose
val likeCount: Long? = null,
@SerializedName("commentCount")
@Expose
val commentCount: Long? = null,
@SerializedName("duration")
@Expose
val duration: Long,
@SerializedName("publishTime")
@Expose
val publishTime: String? = null,
@SerializedName("brs")
@Expose
val brs: Brs? = null,
@SerializedName("commentThreadId")
@Expose
val commentThreadId: String? = null
)
} | gpl-2.0 |
RP-Kit/RPKit | bukkit/rpk-block-log-lib-bukkit/src/main/kotlin/com/rpkit/blocklog/bukkit/block/RPKBlockChange.kt | 1 | 1174 | /*
* Copyright 2021 Ren Binden
* 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.rpkit.blocklog.bukkit.block
import com.rpkit.characters.bukkit.character.RPKCharacter
import com.rpkit.players.bukkit.profile.RPKProfile
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfile
import org.bukkit.Material
import java.time.LocalDateTime
interface RPKBlockChange {
var id: RPKBlockChangeId?
val blockHistory: RPKBlockHistory
val time: LocalDateTime
val profile: RPKProfile?
val minecraftProfile: RPKMinecraftProfile?
val character: RPKCharacter?
val from: Material
val to: Material
val reason: String
} | apache-2.0 |
RP-Kit/RPKit | bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/irc/command/IRCRegisterCommand.kt | 1 | 1984 | /*
* Copyright 2021 Ren Binden
* 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.rpkit.chat.bukkit.irc.command
import com.rpkit.chat.bukkit.RPKChatBukkit
import com.rpkit.chat.bukkit.irc.RPKIRCService
import com.rpkit.core.service.Services
import com.rpkit.players.bukkit.profile.irc.RPKIRCNick
import org.pircbotx.Channel
import org.pircbotx.User
/**
* IRC register command.
* Registers the IRC bot with NickServ on the server using the password given in the config, and the e-mail specified.
*/
class IRCRegisterCommand(private val plugin: RPKChatBukkit) : IRCCommand("register") {
override fun execute(channel: Channel, sender: User, cmd: IRCCommand, label: String, args: Array<String>) {
val ircService = Services[RPKIRCService::class.java]
if (ircService == null) {
sender.send().message(plugin.messages["irc-no-irc-service"])
return
}
if (args.isEmpty()) {
sender.send().message(plugin.messages["irc-register-invalid-email-not-specified"])
return
}
if (!args[0].matches(Regex("(\\w[-._\\w]*\\w@\\w[-._\\w]*\\w\\.\\w{2,3})"))) {
sender.send().message(plugin.messages["irc-register-invalid-email-invalid"])
return
}
ircService.sendMessage(RPKIRCNick("NickServ"), "REGISTER " + plugin.config.getString("irc.password") + " " + args[0])
sender.send().message(plugin.messages["irc-register-valid"])
}
} | apache-2.0 |
commons-app/apps-android-commons | app/src/test/kotlin/fr/free/nrw/commons/customselector/ui/adapter/ImageAdapterTest.kt | 2 | 7443 | package fr.free.nrw.commons.customselector.ui.adapter
import android.content.ContentResolver
import android.content.Context
import android.content.SharedPreferences
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.widget.GridLayout
import com.nhaarman.mockitokotlin2.whenever
import fr.free.nrw.commons.R
import fr.free.nrw.commons.TestCommonsApplication
import fr.free.nrw.commons.customselector.listeners.ImageSelectListener
import fr.free.nrw.commons.customselector.model.Image
import fr.free.nrw.commons.customselector.ui.selector.CustomSelectorActivity
import fr.free.nrw.commons.customselector.ui.selector.ImageLoader
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.jupiter.api.Assertions
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.MockitoAnnotations
import org.powermock.reflect.Whitebox
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.lang.reflect.Field
import java.util.*
import kotlin.collections.ArrayList
/**
* Custom Selector image adapter test.
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [21], application = TestCommonsApplication::class)
@ExperimentalCoroutinesApi
class ImageAdapterTest {
@Mock
private lateinit var imageLoader: ImageLoader
@Mock
private lateinit var imageSelectListener: ImageSelectListener
@Mock
private lateinit var context: Context
@Mock
private lateinit var mockContentResolver: ContentResolver
@Mock
private lateinit var sharedPreferences: SharedPreferences
private lateinit var activity: CustomSelectorActivity
private lateinit var imageAdapter: ImageAdapter
private lateinit var images : ArrayList<Image>
private lateinit var holder: ImageAdapter.ImageViewHolder
private lateinit var selectedImageField: Field
private var uri: Uri = Mockito.mock(Uri::class.java)
private lateinit var image: Image
private val testDispatcher = TestCoroutineDispatcher()
/**
* Set up variables.
*/
@Before
@Throws(Exception::class)
fun setUp() {
MockitoAnnotations.initMocks(this)
Dispatchers.setMain(testDispatcher)
activity = Robolectric.buildActivity(CustomSelectorActivity::class.java).get()
imageAdapter = ImageAdapter(activity, imageSelectListener, imageLoader)
image = Image(1, "image", uri, "abc/abc", 1, "bucket1")
images = ArrayList()
val inflater = activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val listItemView: View = inflater.inflate(R.layout.item_custom_selector_image, null, false)
holder = ImageAdapter.ImageViewHolder(listItemView)
selectedImageField = imageAdapter.javaClass.getDeclaredField("selectedImages")
selectedImageField.isAccessible = true
}
@After
fun tearDown() {
Dispatchers.resetMain()
testDispatcher.cleanupTestCoroutines()
}
/**
* Test on create view holder.
*/
@Test
fun onCreateViewHolder() {
imageAdapter.createViewHolder(GridLayout(activity), 0)
}
/**
* Test on bind view holder.
*/
@Test
fun onBindViewHolder() {
whenever(context.contentResolver).thenReturn(mockContentResolver)
whenever(mockContentResolver.getType(uri)).thenReturn("jpg")
Whitebox.setInternalState(imageAdapter, "context", context)
// Parameters.
images.add(image)
imageAdapter.init(images, images, TreeMap())
whenever(context.getSharedPreferences("custom_selector", 0))
.thenReturn(sharedPreferences)
// Test conditions.
imageAdapter.onBindViewHolder(holder, 0)
selectedImageField.set(imageAdapter, images)
imageAdapter.onBindViewHolder(holder, 0)
}
/**
* Test processThumbnailForActionedImage
*/
@Test
fun processThumbnailForActionedImage() = runBlocking {
Whitebox.setInternalState(imageAdapter, "allImages", listOf(image))
whenever(imageLoader.nextActionableImage(listOf(image), Dispatchers.IO, Dispatchers.Default,
0)).thenReturn(0)
imageAdapter.processThumbnailForActionedImage(holder, 0)
}
/**
* Test processThumbnailForActionedImage
*/
@Test
fun `processThumbnailForActionedImage when reached end of the folder`() = runBlocking {
whenever(imageLoader.nextActionableImage(ArrayList(), Dispatchers.IO, Dispatchers.Default,
0)).thenReturn(-1)
imageAdapter.processThumbnailForActionedImage(holder, 0)
}
/**
* Test init.
*/
@Test
fun init() {
imageAdapter.init(images, images, TreeMap())
}
/**
* Test private function select or remove image.
*/
@Test
fun selectOrRemoveImage() {
// Access function
val func = imageAdapter.javaClass.getDeclaredMethod("selectOrRemoveImage", ImageAdapter.ImageViewHolder::class.java, Int::class.java)
func.isAccessible = true
// Parameters
images.addAll(listOf(image, image))
imageAdapter.init(images, images, TreeMap())
// Test conditions
holder.itemUploaded()
func.invoke(imageAdapter, holder, 0)
holder.itemNotUploaded()
holder.itemNotForUpload()
func.invoke(imageAdapter, holder, 0)
holder.itemNotForUpload()
func.invoke(imageAdapter, holder, 0)
selectedImageField.set(imageAdapter, images)
func.invoke(imageAdapter, holder, 1)
}
/**
* Test private function onThumbnailClicked.
*/
@Test
fun onThumbnailClicked() {
images.add(image)
Whitebox.setInternalState(imageAdapter, "images", images)
// Access function
val func = imageAdapter.javaClass.getDeclaredMethod(
"onThumbnailClicked",
Int::class.java,
ImageAdapter.ImageViewHolder::class.java
)
func.isAccessible = true
func.invoke(imageAdapter, 0, holder)
}
/**
* Test get item count.
*/
@Test
fun getItemCount() {
Assertions.assertEquals(0, imageAdapter.itemCount)
}
/**
* Test setSelectedImages.
*/
@Test
fun setSelectedImages() {
images.add(image)
imageAdapter.setSelectedImages(images)
}
/**
* Test refresh.
*/
@Test
fun refresh() {
imageAdapter.refresh(listOf(image), listOf(image))
}
/**
* Test getSectionName.
*/
@Test
fun getSectionName() {
images.add(image)
Whitebox.setInternalState(imageAdapter, "images", images)
Assertions.assertEquals("", imageAdapter.getSectionName(0))
}
/**
* Test cleanUp.
*/
@Test
fun cleanUp() {
imageAdapter.cleanUp()
}
/**
* Test getImageId
*/
@Test
fun getImageIdAt() {
imageAdapter.init(listOf(image), listOf(image), TreeMap())
Assertions.assertEquals(1, imageAdapter.getImageIdAt(0))
}
} | apache-2.0 |
Naliwe/IntelliJ_WowAddOnSupport | src/org/squarecell/utils/LocaleStrings.kt | 1 | 677 | package org.squarecell.utils
import java.util.*
object LocaleStrings {
private val bundle = ResourceBundle.getBundle("strings")
val WOW_ADDON_CONFIG_PANEL_HEADER_TEXT = bundle.getString("Ui.WowAddOnConfigHeaderText")!!
val WOW_VERSION_COMBOBOX_LABEL = bundle.getString("Ui.WowVersionComboBoxLabel")!!
val WOW_ADDON_TITLE_FIELD_LABEL = bundle.getString("Ui.WowAddOnTitleFieldLabel")!!
val WOW_ADDON_VERSION_FIELD_LABEL = bundle.getString("Ui.WowAddOnVersionFieldLabel")!!
val WOW_ADDON_AUTHOR_FIELD_LABEL = bundle.getString("Ui.WowAddOnAuthorFieldLabel")!!
val WOW_ADDON_MAIN_FILE_NAME_LABEL = bundle.getString("Ui.WowAddOnMainFileNameLabel")!!
}
| mit |
cketti/k-9 | app/core/src/main/java/com/fsck/k9/LocalKeyStoreManager.kt | 1 | 2230 | package com.fsck.k9
import com.fsck.k9.mail.MailServerDirection
import com.fsck.k9.mail.ssl.LocalKeyStore
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
class LocalKeyStoreManager(
private val localKeyStore: LocalKeyStore
) {
/**
* Add a new certificate for the incoming or outgoing server to the local key store.
*/
@Throws(CertificateException::class)
fun addCertificate(account: Account, direction: MailServerDirection, certificate: X509Certificate) {
val serverSettings = if (direction === MailServerDirection.INCOMING) {
account.incomingServerSettings
} else {
account.outgoingServerSettings
}
localKeyStore.addCertificate(serverSettings.host!!, serverSettings.port, certificate)
}
/**
* Examine the existing settings for an account. If the old host/port is different from the
* new host/port, then try and delete any (possibly non-existent) certificate stored for the
* old host/port.
*/
fun deleteCertificate(account: Account, newHost: String, newPort: Int, direction: MailServerDirection) {
val serverSettings = if (direction === MailServerDirection.INCOMING) {
account.incomingServerSettings
} else {
account.outgoingServerSettings
}
val oldHost = serverSettings.host!!
val oldPort = serverSettings.port
if (oldPort == -1) {
// This occurs when a new account is created
return
}
if (newHost != oldHost || newPort != oldPort) {
localKeyStore.deleteCertificate(oldHost, oldPort)
}
}
/**
* Examine the settings for the account and attempt to delete (possibly non-existent)
* certificates for the incoming and outgoing servers.
*/
fun deleteCertificates(account: Account) {
account.incomingServerSettings.let { serverSettings ->
localKeyStore.deleteCertificate(serverSettings.host!!, serverSettings.port)
}
account.outgoingServerSettings.let { serverSettings ->
localKeyStore.deleteCertificate(serverSettings.host!!, serverSettings.port)
}
}
}
| apache-2.0 |
androidx/constraintlayout | projects/ComposeConstraintLayout/macrobenchmark-app/src/main/java/com/example/macrobenchmark/newmessage/NewMessageState.kt | 2 | 1565 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.macrobenchmark.newmessage
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
@Suppress("NOTHING_TO_INLINE")
@Composable
internal inline fun rememberNewMessageState(
key: Any = Unit,
initialLayoutState: NewMessageLayout
): NewMessageState {
return remember(key) { NewMessageState(initialLayoutState) }
}
internal class NewMessageState(initialLayoutState: NewMessageLayout) {
private var _currentState = mutableStateOf(initialLayoutState)
val currentState: NewMessageLayout
get() = _currentState.value
fun setToFull() {
_currentState.value = NewMessageLayout.Full
}
fun setToMini() {
_currentState.value = NewMessageLayout.Mini
}
fun setToFab() {
_currentState.value = NewMessageLayout.Fab
}
}
internal enum class NewMessageLayout {
Full,
Mini,
Fab
} | apache-2.0 |
kittinunf/ReactiveAndroid | reactiveandroid-ui/src/androidTest/kotlin/com/github/kittinunf/reactiveandroid/widget/RadioGroupEventTest.kt | 1 | 1806 | package com.github.kittinunf.reactiveandroid.widget
import android.support.test.InstrumentationRegistry
import android.support.test.annotation.UiThreadTest
import android.support.test.rule.UiThreadTestRule
import android.support.test.runner.AndroidJUnit4
import android.widget.RadioButton
import android.widget.RadioGroup
import io.reactivex.observers.TestObserver
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class RadioGroupEventTest {
@Rule
@JvmField
val uiThreadTestRule = UiThreadTestRule()
private val context = InstrumentationRegistry.getContext()
private val view = RadioGroup(context)
@Test
@UiThreadTest
fun testCheckedChange() {
val radio1 = RadioButton(context)
radio1.id = 1001
val radio2 = RadioButton(context)
radio2.id = 1002
val radio3 = RadioButton(context)
radio3.id = 1003
view.addView(radio1)
view.addView(radio2)
view.addView(radio3)
val t = TestObserver<RadioGroupCheckedChangeListener>()
val s = view.rx_checkedChange().subscribeWith(t)
t.assertNoValues()
t.assertNoErrors()
view.check(1003)
val first = t.values()[0]
assertThat(first.checkedId, equalTo(1003))
t.assertValueCount(2)
view.check(1002)
val second = t.values()[3]
assertThat(second.checkedId, equalTo(1002))
t.assertValueCount(5)
view.check(1001)
val third = t.values()[6]
assertThat(third.checkedId, equalTo(1001))
t.assertValueCount(8)
s.dispose()
view.check(1003)
t.assertValueCount(8)
}
}
| mit |
android/user-interface-samples | CanonicalLayouts/supporting-panel-compose/app/src/main/java/com/example/supportingpanelcompose/ui/theme/Color.kt | 1 | 916 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.supportingpanelcompose.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | apache-2.0 |
weisterjie/FamilyLedger | app/src/main/java/ycj/com/familyledger/impl/IGetLedgerList.kt | 1 | 299 | package ycj.com.familyledger.impl
import ycj.com.familyledger.bean.LedgerBean
import ycj.com.familyledger.bean.PageResult
/**
* @author: ycj
* @date: 2017-06-22 18:01
* @version V1.0 <>
*/
interface IGetLedgerList {
fun onSuccess(data: PageResult<LedgerBean>)
fun onFail(msg: String)
} | apache-2.0 |
luxons/seven-wonders | sw-engine/src/main/kotlin/org/luxons/sevenwonders/engine/converters/Cards.kt | 1 | 1138 | package org.luxons.sevenwonders.engine.converters
import org.luxons.sevenwonders.engine.Player
import org.luxons.sevenwonders.engine.cards.Card
import org.luxons.sevenwonders.engine.moves.Move
import org.luxons.sevenwonders.model.cards.HandCard
import org.luxons.sevenwonders.model.cards.TableCard
internal fun Card.toTableCard(lastMove: Move? = null): TableCard = TableCard(
name = name,
color = color,
requirements = requirements.toApiRequirements(),
chainParent = chainParent,
chainChildren = chainChildren,
image = image,
back = back,
playedDuringLastMove = lastMove != null && this.name == lastMove.card.name,
)
internal fun List<Card>.toHandCards(player: Player, forceSpecialFree: Boolean) =
map { it.toHandCard(player, forceSpecialFree) }
private fun Card.toHandCard(player: Player, forceSpecialFree: Boolean): HandCard = HandCard(
name = name,
color = color,
requirements = requirements.toApiRequirements(),
chainParent = chainParent,
chainChildren = chainChildren,
image = image,
back = back,
playability = computePlayabilityBy(player, forceSpecialFree),
)
| mit |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/utils/declarations/HelpCommand.kt | 1 | 892 | package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.declarations
import net.perfectdreams.loritta.common.locale.LanguageManager
import net.perfectdreams.loritta.i18n.I18nKeysData
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandDeclarationWrapper
import net.perfectdreams.loritta.common.commands.CommandCategory
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.HelpExecutor
class HelpCommand(languageManager: LanguageManager) : CinnamonSlashCommandDeclarationWrapper(languageManager) {
companion object {
val I18N_PREFIX = I18nKeysData.Commands.Command.Help
}
override fun declaration() = slashCommand(I18N_PREFIX.Label, CommandCategory.UTILS, I18N_PREFIX.Description) {
executor = { HelpExecutor(it) }
}
} | agpl-3.0 |
InnoFang/DesignPatterns | src/io/innofang/singleton/example/kotlin/ThreadSafeDoubleCheckSingleton.kt | 1 | 746 | package io.innofang.singleton.example.kotlin
/**
* Created by Inno Fang on 2017/8/12.
*/
class ThreadSafeDoubleCheckSingleton {
companion object {
// implement 1
val instance1 by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
ThreadSafeDoubleCheckSingleton()
}
// implement 2
@Volatile private var instance2: ThreadSafeDoubleCheckSingleton? = null
fun get(): ThreadSafeDoubleCheckSingleton {
if (null == instance2) {
synchronized(this) {
if (null == instance2) {
instance2 = ThreadSafeDoubleCheckSingleton()
}
}
}
return instance2!!
}
}
} | gpl-3.0 |
MaibornWolff/codecharta | analysis/import/SVNLogParser/src/main/kotlin/de/maibornwolff/codecharta/importer/svnlogparser/input/metrics/AbsoluteCoupledChurn.kt | 1 | 1070 | package de.maibornwolff.codecharta.importer.svnlogparser.input.metrics
import de.maibornwolff.codecharta.importer.svnlogparser.input.Commit
import de.maibornwolff.codecharta.importer.svnlogparser.input.Modification
class AbsoluteCoupledChurn : Metric {
private var totalChurn: Long = 0
private var ownChurn: Long = 0
override fun description(): String {
return "Absolute Coupled Churn: Total number of lines changed in all other files when this file was commited."
}
override fun metricName(): String {
return "abs_coupled_churn"
}
override fun value(): Number {
return totalChurn - ownChurn
}
override fun registerCommit(commit: Commit) {
val commitsTotalChurn = commit.modifications
.map { it.additions + it.deletions }
.sum()
if (commitsTotalChurn > 0) {
totalChurn += commitsTotalChurn
}
}
override fun registerModification(modification: Modification) {
ownChurn += modification.additions + modification.deletions
}
}
| bsd-3-clause |
cloverrose/KlickModel | src/main/kotlin/com/github/cloverrose/klickmodel/parsers/Parser.kt | 1 | 226 | package com.github.cloverrose.klickmodel.parsers
import com.github.cloverrose.klickmodel.domain.SearchSession
abstract class Parser {
abstract fun parse(sessionsFilename: String, sessionsMax: Int): List<SearchSession>
}
| gpl-3.0 |
SerenityEnterprises/SerenityCE | src/main/java/host/serenity/serenity/api/module/ModuleCategory.kt | 1 | 403 | package host.serenity.serenity.api.module
enum class ModuleCategory(val humanizedName: String, val displayInGui: Boolean) {
COMBAT("Combat", true),
MINIGAMES("Minigames", true),
MISCELLANEOUS("Miscellaneous", true),
MOVEMENT("Movement", true),
OVERLAY("Overlay", false),
PLAYER("Player", true),
RENDER("Render", true),
TWEAKS("Tweaks", false),
WORLD("World", true)
} | gpl-3.0 |
jtc42/unicornpi-android | app/src/main/java/com/joeltcollins/unicornpi/ItemOneFragment.kt | 1 | 12144 | /*
* Copyright (c) 2017. Truiton (http://www.truiton.com/).
*
* 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.
*
* Contributors:
* Mohit Gupt (https://github.com/mohitgupt)
*
*/
package com.joeltcollins.unicornpi
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.SeekBar
import org.json.JSONException
import org.json.JSONObject
import org.json.JSONTokener
import kotlinx.coroutines.*
import kotlinx.android.synthetic.main.fragment_item_one.*
class ItemOneFragment : Fragment() {
// While creating view
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Get current view
return inflater.inflate(R.layout.fragment_item_one, container, false)
}
// Once view has been inflated/created
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// Grab resources from XML
val fadeStatusActive: String = getString(R.string.fade_status_active)
val fadeStatusInactive: String = getString(R.string.fade_status_inactive)
val statusInactive: Int = ContextCompat.getColor(context!!, R.color.label_inactive)
// BRIGHTNESS SEEK LISTENER & FUNCTIONS
brightness_seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
var progress = 0
override fun onProgressChanged(seekBar: SeekBar, progresValue: Int, fromUser: Boolean) {
progress = progresValue
brightness_text.text = "$progress"
if (fromUser) { // Blocks API call if UI is just updating (caused fades to stop on app load)
// OLD
// val params = mapOf("val" to progress.toString())
// retreiveAsync("brightness/set", params, false)
//NEW
val params = mapOf("global_brightness_val" to progress.toString())
retreiveAsync("state", params, false, method="POST")
}
if (fade_status.text.toString() == fadeStatusActive) {
fade_status.text = fadeStatusInactive
fade_status.setTextColor(statusInactive)
}
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {
val params = mapOf("global_brightness_val" to progress.toString())
retreiveAsync("state", params, false, method="POST")
}
})
// FADE START BUTTON LISTENER & FUNCTIONS
fade_start_button.setOnClickListener(object : View.OnClickListener {
//Get main activity
val activity: MainActivity = getActivity() as MainActivity
override fun onClick(view: View) {
activity.showSnack("Fade started")
val minutes = Integer.parseInt(fade_time!!.text.toString())
val target = fade_target_seekbar!!.progress / 100.toFloat()
val params = mapOf(
"special_fade_minutes" to minutes.toString(),
"special_fade_target" to target.toString(),
"special_fade_status" to "1"
)
retreiveAsync("state", params, false, method = "POST")
}
})
// FADE START BUTTON LISTENER & FUNCTIONS
fade_stop_button.setOnClickListener(object : View.OnClickListener {
//Get main activity
val activity: MainActivity = getActivity() as MainActivity
override fun onClick(view: View) {
activity.showSnack("Fade stopped")
val params = mapOf(
"special_fade_status" to "0"
)
retreiveAsync("state", params, false, method = "POST")
}
})
// ALARM TIME BUTTON LISTENER & FUNCTIONS
alarm_time_button.setOnClickListener(object : View.OnClickListener {
//Get main activity
val activity: MainActivity = getActivity() as MainActivity
override fun onClick(view: View) {
// Start timepicker fragment
// onTimeSet, and UI updating, is handled by AlarmTimeFragment
val newFragment = AlarmTimeFragment()
newFragment.show(activity.fragmentManager, "TimePicker")
}
})
// ALARM START BUTTON LISTENER & FUNCTIONS
alarm_start_button.setOnClickListener(object : View.OnClickListener {
//Get main activity
val activity: MainActivity = getActivity() as MainActivity
override fun onClick(view: View) {
activity.showSnack("Alarm set")
val lead = alarm_lead.text.toString()
val tail = alarm_tail.text.toString()
val time = alarm_time_text.text.toString()
val params = mapOf(
"special_alarm_lead" to lead,
"special_alarm_tail" to tail,
"special_alarm_time" to time,
"special_alarm_status" to "1"
)
retreiveAsync("state", params, false, method = "POST")
}
})
// ALARM START BUTTON LISTENER & FUNCTIONS
alarm_stop_button.setOnClickListener(object : View.OnClickListener {
//Get main activity
val activity: MainActivity = getActivity() as MainActivity
override fun onClick(view: View) {
activity.showSnack("Alarm unset")
val params = mapOf("special_alarm_status" to "0")
retreiveAsync("state", params, false, method = "POST")
}
})
// GET API RESPONSE FOR UI STARTUP
// Happens here because post-execute uses UI elements
retreiveAsync("state", mapOf(), true, redraw_all = true, method = "GET")
}
// Get and process HTTP response in a coroutine
private fun retreiveAsync(
api_arg: String,
params: Map<String, String>,
show_progress: Boolean,
redraw_all: Boolean = false,
method: String = "GET"){
val activity: MainActivity = activity as MainActivity
// Launch a new coroutine that executes in the Android UI thread
GlobalScope.launch(Dispatchers.Main){
// Start loader
if (show_progress) {activity.toggleLoader(true)}
// Suspend while data is obtained
val response = withContext(Dispatchers.Default) {
activity.suspendedGetFromURL(activity.apiBase+api_arg, params, method=method)
}
// Call function to handle response string, only if response not null
if (response != null) {
// If fragment layout is not null (ie. fragment still in view), handle response
if (frag_layout != null) {handleResponse(response, redraw_all=redraw_all)}
// Else log that handling has been aborted
else {Log.i("INFO", "Response processing aborted")}
// Stop loader
if (show_progress) {activity.toggleLoader(false)}
}
}
}
//HANDLE JSON RESPONSE
private fun handleResponse(responseObject: JSONObject, redraw_all: Boolean = false) {
var updateBrightnessSlider = false
//Grab resources from XML
val alarmStatusActive: String = getString(R.string.alarm_status_active)
val alarmStatusInactive: String = getString(R.string.alarm_status_inactive)
val fadeStatusActive: String = getString(R.string.fade_status_active)
val fadeStatusInactive: String = getString(R.string.fade_status_inactive)
val statusActive: Int = ContextCompat.getColor(context!!, R.color.label_active)
val statusInactive: Int = ContextCompat.getColor(context!!, R.color.label_inactive)
try {
// If global status is returned, route music have been status/all, so brightness slider should be updated
if (redraw_all) {
updateBrightnessSlider = true
}
if (responseObject.has("global_brightness_val")) {
val responseBrightnessVal = responseObject.getInt("global_brightness_val")
if (updateBrightnessSlider) {
brightness_seekbar.progress = responseBrightnessVal
}
}
if (responseObject.has("special_alarm_time")) {
val alarmTime = responseObject.getString("special_alarm_time")
val parts = alarmTime.split(":".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()
val currentHours = Integer.parseInt(parts[0])
val currentMins = Integer.parseInt(parts[1])
val formattedTime = String.format("%02d", currentHours) + ":" + String.format("%02d", currentMins)
alarm_time_text.text = formattedTime
}
if (responseObject.has("special_alarm_lead")) {
val responseAlarmLead = responseObject.getInt("special_alarm_lead")
alarm_lead!!.setText(responseAlarmLead.toString())
}
if (responseObject.has("special_alarm_tail")) {
val responseAlarmTail = responseObject.getInt("special_alarm_tail")
alarm_tail!!.setText(responseAlarmTail.toString())
}
if (responseObject.has("special_alarm_status")) {
val responseAlarmStatus = responseObject.getBoolean("special_alarm_status")
if (responseAlarmStatus) {
alarm_status.text = alarmStatusActive
alarm_status.setTextColor(statusActive)
} else {
alarm_status.text = alarmStatusInactive
alarm_status.setTextColor(statusInactive)
}
}
if (responseObject.has("special_fade_minutes")) {
val responseFadeMinutes = responseObject.getInt("special_fade_minutes")
fade_time!!.setText(responseFadeMinutes.toString())
}
if (responseObject.has("special_fade_target")) {
val responseFadeTarget = responseObject.getString("special_fade_target")
val fadePercent = Math.round(java.lang.Float.parseFloat(responseFadeTarget) * 100)
fade_target_seekbar!!.progress = fadePercent
}
if (responseObject.has("special_fade_status")) {
val responseAlarmStatus = responseObject.getBoolean("special_fade_status")
if (responseAlarmStatus) {
fade_status.text = fadeStatusActive
fade_status.setTextColor(statusActive)
} else {
fade_status.text = fadeStatusInactive
fade_status.setTextColor(statusInactive)
}
}
} catch (e: JSONException) {e.printStackTrace()}
}
companion object {
fun newInstance(): ItemOneFragment {
val fragmentHome = ItemOneFragment()
val args = Bundle()
fragmentHome.arguments = args
return fragmentHome
}
}
}
| apache-2.0 |
sampsonjoliver/Firestarter | app/src/main/java/com/sampsonjoliver/firestarter/views/channel/create/CreateChannelActivity.kt | 1 | 14409 | package com.sampsonjoliver.firestarter.views.channel.create
import android.app.Activity
import android.app.DatePickerDialog
import android.app.ProgressDialog
import android.app.TimePickerDialog
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.app.AlertDialog
import android.text.format.DateUtils
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import com.google.android.gms.common.GooglePlayServicesNotAvailableException
import com.google.android.gms.common.GooglePlayServicesRepairableException
import com.google.android.gms.location.places.ui.PlacePicker
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.ValueEventListener
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageMetadata
import com.sampsonjoliver.firestarter.FirebaseActivity
import com.sampsonjoliver.firestarter.R
import com.sampsonjoliver.firestarter.models.Session
import com.sampsonjoliver.firestarter.service.FirebaseService
import com.sampsonjoliver.firestarter.service.References
import com.sampsonjoliver.firestarter.service.SessionManager
import com.sampsonjoliver.firestarter.utils.*
import com.sampsonjoliver.firestarter.utils.IntentUtils.dispatchPickPhotoIntent
import com.sampsonjoliver.firestarter.utils.IntentUtils.dispatchTakePictureIntent
import com.sampsonjoliver.firestarter.views.dialogs.DatePickerDialogFragment
import com.sampsonjoliver.firestarter.views.dialogs.FormDialog
import com.sampsonjoliver.firestarter.views.dialogs.TimePickerDialogFragment
import kotlinx.android.synthetic.main.activity_create_channel.*
import java.io.ByteArrayOutputStream
import java.util.*
class CreateChannelActivity : FirebaseActivity() {
companion object {
val BUNDLE_TAG_TAG = "BUNDLE_TAG_TAG"
}
val calendarHolder = Calendar.getInstance()
var currentPhotoPath: String? = null
var photoUploadPending: Boolean = false
val session = Session().apply {
startDate = Date().time
username = SessionManager.getUsername()
userId = SessionManager.getUid()
}
var startDateSet = false
var endDateSet = false
val progressDialog by lazy { ProgressDialog(this) }
fun setStartTime(timeInMillis: Long) {
val currentDuration = session.durationMs
startDate.text = DateUtils.formatDateTime(this, timeInMillis, DateUtils.FORMAT_SHOW_DATE)
startTime.text = DateUtils.formatDateTime(this, timeInMillis, DateUtils.FORMAT_SHOW_TIME)
if (!endDateSet) {
setEndTime(timeInMillis + currentDuration)
endDateSet = false
} else {
session.durationMs = timeInMillis - session.endDate
}
session.startDate = timeInMillis
startDateSet = true
}
fun setEndTime(timeInMillis: Long) {
endDate.text = DateUtils.formatDateTime(this, timeInMillis, DateUtils.FORMAT_SHOW_DATE)
endTime.text = DateUtils.formatDateTime(this, timeInMillis, DateUtils.FORMAT_SHOW_TIME)
session.durationMs = timeInMillis - session.startDate
endDateSet = true
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_create_channel)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
setStartTime(Date().time)
setEndTime(session.startDate + 1000 * 60 * 60 * 2)
endDateSet = false
startDate.setOnClickListener {
calendarHolder.time = session.startDateAsDate
DatePickerDialogFragment.newInstance(
calendarHolder.get(Calendar.YEAR),
calendarHolder.get(Calendar.MONTH),
calendarHolder.get(Calendar.DAY_OF_MONTH))
.apply { listener = DatePickerDialog.OnDateSetListener { datePicker, year, month, day ->
calendarHolder.time = session.startDateAsDate
calendarHolder.set(Calendar.YEAR, year)
calendarHolder.set(Calendar.MONTH, month)
calendarHolder.set(Calendar.DAY_OF_MONTH, day)
setStartTime(calendarHolder.timeInMillis)
} }
.show(supportFragmentManager, DatePickerDialogFragment.TAG)
}
startTime.setOnClickListener {
calendarHolder.time = session.startDateAsDate
TimePickerDialogFragment.newInstance(
calendarHolder.get(Calendar.HOUR),
calendarHolder.get(Calendar.MINUTE))
.apply { listener = TimePickerDialog.OnTimeSetListener { timePicker, hour, minute ->
calendarHolder.time = session.startDateAsDate
calendarHolder.set(Calendar.HOUR_OF_DAY, hour)
calendarHolder.set(Calendar.MINUTE, minute)
setStartTime(calendarHolder.timeInMillis)
} }
.show(supportFragmentManager, TimePickerDialogFragment.TAG)
}
endDate.setOnClickListener {
calendarHolder.time = session.endDateAsDate
DatePickerDialogFragment.newInstance(
calendarHolder.get(Calendar.YEAR),
calendarHolder.get(Calendar.MONTH),
calendarHolder.get(Calendar.DAY_OF_MONTH),
session.startDateAsDate)
.apply { listener = DatePickerDialog.OnDateSetListener { datePicker, year, month, day ->
calendarHolder.time = session.endDateAsDate
calendarHolder.set(Calendar.YEAR, year)
calendarHolder.set(Calendar.MONTH, month)
calendarHolder.set(Calendar.DAY_OF_MONTH, day)
setEndTime(calendarHolder.timeInMillis)
} }
.show(supportFragmentManager, DatePickerDialogFragment.TAG)
endDateSet = true
}
endTime.setOnClickListener {
calendarHolder.time = session.endDateAsDate
TimePickerDialogFragment.newInstance(
calendarHolder.get(Calendar.HOUR),
calendarHolder.get(Calendar.MINUTE))
.apply { listener = TimePickerDialog.OnTimeSetListener { timePicker, hour, minute ->
calendarHolder.time = session.endDateAsDate
calendarHolder.set(Calendar.HOUR_OF_DAY, hour)
calendarHolder.set(Calendar.MINUTE, minute)
setEndTime(calendarHolder.timeInMillis)
} }
.show(supportFragmentManager, TimePickerDialogFragment.TAG)
}
location.setOnClickListener {
// Construct an intent for the place picker
try {
val intent = PlacePicker.IntentBuilder().build(this)
startActivityForResult(intent, IntentUtils.REQUEST_PLACE_PICKER)
} catch (e: GooglePlayServicesRepairableException) {
// ...
} catch (e: GooglePlayServicesNotAvailableException) {
// ...
}
}
addTag.setOnClickListener {
progressDialog.setMessage(getString(R.string.loading))
progressDialog.show()
FirebaseService.getReference(References.tags).addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError?) {
progressDialog.dismiss()
}
override fun onDataChange(p0: DataSnapshot?) {
progressDialog.dismiss()
val tags = p0?.children?.map { it.key }?.toTypedArray()
val selectedTags = tags?.map { Pair(it, session.tags[it] ?: false) }.orEmpty().toMap(mutableMapOf())
val checkedIndexes = selectedTags.values.toBooleanArray()
AlertDialog.Builder(this@CreateChannelActivity)
.setMultiChoiceItems(tags, checkedIndexes, { dialogInterface, i, b ->
selectedTags.set(tags?.get(i).orEmpty(), b)
})
.setPositiveButton(getString(R.string.save), { dialogInterface, i ->
session.tags = selectedTags
tagList.text = session.tags.entries.filter { it.value == true }.map { it.key }.joinToString()
})
.setNegativeButton(getString(R.string.cancel), null)
.show()
}
})
}
banner.setOnClickListener {
AlertDialog.Builder(this@CreateChannelActivity)
.setItems(arrayOf(getString(R.string.take_photo), getString(R.string.upload_photo)), { dialogInterface, index ->
if (index == 0) {
// Take photo
currentPhotoPath = dispatchTakePictureIntent(this)
} else if (index == 1) {
// Upload photo
dispatchPickPhotoIntent(this)
}
}).show()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
IntentUtils.REQUEST_PLACE_PICKER -> {
resultCode.whenEqual(Activity.RESULT_OK) {
// The user has selected a place. Extract the name and address.
val place = PlacePicker.getPlace(this, data)
val name = place.name
val address = place.address
session.address = address.toString()
session.setLocation(place.latLng)
location.text = address
}
}
IntentUtils.REQUEST_IMAGE_PICKER -> {
photoUploadPending = false
currentPhotoPath = null
resultCode.whenEqual(Activity.RESULT_OK) {
data?.data?.run {
photoUploadPending = true
currentPhotoPath = this.toString()
}
}
banner.setImageURI(currentPhotoPath ?: "")
}
IntentUtils.REQUEST_IMAGE_CAPTURE -> {
photoUploadPending = false
resultCode.whenEqual(Activity.RESULT_OK) {
Uri.parse(currentPhotoPath)?.run {
photoUploadPending = true
}
}
banner.setImageURI(currentPhotoPath)
}
else -> super.onActivityResult(requestCode, resultCode, data)
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_create_channel, menu)
return super.onCreateOptionsMenu(menu)
}
fun saveChannel() {
val progressDialog = ProgressDialog(this@CreateChannelActivity)
progressDialog.setMessage(getString(R.string.creating_channel))
progressDialog.show()
if (photoUploadPending) {
Uri.parse(currentPhotoPath)?.run {
progressDialog.setMessage(getString(R.string.uploading_image, 0f))
val thumb = BitmapUtils.decodeSampledBitmap(currentPhotoPath!!, 820, 312)
val bos = ByteArrayOutputStream()
thumb.compress(Bitmap.CompressFormat.PNG, 100, bos)
val thumbData = bos.toByteArray()
FirebaseStorage.getInstance().getReference("${References.Images}/banners/${this.lastPathSegment}")
.putBytes(thumbData, StorageMetadata.Builder()
.setContentType("image/jpg")
.setCustomMetadata("uid", SessionManager.getUid())
.build()
).addOnFailureListener {
Log.d(TAG, "Upload Failed: " + it.message)
progressDialog.dismiss()
}.addOnProgressListener {
Log.d(TAG, "Upload Progress: ${it.bytesTransferred} / ${it.totalByteCount}")
progressDialog.setMessage(getString(R.string.uploading_image, (it.bytesTransferred.toFloat() / it.totalByteCount.toFloat()) * 100f))
}.addOnSuccessListener { photoIt ->
progressDialog.setMessage(getString(R.string.creating_channel))
session.bannerUrl = photoIt.downloadUrl.toString()
FirebaseService.createSession(session,
{ finish() },
{ Snackbar.make(toolbar, R.string.create_session_save_error, Snackbar.LENGTH_LONG).show() }
)
}
}
} else {
FirebaseService.createSession(session,
{ finish() },
{ Snackbar.make(toolbar, R.string.create_session_save_error, Snackbar.LENGTH_LONG).show() }
)
}
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.menu_save -> {
if (validate()) {
saveChannel()
}
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
fun validate(): Boolean {
session.topic = topic.text.toString()
session.description = description.text.toString()
return session.topic.isNullOrBlank().not() &&
session.address.isNullOrBlank().not() &&
session.username.isNullOrBlank().not() &&
session.startDate > 0 &&
session.durationMs > 0
}
} | apache-2.0 |
jitsi/jitsi-videobridge | rtp/src/main/kotlin/org/jitsi/rtp/extensions/unsigned/Unsigned.kt | 1 | 2016 | /*
* 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.rtp.extensions.unsigned
import kotlin.experimental.and
/**
* Many times fields in packets are defined as unsigned. Since
* we don't have unsigned types (and attempts at using Kotlin's
* unsigned types have not proven to be very usable), we store
* those types as larger than they actually are ([Byte] and
* [Short] held as [Int] and [Int] held as [Long]). These
* helpers are to do the conversion correctly such that
* we get a properly 'unsigned' version of the parsed field.
* No helper is needed for the reverse operation (the use
* of toInt, toShort and toByte is sufficient).
*/
fun Byte.toPositiveInt(): Int = toInt() and 0xFF
fun Short.toPositiveInt(): Int = toInt() and 0xFFFF
fun Int.toPositiveLong(): Long = toLong() and 0xFFFFFFFF
// TODO: i think these should be able to make the above functions obsolete
fun Number.toPositiveShort(): Short {
return when (this) {
is Byte -> this.toShort() and 0xFF
else -> this.toShort()
}
}
fun Number.toPositiveInt(): Int {
return when (this) {
is Byte -> this.toInt() and 0xFF
is Short -> this.toInt() and 0xFFFF
else -> this.toInt()
}
}
fun Number.toPositiveLong(): Long {
return when (this) {
is Byte -> this.toLong() and 0xFF
is Short -> this.toLong() and 0xFFFF
is Int -> this.toLong() and 0xFFFFFFFF
else -> this.toLong()
}
}
| apache-2.0 |
nisrulz/android-examples | UsingTimberLogger/app/src/main/java/github/nisrulz/example/usingtimberlogger/ReleaseTree.kt | 1 | 647 | package github.nisrulz.example.usingtimberlogger
import android.util.Log
import timber.log.Timber
class ReleaseTree : Timber.Tree() {
override fun isLoggable(tag: String?, priority: Int): Boolean {
// Only log WARN, ERROR, WTF
return !(priority == Log.VERBOSE || priority == Log.DEBUG || priority == Log.INFO)
}
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
if (isLoggable(tag, priority)) {
// Report all caught exceptions to crashlytics
if (priority == Log.ERROR && t != null) {
// Crashlytics.log(t)
}
}
}
} | apache-2.0 |
HughG/partial-order | partial-order-app/src/main/kotlin/org/tameter/kotlin/js/jsobject.kt | 1 | 414 | package org.tameter.kotlin.js
/**
* Copyright (c) 2016 Hugh Greene ([email protected]).
*/
@Suppress("NOTHING_TO_INLINE")
inline fun <T> jsobject(): T = js("{ return {}; }").unsafeCast<T>()
@Suppress("NOTHING_TO_INLINE")
inline fun <T> jsobject(init: T.() -> Unit): T = jsobject<T>().apply(init)
@Suppress("NOTHING_TO_INLINE")
inline val Any.objectKeys: Array<String> get() = js("Object").keys(asDynamic()) | mit |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/misc/crafting/FurnaceCraftingProcess.kt | 2 | 1774 | package com.cout970.magneticraft.misc.crafting
import com.cout970.magneticraft.api.internal.ApiUtils
import com.cout970.magneticraft.misc.fromCelsiusToKelvin
import com.cout970.magneticraft.systems.tilemodules.ModuleInventory
import net.minecraft.item.ItemStack
import net.minecraft.item.crafting.FurnaceRecipes
/**
* Created by cout970 on 2017/07/01.
*/
class FurnaceCraftingProcess(
val invModule: ModuleInventory,
val inputSlot: Int,
val outputSlot: Int
) : ICraftingProcess, IHeatCraftingProcess {
private var cacheKey: ItemStack = ItemStack.EMPTY
private var cacheValue: ItemStack = ItemStack.EMPTY
private fun getInput() = invModule.inventory.extractItem(inputSlot, 1, true)
private fun getOutput(input: ItemStack): ItemStack {
if (ApiUtils.equalsIgnoreSize(cacheKey, input)) return cacheValue
val recipe = FurnaceRecipes.instance().getSmeltingResult(input)
cacheKey = input
cacheValue = recipe
return recipe
}
override fun craft() {
val input = invModule.inventory.extractItem(inputSlot, 1, false)
val output = FurnaceRecipes.instance().getSmeltingResult(input).copy()
invModule.inventory.insertItem(outputSlot, output, false)
}
override fun canCraft(): Boolean {
val input = getInput()
// check non empty and size >= 1
if (input.isEmpty) return false
//check recipe
val output = getOutput(input)
if (output.isEmpty) return false
//check inventory space
val insert = invModule.inventory.insertItem(outputSlot, output, true)
return insert.isEmpty
}
override fun duration(): Float = 100f
override fun minTemperature(): Float = 60.fromCelsiusToKelvin().toFloat()
} | gpl-2.0 |
cFerg/CloudStorming | ObjectAvoidance/kotlin/src/elite/gils/country/BB.kt | 1 | 499 | package elite.gils.country
/**
* Continent: (Name)
* Country: (Name)
*/
enum class BB private constructor(
//Leave the code below alone (unless optimizing)
private val name: String) {
//List of State/Province names (Use 2 Letter/Number Combination codes)
/**
* Name:
*/
AA("Example"),
/**
* Name:
*/
AB("Example"),
/**
* Name:
*/
AC("Example");
fun getName(state: BB): String {
return state.name
}
} | bsd-3-clause |
robinverduijn/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/NamedDomainObjectContainerExtensions.kt | 1 | 15405 | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.gradle.kotlin.dsl
import org.gradle.api.Action
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.NamedDomainObjectProvider
import org.gradle.api.PolymorphicDomainObjectContainer
import org.gradle.kotlin.dsl.support.delegates.NamedDomainObjectContainerDelegate
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
/**
* Allows the container to be configured via an augmented DSL.
*
* @param configuration The expression to configure this container with
* @return The container.
*/
inline operator fun <T : Any, C : NamedDomainObjectContainer<T>> C.invoke(
configuration: NamedDomainObjectContainerScope<T>.() -> Unit
): C =
apply {
configuration(NamedDomainObjectContainerScope.of(this))
}
/**
* Property delegate for registering new elements in the container.
*
* `tasks { val rebuild by registering }`
*
* @param T the domain object type
* @param C the concrete container type
*/
inline val <T : Any, C : NamedDomainObjectContainer<T>> C.registering: RegisteringDomainObjectDelegateProvider<out C>
get() = RegisteringDomainObjectDelegateProvider.of(this)
/**
* Property delegate for registering new elements in the container.
*
* ```kotlin
* tasks {
* val rebuild by registering {
* dependsOn("clean", "build")
* }
* }
* ```
*
* @param T the domain object type
* @param C the concrete container type
* @param action the configuration action
*/
fun <T : Any, C : NamedDomainObjectContainer<T>> C.registering(action: T.() -> Unit): RegisteringDomainObjectDelegateProviderWithAction<out C, T> =
RegisteringDomainObjectDelegateProviderWithAction.of(this, action)
/**
* Property delegate for registering new elements in the container.
*
* `tasks { val jar by registering(Jar::class) }`
*
* @param T the domain object type
* @param C the concrete container type
* @param type the domain object type
*/
fun <T : Any, C : PolymorphicDomainObjectContainer<T>, U : T> C.registering(type: KClass<U>): RegisteringDomainObjectDelegateProviderWithType<out C, U> =
RegisteringDomainObjectDelegateProviderWithType.of(this, type)
/**
* Property delegate for registering new elements in the container.
*
* `tasks { val jar by registering(Jar::class) { } }`
*
* @param T the container element type
* @param C the container type
* @param U the desired domain object type
* @param type the domain object type
* @param action the configuration action
*/
fun <T : Any, C : PolymorphicDomainObjectContainer<T>, U : T> C.registering(
type: KClass<U>,
action: U.() -> Unit
): RegisteringDomainObjectDelegateProviderWithTypeAndAction<out C, U> =
RegisteringDomainObjectDelegateProviderWithTypeAndAction.of(this, type, action)
/**
* Registers an element and provides a delegate with the resulting [NamedDomainObjectProvider].
*/
operator fun <T : Any, C : NamedDomainObjectContainer<T>> RegisteringDomainObjectDelegateProvider<C>.provideDelegate(
receiver: Any?,
property: KProperty<*>
) = ExistingDomainObjectDelegate.of(
delegateProvider.register(property.name)
)
/**
* Registers an element and provides a delegate with the resulting [NamedDomainObjectProvider].
*/
operator fun <T : Any, C : NamedDomainObjectContainer<T>> RegisteringDomainObjectDelegateProviderWithAction<C, T>.provideDelegate(
receiver: Any?,
property: KProperty<*>
) = ExistingDomainObjectDelegate.of(
delegateProvider.register(property.name, action)
)
/**
* Registers an element and provides a delegate with the resulting [NamedDomainObjectProvider].
*/
operator fun <T : Any, C : PolymorphicDomainObjectContainer<T>, U : T> RegisteringDomainObjectDelegateProviderWithType<C, U>.provideDelegate(
receiver: Any?,
property: KProperty<*>
) = ExistingDomainObjectDelegate.of(
delegateProvider.register(property.name, type.java)
)
/**
* Registers an element and provides a delegate with the resulting [NamedDomainObjectProvider].
*/
operator fun <T : Any, C : PolymorphicDomainObjectContainer<T>, U : T> RegisteringDomainObjectDelegateProviderWithTypeAndAction<C, U>.provideDelegate(
receiver: Any?,
property: KProperty<*>
) = ExistingDomainObjectDelegate.of(
delegateProvider.register(property.name, type.java, action)
)
/**
* Holds the delegate provider for the `registering` property delegate with
* the purpose of providing specialized implementations for the `provideDelegate` operator
* based on the static type of the provider.
*/
class RegisteringDomainObjectDelegateProvider<T>
private constructor(
internal val delegateProvider: T
) {
companion object {
fun <T> of(delegateProvider: T) =
RegisteringDomainObjectDelegateProvider(delegateProvider)
}
}
/**
* Holds the delegate provider for the `registering` property delegate with
* the purpose of providing specialized implementations for the `provideDelegate` operator
* based on the static type of the provider.
*/
class RegisteringDomainObjectDelegateProviderWithAction<C, T>
private constructor(
internal val delegateProvider: C,
internal val action: T.() -> Unit
) {
companion object {
fun <C, T> of(delegateProvider: C, action: T.() -> Unit) =
RegisteringDomainObjectDelegateProviderWithAction(delegateProvider, action)
}
}
/**
* Holds the delegate provider and expected element type for the `registering` property delegate with
* the purpose of providing specialized implementations for the `provideDelegate` operator
* based on the static type of the provider.
*/
class RegisteringDomainObjectDelegateProviderWithType<T, U : Any>
private constructor(
internal val delegateProvider: T,
internal val type: KClass<U>
) {
companion object {
fun <T, U : Any> of(delegateProvider: T, type: KClass<U>) =
RegisteringDomainObjectDelegateProviderWithType(delegateProvider, type)
}
}
/**
* Holds the delegate provider and expected element type for the `registering` property delegate with
* the purpose of providing specialized implementations for the `provideDelegate` operator
* based on the static type of the provider.
*/
class RegisteringDomainObjectDelegateProviderWithTypeAndAction<T, U : Any>
private constructor(
internal val delegateProvider: T,
internal val type: KClass<U>,
internal val action: U.() -> Unit
) {
companion object {
fun <T, U : Any> of(delegateProvider: T, type: KClass<U>, action: U.() -> Unit) =
RegisteringDomainObjectDelegateProviderWithTypeAndAction(delegateProvider, type, action)
}
}
/**
* Receiver for [NamedDomainObjectContainer] configuration blocks.
*/
class NamedDomainObjectContainerScope<T : Any>
private constructor(
override val delegate: NamedDomainObjectContainer<T>
) : NamedDomainObjectContainerDelegate<T>(), PolymorphicDomainObjectContainer<T> {
companion object {
fun <T : Any> of(container: NamedDomainObjectContainer<T>) =
NamedDomainObjectContainerScope(container)
}
override fun <U : T> register(name: String, type: Class<U>, configurationAction: Action<in U>): NamedDomainObjectProvider<U> =
polymorphicDomainObjectContainer().register(name, type, configurationAction)
override fun <U : T> register(name: String, type: Class<U>): NamedDomainObjectProvider<U> =
polymorphicDomainObjectContainer().register(name, type)
override fun <U : T> create(name: String, type: Class<U>): U =
polymorphicDomainObjectContainer().create(name, type)
override fun <U : T> create(name: String, type: Class<U>, configuration: Action<in U>): U =
polymorphicDomainObjectContainer().create(name, type, configuration)
override fun <U : T> maybeCreate(name: String, type: Class<U>): U =
polymorphicDomainObjectContainer().maybeCreate(name, type)
override fun <U : T> containerWithType(type: Class<U>): NamedDomainObjectContainer<U> =
polymorphicDomainObjectContainer().containerWithType(type)
/**
* Configures an object by name, without triggering its creation or configuration, failing if there is no such object.
*
* @see [NamedDomainObjectContainer.named]
* @see [NamedDomainObjectProvider.configure]
*/
operator fun String.invoke(configuration: T.() -> Unit): NamedDomainObjectProvider<T> =
this().apply { configure(configuration) }
/**
* Locates an object by name, without triggering its creation or configuration, failing if there is no such object.
*
* @see [NamedDomainObjectContainer.named]
*/
operator fun String.invoke(): NamedDomainObjectProvider<T> =
delegate.named(this)
/**
* Configures an object by name, without triggering its creation or configuration, failing if there is no such object.
*
* @see [PolymorphicDomainObjectContainer.named]
* @see [NamedDomainObjectProvider.configure]
*/
operator fun <U : T> String.invoke(type: KClass<U>, configuration: U.() -> Unit): NamedDomainObjectProvider<U> =
delegate.named(this, type, configuration)
/**
* Locates an object by name and type, without triggering its creation or configuration, failing if there is no such object.
*
* @see [PolymorphicDomainObjectContainer.named]
*/
operator fun <U : T> String.invoke(type: KClass<U>): NamedDomainObjectProvider<U> =
delegate.named(this, type)
/**
* Cast this to [PolymorphicDomainObjectContainer] or throw [IllegalArgumentException].
*
* We must rely on the dynamic cast and possible runtime failure here due to a Kotlin extension member limitation.
* Kotlin currently can't disambiguate between invoke operators with more specific receivers in a type hierarchy.
*
* See https://youtrack.jetbrains.com/issue/KT-15711
*/
private
fun polymorphicDomainObjectContainer() =
delegate as? PolymorphicDomainObjectContainer<T>
?: throw IllegalArgumentException("Container '$delegate' is not polymorphic.")
}
/**
* Provides a property delegate that creates elements of the default collection type.
*/
val <T : Any> NamedDomainObjectContainer<T>.creating
get() = NamedDomainObjectContainerCreatingDelegateProvider.of(this)
/**
* Provides a property delegate that creates elements of the default collection type with the given [configuration].
*
* `val myElement by myContainer.creating { myProperty = 42 }`
*/
fun <T : Any> NamedDomainObjectContainer<T>.creating(configuration: T.() -> Unit) =
NamedDomainObjectContainerCreatingDelegateProvider.of(this, configuration)
/**
* A property delegate that creates elements in the given [NamedDomainObjectContainer].
*
* See [creating]
*/
class NamedDomainObjectContainerCreatingDelegateProvider<T : Any>
private constructor(
internal val container: NamedDomainObjectContainer<T>,
internal val configuration: (T.() -> Unit)? = null
) {
companion object {
fun <T : Any> of(container: NamedDomainObjectContainer<T>, configuration: (T.() -> Unit)? = null) =
NamedDomainObjectContainerCreatingDelegateProvider(container, configuration)
}
operator fun provideDelegate(thisRef: Any?, property: KProperty<*>) = ExistingDomainObjectDelegate.of(
when (configuration) {
null -> container.create(property.name)
else -> container.create(property.name, configuration)
}
)
}
/**
* Provides a property delegate that creates elements of the given [type].
*/
fun <T : Any, U : T> PolymorphicDomainObjectContainer<T>.creating(type: KClass<U>) =
PolymorphicDomainObjectContainerCreatingDelegateProvider.of(this, type.java)
/**
* Provides a property delegate that creates elements of the given [type] with the given [configuration].
*/
fun <T : Any, U : T> PolymorphicDomainObjectContainer<T>.creating(type: KClass<U>, configuration: U.() -> Unit) =
creating(type.java, configuration)
/**
* Provides a property delegate that creates elements of the given [type] expressed as a [java.lang.Class]
* with the given [configuration].
*/
fun <T : Any, U : T> PolymorphicDomainObjectContainer<T>.creating(type: Class<U>, configuration: U.() -> Unit) =
PolymorphicDomainObjectContainerCreatingDelegateProvider.of(this, type, configuration)
/**
* A property delegate that creates elements of the given [type] with the given [configuration] in the given [container].
*/
class PolymorphicDomainObjectContainerCreatingDelegateProvider<T : Any, U : T>
private constructor(
internal val container: PolymorphicDomainObjectContainer<T>,
internal val type: Class<U>,
internal val configuration: (U.() -> Unit)? = null
) {
companion object {
fun <T : Any, U : T> of(container: PolymorphicDomainObjectContainer<T>, type: Class<U>, configuration: (U.() -> Unit)? = null) =
PolymorphicDomainObjectContainerCreatingDelegateProvider(container, type, configuration)
}
operator fun provideDelegate(thisRef: Any?, property: KProperty<*>) = ExistingDomainObjectDelegate.of(
when (configuration) {
null -> container.create(property.name, type)
else -> container.create(property.name, type, configuration)
}
)
}
/**
* Provides a property delegate that gets elements of the given [type] and applies the given [configuration].
*/
fun <T : Any, U : T> NamedDomainObjectContainer<T>.getting(type: KClass<U>, configuration: U.() -> Unit) =
PolymorphicDomainObjectContainerGettingDelegateProvider.of(this, type, configuration)
/**
* Provides a property delegate that gets elements of the given [type].
*/
fun <T : Any, U : T> NamedDomainObjectContainer<T>.getting(type: KClass<U>) =
PolymorphicDomainObjectContainerGettingDelegateProvider.of(this, type)
/**
* A property delegate that gets elements of the given [type] from the given [container]
* and applies the given [configuration].
*/
class PolymorphicDomainObjectContainerGettingDelegateProvider<T : Any, U : T>
private constructor(
internal val container: NamedDomainObjectContainer<T>,
internal val type: KClass<U>,
internal val configuration: (U.() -> Unit)? = null
) {
companion object {
fun <T : Any, U : T> of(container: NamedDomainObjectContainer<T>, type: KClass<U>, configuration: (U.() -> Unit)? = null) =
PolymorphicDomainObjectContainerGettingDelegateProvider(container, type, configuration)
}
operator fun provideDelegate(thisRef: Any?, property: KProperty<*>) = ExistingDomainObjectDelegate.of(
when (configuration) {
null -> container.getByName(property.name, type)
else -> container.getByName(property.name, type, configuration)
}
)
}
| apache-2.0 |
f-droid/fdroidclient | libs/index/src/commonMain/kotlin/org/fdroid/index/IndexConverter.kt | 1 | 3486 | package org.fdroid.index
import org.fdroid.index.v1.IndexV1
import org.fdroid.index.v1.Localized
import org.fdroid.index.v2.AntiFeatureV2
import org.fdroid.index.v2.CategoryV2
import org.fdroid.index.v2.IndexV2
import org.fdroid.index.v2.LocalizedTextV2
import org.fdroid.index.v2.PackageV2
import org.fdroid.index.v2.ReleaseChannelV2
public const val RELEASE_CHANNEL_BETA: String = "Beta"
internal const val DEFAULT_LOCALE = "en-US"
public class IndexConverter(
private val defaultLocale: String = DEFAULT_LOCALE,
) {
public fun toIndexV2(v1: IndexV1): IndexV2 {
val antiFeatures = HashMap<String, AntiFeatureV2>()
val categories = HashMap<String, CategoryV2>()
val packagesV2 = HashMap<String, PackageV2>(v1.apps.size)
v1.apps.forEach { app ->
val versions = v1.packages[app.packageName]
val preferredSigner = versions?.get(0)?.signer
val appAntiFeatures: Map<String, LocalizedTextV2> =
app.antiFeatures.associateWith { emptyMap() }
val whatsNew: LocalizedTextV2? = app.localized?.mapValuesNotNull { it.value.whatsNew }
var isFirstVersion = true
val packageV2 = PackageV2(
metadata = app.toMetadataV2(preferredSigner, defaultLocale),
versions = versions?.associate {
val versionCode = it.versionCode ?: 0
val suggestedVersionCode = app.suggestedVersionCode?.toLongOrNull() ?: 0
val versionReleaseChannels = if (versionCode > suggestedVersionCode)
listOf(RELEASE_CHANNEL_BETA) else emptyList()
val wn = if (isFirstVersion) whatsNew else null
isFirstVersion = false
it.hash to it.toPackageVersionV2(versionReleaseChannels, appAntiFeatures, wn)
} ?: emptyMap(),
)
appAntiFeatures.mapInto(antiFeatures)
app.categories.mapInto(categories)
packagesV2[app.packageName] = packageV2
}
return IndexV2(
repo = v1.repo.toRepoV2(
locale = defaultLocale,
antiFeatures = antiFeatures,
categories = categories,
releaseChannels = getV1ReleaseChannels(),
),
packages = packagesV2,
)
}
}
internal fun <T> Collection<String>.mapInto(map: HashMap<String, T>, valueGetter: (String) -> T) {
forEach { key ->
if (!map.containsKey(key)) map[key] = valueGetter(key)
}
}
internal fun List<String>.mapInto(map: HashMap<String, CategoryV2>) {
mapInto(map) { key ->
CategoryV2(name = mapOf(DEFAULT_LOCALE to key))
}
}
internal fun Map<String, LocalizedTextV2>.mapInto(map: HashMap<String, AntiFeatureV2>) {
keys.mapInto(map) { key ->
AntiFeatureV2(name = mapOf(DEFAULT_LOCALE to key))
}
}
public fun getV1ReleaseChannels(): Map<String, ReleaseChannelV2> = mapOf(
RELEASE_CHANNEL_BETA to ReleaseChannelV2(
name = mapOf(DEFAULT_LOCALE to RELEASE_CHANNEL_BETA),
description = emptyMap(),
)
)
internal fun <T> Map<String, Localized>.mapValuesNotNull(
transform: (Map.Entry<String, Localized>) -> T?,
): Map<String, T>? {
val map = LinkedHashMap<String, T>(size)
for (element in this) {
val value = transform(element)
if (value != null) map[element.key] = value
}
return map.takeIf { map.isNotEmpty() }
}
| gpl-3.0 |
toastkidjp/Jitte | app/src/main/java/jp/toastkid/yobidashi/browser/webview/factory/WebViewClientFactory.kt | 1 | 7944 | /*
* Copyright (c) 2020 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.browser.webview.factory
import android.annotation.TargetApi
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.net.http.SslError
import android.os.Build
import android.webkit.SslErrorHandler
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.fragment.app.FragmentActivity
import jp.toastkid.lib.ContentViewModel
import jp.toastkid.lib.dialog.ConfirmDialogFragment
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.yobidashi.R
import jp.toastkid.yobidashi.browser.BrowserHeaderViewModel
import jp.toastkid.yobidashi.browser.FaviconApplier
import jp.toastkid.yobidashi.browser.LoadingViewModel
import jp.toastkid.yobidashi.browser.block.AdRemover
import jp.toastkid.yobidashi.browser.history.ViewHistoryInsertion
import jp.toastkid.yobidashi.browser.tls.TlsErrorMessageGenerator
import jp.toastkid.yobidashi.browser.webview.GlobalWebViewPool
import jp.toastkid.yobidashi.browser.webview.usecase.RedirectionUseCase
import jp.toastkid.rss.suggestion.RssAddingSuggestion
import jp.toastkid.yobidashi.tab.History
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import timber.log.Timber
class WebViewClientFactory(
private val contentViewModel: ContentViewModel?,
private val adRemover: AdRemover,
private val faviconApplier: FaviconApplier,
private val preferenceApplier: PreferenceApplier,
private val browserHeaderViewModel: BrowserHeaderViewModel? = null,
private val rssAddingSuggestion: RssAddingSuggestion? = null,
private val loadingViewModel: LoadingViewModel? = null,
private val currentView: () -> WebView? = { null }
) {
/**
* Add onPageFinished and onPageStarted.
*/
operator fun invoke(): WebViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
browserHeaderViewModel?.updateProgress(0)
browserHeaderViewModel?.nextUrl(url)
rssAddingSuggestion?.invoke(view, url)
browserHeaderViewModel?.setBackButtonEnability(view.canGoBack())
}
override fun onPageFinished(view: WebView, url: String?) {
super.onPageFinished(view, url)
val title = view.title ?: ""
val urlStr = url ?: ""
val tabId = GlobalWebViewPool.getTabId(view)
if (tabId?.isNotBlank() == true) {
CoroutineScope(Dispatchers.Main).launch {
loadingViewModel?.finished(tabId, History.make(title, urlStr))
}
}
browserHeaderViewModel?.updateProgress(100)
browserHeaderViewModel?.stopProgress(true)
try {
if (view == currentView()) {
browserHeaderViewModel?.nextTitle(title)
browserHeaderViewModel?.nextUrl(urlStr)
}
} catch (e: Exception) {
Timber.e(e)
}
if (preferenceApplier.saveViewHistory
&& title.isNotEmpty()
&& urlStr.isNotEmpty()
) {
ViewHistoryInsertion
.make(
view.context,
title,
urlStr,
faviconApplier.makePath(urlStr)
)
.invoke()
}
}
override fun onReceivedError(
view: WebView, request: WebResourceRequest, error: WebResourceError) {
super.onReceivedError(view, request, error)
browserHeaderViewModel?.updateProgress(100)
browserHeaderViewModel?.stopProgress(true)
}
override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
super.onReceivedSslError(view, handler, error)
handler?.cancel()
val context = view?.context ?: return
if (context !is FragmentActivity || context.isFinishing) {
return
}
ConfirmDialogFragment.show(
context.supportFragmentManager,
context.getString(R.string.title_ssl_connection_error),
TlsErrorMessageGenerator().invoke(context, error),
"tls_error"
)
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? =
if (preferenceApplier.adRemove) {
adRemover(request.url.toString())
} else {
super.shouldInterceptRequest(view, request)
}
@Suppress("OverridingDeprecatedMember")
@TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
override fun shouldInterceptRequest(view: WebView, url: String): WebResourceResponse? =
if (preferenceApplier.adRemove) {
adRemover(url)
} else {
@Suppress("DEPRECATION")
super.shouldInterceptRequest(view, url)
}
@Suppress("DEPRECATION")
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean =
shouldOverrideUrlLoading(view, request?.url?.toString())
@Suppress("OverridingDeprecatedMember", "DEPRECATION")
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean =
url?.let {
val context: Context? = view?.context
val uri: Uri = Uri.parse(url)
if (RedirectionUseCase.isTarget(uri)) {
RedirectionUseCase().invoke(view, uri)
return@let false
}
when (uri.scheme) {
"market", "intent" -> {
try {
context?.startActivity(Intent.parseUri(url, Intent.URI_INTENT_SCHEME))
true
} catch (e: ActivityNotFoundException) {
Timber.w(e)
context?.let {
contentViewModel?.snackShort(context.getString(R.string.message_cannot_launch_app))
}
true
}
}
"tel" -> {
context?.startActivity(Intent(Intent.ACTION_DIAL, uri))
view?.reload()
true
}
"mailto" -> {
context?.startActivity(Intent(Intent.ACTION_SENDTO, uri))
view?.reload()
true
}
else -> {
super.shouldOverrideUrlLoading(view, url)
}
}
} ?: super.shouldOverrideUrlLoading(view, url)
}
} | epl-1.0 |
owncloud/android | owncloudDomain/src/main/java/com/owncloud/android/domain/exceptions/LocalFileNotFoundException.kt | 2 | 831 | /**
* ownCloud Android client application
*
* @author David González Verdugo
* Copyright (C) 2020 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* 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.owncloud.android.domain.exceptions
import java.lang.Exception
class LocalFileNotFoundException : Exception()
| gpl-2.0 |
iZettle/wrench | wrench-sample/src/main/java/com/example/wrench/wrenchprefs/WrenchPreferencesFragmentViewModel.kt | 1 | 2453 | package com.example.wrench.wrenchprefs
import android.content.res.Resources
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.wrench.MyEnum
import com.example.wrench.R
import com.izettle.wrench.preferences.WrenchPreferences
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
class WrenchPreferencesFragmentViewModel constructor(val resources: Resources, private val wrenchPreferences: WrenchPreferences) : ViewModel() {
private val job = Job()
private val scope = CoroutineScope(job + Dispatchers.Main)
private val stringConfig: MutableLiveData<String> by lazy {
MutableLiveData<String>()
}
fun getStringConfiguration(): LiveData<String> {
scope.launch {
stringConfig.postValue(wrenchPreferences.getString(resources.getString(R.string.string_configuration), "string1"))
}
return stringConfig
}
private val urlConfig: MutableLiveData<String> by lazy {
MutableLiveData<String>()
}
fun getUrlConfiguration(): LiveData<String> {
scope.launch {
urlConfig.postValue(wrenchPreferences.getString(resources.getString(R.string.url_configuration), "http://www.example.com/path?param=value"))
}
return urlConfig
}
private val booleanConfig: MutableLiveData<Boolean> by lazy {
MutableLiveData<Boolean>()
}
fun getBooleanConfiguration(): LiveData<Boolean> {
scope.launch {
booleanConfig.postValue(wrenchPreferences.getBoolean(resources.getString(R.string.boolean_configuration), true))
}
return booleanConfig
}
private val intConfig: MutableLiveData<Int> by lazy {
MutableLiveData<Int>()
}
fun getIntConfiguration(): LiveData<Int> {
scope.launch {
intConfig.postValue(wrenchPreferences.getInt(resources.getString(R.string.int_configuration), 1))
}
return intConfig
}
private val enumConfig: MutableLiveData<MyEnum> by lazy {
MutableLiveData<MyEnum>()
}
fun getEnumConfiguration(): LiveData<MyEnum> {
scope.launch {
enumConfig.postValue(wrenchPreferences.getEnum(resources.getString(R.string.enum_configuration), MyEnum::class.java, MyEnum.SECOND))
}
return enumConfig
}
}
| mit |
square/leakcanary | shark-hprof/src/main/java/shark/ByteArraySourceProvider.kt | 2 | 841 | package shark
import java.io.IOException
import okio.Buffer
import okio.BufferedSource
class ByteArraySourceProvider(private val byteArray: ByteArray) : DualSourceProvider {
override fun openStreamingSource(): BufferedSource = Buffer().apply { write(byteArray) }
override fun openRandomAccessSource(): RandomAccessSource {
return object : RandomAccessSource {
var closed = false
override fun read(
sink: Buffer,
position: Long,
byteCount: Long
): Long {
if (closed) {
throw IOException("Source closed")
}
val maxByteCount = byteCount.coerceAtMost(byteArray.size - position)
sink.write(byteArray, position.toInt(), maxByteCount.toInt())
return maxByteCount
}
override fun close() {
closed = true
}
}
}
}
| apache-2.0 |
square/leakcanary | leakcanary-android-core/src/main/java/leakcanary/internal/RequestPermissionActivity.kt | 2 | 3004 | /*
* Copyright (C) 2016 Square, 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 leakcanary.internal
import android.annotation.TargetApi
import android.app.Activity
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_UPDATE_CURRENT
import android.app.PendingIntent.FLAG_IMMUTABLE
import android.content.Context
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.os.Bundle
import android.os.Build
import android.widget.Toast
import android.widget.Toast.LENGTH_LONG
import com.squareup.leakcanary.core.R
@TargetApi(Build.VERSION_CODES.M) //
internal class RequestPermissionActivity : Activity() {
private val targetPermission: String
get() = intent.getStringExtra(TARGET_PERMISSION_EXTRA)!!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
if (hasTargetPermission()) {
finish()
return
}
val permissions = arrayOf(targetPermission)
requestPermissions(permissions, 42)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
if (!hasTargetPermission()) {
Toast.makeText(application, R.string.leak_canary_permission_not_granted, LENGTH_LONG)
.show()
}
finish()
}
override fun finish() {
// Reset the animation to avoid flickering.
overridePendingTransition(0, 0)
super.finish()
}
private fun hasTargetPermission(): Boolean {
return checkSelfPermission(targetPermission) == PERMISSION_GRANTED
}
companion object {
private const val TARGET_PERMISSION_EXTRA = "targetPermission"
fun createIntent(context: Context, permission: String): Intent {
return Intent(context, RequestPermissionActivity::class.java).apply {
flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TOP
putExtra(TARGET_PERMISSION_EXTRA, permission)
}
}
fun createPendingIntent(context: Context, permission: String): PendingIntent {
val intent = createIntent(context, permission)
val flags = if (Build.VERSION.SDK_INT >= 23) {
FLAG_UPDATE_CURRENT or FLAG_IMMUTABLE
} else {
FLAG_UPDATE_CURRENT
}
return PendingIntent.getActivity(context, 1, intent, flags)
}
}
}
| apache-2.0 |
mmirhoseini/tehran_traffic_map | app/src/main/java/com/tehran/traffic/TehranTrafficMapApplication.kt | 1 | 674 | package com.tehran.traffic
import androidx.multidex.MultiDexApplication
import timber.log.Timber
class TehranTrafficMapApplication : MultiDexApplication() {
override fun onCreate() {
super.onCreate()
initTimberDebugTree()
}
private fun initTimberDebugTree() {
val debugTree = object : Timber.DebugTree() {
override fun createStackElementTag(element: StackTraceElement): String {
// adding file name and line number link to debug logs
return "${super.createStackElementTag(element)}(${element.fileName}:${element.lineNumber}"
}
}
Timber.plant(debugTree)
}
}
| mit |
shaeberling/euler | kotlin/src/com/s13g/aoc/aoc2020/Day22.kt | 1 | 2882 | package com.s13g.aoc.aoc2020
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import java.util.*
/**
* --- Day 22: Crab Combat ---
* https://adventofcode.com/2020/day/22
*/
class Day22 : Solver {
override fun solve(lines: List<String>): Result {
val playersA = parse(lines)
// Make copy for Part B where we have to start over.
val playersB = playersA.map { LinkedList(it) }
// The game is going while none of them ran out of cards.
while (playersA[0].isNotEmpty() && playersA[1].isNotEmpty()) {
val top = Pair(playersA[0].removeAt(0), playersA[1].removeAt(0))
if (top.first > top.second) {
playersA[0].add(top.first)
playersA[0].add(top.second)
} else {
playersA[1].add(top.second)
playersA[1].add(top.first)
}
}
val winnerA = if (playersA.isNotEmpty()) 0 else 1
val resultA = playersA[winnerA].reversed().withIndex().map { (it.index + 1) * it.value }.sum()
// Part 2
val winnerB = recursiveCombat(playersB, 1)
val resultB = playersB[winnerB].reversed().withIndex().map { (it.index + 1) * it.value }.sum()
return Result("$resultA", "$resultB")
}
private fun recursiveCombat(players: List<LinkedList<Long>>, gameNo: Int): Int {
val history = Array(2) { mutableSetOf<Int>() }
var roundNo = 1
var roundWinner = -42
while (players[0].isNotEmpty() && players[1].isNotEmpty()) {
// Player 0 wins when history repeats.
if (players[0].hashCode() in history[0] || players[1].hashCode() in history[1]) return 0
history[0].add(players[0].hashCode())
history[1].add(players[1].hashCode())
// Top cards.
val top = Pair(players[0].pop(), players[1].pop())
roundWinner = if (players[0].size >= top.first && players[1].size >= top.second) {
// Play sub-game, recursive combat! Create copies so that our list is not changed.
val subListA = LinkedList(players[0].subList(0, top.first.toInt()))
val subListB = LinkedList(players[1].subList(0, top.second.toInt()))
recursiveCombat(listOf(subListA, subListB), gameNo + 1)
} else if (top.first > top.second) 0 else 1
// Add cards to the round winners deck in the right order (winner's first).
players[roundWinner].add(if (roundWinner == 0) top.first else top.second)
players[roundWinner].add(if (roundWinner == 0) top.second else top.first)
roundNo++
}
return roundWinner
}
private fun parse(lines: List<String>): List<LinkedList<Long>> {
val players = mutableListOf<LinkedList<Long>>(LinkedList(), LinkedList())
var activePlayerParsing = 0
for (line in lines) {
if (line.startsWith("Player 1:") || line.isBlank()) continue
if (line.startsWith("Player 2:")) activePlayerParsing = 1
else players[activePlayerParsing].add(line.toLong())
}
return players
}
} | apache-2.0 |
capehorn/swagger-vertx-elm | src/test/kotlin/codegen/CodeGeneratorTest.kt | 1 | 437 | package codegen
import codegen.vertx.VertxCodeGenerator
import io.swagger.parser.SwaggerParser
import org.junit.Test
class CodeGeneratorTest {
val swagger = SwaggerParser().read("file:///C:/home/divers/vertx/src/main/resources/openapis/upbeat-api.json");
@Test
fun processSwaggerTest(){
val codeGen = VertxCodeGenerator("")
val genModel = codeGen.processSwagger(swagger)
println(genModel)
}
} | apache-2.0 |
fython/PackageTracker | mobile/src/main/kotlin/info/papdt/express/helper/ui/adapter/CompanyListAdapter.kt | 1 | 2619 | package info.papdt.express.helper.ui.adapter
import android.graphics.drawable.ColorDrawable
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import java.util.ArrayList
import de.hdodenhof.circleimageview.CircleImageView
import info.papdt.express.helper.R
import info.papdt.express.helper.api.Kuaidi100PackageApi
import info.papdt.express.helper.ui.common.SimpleRecyclerViewAdapter
class CompanyListAdapter(
recyclerView: RecyclerView,
private var list: ArrayList<Kuaidi100PackageApi.CompanyInfo.Company>?
) : SimpleRecyclerViewAdapter(recyclerView) {
fun setList(list: ArrayList<Kuaidi100PackageApi.CompanyInfo.Company>) {
this.list = list
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SimpleRecyclerViewAdapter.ClickableViewHolder {
bindContext(parent.context)
return ItemHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_list_company, parent, false))
}
override fun onBindViewHolder(holder: SimpleRecyclerViewAdapter.ClickableViewHolder, position: Int) {
super.onBindViewHolder(holder, position)
val item = getItem(position)
if (holder is ItemHolder) {
holder.titleText.text = item.name
holder.otherText.text = if (item.phone != null) item.phone else item.website
holder.otherText.visibility = if (holder.otherText.text != null) View.VISIBLE else View.INVISIBLE
/** Set up the logo */
holder.firstCharText.text = item.name.substring(0, 1)
item.getPalette().let {
holder.logoView.setImageDrawable(
ColorDrawable(it.getPackageIconBackground(context!!)))
holder.firstCharText.setTextColor(
it.getPackageIconForeground(context!!))
}
}
}
override fun getItemCount(): Int = list?.size ?: 0
fun getItem(pos: Int): Kuaidi100PackageApi.CompanyInfo.Company = list!![pos]
inner class ItemHolder(itemView: View) : SimpleRecyclerViewAdapter.ClickableViewHolder(itemView) {
internal var titleText: AppCompatTextView = itemView.findViewById(R.id.tv_title)
internal var otherText: AppCompatTextView = itemView.findViewById(R.id.tv_other)
internal var logoView: CircleImageView = itemView.findViewById(R.id.iv_logo)
internal var firstCharText: TextView = itemView.findViewById(R.id.tv_first_char)
}
}
| gpl-3.0 |
wordpress-mobile/WordPress-FluxC-Android | example/src/test/java/org/wordpress/android/fluxc/wc/leaderboards/LeaderboardsRestClientTest.kt | 1 | 5424 | package org.wordpress.android.fluxc.wc.leaderboards
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.mockito.kotlin.mock
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.wordpress.android.fluxc.generated.endpoint.WOOCOMMERCE
import org.wordpress.android.fluxc.network.BaseRequest.BaseNetworkError
import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType.NETWORK_ERROR
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequest.WPComGsonNetworkError
import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder
import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackError
import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackSuccess
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooError
import org.wordpress.android.fluxc.network.rest.wpcom.wc.leaderboards.LeaderboardsApiResponse
import org.wordpress.android.fluxc.network.rest.wpcom.wc.leaderboards.LeaderboardsRestClient
import org.wordpress.android.fluxc.test
import org.wordpress.android.fluxc.wc.leaderboards.WCLeaderboardsTestFixtures.generateSampleLeaderboardsApiResponse
import org.wordpress.android.fluxc.wc.leaderboards.WCLeaderboardsTestFixtures.stubSite
class LeaderboardsRestClientTest {
private lateinit var restClientUnderTest: LeaderboardsRestClient
private lateinit var requestBuilder: JetpackTunnelGsonRequestBuilder
private lateinit var jetpackSuccessResponse: JetpackSuccess<Array<LeaderboardsApiResponse>>
private lateinit var jetpackErrorResponse: JetpackError<Array<LeaderboardsApiResponse>>
@Before
fun setUp() {
requestBuilder = mock()
jetpackSuccessResponse = mock()
jetpackErrorResponse = mock()
restClientUnderTest = LeaderboardsRestClient(
mock(),
mock(),
mock(),
mock(),
mock(),
requestBuilder
)
}
@Test
fun `fetch leaderboards should call syncGetRequest with correct parameters and return expected response`() = test {
val expectedResult = generateSampleLeaderboardsApiResponse()
configureSuccessRequest(expectedResult!!)
val response = restClientUnderTest.fetchLeaderboards(
site = stubSite,
startDate = "10-10-2022",
endDate = "22-10-2022",
quantity = 5,
forceRefresh = false,
interval = "day"
)
verify(requestBuilder, times(1)).syncGetRequest(
restClientUnderTest,
stubSite,
WOOCOMMERCE.leaderboards.pathV4Analytics,
mapOf(
"before" to "22-10-2022",
"after" to "10-10-2022",
"per_page" to "5",
"interval" to "day",
"force_cache_refresh" to "false",
),
Array<LeaderboardsApiResponse>::class.java
)
assertThat(response).isNotNull
assertThat(response.result).isNotNull
assertThat(response.error).isNull()
assertThat(response.result).isEqualTo(expectedResult)
}
@Test
fun `fetch leaderboards should correctly return failure as WooError`() = test {
configureErrorRequest()
val response = restClientUnderTest.fetchLeaderboards(
site = stubSite,
startDate = "10-10-2022",
endDate = "22-10-2022",
forceRefresh = false,
quantity = 5,
interval = "day"
)
assertThat(response).isNotNull
assertThat(response.result).isNull()
assertThat(response.error).isNotNull
assertThat(response.error).isExactlyInstanceOf(WooError::class.java)
}
private suspend fun configureSuccessRequest(expectedResult: Array<LeaderboardsApiResponse>) {
whenever(jetpackSuccessResponse.data).thenReturn(expectedResult)
whenever(
requestBuilder.syncGetRequest(
restClientUnderTest,
stubSite,
WOOCOMMERCE.leaderboards.pathV4Analytics,
mapOf(
"after" to "10-10-2022",
"before" to "22-10-2022",
"per_page" to "5",
"interval" to "day",
"force_cache_refresh" to "false",
),
Array<LeaderboardsApiResponse>::class.java
)
).thenReturn(jetpackSuccessResponse)
}
private suspend fun configureErrorRequest() {
whenever(jetpackErrorResponse.error).thenReturn(WPComGsonNetworkError(BaseNetworkError(NETWORK_ERROR)))
whenever(
requestBuilder.syncGetRequest(
restClientUnderTest,
stubSite,
WOOCOMMERCE.leaderboards.pathV4Analytics,
mapOf(
"after" to "10-10-2022",
"before" to "22-10-2022",
"per_page" to "5",
"interval" to "day",
"force_cache_refresh" to "false",
),
Array<LeaderboardsApiResponse>::class.java
)
).thenReturn(jetpackErrorResponse)
}
}
| gpl-2.0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.