content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.foo.rest.examples.spring.openapi.v3.wiremock.harvestresponse
import com.foo.rest.examples.spring.openapi.v3.SpringController
class WmHarvestResponseController() : SpringController(WmHarvestResponseApplication::class.java) | e2e-tests/spring-rest-openapi-v3/src/test/kotlin/com/foo/rest/examples/spring/openapi/v3/wiremock/harvestresponse/WmHarvestResponseController.kt | 3444538955 |
package org.evomaster.core.search.gene.sql
import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType
import org.evomaster.core.logging.LoggingUtil
import org.evomaster.core.output.OutputFormat
import org.evomaster.core.search.gene.*
import org.evomaster.core.search.gene.collection.ArrayGene
import org.evomaster.core.search.gene.root.CompositeGene
import org.evomaster.core.search.gene.utils.GeneUtils
import org.evomaster.core.search.impact.impactinfocollection.ImpactUtils
import org.evomaster.core.search.service.Randomness
import org.evomaster.core.search.service.mutator.MutationWeightControl
import org.evomaster.core.search.service.mutator.genemutation.AdditionalGeneMutationInfo
import org.evomaster.core.search.service.mutator.genemutation.SubsetGeneMutationSelectionStrategy
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* https://www.postgresql.org/docs/14/arrays.html
* A multidimensional array representation.
* When created, all dimensions have length 0
*/
class SqlMultidimensionalArrayGene<T>(
/**
* The name of this gene
*/
name: String,
/**
* The database type of the column where the gene is inserted.
* By default, the database type is POSTGRES
*/
val databaseType: DatabaseType = DatabaseType.POSTGRES,
/**
* The type for this array. Every time we create a new element to add, it has to be based
* on this template
*/
val template: T,
/**
* Fixed number of dimensions for this multidimensional array.
* Once created, the number of dimensions do not change.
*/
val numberOfDimensions: Int,
/**
* How many elements each dimension can have.
*/
private val maxDimensionSize: Int = ArrayGene.MAX_SIZE
) : CompositeGene(name, mutableListOf()) where T : Gene {
/**
* Stores what is the size of each dimension.
* It is used to check that the multidimensional array
* is valid.
*/
private var dimensionSizes: List<Int> = listOf()
init {
if (numberOfDimensions < 1)
throw IllegalArgumentException("Invalid number of dimensions $numberOfDimensions")
}
/*
FIXME
only one direct child
override children modifications to rather work on internal array genes.
but, before that, need to refactor/look-into CollectionGene
*/
companion object {
val log: Logger = LoggerFactory.getLogger(SqlMultidimensionalArrayGene::class.java)
/**
* Checks if the given index is within range.
* Otherwise an IndexOutOfBounds exception is thrown.
*/
private fun checkIndexWithinRange(index: Int, indices: IntRange) {
if (index !in indices) {
throw IndexOutOfBoundsException("Cannot access index $index in a dimension of size $indices")
}
}
/**
* Recursively creates the internal representation
* of the multidimensional array. The argument is
* a list of the size for each dimension.
*/
private fun <T : Gene> buildNewElements(
dimensionSizes: List<Int>,
elementTemplate: T
): ArrayGene<*> {
val s = dimensionSizes[0]
return if (dimensionSizes.size == 1) {
// leaf ArrayGene case
ArrayGene("[$s]", elementTemplate.copy(), maxSize = s, minSize = s)
} else {
// nested/inner ArrayGene case
val currentDimensionSize = dimensionSizes.first()
val nextDimensionSizes = dimensionSizes.drop(1)
val arrayTemplate = buildNewElements(nextDimensionSizes, elementTemplate)
ArrayGene("[$currentDimensionSize]${arrayTemplate.name}", arrayTemplate,
maxSize = currentDimensionSize, minSize = currentDimensionSize)
}
}
}
override fun isMutable(): Boolean {
return !initialized || this.children[0].isMutable()
}
/**
* Returns the element by using a list of indices for
* each dimension. The number of indices must be equal
* to the number of dimensions of the multidimensional array.
* Additionally, each index must be within range.
*
* For example, given the following multidimensional array.
* { {g1,g2,g3} , {g4, g5, g6} }
* getElement({0,0}) returns g1.
* getElement({2,2}) returns g6
*/
fun getElement(dimensionIndexes: List<Int>): T {
if (!initialized) {
throw IllegalStateException("Cannot get element from an unitialized multidimensional array")
}
if (dimensionIndexes.size != numberOfDimensions) {
throw IllegalArgumentException("Incorrect number of indices to get an element of an array of $numberOfDimensions dimensions")
}
var current = getArray()
((0..(dimensionIndexes.size - 2))).forEach {
checkIndexWithinRange(dimensionIndexes[it], current.getViewOfElements().indices)
current = current.getViewOfElements()[dimensionIndexes[it]] as ArrayGene<*>
}
checkIndexWithinRange(dimensionIndexes.last(), current.getViewOfElements().indices)
return current.getViewOfElements()[dimensionIndexes.last()] as T
}
private fun isValid(currentArrayGene: ArrayGene<*>, currentDimensionIndex: Int): Boolean {
return if (!currentArrayGene.isLocallyValid())
false
else if (currentArrayGene.getViewOfChildren().size != this.dimensionSizes[currentDimensionIndex]) {
false
} else if (currentDimensionIndex == numberOfDimensions - 1) {
// case of leaf ArrayGene
currentArrayGene.getViewOfChildren().all { it::class.java.isAssignableFrom(template::class.java) }
} else {
// case of inner, nested ArrayGene
currentArrayGene.getViewOfChildren().all { isValid(it as ArrayGene<*>, currentDimensionIndex + 1) }
}
}
/**
* Check that the nested arraygenes equal the number of dimensions, check that each
* dimension length is preserved.
*/
override fun isLocallyValid(): Boolean {
return if (this.children.size != 1) {
false
} else {
isValid(this.children[0] as ArrayGene<*>, 0)
}
}
/**
* Requires the multidimensional array to be initialized
*/
private fun getArray(): ArrayGene<*> {
assert(initialized)
return children[0] as ArrayGene<*>
}
/**
* Returns the dimension size for the required dimension
* For example, given the following multidimensional array.
* { {g1,g2,g3} , {g4, g5, g6} }
* getDimensionSize(0) returns 2.
* getDimensionSize(1) returns 3
*/
fun getDimensionSize(dimensionIndex: Int): Int {
if (!initialized) {
throw IllegalStateException("Cannot get element from an unitialized multidimensional array")
}
if (dimensionIndex >= this.numberOfDimensions) {
throw IndexOutOfBoundsException("Cannot get dimension size of dimension ${dimensionIndex} for an array of ${numberOfDimensions} dimensions")
}
var current = getArray()
if (current.getViewOfElements().isEmpty()) {
checkIndexWithinRange(dimensionIndex, IntRange(0, numberOfDimensions - 1))
return 0
}
repeat(dimensionIndex) {
current = current.getViewOfElements()[0] as ArrayGene<*>
}
return current.getViewOfElements().size
}
/**
* Randomizes the whole multidimensional array by removing all dimensions, and then
* creating new sizes for each dimension, and new gene elements from the template.
*/
override fun randomize(randomness: Randomness, tryToForceNewValue: Boolean) {
val newDimensionSizes: List<Int> = buildNewDimensionSizes(randomness)
val newChild = buildNewElements(newDimensionSizes, template.copy())
killAllChildren()
this.dimensionSizes = newDimensionSizes
if(initialized){
newChild.doInitialize(randomness)
} else {
newChild.randomize(randomness, tryToForceNewValue)
}
addChild(newChild)
}
/**
* Creates a new list of randomized dimension sizes.
* The total number of dimensions is equal to numberOfDimensions, and
* no dimension is greater than maxDimensionSize.
* If the array is unidimensional, the dimensionSize could be 0, otherwise
* is always greater than 0.
*/
private fun buildNewDimensionSizes(randomness: Randomness): List<Int> {
if (numberOfDimensions == 1) {
val dimensionSize = randomness.nextInt(0, maxDimensionSize)
return mutableListOf(dimensionSize)
} else {
val dimensionSizes: MutableList<Int> = mutableListOf()
repeat(numberOfDimensions) {
val dimensionSize = randomness.nextInt(1, maxDimensionSize)
dimensionSizes.add(dimensionSize)
}
return dimensionSizes.toList()
}
}
/**
* Returns true if the other gene is another multidimensional array,
* with the same number of dimensions, size of each dimension,
* and containsSameValueAs the other genes.
*/
override fun containsSameValueAs(other: Gene): Boolean {
if (!initialized) {
throw IllegalStateException("Cannot call to containsSameValueAs using an unitialized multidimensional array")
}
if (other !is SqlMultidimensionalArrayGene<*>) {
throw IllegalArgumentException("Invalid gene type ${other.javaClass}")
}
if (this.numberOfDimensions != other.numberOfDimensions) {
return false
}
if (this.dimensionSizes != other.dimensionSizes) {
return false
}
return this.getViewOfChildren()[0].containsSameValueAs(other.getViewOfChildren()[0])
}
/**
* A multidimensional array gene can only bind to other multidimensional array genes
* with the same template and number of dimensions.
*/
override fun bindValueBasedOn(gene: Gene): Boolean {
if (gene !is SqlMultidimensionalArrayGene<*>) {
LoggingUtil.uniqueWarn(ArrayGene.log, "cannot bind SqlMultidimensionalArrayGene to ${gene::class.java.simpleName}")
return false
}
if (gene.template::class.java.simpleName != template::class.java.simpleName) {
LoggingUtil.uniqueWarn(ArrayGene.log, "cannot bind SqlMultidimensionalArrayGene with the template (${template::class.java.simpleName}) with ${gene::class.java.simpleName}")
return false
}
if (numberOfDimensions != gene.numberOfDimensions) {
LoggingUtil.uniqueWarn(ArrayGene.log, "cannot bind SqlMultidimensionalArrayGene of ${numberOfDimensions} dimensions to another multidimensional array gene of ${gene.numberOfDimensions}")
return false
}
killAllChildren()
val elements = gene.getViewOfChildren().mapNotNull { it.copy() as? T }.toMutableList()
addChildren(elements)
this.dimensionSizes = gene.dimensionSizes
return true
}
override fun getValueAsPrintableString(
previousGenes: List<Gene>,
mode: GeneUtils.EscapeMode?,
targetFormat: OutputFormat?,
extraCheck: Boolean
): String {
if (!initialized) {
throw IllegalStateException("Cannot call to getValueAsPrintableString() using an unitialized multidimensional array")
}
val printableString = getValueAsPrintableString(this.children[0], previousGenes, mode,targetFormat , extraCheck)
return when (databaseType) {
DatabaseType.H2 -> printableString
DatabaseType.POSTGRES -> "\"$printableString\""
else -> throw IllegalStateException("Unsupported getValueAsPrintableString for database type $databaseType")
}
}
/**
* Helper funcgtion for printing the inner arrays and elements
*/
private fun getValueAsPrintableString(gene: Gene, previousGenes: List<Gene>,
mode: GeneUtils.EscapeMode?,
targetFormat: OutputFormat?,
extraCheck: Boolean
): String {
return if (gene is ArrayGene<*>) {
val str = gene.getViewOfElements().joinToString(", ") { g ->
getValueAsPrintableString(g, previousGenes, mode, targetFormat, extraCheck)}
when (databaseType) {
DatabaseType.POSTGRES -> "{$str}"
DatabaseType.H2 -> "ARRAY[$str]"
else -> throw IllegalStateException("Unsupported getValueAsPrintableString for database type $databaseType")
}
} else {
val str = gene.getValueAsPrintableString(previousGenes, mode, targetFormat, extraCheck)
when (databaseType) {
DatabaseType.POSTGRES -> str
DatabaseType.H2 -> GeneUtils.replaceEnclosedQuotationMarksWithSingleApostrophePlaceHolder(str)
else -> throw IllegalStateException("Unsupported getValueAsPrintableString for database type $databaseType")
}
}
}
override fun copyValueFrom(other: Gene) {
if (other !is SqlMultidimensionalArrayGene<*>) {
throw IllegalArgumentException("Invalid gene type ${other.javaClass}")
}
if (numberOfDimensions != other.numberOfDimensions) {
throw IllegalArgumentException("Cannot copy value to array of $numberOfDimensions dimensions from array of ${other.numberOfDimensions} dimensions")
}
getViewOfChildren()[0].copyValueFrom(other.getViewOfChildren()[0])
this.dimensionSizes = other.dimensionSizes
}
/**
* 1 is for 'remove' or 'add' element.
* The mutationWeight is computed on all elements in the same way
* as ArrayGene.mutationWeight()
*/
override fun mutationWeight(): Double {
return 1.0 //TODO
//return 1.0 + getAllGenes(this.nestedListOfElements).sumOf { it.mutationWeight() }
}
/**
* The function adaptiveSelectSubset() behaves as ArrayGene.adaptiveSelectSubset()
*/
override fun adaptiveSelectSubsetToMutate(randomness: Randomness,
internalGenes: List<Gene>,
mwc: MutationWeightControl,
additionalGeneMutationInfo: AdditionalGeneMutationInfo
): List<Pair<Gene, AdditionalGeneMutationInfo?>> {
/*
element is dynamically modified, then we do not collect impacts for it now.
thus for the internal genes, adaptive gene selection for mutation is not applicable
*/
val s = randomness.choose(internalGenes)
/*
TODO impact for an element in ArrayGene
*/
val geneImpact = ImpactUtils.createGeneImpact(s, s.name)
return listOf(s to additionalGeneMutationInfo.copyFoInnerGene(geneImpact, s))
}
override fun copyContent(): Gene {
/*
TODO Not sure about this. Even if we want to put this constraint, then should be in Gene
*/
// if (!initialized) {
// throw IllegalStateException("Cannot call to copyContent() from an uninitialized multidimensional array")
// }
val copy = SqlMultidimensionalArrayGene(
name = name,
databaseType = this.databaseType,
template = template.copy(),
numberOfDimensions = numberOfDimensions,
maxDimensionSize = maxDimensionSize
)
if (children.isNotEmpty()) {
copy.addChild(this.children[0].copy())
}
copy.dimensionSizes = this.dimensionSizes
return copy
}
override fun isPrintable(): Boolean {
return getViewOfChildren().all { it.isPrintable() }
}
override fun customShouldApplyShallowMutation(
randomness: Randomness,
selectionStrategy: SubsetGeneMutationSelectionStrategy,
enableAdaptiveGeneMutation: Boolean,
additionalGeneMutationInfo: AdditionalGeneMutationInfo?
): Boolean {
return false
}
} | core/src/main/kotlin/org/evomaster/core/search/gene/sql/SqlMultidimensionalArrayGene.kt | 3162955691 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vfs.local
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.IoTestUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.*
import com.intellij.openapi.vfs.impl.local.FileWatcher
import com.intellij.openapi.vfs.impl.local.LocalFileSystemImpl
import com.intellij.openapi.vfs.impl.local.NativeFileWatcherImpl
import com.intellij.openapi.vfs.newvfs.NewVirtualFile
import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.VfsTestUtil
import com.intellij.testFramework.fixtures.BareTestFixtureTestCase
import com.intellij.testFramework.rules.TempDirectory
import com.intellij.testFramework.runInEdtAndWait
import com.intellij.util.Alarm
import com.intellij.util.TimeoutUtil
import com.intellij.util.concurrency.Semaphore
import org.assertj.core.api.Assertions.assertThat
import org.junit.After
import org.junit.Assume.assumeFalse
import org.junit.Assume.assumeTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import java.io.File
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class FileWatcherTest : BareTestFixtureTestCase() {
//<editor-fold desc="Set up / tear down">
private val LOG: Logger by lazy { Logger.getInstance(NativeFileWatcherImpl::class.java) }
private val START_STOP_DELAY = 10000L // time to wait for the watcher spin up/down
private val INTER_RESPONSE_DELAY = 500L // time to wait for a next event in a sequence
private val NATIVE_PROCESS_DELAY = 60000L // time to wait for a native watcher response
private val SHORT_PROCESS_DELAY = 5000L // time to wait when no native watcher response is expected
private val UNICODE_NAME_1 = "Úñíçødê"
private val UNICODE_NAME_2 = "Юникоде"
@Rule @JvmField val tempDir = TempDirectory()
private lateinit var fs: LocalFileSystem
private lateinit var root: VirtualFile
private lateinit var watcher: FileWatcher
private lateinit var alarm: Alarm
private val watchedPaths = mutableListOf<String>()
private val watcherEvents = Semaphore()
private val resetHappened = AtomicBoolean()
@Before fun setUp() {
LOG.debug("================== setting up " + getTestName(false) + " ==================")
fs = LocalFileSystem.getInstance()
root = refresh(tempDir.root)
runInEdtAndWait { VirtualFileManager.getInstance().syncRefresh() }
alarm = Alarm(Alarm.ThreadToUse.POOLED_THREAD, testRootDisposable)
watcher = (fs as LocalFileSystemImpl).fileWatcher
assertFalse(watcher.isOperational)
watchedPaths += tempDir.root.path
watcher.startup { path ->
if (path == FileWatcher.RESET || path != FileWatcher.OTHER && watchedPaths.any { path.startsWith(it) }) {
alarm.cancelAllRequests()
alarm.addRequest({ watcherEvents.up() }, INTER_RESPONSE_DELAY)
if (path == FileWatcher.RESET) resetHappened.set(true)
}
}
wait { !watcher.isOperational }
LOG.debug("================== setting up " + getTestName(false) + " ==================")
}
@After fun tearDown() {
LOG.debug("================== tearing down " + getTestName(false) + " ==================")
watcher.shutdown()
wait { watcher.isOperational }
runInEdtAndWait {
runWriteAction { root.delete(this) }
(fs as LocalFileSystemImpl).cleanupForNextTest()
}
LOG.debug("================== tearing down " + getTestName(false) + " ==================")
}
//</editor-fold>
@Test fun testWatchRequestConvention() {
val dir = tempDir.newFolder("dir")
val r1 = watch(dir)
val r2 = watch(dir)
assertFalse(r1 == r2)
}
@Test fun testFileRoot() {
val files = arrayOf(tempDir.newFile("test1.txt"), tempDir.newFile("test2.txt"))
files.forEach { refresh(it) }
files.forEach { watch(it, false) }
assertEvents({ files.forEach { it.writeText("new content") } }, files.map { it to 'U' }.toMap())
assertEvents({ files.forEach { it.delete() } }, files.map { it to 'D' }.toMap())
assertEvents({ files.forEach { it.writeText("re-creation") } }, files.map { it to 'C' }.toMap())
}
@Test fun testFileRootRecursive() {
val files = arrayOf(tempDir.newFile("test1.txt"), tempDir.newFile("test2.txt"))
files.forEach { refresh(it) }
files.forEach { watch(it, true) }
assertEvents({ files.forEach { it.writeText("new content") } }, files.map { it to 'U' }.toMap())
assertEvents({ files.forEach { it.delete() } }, files.map { it to 'D' }.toMap())
assertEvents({ files.forEach { it.writeText("re-creation") } }, files.map { it to 'C' }.toMap())
}
@Test fun testNonCanonicallyNamedFileRoot() {
assumeTrue(!SystemInfo.isFileSystemCaseSensitive)
val file = tempDir.newFile("test.txt")
refresh(file)
watch(File(file.path.toUpperCase(Locale.US)))
assertEvents({ file.writeText("new content") }, mapOf(file to 'U'))
assertEvents({ file.delete() }, mapOf(file to 'D'))
assertEvents({ file.writeText("re-creation") }, mapOf(file to 'C'))
}
@Test fun testDirectoryRecursive() {
val top = tempDir.newFolder("top")
val sub = File(top, "sub")
val file = File(sub, "test.txt")
refresh(top)
watch(top)
assertEvents({ sub.mkdir() }, mapOf(sub to 'C'))
refresh(sub)
assertEvents({ file.createNewFile() }, mapOf(file to 'C'))
assertEvents({ file.writeText("new content") }, mapOf(file to 'U'))
assertEvents({ file.delete() }, mapOf(file to 'D'))
assertEvents({ file.writeText("re-creation") }, mapOf(file to 'C'))
}
@Test fun testDirectoryFlat() {
val top = tempDir.newFolder("top")
val watchedFile = tempDir.newFile("top/test.txt")
val unwatchedFile = tempDir.newFile("top/sub/test.txt")
refresh(top)
watch(top, false)
assertEvents({ watchedFile.writeText("new content") }, mapOf(watchedFile to 'U'))
assertEvents({ unwatchedFile.writeText("new content") }, mapOf(), SHORT_PROCESS_DELAY)
}
@Test fun testDirectoryMixed() {
val top = tempDir.newFolder("top")
val sub = tempDir.newFolder("top/sub2")
val unwatchedFile = tempDir.newFile("top/sub1/test.txt")
val watchedFile1 = tempDir.newFile("top/test.txt")
val watchedFile2 = tempDir.newFile("top/sub2/sub/test.txt")
refresh(top)
watch(top, false)
watch(sub, true)
assertEvents(
{ arrayOf(watchedFile1, watchedFile2, unwatchedFile).forEach { it.writeText("new content") } },
mapOf(watchedFile1 to 'U', watchedFile2 to 'U'))
}
@Test fun testIncorrectPath() {
val root = tempDir.newFolder("root")
val file = tempDir.newFile("root/file.zip")
val pseudoDir = File(file, "sub/zip")
refresh(root)
watch(pseudoDir, false)
assertEvents({ file.writeText("new content") }, mapOf(), SHORT_PROCESS_DELAY)
}
@Test fun testDirectoryOverlapping() {
val top = tempDir.newFolder("top")
val topFile = tempDir.newFile("top/file1.txt")
val sub = tempDir.newFolder("top/sub")
val subFile = tempDir.newFile("top/sub/file2.txt")
val side = tempDir.newFolder("side")
val sideFile = tempDir.newFile("side/file3.txt")
refresh(top)
refresh(side)
watch(sub)
watch(side)
assertEvents(
{ arrayOf(subFile, sideFile).forEach { it.writeText("first content") } },
mapOf(subFile to 'U', sideFile to 'U'))
assertEvents(
{ arrayOf(topFile, subFile, sideFile).forEach { it.writeText("new content") } },
mapOf(subFile to 'U', sideFile to 'U'))
val requestForTopDir = watch(top)
assertEvents(
{ arrayOf(topFile, subFile, sideFile).forEach { it.writeText("newer content") } },
mapOf(topFile to 'U', subFile to 'U', sideFile to 'U'))
unwatch(requestForTopDir)
assertEvents(
{ arrayOf(topFile, subFile, sideFile).forEach { it.writeText("newest content") } },
mapOf(subFile to 'U', sideFile to 'U'))
assertEvents(
{ arrayOf(topFile, subFile, sideFile).forEach { it.delete() } },
mapOf(topFile to 'D', subFile to 'D', sideFile to 'D'))
}
// ensure that flat roots set via symbolic paths behave correctly and do not report dirty files returned from other recursive roots
@Test fun testSymbolicLinkIntoFlatRoot() {
val root = tempDir.newFolder("root")
val cDir = tempDir.newFolder("root/A/B/C")
val aLink = IoTestUtil.createSymLink("${root.path}/A", "${root.path}/aLink")
val flatWatchedFile = tempDir.newFile("root/aLink/test.txt")
val fileOutsideFlatWatchRoot = tempDir.newFile("root/A/B/C/test.txt")
refresh(root)
watch(aLink, false)
watch(cDir, false)
assertEvents({ flatWatchedFile.writeText("new content") }, mapOf(flatWatchedFile to 'U'))
assertEvents({ fileOutsideFlatWatchRoot.writeText("new content") }, mapOf(fileOutsideFlatWatchRoot to 'U'))
}
@Test fun testMultipleSymbolicLinkPathsToFile() {
val root = tempDir.newFolder("root")
val file = tempDir.newFile("root/A/B/C/test.txt")
val bLink = IoTestUtil.createSymLink("${root.path}/A/B", "${root.path}/bLink")
val cLink = IoTestUtil.createSymLink("${root.path}/A/B/C", "${root.path}/cLink")
refresh(root)
val bFilePath = File(bLink.path, "C/${file.name}")
val cFilePath = File(cLink.path, file.name)
watch(bLink)
watch(cLink)
assertEvents({ file.writeText("new content") }, mapOf(bFilePath to 'U', cFilePath to 'U'))
assertEvents({ file.delete() }, mapOf(bFilePath to 'D', cFilePath to 'D'))
assertEvents({ file.writeText("re-creation") }, mapOf(bFilePath to 'C', cFilePath to 'C'))
}
@Test fun testSymbolicLinkAboveWatchRoot() {
val top = tempDir.newFolder("top")
val file = tempDir.newFile("top/dir1/dir2/dir3/test.txt")
val link = IoTestUtil.createSymLink("${top.path}/dir1/dir2", "${top.path}/link")
val fileLink = File(top, "link/dir3/test.txt")
refresh(top)
watch(link)
assertEvents({ file.writeText("new content") }, mapOf(fileLink to 'U'))
assertEvents({ file.delete() }, mapOf(fileLink to 'D'))
assertEvents({ file.writeText("re-creation") }, mapOf(fileLink to 'C'))
}
/*
public void testSymlinkBelowWatchRoot() throws Exception {
final File targetDir = FileUtil.createTempDirectory("top.", null);
final File file = FileUtil.createTempFile(targetDir, "test.", ".txt");
final File linkDir = FileUtil.createTempDirectory("link.", null);
final File link = new File(linkDir, "link");
IoTestUtil.createTempLink(targetDir.getPath(), link.getPath());
final File fileLink = new File(link, file.getName());
refresh(targetDir);
refresh(linkDir);
final LocalFileSystem.WatchRequest request = watch(linkDir);
try {
myAccept = true;
FileUtil.writeToFile(file, "new content");
assertEvent(VFileContentChangeEvent.class, fileLink.getPath());
myAccept = true;
FileUtil.delete(file);
assertEvent(VFileDeleteEvent.class, fileLink.getPath());
myAccept = true;
FileUtil.writeToFile(file, "re-creation");
assertEvent(VFileCreateEvent.class, fileLink.getPath());
}
finally {
myFileSystem.removeWatchedRoot(request);
delete(linkDir);
delete(targetDir);
}
}
*/
@Test fun testSubst() {
assumeTrue(SystemInfo.isWindows)
val target = tempDir.newFolder("top")
val file = tempDir.newFile("top/sub/test.txt")
val substRoot = IoTestUtil.createSubst(target.path)
VfsRootAccess.allowRootAccess(testRootDisposable, substRoot.path)
val vfsRoot = fs.findFileByIoFile(substRoot)!!
watchedPaths += substRoot.path
val substFile = File(substRoot, "sub/test.txt")
refresh(target)
refresh(substRoot)
try {
watch(substRoot)
assertEvents({ file.writeText("new content") }, mapOf(substFile to 'U'))
val request = watch(target)
assertEvents({ file.writeText("updated content") }, mapOf(file to 'U', substFile to 'U'))
assertEvents({ file.delete() }, mapOf(file to 'D', substFile to 'D'))
unwatch(request)
assertEvents({ file.writeText("re-creation") }, mapOf(substFile to 'C'))
}
finally {
IoTestUtil.deleteSubst(substRoot.path)
(vfsRoot as NewVirtualFile).markDirty()
fs.refresh(false)
}
}
@Test fun testDirectoryRecreation() {
val root = tempDir.newFolder("root")
val dir = tempDir.newFolder("root/dir")
val file1 = tempDir.newFile("root/dir/file1.txt")
val file2 = tempDir.newFile("root/dir/file2.txt")
refresh(root)
watch(root)
assertEvents(
{ dir.deleteRecursively(); dir.mkdir(); arrayOf(file1, file2).forEach { it.writeText("text") } },
mapOf(file1 to 'U', file2 to 'U'))
}
@Test fun testWatchRootRecreation() {
val root = tempDir.newFolder("root")
val file1 = tempDir.newFile("root/file1.txt")
val file2 = tempDir.newFile("root/file2.txt")
refresh(root)
watch(root)
assertEvents(
{
root.deleteRecursively(); root.mkdir()
if (SystemInfo.isLinux) TimeoutUtil.sleep(1500) // implementation specific
arrayOf(file1, file2).forEach { it.writeText("text") }
},
mapOf(file1 to 'U', file2 to 'U'))
}
@Test fun testWatchNonExistingRoot() {
val top = File(tempDir.root, "top")
val root = File(tempDir.root, "top/d1/d2/d3/root")
refresh(tempDir.root)
watch(root)
assertEvents({ root.mkdirs() }, mapOf(top to 'C'))
}
@Test fun testWatchRootRenameRemove() {
val top = tempDir.newFolder("top")
val root = tempDir.newFolder("top/d1/d2/d3/root")
val root2 = File(top, "_root")
refresh(top)
watch(root)
assertEvents({ root.renameTo(root2) }, mapOf(root to 'D', root2 to 'C'))
assertEvents({ root2.renameTo(root) }, mapOf(root to 'C', root2 to 'D'))
assertEvents({ root.deleteRecursively() }, mapOf(root to 'D'))
assertEvents({ root.mkdirs() }, mapOf(root to 'C'))
assertEvents({ top.deleteRecursively() }, mapOf(top to 'D'))
assertEvents({ root.mkdirs() }, mapOf(top to 'C'))
}
@Test fun testSwitchingToFsRoot() {
val top = tempDir.newFolder("top")
val root = tempDir.newFolder("top/root")
val file1 = tempDir.newFile("top/1.txt")
val file2 = tempDir.newFile("top/root/2.txt")
refresh(top)
val fsRoot = File(if (SystemInfo.isUnix) "/" else top.path.substring(0, 3))
assertTrue(fsRoot.exists(), "can't guess root of " + top)
val request = watch(root)
assertEvents({ arrayOf(file1, file2).forEach { it.writeText("new content") } }, mapOf(file2 to 'U'))
val rootRequest = watch(fsRoot)
assertEvents({ arrayOf(file1, file2).forEach { it.writeText("12345") } }, mapOf(file1 to 'U', file2 to 'U'), SHORT_PROCESS_DELAY)
unwatch(rootRequest)
assertEvents({ arrayOf(file1, file2).forEach { it.writeText("") } }, mapOf(file2 to 'U'))
unwatch(request)
assertEvents({ arrayOf(file1, file2).forEach { it.writeText("xyz") } }, mapOf(), SHORT_PROCESS_DELAY)
}
@Test fun testLineBreaksInName() {
assumeTrue(SystemInfo.isUnix)
val root = tempDir.newFolder("root")
val file = tempDir.newFile("root/weird\ndir\nname/weird\nfile\nname")
refresh(root)
watch(root)
assertEvents({ file.writeText("abc") }, mapOf(file to 'U'))
}
@Test fun testHiddenFiles() {
assumeTrue(SystemInfo.isWindows)
val root = tempDir.newFolder("root")
val file = tempDir.newFile("root/dir/file")
refresh(root)
watch(root)
assertEvents({ IoTestUtil.setHidden(file.path, true) }, mapOf(file to 'P'))
}
@Test fun testFileCaseChange() {
assumeTrue(!SystemInfo.isFileSystemCaseSensitive)
val root = tempDir.newFolder("root")
val file = tempDir.newFile("root/file.txt")
val newFile = File(file.parent, StringUtil.capitalize(file.name))
refresh(root)
watch(root)
assertEvents({ file.renameTo(newFile) }, mapOf(newFile to 'P'))
}
// tests the same scenarios with an active file watcher (prevents explicit marking of refreshed paths)
@Test fun testPartialRefresh() = LocalFileSystemTest.doTestPartialRefresh(tempDir.newFolder("top"))
@Test fun testInterruptedRefresh() = LocalFileSystemTest.doTestInterruptedRefresh(tempDir.newFolder("top"))
@Test fun testRefreshAndFindFile() = LocalFileSystemTest.doTestRefreshAndFindFile(tempDir.newFolder("top"))
@Test fun testRefreshEquality() = LocalFileSystemTest.doTestRefreshEquality(tempDir.newFolder("top"))
@Test fun testUnicodePaths() {
val root = tempDir.newFolder(UNICODE_NAME_1)
val file = tempDir.newFile("${UNICODE_NAME_1}/${UNICODE_NAME_2}.txt")
refresh(root)
watch(root)
assertEvents({ file.writeText("abc") }, mapOf(file to 'U'))
}
@Test fun testDisplacementByIsomorphicTree() {
assumeTrue(!SystemInfo.isMac)
val top = tempDir.newFolder("top")
val root = tempDir.newFolder("top/root")
val file = tempDir.newFile("top/root/middle/file.txt")
file.writeText("original content")
val root_copy = File(top, "root_copy")
root.copyRecursively(root_copy)
file.writeText("new content")
val root_bak = File(top, "root.bak")
val vFile = fs.refreshAndFindFileByIoFile(file)!!
assertEquals("new content", VfsUtilCore.loadText(vFile))
watch(root)
assertEvents({ root.renameTo(root_bak); root_copy.renameTo(root) }, mapOf(file to 'U'))
assertTrue(vFile.isValid)
assertEquals("original content", VfsUtilCore.loadText(vFile))
}
@Test fun testWatchRootReplacement() {
val root1 = tempDir.newFolder("top/root1")
val root2 = tempDir.newFolder("top/root2")
val file1 = tempDir.newFile("top/root1/file.txt")
val file2 = tempDir.newFile("top/root2/file.txt")
refresh(file1)
refresh(file2)
val request = watch(root1)
assertEvents({ arrayOf(file1, file2).forEach { it.writeText("data") } }, mapOf(file1 to 'U'))
fs.replaceWatchedRoot(request, root2.path, true)
wait { watcher.isSettingRoots }
assertEvents({ arrayOf(file1, file2).forEach { it.writeText("more data") } }, mapOf(file2 to 'U'))
}
@Test fun testPermissionUpdate() {
val file = tempDir.newFile("test.txt")
val vFile = refresh(file)
assertTrue(vFile.isWritable)
val ro = if (SystemInfo.isWindows) arrayOf("attrib", "+R", file.path) else arrayOf("chmod", "500", file.path)
val rw = if (SystemInfo.isWindows) arrayOf("attrib", "-R", file.path) else arrayOf("chmod", "700", file.path)
watch(file)
assertEvents({ PlatformTestUtil.assertSuccessful(GeneralCommandLine(*ro)) }, mapOf(file to 'P'))
assertFalse(vFile.isWritable)
assertEvents({ PlatformTestUtil.assertSuccessful(GeneralCommandLine(*rw)) }, mapOf(file to 'P'))
assertTrue(vFile.isWritable)
}
@Test fun testSyncRefreshNonWatchedFile() {
val file = tempDir.newFile("test.txt")
val vFile = refresh(file)
file.writeText("new content")
assertThat(VfsTestUtil.print(VfsTestUtil.getEvents { vFile.refresh(false, false) })).containsOnly("U : ${vFile.path}")
}
//<editor-fold desc="Helpers">
private fun wait(timeout: Long = START_STOP_DELAY, condition: () -> Boolean) {
val stopAt = System.currentTimeMillis() + timeout
while (condition()) {
assertTrue(System.currentTimeMillis() < stopAt, "operation timed out")
TimeoutUtil.sleep(10)
}
}
private fun watch(file: File, recursive: Boolean = true): LocalFileSystem.WatchRequest {
val request = fs.addRootToWatch(file.path, recursive)!!
wait { watcher.isSettingRoots }
return request
}
private fun unwatch(request: LocalFileSystem.WatchRequest) {
fs.removeWatchedRoot(request)
wait { watcher.isSettingRoots }
fs.refresh(false)
}
private fun refresh(file: File): VirtualFile {
val vFile = fs.refreshAndFindFileByIoFile(file)!!
VfsUtilCore.visitChildrenRecursively(vFile, object : VirtualFileVisitor<Any>() {
override fun visitFile(file: VirtualFile): Boolean { file.children; return true }
})
vFile.refresh(false, true)
return vFile
}
private fun assertEvents(action: () -> Unit, expectedOps: Map<File, Char>, timeout: Long = NATIVE_PROCESS_DELAY) {
LOG.debug("** waiting for ${expectedOps}")
watcherEvents.down()
alarm.cancelAllRequests()
resetHappened.set(false)
if (SystemInfo.isWindows || SystemInfo.isMac) TimeoutUtil.sleep(250)
action()
LOG.debug("** action performed")
watcherEvents.waitFor(timeout)
watcherEvents.up()
assumeFalse("reset happened", resetHappened.get())
LOG.debug("** done waiting")
val events = VfsTestUtil.getEvents { fs.refresh(false) }
val expected = expectedOps.entries.map { "${it.value} : ${FileUtil.toSystemIndependentName(it.key.path)}" }.sorted()
val actual = VfsTestUtil.print(events).sorted()
assertEquals(expected, actual)
}
//</editor-fold>
} | platform/platform-tests/testSrc/com/intellij/openapi/vfs/local/FileWatcherTest.kt | 2828277628 |
package com.collave.workbench.common.android.activity
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import com.collave.workbench.common.android.base.BaseActivity
import com.collave.workbench.common.android.extension.fragmentManagerTransact
/**
* Created by Andrew on 6/2/2017.
*/
abstract class FragmentContainerActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
fragmentManagerTransact {
add(android.R.id.content, getStartingFragment())
}
}
abstract fun getStartingFragment(): Fragment
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val fragments = supportFragmentManager.fragments ?: return
fragments
.asSequence()
.filterNotNull()
.distinct()
.filter { it.isResumed }
.forEach { it.onActivityResult(requestCode, resultCode, data) }
}
} | library/src/main/kotlin/com/collave/workbench/common/android/activity/FragmentContainerActivity.kt | 1972050845 |
package ru.bartwell.exfilepicker.ui
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Environment
import androidx.documentfile.provider.DocumentFile
import ru.bartwell.exfilepicker.ExFilePicker
import ru.bartwell.exfilepicker.core.BaseViewModel
import ru.bartwell.exfilepicker.core.extension.findActivity
import ru.bartwell.exfilepicker.core.extension.resolvePath
import ru.bartwell.exfilepicker.data.FileInfo
import ru.bartwell.exfilepicker.data.config.Config
import java.io.File
internal class MainScreenViewModel(
private val context: Context,
config: Config
) : BaseViewModel<MainScreenState>(MainScreenState(config = config)) {
init {
if (state.config.startDirectory == null) {
val storagePath = Environment.getExternalStorageDirectory().absolutePath
updateState { copy(currentDirectory = storagePath) }
}
readDir()
}
private fun readDir() {
val files = DocumentFile.fromFile(File(state.currentDirectory))
.listFiles()
.mapNotNull { documentFile ->
documentFile.resolvePath(context)?.let { path ->
val file = File(path)
FileInfo(
fileName = documentFile.name.orEmpty(),
parentDirectory = file.parent.orEmpty(),
absolutePath = file.absolutePath,
isDirectory = documentFile.isDirectory,
size = documentFile.length(),
lastModifiedMillis = documentFile.lastModified(),
)
}
}
updateState { copy(files = files) }
}
fun onItemClick(position: Int) {
context.findActivity()?.let { activity ->
val result = arrayOf(state.files[position])
.map { it.absolutePath }
.toTypedArray()
val intent = Intent()
intent.putExtra(ExFilePicker.EXTRA_RESULT, result)
activity.setResult(Activity.RESULT_OK, intent)
activity.finish()
}
}
}
internal data class MainScreenState(
val config: Config,
val currentDirectory: String = config.startDirectory.orEmpty(),
val files: List<FileInfo> = emptyList(),
)
| library/src/main/java/ru/bartwell/exfilepicker/ui/MainScreenViewModel.kt | 4067394703 |
package kscript.app.model
enum class ScriptSource { FILE, HTTP, STD_INPUT, OTHER_FILE, PARAMETER }
| src/main/kotlin/kscript/app/model/ScriptSource.kt | 3099789813 |
package life.shank
interface ShankModule
object Shank {
internal val scopedInstancesClearActions = HashSet<(Any?) -> Unit>()
val internalSingletonInstanceCache by lazy { HashcodeHashMap<Any?>() }
val internalInstancesInScopesCache = HashcodeHashMap<HashcodeHashMap<Any?>>()
fun addScopedInstanceClearAction(action: (Any?) -> Unit) {
scopedInstancesClearActions.add(action)
}
fun removeScopedInstanceClearAction(action: (Any?) -> Unit) {
scopedInstancesClearActions.remove(action)
}
}
| core/src/main/java/life/shank/Shank.kt | 358008717 |
package com.bubelov.coins.model
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class Location(
val latitude: Double,
val longitude: Double
) : Parcelable | app/src/main/java/com/bubelov/coins/model/Location.kt | 1933189639 |
package cz.cuni.lf1.thunderstorm.parser
internal class FormulaParserException(message: String, thr: Throwable? = null) : Exception(message, thr)
| src/main/kotlin/cz/cuni/lf1/thunderstorm/parser/FormulaParserException.kt | 3207596544 |
/*
* AOPApplication 2016-05-13
* Copyright (c) 2016 hujiang Co.Ltd. All right reserved(http://www.hujiang.com).
*
*/
package com.firefly1126.permissionaspect.demo
import android.app.Application
import android.content.Context
import android.support.multidex.MultiDex
import com.firefly1126.permissionaspect.PermissionCheckSDK
/**
* class description here
* @author simon
* *
* @version 1.0.0
* *
* @since 2016-05-13
*/
class AOPApplication : Application() {
override fun onCreate() {
super.onCreate()
PermissionCheckSDK.init(this@AOPApplication)
}
override fun attachBaseContext(base: Context) {
super.attachBaseContext(base)
MultiDex.install(this)
}
// @NeedPermission(permissions = {Manifest.permission.READ_PHONE_STATE})
// private void requestPermission() {
// }
} | app/src/main/kotlin/com/firefly1126/permissionaspect/demo/AOPApplication.kt | 3813556463 |
package com.sbg.arena.core.input
import com.sbg.arena.core.geom.Point
import com.sbg.arena.core.Level
import com.sbg.arena.core.InputType
import com.sbg.arena.core.Player
import com.sbg.arena.core.Direction
import kotlin.properties.Delegates
class MoveRequest(val level: Level, val player: Player, val direction: Direction): InputRequest {
var destination: Point by Delegates.notNull()
override fun initialize() {
destination = when (direction) {
Direction.North -> level.playerCoordinates.let { Point(it.x, it.y - 1) }
Direction.South -> level.playerCoordinates.let { Point(it.x, it.y + 1) }
Direction.East -> level.playerCoordinates.let { Point(it.x + 1, it.y) }
Direction.West -> level.playerCoordinates.let { Point(it.x - 1, it.y) }
}
}
override fun isValid() = (level.isWithinBounds(destination) && level[destination].isFloor())
override fun execute() = level.movePlayer(destination)
} | src/main/java/com/sbg/arena/core/input/MoveRequest.kt | 2318162599 |
/*
* 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.players.bukkit.command.profile
import com.rpkit.core.command.RPKCommandExecutor
import com.rpkit.core.command.result.*
import com.rpkit.core.command.sender.RPKCommandSender
import com.rpkit.core.service.Services
import com.rpkit.players.bukkit.RPKPlayersBukkit
import com.rpkit.players.bukkit.command.result.NoProfileSelfFailure
import com.rpkit.players.bukkit.command.result.NotAPlayerFailure
import com.rpkit.players.bukkit.profile.RPKProfile
import com.rpkit.players.bukkit.profile.RPKProfileName
import com.rpkit.players.bukkit.profile.RPKProfileService
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfile
import java.util.concurrent.CompletableFuture
class ProfileSetNameCommand(private val plugin: RPKPlayersBukkit) : RPKCommandExecutor {
class InvalidNameFailure : CommandFailure()
override fun onCommand(sender: RPKCommandSender, args: Array<out String>): CompletableFuture<CommandResult> {
if (args.isEmpty()) {
sender.sendMessage(plugin.messages.profileSetNameUsage)
return CompletableFuture.completedFuture(IncorrectUsageFailure())
}
if (sender !is RPKMinecraftProfile) {
sender.sendMessage(plugin.messages.notFromConsole)
return CompletableFuture.completedFuture(NotAPlayerFailure())
}
val profile = sender.profile
if (profile !is RPKProfile) {
sender.sendMessage(plugin.messages.noProfileSelf)
return CompletableFuture.completedFuture(NoProfileSelfFailure())
}
val name = RPKProfileName(args[0])
if (!name.value.matches(Regex("[A-z0-9_]{3,16}"))) {
sender.sendMessage(plugin.messages.profileSetNameInvalidName)
return CompletableFuture.completedFuture(InvalidNameFailure())
}
val profileService = Services[RPKProfileService::class.java]
if (profileService == null) {
sender.sendMessage(plugin.messages.noProfileService)
return CompletableFuture.completedFuture(MissingServiceFailure(RPKProfileService::class.java))
}
profile.name = name
profileService.generateDiscriminatorFor(name).thenAccept { discriminator ->
profile.discriminator = discriminator
profileService.updateProfile(profile)
sender.sendMessage(plugin.messages.profileSetNameValid.withParameters(name = name))
}
return CompletableFuture.completedFuture(CommandSuccess)
}
} | bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/command/profile/ProfileSetNameCommand.kt | 1002413688 |
/*
* Copyright 2020 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.characters.bukkit.event.character
import com.rpkit.characters.bukkit.character.RPKCharacter
import com.rpkit.core.bukkit.event.RPKBukkitEvent
import org.bukkit.event.Cancellable
import org.bukkit.event.HandlerList
class RPKBukkitCharacterDeleteEvent(
override val character: RPKCharacter,
isAsync: Boolean
) : RPKBukkitEvent(isAsync), RPKCharacterDeleteEvent, Cancellable {
companion object {
@JvmStatic
val handlerList = HandlerList()
}
private var cancel: Boolean = false
override fun isCancelled(): Boolean {
return cancel
}
override fun setCancelled(cancel: Boolean) {
this.cancel = cancel
}
override fun getHandlers(): HandlerList {
return handlerList
}
} | bukkit/rpk-character-lib-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/event/character/RPKBukkitCharacterDeleteEvent.kt | 1948403267 |
/*
* Copyright (c) 2020 Giorgio Antonioli
*
* 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.fondesa.recyclerviewdivider.tint
import androidx.annotation.ColorInt
import androidx.annotation.VisibleForTesting
import com.fondesa.recyclerviewdivider.Divider
import com.fondesa.recyclerviewdivider.Grid
/**
* Implementation of [TintProvider] which provides the same tint color for each divider.
*
* @param dividerTintColor the tint color of each divider or null if the dividers shouldn't be tinted.
*/
internal class TintProviderImpl(@[VisibleForTesting ColorInt] internal val dividerTintColor: Int?) : TintProvider {
@ColorInt
override fun getDividerTintColor(grid: Grid, divider: Divider): Int? = dividerTintColor
}
| recycler-view-divider/src/main/kotlin/com/fondesa/recyclerviewdivider/tint/TintProviderImpl.kt | 1317365413 |
package test.assertk.assertions
import assertk.assertThat
import assertk.assertions.*
import test.assertk.opentestPackageName
import assertk.assertions.support.show
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
$T:$N:$E = FloatArray:floatArray:Float, DoubleArray:doubleArray:Double
class $TContainsTest {
//region contains
@Test fun contains_element_present_passes() {
assertThat($NOf(1.to$E(), 2.to$E())).contains(2.to$E())
}
@Test fun contains_nan_present_passes() {
assertThat($NOf($E.NaN)).contains($E.NaN)
}
@Test fun contains_element_missing_fails() {
val error = assertFails {
assertThat($NOf()).contains(1.to$E())
}
assertEquals("expected to contain:<${show(1.to$E(), "")}> but was:<[]>", error.message)
}
//endregion
//region doesNotContain
@Test fun doesNotContain_element_missing_passes() {
assertThat($NOf()).doesNotContain(1.to$E())
}
@Test fun doesNotContain_element_present_fails() {
val error = assertFails {
assertThat($NOf(1.to$E(), 2.to$E())).doesNotContain(2.to$E())
}
assertEquals("expected to not contain:<${show(2.to$E(), "")}> but was:<[${show(1.to$E(), "")}, ${show(2.to$E(), "")}]>", error.message)
}
@Test fun doesNotContain_nan_present_fails() {
val error = assertFails {
assertThat($NOf($E.NaN)).doesNotContain($E.NaN)
}
assertEquals("expected to not contain:<${show($E.NaN, "")}> but was:<[${show($E.NaN, "")}]>", error.message)
}
//endregion
//region containsNone
@Test fun containsNone_missing_elements_passes() {
assertThat($NOf()).containsNone(1.to$E())
}
@Test fun containsNone_present_element_fails() {
val error = assertFails {
assertThat($NOf(1.to$E(), 2.to$E())).containsNone(2.to$E(), 3.to$E())
}
assertEquals(
"""expected to contain none of:<[${show(2.to$E(), "")}, ${show(3.to$E(), "")}]> but was:<[${show(1.to$E(), "")}, ${show(2.to$E(), "")}]>
| elements not expected:<[${show(2.to$E(), "")}]>
""".trimMargin(), error.message
)
}
//region
//region containsAll
@Test fun containsAll_all_elements_passes() {
assertThat($NOf(1.to$E(), 2.to$E())).containsAll(2.to$E(), 1.to$E())
}
@Test fun containsAll_some_elements_fails() {
val error = assertFails {
assertThat($NOf(1.to$E())).containsAll(1.to$E(), 2.to$E())
}
assertEquals(
"""expected to contain all:<[${show(1.to$E(), "")}, ${show(2.to$E(), "")}]> but was:<[${show(1.to$E(), "")}]>
| elements not found:<[${show(2.to$E(), "")}]>
""".trimMargin(), error.message
)
}
//endregion
//region containsOnly
@Test fun containsOnly_only_elements_passes() {
assertThat($NOf(1.to$E(), 2.to$E())).containsOnly(2.to$E(), 1.to$E())
}
@Test fun containsOnly_duplicate_elements_passes() {
assertThat($NOf(1.to$E(), 2.to$E(), 2.to$E())).containsOnly(2.to$E(), 1.to$E())
}
@Test fun containsOnly_duplicate_elements_passes2() {
assertThat($NOf(1.to$E(), 2.to$E())).containsOnly(2.to$E(), 2.to$E(), 1.to$E())
}
@Test fun containsOnly_more_elements_fails() {
val error = assertFails {
assertThat($NOf(1.to$E(), 2.to$E(), 3.to$E())).containsOnly(2.to$E(), 1.to$E())
}
assertEquals(
"""expected to contain only:<[${show(2.to$E(), "")}, ${show(1.to$E(), "")}]> but was:<[${show(1.to$E(), "")}, ${show(2.to$E(), "")}, ${show(3.to$E(), "")}]>
| extra elements found:<[${show(3.to$E(), "")}]>
""".trimMargin(), error.message
)
}
@Test fun containsOnly_less_elements_fails() {
val error = assertFails {
assertThat($NOf(1.to$E(), 2.to$E(), 3.to$E())).containsOnly(2.to$E(), 1.to$E(), 3.to$E(), 4.to$E())
}
assertEquals(
"""expected to contain only:<[${show(2.to$E(), "")}, ${show(1.to$E(), "")}, ${show(3.to$E(), "")}, ${show(4.to$E(), "")}]> but was:<[${show(1.to$E(), "")}, ${show(2.to$E(), "")}, ${show(3.to$E(), "")}]>
| elements not found:<[${show(4.to$E(), "")}]>
""".trimMargin(),
error.message
)
}
@Test fun containsOnly_different_elements_fails() {
val error = assertFails {
assertThat($NOf(1.to$E())).containsOnly(2.to$E())
}
assertEquals(
"""expected to contain only:<[${show(2.to$E(), "")}]> but was:<[${show(1.to$E(), "")}]>
| elements not found:<[${show(2.to$E(), "")}]>
| extra elements found:<[${show(1.to$E(), "")}]>
""".trimMargin(),
error.message
)
}
//endregion
//region containsExactly
@Test fun containsExactly_all_elements_in_same_order_passes() {
assertThat($NOf(1.to$E(), 2.to$E())).containsExactly(1.to$E(), 2.to$E())
}
@Test fun containsExactly_all_elements_in_different_order_fails() {
val error = assertFails {
assertThat($NOf(1.to$E(), 2.to$E())).containsExactly(2.to$E(), 1.to$E())
}
assertEquals(
"""expected to contain exactly:<${show(listOf(2.to$E(), 1.to$E()), "")}> but was:<${show(listOf(1.to$E(), 2.to$E()), "")}>
| at index:0 expected:<${show(2.to$E(), "")}>
| at index:1 unexpected:<${show(2.to$E(), "")}>
""".trimMargin(), error.message
)
}
@Test fun containsExactly_missing_element_fails() {
val error = assertFails {
assertThat($NOf(1.to$E(), 2.to$E())).containsExactly(3.to$E())
}
assertEquals(
"""expected to contain exactly:<${show(listOf(3.to$E()), "")}> but was:<${show(listOf(1.to$E(), 2.to$E()), "")}>
| at index:0 expected:<${show(3.to$E(), "")}>
| at index:0 unexpected:<${show(1.to$E(), "")}>
| at index:1 unexpected:<${show(2.to$E(), "")}>
""".trimMargin(), error.message
)
}
@Test fun containsExactly_same_indexes_are_together() {
val error = assertFails {
assertThat($NOf(1.to$E(), 1.to$E())).containsExactly(2.to$E(), 2.to$E())
}
assertEquals(
"""expected to contain exactly:<${show(listOf(2.to$E(), 2.to$E()), "")}> but was:<${show(listOf(1.to$E(), 1.to$E()), "")}>
| at index:0 expected:<${show(2.to$E(), "")}>
| at index:0 unexpected:<${show(1.to$E(), "")}>
| at index:1 expected:<${show(2.to$E(), "")}>
| at index:1 unexpected:<${show(1.to$E(), "")}>
""".trimMargin(), error.message
)
}
@Test fun containsExactly_extra_element_fails() {
val error = assertFails {
assertThat($NOf(1.to$E(), 2.to$E())).containsExactly(1.to$E(), 2.to$E(), 3.to$E())
}
assertEquals(
"""expected to contain exactly:<${show(listOf(1.to$E(), 2.to$E(), 3.to$E()), "")}> but was:<${show(listOf(1.to$E(), 2.to$E()), "")}>
| at index:2 expected:<${show(3.to$E(), "")}>
""".trimMargin(), error.message
)
}
@Test fun containsExactly_missing_element_in_middle_fails() {
val error = assertFails {
assertThat($NOf(1.to$E(), 3.to$E())).containsExactly(1.to$E(), 2.to$E(), 3.to$E())
}
assertEquals(
"""expected to contain exactly:<${show(listOf(1.to$E(), 2.to$E(), 3.to$E()), "")}> but was:<${show(listOf(1.to$E(), 3.to$E()), "")}>
| at index:1 expected:<${show(2.to$E(), "")}>
""".trimMargin(), error.message
)
}
@Test fun containsExactly_extra_element_in_middle_fails() {
val error = assertFails {
assertThat($NOf(1.to$E(), 2.to$E(), 3.to$E())).containsExactly(1.to$E(), 3.to$E())
}
assertEquals(
"""expected to contain exactly:<${show(listOf(1.to$E(), 3.to$E()), "")}> but was:<${show(listOf(1.to$E(), 2.to$E(), 3.to$E()), "")}>
| at index:1 unexpected:<${show(2.to$E(), "")}>
""".trimMargin(), error.message
)
}
//endregion
//region containsExactlyInAnyOrder
@Test fun containsExactlyInAnyOrder_only_elements_passes() {
assertThat($NOf(1.to$E(), 2.to$E())).containsExactlyInAnyOrder(2.to$E(), 1.to$E())
}
@Test fun containsExactlyInAnyOrder_only_elements_passes2() {
assertThat($NOf(1.to$E(), 2.to$E(), 1.to$E())).containsExactlyInAnyOrder(2.to$E(), 1.to$E(), 1.to$E())
}
@Test fun containsExactlyInAnyOrder_duplicate_elements_fails() {
val error = assertFails {
assertThat($NOf(1.to$E(), 2.to$E(), 2.to$E())).containsExactlyInAnyOrder(2.to$E(), 1.to$E())
}
assertEquals(
"""expected to contain exactly in any order:<${show(listOf(2.to$E(), 1.to$E()), "")}> but was:<${show(listOf(1.to$E(), 2.to$E(), 2.to$E()), "")}>
| extra elements found:<[${show(2.to$E(), "")}]>
""".trimMargin(), error.message
)
}
@Test fun containsExactlyInAnyOrder_duplicate_elements_fails2() {
val error = assertFails {
assertThat($NOf(1.to$E(), 2.to$E())).containsExactlyInAnyOrder(2.to$E(), 2.to$E(), 1.to$E())
}
assertEquals(
"""expected to contain exactly in any order:<${show(listOf(2.to$E(), 2.to$E(), 1.to$E()), "")}> but was:<${show(listOf(1.to$E(), 2.to$E()), "")}>
| elements not found:<[${show(2.to$E(), "")}]>
""".trimMargin(), error.message
)
}
@Test fun containsExactlyInAnyOrder_more_elements_fails() {
val error = assertFails {
assertThat($NOf(1.to$E(), 2.to$E(), 3.to$E())).containsExactlyInAnyOrder(2.to$E(), 1.to$E())
}
assertEquals(
"""expected to contain exactly in any order:<${show(listOf(2.to$E(), 1.to$E()), "")}> but was:<${show(listOf(1.to$E(), 2.to$E(), 3.to$E()), "")}>
| extra elements found:<[${show(3.to$E(), "")}]>
""".trimMargin(), error.message
)
}
@Test fun containsExactlyInAnyOrder_less_elements_fails() {
val error = assertFails {
assertThat($NOf(1.to$E(), 2.to$E(), 3.to$E())).containsExactlyInAnyOrder(2.to$E(), 1.to$E(), 3.to$E(), 4.to$E())
}
assertEquals(
"""expected to contain exactly in any order:<${show(listOf(2.to$E(), 1.to$E(), 3.to$E(), 4.to$E()), "")}> but was:<${show(listOf(1.to$E(), 2.to$E(), 3.to$E()), "")}>
| elements not found:<[${show(4.to$E(), "")}]>
""".trimMargin(),
error.message
)
}
@Test fun containsExactlyInAnyOrder_different_elements_fails() {
val error = assertFails {
assertThat($NOf(1.to$E())).containsExactlyInAnyOrder(2.to$E())
}
assertEquals(
"""expected to contain exactly in any order:<[${show(2.to$E(), "")}]> but was:<[${show(1.to$E(), "")}]>
| elements not found:<[${show(2.to$E(), "")}]>
| extra elements found:<[${show(1.to$E(), "")}]>
""".trimMargin(),
error.message
)
}
//endregion
//region each
@Test fun each_empty_list_passes() {
assertThat($NOf()).each { it.isEqualTo(1) }
}
@Test fun each_content_passes() {
assertThat($NOf(1.to$E(), 2.to$E())).each { it.isGreaterThan(0.to$E()) }
}
@Test fun each_non_matching_content_fails() {
val error = assertFails {
assertThat($NOf(1.to$E(), 2.to$E(), 3.to$E())).each { it.isLessThan(2.to$E()) }
}
assertEquals(
"""The following assertions failed (2 failures)
| ${opentestPackageName}AssertionFailedError: expected [[1]] to be less than:<${show(2.to$E(), "")}> but was:<${show(2.to$E(), "")}> ([${show(1.to$E(), "")}, ${show(2.to$E(), "")}, ${show(3.to$E(), "")}])
| ${opentestPackageName}AssertionFailedError: expected [[2]] to be less than:<${show(2.to$E(), "")}> but was:<${show(3.to$E(), "")}> ([${show(1.to$E(), "")}, ${show(2.to$E(), "")}, ${show(3.to$E(), "")}])
""".trimMargin().lines(), error.message!!.lines()
)
}
//endregion
//region index
@Test fun index_successful_assertion_passes() {
assertThat($NOf(1.to$E(), 2.to$E()), name = "subject").index(0).isEqualTo(1.to$E())
}
@Test fun index_unsuccessful_assertion_fails() {
val error = assertFails {
assertThat($NOf(1.to$E(), 2.to$E()), name = "subject").index(0).isGreaterThan(2.to$E())
}
assertEquals(
"expected [subject[0]] to be greater than:<${show(2.to$E(), "")}> but was:<${show(1.to$E(), "")}> ([${show(1.to$E(), "")}, ${show(2.to$E(), "")}])",
error.message
)
}
@Test fun index_out_of_range_fails() {
val error = assertFails {
assertThat($NOf(1.to$E(), 2.to$E()), name = "subject").index(-1).isEqualTo(listOf(1.to$E()))
}
assertEquals("expected [subject] index to be in range:[0-2) but was:<-1>", error.message)
}
//endregion
}
| assertk/src/testTemplate/test/assertk/assertions/FloatArrayContainsTest.kt | 58233488 |
package v_builders
import util.TODO
import kotlin.collections.HashMap
fun buildStringExample(): String {
fun buildString(build: StringBuilder.() -> Unit): String {
val stringBuilder = StringBuilder()
stringBuilder.build()
return stringBuilder.toString()
}
return buildString {
this.append("Numbers: ")
for (i in 1..10) {
// 'this' can be omitted
append(i)
}
}
}
fun todoTask37(): Nothing = TODO(
"""
Task 37.
Uncomment the commented code and make it compile.
Add and implement function 'buildMap' with one parameter (of type extension function) creating a new HashMap,
building it and returning it as a result.
"""
)
fun buildMap(build: HashMap<Int, String>.() -> Unit): HashMap<Int, String>{
val map = HashMap<Int, String>()
map.build()
return map
}
fun task37(): Map<Int, String> {
return buildMap {
put(0, "0")
for (i in 1..10) {
put(i, "$i")
}
}
}
| src/v_builders/_37_StringAndMapBuilders.kt | 3071031964 |
package jsonblob.core.store
import jsonblob.core.id.IdHandler
import java.time.ZoneId
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import java.time.temporal.Temporal
abstract class JsonBlobBase(
private val basePath: String,
private val idResolvers: List<IdHandler<*>>
) {
companion object {
internal val directoryFormat = DateTimeFormatter.ofPattern("yyyy/MM/dd").withZone(ZoneId.from(ZoneOffset.UTC))
}
protected fun resolveTimestamp(id: String) = idResolvers.findLast { it.handles(id) }?.resolveTimestamp(id = id) ?: throw IllegalStateException("No Resolver for '$id'")
protected fun getPrefix(timestamp: Temporal) = "$basePath/${directoryFormat.format(timestamp)}"
} | src/main/kotlin/jsonblob/core/store/JsonBlobBase.kt | 247782627 |
package com.mvcoding.mvp.data
import com.mvcoding.mvp.DataSource
import com.mvcoding.mvp.DataWriter
import io.reactivex.observers.TestObserver
fun <DATA, CACHE> testMemoryDataCache(data: DATA, createDataCache: (DATA?) -> CACHE) where CACHE : DataSource<DATA>, CACHE : DataWriter<DATA> {
testDoesNotEmitAnythingInitiallyIfInitialDataWasNotProvided(createDataCache)
testEmitsInitialValueIfItWasProvided(data, createDataCache)
testEmitsLastValueThatWasWrittenBeforeSubscriptions(data, createDataCache)
testEmitsLastValueThatWasWrittenAfterSubscriptions(null, data, createDataCache)
}
fun <DATA, CACHE> testMemoryDataCacheWithDefaultValue(initialValue: DATA, data: DATA, createDataCache: (DATA?) -> CACHE) where CACHE : DataSource<DATA>, CACHE : DataWriter<DATA> {
testEmitsInitialValueIfItWasProvided(initialValue, createDataCache)
testEmitsLastValueThatWasWrittenBeforeSubscriptions(data, createDataCache)
testEmitsLastValueThatWasWrittenAfterSubscriptions(initialValue, data, createDataCache)
}
internal fun <DATA, CACHE> testDoesNotEmitAnythingInitiallyIfInitialDataWasNotProvided(createDataCache: (DATA?) -> CACHE) where CACHE : DataSource<DATA>, CACHE : DataWriter<DATA> {
val observer = TestObserver.create<DATA>()
val dataCache = createDataCache(null)
dataCache.data().subscribe(observer)
observer.assertNoValues()
}
internal fun <DATA, CACHE> testEmitsInitialValueIfItWasProvided(initialData: DATA, createDataCache: (DATA?) -> CACHE) where CACHE : DataSource<DATA>, CACHE : DataWriter<DATA> {
val observer = TestObserver.create<DATA>()
val dataCache = createDataCache(initialData)
dataCache.data().subscribe(observer)
observer.assertValue(initialData)
}
internal fun <DATA, CACHE> testEmitsLastValueThatWasWrittenBeforeSubscriptions(data: DATA, createDataCache: (DATA?) -> CACHE) where CACHE : DataSource<DATA>, CACHE : DataWriter<DATA> {
val observer = TestObserver.create<DATA>()
val dataCache = createDataCache(null)
dataCache.write(data)
dataCache.data().subscribe(observer)
observer.assertValue(data)
}
internal fun <DATA, CACHE> testEmitsLastValueThatWasWrittenAfterSubscriptions(initialData: DATA?, data: DATA, createDataCache: (DATA?) -> CACHE) where CACHE : DataSource<DATA>, CACHE : DataWriter<DATA> {
val observer1 = TestObserver.create<DATA>()
val observer2 = TestObserver.create<DATA>()
val dataCache = createDataCache(null)
dataCache.data().subscribe(observer1)
dataCache.data().subscribe(observer2)
dataCache.write(data)
if (initialData != null) {
observer1.assertValues(initialData, data)
observer2.assertValues(initialData, data)
} else {
observer1.assertValue(data)
observer2.assertValue(data)
}
} | mvp-test/src/main/kotlin/com/mvcoding/mvp/data/MemoryDataCacheTestFunctions.kt | 1652200369 |
package de.mineformers.bitreplicator.network
import de.mineformers.bitreplicator.block.Replicator
import io.netty.buffer.ByteBuf
import net.minecraft.util.math.BlockPos
import net.minecraftforge.fml.common.network.simpleimpl.IMessage
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext
/**
* Message and handler for notifying the server about a mode change in a replicator.
*/
object ReplicatorMode {
/**
* The message simply holds the repliactors's position and the mode to be set.
*/
data class Message(var pos: BlockPos = BlockPos.ORIGIN,
var mode: Int = 0) : IMessage {
override fun toBytes(buf: ByteBuf) {
buf.writeLong(pos.toLong())
buf.writeInt(mode)
}
override fun fromBytes(buf: ByteBuf) {
pos = BlockPos.fromLong(buf.readLong())
mode = buf.readInt()
}
}
object Handler : IMessageHandler<Message, IMessage> {
override fun onMessage(msg: Message, ctx: MessageContext): IMessage? {
val player = ctx.serverHandler.playerEntity
// We interact with the world, hence schedule our action
player.serverWorld.addScheduledTask {
val tile = player.world.getTileEntity(msg.pos)
if (tile is Replicator) {
tile.mode = msg.mode
}
}
return null
}
}
} | src/main/kotlin/de/mineformers/bitreplicator/network/ReplicatorMode.kt | 3272915922 |
/*
* 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.android.text.ui.utils
import android.widget.SeekBar
fun SeekBar.doOnChange(
onStartTrackingTouch: () -> Unit = {},
onStopTrackingTouch: () -> Unit = {},
onProgressChanged: (progress: Int, fromUser: Boolean) -> Unit
) {
setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
onProgressChanged(progress, fromUser)
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
onStartTrackingTouch()
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
onStopTrackingTouch()
}
})
}
| Text/app/src/main/java/com/example/android/text/ui/utils/SeekBar.kt | 1598789446 |
package org.rust.ide.inspections
/**
* Tests for Dangling Else inspection.
*/
class RustDanglingElseInspectionTest : RustInspectionsTestBase() {
fun testSimple() = checkByText<RustDanglingElseInspection>("""
fn main() {
if true {
} <warning descr="Suspicious `else if` formatting">else
if</warning> true {
}
}
""")
fun testElseOnSeparateLine() = checkByText<RustDanglingElseInspection>("""
fn main() {
if true {
}
<warning descr="Suspicious `else if` formatting">else
if</warning> true {
}
}
""")
fun testMultipleNewLines() = checkByText<RustDanglingElseInspection>("""
fn main() {
if true {
} <warning descr="Suspicious `else if` formatting">else
if</warning> true {
}
}
""")
fun testComments() = checkByText<RustDanglingElseInspection>("""
fn main() {
if true {
} <warning descr="Suspicious `else if` formatting">else
// comments
/* inside */
if</warning> true {
}
}
""")
fun testNotAppliedWhenNoIf() = checkByText<RustDanglingElseInspection>("""
fn main() {
if true {
} else {
}
}
""")
fun testNotAppliedWhenNotDangling() = checkByText<RustDanglingElseInspection>("""
fn main() {
if true {
} else if false {
}
}
""")
fun testFixRemoveElse() = checkFixByText<RustDanglingElseInspection>("Remove `else`", """
fn main() {
if true {
} <warning descr="Suspicious `else if` formatting">els<caret>e
if</warning> false {
}
}
""", """
fn main() {
if true {
}
if false {
}
}
""")
fun testFixJoin() = checkFixByText<RustDanglingElseInspection>("Join `else if`", """
fn main() {
if true {
} <warning descr="Suspicious `else if` formatting">else
<caret>if</warning> false {
}
}
""", """
fn main() {
if true {
} else if false {
}
}
""")
}
| src/test/kotlin/org/rust/ide/inspections/RustDanglingElseInspectionTest.kt | 3382525611 |
/*
* Copyright 2018 Michael Rozumyanskiy
*
* 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.michaelrocks.lightsaber.processor.commons
import io.michaelrocks.grip.mirrors.signature.GenericType
fun GenericType.boxed(): GenericType {
if (this !is GenericType.Raw) {
return this
}
val boxedType = type.boxed()
if (boxedType === type) {
return this
}
return GenericType.Raw(boxedType)
}
| processor/src/main/java/io/michaelrocks/lightsaber/processor/commons/GenericTypeExtensions.kt | 1068017581 |
package org.jitsi.jibri.helpers
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.Runs
import org.jitsi.jibri.error.JibriError
import org.jitsi.jibri.selenium.JibriSelenium
import org.jitsi.jibri.status.ComponentState
class SeleniumMockHelper {
private val eventHandlers = mutableListOf<(ComponentState) -> Boolean>()
val mock: JibriSelenium = mockk(relaxed = true) {
every { addTemporaryHandler(capture(eventHandlers)) } just Runs
every { addStatusHandler(captureLambda()) } answers {
// This behavior mimics what's done in StatusPublisher#addStatusHandler
eventHandlers.add {
lambda<(ComponentState) -> Unit>().captured(it)
true
}
}
}
fun startSuccessfully() {
eventHandlers.forEach { it(ComponentState.Running) }
}
fun error(error: JibriError) {
eventHandlers.forEach { it(ComponentState.Error(error)) }
}
}
| src/test/kotlin/org/jitsi/jibri/helpers/SeleniumMockHelper.kt | 3461308179 |
package io.github.droidkaigi.confsched2017.repository.sessions
import com.sys1yagi.kmockito.invoked
import com.sys1yagi.kmockito.mock
import com.sys1yagi.kmockito.verify
import io.github.droidkaigi.confsched2017.api.DroidKaigiClient
import io.github.droidkaigi.confsched2017.model.OrmaDatabase
import io.github.droidkaigi.confsched2017.model.Session
import io.github.droidkaigi.confsched2017.util.LocaleUtil
import io.reactivex.Completable
import io.reactivex.Single
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.*
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import java.util.Date
@RunWith(RobolectricTestRunner::class)
class SessionsRepositoryTest {
@Test
fun hasCacheSessions() {
// false. cache is null.
run {
val repository = SessionsRepository(
SessionsLocalDataSource(mock()),
SessionsRemoteDataSource(mock())
)
assertThat(repository.hasCacheSessions()).isFalse()
}
// false. repository has any cached session, but repository is dirty.
run {
val repository = SessionsRepository(
SessionsLocalDataSource(mock()),
SessionsRemoteDataSource(mock())
)
repository.cachedSessions = mapOf(0 to Session())
repository.setIdDirty(true)
assertThat(repository.hasCacheSessions()).isFalse()
}
// true.
run {
val repository = SessionsRepository(
SessionsLocalDataSource(mock()),
SessionsRemoteDataSource(mock())
)
repository.cachedSessions = mapOf(0 to Session())
repository.setIdDirty(false)
assertThat(repository.hasCacheSessions()).isTrue()
}
}
@Test
fun findAllRemoteRequestAndLocalCache() {
val sessions = listOf(Session())
val client = mockDroidKaigiClient(sessions)
val ormaDatabase = mock<OrmaDatabase>().apply {
transactionAsCompletable(any()).invoked.thenReturn(Completable.complete())
}
val cachedSessions: Map<Int, Session> = spy(mutableMapOf())
val repository = SessionsRepository(
SessionsLocalDataSource(ormaDatabase),
SessionsRemoteDataSource(client)
).apply {
this.cachedSessions = cachedSessions
}
// TODO I want to use enum for language id.
repository.findAll(LocaleUtil.LANG_JA)
.test()
.run {
assertNoErrors()
assertResult(sessions)
assertComplete()
client.verify().getSessions(eq(LocaleUtil.LANG_JA))
ormaDatabase.verify().transactionAsCompletable(any())
cachedSessions.verify(never()).values
}
repository.findAll(LocaleUtil.LANG_JA)
.test()
.run {
assertNoErrors()
assertThat(values().first().size).isEqualTo(1)
assertComplete()
cachedSessions.verify().values
}
}
@Test
fun findAllLocalCache() {
val sessions = listOf(Session())
val client = mockDroidKaigiClient(sessions)
val ormaDatabase = OrmaDatabase
.builder(RuntimeEnvironment.application)
.name(null)
.build()
val cachedSessions: Map<Int, Session> = mock()
val repository = SessionsRepository(
SessionsLocalDataSource(ormaDatabase),
SessionsRemoteDataSource(client)
).apply {
this.cachedSessions = cachedSessions
}
repository.findAll(LocaleUtil.LANG_JA)
.test()
.run {
assertNoErrors()
assertResult(sessions)
assertComplete()
client.verify().getSessions(eq(LocaleUtil.LANG_JA))
cachedSessions.verify(never()).values
}
repository.setIdDirty(true)
repository.findAll(LocaleUtil.LANG_JA)
.test()
.run {
assertNoErrors()
assertThat(values().first().size).isEqualTo(1)
assertComplete()
cachedSessions.verify(never()).values
}
}
@Test
fun hasCacheSession() {
// false cachedSessions is null
run {
val repository = SessionsRepository(
SessionsLocalDataSource(mock()),
SessionsRemoteDataSource(mock())
)
assertThat(repository.hasCacheSession(0)).isFalse()
}
// false sessionId not found
run {
val repository = SessionsRepository(
SessionsLocalDataSource(mock()),
SessionsRemoteDataSource(mock())
)
repository.cachedSessions = mapOf(1 to Session())
repository.setIdDirty(false)
assertThat(repository.hasCacheSession(0)).isFalse()
}
// false dirty
run {
val repository = SessionsRepository(
SessionsLocalDataSource(mock()),
SessionsRemoteDataSource(mock())
)
repository.cachedSessions = mapOf(1 to Session())
repository.setIdDirty(true)
assertThat(repository.hasCacheSession(1)).isFalse()
}
// true
run {
val repository = SessionsRepository(
SessionsLocalDataSource(mock()),
SessionsRemoteDataSource(mock())
)
repository.cachedSessions = mapOf(1 to Session())
repository.setIdDirty(false)
assertThat(repository.hasCacheSession(1)).isTrue()
}
}
@Test
fun findRemoteRequestSuccess() {
val sessions = listOf(createSession(2), createSession(3))
val client = mockDroidKaigiClient(sessions)
val repository = SessionsRepository(
SessionsLocalDataSource(mock()),
SessionsRemoteDataSource(client)
)
repository.find(3, LocaleUtil.LANG_JA)
.test()
.run {
assertNoErrors()
assertThat(values().first().id).isEqualTo(3)
assertComplete()
}
}
@Test
fun findRemoteRequestNotFound() {
val sessions = listOf(createSession(1), createSession(2))
val client = mockDroidKaigiClient(sessions)
val repository = SessionsRepository(
SessionsLocalDataSource(mock()),
SessionsRemoteDataSource(client)
)
repository.find(3, LocaleUtil.LANG_JA)
.test()
.run {
assertNoErrors()
assertNoValues()
assertComplete()
}
}
@Test
fun findHasSessions() {
val cachedSessions: Map<Int, Session> = spy(mutableMapOf(1 to createSession(1)))
val repository = SessionsRepository(
SessionsLocalDataSource(mock()),
SessionsRemoteDataSource(mock())
).apply {
this.cachedSessions = cachedSessions
}
repository.setIdDirty(false)
repository.find(1, LocaleUtil.LANG_JA)
.test()
.run {
assertNoErrors()
assertThat(values().first().id).isEqualTo(1)
assertComplete()
cachedSessions.verify().get(eq(1))
}
}
@Test
fun findLocalStorage() {
val ormaDatabase = OrmaDatabase
.builder(RuntimeEnvironment.application)
.name(null)
.build()
ormaDatabase
.insertIntoSession(createSession(12).apply {
title = "awesome session"
stime = Date()
etime = Date()
durationMin = 30
type = "android"
})
val cachedSessions: Map<Int, Session> = mock()
val client: DroidKaigiClient = mock()
val repository = SessionsRepository(
SessionsLocalDataSource(ormaDatabase),
SessionsRemoteDataSource(client)
)
repository.cachedSessions = cachedSessions
repository.setIdDirty(false)
repository.find(12, LocaleUtil.LANG_JA)
.test()
.run {
assertNoErrors()
assertThat(values().first().id).isEqualTo(12)
assertComplete()
cachedSessions.verify(never()).get(eq(12))
client.verify(never()).getSessions(anyString())
}
}
fun createSession(sessionId: Int) = Session().apply { id = sessionId }
fun mockDroidKaigiClient(sessions: List<Session>) = mock<DroidKaigiClient>().apply {
getSessions(anyString()).invoked.thenReturn(
Single.just(sessions)
)
}
}
| app/src/test/java/io/github/droidkaigi/confsched2017/repository/sessions/SessionsRepositoryTest.kt | 2106553647 |
package xyz.jmullin.drifter.memory
import com.badlogic.gdx.Gdx
import xyz.jmullin.drifter.extensions.drifter
import xyz.jmullin.drifter.memory.Memory.prefs
object Memory {
val prefs by lazy { Gdx.app.getPreferences(drifter().name)!! }
}
fun getString(key: String, default: String? = null): String {
return if(default == null) prefs.getString(key) else prefs.getString(key, default)
}
fun getInt(key: String, default: Int? = null): Int {
return if(default == null) prefs.getInteger(key) else prefs.getInteger(key, default)
}
fun getFloat(key: String, default: Float? = null): Float {
return if(default == null) prefs.getFloat(key) else prefs.getFloat(key, default)
}
fun getLong(key: String, default: Long? = null): Long {
return if(default == null) prefs.getLong(key) else prefs.getLong(key, default)
}
fun getBoolean(key: String, default: Boolean? = null): Boolean {
return if(default == null) prefs.getBoolean(key) else prefs.getBoolean(key, default)
}
fun forget(key: String) {
prefs.remove(key)
prefs.flush()
}
fun clearMemory() {
prefs.clear()
prefs.flush()
}
fun putString(key: String, value: String) {
prefs.putString(key, value)
prefs.flush()
}
fun putInt(key: String, value: Int) {
prefs.putInteger(key, value)
prefs.flush()
}
fun putFloat(key: String, value: Float) {
prefs.putFloat(key, value)
prefs.flush()
}
fun putLong(key: String, value: Long) {
prefs.putLong(key, value)
prefs.flush()
}
fun putBoolean(key: String, value: Boolean) {
prefs.putBoolean(key, value)
prefs.flush()
} | src/main/kotlin/xyz/jmullin/drifter/memory/Memory.kt | 1513832350 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.navigation
import com.intellij.psi.PsiClass
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
/**
* @author Pavel.Dolgov
*/
class JavaReflectionClassNavigationTest : LightCodeInsightFixtureTestCase() {
override fun getProjectDescriptor(): LightProjectDescriptor =
if (getTestName(false).contains("Java9")) JAVA_9 else super.getProjectDescriptor()
fun testPublicClass() {
myFixture.addClass("package foo.bar; public class PublicClass {}")
doTest("foo.bar.PublicClass")
}
fun testPublicInnerClass() {
myFixture.addClass("package foo.bar; public class PublicClass { public class PublicInnerClass {} }")
doTest("foo.bar.PublicClass.PublicInnerClass")
}
fun testPublicInnerClass2() {
myFixture.addClass("package foo.bar; public class PublicClass { public class PublicInnerClass {} }")
doTest("foo.bar.<caret>PublicClass.PublicInnerClass")
}
fun testPackageLocalClass() {
myFixture.addClass("package foo.bar; class PackageLocalClass {}")
doTest("foo.bar.PackageLocalClass")
}
fun testPrivateInnerClass() {
myFixture.addClass("package foo.bar; public class PublicClass { private class PrivateInnerClass {} }")
doTest("foo.bar.PublicClass.PrivateInnerClass")
}
fun testPrivateInnerClass2() {
myFixture.addClass("package foo.bar; public class PublicClass { private class PrivateInnerClass {} }")
doTest("foo.bar.<caret>PublicClass.PrivateInnerClass")
}
fun testWithClassLoader() {
myFixture.addClass("package foo.bar; public class PublicClass {}")
doTest("foo.bar.<caret>PublicClass.PrivateInnerClass", { "Thread.currentThread().getContextClassLoader().loadClass(\"$it\")" })
}
fun testJava9MethodHandlesLookup() {
myFixture.addClass("package foo.bar; public class PublicClass {}")
doTest("foo.bar.PublicClass", { "java.lang.invoke.MethodHandles.lookup().findClass(\"$it\")" })
}
private fun doTest(className: String, usageFormatter: (String) -> String = { "Class.forName(\"$it\")" }) {
val caretPos = className.indexOf("<caret>")
val atCaret: String
var expectedName = className
if (caretPos >= 0) {
atCaret = className
val dotPos = className.indexOf(".", caretPos + 1)
if (dotPos >= 0) expectedName = className.substring(0, dotPos).replace("<caret>", "")
}
else {
atCaret = className + "<caret>"
}
myFixture.configureByText("Main.java",
"""import foo.bar.*;
class Main {
void foo() throws ReflectiveOperationException {
${usageFormatter(atCaret)};
}
}""")
val reference = myFixture.file.findReferenceAt(myFixture.caretOffset)
assertNotNull("No reference at the caret", reference)
val resolved = reference!!.resolve()
assertTrue("Class not resolved: " + reference.canonicalText, resolved is PsiClass)
val psiClass = resolved as? PsiClass
assertEquals("Class name", expectedName, psiClass?.qualifiedName)
}
}
| java/java-tests/testSrc/com/intellij/codeInsight/navigation/JavaReflectionClassNavigationTest.kt | 817315747 |
package com.xandr.lazyloaddemo
import android.app.Application
import android.widget.Toast
import com.appnexus.opensdk.XandrAd
class MainApplication: Application() {
override fun onCreate() {
super.onCreate()
XandrAd.init(10094, this, true) {
Toast.makeText(this, "Init Completed", Toast.LENGTH_SHORT).show()
}
}
} | examples/kotlin/LazyLoadDemo/app/src/main/java/com/xandr/lazyloaddemo/MainApplication.kt | 128472422 |
package com.ghstudios.android.features.armor.detail
import androidx.lifecycle.ViewModelProvider
import com.ghstudios.android.AssetLoader
import com.ghstudios.android.BasePagerActivity
import com.ghstudios.android.MenuSection
import com.ghstudios.android.mhgendatabase.R
class ArmorSetDetailPagerActivity : BasePagerActivity() {
companion object {
const val EXTRA_ARMOR_ID = "com.daviancorp.android.android.ui.detail.armor_id"
const val EXTRA_FAMILY_ID = "com.daviancorp.android.android.ui.detail.family_id"
}
private val viewModel by lazy {
ViewModelProvider(this).get(ArmorSetDetailViewModel::class.java)
}
override fun getSelectedSection() = MenuSection.ARMOR
override fun onAddTabs(tabs: TabAdder) {
this.hideTabsIfSingular()
this.setTabBehavior(BasePagerActivity.TabBehavior.FIXED)
val armorId = intent.getLongExtra(EXTRA_ARMOR_ID, -1)
val familyId = intent.getLongExtra(EXTRA_FAMILY_ID, -1)
val metadata = when (familyId > -1) {
true -> viewModel.initByFamily(familyId)
false -> viewModel.initByArmor(armorId)
}
title = metadata.first().familyName
val hasSummaryTab = metadata.size > 1
if (hasSummaryTab) {
tabs.addTab(R.string.armor_title_set) { ArmorSetSummaryFragment() }
}
for ((idx, armorData) in metadata.withIndex()) {
val icon = AssetLoader.loadIconFor(armorData)
tabs.addTab("", icon) {
ArmorDetailFragment.newInstance(armorData.id)
}
// If this is the armor we came here for, set it as the default tab
if (armorData.id == armorId) {
val preTabCount = if (hasSummaryTab) 1 else 0
tabs.setDefaultItem(idx + preTabCount)
}
}
}
} | app/src/main/java/com/ghstudios/android/features/armor/detail/ArmorSetDetailPagerActivity.kt | 766594115 |
package com.rartworks.engine.apis
interface LeaderboardServices {
fun getScore(leaderboardId: String? = null, callback: (Int) -> (Unit))
fun getScores(leaderboardId: String? = null, limit: Int = 5, callback: (List<PlayerScore>) -> (Unit))
fun showScores(leaderboardId: String? = null)
fun submitScore(score: Long, leaderboardId: String? = null)
}
| core/src/com/rartworks/engine/apis/LeaderboardServices.kt | 2240993029 |
/*
* Sone - ImageBuilderFactory.kt - Copyright © 2013–2020 David Roden
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.pterodactylus.sone.database
/**
* Factory for [ImageBuilder]s.
*/
interface ImageBuilderFactory {
fun newImageBuilder(): ImageBuilder
}
| src/main/kotlin/net/pterodactylus/sone/database/ImageBuilderFactory.kt | 3756260016 |
// Copyright 2020 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.common
import com.google.common.truth.Truth.assertThat
import com.google.protobuf.ByteString
import kotlin.test.assertFails
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.runBlocking
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class BytesTest {
@Test
fun `ByteString is bidirectionally convertible with Long`() {
val longValue = -3519155157501101422L
val binaryValue = HexString("CF2973078FA9BA92").bytes
assertThat(longValue.toByteString()).isEqualTo(binaryValue)
assertThat(binaryValue.toLong()).isEqualTo(longValue)
}
@Test
fun `ByteString asBufferedFlow with non-full last part`() = runBlocking {
val flow = ByteString.copyFromUtf8("Hello World").asBufferedFlow(3)
assertThat(flow.map { it.toStringUtf8() }.toList())
.containsExactly("Hel", "lo ", "Wor", "ld")
.inOrder()
}
@Test
fun `ByteString asBufferedFlow on empty ByteString`() = runBlocking {
val flow = ByteString.copyFromUtf8("").asBufferedFlow(3)
assertThat(flow.toList()).isEmpty()
}
@Test
fun `ByteString asBufferedFlow with invalid buffer size`(): Unit = runBlocking {
assertFails { ByteString.copyFromUtf8("this should throw").asBufferedFlow(0).toList() }
}
}
| src/test/kotlin/org/wfanet/measurement/common/BytesTest.kt | 4025753402 |
/*
* Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.efficios.jabberwocky.utils
import java.util.*
/**
* Tests for the [SortedCompoundIterator].
*/
class SortedCompoundIteratorTest : SortedCompoundIteratorTestBase() {
override fun <T> provideCompoundIterator(iterators: Collection<Iterator<T>>, comparator: Comparator<T>): Iterator<T> {
return SortedCompoundIterator(iterators, comparator)
}
} | jabberwocky-core/src/test/kotlin/com/efficios/jabberwocky/utils/SortedCompoundIteratorTest.kt | 207614807 |
package org.fossasia.susi.ai.login
import android.app.ProgressDialog
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ArrayAdapter
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_login.*
import org.fossasia.susi.ai.R
import org.fossasia.susi.ai.signup.SignUpActivity
import org.fossasia.susi.ai.chat.ChatActivity
import org.fossasia.susi.ai.forgotpassword.ForgotPasswordActivity
import org.fossasia.susi.ai.helper.AlertboxHelper
import org.fossasia.susi.ai.helper.Constant
import org.fossasia.susi.ai.login.contract.ILoginPresenter
import org.fossasia.susi.ai.login.contract.ILoginView
/**
* <h1>The Login activity.</h1>
* <h2>This activity is used to login into the app.</h2>
*
* Created by chiragw15 on 4/7/17.
*/
class LoginActivity : AppCompatActivity(), ILoginView {
lateinit var loginPresenter: ILoginPresenter
lateinit var progressDialog: ProgressDialog
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
if (savedInstanceState != null) {
email.editText?.setText(savedInstanceState.getCharSequenceArray(Constant.SAVED_STATES)[0].toString())
password.editText?.setText(savedInstanceState.getCharSequenceArray(Constant.SAVED_STATES)[1].toString())
if (savedInstanceState.getBoolean(Constant.SERVER)) {
input_url.visibility = View.VISIBLE
} else {
input_url.visibility = View.GONE
}
}
progressDialog = ProgressDialog(this)
progressDialog.setCancelable(false)
progressDialog.setMessage(getString(R.string.login))
addListeners()
loginPresenter = LoginPresenter(this)
loginPresenter.onAttach(this)
}
override fun onLoginSuccess(message: String?) {
Toast.makeText(this@LoginActivity, message, Toast.LENGTH_SHORT).show()
val intent = Intent(this@LoginActivity, ChatActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
intent.putExtra(Constant.FIRST_TIME, true)
startActivity(intent)
finish()
}
override fun skipLogin() {
val intent = Intent(this@LoginActivity, ChatActivity::class.java)
intent.putExtra(Constant.FIRST_TIME, false)
startActivity(intent)
finish()
}
override fun invalidCredentials(isEmpty: Boolean, what: String) {
if(isEmpty) {
when(what) {
Constant.EMAIL -> email.error = getString(R.string.email_cannot_be_empty)
Constant.PASSWORD -> password.error = getString(R.string.password_cannot_be_empty)
Constant.INPUT_URL -> input_url.error = getString(R.string.url_cannot_be_empty)
}
} else {
when(what) {
Constant.EMAIL -> email.error = getString(R.string.email_invalid_title)
Constant.INPUT_URL -> input_url.error = getString(R.string.invalid_url)
}
}
log_in.isEnabled = true
}
override fun showProgress(boolean: Boolean) {
if (boolean) progressDialog.show() else progressDialog.dismiss()
}
override fun onLoginError(title: String?, message: String?) {
val notSuccessAlertboxHelper = AlertboxHelper(this@LoginActivity, title, message, null, null, getString(R.string.ok), null, Color.BLUE)
notSuccessAlertboxHelper.showAlertBox()
log_in.isEnabled = true
}
override fun attachEmails(savedEmails: MutableSet<String>?) {
if (savedEmails != null)
email_input.setAdapter(ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ArrayList<String>(savedEmails)))
}
fun addListeners() {
showURL()
signUp()
forgotPassword()
skip()
logIn()
cancelLogin()
onEditorAction()
}
fun showURL() {
customer_server.setOnClickListener { input_url.visibility = if(customer_server.isChecked) View.VISIBLE else View.GONE}
}
fun signUp() {
sign_up.setOnClickListener { startActivity(Intent(this@LoginActivity, SignUpActivity::class.java)) }
}
fun forgotPassword() {
forgot_password.setOnClickListener { startActivity(Intent(this@LoginActivity, ForgotPasswordActivity::class.java)) }
}
fun skip() {
skip.setOnClickListener { loginPresenter.skipLogin() }
}
fun logIn() {
log_in.setOnClickListener {
startLogin()
}
}
fun startLogin() {
val stringEmail = email.editText?.text.toString()
val stringPassword = password.editText?.text.toString()
val stringURL = input_url.editText?.text.toString()
log_in.isEnabled = false
email.error = null
password.error = null
input_url.error = null
loginPresenter.login(stringEmail, stringPassword, !customer_server.isChecked, stringURL)
}
fun cancelLogin() {
progressDialog.setOnCancelListener({
loginPresenter.cancelLogin()
log_in.isEnabled = true
})
}
fun onEditorAction(){
password_input.setOnEditorActionListener { _, actionId, _ ->
var handled = false
if (actionId == EditorInfo.IME_ACTION_GO) {
startLogin()
handled = true
}
handled
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
val values = arrayOf<CharSequence>(email.editText?.text.toString(), password.editText?.text.toString())
outState.putCharSequenceArray(Constant.SAVED_STATES, values)
outState.putBoolean(Constant.SERVER, customer_server.isChecked)
}
override fun onDestroy() {
loginPresenter.onDetach()
super.onDestroy()
}
}
| app/src/main/java/org/fossasia/susi/ai/login/LoginActivity.kt | 662160223 |
package de.ph1b.audiobook.data.repo
import de.ph1b.audiobook.data.Book2
import de.ph1b.audiobook.data.BookContent2
import de.ph1b.audiobook.data.Bookmark2
import de.ph1b.audiobook.data.repo.internals.AppDb
import de.ph1b.audiobook.data.repo.internals.dao.BookmarkDao2
import de.ph1b.audiobook.data.repo.internals.transaction
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.time.Instant
import java.time.temporal.ChronoUnit
import javax.inject.Inject
import javax.inject.Singleton
/**
* Provides access to bookmarks.
*/
@Singleton
class BookmarkRepo
@Inject constructor(
private val dao: BookmarkDao2,
private val appDb: AppDb
) {
suspend fun deleteBookmark(id: Bookmark2.Id) {
dao.deleteBookmark(id)
}
suspend fun addBookmark(bookmark: Bookmark2) {
dao.addBookmark(bookmark)
}
suspend fun addBookmarkAtBookPosition(book: Book2, title: String?, setBySleepTimer: Boolean): Bookmark2 {
return withContext(Dispatchers.IO) {
val bookMark = Bookmark2(
title = title,
time = book.content.positionInChapter,
id = Bookmark2.Id.random(),
addedAt = Instant.now().minus(2, ChronoUnit.DAYS),
setBySleepTimer = setBySleepTimer,
chapterId = book.content.currentChapter,
bookId = book.id
)
addBookmark(bookMark)
Timber.v("Added bookmark=$bookMark")
bookMark
}
}
suspend fun bookmarks(book: BookContent2): List<Bookmark2> {
val chapters = book.chapters
// we can only query SQLITE_MAX_VARIABLE_NUMBER at once (999 bugs on some devices so we use a number a little smaller.)
// if it's larger than the limit, we query in chunks.
val limit = 990
return if (chapters.size > limit) {
appDb.transaction {
chapters.chunked(limit).flatMap {
dao.allForFiles(it)
}
}
} else {
dao.allForFiles(chapters)
}
}
}
| data/src/main/kotlin/de/ph1b/audiobook/data/repo/BookmarkRepo.kt | 1612463059 |
package elite.gils.country
/**
* Continent: (Name)
* Country: (Name)
*/
enum class AI 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: AI): String {
return state.name
}
} | ObjectAvoidance/kotlin/src/elite/gils/country/AI.kt | 705009751 |
package elite.gils
class IPvC {
internal var address: Int = 0
internal var value: Int = 0
constructor(a: IPv4) {
value = a.value
}
constructor(a: IPv6) {
value = a.value
}
} | ObjectAvoidance/kotlin/src/elite/gils/IPvC.kt | 2986153216 |
/**
* ownCloud Android client application
*
* @author Juan Carlos Garrote Gascón
*
* Copyright (C) 2021 ownCloud GmbH.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.settings.more
import android.content.Context
import android.content.Intent
import android.content.Intent.EXTRA_SUBJECT
import android.content.Intent.EXTRA_TEXT
import android.net.Uri
import androidx.fragment.app.testing.FragmentScenario
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.preference.Preference
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.intent.Intents.intended
import androidx.test.espresso.intent.matcher.IntentMatchers.hasAction
import androidx.test.espresso.intent.matcher.IntentMatchers.hasData
import androidx.test.espresso.intent.matcher.IntentMatchers.hasExtra
import androidx.test.espresso.intent.matcher.IntentMatchers.hasFlag
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.platform.app.InstrumentationRegistry
import com.owncloud.android.BuildConfig
import com.owncloud.android.R
import com.owncloud.android.presentation.ui.settings.fragments.SettingsMoreFragment
import com.owncloud.android.presentation.viewmodels.settings.SettingsMoreViewModel
import com.owncloud.android.utils.matchers.verifyPreference
import com.owncloud.android.utils.mockIntent
import io.mockk.every
import io.mockk.mockk
import io.mockk.unmockkAll
import org.hamcrest.Matchers.allOf
import org.junit.After
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.core.context.startKoin
import org.koin.core.context.stopKoin
import org.koin.dsl.module
class SettingsMoreFragmentTest {
private lateinit var fragmentScenario: FragmentScenario<SettingsMoreFragment>
private var prefHelp: Preference? = null
private var prefSync: Preference? = null
private var prefRecommend: Preference? = null
private var prefFeedback: Preference? = null
private var prefImprint: Preference? = null
private lateinit var moreViewModel: SettingsMoreViewModel
private lateinit var context: Context
@Before
fun setUp() {
context = InstrumentationRegistry.getInstrumentation().targetContext
moreViewModel = mockk(relaxed = true)
stopKoin()
startKoin {
context
allowOverride(override = true)
modules(
module {
viewModel {
moreViewModel
}
}
)
}
Intents.init()
}
@After
fun tearDown() {
Intents.release()
unmockkAll()
}
private fun getPreference(key: String): Preference? {
var preference: Preference? = null
fragmentScenario.onFragment { fragment ->
preference = fragment.findPreference(key)
}
return preference
}
private fun launchTest(
helpEnabled: Boolean = true,
syncEnabled: Boolean = true,
recommendEnabled: Boolean = true,
feedbackEnabled: Boolean = true,
imprintEnabled: Boolean = true
) {
every { moreViewModel.isHelpEnabled() } returns helpEnabled
every { moreViewModel.isSyncEnabled() } returns syncEnabled
every { moreViewModel.isRecommendEnabled() } returns recommendEnabled
every { moreViewModel.isFeedbackEnabled() } returns feedbackEnabled
every { moreViewModel.isImprintEnabled() } returns imprintEnabled
fragmentScenario = launchFragmentInContainer(themeResId = R.style.Theme_ownCloud)
}
@Test
fun moreView() {
launchTest()
prefHelp = getPreference(PREFERENCE_HELP)
assertNotNull(prefHelp)
prefHelp?.verifyPreference(
keyPref = PREFERENCE_HELP,
titlePref = context.getString(R.string.prefs_help),
visible = true,
enabled = true
)
prefSync = getPreference(PREFERENCE_SYNC_CALENDAR_CONTACTS)
assertNotNull(prefSync)
prefSync?.verifyPreference(
keyPref = PREFERENCE_SYNC_CALENDAR_CONTACTS,
titlePref = context.getString(R.string.prefs_sync_calendar_contacts),
summaryPref = context.getString(R.string.prefs_sync_calendar_contacts_summary),
visible = true,
enabled = true
)
prefRecommend = getPreference(PREFERENCE_RECOMMEND)
assertNotNull(prefRecommend)
prefRecommend?.verifyPreference(
keyPref = PREFERENCE_RECOMMEND,
titlePref = context.getString(R.string.prefs_recommend),
visible = true,
enabled = true
)
prefFeedback = getPreference(PREFERENCE_FEEDBACK)
assertNotNull(prefFeedback)
prefFeedback?.verifyPreference(
keyPref = PREFERENCE_FEEDBACK,
titlePref = context.getString(R.string.prefs_send_feedback),
visible = true,
enabled = true
)
prefImprint = getPreference(PREFERENCE_IMPRINT)
assertNotNull(prefImprint)
prefImprint?.verifyPreference(
keyPref = PREFERENCE_IMPRINT,
titlePref = context.getString(R.string.prefs_imprint),
visible = true,
enabled = true
)
}
@Test
fun helpNotEnabledView() {
launchTest(helpEnabled = false)
prefHelp = getPreference(PREFERENCE_HELP)
assertNull(prefHelp)
}
@Test
fun syncNotEnabledView() {
launchTest(syncEnabled = false)
prefSync = getPreference(PREFERENCE_SYNC_CALENDAR_CONTACTS)
assertNull(prefSync)
}
@Test
fun recommendNotEnabledView() {
launchTest(recommendEnabled = false)
prefRecommend = getPreference(PREFERENCE_RECOMMEND)
assertNull(prefRecommend)
}
@Test
fun feedbackNotEnabledView() {
launchTest(feedbackEnabled = false)
prefFeedback = getPreference(PREFERENCE_FEEDBACK)
assertNull(prefFeedback)
}
@Test
fun imprintNotEnabledView() {
launchTest(imprintEnabled = false)
prefImprint = getPreference(PREFERENCE_IMPRINT)
assertNull(prefImprint)
}
@Test
fun helpOpensNotEmptyUrl() {
every { moreViewModel.getHelpUrl() } returns context.getString(R.string.url_help)
launchTest()
mockIntent(action = Intent.ACTION_VIEW)
onView(withText(R.string.prefs_help)).perform(click())
intended(hasData(context.getString(R.string.url_help)))
}
@Test
fun syncOpensNotEmptyUrl() {
every { moreViewModel.getSyncUrl() } returns context.getString(R.string.url_sync_calendar_contacts)
launchTest()
mockIntent(action = Intent.ACTION_VIEW)
onView(withText(R.string.prefs_sync_calendar_contacts)).perform(click())
intended(hasData(context.getString(R.string.url_sync_calendar_contacts)))
}
@Test
fun recommendOpensSender() {
launchTest()
mockIntent(action = Intent.ACTION_SENDTO)
onView(withText(R.string.prefs_recommend)).perform(click())
// Delay needed since depending on the performance of the device where tests are executed,
// sender can interfere with the subsequent tests
Thread.sleep(1000)
intended(
allOf(
hasAction(Intent.ACTION_SENDTO), hasExtra(
EXTRA_SUBJECT, String.format(
context.getString(R.string.recommend_subject),
context.getString(R.string.app_name)
)
),
hasExtra(
EXTRA_TEXT,
String.format(
context.getString(R.string.recommend_text),
context.getString(R.string.app_name),
context.getString(R.string.url_app_download)
)
),
hasFlag(Intent.FLAG_ACTIVITY_NEW_TASK)
)
)
}
@Test
fun feedbackOpensSender() {
launchTest()
mockIntent(action = Intent.ACTION_SENDTO)
onView(withText(R.string.prefs_send_feedback)).perform(click())
// Delay needed since depending on the performance of the device where tests are executed,
// sender can interfere with the subsequent tests
Thread.sleep(1000)
intended(
allOf(
hasAction(Intent.ACTION_SENDTO),
hasExtra(
EXTRA_SUBJECT,
"Android v" + BuildConfig.VERSION_NAME + " - " + context.getText(R.string.prefs_feedback)
),
hasData(Uri.parse(context.getString(R.string.mail_feedback))),
hasFlag(Intent.FLAG_ACTIVITY_NEW_TASK)
)
)
}
@Test
fun imprintOpensUrl() {
every { moreViewModel.getImprintUrl() } returns "https://owncloud.com/mobile"
launchTest()
mockIntent(action = Intent.ACTION_VIEW)
onView(withText(R.string.prefs_imprint)).perform(click())
intended(hasData("https://owncloud.com/mobile"))
}
companion object {
private const val PREFERENCE_HELP = "help"
private const val PREFERENCE_SYNC_CALENDAR_CONTACTS = "syncCalendarContacts"
private const val PREFERENCE_RECOMMEND = "recommend"
private const val PREFERENCE_FEEDBACK = "feedback"
private const val PREFERENCE_IMPRINT = "imprint"
}
}
| owncloudApp/src/androidTest/java/com/owncloud/android/settings/more/SettingsMoreFragmentTest.kt | 1092838176 |
@file:Suppress("unused")
package cn.thens.kdroid.core.app.res
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.drawable.Drawable
import androidx.annotation.*
import androidx.core.content.ContextCompat
import android.util.DisplayMetrics
import android.view.View
fun Context.colorOf(@ColorRes resId: Int): Int = ContextCompat.getColor(this, resId)
fun Context.colorStateListOf(@ColorRes resId: Int): ColorStateList? = ContextCompat.getColorStateList(this, resId)
fun Context.drawableOf(@DrawableRes resId: Int): Drawable? = ContextCompat.getDrawable(this, resId)
fun Context.stringOf(@StringRes resId: Int): String = getString(resId)
fun Context.dimenOf(@DimenRes resId: Int): Int = resources.getDimensionPixelSize(resId)
fun Context.integerOf(@IntegerRes resId: Int): Int = resources.getInteger(resId)
inline val Context.displayMetrics: DisplayMetrics get() = resources.displayMetrics
fun View.colorOf(@ColorRes resId: Int): Int = context.colorOf(resId)
fun View.colorStateListOf(@ColorRes resId: Int): ColorStateList? = context.colorStateListOf(resId)
fun View.drawableOf(@DrawableRes resId: Int): Drawable? = context.drawableOf(resId)
fun View.stringOf(@StringRes resId: Int): String = context.stringOf(resId)
fun View.dimenOf(@DimenRes resId: Int): Int = context.dimenOf(resId)
fun View.integerOf(@IntegerRes resId: Int): Int = context.integerOf(resId)
inline val View.displayMetrics: DisplayMetrics get() = context.displayMetrics | core/src/main/java/cn/thens/kdroid/core/app/res/Resources.kt | 587473827 |
/*
* Copyright (c) 2021 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.libs
import android.content.Context
import android.graphics.Color
import android.view.View
import android.widget.TextView
import android.widget.Toast
import com.google.android.material.snackbar.Snackbar
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.mockk
import io.mockk.mockkStatic
import io.mockk.unmockkAll
import io.mockk.verify
import jp.toastkid.lib.preference.ColorPair
import org.junit.After
import org.junit.Before
import org.junit.Test
class ToasterTest {
@MockK
private lateinit var toast: Toast
@MockK
private lateinit var snackbar: Snackbar
@MockK
private lateinit var snackbarView: View
@MockK
private lateinit var view: View
@MockK
private lateinit var context: Context
@MockK
private lateinit var colorPair: ColorPair
@Before
fun setUp() {
MockKAnnotations.init(this)
every { toast.show() }.answers { Unit }
mockkStatic(Toast::class)
every { Toast.makeText(any(), any<Int>(), any()) }.returns(toast)
every { Toast.makeText(any(), any<String>(), any()) }.returns(toast)
every { view.getContext() }.returns(context)
every { context.getString(any()) }.returns("test")
mockkStatic(Snackbar::class)
every { Snackbar.make(any(), any<String>(), any()) }.returns(snackbar)
val snackbarContentView = mockk<TextView>()
every { snackbarView.setBackgroundColor(any()) }.answers { Unit }
every { snackbarView.findViewById<View>(any()) }.returns(snackbarContentView)
every { snackbarContentView.setTextColor(any<Int>()) }.answers { Unit }
every { colorPair.fontColor() }.returns(Color.WHITE)
every { colorPair.bgColor() }.returns(Color.BLACK)
every { snackbar.getView() }.returns(snackbarView)
every { snackbar.setAction(any<String>(), any()) }.returns(snackbar)
every { snackbar.show() }.answers { Unit }
}
@After
fun tearDown() {
unmockkAll()
}
@Test
fun testToast() {
Toaster.tShort(mockk(), -1)
verify(exactly = 1) { Toast.makeText(any(), any<Int>(), Toast.LENGTH_SHORT) }
verify(exactly = 0) { Toast.makeText(any(), any<String>(), any()) }
verify(exactly = 1) { toast.show() }
}
@Test
fun testToastShortWithString() {
Toaster.tShort(mockk(), "test")
verify(exactly = 0) { Toast.makeText(any(), any<Int>(), any()) }
verify(exactly = 1) { Toast.makeText(any(), any<String>(), Toast.LENGTH_SHORT) }
verify(exactly = 1) { toast.show() }
}
@Test
fun testSnackShort() {
Toaster.snackShort(view, 1, colorPair)
verify(exactly = 1) { view.getContext() }
verify(exactly = 1) { context.getString(any()) }
verify(exactly = 1) { snackbar.getView() }
verify(exactly = 1) { snackbar.show() }
verify(exactly = 1) { Snackbar.make(any(), any<String>(), Snackbar.LENGTH_SHORT) }
verify(exactly = 1) { snackbarView.setBackgroundColor(any()) }
verify(exactly = 1) { snackbarView.findViewById<View>(any()) }
verify(exactly = 1) { colorPair.fontColor() }
verify(exactly = 1) { colorPair.bgColor() }
}
@Test
fun testSnackShortWithText() {
Toaster.snackShort(view, "test", colorPair)
verify(exactly = 0) { view.getContext() }
verify(exactly = 0) { context.getString(any()) }
verify(exactly = 1) { snackbar.getView() }
verify(exactly = 1) { snackbar.show() }
verify(exactly = 1) { Snackbar.make(any(), any<String>(), Snackbar.LENGTH_SHORT) }
verify(exactly = 1) { snackbarView.setBackgroundColor(any()) }
verify(exactly = 1) { snackbarView.findViewById<View>(any()) }
verify(exactly = 1) { colorPair.fontColor() }
verify(exactly = 1) { colorPair.bgColor() }
}
@Test
fun testSnackIndefinite() {
Toaster.snackIndefinite(view, "test", colorPair)
verify(exactly = 0) { view.getContext() }
verify(exactly = 0) { context.getString(any()) }
verify(exactly = 1) { snackbar.getView() }
verify(exactly = 1) { snackbar.show() }
verify(exactly = 1) { Snackbar.make(any(), any<String>(), Snackbar.LENGTH_INDEFINITE) }
verify(exactly = 1) { snackbarView.setBackgroundColor(any()) }
verify(exactly = 1) { snackbarView.findViewById<View>(any()) }
verify(exactly = 1) { colorPair.fontColor() }
verify(exactly = 1) { colorPair.bgColor() }
}
@Test
fun testSnackLong() {
Toaster.snackLong(view, "test", colorPair)
verify(exactly = 0) { view.getContext() }
verify(exactly = 0) { context.getString(any()) }
verify(exactly = 1) { snackbar.getView() }
verify(exactly = 1) { snackbar.show() }
verify(exactly = 1) { Snackbar.make(any(), any<String>(), Snackbar.LENGTH_LONG) }
verify(exactly = 1) { snackbarView.setBackgroundColor(any()) }
verify(exactly = 1) { snackbarView.findViewById<View>(any()) }
verify(exactly = 1) { colorPair.fontColor() }
verify(exactly = 1) { colorPair.bgColor() }
}
@Test
fun snackLongWithAction() {
Toaster.snackLong(view, "test", -1, View.OnClickListener { }, colorPair)
verify(exactly = 1) { view.getContext() }
verify(exactly = 1) { context.getString(any()) }
verify(exactly = 1) { snackbar.getView() }
verify(exactly = 1) { snackbar.setAction(any<String>(), any()) }
verify(exactly = 1) { snackbar.show() }
verify(exactly = 1) { Snackbar.make(any(), any<String>(), Snackbar.LENGTH_LONG) }
verify(exactly = 1) { snackbarView.setBackgroundColor(any()) }
verify(atLeast = 1) { snackbarView.findViewById<View>(any()) }
verify(atLeast = 1) { colorPair.fontColor() }
verify(exactly = 1) { colorPair.bgColor() }
}
@Test
fun withAction() {
Toaster.withAction(view, "test", -1, View.OnClickListener { }, colorPair)
verify(exactly = 1) { view.getContext() }
verify(exactly = 1) { context.getString(any()) }
verify(exactly = 1) { snackbar.getView() }
verify(exactly = 1) { snackbar.setAction(any<String>(), any()) }
verify(exactly = 1) { snackbar.show() }
verify(exactly = 1) { Snackbar.make(any(), any<String>(), Snackbar.LENGTH_INDEFINITE) }
verify(exactly = 1) { snackbarView.setBackgroundColor(any()) }
verify(atLeast = 1) { snackbarView.findViewById<View>(any()) }
verify(atLeast = 1) { colorPair.fontColor() }
verify(exactly = 1) { colorPair.bgColor() }
}
@Test
fun withActionWithId() {
Toaster.withAction(view, -1, -1, View.OnClickListener { }, colorPair)
verify(atLeast = 1) { view.getContext() }
verify(atLeast = 1) { context.getString(any()) }
verify(exactly = 1) { snackbar.getView() }
verify(exactly = 1) { snackbar.setAction(any<String>(), any()) }
verify(exactly = 1) { snackbar.show() }
verify(exactly = 1) { Snackbar.make(any(), any<String>(), Snackbar.LENGTH_INDEFINITE) }
verify(exactly = 1) { snackbarView.setBackgroundColor(any()) }
verify(atLeast = 1) { snackbarView.findViewById<View>(any()) }
verify(atLeast = 1) { colorPair.fontColor() }
verify(exactly = 1) { colorPair.bgColor() }
}
} | app/src/test/java/jp/toastkid/yobidashi/libs/ToasterTest.kt | 2913964188 |
package siosio.doma.inspection.dao
import com.intellij.codeHighlighting.*
import com.intellij.codeInspection.*
import com.intellij.psi.*
import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtVisitorVoid
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import siosio.doma.*
import siosio.doma.psi.*
/**
* DomaのDAOのチェックを行うクラス。
*/
class DaoInspectionTool : AbstractBaseJavaLocalInspectionTool() {
override fun getDisplayName(): String = DomaBundle.message("inspection.dao-inspection")
override fun isEnabledByDefault(): Boolean = true
override fun getDefaultLevel(): HighlightDisplayLevel = HighlightDisplayLevel.ERROR
override fun getGroupDisplayName(): String = "Doma"
override fun getShortName(): String = "DaoInspection"
override fun buildVisitor(problemsHolder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return object : JavaElementVisitor() {
override fun visitMethod(method: PsiMethod) {
super.visitMethod(method)
val daoType = DaoType.valueOf(method)
daoType?.let {
val psiDaoMethod = PsiDaoMethod(method, it)
val rule = psiDaoMethod.daoType.rule
rule.inspect(problemsHolder, psiDaoMethod)
}
}
}
}
}
class KotlinDaoInspectionTool: AbstractKotlinInspection() {
override fun getDisplayName(): String = DomaBundle.message("inspection.kotlin-dao-inspection")
override fun isEnabledByDefault(): Boolean = true
override fun getDefaultLevel(): HighlightDisplayLevel = HighlightDisplayLevel.ERROR
override fun getGroupDisplayName(): String = "Doma"
override fun getShortName(): String = "KotlinDaoInspection"
override fun buildVisitor(holder: ProblemsHolder,
isOnTheFly: Boolean,
session: LocalInspectionToolSession): PsiElementVisitor {
return object: KtVisitorVoid() {
override fun visitNamedFunction(function: KtNamedFunction) {
super.visitNamedFunction(function)
if (function.containingClass() == null) {
return
}
DaoType.valueOf(function)?.let {
it.kotlinRule.inspect(holder, PsiDaoFunction(function, it))
}
}
}
}
}
| src/main/java/siosio/doma/inspection/dao/DaoInspectionTool.kt | 175166139 |
package org.gravidence.gravifon.event.playback
import org.gravidence.gravifon.event.Event
import kotlin.time.Duration
/**
* Move to specific playback point.
*/
class RepositionPlaybackPointAbsoluteEvent(val position: Duration) : Event | gravifon/src/main/kotlin/org/gravidence/gravifon/event/playback/RepositionPlaybackPointAbsoluteEvent.kt | 3419621313 |
/**
* DO NOT EDIT THIS FILE.
*
* This source code was autogenerated from source code within the `app/src/gms` directory
* and is not intended for modifications. If any edits should be made, please do so in the
* corresponding file under the `app/src/gms` directory.
*/
/*
* Copyright 2018 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
*
* 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.kotlindemos
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.CompoundButton
import android.widget.SeekBar
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.libraries.maps.CameraUpdate
import com.google.android.libraries.maps.CameraUpdateFactory
import com.google.android.libraries.maps.GoogleMap
import com.google.android.libraries.maps.GoogleMap.CancelableCallback
import com.google.android.libraries.maps.GoogleMap.OnCameraIdleListener
import com.google.android.libraries.maps.GoogleMap.OnCameraMoveCanceledListener
import com.google.android.libraries.maps.GoogleMap.OnCameraMoveListener
import com.google.android.libraries.maps.GoogleMap.OnCameraMoveStartedListener
import com.google.android.libraries.maps.OnMapReadyCallback
import com.google.android.libraries.maps.SupportMapFragment
import com.google.android.libraries.maps.model.CameraPosition
import com.google.android.libraries.maps.model.LatLng
import com.google.android.libraries.maps.model.PolylineOptions
/**
* This shows how to change the camera position for the map.
*/
// [START maps_camera_events]
class CameraDemoActivity :
AppCompatActivity(),
OnCameraMoveStartedListener,
OnCameraMoveListener,
OnCameraMoveCanceledListener,
OnCameraIdleListener,
OnMapReadyCallback {
// [START_EXCLUDE silent]
/**
* The amount by which to scroll the camera. Note that this amount is in raw pixels, not dp
* (density-independent pixels).
*/
private val SCROLL_BY_PX = 100
private val TAG = CameraDemoActivity::class.java.name
private val sydneyLatLng = LatLng(-33.87365, 151.20689)
private val bondiLocation: CameraPosition = CameraPosition.Builder()
.target(LatLng(-33.891614, 151.276417))
.zoom(15.5f)
.bearing(300f)
.tilt(50f)
.build()
private val sydneyLocation: CameraPosition = CameraPosition.Builder().
target(LatLng(-33.87365, 151.20689))
.zoom(15.5f)
.bearing(0f)
.tilt(25f)
.build()
// [END_EXCLUDE]
private lateinit var map: GoogleMap
// [START_EXCLUDE silent]
private lateinit var animateToggle: CompoundButton
private lateinit var customDurationToggle: CompoundButton
private lateinit var customDurationBar: SeekBar
private var currPolylineOptions: PolylineOptions? = null
private var isCanceled = false
// [END_EXCLUDE]
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.camera_demo)
// [START_EXCLUDE silent]
animateToggle = findViewById(R.id.animate)
customDurationToggle = findViewById(R.id.duration_toggle)
customDurationBar = findViewById(R.id.duration_bar)
updateEnabledState()
// [END_EXCLUDE]
val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
}
// [START_EXCLUDE silent]
override fun onResume() {
super.onResume()
updateEnabledState()
}
// [END_EXCLUDE]
override fun onMapReady(googleMap: GoogleMap?) {
// return early if the map was not initialised properly
map = googleMap ?: return
with(googleMap) {
setOnCameraIdleListener(this@CameraDemoActivity)
setOnCameraMoveStartedListener(this@CameraDemoActivity)
setOnCameraMoveListener(this@CameraDemoActivity)
setOnCameraMoveCanceledListener(this@CameraDemoActivity)
// [START_EXCLUDE silent]
// We will provide our own zoom controls.
uiSettings.isZoomControlsEnabled = false
uiSettings.isMyLocationButtonEnabled = true
// [END_EXCLUDE]
// Show Sydney
moveCamera(CameraUpdateFactory.newLatLngZoom(sydneyLatLng, 10f))
}
}
// [START_EXCLUDE silent]
/**
* When the map is not ready the CameraUpdateFactory cannot be used. This should be used to wrap
* all entry points that call methods on the Google Maps API.
*
* @param stuffToDo the code to be executed if the map is initialised
*/
private fun checkReadyThen(stuffToDo: () -> Unit) {
if (!::map.isInitialized) {
Toast.makeText(this, R.string.map_not_ready, Toast.LENGTH_SHORT).show()
} else {
stuffToDo()
}
}
/**
* Called when the Go To Bondi button is clicked.
*/
@Suppress("UNUSED_PARAMETER")
fun onGoToBondi(view: View) {
checkReadyThen {
changeCamera(CameraUpdateFactory.newCameraPosition(bondiLocation))
}
}
/**
* Called when the Animate To Sydney button is clicked.
*/
@Suppress("UNUSED_PARAMETER")
fun onGoToSydney(view: View) {
checkReadyThen {
changeCamera(CameraUpdateFactory.newCameraPosition(sydneyLocation),
object : CancelableCallback {
override fun onFinish() {
Toast.makeText(baseContext, "Animation to Sydney complete",
Toast.LENGTH_SHORT).show()
}
override fun onCancel() {
Toast.makeText(baseContext, "Animation to Sydney canceled",
Toast.LENGTH_SHORT).show()
}
})
}
}
/**
* Called when the stop button is clicked.
*/
@Suppress("UNUSED_PARAMETER")
fun onStopAnimation(view: View) = checkReadyThen { map.stopAnimation() }
/**
* Called when the zoom in button (the one with the +) is clicked.
*/
@Suppress("UNUSED_PARAMETER")
fun onZoomIn(view: View) = checkReadyThen { changeCamera(CameraUpdateFactory.zoomIn()) }
/**
* Called when the zoom out button (the one with the -) is clicked.
*/
@Suppress("UNUSED_PARAMETER")
fun onZoomOut(view: View) = checkReadyThen { changeCamera(CameraUpdateFactory.zoomOut()) }
/**
* Called when the tilt more button (the one with the /) is clicked.
*/
@Suppress("UNUSED_PARAMETER")
fun onTiltMore(view: View) {
checkReadyThen {
val newTilt = Math.min(map.cameraPosition.tilt + 10, 90F)
val cameraPosition = CameraPosition.Builder(map.cameraPosition).tilt(newTilt).build()
changeCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
}
}
/**
* Called when the tilt less button (the one with the \) is clicked.
*/
@Suppress("UNUSED_PARAMETER")
fun onTiltLess(view: View) {
checkReadyThen {
val newTilt = Math.max(map.cameraPosition.tilt - 10, 0F)
val cameraPosition = CameraPosition.Builder(map.cameraPosition).tilt(newTilt).build()
changeCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
}
}
/**
* Called when the left arrow button is clicked. This causes the camera to move to the left
*/
@Suppress("UNUSED_PARAMETER")
fun onScrollLeft(view: View) {
checkReadyThen {
changeCamera(CameraUpdateFactory.scrollBy((-SCROLL_BY_PX).toFloat(),0f))
}
}
/**
* Called when the right arrow button is clicked. This causes the camera to move to the right.
*/
@Suppress("UNUSED_PARAMETER")
fun onScrollRight(view: View) {
checkReadyThen {
changeCamera(CameraUpdateFactory.scrollBy(SCROLL_BY_PX.toFloat(), 0f))
}
}
/**
* Called when the up arrow button is clicked. The causes the camera to move up.
*/
@Suppress("UNUSED_PARAMETER")
fun onScrollUp(view: View) {
checkReadyThen {
changeCamera(CameraUpdateFactory.scrollBy(0f, (-SCROLL_BY_PX).toFloat()))
}
}
/**
* Called when the down arrow button is clicked. This causes the camera to move down.
*/
@Suppress("UNUSED_PARAMETER")
fun onScrollDown(view: View) {
checkReadyThen {
changeCamera(CameraUpdateFactory.scrollBy(0f, SCROLL_BY_PX.toFloat()))
}
}
/**
* Called when the animate button is toggled
*/
@Suppress("UNUSED_PARAMETER")
fun onToggleAnimate(view: View) = updateEnabledState()
/**
* Called when the custom duration checkbox is toggled
*/
@Suppress("UNUSED_PARAMETER")
fun onToggleCustomDuration(view: View) = updateEnabledState()
/**
* Update the enabled state of the custom duration controls.
*/
private fun updateEnabledState() {
customDurationToggle.isEnabled = animateToggle.isChecked
customDurationBar.isEnabled = animateToggle.isChecked && customDurationToggle.isChecked
}
/**
* Change the camera position by moving or animating the camera depending on the state of the
* animate toggle button.
*/
private fun changeCamera(update: CameraUpdate, callback: CancelableCallback? = null) {
if (animateToggle.isChecked) {
if (customDurationToggle.isChecked) {
// The duration must be strictly positive so we make it at least 1.
map.animateCamera(update, Math.max(customDurationBar.progress, 1), callback)
} else {
map.animateCamera(update, callback)
}
} else {
map.moveCamera(update)
}
}
// [END_EXCLUDE]
override fun onCameraMoveStarted(reason: Int) {
// [START_EXCLUDE silent]
if (!isCanceled) map.clear()
// [END_EXCLUDE]
var reasonText = "UNKNOWN_REASON"
// [START_EXCLUDE silent]
currPolylineOptions = PolylineOptions().width(5f)
// [END_EXCLUDE]
when (reason) {
OnCameraMoveStartedListener.REASON_GESTURE -> {
// [START_EXCLUDE silent]
currPolylineOptions?.color(Color.BLUE)
// [END_EXCLUDE]
reasonText = "GESTURE"
}
OnCameraMoveStartedListener.REASON_API_ANIMATION -> {
// [START_EXCLUDE silent]
currPolylineOptions?.color(Color.RED)
// [END_EXCLUDE]
reasonText = "API_ANIMATION"
}
OnCameraMoveStartedListener.REASON_DEVELOPER_ANIMATION -> {
// [START_EXCLUDE silent]
currPolylineOptions?.color(Color.GREEN)
// [END_EXCLUDE]
reasonText = "DEVELOPER_ANIMATION"
}
}
Log.d(TAG, "onCameraMoveStarted($reasonText)")
// [START_EXCLUDE silent]
addCameraTargetToPath()
// [END_EXCLUDE]
}
// [START_EXCLUDE silent]
/**
* Ensures that currPolyLine options is not null before accessing it
*
* @param stuffToDo the code to be executed if currPolylineOptions is not null
*/
private fun checkPolylineThen(stuffToDo: () -> Unit) {
if (currPolylineOptions != null) stuffToDo()
}
// [END_EXCLUDE]
override fun onCameraMove() {
Log.d(TAG, "onCameraMove")
// [START_EXCLUDE silent]
// When the camera is moving, add its target to the current path we'll draw on the map.
checkPolylineThen { addCameraTargetToPath() }
// [END_EXCLUDE]
}
override fun onCameraMoveCanceled() {
// [START_EXCLUDE silent]
// When the camera stops moving, add its target to the current path, and draw it on the map.
checkPolylineThen {
addCameraTargetToPath()
map.addPolyline(currPolylineOptions)
}
isCanceled = true // Set to clear the map when dragging starts again.
currPolylineOptions = null
// [END_EXCLUDE]
Log.d(TAG, "onCameraMoveCancelled")
}
override fun onCameraIdle() {
// [START_EXCLUDE silent]
checkPolylineThen {
addCameraTargetToPath()
map.addPolyline(currPolylineOptions)
}
currPolylineOptions = null
isCanceled = false // Set to *not* clear the map when dragging starts again.
// [END_EXCLUDE]
Log.d(TAG, "onCameraIdle")
}
// [START_EXCLUDE silent]
private fun addCameraTargetToPath() {
currPolylineOptions?.add(map.cameraPosition.target)
}
// [END_EXCLUDE]
}
// [END maps_camera_events] | ApiDemos/kotlin/app/src/v3/java/com/example/kotlindemos/CameraDemoActivity.kt | 856184102 |
package org.koin.example
interface Pump {
fun pump()
} | koin-projects/examples/coffee-maker/src/main/kotlin/org/koin/example/Pump.kt | 1284566248 |
package org.wordpress.android.fluxc.example
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentManager.OnBackStackChangedListener
import dagger.android.AndroidInjection
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.HasAndroidInjector
import kotlinx.android.synthetic.main.activity_example.*
import javax.inject.Inject
class MainExampleActivity : AppCompatActivity(), OnBackStackChangedListener, HasAndroidInjector {
@Inject lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Any>
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_example)
setSupportActionBar(toolbar)
supportFragmentManager.addOnBackStackChangedListener(this)
if (savedInstanceState == null) {
val mf = MainFragment()
supportFragmentManager.beginTransaction().add(R.id.fragment_container, mf).commit()
}
log.movementMethod = ScrollingMovementMethod()
prependToLog("I'll log stuff here.")
updateBackArrow()
}
fun prependToLog(s: String) {
val output = s + "\n" + log.text
log.text = output
}
override fun androidInjector(): AndroidInjector<Any> = dispatchingAndroidInjector
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onBackStackChanged() {
updateBackArrow()
}
private fun updateBackArrow() {
val showBackArrow = supportFragmentManager.backStackEntryCount > 0
supportActionBar?.setDisplayHomeAsUpEnabled(showBackArrow)
}
}
| example/src/main/java/org/wordpress/android/fluxc/example/MainExampleActivity.kt | 580240142 |
/*
* Copyright 2020 Andrey Tolpeev
*
* 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 teamcityapp.libraries.remote
interface RemoteService {
fun isNotChurn(): Boolean
fun showTryItOut(
onSuccess: (showTryItOut: Boolean) -> Unit,
onStart: () -> Unit,
onFinish: () -> Unit
)
fun getTryItOutUrl(): String
companion object {
const val PARAMETER_NOT_CHURN = "param_not_churn"
const val PARAMETER_URL_SHOW_TRY_IT_OUT = "param_url_try_it_out"
const val PARAMETER_SHOW_TRY_IT_OUT = "param_show_try_it_out"
}
}
| libraries/remote/src/main/java/teamcityapp/libraries/remote/RemoteService.kt | 3293042348 |
/*
* MIT License
*
* Copyright (c) 2019 emufog contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package emufog.fog
import io.mockk.mockk
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
internal class FogResultTest {
@Test
fun `initialize a new instance`() {
val result = FogResult()
assertFalse(result.status)
assertEquals(0, result.placements.size)
}
@Test
fun `set the status to true`() {
val result = FogResult()
assertFalse(result.status)
result.setSuccess()
assertTrue(result.status)
}
@Test
fun `set the status to false`() {
val result = FogResult()
assertFalse(result.status)
result.setFailure()
assertFalse(result.status)
result.setSuccess()
assertTrue(result.status)
result.setFailure()
assertFalse(result.status)
}
@Test
fun `addPlacement should increase list by one`() {
val result = FogResult()
assertEquals(0, result.placements.size)
val placement: FogNodePlacement = mockk()
result.addPlacement(placement)
assertEquals(1, result.placements.size)
assertEquals(placement, result.placements[0])
}
@Test
fun `addPlacements should increase list by all elements of the collection`() {
val result = FogResult()
assertEquals(0, result.placements.size)
val placement1: FogNodePlacement = mockk()
val placement2: FogNodePlacement = mockk()
result.addPlacements(listOf(placement1, placement2))
assertEquals(2, result.placements.size)
assertTrue(result.placements.contains(placement1))
assertTrue(result.placements.contains(placement2))
}
} | src/test/kotlin/emufog/fog/FogResultTest.kt | 3060548204 |
package io.piano.android.composer
import io.piano.android.composer.model.ExperienceRequest
import io.piano.android.composer.model.ExperienceResponse
interface ExperienceInterceptor {
fun beforeExecute(request: ExperienceRequest) {}
fun afterExecute(request: ExperienceRequest, response: ExperienceResponse) {}
}
| composer/src/main/java/io/piano/android/composer/ExperienceInterceptor.kt | 47940237 |
/*
* Copyright 2019 Andrey Tolpeev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.vase4kin.teamcityapp.buildlog.view
import android.content.Intent
import android.os.Bundle
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.scrollTo
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.espresso.web.assertion.WebViewAssertions.webMatches
import androidx.test.espresso.web.sugar.Web.onWebView
import androidx.test.espresso.web.webdriver.DriverAtoms.findElement
import androidx.test.espresso.web.webdriver.DriverAtoms.getText
import androidx.test.espresso.web.webdriver.Locator
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.github.vase4kin.teamcityapp.TeamCityApplication
import com.github.vase4kin.teamcityapp.api.TeamCityService
import com.github.vase4kin.teamcityapp.base.extractor.BundleExtractorValues
import com.github.vase4kin.teamcityapp.build_details.view.BuildDetailsActivity
import com.github.vase4kin.teamcityapp.dagger.components.AppComponent
import com.github.vase4kin.teamcityapp.dagger.components.RestApiComponent
import com.github.vase4kin.teamcityapp.dagger.modules.AppModule
import com.github.vase4kin.teamcityapp.dagger.modules.FakeTeamCityServiceImpl
import com.github.vase4kin.teamcityapp.dagger.modules.Mocks
import com.github.vase4kin.teamcityapp.dagger.modules.RestApiModule
import com.github.vase4kin.teamcityapp.helper.CustomIntentsTestRule
import com.github.vase4kin.teamcityapp.helper.TestUtils
import io.reactivex.Single
import it.cosenonjaviste.daggermock.DaggerMockRule
import org.hamcrest.Matchers.containsString
import org.junit.BeforeClass
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Matchers.anyString
import org.mockito.Mockito.`when`
import org.mockito.Spy
/**
* Tests for [BuildLogFragment]
*/
@RunWith(AndroidJUnit4::class)
class BuildLogFragmentTest {
@JvmField
@Rule
val restComponentDaggerRule: DaggerMockRule<RestApiComponent> =
DaggerMockRule(RestApiComponent::class.java, RestApiModule(Mocks.URL))
.addComponentDependency(
AppComponent::class.java,
AppModule(InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as TeamCityApplication)
)
.set { restApiComponent ->
val app =
InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as TeamCityApplication
app.setRestApiInjector(restApiComponent)
}
@JvmField
@Rule
val activityRule: CustomIntentsTestRule<BuildDetailsActivity> =
CustomIntentsTestRule(BuildDetailsActivity::class.java)
@Spy
private val teamCityService: TeamCityService = FakeTeamCityServiceImpl()
@Spy
private val build = Mocks.successBuild()
companion object {
@JvmStatic
@BeforeClass
fun disableOnboarding() {
TestUtils.disableOnboarding()
val storage =
(InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as TeamCityApplication).appInjector.sharedUserStorage()
storage.clearAll()
storage.saveGuestUserAccountAndSetItAsActive(Mocks.URL, false)
}
}
@Test
fun testUserCanSeeBuildLog() {
// Prepare mocks
`when`(teamCityService.build(anyString())).thenReturn(Single.just(build))
// Prepare intent
// <! ---------------------------------------------------------------------- !>
// Passing build object to activity, had to create it for real, Can't pass mock object as serializable in bundle :(
// <! ---------------------------------------------------------------------- !>
val intent = Intent()
val b = Bundle()
b.putSerializable(BundleExtractorValues.BUILD, Mocks.successBuild())
b.putString(BundleExtractorValues.NAME, "name")
intent.putExtras(b)
// Start activity
activityRule.launchActivity(intent)
// Checking build log tab title
onView(withText("Build Log"))
.perform(scrollTo())
.check(matches(isDisplayed()))
.perform(click())
// Check web view content
onWebView()
.withElement(findElement(Locator.ID, "build_log"))
.check(webMatches(getText(), containsString("Hello, this is fake build log!")))
}
}
| app/src/androidTest/java/com/github/vase4kin/teamcityapp/buildlog/view/BuildLogFragmentTest.kt | 727417259 |
/*
* Copyright 2016 Jan Hackel
*
* 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 jhunovis.umlauts
import junitparams.JUnitParamsRunner
import junitparams.Parameters
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.CoreMatchers.equalTo
import org.junit.Assert.assertThat
import org.junit.Test
import org.junit.runner.RunWith
/**
* A unit-test for [GermanTransliteration].
*
* @author [Jan Hackel](mailto:[email protected])
*/
@RunWith(JUnitParamsRunner::class)
class GermanTransliterationTest {
@Test
@Parameters(
"Ä, Ae",
"Ö, Oe",
"Ü, Ue",
"ä, ae",
"ö, oe",
"ü, ue",
"ß, ss")
fun replaceAllGermanSpecialCharactersWithTheirTransliteration(word: String, expectedTransliteration: String) {
assertIsTranslatedFromInto(expectedTransliteration, word)
}
@Test
@Parameters(
"Ae, Ä",
"Oe, Ö",
"Ue, Ü",
"ae, ä",
"oe, ö",
"ue, ü",
"ss, ß")
fun replaceAllTransliterationsWithTheirNativeForm(word: String, expectedTransliteration: String) {
assertIsTranslatedFromInto(expectedTransliteration, word)
}
@Test
@Parameters(
"Käsefondue, Kaesefondue",
"Autoeinführung, Autoeinfuehrung")
fun whenWordContainsBothNativeAndTransliteratedForms_PreferTheNativeFormAndLeaveTheTransliterationsAsTheyAre(word: String, expectedTransliteration: String) {
assertIsTranslatedFromInto(expectedTransliteration, word)
}
@Test
fun givenTransliteratedWritings_IncorrectMappingsMayResult() {
assertIsTranslatedFromInto("Kaesefondueueberfluss", "Käsefondüüberfluß")
}
private fun assertIsTranslatedFromInto(expectedTransliteration: String, word: String) {
assertThat(
GermanTransliteration().transliterate(word), `is`(equalTo(expectedTransliteration))
)
}
} | src/test/kotlin/jhunovis/umlauts/GermanTransliterationTest.kt | 4041829956 |
package by.vshkl.android.pik.ui.albums
import android.support.v7.widget.RecyclerView.ViewHolder
import android.view.View
import android.widget.ImageView
import by.vshkl.android.pik.customview.PlayRegularTextView
import kotlinx.android.synthetic.main.item_album.view.*
class AlbumsViewHolder(itemView: View) : ViewHolder(itemView) {
val ivThumbnail: ImageView = itemView.ivAlbumThumbnail
val ivCheck: ImageView = itemView.ivCheck
val tvName: PlayRegularTextView = itemView.tvAlbumName
val tvCount: PlayRegularTextView = itemView.tvAlbumCount
}
| app/src/main/java/by/vshkl/android/pik/ui/albums/AlbumsViewHolder.kt | 500734511 |
package com.tngtech.demo.weather.domain.measurement
data class AtmosphericData(
/**
* temperature in degrees celsius
*/
val temperature: DataPoint? = null,
/**
* wind speed in km/h
*/
val wind: DataPoint? = null,
/**
* humidity in percent
*/
val humidity: DataPoint? = null,
/**
* precipitation in cm
*/
val precipitation: DataPoint? = null,
/**
* pressure in mmHg
*/
val pressure: DataPoint? = null,
/**
* cloud cover percent from 0 - 100 (integer)
*/
val cloudCover: DataPoint? = null,
/**
* the last time this data was updated, in milliseconds since UTC epoch
*/
val lastUpdateTime: Long = 0)
| src/main/java/com/tngtech/demo/weather/domain/measurement/AtmosphericData.kt | 795538453 |
package com.yy.codex.uikit
import android.text.TextPaint
import android.text.style.CharacterStyle
internal class NSBoldSpan : CharacterStyle() {
override fun updateDrawState(textPaint: TextPaint) {
textPaint.isFakeBoldText = true
}
} | library/src/main/java/com/yy/codex/uikit/NSBoldSpan.kt | 376286549 |
package com.yy.codex.uikit
import android.content.Context
import java.util.ArrayList
/**
* Created by cuiminghui on 2017/1/18.
*/
class UINavigationItem(val mContext: Context) {
internal var navigationBar: UINavigationBar? = null
/* Title */
var title: String? = null
set(title) {
field = title
updateTitle()
}
fun updateTitle() {
(titleView as? UILabel)?.let {
var titleView = it;
val navigationBar = navigationBar as? UINavigationBar
if (navigationBar != null && navigationBar.titleTextAttributes != null) {
navigationBar.titleTextAttributes?.let {
if (title is String) {
titleView.attributedText = NSAttributedString(title as String, it)
}
else {
titleView.text = ""
}
}
}
else {
titleView.text = title
}
titleView.superview?.let(UIView::layoutSubviews)
}
}
/* FrontView */
internal var frontView: UINavigationItemView = UINavigationItemView(mContext);
fun setNeedsUpdate() {
for (subview in frontView.subviews) {
subview.removeFromSuperview()
}
titleView?.let {
updateTitle()
frontView.addSubview(it)
frontView.titleView = it
}
frontView.leftViews = leftBarButtonItems.mapNotNull { it.getContentView(mContext) }
for (view in frontView.leftViews) {
frontView.addSubview(view)
}
frontView.rightViews = rightBarButtonItems.mapNotNull { it.getContentView(mContext) }
for (view in frontView.rightViews) {
frontView.addSubview(view)
}
}
/* TitleView */
var titleView: UIView? = null
get() {
if (field == null) {
val labelTitleView = UILabel(mContext)
labelTitleView.font = UIFont(17f)
labelTitleView.textColor = UIColor.blackColor
field = labelTitleView
}
return field
}
set(titleView) {
field?.let(UIView::removeFromSuperview)
field = titleView
setNeedsUpdate()
}
/* BarButtonItems */
var leftBarButtonItems: List<UIBarButtonItem> = listOf()
set(value) {
field = value
setNeedsUpdate()
}
fun setLeftBarButtonItem(leftBarButtonItem: UIBarButtonItem?) {
if (leftBarButtonItem == null) {
leftBarButtonItems = listOf()
}
else {
leftBarButtonItems = listOf(leftBarButtonItem)
}
}
var rightBarButtonItems: List<UIBarButtonItem> = listOf()
set(value) {
field = value
setNeedsUpdate()
}
fun setRightBarButtonItem(rightBarButtonItem: UIBarButtonItem?) {
if (rightBarButtonItem == null) {
rightBarButtonItems = listOf()
}
else {
rightBarButtonItems = listOf(rightBarButtonItem)
}
}
var backBarButtonItemUsingMaterialDesign = false
var backBarButtonItem: UIBarButtonItem? = null
get() {
val navigationBar = navigationBar ?: return null
if (navigationBar.materialDesign && !backBarButtonItemUsingMaterialDesign && (field?.isSystemBackItem ?: false)) {
field = null
}
if (field == null && navigationBar.materialDesign) {
val arrowImage = UIImage("iVBORw0KGgoAAAANSUhEUgAAABsAAAAwCAYAAADgvwGgAAAAAXNSR0IArs4c6QAABDVJREFUWAm1mFuITVEYx791ZpCI3O+XcQmjcUu5FLmNSybkMuZIRBSlvCiFULzhUfIiCXs75ozcLzF4UBIlHjSePHgQymSMu/P5f+fMtte+rX3OmWPVPmut7/bb69trrb32UfQ/is3TiekoQk/E9ZoStIfWqtuq5Cybl1OGLiJuBy12hspodpkmaH/T5hqA0j6QxFUYac/SwWxegoANCNxRooeU1vIQYeEimxdiRALqZHB+2v5nZvF8AK5iVJ0NoI9UTlUJg0G8yuI5MLoSA/oEUDXVqnfFj8ziWYDcBKyL4a6aAVoA0DOxKW6CWDwTvrdwdZUgEeUzQAsBeuroC58gFk9rG5EJ1IKFvAigJw5I6sJgFk+Fz21c3cQ5tCj6AtAS7BiP/fr8J4jNUzCiO7i6+4No/VaAlgL0SJP9a+Y3QWyeCEgjrp7/PP0NRd/aQPf9KqcfP7IUV2HB3jWCiL4DtAwjigQJ0PzMUlxJf+ge7Ho7dxeoFf0AaAVAdwM6nyB6ZPU8FiBJXR+fj9tV9BOglQDJpIkt4SOr59EI0wjvfoYIvwBaDdANg41HFYTZPJJ+keR+gMdS7yj6je5agK7q4ri2N40prkDa7uMaFOmYAyUpqS5F2kQoXFiah+F+BTQkwlZegX+gWw9QfaSNQZFbZxYL4CFAFQbbDJ7RBqpT5ww2RlWCGrgXLGREcaBN7QHJXZRjOR5BPVI6oUVOD0RbAToTqi9AmMBzqDHaK9qGZ3TKaJOnUibIT6NthoYa9QUoE0jShRj7vWTxwRibvNQJ6kX7Yel5yQU8mQ4AuC8gL1CA96lqxbloEfyy54RIf6ZDAO6O1OehcN9n17gHtWCHZ5oc47eL1qljMTahancHqVGfcMSsxux8EWrpCo+SzTvdbv4td2SOT4r7YFOSRT7eEYXWinZgSRwP1UUIgzAxbOC+eCU+AHBchF/uU0HRdiz2k5E2PoWbRl2xUr3HiXIeRE262NPm7JfJCaR0i0du6ISPzHGweCCaskGPckSBOredbUZKTwd0PoEZJsZpHoyUPkRrhM9X72bQ2YhZelYX+tvhadStVqm32K7nImlvdLGvLXvsaTrPSZ/c040fmWNu8XA0JaXRe6W8XBUlMWnkMzdQ8oeJa5pHtKV0cCCSI5Bjg8L5pE7Jx6GnFAYT1xSPwv3LCGXyRBU5ea0B8LJuUDhMvFM8BkBZh/31YJ62nCkJZ8qkuu7I4yeIY6nXtaoJqZJ1+F4Xe9qc/ZBPY9IsduTFwcS7Tr3C7zxAPzjBAjVnP+gvAVgtuuLSqEc9zxPQbcQlB6fwougr/oKZ1H6YhE/xJMxBAfYIp0Gq6GzxadSj1qrnWPiSqmZd7GtXlgYmUeUfgfLsG/+zD+J0m0qTRiec1CmegZTKPwnud7d8w5XRlNLDcsAKrMPDaMrkeQ3QQYz85V9acAeH0YiWqgAAAABJRU5ErkJggg==", 3.0)
field = UIBarButtonItem(arrowImage, this, "onBackButtonItemTouchUpInside")
field?.insets = UIEdgeInsets.zero
field?.isSystemBackItem = true
}
else if (field == null) {
field = UIBarButtonItem(title ?: "Back", this, "onBackButtonItemTouchUpInside")
field?.image = UIImage("iVBORw0KGgoAAAANSUhEUgAAACcAAABCCAYAAADUms/cAAAAAXNSR0IArs4c6QAAAbFJREFUaAXt2stNxDAQBuDfSNQBpWwVcORRBhHSXqALkOBCG1SCdkUfeD2CKC8ncex5+MAcR5b8aRxLmUmA/1iowKO/QuMvYivOYkm1XONv8IMPeHzGgE4NMt6IYMBrgLUFOsBhhyd3bJfa4Kaw1jMA6uPmYROgLm4dNgDq4dJhLfBLB7cV5sIdBu7lcZmwcGvfZHEFMDpbOVwhTA7HAJPBMcH4cYwwXhwzjA8nAOPBCcHKcYKwMpwwLB+nAMvDKcG24xRh23DKsHScASwNZwRbxxnClnHGsHlcBbA4rhLYFFcRbIirDNbhKoQR7nfC4zO6MB/mQ8LRtYY51fO4w7N7lzJ2ONqhMuAQlwsMcw0aH3BXcIrLBQoccRxXCXAeVwFwGWcMXMcZAtNwRsB0nAFwG04ZuB2nCMzDKQHzcQrAMpwwsBwnCOTBCQH5cAJAXhwzkB/HCJTB5QJHb9RyOAagLK4QKI8rAOrgCPjgb0Pr/tL7VYOyS6H0Gb0lpPbFDkecY6dXuVTgHwx7d9DHEXKugj0YLbPBxYAjmC2uDwS+6Rmjo6R0PdH4a+z9ZT2gRMkJbMiClVJCMU0AAAAASUVORK5CYII=", 3.0)
field?.imageInsets = UIEdgeInsets(0.0, 0.0, 0.0, 4.0)
field?.isSystemBackItem = true
}
return field
}
set(backBarButtonItem) {
field = backBarButtonItem
}
fun onBackButtonItemTouchUpInside() {
var nextResponder: UIResponder? = frontView
while (nextResponder != null) {
nextResponder = nextResponder.nextResponder
if (nextResponder is UINavigationController) {
nextResponder.popViewController(true)
return
}
}
}
}
| library/src/main/java/com/yy/codex/uikit/UINavigationItem.kt | 41535201 |
package siilinkari.vm
import siilinkari.ast.FunctionDefinition
import siilinkari.env.GlobalStaticEnvironment
import siilinkari.lexer.LookaheadLexer
import siilinkari.lexer.Token.Keyword
import siilinkari.objects.Value
import siilinkari.optimizer.optimize
import siilinkari.parser.parseExpression
import siilinkari.parser.parseFunctionDefinition
import siilinkari.parser.parseFunctionDefinitions
import siilinkari.translator.FunctionTranslator
import siilinkari.translator.translateToCode
import siilinkari.translator.translateToIR
import siilinkari.types.Type
import siilinkari.types.TypedExpression
import siilinkari.types.typeCheck
import siilinkari.vm.OpCode.*
import siilinkari.vm.OpCode.Binary.*
/**
* Evaluator for opcodes.
*
* @see OpCode
*/
class Evaluator {
private val globalData = DataSegment()
private val globalTypeEnvironment = GlobalStaticEnvironment()
private var globalCode = CodeSegment()
private val functionTranslator = FunctionTranslator(globalTypeEnvironment)
var trace = false
var optimize = true
/**
* Binds a global name to given value.
*/
fun bind(name: String, value: Value, mutable: Boolean = true) {
val binding = globalTypeEnvironment.bind(name, value.type, mutable)
globalData[binding.index] = value
}
/**
* Evaluates code which can either be a definition, statement or expression.
* If the code represented an expression, returns its value. Otherwise [Value.Unit] is returned.
*/
fun evaluate(code: String): EvaluationResult {
if (LookaheadLexer(code).nextTokenIs(Keyword.Fun)) {
val definition = parseFunctionDefinition(code)
bindFunction(definition)
return EvaluationResult(Value.Unit, Type.Unit)
} else {
val (segment, type) = translate(code)
return EvaluationResult(evaluateSegment(segment), type)
}
}
/**
* Loads contents of given file.
*/
fun loadResource(file: String) {
val source = javaClass.classLoader.getResource(file).openStream().use { it.reader().readText() }
val defs = parseFunctionDefinitions(source, file)
for (def in defs)
bindFunction(def)
}
/**
* Returns the names of all global bindings.
*/
fun bindingsNames(): Set<String> =
globalTypeEnvironment.bindingNames()
/**
* Translates given code to opcodes and returns string representation of the opcodes.
*/
fun dump(code: String): String {
val exp = parseAndTypeCheck(code)
if (exp is TypedExpression.Ref && exp.type is Type.Function) {
val value = globalData[exp.binding.index] as Value.Function
return when (value) {
is Value.Function.Compound -> globalCode.getRegion(value.address, value.codeSize).toString()
is Value.Function.Native -> "native function $value"
}
} else {
return translate(exp).toString()
}
}
/**
* Compiles and binds a global function.
*/
private fun bindFunction(func: FunctionDefinition) {
// We have to create the binding into global environment before calling createFunction
// because the function might want to call itself recursively. But if createFunction fails
// (most probably to type-checking), we need to unbind the binding.
var binding = func.returnType?.let { returnType ->
globalTypeEnvironment.bind(func.name, Type.Function(func.args.map { it.second }, returnType), mutable = false)
}
try {
val (signature, code) = functionTranslator.translateFunction(func, optimize)
val (newGlobalCode, address) = globalCode.mergeWithRelocatedSegment(code)
globalCode = newGlobalCode
if (binding == null)
binding = globalTypeEnvironment.bind(func.name, signature, mutable = false)
globalData[binding.index] = Value.Function.Compound(func.name, signature, address, code.size)
} catch (e: Exception) {
if (binding != null)
globalTypeEnvironment.unbind(func.name)
throw e
}
}
/**
* Translates code to opcodes.
*/
private fun translate(code: String): Pair<CodeSegment, Type> {
val exp = parseAndTypeCheck(code)
return Pair(translate(exp), exp.type)
}
private fun translate(exp: TypedExpression): CodeSegment {
val optExp = if (optimize)
exp.optimize()
else
exp
val blocks = optExp.translateToIR()
if (optimize)
blocks.optimize()
return blocks.translateToCode(0)
}
private fun parseAndTypeCheck(code: String) =
parseExpression(code).typeCheck(globalTypeEnvironment)
/**
* Evaluates given code segment.
*/
private fun evaluateSegment(segment: CodeSegment): Value {
val (code, startAddress) = globalCode.mergeWithRelocatedSegment(segment)
val quitPointer = Value.Pointer.Code(-1)
val state = ThreadState()
state.pc = startAddress
state.fp = 0
state[0] = quitPointer
evalLoop@while (true) {
val op = code[state.pc]
if (trace)
println("${state.pc.toString().padStart(4)}: ${op.toString().padEnd(40)} [fp=${state.fp}]")
state.pc++
when (op) {
is Not -> state[op.target] = !(state[op.source] as Value.Bool)
is Add -> state.evalBinary(op) { l, r -> l + r }
is Subtract -> state.evalBinary(op) { l, r -> l - r }
is Multiply -> state.evalBinary(op) { l, r -> l * r }
is Divide -> state.evalBinary(op) { l, r -> l / r }
is Equal -> state.evalBinaryBool(op) { l, r -> l == r }
is LessThan -> state.evalBinaryBool(op) { l, r -> l.lessThan(r) }
is LessThanOrEqual -> state.evalBinaryBool(op) { l, r -> l == r || l.lessThan(r) }
is ConcatString -> state.evalBinary(op) { l, r-> l + r }
is LoadConstant -> state[op.target] = op.value
is Copy -> state[op.target] = state[op.source]
is LoadGlobal -> state[op.target] = globalData[op.sourceGlobal]
is StoreGlobal -> globalData[op.targetGlobal] = state[op.source]
is Jump -> state.pc = op.address
is JumpIfFalse -> if (!(state[op.sp] as Value.Bool).value) state.pc = op.address
is Call -> evalCall(op, state)
is RestoreFrame -> state.fp -= op.sp
is Ret -> {
val returnAddress = state[op.returnAddressPointer]
state[0] = state[op.valuePointer]
if (returnAddress == quitPointer)
break@evalLoop
state.pc = (returnAddress as Value.Pointer.Code).value
}
Nop -> {}
else -> error("unknown opcode: $op")
}
}
return state[0]
}
private fun evalCall(op: Call, state: ThreadState) {
val func = state[op.offset] as Value.Function
state.fp += op.offset - op.argumentCount
when (func) {
is Value.Function.Compound -> {
state[op.argumentCount] = Value.Pointer.Code(state.pc)
state.pc = func.address
}
is Value.Function.Native -> {
val args = state.getArgs(func.argumentCount)
state[0] = func(args)
}
}
}
}
| src/main/kotlin/siilinkari/vm/Evaluator.kt | 2208769160 |
/*
* Copyright (C) 2018 Saúl Díaz
*
* 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.sefford.kor.usecases
import arrow.core.*
import com.sefford.kor.usecases.components.*
/**
* Use case implementation.
*
* As stated in the documentation, it passes through three stages
* <ul>
* <li>Execution</li>
* <li>Postprocessing</li>
* <li>Persistance</li>
* </ul>
*
* By default the postprocessing and persistance stages are optional and
* are defaulted to an identity lambda.
*
* @author Saul Diaz <[email protected]>
*/
class UseCase<E : Error, R : Response>
/**
* Creates a new use case.
* @param logic Lambda that outputs a {@link Response Response}
* @param postProcessor Lambda that processes the response from the logic phase and returns it.
*
* Note that it can be passed back or create a new one. By default it is an identity lambda.
* @param cachePersistance Lambda that caches the response from the postprocessing phase and returns it.
*
* Note that it can be passed back or create a new one. This is the final result that will be returned by the use case.
*
* By default it is an identity lambda.
*/
private constructor(internal val logic: () -> R,
internal val postProcessor: (response: R) -> R = ::identity,
internal val cachePersistance: (response: R) -> R = ::identity,
internal val errorHandler: (ex: Throwable) -> E,
internal val performance: PerformanceModule = NoModule) {
/**
* Execute the use case inmediately in the current thread.
*/
fun execute(): Either<E, R> {
performance.start()
return Try { cachePersistance(postProcessor(logic())) }
.also { performance.end() }
.map { response -> response.right() }
.getOrElse { errorHandler(it).left() }
}
/**
* Use case builder
*
* @author Saul Diaz <[email protected]>
*/
class Execute<E : Error, R : Response>
/**
* Initializes a new use case with the required logic.
*
* If no further piece is returned, postprocessor and persistance phases are an identity function and the
* error handling is a default one to produce a basic error.
*
* @param logic Logic of the use case.
*/
(internal val logic: () -> R) {
internal var postProcessor: (R) -> R = ::identity
internal var cachePersistance: (R) -> R = ::identity
internal var errorHandler: (Throwable) -> E = emptyErrorHandler()
internal var performanceModule: PerformanceModule = NoModule
/**
* Sets up the logic for the post processing phase.
*
* The response returned by this piece of logic will be fed to the persistence phase, and does not matter
* if the input is returned or a new response is created.
*
* @param postProcessor Logic that will be applied to the post processor phase
*/
fun process(postProcessor: (R) -> R): Execute<E, R> {
this.postProcessor = postProcessor
return this
}
/**
* Sets up the logic for the persistence phase.
*
* The response returned by this piece of logic will be returned, and does not matter if the input is returned
* or a new response is created.
*
* @param cachePersistance Logic that will be applied to the persistance phase.
*/
fun persist(cachePersistance: (R) -> R): Execute<E, R> {
this.cachePersistance = cachePersistance
return this
}
/**
* Sets up a customized error handling.
*
* This will be returned in the case of any failure in any of execution, postprocessing or persistance stages.
*
* @param errorHandler Custom error handler.
*/
fun onError(errorHandler: (Throwable) -> E): Execute<E, R> {
this.errorHandler = errorHandler
return this;
}
/**
* Sets up a performance module.
*
* @param module Performance module which will output the metric
*/
fun withIntrospection(module: PerformanceModule): Execute<E, R> {
this.performanceModule = module
return this;
}
/**
* Builds a new use case as specified
*/
fun build(): UseCase<E, R> {
return UseCase(logic, postProcessor, cachePersistance, errorHandler, performanceModule)
}
}
}
| modules/kor-usecases/src/main/kotlin/com/sefford/kor/usecases/UseCase.kt | 4033908074 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi
import com.intellij.psi.impl.source.tree.LeafPsiElement
import org.junit.Assert.assertEquals
import org.junit.Assert.fail
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.rust.lang.core.psi.RsElementTypes.FLOAT_LITERAL
import java.util.*
@RunWith(Parameterized::class)
class RsNumericLiteralValueTest(private val constructor: (String) -> RsLiteralKind.Float,
private val input: String,
private val expectedOutput: Any?) {
@Test
fun test() {
val elem = constructor(input)
assertEquals(expectedOutput, elem.value)
}
companion object {
@Parameterized.Parameters(name = "{index}: {1}")
@JvmStatic fun data(): Collection<Array<out Any?>> = listOf(
arrayOf(f64, "1.0", 1.0),
arrayOf(f64, "1.0_1", 1.01),
arrayOf(f64, "2.4e8", 2.4e8),
arrayOf(f64, "10_E-6", 10e-6),
arrayOf(f64, "9.", 9.0)
)
val f64 = { s: String -> RsLiteralKind.Float(LeafPsiElement(FLOAT_LITERAL, s)) }
}
}
class RsNumericLiteralValueFuzzyTest {
@Test
fun testFuzzyFloats() {
repeat(10000) {
doTest(randomLiteral())
}
}
private fun doTest(text: String) {
try {
RsLiteralKind.Float(LeafPsiElement(FLOAT_LITERAL, text)).value
} catch(e: Exception) {
fail("exception thrown by $text")
}
}
private fun randomLiteral(): String {
val random = Random()
val length = random.nextInt(10)
val chars = "0123456789abcdefABCDEFxo._eE-+"
val xs = CharArray(length, {
chars[random.nextInt(chars.length)]
})
return String(xs)
}
}
| src/test/kotlin/org/rust/lang/core/psi/RsNumericLiteralValueTest.kt | 2087930466 |
package com.garpr.android.data.models
import android.os.Parcel
import android.os.Parcelable
import androidx.annotation.StringRes
import com.garpr.android.R
import com.garpr.android.extensions.createParcel
import com.squareup.moshi.Json
import java.util.concurrent.TimeUnit
enum class PollFrequency constructor(
@StringRes val textResId: Int,
timeInMillis: Long
) : Parcelable {
@Json(name = "every_8_hours")
EVERY_8_HOURS(R.string.every_8_hours, TimeUnit.HOURS.toMillis(8)),
@Json(name = "daily")
DAILY(R.string.daily, TimeUnit.DAYS.toMillis(1)),
@Json(name = "every_2_days")
EVERY_2_DAYS(R.string.every_2_days, TimeUnit.DAYS.toMillis(2)),
@Json(name = "every_3_days")
EVERY_3_DAYS(R.string.every_3_days, TimeUnit.DAYS.toMillis(3)),
@Json(name = "every_5_days")
EVERY_5_DAYS(R.string.every_5_days, TimeUnit.DAYS.toMillis(5)),
@Json(name = "weekly")
WEEKLY(R.string.weekly, TimeUnit.DAYS.toMillis(7)),
@Json(name = "every_10_days")
EVERY_10_DAYS(R.string.every_10_days, TimeUnit.DAYS.toMillis(10)),
@Json(name = "every_2_weeks")
EVERY_2_WEEKS(R.string.every_2_weeks, TimeUnit.DAYS.toMillis(14));
val timeInSeconds: Long = TimeUnit.MILLISECONDS.toSeconds(timeInMillis)
override fun describeContents(): Int = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeInt(ordinal)
}
companion object {
@JvmField
val CREATOR = createParcel { values()[it.readInt()] }
}
}
| smash-ranks-android/app/src/main/java/com/garpr/android/data/models/PollFrequency.kt | 4189995763 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.runconfig
import com.intellij.execution.configurations.ConfigurationTypeUtil
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.execution.executors.DefaultRunExecutor
import com.intellij.execution.process.*
import com.intellij.execution.runners.ExecutionEnvironmentBuilder
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import org.assertj.core.api.Assertions.assertThat
import org.rust.cargo.RustWithToolchainTestBase
import org.rust.cargo.runconfig.command.CargoCommandConfiguration
import org.rust.cargo.runconfig.command.CargoCommandConfigurationType
import org.rust.fileTree
class RunConfigurationTestCase : RustWithToolchainTestBase() {
override val dataPath = "src/test/resources/org/rust/cargo/runconfig/fixtures"
fun testApplicationConfiguration() {
fileTree {
toml("Cargo.toml", """
[package]
name = "hello"
version = "0.1.0"
authors = []
""")
dir("src") {
rust("main.rs", """
fn main() {
println!("Hello, world!");
}
""")
}
}.create()
val configuration = createConfiguration()
val result = execute(configuration)
assertThat(result.stdout).contains("Hello, world!")
}
private fun createConfiguration(): CargoCommandConfiguration {
val configurationType = ConfigurationTypeUtil.findConfigurationType(CargoCommandConfigurationType::class.java)
val factory = configurationType.factory
val configuration = factory.createTemplateConfiguration(myModule.project) as CargoCommandConfiguration
configuration.setModule(myModule)
return configuration
}
private fun execute(configuration: RunConfiguration): ProcessOutput {
val executor = DefaultRunExecutor.getRunExecutorInstance()
val state = ExecutionEnvironmentBuilder
.create(executor, configuration)
.build()
.state!!
val result = state.execute(executor, RsRunner())!!
val listener = AnsiAwareCapturingProcessAdapter()
with(result.processHandler) {
addProcessListener(listener)
startNotify()
waitFor()
}
Disposer.dispose(result.executionConsole)
return listener.output
}
}
/**
* Capturing adapter that removes ANSI escape codes from the output
*/
class AnsiAwareCapturingProcessAdapter : ProcessAdapter(), AnsiEscapeDecoder.ColoredTextAcceptor {
val output = ProcessOutput()
private val decoder = object : AnsiEscapeDecoder() {
override fun getCurrentOutputAttributes(outputType: Key<*>) = outputType
}
override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) =
decoder.escapeText(event.text, outputType, this)
private fun addToOutput(text: String, outputType: Key<*>) {
if (outputType === ProcessOutputTypes.STDERR) {
output.appendStderr(text)
} else {
output.appendStdout(text)
}
}
override fun processTerminated(event: ProcessEvent) {
output.exitCode = event.exitCode
}
override fun coloredTextAvailable(text: String, attributes: Key<*>) =
addToOutput(text, attributes)
}
| src/test/kotlin/org/rust/cargo/runconfig/RunConfigurationTestCase.kt | 2967604983 |
package v_builders
import util.TODO
import util.doc36
fun todoTask36(): Nothing = TODO(
"""
Task 36.
Read about extension function literals.
You can declare `isEven` and `isOdd` as values, that can be called as extension functions.
Complete the declarations below.
""",
documentation = doc36()
)
fun task36(): List<Boolean> {
val isEven: Int.() -> Boolean = { this % 2 == 0 }
val isOdd: Int.() -> Boolean = { this % 2 != 0 }
return listOf(42.isOdd(), 239.isOdd(), 294823098.isEven())
}
| src/v_builders/n36ExtensionFunctionLiterals.kt | 3142766977 |
package org.http4k.routing.experimental
import org.http4k.core.Body
import org.http4k.core.ContentType
import org.http4k.core.ContentType.Companion.OCTET_STREAM
import org.http4k.core.Headers
import org.http4k.core.HttpHandler
import org.http4k.core.MemoryResponse
import org.http4k.core.Request
import org.http4k.core.Status.Companion.NOT_MODIFIED
import org.http4k.core.Status.Companion.OK
import org.http4k.core.etag.ETag
import org.http4k.core.etag.ETagValidationRequestParser
import org.http4k.core.etag.FieldValue
import java.io.InputStream
import java.time.Instant
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME
interface Resource : HttpHandler {
fun openStream(): InputStream
val length: Long? get() = null
val lastModified: Instant? get() = null
val contentType: ContentType get() = OCTET_STREAM
val etag: ETag? get() = null
fun isModifiedSince(instant: Instant): Boolean = lastModified?.isAfter(instant) ?: true
val headers: Headers
get() = listOf(
"Content-Type" to contentType.value,
"Content-Length" to length?.toString(),
"Last-Modified" to lastModified?.formattedWith(dateTimeFormatter),
"ETag" to etag?.toHeaderString()
)
override fun invoke(request: Request) = if (notModifiedSince(request) || etagMatch(request))
MemoryResponse(NOT_MODIFIED, headers)
else
MemoryResponse(OK, headers, Body(openStream(), length)) // Pipeline is responsible for closing stream
private fun notModifiedSince(request: Request): Boolean {
val ifModifiedSince = request.header("If-Modified-Since")?.parsedWith(dateTimeFormatter)
return ifModifiedSince != null && !isModifiedSince(ifModifiedSince)
}
private fun etagMatch(request: Request): Boolean {
val fieldValue = request.header("If-None-Match")?.parsedForEtags()
return fieldValue != null && etagMatch(fieldValue)
}
private fun etagMatch(fieldValue: FieldValue): Boolean {
val localEtag = etag
return when {
localEtag == null -> false
fieldValue === FieldValue.Wildcard -> true
fieldValue is FieldValue.ETags -> fieldValue.hasAnEtagWithValue(localEtag.value)
else -> false
}
}
}
private val dateTimeFormatter = RFC_1123_DATE_TIME.withZone(ZoneOffset.UTC)
private fun Instant.formattedWith(formatter: DateTimeFormatter) = formatter.format(this)
private fun String.parsedWith(formatter: DateTimeFormatter): Instant? =
try {
Instant.from(formatter.parse(this))
} catch (x: Exception) {
null // "if the passed If-Modified-Since date is invalid, the response is exactly the same as for a normal GET"
}
private fun String.parsedForEtags(): FieldValue = ETagValidationRequestParser.parse(this)
private fun FieldValue.ETags.hasAnEtagWithValue(value: String) = this.value.map(ETag::value).contains(value)
| http4k-incubator/src/main/kotlin/org/http4k/routing/experimental/Resource.kt | 2553189001 |
package org.http4k.format
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.squareup.moshi.Moshi.Builder
import org.http4k.format.StrictnessMode.FailOnUnknown
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
class MoshiYamlAutoTest : AutoMarshallingContract(MoshiYaml) {
override val expectedAutoMarshallingResult: String = "string:hello\n" +
"child:\n" +
" string:world\n" +
" numbers:\n" +
" - 1.0\n" +
" bool:true\n" +
"numbers:[\n" +
" ]\n" +
"bool:false\n"
override val expectedAutoMarshallingResultPrimitives: String = "duration:PT1S\n" +
"localDate:'2000-01-01'\n" +
"localTime:01:01:01\n" +
"localDateTime:'2000-01-01T01:01:01'\n" +
"zonedDateTime:2000-01-01T01:01:01Z[UTC]\n" +
"offsetTime:01:01:01Z\n" +
"offsetDateTime:'2000-01-01T01:01:01Z'\n" +
"instant:'1970-01-01T00:00:00Z'\n" +
"uuid:1a448854-1687-4f90-9562-7d527d64383c\n" +
"uri:http://uri:8000\n" +
"url:http://url:9000\n" +
"status:200.0\n"
override val expectedWrappedMap: String = "value:\n" +
" key:value\n" +
" key2:'123'\n"
override val expectedConvertToInputStream: String = "value:hello\n"
override val expectedThrowable: String = """value: "org.http4k.format.CustomException: foobar"""
override val inputUnknownValue: String = """value: "value"
unknown: "2000-01-01"
"""
override val inputEmptyObject: String = """"""
override val expectedRegexSpecial: String = """regex: .*
"""
override val expectedMap = "key:value\n" +
"key2:'123'\n"
override val expectedAutoMarshallingZonesAndLocale = "zoneId:America/Toronto\nzoneOffset:-04:00\nlocale:en-CA\n"
override fun strictMarshaller() = object : ConfigurableMoshiYaml(
Builder().asConfigurable().customise(), strictness = FailOnUnknown
) {}
override fun customMarshaller() = ConfigurableMoshiYaml(Builder().asConfigurable().customise()
.add(NullSafeMapAdapter).add(ListAdapter))
override fun customMarshallerProhibitStrings() = ConfigurableMoshiYaml(
Builder().asConfigurable().prohibitStrings()
.customise()
)
data class MapHolder(val map: Map<String, MapHolder?>)
@Test
fun `nulls are serialised for map entries`() {
val input = MapHolder(mapOf("key" to null))
assertThat(MoshiYaml.asFormatString(input), equalTo("map: {\n }\n"))
}
@Disabled("not supported")
override fun `throwable is marshalled`() {
}
@Disabled("not supported")
override fun `exception is marshalled`() {
}
@Test
override fun `roundtrip custom boolean`() {
val marshaller = customMarshaller()
val wrapper = BooleanHolder(true)
assertThat(marshaller.asFormatString(wrapper), equalTo("'true'\n"))
assertThat(marshaller.asA("true", BooleanHolder::class), equalTo(wrapper))
}
@Test
override fun `roundtrip custom decimal`() {
val marshaller = customMarshaller()
val wrapper = BigDecimalHolder(1.01.toBigDecimal())
assertThat(marshaller.asFormatString(wrapper), equalTo("'1.01'\n"))
assertThat(marshaller.asA("1.01", BigDecimalHolder::class), equalTo(wrapper))
}
@Test
override fun `roundtrip custom number`() {
val marshaller = customMarshaller()
val wrapper = BigIntegerHolder(1.toBigInteger())
assertThat(marshaller.asFormatString(wrapper), equalTo("'1'\n"))
assertThat(marshaller.asA("1", BigIntegerHolder::class), equalTo(wrapper))
}
@Test
override fun `roundtrip custom value`() {
val marshaller = customMarshaller()
val wrapper = MyValueHolder(MyValue("foobar"))
assertThat(marshaller.asFormatString(wrapper), equalTo("value: foobar\n"))
assertThat(marshaller.asA("value: foobar\n", MyValueHolder::class), equalTo(wrapper))
assertThat(marshaller.asA("value: \n", MyValueHolder::class), equalTo(MyValueHolder(null)))
}
@Test
fun `on as a key is not quoted`() {
val wrapper = mapOf("on" to "hello")
assertThat(MoshiYaml.asFormatString(wrapper), equalTo("on: hello\n"))
}
}
| http4k-format/moshi-yaml/src/test/kotlin/org/http4k/format/moshiYamlTests.kt | 3508321342 |
package com.muhron.kotlinq
import org.junit.Assert
import org.junit.Test
class GroupByTest {
@Test
fun testA() {
val result = sequenceOf(1, 2, 3, 4, 5, 1, 2, 3, 1).groupBy { it }.toList()
Assert.assertEquals(result.size, 5);
Assert.assertEquals(result.elementAt(0).key, 1);
Assert.assertEquals(result.elementAt(0).asSequence().toList(), listOf(1, 1, 1));
Assert.assertEquals(result.elementAt(1).key, 2);
Assert.assertEquals(result.elementAt(1).asSequence().toList(), listOf(2, 2));
Assert.assertEquals(result.elementAt(2).key, 3);
Assert.assertEquals(result.elementAt(2).asSequence().toList(), listOf(3, 3));
Assert.assertEquals(result.elementAt(3).key, 4);
Assert.assertEquals(result.elementAt(3).asSequence().toList(), listOf(4));
Assert.assertEquals(result.elementAt(4).key, 5);
Assert.assertEquals(result.elementAt(4).asSequence().toList(), listOf(5));
}
@Test
fun testB() {
val result = sequenceOf(1, 2, 3, 4, 5, 1, 2, 3, 1)
.groupBy(keySelector = { it }, elementSelector = { it.toString() })
.toList()
Assert.assertEquals(result.size, 5);
Assert.assertEquals(result.elementAt(0).key, 1);
Assert.assertEquals(result.elementAt(0).asSequence().toList(), listOf("1", "1", "1"));
Assert.assertEquals(result.elementAt(1).key, 2);
Assert.assertEquals(result.elementAt(1).asSequence().toList(), listOf("2", "2"));
Assert.assertEquals(result.elementAt(2).key, 3);
Assert.assertEquals(result.elementAt(2).asSequence().toList(), listOf("3", "3"));
Assert.assertEquals(result.elementAt(3).key, 4);
Assert.assertEquals(result.elementAt(3).asSequence().toList(), listOf("4"));
Assert.assertEquals(result.elementAt(4).key, 5);
Assert.assertEquals(result.elementAt(4).asSequence().toList(), listOf("5"));
}
@Test
fun testC() {
val result = sequenceOf(1, 2, 3, 4, 5, 1, 2, 3, 1)
.groupBy(keySelector = { it }, resultSelector = { key, sequences -> sequences.sum() })
.toList()
Assert.assertEquals(result.size, 5);
Assert.assertEquals(result, listOf(3, 4, 6, 4, 5))
}
@Test
fun testD() {
val result = sequenceOf(1, 2, 3, 4, 5, 1, 2, 3, 1)
.groupBy(keySelector = { it }, elementSelector = { it.toString() }, resultSelector = { key, sequences -> sequences.joinToString() })
.toList()
Assert.assertEquals(result.size, 5);
Assert.assertEquals(result, listOf("1, 1, 1", "2, 2", "3, 3", "4", "5"))
}
@Test
fun testNoThrownException1() {
exceptionSequence<Int>().groupBy(keySelector = { it })
exceptionSequence<Int>().groupBy(keySelector = { it }, resultSelector = { key, sequences -> key })
exceptionSequence<Int>().groupBy(keySelector = { it }, elementSelector = { it })
exceptionSequence<Int>().groupBy(keySelector = { it }, elementSelector = { it }, resultSelector = { key, sequences -> key })
}
}
| src/test/kotlin/com/muhron/kotlinq/GroupByTest.kt | 2233133784 |
package cm.aptoide.pt.aab
import java.util.*
class SplitsMapper {
fun mapSplits(splits: List<cm.aptoide.pt.dataprovider.model.v7.Split>?): List<Split> {
val splitsMapResult = ArrayList<Split>()
if (splits == null) return splitsMapResult
for (split in splits) {
splitsMapResult.add(
Split(split.name, split.type, split.path, split.filesize,
split.md5sum))
}
return splitsMapResult
}
} | app/src/main/java/cm/aptoide/pt/aab/SplitsMapper.kt | 3630478175 |
package com.google.codelabs.mdc.kotlin.shrine
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumented test, which will execute on an Android device.
*
* @see [Testing documentation](http://d.android.com/tools/testing)
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.google.codelabs.mdc.java.shrine", appContext.packageName)
}
}
| kotlin/shrine/app/src/androidTest/java/com/google/codelabs/mdc/kotlin/shrine/ExampleInstrumentedTest.kt | 4019588304 |
package io.gitlab.arturbosch.detekt.formatting.wrappers
import com.pinterest.ktlint.ruleset.standard.SpacingAroundParensRule
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.formatting.FormattingRule
/**
* See <a href="https://ktlint.github.io/#rule-spacing">ktlint-website</a> for documentation.
*
* @active since v1.0.0
* @autoCorrect since v1.0.0
*/
class SpacingAroundParens(config: Config) : FormattingRule(config) {
override val wrapping = SpacingAroundParensRule()
override val issue = issueFor("Reports spaces around parentheses")
}
| detekt-formatting/src/main/kotlin/io/gitlab/arturbosch/detekt/formatting/wrappers/SpacingAroundParens.kt | 2474421936 |
package de.christinecoenen.code.zapp.app.mediathek.controller.downloads
import android.content.Context
import android.net.ConnectivityManager
import com.tonyodev.fetch2.*
import com.tonyodev.fetch2.Fetch.Impl.getInstance
import com.tonyodev.fetch2.database.DownloadInfo
import com.tonyodev.fetch2core.DownloadBlock
import com.tonyodev.fetch2core.Downloader.FileDownloaderType
import com.tonyodev.fetch2okhttp.OkHttpDownloader
import de.christinecoenen.code.zapp.app.mediathek.controller.downloads.exceptions.DownloadException
import de.christinecoenen.code.zapp.app.mediathek.controller.downloads.exceptions.NoNetworkException
import de.christinecoenen.code.zapp.app.mediathek.controller.downloads.exceptions.WrongNetworkConditionException
import de.christinecoenen.code.zapp.app.settings.repository.SettingsRepository
import de.christinecoenen.code.zapp.models.shows.DownloadStatus
import de.christinecoenen.code.zapp.models.shows.PersistedMediathekShow
import de.christinecoenen.code.zapp.models.shows.Quality
import de.christinecoenen.code.zapp.repositories.MediathekRepository
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import okhttp3.JavaNetCookieJar
import okhttp3.OkHttpClient
import org.joda.time.DateTime
import java.net.CookieManager
import java.net.CookiePolicy
import java.util.concurrent.TimeUnit
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
class DownloadController(
applicationContext: Context,
private val mediathekRepository: MediathekRepository
) : FetchListener, IDownloadController {
private lateinit var fetch: Fetch
private val connectivityManager: ConnectivityManager =
applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
private val settingsRepository: SettingsRepository = SettingsRepository(applicationContext)
private val downloadFileInfoManager: DownloadFileInfoManager =
DownloadFileInfoManager(applicationContext, settingsRepository)
init {
val cookieManager = CookieManager()
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL)
val client: OkHttpClient = OkHttpClient.Builder()
.readTimeout(40, TimeUnit.SECONDS) // fetch default: 20 seconds
.connectTimeout(30, TimeUnit.SECONDS) // fetch default: 15 seconds
.cache(null)
.followRedirects(true)
.followSslRedirects(true)
.retryOnConnectionFailure(false)
.cookieJar(JavaNetCookieJar(cookieManager))
.build()
val fetchConfiguration: FetchConfiguration = FetchConfiguration.Builder(applicationContext)
.setNotificationManager(object :
ZappNotificationManager(applicationContext, mediathekRepository) {
override fun getFetchInstanceForNamespace(namespace: String): Fetch {
return fetch
}
})
.enableRetryOnNetworkGain(false)
.setAutoRetryMaxAttempts(0)
.setDownloadConcurrentLimit(1)
.preAllocateFileOnCreation(false) // true causes downloads to sd card to hang
.setHttpDownloader(OkHttpDownloader(client, FileDownloaderType.SEQUENTIAL))
.enableLogging(true)
.build()
fetch = getInstance(fetchConfiguration)
fetch.addListener(this)
}
override suspend fun startDownload(show: PersistedMediathekShow, quality: Quality) {
val downloadUrl = show.mediathekShow.getVideoUrl(quality)
?: throw DownloadException("$quality is no valid download quality.")
val download = getDownload(show.downloadId)
if (download.id != 0 && download.url == downloadUrl) {
// same quality as existing download
// save new settings to request
applySettingsToRequest(download.request)
fetch.updateRequest(download.id, download.request, false, null, null)
// update show properties
show.downloadedAt = DateTime.now()
show.downloadProgress = 0
mediathekRepository.updateShow(show)
// retry
fetch.retry(show.downloadId)
} else {
// delete old file with wrong quality
fetch.delete(show.downloadId)
val filePath =
downloadFileInfoManager.getDownloadFilePath(show.mediathekShow, quality)
val request: Request
try {
request = Request(downloadUrl, filePath)
request.identifier = show.id.toLong()
} catch (e: Exception) {
throw DownloadException("Constructing download request failed.", e)
}
// update show properties
show.downloadId = request.id
show.downloadedAt = DateTime.now()
show.downloadProgress = 0
mediathekRepository.updateShow(show)
enqueueDownload(request)
}
}
override fun stopDownload(persistedShowId: Int) {
fetch.getDownloadsByRequestIdentifier(persistedShowId.toLong()) { downloadList ->
for (download in downloadList) {
fetch.cancel(download.id)
}
}
}
override fun deleteDownload(persistedShowId: Int) {
fetch.getDownloadsByRequestIdentifier(persistedShowId.toLong()) { downloadList ->
for (download in downloadList) {
fetch.delete(download.id)
}
}
}
override fun getDownloadStatus(persistedShowId: Int): Flow<DownloadStatus> {
return mediathekRepository.getDownloadStatus(persistedShowId)
}
override fun getDownloadProgress(persistedShowId: Int): Flow<Int> {
return mediathekRepository.getDownloadProgress(persistedShowId)
}
override fun deleteDownloadsWithDeletedFiles() {
fetch.getDownloadsWithStatus(Status.COMPLETED) { downloads ->
for (download in downloads) {
if (downloadFileInfoManager.shouldDeleteDownload(download)) {
fetch.remove(download.id)
}
}
}
}
/**
* @return download with the given id or empty download with id of 0
*/
private suspend fun getDownload(downloadId: Int): Download = suspendCoroutine { continuation ->
fetch.getDownload(downloadId) { download ->
if (download == null) {
continuation.resume(DownloadInfo())
} else {
continuation.resume(download)
}
}
}
private fun enqueueDownload(request: Request) {
applySettingsToRequest(request)
fetch.enqueue(request, null, null)
}
private fun applySettingsToRequest(request: Request) {
request.networkType = if (settingsRepository.downloadOverUnmeteredNetworkOnly) {
NetworkType.UNMETERED
} else {
NetworkType.ALL
}
if (connectivityManager.activeNetwork == null) {
throw NoNetworkException("No active network available.")
}
if (settingsRepository.downloadOverUnmeteredNetworkOnly && connectivityManager.isActiveNetworkMetered) {
throw WrongNetworkConditionException("Download over metered networks prohibited.")
}
}
private suspend fun updateDownloadStatus(download: Download) {
val downloadStatus = DownloadStatus.values()[download.status.value]
mediathekRepository.updateDownloadStatus(download.id, downloadStatus)
}
private suspend fun updateDownloadProgress(download: Download, progress: Int) {
mediathekRepository.updateDownloadProgress(download.id, progress)
}
override fun onAdded(download: Download) {
GlobalScope.launch {
updateDownloadStatus(download)
}
}
override fun onCancelled(download: Download) {
GlobalScope.launch {
fetch.delete(download.id)
updateDownloadStatus(download)
updateDownloadProgress(download, 0)
}
}
override fun onCompleted(download: Download) {
GlobalScope.launch {
updateDownloadStatus(download)
mediathekRepository.updateDownloadedVideoPath(download.id, download.file)
downloadFileInfoManager.updateDownloadFileInMediaCollection(download)
}
}
override fun onDeleted(download: Download) {
GlobalScope.launch {
updateDownloadStatus(download)
updateDownloadProgress(download, 0)
downloadFileInfoManager.updateDownloadFileInMediaCollection(download)
}
}
override fun onDownloadBlockUpdated(
download: Download,
downloadBlock: DownloadBlock,
totalBlocks: Int
) {
}
override fun onError(download: Download, error: Error, throwable: Throwable?) {
GlobalScope.launch {
downloadFileInfoManager.deleteDownloadFile(download)
updateDownloadStatus(download)
}
}
override fun onPaused(download: Download) {
GlobalScope.launch {
updateDownloadStatus(download)
}
}
override fun onProgress(
download: Download,
etaInMilliSeconds: Long,
downloadedBytesPerSecond: Long
) {
GlobalScope.launch {
updateDownloadProgress(download, download.progress)
}
}
override fun onQueued(download: Download, waitingOnNetwork: Boolean) {
GlobalScope.launch {
updateDownloadStatus(download)
}
}
override fun onRemoved(download: Download) {
GlobalScope.launch {
updateDownloadStatus(download)
}
}
override fun onResumed(download: Download) {
GlobalScope.launch {
updateDownloadStatus(download)
}
}
override fun onStarted(
download: Download,
downloadBlocks: List<DownloadBlock>,
totalBlocks: Int
) {
GlobalScope.launch {
updateDownloadStatus(download)
}
}
override fun onWaitingNetwork(download: Download) {
GlobalScope.launch {
updateDownloadStatus(download)
}
}
}
| app/src/main/java/de/christinecoenen/code/zapp/app/mediathek/controller/downloads/DownloadController.kt | 1305324581 |
/*
* Copyright 2018-present Facebook, 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.facebook.buck.datascience.traces
class CollectDeviceSerials : TraceAnalysisVisitor<Map<String, Long>> {
companion object {
val PATTERN_EMULATOR = Regex("^emulator-\\d+$")
val PATTERN_GENYMOTION = Regex("^[\\d.:\\[\\]]+:5\\d\\d\\d$")
}
/**
* Map of serial number to number of installations.
* It seems unlikely that we'd ever have more than one for a single trace, but be safe.
* Multiple keys can be present with "buck install -x".
*/
private val serialCounts = mutableMapOf<String, Long>()
override fun traceComplete() = serialCounts
override fun finishAnalysis(args: List<String>, intermediates: List<Map<String, Long>>) {
// Add up the maps from each trace.
val totals = mutableMapOf<String, Long>()
intermediates.forEach {
it.forEach { k, v ->
totals[k] = v + totals.getOrDefault(k, 0)
}
}
totals.toSortedMap().forEach { serial, count ->
System.out.println("%24s %d".format(serial, count))
}
System.out.println()
// Group and count by device type.
val kinds = mutableMapOf<String, Long>()
totals.forEach { k, v ->
val kind = when {
k.matches(PATTERN_EMULATOR) -> "emulator"
k.matches(PATTERN_GENYMOTION) -> "genymotion"
else -> "device"
}
kinds[kind] = v + kinds.getOrDefault(kind, 0)
}
kinds.toSortedMap().forEach { kind, count ->
System.out.println("%12s %d".format(kind, count))
}
}
override fun eventBegin(event: TraceEvent, state: TraceState) {
if (event.name == "adb_call install exopackage apk") {
val serial = event.args["device_serial"].textValue()
if (serial != null) {
serialCounts[serial] = 1 + serialCounts.getOrDefault(serial, 0)
}
}
}
}
| tools/datascience/src/com/facebook/buck/datascience/traces/CollectDeviceSerials.kt | 3093100139 |
package com.developer.davidtc.flickrpublicfeedandroid.rest.publicfeed.response
/**
* Created by david.tiago on 11/26/17.
*/
data class MediaResponse (val m: String) | app/src/main/java/com/developer/davidtc/flickrpublicfeedandroid/rest/publicfeed/response/MediaResponse.kt | 2444890553 |
package ca.jonathanfritz.funopoly.game
import ca.jonathanfritz.funopoly.game.board.ChanceCard
import ca.jonathanfritz.funopoly.game.board.CommunityChestCard
import ca.jonathanfritz.funopoly.game.board.Deck
class Bank(
private var houses: Int,
private var hotels: Int,
private var funds: Int,
val chance: Deck<ChanceCard>,
val communityChest: Deck<CommunityChestCard>
) {
private var chanceDeckIndex: Int = 0
fun transferTo(player: Player, amount: Int) {
println("Bank transfers $amount to ${player.name}")
funds -= amount
player.credit(funds)
}
fun transferFrom(amount: Int, player: Player) {
println("Player transfers $amount to Bank")
// TODO: what happens if player can't afford this? throw an exception?
player.debit(amount)
funds += amount
}
} | src/main/kotlin/ca/jonathanfritz/funopoly/game/Bank.kt | 2512017213 |
package de.randombyte.holograms
import com.google.inject.Inject
import de.randombyte.holograms.api.HologramsService
import de.randombyte.holograms.commands.ListNearbyHologramsCommand
import de.randombyte.holograms.commands.SetNearestHologramText
import de.randombyte.holograms.commands.SpawnMultiLineTextHologramCommand
import de.randombyte.holograms.commands.SpawnTextHologramCommand
import de.randombyte.holograms.data.HologramData
import de.randombyte.holograms.data.HologramKeys
import de.randombyte.kosp.extensions.toText
import org.bstats.sponge.Metrics2
import org.slf4j.Logger
import org.spongepowered.api.Sponge
import org.spongepowered.api.command.args.GenericArguments.*
import org.spongepowered.api.command.spec.CommandSpec
import org.spongepowered.api.config.ConfigDir
import org.spongepowered.api.data.DataRegistration
import org.spongepowered.api.event.Listener
import org.spongepowered.api.event.game.GameReloadEvent
import org.spongepowered.api.event.game.state.GameInitializationEvent
import org.spongepowered.api.event.game.state.GamePreInitializationEvent
import org.spongepowered.api.plugin.Plugin
import org.spongepowered.api.plugin.PluginContainer
import java.nio.file.Files
import java.nio.file.Path
@Plugin(id = Holograms.ID, name = Holograms.NAME, version = Holograms.VERSION, authors = arrayOf(Holograms.AUTHOR))
class Holograms @Inject constructor(
private val logger: Logger,
@ConfigDir(sharedRoot = false) private val configPath: Path,
private val pluginContainer: PluginContainer,
val bStats: Metrics2
) {
companion object {
const val NAME = "Holograms"
const val ID = "holograms"
const val VERSION = "3.2.0"
const val AUTHOR = "RandomByte"
}
val inputFile: Path = configPath.resolve("input.txt")
@Listener
fun onPreInit(event: GamePreInitializationEvent) {
Sponge.getServiceManager().setProvider(this, HologramsService::class.java, HologramsServiceImpl())
HologramKeys.buildKeys()
Sponge.getDataManager().registerLegacyManipulatorIds("de.randombyte.holograms.data.HologramData", DataRegistration.builder()
.dataClass(HologramData::class.java)
.immutableClass(HologramData.Immutable::class.java)
.builder(HologramData.Builder())
.manipulatorId("holograms-data")
.dataName("Holograms Data")
.buildAndRegister(pluginContainer))
}
@Listener
fun onInit(event: GameInitializationEvent) {
inputFile.safelyCreateFile()
Sponge.getCommandManager().register(this, CommandSpec.builder()
.permission("holograms.list")
.executor(ListNearbyHologramsCommand(this))
.arguments(optional(integer("maxDistance".toText())))
.child(CommandSpec.builder()
.permission("holograms.create")
.arguments(remainingJoinedStrings("text".toText()))
.executor(SpawnTextHologramCommand())
.build(), "create")
.child(CommandSpec.builder()
.permission("holograms.createMultiLine")
.arguments(seq(
doubleNum("verticalSpace".toText()),
firstParsing(
integer("numberOfLines".toText()),
remainingJoinedStrings("texts".toText())
)
))
.executor(SpawnMultiLineTextHologramCommand())
.build(), "createMultiLine", "cml")
.child(CommandSpec.builder()
.permission("holograms.list")
.arguments(optional(integer("maxDistance".toText())))
.executor(ListNearbyHologramsCommand(this))
.build(), "list")
.child(CommandSpec.builder()
.permission("holograms.setText")
.arguments(remainingJoinedStrings("text".toText()))
.executor(SetNearestHologramText())
.build(), "setText")
.build(), "holograms")
logger.info("$NAME loaded: $VERSION")
}
@Listener
fun onReload(event: GameReloadEvent) {
inputFile.safelyCreateFile()
}
private fun Path.safelyCreateFile() {
if (!Files.exists(this)) {
Files.createDirectories(this.parent)
Files.createFile(this)
}
}
}
| src/main/kotlin/de/randombyte/holograms/Holograms.kt | 2733300432 |
package de.westnordost.streetcomplete.data.osm.edits
import de.westnordost.streetcomplete.data.osm.mapdata.Element
import de.westnordost.streetcomplete.data.osm.mapdata.MapDataChanges
import de.westnordost.streetcomplete.data.osm.mapdata.MapDataRepository
interface ElementEditAction {
/** the number of new elements this edit creates. This needs to be stated in advance so that
* negative element ids can be reserved for this edit: The same element id needs to be used
* when applying the edit locally and when uploading the edit */
val newElementsCount: NewElementsCount get() = NewElementsCount(0,0,0)
/** Using the given map data repository (if necessary) and the id provider (if this action
* creates new elements), this function should return all updated elements this action produces
* when applied to the given element or throw a ElementConflictException
* */
fun createUpdates(
originalElement: Element,
element: Element?,
mapDataRepository: MapDataRepository,
idProvider: ElementIdProvider
): MapDataChanges
}
data class NewElementsCount(val nodes: Int, val ways: Int, val relations: Int)
interface IsActionRevertable {
fun createReverted(): ElementEditAction
}
interface IsRevertAction
| app/src/main/java/de/westnordost/streetcomplete/data/osm/edits/ElementEditAction.kt | 552035143 |
package ninenine.com.duplicateuser.presenter
import ninenine.com.duplicateuser.view.UserContractView
interface UserPresenter : Presenter<UserContractView>{
fun loadUsers()
} | app/src/main/java/ninenine/com/duplicateuser/presenter/UserPresenter.kt | 891636221 |
package me.shkschneider.skeleton.extensions
// Flags
fun Int.has(other: Int): Boolean =
(this and other) != 0
fun Long.has(other: Long): Boolean =
(this and other) != 0.toLong()
| core/src/main/kotlin/me/shkschneider/skeleton/extensions/_Number.kt | 855309760 |
package org.wordpress.android.fluxc.model
import com.yarolegovich.wellsql.core.Identifiable
import com.yarolegovich.wellsql.core.annotation.Column
import com.yarolegovich.wellsql.core.annotation.PrimaryKey
import com.yarolegovich.wellsql.core.annotation.RawConstraints
import com.yarolegovich.wellsql.core.annotation.Table
import org.wordpress.android.fluxc.persistence.WellSqlConfig
@Table(addOn = WellSqlConfig.ADDON_WOOCOMMERCE)
@RawConstraints(
"FOREIGN KEY(LOCAL_SITE_ID) REFERENCES SiteModel(_id) ON DELETE CASCADE",
"UNIQUE (REMOTE_TAG_ID, LOCAL_SITE_ID) ON CONFLICT REPLACE"
)
class WCProductTagModel(@PrimaryKey @Column private var id: Int = 0) : Identifiable {
@Column var localSiteId = 0
@Column var remoteTagId = 0L // The unique identifier for this tag on the server
@Column var name = ""
@Column var slug = ""
@Column var description = ""
@Column var count = 0
override fun getId() = id
override fun setId(id: Int) {
this.id = id
}
}
| plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/model/WCProductTagModel.kt | 898315673 |
package com.github.perseacado.feedbackui.slack.client
/**
* @author Marco Eigletsberger, 24.06.16.
*/
object SlackClientFactory {
/**
* Creates a new [SlackClient] with the given [token].
* @param[token] the Slack API token
* @return a new [SlackClient] using the given [SlackClient].
*/
fun create(token: String): SlackClient = SlackClientImpl(token)
} | feedback-ui-slack/src/main/java/com/github/perseacado/feedbackui/slack/client/SlackClientFactory.kt | 3761328566 |
package org.wordpress.android.fluxc.model.encryptedlogging
import android.util.Base64
import com.goterl.lazysodium.interfaces.SecretStream
import com.goterl.lazysodium.interfaces.SecretStream.State
import com.goterl.lazysodium.utils.Key
import dagger.Reusable
import javax.inject.Inject
private const val ENCODED_ENCRYPTED_KEY_LENGTH = 108
private const val ENCODED_HEADER_LENGTH = 32
data class EncryptedLoggingKey(val publicKey: Key)
/**
* [LogEncrypter] encrypts the logs for the given text.
**
* @param encryptedLoggingKey The public key used to encrypt the log
*
*/
@Reusable
class LogEncrypter @Inject constructor(private val encryptedLoggingKey: EncryptedLoggingKey) {
/**
* Encrypts the given [text]. It also adds the given [uuid] to its headers.
*
* @param text Text contents to be encrypted
* @param uuid Uuid for the encrypted log
*/
fun encrypt(text: String, uuid: String): String = buildString {
val state = State.ByReference()
append(buildHeader(uuid, state))
val lines = text.lines()
lines.asSequence().mapIndexed { index, line ->
if (index + 1 >= lines.size) {
// If it's the last element
line
} else {
"$line\n"
}
}.forEach { line ->
append(buildMessage(line, state))
}
append(buildFooter(state))
}
/**
* Encrypt and write the provided string to the encrypted log file.
* @param string: The string to be written to the file.
*/
private fun buildMessage(string: String, state: State): String {
val encryptedString = encryptMessage(string, SecretStream.TAG_MESSAGE, state)
return "\t\t\"$encryptedString\",\n"
}
/**
* An internal convenience function to extract the header building process.
*/
private fun buildHeader(uuid: String, state: State): String {
val header = ByteArray(SecretStream.HEADERBYTES)
val key = SecretStreamKey.generate().let {
check(EncryptionUtils.sodium.cryptoSecretStreamInitPush(state, header, it.bytes))
it.encrypt(encryptedLoggingKey.publicKey)
}
require(SecretStream.Checker.headerCheck(header.size)) {
"The secret stream header must be the correct length"
}
val encodedEncryptedKey = base64Encode(key.bytes)
check(encodedEncryptedKey.length == ENCODED_ENCRYPTED_KEY_LENGTH) {
"The encoded, encrypted key must always be $ENCODED_ENCRYPTED_KEY_LENGTH bytes long"
}
val encodedHeader = base64Encode(header)
check(encodedHeader.length == ENCODED_HEADER_LENGTH) {
"The encoded header must always be $ENCODED_HEADER_LENGTH bytes long"
}
return buildString {
append("{")
append("\t\"keyedWith\": \"v1\",\n")
append("\t\"encryptedKey\": \"$encodedEncryptedKey\",\n")
append("\t\"header\": \"$encodedHeader\",\n")
append("\t\"uuid\": \"$uuid\",\n")
append("\t\"messages\": [\n")
}
}
/**
* Add the closing file tag
*/
private fun buildFooter(state: State): String {
val encryptedClosingTag = encryptMessage("", SecretStream.TAG_FINAL, state)
return buildString {
append("\t\t\"$encryptedClosingTag\"\n")
append("\t]\n")
append("}")
}
}
/**
* An internal convenience function to push more data into the sodium secret stream.
*/
private fun encryptMessage(string: String, tag: Byte, state: State): String {
val plainBytes = string.toByteArray()
val encryptedBytes = ByteArray(SecretStream.ABYTES + plainBytes.size) // Stores the encrypted bytes
check(
EncryptionUtils.sodium.cryptoSecretStreamPush(
state,
encryptedBytes,
plainBytes,
plainBytes.size.toLong(),
tag
)
) {
"Unable to encrypt message: $string"
}
return base64Encode(encryptedBytes)
}
}
// On Android base64 has lots of options, so define a helper to make it easier to
// avoid encoding issues.
private fun base64Encode(byteArray: ByteArray): String {
return Base64.encodeToString(byteArray, Base64.NO_WRAP)
}
| fluxc/src/main/java/org/wordpress/android/fluxc/model/encryptedlogging/LogEncrypter.kt | 940747259 |
/*
* Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.cbor
import kotlinx.serialization.*
import kotlinx.serialization.builtins.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
@Serializable
data class Simple(val a: String)
@Serializable
data class TypesUmbrella(
val str: String,
val i: Int,
val nullable: Double?,
val list: List<String>,
val map: Map<Int, Boolean>,
val inner: Simple,
val innersList: List<Simple>,
@ByteString val byteString: ByteArray,
val byteArray: ByteArray
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as TypesUmbrella
if (str != other.str) return false
if (i != other.i) return false
if (nullable != other.nullable) return false
if (list != other.list) return false
if (map != other.map) return false
if (inner != other.inner) return false
if (innersList != other.innersList) return false
if (!byteString.contentEquals(other.byteString)) return false
if (!byteArray.contentEquals(other.byteArray)) return false
return true
}
override fun hashCode(): Int {
var result = str.hashCode()
result = 31 * result + i
result = 31 * result + (nullable?.hashCode() ?: 0)
result = 31 * result + list.hashCode()
result = 31 * result + map.hashCode()
result = 31 * result + inner.hashCode()
result = 31 * result + innersList.hashCode()
result = 31 * result + byteString.contentHashCode()
result = 31 * result + byteArray.contentHashCode()
return result
}
}
@Serializable
data class NumberTypesUmbrella(
val int: Int,
val long: Long,
val float: Float,
val double: Double,
val boolean: Boolean,
val char: Char
)
@Serializable
data class NullableByteString(
@ByteString val byteString: ByteArray?
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as NullableByteString
if (byteString != null) {
if (other.byteString == null) return false
if (!byteString.contentEquals(other.byteString)) return false
} else if (other.byteString != null) return false
return true
}
override fun hashCode(): Int {
return byteString?.contentHashCode() ?: 0
}
}
@Serializable(with = CustomByteStringSerializer::class)
data class CustomByteString(val a: Byte, val b: Byte, val c: Byte)
class CustomByteStringSerializer : KSerializer<CustomByteString> {
override val descriptor = SerialDescriptor("CustomByteString", ByteArraySerializer().descriptor)
override fun serialize(encoder: Encoder, value: CustomByteString) {
encoder.encodeSerializableValue(ByteArraySerializer(), byteArrayOf(value.a, value.b, value.c))
}
override fun deserialize(decoder: Decoder): CustomByteString {
val array = decoder.decodeSerializableValue(ByteArraySerializer())
return CustomByteString(array[0], array[1], array[2])
}
}
@Serializable
data class TypeWithCustomByteString(@ByteString val x: CustomByteString)
@Serializable
data class TypeWithNullableCustomByteString(@ByteString val x: CustomByteString?) | formats/cbor/commonTest/src/kotlinx/serialization/cbor/SampleClasses.kt | 112527948 |
/*
* Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.features
import kotlinx.serialization.*
import kotlinx.serialization.builtins.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.json.*
import kotlinx.serialization.modules.*
import kotlinx.serialization.test.*
import kotlin.test.*
class ContextAndPolymorphicTest {
@Serializable
data class Data(val a: Int, val b: Int = 42)
@Serializable
data class EnhancedData(
val data: Data,
@Contextual val stringPayload: Payload,
@Serializable(with = BinaryPayloadSerializer::class) val binaryPayload: Payload
)
@Serializable
@SerialName("Payload")
data class Payload(val s: String)
@Serializable
data class PayloadList(val ps: List<@Contextual Payload>)
@Serializer(forClass = Payload::class)
object PayloadSerializer
object BinaryPayloadSerializer : KSerializer<Payload> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("BinaryPayload", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: Payload) {
encoder.encodeString(InternalHexConverter.printHexBinary(value.s.encodeToByteArray()))
}
override fun deserialize(decoder: Decoder): Payload {
return Payload(InternalHexConverter.parseHexBinary(decoder.decodeString()).decodeToString())
}
}
private val value = EnhancedData(Data(100500), Payload("string"), Payload("binary"))
private lateinit var json: Json
@BeforeTest
fun initContext() {
val scope = serializersModuleOf(Payload::class, PayloadSerializer)
val bPolymorphicModule = SerializersModule { polymorphic(Any::class) { subclass(PayloadSerializer) } }
json = Json {
useArrayPolymorphism = true
encodeDefaults = true
serializersModule = scope + bPolymorphicModule
}
}
@Test
fun testWriteCustom() {
val s = json.encodeToString(EnhancedData.serializer(), value)
assertEquals("""{"data":{"a":100500,"b":42},"stringPayload":{"s":"string"},"binaryPayload":"62696E617279"}""", s)
}
@Test
fun testReadCustom() {
val s = json.decodeFromString(
EnhancedData.serializer(),
"""{"data":{"a":100500,"b":42},"stringPayload":{"s":"string"},"binaryPayload":"62696E617279"}""")
assertEquals(value, s)
}
@Test
fun testWriteCustomList() {
val s = json.encodeToString(PayloadList.serializer(), PayloadList(listOf(Payload("1"), Payload("2"))))
assertEquals("""{"ps":[{"s":"1"},{"s":"2"}]}""", s)
}
@Test
fun testPolymorphicResolve() {
val map = mapOf<String, Any>("Payload" to Payload("data"))
val serializer = MapSerializer(String.serializer(), PolymorphicSerializer(Any::class))
val s = json.encodeToString(serializer, map)
assertEquals("""{"Payload":["Payload",{"s":"data"}]}""", s)
}
@Test
fun testDifferentRepresentations() {
val simpleModule = serializersModuleOf(PayloadSerializer)
val binaryModule = serializersModuleOf(BinaryPayloadSerializer)
val json1 = Json { useArrayPolymorphism = true; serializersModule = simpleModule }
val json2 = Json { useArrayPolymorphism = true; serializersModule = binaryModule }
// in json1, Payload would be serialized with PayloadSerializer,
// in json2, Payload would be serialized with BinaryPayloadSerializer
val list = PayloadList(listOf(Payload("string")))
assertEquals("""{"ps":[{"s":"string"}]}""", json1.encodeToString(PayloadList.serializer(), list))
assertEquals("""{"ps":["737472696E67"]}""", json2.encodeToString(PayloadList.serializer(), list))
}
private fun SerialDescriptor.inContext(module: SerializersModule): SerialDescriptor = when (kind) {
SerialKind.CONTEXTUAL -> requireNotNull(module.getContextualDescriptor(this)) { "Expected $this to be registered in module" }
else -> error("Expected this function to be called on CONTEXTUAL descriptor")
}
@Test
fun testResolveContextualDescriptor() {
val simpleModule = serializersModuleOf(PayloadSerializer)
val binaryModule = serializersModuleOf(BinaryPayloadSerializer)
val contextDesc = EnhancedData.serializer().descriptor.elementDescriptors.toList()[1] // @ContextualSer stringPayload
assertEquals(SerialKind.CONTEXTUAL, contextDesc.kind)
assertEquals(0, contextDesc.elementsCount)
val resolvedToDefault = contextDesc.inContext(simpleModule)
assertEquals(StructureKind.CLASS, resolvedToDefault.kind)
assertEquals("Payload", resolvedToDefault.serialName)
assertEquals(1, resolvedToDefault.elementsCount)
val resolvedToBinary = contextDesc.inContext(binaryModule)
assertEquals(PrimitiveKind.STRING, resolvedToBinary.kind)
assertEquals("BinaryPayload", resolvedToBinary.serialName)
}
@Test
fun testContextualSerializerUsesDefaultIfModuleIsEmpty() {
val s = Json { useArrayPolymorphism = true; encodeDefaults = true }.encodeToString(EnhancedData.serializer(), value)
assertEquals("""{"data":{"a":100500,"b":42},"stringPayload":{"s":"string"},"binaryPayload":"62696E617279"}""", s)
}
}
| formats/json-tests/commonTest/src/kotlinx/serialization/features/ContextAndPolymorphicTest.kt | 2973691823 |
// Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.kingdom.service.internal.testing
import com.google.gson.JsonParser
import com.google.protobuf.kotlin.toByteStringUtf8
import com.google.rpc.ErrorInfo
import io.grpc.StatusRuntimeException
import io.grpc.protobuf.ProtoUtils
import java.time.Clock
import java.time.Instant
import java.time.temporal.ChronoUnit
import kotlin.random.Random
import org.wfanet.measurement.common.base64UrlDecode
import org.wfanet.measurement.common.crypto.hashSha256
import org.wfanet.measurement.common.crypto.tink.PublicJwkHandle
import org.wfanet.measurement.common.crypto.tink.SelfIssuedIdTokens
import org.wfanet.measurement.common.crypto.tink.SelfIssuedIdTokens.generateIdToken
import org.wfanet.measurement.common.identity.IdGenerator
import org.wfanet.measurement.common.openid.createRequestUri
import org.wfanet.measurement.common.toProtoTime
import org.wfanet.measurement.internal.kingdom.Account
import org.wfanet.measurement.internal.kingdom.AccountKt.openIdConnectIdentity
import org.wfanet.measurement.internal.kingdom.AccountsGrpcKt.AccountsCoroutineImplBase
import org.wfanet.measurement.internal.kingdom.Certificate
import org.wfanet.measurement.internal.kingdom.CertificateKt
import org.wfanet.measurement.internal.kingdom.CertificatesGrpcKt.CertificatesCoroutineImplBase
import org.wfanet.measurement.internal.kingdom.DataProvider
import org.wfanet.measurement.internal.kingdom.DataProviderKt
import org.wfanet.measurement.internal.kingdom.DataProvidersGrpcKt.DataProvidersCoroutineImplBase
import org.wfanet.measurement.internal.kingdom.DuchyProtocolConfigKt
import org.wfanet.measurement.internal.kingdom.Measurement
import org.wfanet.measurement.internal.kingdom.MeasurementConsumer
import org.wfanet.measurement.internal.kingdom.MeasurementConsumerKt
import org.wfanet.measurement.internal.kingdom.MeasurementConsumersGrpcKt.MeasurementConsumersCoroutineImplBase
import org.wfanet.measurement.internal.kingdom.MeasurementKt
import org.wfanet.measurement.internal.kingdom.MeasurementKt.dataProviderValue
import org.wfanet.measurement.internal.kingdom.MeasurementsGrpcKt.MeasurementsCoroutineImplBase
import org.wfanet.measurement.internal.kingdom.ModelProvider
import org.wfanet.measurement.internal.kingdom.ModelProvidersGrpcKt.ModelProvidersCoroutineImplBase
import org.wfanet.measurement.internal.kingdom.ProtocolConfigKt
import org.wfanet.measurement.internal.kingdom.account
import org.wfanet.measurement.internal.kingdom.activateAccountRequest
import org.wfanet.measurement.internal.kingdom.certificate
import org.wfanet.measurement.internal.kingdom.createMeasurementConsumerCreationTokenRequest
import org.wfanet.measurement.internal.kingdom.createMeasurementConsumerRequest
import org.wfanet.measurement.internal.kingdom.dataProvider
import org.wfanet.measurement.internal.kingdom.duchyProtocolConfig
import org.wfanet.measurement.internal.kingdom.generateOpenIdRequestParamsRequest
import org.wfanet.measurement.internal.kingdom.measurement
import org.wfanet.measurement.internal.kingdom.measurementConsumer
import org.wfanet.measurement.internal.kingdom.modelProvider
import org.wfanet.measurement.internal.kingdom.protocolConfig
private const val API_VERSION = "v2alpha"
class Population(val clock: Clock, val idGenerator: IdGenerator) {
private fun buildRequestCertificate(
derUtf8: String,
skidUtf8: String,
notValidBefore: Instant,
notValidAfter: Instant
) = certificate { fillRequestCertificate(derUtf8, skidUtf8, notValidBefore, notValidAfter) }
private fun CertificateKt.Dsl.fillRequestCertificate(
derUtf8: String,
skidUtf8: String,
notValidBefore: Instant,
notValidAfter: Instant
) {
this.notValidBefore = notValidBefore.toProtoTime()
this.notValidAfter = notValidAfter.toProtoTime()
subjectKeyIdentifier = skidUtf8.toByteStringUtf8()
details = CertificateKt.details { x509Der = derUtf8.toByteStringUtf8() }
}
suspend fun createMeasurementConsumer(
measurementConsumersService: MeasurementConsumersCoroutineImplBase,
accountsService: AccountsCoroutineImplBase,
notValidBefore: Instant = clock.instant(),
notValidAfter: Instant = notValidBefore.plus(365L, ChronoUnit.DAYS)
): MeasurementConsumer {
val account = createAccount(accountsService)
activateAccount(accountsService, account)
val measurementConsumerCreationTokenHash =
hashSha256(createMeasurementConsumerCreationToken(accountsService))
return measurementConsumersService.createMeasurementConsumer(
createMeasurementConsumerRequest {
measurementConsumer = measurementConsumer {
certificate =
buildRequestCertificate(
"MC cert",
"MC SKID " + idGenerator.generateExternalId().value,
notValidBefore,
notValidAfter
)
details =
MeasurementConsumerKt.details {
apiVersion = API_VERSION
publicKey = "MC public key".toByteStringUtf8()
publicKeySignature = "MC public key signature".toByteStringUtf8()
}
}
externalAccountId = account.externalAccountId
this.measurementConsumerCreationTokenHash = measurementConsumerCreationTokenHash
}
)
}
suspend fun createDataProvider(
dataProvidersService: DataProvidersCoroutineImplBase,
notValidBefore: Instant = clock.instant(),
notValidAfter: Instant = notValidBefore.plus(365L, ChronoUnit.DAYS)
): DataProvider {
return dataProvidersService.createDataProvider(
dataProvider {
certificate =
buildRequestCertificate(
"EDP cert",
"EDP SKID " + idGenerator.generateExternalId().value,
notValidBefore,
notValidAfter
)
details =
DataProviderKt.details {
apiVersion = API_VERSION
publicKey = "EDP public key".toByteStringUtf8()
publicKeySignature = "EDP public key signature".toByteStringUtf8()
}
}
)
}
suspend fun createModelProvider(
modelProvidersService: ModelProvidersCoroutineImplBase
): ModelProvider {
return modelProvidersService.createModelProvider(modelProvider {})
}
private suspend fun createMeasurement(
measurementsService: MeasurementsCoroutineImplBase,
measurementConsumer: MeasurementConsumer,
providedMeasurementId: String,
dataProviders: Map<Long, Measurement.DataProviderValue> = mapOf(),
details: Measurement.Details
): Measurement {
return measurementsService.createMeasurement(
measurement {
externalMeasurementConsumerId = measurementConsumer.externalMeasurementConsumerId
this.providedMeasurementId = providedMeasurementId
externalMeasurementConsumerCertificateId =
measurementConsumer.certificate.externalCertificateId
this.details = details
this.dataProviders.putAll(dataProviders)
}
)
}
suspend fun createComputedMeasurement(
measurementsService: MeasurementsCoroutineImplBase,
measurementConsumer: MeasurementConsumer,
providedMeasurementId: String,
dataProviders: Map<Long, Measurement.DataProviderValue> = mapOf()
): Measurement {
val details =
MeasurementKt.details {
apiVersion = API_VERSION
measurementSpec = "MeasurementSpec".toByteStringUtf8()
measurementSpecSignature = "MeasurementSpec signature".toByteStringUtf8()
duchyProtocolConfig = duchyProtocolConfig {
liquidLegionsV2 = DuchyProtocolConfigKt.liquidLegionsV2 {}
}
protocolConfig = protocolConfig { liquidLegionsV2 = ProtocolConfigKt.liquidLegionsV2 {} }
}
return createMeasurement(
measurementsService,
measurementConsumer,
providedMeasurementId,
dataProviders,
details
)
}
suspend fun createComputedMeasurement(
measurementsService: MeasurementsCoroutineImplBase,
measurementConsumer: MeasurementConsumer,
providedMeasurementId: String,
vararg dataProviders: DataProvider
): Measurement {
return createComputedMeasurement(
measurementsService,
measurementConsumer,
providedMeasurementId,
dataProviders.associate { it.externalDataProviderId to it.toDataProviderValue() }
)
}
suspend fun createDirectMeasurement(
measurementsService: MeasurementsCoroutineImplBase,
measurementConsumer: MeasurementConsumer,
providedMeasurementId: String,
dataProviders: Map<Long, Measurement.DataProviderValue> = mapOf()
): Measurement {
val details =
MeasurementKt.details {
apiVersion = API_VERSION
measurementSpec = "MeasurementSpec".toByteStringUtf8()
measurementSpecSignature = "MeasurementSpec signature".toByteStringUtf8()
}
return createMeasurement(
measurementsService,
measurementConsumer,
providedMeasurementId,
dataProviders,
details
)
}
suspend fun createDirectMeasurement(
measurementsService: MeasurementsCoroutineImplBase,
measurementConsumer: MeasurementConsumer,
providedMeasurementId: String,
vararg dataProviders: DataProvider
): Measurement {
return createDirectMeasurement(
measurementsService,
measurementConsumer,
providedMeasurementId,
dataProviders.associate { it.externalDataProviderId to it.toDataProviderValue() }
)
}
suspend fun createDuchyCertificate(
certificatesService: CertificatesCoroutineImplBase,
externalDuchyId: String,
notValidBefore: Instant = clock.instant(),
notValidAfter: Instant = notValidBefore.plus(365L, ChronoUnit.DAYS)
): Certificate {
return certificatesService.createCertificate(
certificate {
this.externalDuchyId = externalDuchyId
fillRequestCertificate(
"Duchy cert",
"Duchy $externalDuchyId SKID",
notValidBefore,
notValidAfter
)
}
)
}
/** Creates an [Account] and returns it. */
suspend fun createAccount(
accountsService: AccountsCoroutineImplBase,
externalCreatorAccountId: Long = 0L,
externalOwnedMeasurementConsumerId: Long = 0L
): Account {
return accountsService.createAccount(
account {
this.externalCreatorAccountId = externalCreatorAccountId
this.externalOwnedMeasurementConsumerId = externalOwnedMeasurementConsumerId
}
)
}
/**
* Generates a self-issued ID token and uses it to activate the [Account].
*
* @return generated self-issued ID token used for activation
*/
suspend fun activateAccount(
accountsService: AccountsCoroutineImplBase,
account: Account,
): String {
val openIdRequestParams =
accountsService.generateOpenIdRequestParams(generateOpenIdRequestParamsRequest {})
val idToken =
generateIdToken(
createRequestUri(
state = openIdRequestParams.state,
nonce = openIdRequestParams.nonce,
redirectUri = "",
isSelfIssued = true
),
clock
)
val openIdConnectIdentity = parseIdToken(idToken)
accountsService.activateAccount(
activateAccountRequest {
externalAccountId = account.externalAccountId
activationToken = account.activationToken
identity = openIdConnectIdentity
}
)
return idToken
}
fun parseIdToken(idToken: String, redirectUri: String = ""): Account.OpenIdConnectIdentity {
val tokenParts = idToken.split(".")
val claims =
JsonParser.parseString(tokenParts[1].base64UrlDecode().toString(Charsets.UTF_8)).asJsonObject
val subJwk = claims.get("sub_jwk")
val jwk = subJwk.asJsonObject
val publicJwkHandle = PublicJwkHandle.fromJwk(jwk)
val verifiedJwt =
SelfIssuedIdTokens.validateJwt(
redirectUri = redirectUri,
idToken = idToken,
publicJwkHandle = publicJwkHandle
)
return openIdConnectIdentity {
issuer = verifiedJwt.issuer!!
subject = verifiedJwt.subject!!
}
}
suspend fun createMeasurementConsumerCreationToken(
accountsService: AccountsCoroutineImplBase
): Long {
val createMeasurementConsumerCreationTokenResponse =
accountsService.createMeasurementConsumerCreationToken(
createMeasurementConsumerCreationTokenRequest {}
)
return createMeasurementConsumerCreationTokenResponse.measurementConsumerCreationToken
}
}
fun DataProvider.toDataProviderValue(nonce: Long = Random.Default.nextLong()) = dataProviderValue {
externalDataProviderCertificateId = certificate.externalCertificateId
dataProviderPublicKey = details.publicKey
dataProviderPublicKeySignature = details.publicKeySignature
encryptedRequisitionSpec = "Encrypted RequisitionSpec $nonce".toByteStringUtf8()
nonceHash = hashSha256(nonce)
}
/**
* [ErrorInfo] from [trailers][StatusRuntimeException.getTrailers].
*
* TODO(@SanjayVas): Move this to common.grpc.
*/
val StatusRuntimeException.errorInfo: ErrorInfo?
get() {
val key = ProtoUtils.keyForProto(ErrorInfo.getDefaultInstance())
return trailers?.get(key)
}
| src/main/kotlin/org/wfanet/measurement/kingdom/service/internal/testing/Population.kt | 2340424372 |
/*
* Copyright 2018 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
*
* 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.google.api.kotlin.config
import com.google.common.base.CaseFormat
import com.google.protobuf.DescriptorProtos
import com.squareup.kotlinpoet.ClassName
/** Maps proto names to kotlin names */
internal class ProtobufTypeMapper private constructor() {
private val typeMap = mutableMapOf<String, String>()
private val serviceMap = mutableMapOf<String, String>()
private val knownProtoTypes = mutableMapOf<String, DescriptorProtos.DescriptorProto>()
private val knownProtoEnums = mutableMapOf<String, DescriptorProtos.EnumDescriptorProto>()
/** Lookup the Kotlin type given the proto type. */
fun getKotlinType(protoType: String) =
ClassName.bestGuess(
typeMap[protoType]
?: throw IllegalArgumentException("proto type: $protoType is not recognized")
)
/** Get all Kotlin types (excluding enums and map types) */
fun getAllKotlinTypes() = knownProtoTypes.keys
.asSequence()
.filter { !(knownProtoTypes[it]?.options?.mapEntry ?: false) }
.map { typeMap[it] ?: throw IllegalStateException("unknown type: $it") }
.toList()
fun getAllTypes() = knownProtoTypes.keys.map { TypeNamePair(it, typeMap[it]!!) }
/** Checks if the message type is in this mapper */
fun hasProtoTypeDescriptor(type: String) = knownProtoTypes.containsKey(type)
/** Lookup up a known proto message type by name */
fun getProtoTypeDescriptor(type: String) = knownProtoTypes[type]
?: throw IllegalArgumentException("unknown type: $type")
/** Checks if the enum type is in this mapper */
fun hasProtoEnumDescriptor(type: String) = knownProtoEnums.containsKey(type)
/** Lookup a known proto enum type by name */
fun getProtoEnumDescriptor(type: String) = knownProtoEnums[type]
?: throw IllegalArgumentException("unknown enum: $type")
override fun toString(): String {
val ret = StringBuilder("Types:")
typeMap.forEach { k, v -> ret.append("\n $k -> $v") }
return ret.toString()
}
companion object {
/** Create a map from a set of proto descriptors */
fun fromProtos(descriptors: Collection<DescriptorProtos.FileDescriptorProto>): ProtobufTypeMapper {
val map = ProtobufTypeMapper()
descriptors.map { proto ->
val protoPackage = if (proto.hasPackage()) "." + proto.`package` else ""
val javaPackage = if (proto.options.hasJavaPackage())
proto.options.javaPackage
else
proto.`package`
val enclosingClassName = if (proto.options?.javaMultipleFiles != false)
null
else
getOuterClassname(proto)
fun addMsg(p: DescriptorProtos.DescriptorProto, parent: String) {
val key = "$protoPackage$parent.${p.name}"
map.typeMap[key] = listOfNotNull("$javaPackage$parent", enclosingClassName, p.name)
.joinToString(".")
map.knownProtoTypes[key] = p
}
fun addEnum(p: DescriptorProtos.EnumDescriptorProto, parent: String) {
val key = "$protoPackage$parent.${p.name}"
map.typeMap[key] = listOfNotNull("$javaPackage$parent", enclosingClassName, p.name)
.joinToString(".")
map.knownProtoEnums[key] = p
}
fun addService(p: DescriptorProtos.ServiceDescriptorProto, parent: String) {
map.serviceMap["$protoPackage$parent.${p.name}"] =
listOfNotNull("$javaPackage$parent", enclosingClassName, p.name)
.joinToString(".")
}
fun addNested(p: DescriptorProtos.DescriptorProto, parent: String) {
addMsg(p, parent)
p.enumTypeList.forEach { addEnum(it, "$parent.${p.name}") }
p.nestedTypeList.forEach { addNested(it, "$parent.${p.name}") }
}
// process top level types and services
proto.messageTypeList.forEach { addNested(it, "") }
proto.serviceList.forEach { addService(it, "") }
proto.enumTypeList.forEach { addEnum(it, "") }
}
return map
}
private fun getOuterClassname(proto: DescriptorProtos.FileDescriptorProto): String {
if (proto.options.hasJavaOuterClassname()) {
return proto.options.javaOuterClassname
}
var fileName = proto.name.substring(0, proto.name.length - ".proto".length)
if (fileName.contains("/")) {
fileName = fileName.substring(fileName.lastIndexOf('/') + 1)
}
fileName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, fileName)
if (proto.enumTypeList.any { it.name == fileName } ||
proto.messageTypeList.any { it.name == fileName } ||
proto.serviceList.any { it.name == fileName }) {
fileName += "OuterClass"
}
return fileName
}
}
}
internal data class TypeNamePair(val protoName: String, val kotlinName: String)
| generator/src/main/kotlin/com/google/api/kotlin/config/ProtobufTypeMapper.kt | 1722391494 |
package com.makeevapps.simpletodolist.ui.view
import android.content.Context
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.FloatingActionButton
import android.support.v4.view.ViewCompat
import android.util.AttributeSet
import android.view.View
import com.makeevapps.simpletodolist.R
class ScrollAwareFABBehavior(context: Context, attrs: AttributeSet) : FloatingActionButton.Behavior() {
override fun onStartNestedScroll(coordinatorLayout: CoordinatorLayout, child: FloatingActionButton,
directTargetChild: View, target: View, nestedScrollAxes: Int): Boolean {
// Ensure we react to vertical scrolling
val o = child.getTag(R.id.can_be_visible)
val canBeVisible = o == null || o as Boolean
return canBeVisible && (nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL || super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes))
}
override fun onNestedScroll(coordinatorLayout: CoordinatorLayout, child: FloatingActionButton,
target: View, dxConsumed: Int, dyConsumed: Int,
dxUnconsumed: Int, dyUnconsumed: Int) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed)
if (dyConsumed > 0 && child.visibility == View.VISIBLE) {
child.hide(object : FloatingActionButton.OnVisibilityChangedListener() {
override fun onHidden(fab: FloatingActionButton?) {
super.onHidden(fab)
child.visibility = View.INVISIBLE
}
})
} else if (dyConsumed < 0 && child.visibility != View.VISIBLE) {
child.show()
}
}
/*override fun onStartNestedScroll(coordinatorLayout: CoordinatorLayout, child: FloatingActionButton, directTargetChild: View, target: View, axes: Int, type: Int): Boolean {
// Ensure we react to vertical scrolling
val o = child.getTag(R.id.can_be_visible)
val canBeVisible = o == null || o as Boolean
return canBeVisible && (type == ViewCompat.SCROLL_AXIS_VERTICAL || super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, axes, type))
}
override fun onNestedScroll(coordinatorLayout: CoordinatorLayout, child: FloatingActionButton, target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int, type: Int) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type)
if (dyConsumed > 0 && child.visibility == View.VISIBLE) {
child.hide(object : FloatingActionButton.OnVisibilityChangedListener() {
override fun onHidden(fab: FloatingActionButton?) {
super.onHidden(fab)
child.visibility = View.INVISIBLE
}
})
} else if (dyConsumed < 0 && child.visibility != View.VISIBLE) {
child.show()
}
}*/
} | app/src/main/java/com/makeevapps/simpletodolist/ui/view/ScrollAwareFABBehavior.kt | 1159998527 |
package org.rizki.mufrizal.starter.backend.domain.oauth2
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.Table
/**
*
* @Author Rizki Mufrizal <[email protected]>
* @Web <https://RizkiMufrizal.github.io>
* @Since 20 August 2017
* @Time 6:06 PM
* @Project Starter-BackEnd
* @Package org.rizki.mufrizal.starter.backend.domain.oauth2
* @File OAuth2RefreshToken
*
*/
@Entity
@Table(name = "oauth_refresh_token")
data class OAuth2RefreshToken(
@Id
@Column(name = "token_id")
val tokenId: String? = null,
@Column(name = "token", columnDefinition = "BLOB")
val token: ByteArray? = null,
@Column(name = "authentication", columnDefinition = "BLOB")
val authentication: ByteArray? = null
) | Starter-BackEnd/src/main/kotlin/org/rizki/mufrizal/starter/backend/domain/oauth2/OAuth2RefreshToken.kt | 3247172771 |
package i_introduction._0_Hello_World
import util.TODO
import util.doc0
fun todoTask0(): Nothing = TODO(
"""
Introduction:
Workshop tasks are usually to change the function 'taskN' by replacing its body
(which starts out as the function invocation 'todoTaskN()'), with the correct code according to the problem.
The function 'todoTaskN()' throws an exception, so you usually have to replace that invocation with
meaningful code.
Using 'documentation' argument you can open the related part of Kotlin online documentation.
Press 'F1' (Quick Documentation) on 'doc0()', "See also" section gives you a link.
Using 'references' you can usually navigate and see the code mentioned in the task description.
To start please make the function 'task0' return "OK".
""",
documentation = doc0(),
references = { task0(); "OK" }
)
fun task0(): String = "OK"
| src/i_introduction/_0_Hello_World/HelloWorld.kt | 941669472 |
package com.duopoints.android.rest.models.dbviews
import com.google.gson.Gson
import org.junit.Assert.assertEquals
import org.junit.Test
class UserDataTest {
@Test
fun testConvert() {
var jsonString = "{\"userUuid\":\"ea40f25c-0496-4741-9e51-44eb5ced6ac5\",\"userAuthProvider\":\"G\",\"userAuthUuid\":\"12345678\",\"userEmail\":\"[email protected]\",\"userFirstname\":\"Bahram\",\"userLastname\":\"Malaekeh\",\"userNickname\":\"Bam\",\"userGender\":\"M\",\"userAge\":30,\"userTotalPoints\":0,\"userStatus\":\"ACTIVE\",\"userJoined\":1516623778207,\"userLoggedInLast\":1516623778207,\"userImageUuid\":\"f713a264-62e3-4d7e-bf34-87dd2abff4a1\",\"addressUuid\":\"f713a264-62e3-4d7e-bf34-87dd2abff4a1\",\"userLevelUuid\":\"2a49aa26-e861-487c-aa71-d3b7fb5865e5\",\"userLevelNumber\":1,\"adrCountry\":\"Norway\",\"adrCity\":\"Oslo-1\",\"adrRegion\":\"Oslo-1\"}"
val gson = Gson()
var userData = gson.fromJson(jsonString, UserData::class.java)
assertEquals(jsonString, gson.toJson(userData))
}
} | app/src/test/java/com/duopoints/android/rest/models/dbviews/UserDataTest.kt | 840475060 |
package com.jamieadkins.gwent.deck.create
import com.jamieadkins.gwent.domain.GwentFaction
import com.jamieadkins.gwent.base.MvpPresenter
interface CreateDeckContract {
interface View {
fun showDeckDetails(deckId: String)
fun close()
}
interface Presenter : MvpPresenter {
fun createDeck(name: String, faction: GwentFaction)
}
}
| app/src/main/java/com/jamieadkins/gwent/deck/create/CreateDeckContract.kt | 547779839 |
package core
import metadata.data.Schema
import storage.ExPage
/**
* Created by liufengkai on 2017/7/8.
*/
/**
* Support Value Types
*/
enum class Types(value: Int) {
INTEGER(4),
VARCHAR(12)
}
class UnSupportException(type: String) : Exception("UnSupport Type Value $type")
/**
* Schema support type API
* @param fieldName fieldType
* @return length of Type
*/
fun Schema.lengthOfType(fieldName: String): Int {
when (infoType(fieldName)) {
Types.INTEGER -> return ExPage.INT_SIZE
Types.VARCHAR -> return ExPage.strSize(this[fieldName].length)
else -> throw UnSupportException(infoType(fieldName).toString())
}
} | src/core/SupportTypes.kt | 1818043910 |
/**
* **************************************************************************
* BaseBrowserFragment.kt
* ****************************************************************************
* Copyright © 2018 VLC authors and VideoLAN
* Author: Geoffrey Métais
*
* 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 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
* ***************************************************************************
*/
package org.videolan.vlc.gui.browser
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.*
import androidx.appcompat.view.ActionMode
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.*
import org.videolan.medialibrary.MLServiceLocator
import org.videolan.medialibrary.interfaces.media.MediaWrapper
import org.videolan.medialibrary.media.MediaLibraryItem
import org.videolan.resources.*
import org.videolan.tools.*
import org.videolan.vlc.BuildConfig
import org.videolan.vlc.R
import org.videolan.vlc.databinding.DirectoryBrowserBinding
import org.videolan.vlc.gui.AudioPlayerContainerActivity
import org.videolan.vlc.gui.dialogs.CtxActionReceiver
import org.videolan.vlc.gui.dialogs.SavePlaylistDialog
import org.videolan.vlc.gui.dialogs.showContext
import org.videolan.vlc.gui.helpers.MedialibraryUtils
import org.videolan.vlc.gui.helpers.UiTools
import org.videolan.vlc.gui.helpers.UiTools.addToPlaylist
import org.videolan.vlc.gui.helpers.UiTools.addToPlaylistAsync
import org.videolan.vlc.gui.helpers.UiTools.showMediaInfo
import org.videolan.vlc.gui.helpers.hf.OTG_SCHEME
import org.videolan.vlc.gui.view.EmptyLoadingState
import org.videolan.vlc.gui.view.VLCDividerItemDecoration
import org.videolan.vlc.interfaces.IEventsHandler
import org.videolan.vlc.interfaces.IRefreshable
import org.videolan.vlc.media.MediaUtils
import org.videolan.vlc.media.PlaylistManager
import org.videolan.vlc.repository.BrowserFavRepository
import org.videolan.vlc.util.Permissions
import org.videolan.vlc.util.isSchemeSupported
import org.videolan.vlc.viewmodels.browser.BrowserModel
import java.util.*
private const val TAG = "VLC/BaseBrowserFragment"
internal const val KEY_MEDIA = "key_media"
private const val KEY_POSITION = "key_list"
private const val MSG_SHOW_LOADING = 0
internal const val MSG_HIDE_LOADING = 1
private const val MSG_REFRESH = 3
@ObsoleteCoroutinesApi
@ExperimentalCoroutinesApi
abstract class BaseBrowserFragment : MediaBrowserFragment<BrowserModel>(), IRefreshable, SwipeRefreshLayout.OnRefreshListener, View.OnClickListener, IEventsHandler<MediaLibraryItem>, CtxActionReceiver, PathAdapterListener, BrowserContainer<MediaLibraryItem> {
private lateinit var addPlaylistFolderOnly: MenuItem
protected val handler = BrowserFragmentHandler(this)
private lateinit var layoutManager: LinearLayoutManager
override var mrl: String? = null
protected var currentMedia: MediaWrapper? = null
private var savedPosition = -1
override var isRootDirectory: Boolean = false
override val scannedDirectory = false
override val inCards = false
protected var showHiddenFiles: Boolean = false
protected lateinit var adapter: BaseBrowserAdapter
protected abstract val categoryTitle: String
protected lateinit var binding: DirectoryBrowserBinding
protected lateinit var browserFavRepository: BrowserFavRepository
protected abstract fun createFragment(): Fragment
protected abstract fun browseRoot()
override fun onCreate(bundle: Bundle?) {
@Suppress("NAME_SHADOWING")
var bundle = bundle
super.onCreate(bundle)
if (bundle == null) bundle = arguments
if (bundle != null) {
currentMedia = bundle.getParcelable(KEY_MEDIA)
mrl = currentMedia?.location ?: bundle.getString(KEY_MRL)
savedPosition = bundle.getInt(KEY_POSITION)
} else if (requireActivity().intent != null) {
mrl = requireActivity().intent.dataString
requireActivity().intent = null
}
showHiddenFiles = Settings.getInstance(requireContext()).getBoolean("browser_show_hidden_files", false)
isRootDirectory = defineIsRoot()
browserFavRepository = BrowserFavRepository.getInstance(requireContext())
}
override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu)
menu.findItem(R.id.ml_menu_filter)?.isVisible = enableSearchOption()
menu.findItem(R.id.ml_menu_sortby)?.isVisible = !isRootDirectory
menu.findItem(R.id.ml_menu_add_playlist)?.isVisible = !isRootDirectory
addPlaylistFolderOnly = menu.findItem(R.id.folder_add_playlist)
addPlaylistFolderOnly.isVisible = adapter.mediaCount > 0
val browserShowAllFiles = menu.findItem(R.id.browser_show_all_files)
browserShowAllFiles.isVisible = true
browserShowAllFiles.isChecked = Settings.getInstance(requireActivity()).getBoolean("browser_show_all_files", true)
val browserShowHiddenFiles = menu.findItem(R.id.browser_show_hidden_files)
browserShowHiddenFiles.isVisible = true
browserShowHiddenFiles.isChecked = Settings.getInstance(requireActivity()).getBoolean("browser_show_hidden_files", true)
}
protected open fun defineIsRoot() = mrl == null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DirectoryBrowserBinding.inflate(inflater, container, false)
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
if (!this::adapter.isInitialized) adapter = BaseBrowserAdapter(this)
layoutManager = LinearLayoutManager(activity)
binding.networkList.layoutManager = layoutManager
binding.networkList.adapter = adapter
registerSwiperRefreshlayout()
viewModel.dataset.observe(viewLifecycleOwner, Observer<MutableList<MediaLibraryItem>> { mediaLibraryItems ->
adapter.update(mediaLibraryItems!!)
if (::addPlaylistFolderOnly.isInitialized) addPlaylistFolderOnly.isVisible = adapter.mediaCount > 0
})
viewModel.getDescriptionUpdate().observe(viewLifecycleOwner, Observer { pair -> if (pair != null) adapter.notifyItemChanged(pair.first, pair.second) })
viewModel.loading.observe(viewLifecycleOwner, Observer { loading ->
swipeRefreshLayout.isRefreshing = loading
updateEmptyView()
})
}
open fun registerSwiperRefreshlayout() = swipeRefreshLayout.setOnRefreshListener(this)
override fun setBreadcrumb() {
val ariane = requireActivity().findViewById<RecyclerView>(R.id.ariane) ?: return
val media = currentMedia
if (media != null && isSchemeSupported(media.uri?.scheme)) {
ariane.visibility = View.VISIBLE
ariane.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
ariane.adapter = PathAdapter(this, media)
if (ariane.itemDecorationCount == 0) {
ariane.addItemDecoration(VLCDividerItemDecoration(requireContext(), DividerItemDecoration.HORIZONTAL, ContextCompat.getDrawable(requireContext(), R.drawable.ic_divider)!!))
}
ariane.scrollToPosition(ariane.adapter!!.itemCount - 1)
} else ariane.visibility = View.GONE
}
override fun backTo(tag: String) {
val supportFragmentManager = requireActivity().supportFragmentManager
var poped = false
for (i in 0 until supportFragmentManager.backStackEntryCount) {
if (tag == supportFragmentManager.getBackStackEntryAt(i).name) {
supportFragmentManager.popBackStack(tag, FragmentManager.POP_BACK_STACK_INCLUSIVE)
poped = true
break
}
}
if (!poped) {
viewModel.setDestination(MLServiceLocator.getAbstractMediaWrapper(Uri.parse(tag)))
supportFragmentManager.popBackStackImmediate()
}
}
override fun currentContext() = requireContext()
override fun showRoot() = true
override fun getPathOperationDelegate() = viewModel
override fun onStart() {
super.onStart()
fabPlay?.run {
setImageResource(R.drawable.ic_fab_play)
updateFab()
}
(activity as? AudioPlayerContainerActivity)?.expandAppBar()
}
override fun onResume() {
super.onResume()
viewModel.getAndRemoveDestination()?.let {
browse(it, true)
}
}
override fun onStop() {
super.onStop()
viewModel.stop()
}
override fun onDestroy() {
if (::adapter.isInitialized) adapter.cancel()
super.onDestroy()
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putString(KEY_MRL, mrl)
outState.putParcelable(KEY_MEDIA, currentMedia)
outState.putInt(KEY_POSITION, if (::layoutManager.isInitialized) layoutManager.findFirstCompletelyVisibleItemPosition() else 0)
super.onSaveInstanceState(outState)
}
override fun getTitle(): String = when {
isRootDirectory -> categoryTitle
currentMedia != null -> currentMedia!!.title
else -> mrl ?: ""
}
override fun getMultiHelper(): MultiSelectHelper<BrowserModel>? = if (::adapter.isInitialized) adapter.multiSelectHelper as? MultiSelectHelper<BrowserModel> else null
override val subTitle: String? =
if (isRootDirectory) null else {
var mrl = mrl?.removeFileProtocole() ?: ""
if (!TextUtils.isEmpty(mrl)) {
if (this is FileBrowserFragment && mrl.startsWith(AndroidDevices.EXTERNAL_PUBLIC_DIRECTORY))
mrl = getString(R.string.internal_memory) + mrl.substring(AndroidDevices.EXTERNAL_PUBLIC_DIRECTORY.length)
mrl = Uri.decode(mrl).replace("://".toRegex(), " ").replace("/".toRegex(), " > ")
}
if (currentMedia != null) mrl else null
}
fun goBack(): Boolean {
val activity = activity
if (activity?.isStarted() != true) return false
if (!isRootDirectory && !activity.isFinishing && !activity.isDestroyed) activity.supportFragmentManager.popBackStack()
return !isRootDirectory
}
fun browse(media: MediaWrapper, save: Boolean) {
val ctx = activity
if (ctx == null || !isResumed || isRemoving) return
val ft = ctx.supportFragmentManager.beginTransaction()
val next = createFragment()
val args = Bundle()
viewModel.saveList(media)
args.putParcelable(KEY_MEDIA, media)
next.arguments = args
if (save) ft.addToBackStack(if (isRootDirectory) "root" else if (currentMedia != null) currentMedia?.uri.toString() else mrl!!)
if (BuildConfig.DEBUG) for (i in 0 until ctx.supportFragmentManager.backStackEntryCount) {
Log.d(this::class.java.simpleName, "Adding to back stack from PathAdapter: ${ctx.supportFragmentManager.getBackStackEntryAt(i).name}")
}
ft.replace(R.id.fragment_placeholder, next, media.title)
ft.commit()
}
override fun onRefresh() {
savedPosition = layoutManager.findFirstCompletelyVisibleItemPosition()
viewModel.refresh()
}
/**
* Update views visibility and emptiness info
*/
protected open fun updateEmptyView() {
swipeRefreshLayout.let {
when {
it.isRefreshing -> {
binding.emptyLoading.state = EmptyLoadingState.LOADING
binding.networkList.visibility = View.GONE
}
viewModel.isEmpty() -> {
binding.emptyLoading.state = EmptyLoadingState.EMPTY
binding.networkList.visibility = View.GONE
}
else -> {
binding.emptyLoading.state = EmptyLoadingState.NONE
binding.networkList.visibility = View.VISIBLE
}
}
}
}
override fun refresh() = viewModel.refresh()
override fun onClick(v: View) {
when (v.id) {
R.id.fab -> playAll(null)
}
}
class BrowserFragmentHandler(owner: BaseBrowserFragment) : WeakHandler<BaseBrowserFragment>(owner) {
override fun handleMessage(msg: Message) {
val fragment = owner ?: return
when (msg.what) {
MSG_SHOW_LOADING -> fragment.swipeRefreshLayout.isRefreshing = true
MSG_HIDE_LOADING -> {
removeMessages(MSG_SHOW_LOADING)
fragment.swipeRefreshLayout.isRefreshing = false
}
MSG_REFRESH -> {
removeMessages(MSG_REFRESH)
if (!fragment.isDetached) fragment.refresh()
}
}
}
}
override fun clear() = adapter.clear()
override fun removeItem(item: MediaLibraryItem): Boolean {
val view = view ?: return false
val mw = item as? MediaWrapper
?: return false
val cancel = Runnable { viewModel.refresh() }
val deleteAction = Runnable {
lifecycleScope.launch {
MediaUtils.deleteMedia(mw, cancel)
viewModel.remove(mw)
}
}
val resId = if (mw.type == MediaWrapper.TYPE_DIR) R.string.confirm_delete_folder else R.string.confirm_delete
UiTools.snackerConfirm(view, getString(resId, mw.title), Runnable { if (Permissions.checkWritePermission(requireActivity(), mw, deleteAction)) deleteAction.run() })
return true
}
private fun playAll(mw: MediaWrapper?) {
var positionInPlaylist = 0
val mediaLocations = LinkedList<MediaWrapper>()
for (file in viewModel.dataset.getList())
if (file is MediaWrapper) {
if (file.type == MediaWrapper.TYPE_VIDEO || file.type == MediaWrapper.TYPE_AUDIO) {
mediaLocations.add(file)
if (mw != null && file.equals(mw))
positionInPlaylist = mediaLocations.size - 1
}
}
activity?.let { MediaUtils.openList(it, mediaLocations, positionInPlaylist) }
}
override fun enableSearchOption() = !isRootDirectory
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
mode.menuInflater.inflate(R.menu.action_mode_browser_file, menu)
return true
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
val count = adapter.multiSelectHelper.getSelectionCount()
if (count == 0) {
stopActionMode()
return false
}
val fileBrowser = this is FileBrowserFragment
val single = fileBrowser && count == 1
val selection = if (single) adapter.multiSelectHelper.getSelection() else null
val type = if (!selection.isNullOrEmpty()) (selection[0] as MediaWrapper).type else -1
menu.findItem(R.id.action_mode_file_info).isVisible = single && (type == MediaWrapper.TYPE_AUDIO || type == MediaWrapper.TYPE_VIDEO)
menu.findItem(R.id.action_mode_file_append).isVisible = PlaylistManager.hasMedia()
menu.findItem(R.id.action_mode_file_delete).isVisible = fileBrowser
return true
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
if (!isStarted()) return false
val list = adapter.multiSelectHelper.getSelection() as? List<MediaWrapper>
?: return false
if (list.isNotEmpty()) {
when (item.itemId) {
R.id.action_mode_file_play -> MediaUtils.openList(activity, list, 0)
R.id.action_mode_file_append -> MediaUtils.appendMedia(activity, list)
R.id.action_mode_file_add_playlist -> requireActivity().addToPlaylist(list)
R.id.action_mode_file_info -> requireActivity().showMediaInfo(list[0])
R.id.action_mode_file_delete -> removeItems(list)
else -> {
stopActionMode()
return false
}
}
}
stopActionMode()
return true
}
override fun onDestroyActionMode(mode: ActionMode?) {
actionMode = null
adapter.multiSelectHelper.clearSelection()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.ml_menu_save -> {
toggleFavorite()
menu?.let { onPrepareOptionsMenu(it) }
true
}
R.id.browser_show_all_files -> {
item.isChecked = !Settings.getInstance(requireActivity()).getBoolean("browser_show_all_files", true)
Settings.getInstance(requireActivity()).putSingle("browser_show_all_files", item.isChecked)
viewModel.updateShowAllFiles(item.isChecked)
true
}
R.id.browser_show_hidden_files -> {
item.isChecked = !Settings.getInstance(requireActivity()).getBoolean("browser_show_hidden_files", true)
Settings.getInstance(requireActivity()).putSingle("browser_show_hidden_files", item.isChecked)
viewModel.updateShowHiddenFiles(item.isChecked)
true
}
R.id.ml_menu_scan -> {
currentMedia?.let { media ->
addToScannedFolders(media)
item.isVisible = false
}
true
}
R.id.folder_add_playlist -> {
currentMedia?.let { requireActivity().addToPlaylistAsync(it.uri.toString()) }
true
}
R.id.subfolders_add_playlist -> {
currentMedia?.let { requireActivity().addToPlaylistAsync(it.uri.toString(), true) }
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun addToScannedFolders(mw: MediaWrapper) {
MedialibraryUtils.addDir(mw.uri.toString(), requireActivity().applicationContext)
Snackbar.make(binding.root, getString(R.string.scanned_directory_added, Uri.parse(mw.uri.toString()).lastPathSegment), Snackbar.LENGTH_LONG).show()
}
private fun toggleFavorite() = lifecycleScope.launch {
val mw = currentMedia ?: return@launch
when {
browserFavRepository.browserFavExists(mw.uri) -> browserFavRepository.deleteBrowserFav(mw.uri)
mw.uri.scheme == "file" -> browserFavRepository.addLocalFavItem(mw.uri, mw.title, mw.artworkURL)
else -> browserFavRepository.addNetworkFavItem(mw.uri, mw.title, mw.artworkURL)
}
activity?.invalidateOptionsMenu()
}
override fun onClick(v: View, position: Int, item: MediaLibraryItem) {
val mediaWrapper = item as MediaWrapper
if (actionMode != null) {
if (mediaWrapper.type == MediaWrapper.TYPE_AUDIO ||
mediaWrapper.type == MediaWrapper.TYPE_VIDEO ||
mediaWrapper.type == MediaWrapper.TYPE_DIR) {
adapter.multiSelectHelper.toggleSelection(position)
invalidateActionMode()
}
} else {
mediaWrapper.removeFlags(MediaWrapper.MEDIA_FORCE_AUDIO)
if (mediaWrapper.type == MediaWrapper.TYPE_DIR) browse(mediaWrapper, true)
else MediaUtils.openMedia(v.context, mediaWrapper)
}
}
override fun onLongClick(v: View, position: Int, item: MediaLibraryItem): Boolean {
if (item.itemType != MediaLibraryItem.TYPE_MEDIA) return false
val mediaWrapper = item as MediaWrapper
if (mediaWrapper.type == MediaWrapper.TYPE_AUDIO ||
mediaWrapper.type == MediaWrapper.TYPE_VIDEO ||
mediaWrapper.type == MediaWrapper.TYPE_DIR) {
adapter.multiSelectHelper.toggleSelection(position)
if (actionMode == null) startActionMode()
} else onCtxClick(v, position, item)
return true
}
override fun onCtxClick(v: View, position: Int, item: MediaLibraryItem) {
if (actionMode == null && item.itemType == MediaLibraryItem.TYPE_MEDIA) lifecycleScope.launch {
val mw = item as MediaWrapper
if (mw.uri.scheme == "content" || mw.uri.scheme == OTG_SCHEME) return@launch
var flags = if (!isRootDirectory && this@BaseBrowserFragment is FileBrowserFragment) CTX_DELETE else 0
if (!isRootDirectory && this is FileBrowserFragment) flags = flags or CTX_DELETE
if (mw.type == MediaWrapper.TYPE_DIR) {
val isEmpty = viewModel.isFolderEmpty(mw)
if (!isEmpty) flags = flags or CTX_PLAY
val isFileBrowser = this@BaseBrowserFragment is FileBrowserFragment && item.uri.scheme == "file"
val isNetworkBrowser = this@BaseBrowserFragment is NetworkBrowserFragment
if (isFileBrowser || isNetworkBrowser) {
val favExists = browserFavRepository.browserFavExists(mw.uri)
flags = if (favExists) {
if (isNetworkBrowser) flags or CTX_FAV_EDIT or CTX_FAV_REMOVE
else flags or CTX_FAV_REMOVE
} else flags or CTX_FAV_ADD
}
if (isFileBrowser && !isRootDirectory && !MedialibraryUtils.isScanned(item.uri.toString())) {
flags = flags or CTX_ADD_SCANNED
}
if (isFileBrowser) {
if (viewModel.provider.hasMedias(mw)) flags = flags or CTX_ADD_FOLDER_PLAYLIST
if (viewModel.provider.hasSubfolders(mw)) flags = flags or CTX_ADD_FOLDER_AND_SUB_PLAYLIST
}
} else {
val isVideo = mw.type == MediaWrapper.TYPE_VIDEO
val isAudio = mw.type == MediaWrapper.TYPE_AUDIO
val isMedia = isVideo || isAudio
if (isMedia) flags = flags or CTX_PLAY_ALL or CTX_APPEND or CTX_INFORMATION or CTX_ADD_TO_PLAYLIST
if (!isAudio) flags = flags or CTX_PLAY_AS_AUDIO
if (isVideo) flags = flags or CTX_DOWNLOAD_SUBTITLES
}
if (flags != 0L) showContext(requireActivity(), this@BaseBrowserFragment, position, item.getTitle(), flags)
}
}
override fun onCtxAction(position: Int, option: Long) {
val mw = adapter.getItem(position) as? MediaWrapper
?: return
when (option) {
CTX_PLAY -> MediaUtils.openMedia(activity, mw)
CTX_PLAY_ALL -> {
mw.removeFlags(MediaWrapper.MEDIA_FORCE_AUDIO)
playAll(mw)
}
CTX_APPEND -> MediaUtils.appendMedia(activity, mw)
CTX_DELETE -> removeItem(mw)
CTX_INFORMATION -> requireActivity().showMediaInfo(mw)
CTX_PLAY_AS_AUDIO -> {
mw.addFlags(MediaWrapper.MEDIA_FORCE_AUDIO)
MediaUtils.openMedia(activity, mw)
}
CTX_ADD_TO_PLAYLIST -> requireActivity().addToPlaylist(mw.tracks, SavePlaylistDialog.KEY_NEW_TRACKS)
CTX_DOWNLOAD_SUBTITLES -> MediaUtils.getSubs(requireActivity(), mw)
CTX_FAV_REMOVE -> lifecycleScope.launch(Dispatchers.IO) { browserFavRepository.deleteBrowserFav(mw.uri) }
CTX_ADD_SCANNED -> addToScannedFolders(mw)
CTX_FIND_METADATA -> {
val intent = Intent().apply {
setClassName(requireContext().applicationContext, MOVIEPEDIA_ACTIVITY)
putExtra(MOVIEPEDIA_MEDIA, mw)
}
startActivity(intent)
}
CTX_ADD_FOLDER_PLAYLIST -> {
requireActivity().addToPlaylistAsync(mw.uri.toString(), false)
}
CTX_ADD_FOLDER_AND_SUB_PLAYLIST -> {
requireActivity().addToPlaylistAsync(mw.uri.toString(), true)
}
}
}
override fun onImageClick(v: View, position: Int, item: MediaLibraryItem) {
if (actionMode != null) {
onClick(v, position, item)
return
}
onLongClick(v, position, item)
}
override fun onMainActionClick(v: View, position: Int, item: MediaLibraryItem) {}
override fun onUpdateFinished(adapter: RecyclerView.Adapter<*>) {
if (!isStarted()) return
restoreMultiSelectHelper()
swipeRefreshLayout.isRefreshing = false
handler.sendEmptyMessage(MSG_HIDE_LOADING)
updateEmptyView()
if (!viewModel.isEmpty()) {
if (savedPosition > 0) {
layoutManager.scrollToPositionWithOffset(savedPosition, 0)
savedPosition = 0
}
}
if (!isRootDirectory) {
updateFab()
UiTools.updateSortTitles(this)
}
}
override fun onItemFocused(v: View, item: MediaLibraryItem) {
}
private fun updateFab() {
fabPlay?.let {
if (adapter.mediaCount > 0) {
it.show()
it.setOnClickListener(this)
} else {
it.hide()
it.setOnClickListener(null)
}
}
}
}
| application/vlc-android/src/org/videolan/vlc/gui/browser/BaseBrowserFragment.kt | 3129832515 |
package swak.undertow
import io.reactivex.Single
import io.undertow.server.HttpServerExchange
import swak.http.Headers
import swak.http.MutableHeaders
import swak.http.request.BasicRequest
import swak.http.request.Method
import java.util.*
internal class UndertowBasicRequest(private val exchange: HttpServerExchange) : BasicRequest {
override val headers: Headers by lazy {
MutableHeaders(exchange.requestHeaders
.map { it.headerName.toString() to ArrayList(it) }
.toMap()
.toMutableMap())
}
override val path: String by lazy {
exchange.requestPath
}
override val method: Method by lazy {
Method.valueOf(exchange.requestMethod.toString())
}
override val body: Single<String> by lazy {
Single.create<String> {
exchange.requestReceiver.receiveFullString(
{ _, stringValue -> it.onSuccess(stringValue) },
{ _, error -> it.onError(error) },
charset(exchange.requestCharset))
}
}
override val queryParam: Map<String, List<String>> by lazy {
exchange.queryParameters.map { entry -> entry.key to ArrayList(entry.value) }
.toMap()
}
} | undertow/src/main/kotlin/swak/undertow/UndertowBasicRequest.kt | 1478979414 |
package com.quickblox.sample.conference.kotlin.domain.chat
import android.os.Bundle
import android.text.TextUtils
import androidx.collection.ArraySet
import com.quickblox.chat.QBChatService
import com.quickblox.chat.exception.QBChatException
import com.quickblox.chat.listeners.QBChatDialogMessageListener
import com.quickblox.chat.listeners.QBSystemMessageListener
import com.quickblox.chat.model.QBAttachment
import com.quickblox.chat.model.QBChatDialog
import com.quickblox.chat.model.QBChatMessage
import com.quickblox.chat.model.QBDialogType
import com.quickblox.chat.request.QBDialogRequestBuilder
import com.quickblox.chat.request.QBMessageGetBuilder
import com.quickblox.content.model.QBFile
import com.quickblox.core.request.QBRequestGetBuilder
import com.quickblox.sample.conference.kotlin.R
import com.quickblox.sample.conference.kotlin.data.DataCallBack
import com.quickblox.sample.conference.kotlin.domain.DomainCallback
import com.quickblox.sample.conference.kotlin.domain.repositories.chat.ChatRepository
import com.quickblox.sample.conference.kotlin.domain.repositories.db.DBRepository
import com.quickblox.sample.conference.kotlin.domain.repositories.dialog.DialogRepository
import com.quickblox.sample.conference.kotlin.domain.repositories.settings.SettingsRepository
import com.quickblox.sample.conference.kotlin.domain.user.USER_DEFAULT_PASSWORD
import com.quickblox.sample.conference.kotlin.executor.Executor
import com.quickblox.sample.conference.kotlin.executor.ExecutorTask
import com.quickblox.sample.conference.kotlin.executor.TaskExistException
import com.quickblox.sample.conference.kotlin.presentation.resources.ResourcesManager
import com.quickblox.sample.conference.kotlin.presentation.screens.chat.adapters.attachment.AttachmentModel
import com.quickblox.sample.conference.kotlin.presentation.screens.main.DIALOGS_LIMIT
import com.quickblox.sample.conference.kotlin.presentation.screens.main.EXTRA_SKIP
import com.quickblox.sample.conference.kotlin.presentation.screens.main.EXTRA_TOTAL_ENTRIES
import com.quickblox.users.model.QBUser
import org.jivesoftware.smack.ConnectionListener
import org.jivesoftware.smack.SmackException
import org.jivesoftware.smack.XMPPConnection
import org.jivesoftware.smackx.muc.DiscussionHistory
private const val PROPERTY_OCCUPANTS_IDS = "current_occupant_ids"
private const val PROPERTY_DIALOG_TYPE = "type"
private const val PROPERTY_DIALOG_NAME = "room_name"
private const val PROPERTY_NOTIFICATION_TYPE = "notification_type"
private const val PROPERTY_NEW_OCCUPANTS_IDS = "new_occupants_ids"
const val PROPERTY_CONVERSATION_ID = "conference_id"
private const val CREATING_DIALOG = "1"
private const val OCCUPANTS_ADDED = "2"
private const val OCCUPANT_LEFT = "3"
private const val START_CONFERENCE = "4"
private const val START_STREAM = "5"
private const val LOAD_DIALOGS = "load_dialogs"
const val CHAT_HISTORY_ITEMS_PER_PAGE = 50
private const val CHAT_HISTORY_ITEMS_SORT_FIELD = "date_sent"
/*
* Created by Injoit in 2021-09-30.
* Copyright © 2021 Quickblox. All rights reserved.
*/
class ChatManagerImpl(private val dbRepository: DBRepository, private val dialogRepository: DialogRepository,
private val chatRepository: ChatRepository, private val resourcesManager: ResourcesManager,
private val executor: Executor, private val settingsRepository: SettingsRepository) : ChatManager {
private var chatListeners = hashSetOf<ChatListener>()
private var dialogListeners = hashSetOf<DialogListener>()
private var systemMessagesListener = SystemMessagesListener()
private var dialogsMessageListener = DialogsMessageListener()
private var chatMessageListener = ChatMessageListener()
private var connectionListener: ChatConnectionListener? = null
private var chatService: QBChatService? = QBChatService.getInstance()
private val dialogs = arrayListOf<QBChatDialog>()
private var totalCount = 0
private var skip = 0
private var connectionChatListeners = hashSetOf<ConnectionChatListener>()
override fun subscribeConnectionChatListener(connectionChatListener: ConnectionChatListener) {
connectionChatListeners.add(connectionChatListener)
}
override fun unSubscribeConnectionChatListener(connectionChatListener: ConnectionChatListener) {
connectionChatListeners.remove(connectionChatListener)
}
override fun subscribeDialogListener(dialogListener: DialogListener) {
chatService?.systemMessagesManager?.addSystemMessageListener(systemMessagesListener)
chatService?.incomingMessagesManager?.addDialogMessageListener(dialogsMessageListener)
dialogListeners.add(dialogListener)
}
override fun unsubscribeDialogListener(dialogListener: DialogListener) {
chatService?.systemMessagesManager?.removeSystemMessageListener(systemMessagesListener)
chatService?.incomingMessagesManager?.removeDialogMessageListrener(dialogsMessageListener)
dialogListeners.remove(dialogListener)
}
override fun subscribeChatListener(chatListener: ChatListener) {
chatService?.incomingMessagesManager?.addDialogMessageListener(chatMessageListener)
chatListeners.add(chatListener)
}
override fun unsubscribeChatListener(chatListener: ChatListener) {
chatService?.incomingMessagesManager?.removeDialogMessageListrener(chatMessageListener)
chatListeners.remove(chatListener)
}
private fun addConnectionListener() {
if (connectionListener == null) {
connectionListener = ChatConnectionListener()
chatService?.addConnectionListener(connectionListener)
}
}
private fun removeConnectionListener() {
chatService?.removeConnectionListener(connectionListener)
connectionListener = null
}
override fun loadDialogById(dialogId: String, callback: DomainCallback<QBChatDialog, Exception>) {
executor.addTask(object : ExecutorTask<QBChatDialog> {
override fun backgroundWork(): QBChatDialog {
return dialogRepository.getByIdSync(dialogId)
}
override fun foregroundResult(result: QBChatDialog) {
callback.onSuccess(result, null)
}
override fun onError(exception: Exception) {
callback.onError(exception)
}
})
}
override fun createDialog(users: List<QBUser>, chatName: String, callback: DomainCallback<QBChatDialog, Exception>) {
val dialog = buildDialog(users, chatName)
executor.addTask(object : ExecutorTask<QBChatDialog> {
override fun backgroundWork(): QBChatDialog {
val createdDialog = dialogRepository.createSync(dialog)
val chatMessage = buildMessageCreatedGroupDialog(createdDialog)
val systemMessage = buildMessageCreatedGroupDialog(createdDialog)
createdDialog.initForChat(chatService)
dialogRepository.joinSync(createdDialog)
sendSystemMessage(chatMessage, createdDialog.occupants)
sendChatMessage(createdDialog, systemMessage)
return createdDialog
}
override fun foregroundResult(result: QBChatDialog) {
dialogs.add(result)
callback.onSuccess(result, null)
}
override fun onError(exception: Exception) {
callback.onError(exception)
}
})
}
override fun loadMessages(dialog: QBChatDialog, skipPagination: Int, callback: DomainCallback<ArrayList<QBChatMessage>, Exception>) {
val messageGetBuilder = QBMessageGetBuilder()
messageGetBuilder.skip = skipPagination
messageGetBuilder.limit = CHAT_HISTORY_ITEMS_PER_PAGE
messageGetBuilder.sortDesc(CHAT_HISTORY_ITEMS_SORT_FIELD)
messageGetBuilder.markAsRead(false)
executor.addTask(object : ExecutorTask<ArrayList<QBChatMessage>> {
override fun backgroundWork(): ArrayList<QBChatMessage> {
val result = chatRepository.loadHistorySync(dialog, messageGetBuilder)
return result.first
}
override fun foregroundResult(result: ArrayList<QBChatMessage>) {
callback.onSuccess(result, null)
}
override fun onError(exception: Exception) {
callback.onError(exception)
}
})
}
private fun buildDialog(users: List<QBUser>, chatName: String?): QBChatDialog {
val userIds: MutableList<Int> = ArrayList()
for (user in users) {
userIds.add(user.id)
}
val dialog = QBChatDialog()
dialog.name = chatName
dialog.type = QBDialogType.GROUP
dialog.setOccupantsIds(userIds)
return dialog
}
override fun loginToChat(user: QBUser?, callback: DomainCallback<Unit, Exception>) {
if (isLoggedInChat()) {
callback.onSuccess(Unit, null)
} else {
settingsRepository.applyChatSettings()
//Need to set password, because the server will not register to chat without password
user?.password = USER_DEFAULT_PASSWORD
user?.let {
executor.addTask(object : ExecutorTask<Unit> {
override fun backgroundWork() {
QBChatService.getInstance().login(it)
}
override fun foregroundResult(result: Unit) {
chatService = QBChatService.getInstance()
addConnectionListener()
joinDialogs(dialogs)
callback.onSuccess(result, null)
}
override fun onError(exception: Exception) {
callback.onError(exception)
}
})
}
}
}
override fun loadDialogs(refresh: Boolean, reJoin: Boolean, callback: DomainCallback<ArrayList<QBChatDialog>, Exception>) {
if (refresh) {
skip = 0
executor.removeTask(LOAD_DIALOGS)
}
val requestBuilder = QBRequestGetBuilder()
requestBuilder.limit = DIALOGS_LIMIT
requestBuilder.skip = skip
if (skip != 0 && totalCount.minus(skip) == 0) {
return
}
executor.addTaskWithKey(object : ExecutorTask<Pair<ArrayList<QBChatDialog>, Bundle?>> {
override fun backgroundWork(): Pair<ArrayList<QBChatDialog>, Bundle?> {
return dialogRepository.loadSync(requestBuilder)
}
override fun foregroundResult(result: Pair<ArrayList<QBChatDialog>, Bundle?>) {
totalCount = result.second?.getInt(EXTRA_TOTAL_ENTRIES) ?: 0
skip = result.second?.getInt(EXTRA_SKIP) ?: 0
skip += if (totalCount.minus(skip) < DIALOGS_LIMIT) {
totalCount.minus(skip)
} else {
DIALOGS_LIMIT
}
if (refresh) {
dialogs.clear()
}
dialogs.addAll(result.first)
callback.onSuccess(result.first, null)
if (dialogs.isEmpty()) {
return
}
if (isLoggedInChat() && reJoin) {
joinDialogs(dialogs)
}
if (dialogs.size < totalCount) {
loadDialogs(false, reJoin, callback)
}
}
override fun onError(exception: Exception) {
if (exception is TaskExistException) {
// empty
} else {
callback.onError(exception)
}
}
}, LOAD_DIALOGS)
}
override fun addUsersToDialog(dialog: QBChatDialog, users: ArraySet<QBUser>, callback: DomainCallback<QBChatDialog?, Exception>) {
executor.addTask(object : ExecutorTask<Pair<QBChatDialog?, Bundle>> {
override fun backgroundWork(): Pair<QBChatDialog?, Bundle> {
val usersIds = arrayListOf<Int>()
users.forEach { user ->
usersIds.add(user.id)
}
val message = buildMessageAddedUsers(dialog, occupantsIdsToString(usersIds), dbRepository.getCurrentUser()?.fullName
?: "", getOccupantsNames(users) ?: ""
)
val qbRequestBuilder = QBDialogRequestBuilder()
qbRequestBuilder.addUsers(*users.toTypedArray())
sendChatMessage(dialog, message)
sendSystemMessage(message, usersIds)
return dialogRepository.updateSync(dialog, qbRequestBuilder)
}
override fun foregroundResult(result: Pair<QBChatDialog?, Bundle>) {
callback.onSuccess(result.first, result.second)
}
override fun onError(exception: Exception) {
callback.onError(exception)
}
})
}
private fun getOccupantsNames(qbUsers: Collection<QBUser>): String? {
val userNameList = arrayListOf<String>()
for (user in qbUsers) {
if (TextUtils.isEmpty(user.fullName)) {
userNameList.add(user.login)
} else {
userNameList.add(user.fullName)
}
}
return TextUtils.join(", ", userNameList)
}
private fun occupantsIdsToString(occupantIdsList: Collection<Int>): String {
return TextUtils.join(",", occupantIdsList)
}
private fun sendChatMessage(dialog: QBChatDialog, qbChatMessage: QBChatMessage) {
if (dialog.isJoined) {
dialog.sendMessage(qbChatMessage)
} else {
dialogRepository.joinSync(dialog)
dialog.sendMessage(qbChatMessage)
}
}
private fun sendSystemMessage(message: QBChatMessage, occupants: List<Int>) {
message.setSaveToHistory(false)
message.isMarkable = false
for (opponentId in occupants) {
if (opponentId != dbRepository.getCurrentUser()?.id) {
message.recipientId = opponentId
chatService?.systemMessagesManager?.sendSystemMessage(message)
}
}
}
override fun deleteDialogs(dialogsDelete: ArrayList<QBChatDialog>, qbUser: QBUser, callback: DomainCallback<List<QBChatDialog>, Exception>) {
val qbRequestBuilder = QBDialogRequestBuilder()
qbRequestBuilder.removeUsers(qbUser)
val size = dialogsDelete.size
var responseCounter = 0
for (dialog in dialogsDelete) {
executor.addTask(object : ExecutorTask<Pair<QBChatDialog?, Bundle>> {
override fun backgroundWork(): Pair<QBChatDialog?, Bundle> {
val message = buildMessageLeftUser(dialog)
sendChatMessage(dialog, message)
return dialogRepository.updateSync(dialog, qbRequestBuilder)
}
override fun foregroundResult(result: Pair<QBChatDialog?, Bundle>) {
dialogsDelete.remove(result.first)
dialogs.remove(result.first)
if (++responseCounter == size) {
callback.onSuccess(ArrayList<QBChatDialog>(dialogsDelete), result.second)
}
}
override fun onError(exception: Exception) {
if (++responseCounter == size) {
callback.onSuccess(ArrayList<QBChatDialog>(dialogsDelete), null)
}
}
})
}
}
// TODO: 6/9/21 Need to add only 1 logic for leave from dialog
override fun leaveDialog(dialog: QBChatDialog, qbUser: QBUser, callback: DomainCallback<QBChatDialog, Exception>) {
val qbRequestBuilder = QBDialogRequestBuilder()
qbRequestBuilder.removeUsers(qbUser)
executor.addTask(object : ExecutorTask<Pair<QBChatDialog?, Bundle>> {
override fun backgroundWork(): Pair<QBChatDialog?, Bundle> {
val chatMessage = buildMessageLeftUser(dialog)
val systemMessage = buildMessageLeftUser(dialog)
dialog.leave()
sendChatMessage(dialog, chatMessage)
sendSystemMessage(systemMessage, dialog.occupants)
return dialogRepository.updateSync(dialog, qbRequestBuilder)
}
override fun foregroundResult(result: Pair<QBChatDialog?, Bundle>) {
result.first?.let { callback.onSuccess(it, result.second) }
}
override fun onError(exception: Exception) {
callback.onError(exception)
}
})
}
override fun readMessage(qbChatMessage: QBChatMessage, qbDialog: QBChatDialog, callback: DomainCallback<Unit, Exception>) {
executor.addTask(object : ExecutorTask<Unit> {
override fun backgroundWork() {
return qbDialog.readMessage(qbChatMessage)
}
override fun foregroundResult(result: Unit) {
callback.onSuccess(result, null)
}
override fun onError(exception: Exception) {
callback.onError(exception)
}
})
}
override fun sendCreateConference(dialog: QBChatDialog, callback: DomainCallback<Unit, Exception>) {
val message = buildMessageConferenceStarted(dialog)
executor.addTask(object : ExecutorTask<Unit> {
override fun backgroundWork() {
return sendChatMessage(dialog, message)
}
override fun foregroundResult(result: Unit) {
// empty
}
override fun onError(exception: Exception) {
// empty
}
})
}
override fun sendCreateStream(dialog: QBChatDialog, streamId: String, callback: DomainCallback<Unit, Exception>) {
val message = buildMessageStreamStarted(dialog, streamId)
executor.addTask(object : ExecutorTask<Unit> {
override fun backgroundWork() {
return sendChatMessage(dialog, message)
}
override fun foregroundResult(result: Unit) {
// empty
}
override fun onError(exception: Exception) {
// empty
}
})
}
override fun sendMessage(currentUser: QBUser, qbDialog: QBChatDialog, text: String, attachmentModels: ArrayList<AttachmentModel>, callback: DomainCallback<Unit, Exception>) {
if (isLoggedInChat()) {
send(text, qbDialog, attachmentModels, callback)
} else {
loginToChat(currentUser, object : DomainCallback<Unit, Exception> {
override fun onSuccess(result: Unit, bundle: Bundle?) {
send(text, qbDialog, attachmentModels, callback)
}
override fun onError(error: Exception) {
callback.onError(error)
}
})
}
}
override fun getDialogs(): ArrayList<QBChatDialog> {
return dialogs
}
override fun clearDialogs() {
totalCount = 0
skip = 0
dialogs.clear()
}
private fun send(text: String, qbDialog: QBChatDialog?, attachmentModels: ArrayList<AttachmentModel>, callback: DomainCallback<Unit, Exception>) {
qbDialog?.let { dialog ->
chatService?.let {
qbDialog.initForChat(it)
}
executor.addTask(object : ExecutorTask<Unit> {
override fun backgroundWork() {
if (attachmentModels.isNotEmpty()) {
for (attachmentModel in attachmentModels) {
try {
dialog.join(DiscussionHistory())
attachmentModel.qbFile?.let {
dialog.sendMessage(buildAttachmentMessage(it))
}
attachmentModels.remove(attachmentModel)
} catch (exception: Exception) {
callback.onError(exception)
}
}
}
if (text.isNotEmpty()) {
try {
dialog.join(DiscussionHistory())
dialog.sendMessage(buildTextMessage(text))
} catch (exception: SmackException.NotConnectedException) {
callback.onError(exception)
}
}
return
}
override fun foregroundResult(result: Unit) {
callback.onSuccess(result, null)
}
override fun onError(exception: Exception) {
callback.onError(exception)
}
})
}
}
private fun buildMessageAddedUsers(dialog: QBChatDialog?, userIds: String, currentUserName: String, usersNames: String?): QBChatMessage {
val qbChatMessage = QBChatMessage()
qbChatMessage.dialogId = dialog?.dialogId
qbChatMessage.setProperty(PROPERTY_NOTIFICATION_TYPE, OCCUPANTS_ADDED)
qbChatMessage.setProperty(PROPERTY_NEW_OCCUPANTS_IDS, userIds)
qbChatMessage.body = resourcesManager.get().getString(R.string.occupant_added, currentUserName, usersNames)
qbChatMessage.setSaveToHistory(true)
qbChatMessage.isMarkable = true
return qbChatMessage
}
private fun buildMessageLeftUser(dialog: QBChatDialog): QBChatMessage {
val qbChatMessage = QBChatMessage()
qbChatMessage.dialogId = dialog.dialogId
qbChatMessage.senderId = dbRepository.getCurrentUser()?.id
qbChatMessage.setProperty(PROPERTY_NOTIFICATION_TYPE, OCCUPANT_LEFT)
qbChatMessage.body = resourcesManager.get().getString(R.string.occupant_left, dbRepository.getCurrentUser()?.fullName)
qbChatMessage.setSaveToHistory(true)
qbChatMessage.isMarkable = true
return qbChatMessage
}
private fun buildMessageCreatedGroupDialog(dialog: QBChatDialog): QBChatMessage {
val qbChatMessage = QBChatMessage()
qbChatMessage.dialogId = dialog.dialogId
qbChatMessage.setProperty(PROPERTY_OCCUPANTS_IDS, occupantsIdsToString(dialog.occupants))
qbChatMessage.setProperty(PROPERTY_DIALOG_TYPE, dialog.type.code.toString())
qbChatMessage.setProperty(PROPERTY_DIALOG_NAME, dialog.name.toString())
qbChatMessage.setProperty(PROPERTY_NOTIFICATION_TYPE, CREATING_DIALOG)
qbChatMessage.dateSent = System.currentTimeMillis() / 1000
qbChatMessage.body = resourcesManager.get().getString(
R.string.new_chat_created, dbRepository.getCurrentUser()?.fullName
?: dbRepository.getCurrentUser()?.login, dialog.name
)
qbChatMessage.setSaveToHistory(true)
qbChatMessage.isMarkable = true
return qbChatMessage
}
private fun buildAttachmentMessage(qbFile: QBFile): QBChatMessage {
val chatMessage = QBChatMessage()
chatMessage.addAttachment(buildAttachment(qbFile))
chatMessage.setSaveToHistory(true)
chatMessage.dateSent = System.currentTimeMillis() / 1000
chatMessage.isMarkable = true
return chatMessage
}
private fun buildTextMessage(text: String): QBChatMessage {
val chatMessage = QBChatMessage()
chatMessage.body = text
chatMessage.setSaveToHistory(true)
chatMessage.dateSent = System.currentTimeMillis() / 1000
chatMessage.isMarkable = true
return chatMessage
}
private fun buildAttachment(qbFile: QBFile): QBAttachment {
val type = QBAttachment.IMAGE_TYPE
val attachment = QBAttachment(type)
attachment.id = qbFile.uid
attachment.size = qbFile.size.toDouble()
attachment.name = qbFile.name
attachment.contentType = qbFile.contentType
return attachment
}
private fun buildMessageConferenceStarted(dialog: QBChatDialog): QBChatMessage {
val qbChatMessage = QBChatMessage()
qbChatMessage.dialogId = dialog.dialogId
qbChatMessage.setProperty(PROPERTY_NOTIFICATION_TYPE, START_CONFERENCE)
qbChatMessage.setProperty(PROPERTY_CONVERSATION_ID, dialog.dialogId)
qbChatMessage.body = resourcesManager.get().getString(R.string.chat_conversation_started, resourcesManager.get().getString(R.string.conference))
qbChatMessage.setSaveToHistory(true)
qbChatMessage.isMarkable = true
return qbChatMessage
}
private fun buildMessageStreamStarted(dialog: QBChatDialog, streamId: String): QBChatMessage {
val qbChatMessage = QBChatMessage()
qbChatMessage.dialogId = dialog.dialogId
qbChatMessage.setProperty(PROPERTY_NOTIFICATION_TYPE, START_STREAM)
qbChatMessage.setProperty(PROPERTY_CONVERSATION_ID, streamId)
qbChatMessage.body = resourcesManager.get().getString(R.string.started_stream)
qbChatMessage.setSaveToHistory(true)
qbChatMessage.isMarkable = true
return qbChatMessage
}
override fun destroyChat() {
removeConnectionListener()
chatService?.destroy()
chatService = null
}
override fun isLoggedInChat(): Boolean {
chatService?.let {
return it.isLoggedIn
}
return false
}
override fun joinDialogs(dialogs: List<QBChatDialog>) {
executor.addTask(object : ExecutorTask<Unit> {
override fun backgroundWork() {
for (dialog in dialogs) {
dialogRepository.joinSync(dialog)
}
}
override fun foregroundResult(result: Unit) {
// empty
}
override fun onError(exception: Exception) {
// empty
}
})
}
override fun joinDialog(dialog: QBChatDialog, callback: DataCallBack<Unit?, Exception>) {
dialog.initForChat(chatService)
if (dialog.isJoined) {
callback.onSuccess(Unit, null)
return
}
executor.addTask(object : ExecutorTask<Unit> {
override fun backgroundWork() {
return dialogRepository.joinSync(dialog)
}
override fun foregroundResult(result: Unit) {
callback.onSuccess(result, null)
}
override fun onError(exception: Exception) {
callback.onError(exception)
}
})
}
inner class ChatConnectionListener : ConnectionListener {
override fun connected(p0: XMPPConnection?) {
//empty
}
override fun authenticated(p0: XMPPConnection?, p1: Boolean) {
//empty
}
override fun connectionClosed() {
chatService = null
}
override fun connectionClosedOnError(exception: Exception) {
connectionChatListeners.forEach { listener ->
listener.onError(exception)
}
}
override fun reconnectionSuccessful() {
chatService = QBChatService.getInstance()
for (dialog in dialogs) {
dialog.initForChat(chatService)
}
joinDialogs(dialogs)
connectionChatListeners.forEach { listener ->
listener.onConnectedChat()
}
}
override fun reconnectingIn(p0: Int) {
//empty
}
override fun reconnectionFailed(exception: Exception) {
connectionChatListeners.forEach { listener ->
listener.reconnectionFailed(exception)
}
chatService = null
}
}
private inner class SystemMessagesListener : QBSystemMessageListener {
override fun processMessage(qbChatMessage: QBChatMessage) {
executor.addTask(object : ExecutorTask<QBChatDialog> {
override fun backgroundWork(): QBChatDialog {
// TODO: 5/17/21 Delay for show message
try {
Thread.sleep(1000)
} catch (e: InterruptedException) {
e.printStackTrace()
}
val dialog = dialogRepository.getByIdSync(qbChatMessage.dialogId)
if (qbChatMessage.getProperty(PROPERTY_NOTIFICATION_TYPE) == CREATING_DIALOG) {
dialogRepository.joinSync(dialog)
}
return dialog
}
override fun foregroundResult(result: QBChatDialog) {
dialogListeners.forEach { listener ->
listener.onUpdatedDialog(result)
}
}
override fun onError(exception: Exception) {
dialogListeners.forEach { listener ->
listener.onError(exception)
}
}
})
}
override fun processError(exception: QBChatException, qbChatMessage: QBChatMessage) {
dialogListeners.forEach { listener ->
listener.onError(exception)
}
}
}
private inner class ChatMessageListener : QBChatDialogMessageListener {
override fun processMessage(dialogId: String, chatMessage: QBChatMessage, senderId: Int) {
when (chatMessage.getProperty(PROPERTY_NOTIFICATION_TYPE)) {
OCCUPANT_LEFT -> {
if (dbRepository.getCurrentUser()?.id != senderId) {
loadDialogWithJoin(dialogId, chatMessage)
}
}
OCCUPANTS_ADDED -> {
loadDialogWithJoin(dialogId, chatMessage)
}
else -> {
chatListeners.forEach { listener ->
listener.onReceivedMessage(dialogId, chatMessage, false)
}
}
}
}
override fun processError(dialogId: String?, exception: QBChatException?, qbChatMessage: QBChatMessage?, userId: Int?) {
exception?.message?.let {
chatListeners.forEach { listener ->
listener.onError(exception)
}
}
}
private fun loadDialogWithJoin(dialogId: String, chatMessage: QBChatMessage) {
executor.addTask(object : ExecutorTask<Unit> {
override fun backgroundWork() {
for ((index, dialog) in dialogs.withIndex()) {
if (dialog.dialogId == dialogId) {
val updatedDialog = dialogRepository.getByIdSync(dialogId)
dialogs[index] = updatedDialog
dialogRepository.joinSync(updatedDialog)
break
}
}
}
override fun foregroundResult(result: Unit) {
chatListeners.forEach { listener ->
listener.onReceivedMessage(dialogId, chatMessage, true)
}
}
override fun onError(exception: Exception) {
chatListeners.forEach { listener ->
listener.onError(exception)
}
}
})
}
}
private inner class DialogsMessageListener : QBChatDialogMessageListener {
override fun processMessage(dialogId: String, qbChatMessage: QBChatMessage, senderId: Int) {
if (qbChatMessage.getProperty(PROPERTY_NOTIFICATION_TYPE) == OCCUPANT_LEFT &&
senderId == dbRepository.getCurrentUser()?.id) {
return
}
executor.addTask(object : ExecutorTask<QBChatDialog> {
override fun backgroundWork(): QBChatDialog {
val dialog = dialogRepository.getByIdSync(qbChatMessage.dialogId)
dialogRepository.joinSync(dialog)
return dialog
}
override fun foregroundResult(result: QBChatDialog) {
dialogListeners.forEach { listener ->
listener.onUpdatedDialog(result)
}
}
override fun onError(exception: Exception) {
dialogListeners.forEach { listener ->
listener.onError(exception)
}
}
})
}
override fun processError(dialogId: String?, exception: QBChatException?, qbChatMessage: QBChatMessage?, userId: Int?) {
exception?.message?.let {
dialogListeners.forEach { listener ->
listener.onError(exception)
}
}
}
}
} | sample-conference-kotlin/app/src/main/java/com/quickblox/sample/conference/kotlin/domain/chat/ChatManagerImpl.kt | 3758200994 |
package chat.willow.thump.minecraft
import chat.willow.thump.Thump
import chat.willow.thump.api.IThumpServiceSink
import chat.willow.thump.helper.StringHelper
import chat.willow.thump.helper.TokenHelper
import com.google.common.base.Joiner
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.entity.player.EntityPlayerMP
import net.minecraft.util.DamageSource
import net.minecraft.util.text.ITextComponent
import net.minecraft.util.text.TextComponentTranslation
import net.minecraftforge.event.CommandEvent
import net.minecraftforge.event.ServerChatEvent
import net.minecraftforge.event.entity.living.LivingDeathEvent
import net.minecraftforge.event.entity.player.AchievementEvent
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
import net.minecraftforge.fml.common.gameevent.PlayerEvent
@Suppress("UNUSED")
class MinecraftEventsHandler(private val sink: IThumpServiceSink) {
@SubscribeEvent
fun onServerChatEvent(event: ServerChatEvent) {
if (!Thump.configuration.events.minecraft.playerMessage) {
return
}
val playerName = event.player.displayName.unformattedText
val chatMessage = event.component.unformattedText.removePrefix("<$playerName> ")
val message = TokenHelper().addUserToken(StringHelper.obfuscateNameIfNecessary(playerName)).addMessageToken(chatMessage).applyTokens(Thump.configuration.formats.minecraft.playerMessage)
sink.sendToAllServices(message)
}
@SubscribeEvent
fun onCommandEvent(event: CommandEvent) {
val commandName = event.command.name
val isServer = event.sender.name == "Server"
if (commandName.equals("me", ignoreCase = true)) {
if (isServer && !Thump.configuration.events.minecraft.serverAction) {
return
}
if (!isServer && !Thump.configuration.events.minecraft.playerAction) {
return
}
val message = TokenHelper().addUserToken(StringHelper.obfuscateNameIfNecessary(event.sender.displayName.unformattedText)).addMessageToken(Joiner.on(" ").join(event.parameters)).applyTokens(Thump.configuration.formats.minecraft.playerAction)
sink.sendToAllServices(message)
return
}
if (commandName.equals("say", ignoreCase = true)) {
if (isServer && !Thump.configuration.events.minecraft.serverMessage) {
return
}
if (!isServer && !Thump.configuration.events.minecraft.playerMessage) {
return
}
val message = TokenHelper().addUserToken(StringHelper.obfuscateNameIfNecessary(event.sender.displayName.unformattedText)).addMessageToken(Joiner.on(" ").join(event.parameters)).applyTokens(Thump.configuration.formats.minecraft.playerMessage)
sink.sendToAllServices(message)
}
}
@SubscribeEvent
fun onPlayerLoggedInEvent(event: PlayerEvent.PlayerLoggedInEvent) {
if (!Thump.configuration.events.minecraft.playerJoined) {
return
}
val message = TokenHelper().addUserToken(StringHelper.obfuscateNameIfNecessary(event.player.displayName.unformattedText)).applyTokens(Thump.configuration.formats.minecraft.playerJoined)
sink.sendToAllServices(message)
}
@SubscribeEvent
fun onPlayerLoggedOutEvent(event: PlayerEvent.PlayerLoggedOutEvent) {
if (!Thump.configuration.events.minecraft.playerLeft) {
return
}
val message = TokenHelper().addUserToken(StringHelper.obfuscateNameIfNecessary(event.player.displayName.unformattedText)).applyTokens(Thump.configuration.formats.minecraft.playerLeft)
sink.sendToAllServices(message)
}
@SubscribeEvent
fun onLivingDeathEvent(event: LivingDeathEvent) {
if (!Thump.configuration.events.minecraft.playerDeath) {
return
}
val player = event.entityLiving as? EntityPlayer ?: return
var deathMessage: ITextComponent? = player.combatTracker.deathMessage
if (deathMessage == null) {
deathMessage = generateNewDeathMessageFromLastDeath(player, event.source)
}
var unformattedText = deathMessage.unformattedText
if (Thump.configuration.general.obfuscateUserSourceFromMinecraft) {
val playerDisplayName = player.displayName.unformattedText
val obfuscatedName = StringHelper.obfuscateString(playerDisplayName)
unformattedText = unformattedText.replace(playerDisplayName, obfuscatedName)
}
val relevantEmoji = DeathEmojiPicker.relevantEmojisForDeathMessage(unformattedText)
val message = TokenHelper().addMessageToken(unformattedText).addDeathEmojiToken(relevantEmoji).applyTokens(Thump.configuration.formats.minecraft.playerDeath)
sink.sendToAllServices(message)
}
private fun generateNewDeathMessageFromLastDeath(player: EntityPlayer, source: DamageSource): ITextComponent {
return source.getDeathMessage(player)
}
@SubscribeEvent
fun onAchievementEvent(event: AchievementEvent) {
if (!Thump.configuration.events.minecraft.playerAchievement) {
return
}
val achievement = event.achievement
val entityPlayer = event.entityPlayer as? EntityPlayerMP ?: return
val statFile = entityPlayer.statFile
if (!statFile.canUnlockAchievement(achievement) || statFile.hasAchievementUnlocked(achievement)) {
return
}
val playerDisplayNameComponent = entityPlayer.displayName
val achievementMessage = TextComponentTranslation("chat.type.achievement", playerDisplayNameComponent, achievement.createChatComponent())
var unformattedText = achievementMessage.unformattedText
if (Thump.configuration.general.obfuscateUserSourceFromMinecraft) {
val playerDisplayName = playerDisplayNameComponent.unformattedText
val obfuscatedName = StringHelper.obfuscateString(playerDisplayName)
unformattedText = unformattedText.replace(playerDisplayName, obfuscatedName)
}
val message = TokenHelper().addMessageToken(unformattedText).applyTokens(Thump.configuration.formats.minecraft.playerAchievement)
sink.sendToAllServices(message)
}
}
| src/main/kotlin/chat/willow/thump/minecraft/MinecraftEventsHandler.kt | 326544548 |
// DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2018. Saarland University
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// Current Maintainers:
// Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland>
// Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland>
//
// Former Maintainers:
// Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de>
//
// web: www.droidmate.org
package org.droidmate.device.datatypes
class UiautomatorWindowDumpTestHelper {
// TODO Fix tests
/*companion object {
private val deviceModel = DeviceModel.buildDefault()
//region Fixture dumps
@JvmStatic
fun newEmptyWindowDump(): UiautomatorWindowDump =
UiautomatorWindowDump("", deviceModel.getDeviceDisplayDimensionsForTesting(), deviceModel.getAndroidLauncherPackageName())
@JvmStatic
fun newEmptyActivityWindowDump(): UiautomatorWindowDump =
UiautomatorWindowDump(windowDump_tsa_emptyAct, deviceModel.getDeviceDisplayDimensionsForTesting(), deviceModel.getAndroidLauncherPackageName())
@JvmStatic
fun newAppHasStoppedDialogWindowDump(): UiautomatorWindowDump =
UiautomatorWindowDump(windowDump_app_stopped_dialogbox, deviceModel.getDeviceDisplayDimensionsForTesting(), deviceModel.getAndroidLauncherPackageName())
@JvmStatic
fun newAppHasStoppedDialogOKDisabledWindowDump(): UiautomatorWindowDump =
UiautomatorWindowDump(windowDump_app_stopped_OK_disabled, deviceModel.getDeviceDisplayDimensionsForTesting(), deviceModel.getAndroidLauncherPackageName())
@JvmStatic
fun newSelectAHomeAppWindowDump(): UiautomatorWindowDump =
UiautomatorWindowDump(windowDump_selectAHomeApp, deviceModel.getDeviceDisplayDimensionsForTesting(), deviceModel.getAndroidLauncherPackageName())
@JvmStatic
fun newCompleteActionUsingWindowDump(): UiautomatorWindowDump =
UiautomatorWindowDump(windowDump_complActUsing_dialogbox, deviceModel.getDeviceDisplayDimensionsForTesting(), deviceModel.getAndroidLauncherPackageName())
@JvmStatic
fun newHomeScreenWindowDump(id: String = ""): UiautomatorWindowDump =
UiautomatorWindowDump(windowDump_nexus7_home_screen, deviceModel.getDeviceDisplayDimensionsForTesting(), deviceModel.getAndroidLauncherPackageName(), id)
@JvmStatic
fun newAppOutOfScopeWindowDump(id: String = ""): UiautomatorWindowDump =
UiautomatorWindowDump(windowDump_chrome_offline, deviceModel.getDeviceDisplayDimensionsForTesting(), deviceModel.getAndroidLauncherPackageName(), id)
//endregion Fixture dumps
@JvmStatic
fun newWindowDump(windowHierarchyDump: String): UiautomatorWindowDump =
UiautomatorWindowDump(windowHierarchyDump, deviceModel.getDeviceDisplayDimensionsForTesting(), deviceModel.getAndroidLauncherPackageName())
@Suppress("unused")
@JvmStatic
fun newEmptyActivityWithPackageWindowDump(appPackageName: String): UiautomatorWindowDump {
val payload = ""
return skeletonWithPayload(topNode(appPackageName, payload))
}
@Suppress("unused")
@JvmStatic
fun new1ButtonWithPackageWindowDump(appPackageName: String): UiautomatorWindowDump =
skeletonWithPayload(defaultButtonDump(appPackageName))
@JvmStatic
private fun skeletonWithPayload(payload: String, id: String = ""): UiautomatorWindowDump =
UiautomatorWindowDump(createDumpSkeleton(payload), deviceModel.getDeviceDisplayDimensionsForTesting(), deviceModel.getAndroidLauncherPackageName(), id)
@JvmStatic internal fun createDumpSkeleton(payload: String): String
=
"""<?xml version = '1.0' encoding = 'UTF-8' standalone = 'yes' ?><hierarchy rotation = "0">$payload</hierarchy>"""
@JvmStatic
private fun topNode(appPackageName: String = apkFixture_simple_packageName, payload: String): String {
return """<node index="0" text="" resource-uid="" class="android.widget.FrameLayout" package="$appPackageName"
content-contentDesc="" check="false" check="false" clickable="false" enabled="true" focusable="false" focus="false"
scrollable="false" long-clickable="false" password="false" selected="false" bounds="[0,0][800,1205]">$payload</node>"""
}
@JvmStatic
private fun defaultButtonDump(packageName: String = apkFixture_simple_packageName): String {
val buttonBounds = createConstantButtonBounds()
return createButtonDump(0, "dummyText", buttonBounds, packageName)
}
@JvmStatic
private fun createConstantButtonBounds(): String {
val x = 10
val y = 20
val width = 100
val height = 200
return "[$x,$y][${x + width},${y + height}]"
}
@JvmStatic
fun dump(w: Widget): String {
val idString = if (w.id.isNotEmpty()) "uid=\"${w.id}\"" else ""
return """<node
index="${w.index}"
text="${w.text}"
resource-uid="${w.resourceId}"
class="${w.className}"
package="${w.packageName}"
content-contentDesc="${w.contentDesc}"
check="${w.checkable}"
check="${w.checked}"
clickable="${w.clickable}"
enabled="${w.enabled}"
focusable="${w.focusable}"
focus="${w.focused}"
scrollable="${w.scrollable}"
long-clickable="${w.longClickable}"
password="${w.password}"
selected="${w.selected}"
bounds="${rectShortString(w.bounds)}"
$idString
/>"""
}
// WISH deprecated as well as calling methods. Instead, use org.droidmate.test.device.datatypes.UiautomatorWindowDumpTestHelper.dump
@JvmStatic
private fun createButtonDump(index: Int, text: String, bounds: String, packageName: String = apkFixture_simple_packageName): String =
"""<node index="$index" text="$text" resource-uid="dummy.package.ExampleApp:uid/button_$text"
class="android.widget.Button" package="$packageName" content-contentDesc="" check="false" check="false"
clickable="true" enabled="true" focusable="true" focus="false" scrollable="false" long-clickable="false" password="false"
selected="false" bounds="$bounds"/>"""
/**
* Returns the same value as {@code android.graphics.Rect.toShortString (java.lang.StringBuilder)}
*/
@JvmStatic
private fun rectShortString(r: Rectangle): String {
with(r) {
return "[${minX.toInt()},${minY.toInt()}][${maxX.toInt()},${maxY.toInt()}]"
}
}
@JvmStatic
fun fromGuiState(guiStatus: IGuiStatus): IDeviceGuiSnapshot {
return skeletonWithPayload(
guiStatus.widgets.joinToString(System.lineSeparator()) { dump(it) }, guiStatus.id)
}
}*/
} | project/pcComponents/core/src/test/kotlin/org/droidmate/device/datatypes/UiautomatorWindowDumpTestHelper.kt | 206358460 |
package br.com.dgimenes.nasapiccontentfetcher
import br.com.dgimenes.nasapiccontentfetcher.service.api.NasaAPODWebservice
import br.com.dgimenes.nasapiccontentfetcher.service.api.RetrofitFactory
import br.com.dgimenes.nasapicserver.model.SpacePic
import br.com.dgimenes.nasapicserver.model.SpacePicSource
import br.com.dgimenes.nasapicserver.model.SpacePicStatus
import com.cloudinary.Cloudinary
import com.cloudinary.Transformation
import com.cloudinary.utils.ObjectUtils
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import java.text.SimpleDateFormat
import java.util.*
import javax.persistence.Persistence
fun main(args: Array<String>) {
val program = DownloadLatestPics()
try {
if (args.size > 0 && args[0] == "test-data")
program.insertTestData()
else if (args.size > 1 && args[0] == "check-interval")
program.downloadLatest(args[1].toInt())
else if (args.size > 1 && args[0] == "set-best")
program.downloadAndSetBest(args[1].toString())
else {
program.downloadLatest()
}
program.close()
} catch(e: Exception) {
e.printStackTrace()
program.close()
} finally {
Thread.sleep(2000)
}
}
class DownloadLatestPics {
var em = Persistence.createEntityManagerFactory("primary_pu_dev").createEntityManager()
val DATE_FORMAT = "yyyy-MM-dd"
val APOD_BASE_URL = "https://api.nasa.gov"
val CONFIG_FILE_NAME = "nasapiccontentfetcher.config"
var APOD_API_KEY: String? = null
var CLOUDINARY_CLOUD_NAME: String? = null
var CLOUDINARY_API_KEY: String? = null
var CLOUDINARY_API_SECRET: String? = null
var cloudinary: Cloudinary? = null
fun downloadLatest(checkInterval: Int? = null) {
loadConfigurations()
println("Fetching pictures metadata...")
val spacePics =
if (checkInterval != null)
downloadLatestAPODsMetadata(checkInterval)
else
downloadLatestAPODsMetadata()
println("SpacePics to persist = ${spacePics.size}")
spacePics.forEach { persistNewSpacePic(it) }
println("Persisted!")
println("Checking SpacePics not published yet...")
val spacePicsToPublish = getSpacePicsToPublish()
println("Pics to publish = ${spacePicsToPublish.size}")
if (spacePicsToPublish.size > 0) {
setupCloudinary()
println("Preparing and publishing SpacePics...")
spacePicsToPublish.map { prepareSpacePicForPublishing(it) }
.filterNotNull()
.forEach { persistNewSpacePic(it) }
}
println("All done! Bye")
}
fun downloadAndSetBest(dateStr: String) {
loadConfigurations()
println("Fetching picture metadata...")
SimpleDateFormat(DATE_FORMAT).parse(dateStr).toString() // just validating
val spacePic = downloadAPODMetadata(dateStr)
?: throw RuntimeException("APOD could not be downloaded")
spacePic.best = true
println("Preparing and publishing SpacePic...")
prepareSpacePicForPublishing(spacePic)
persistNewSpacePic(spacePic)
println("All done! Bye")
}
private fun loadConfigurations() {
val inputStream = this.javaClass.classLoader.getResourceAsStream(CONFIG_FILE_NAME)
inputStream ?: throw RuntimeException("Configurations file $CONFIG_FILE_NAME not found!")
val properties = Properties()
properties.load(inputStream)
APOD_API_KEY = properties.get("apod-api-key") as String?
CLOUDINARY_CLOUD_NAME = properties.get("cloudinary-cloud-name") as String?
CLOUDINARY_API_KEY = properties.get("cloudinary-api-key") as String?
CLOUDINARY_API_SECRET = properties.get("cloudinary-api-secret") as String?
if (APOD_API_KEY == null || CLOUDINARY_CLOUD_NAME == null || CLOUDINARY_API_KEY == null
|| CLOUDINARY_API_SECRET == null) {
throw RuntimeException("Invalid configurations!")
}
}
private fun setupCloudinary() {
val config = HashMap<String, String>()
config.put("cloud_name", CLOUDINARY_CLOUD_NAME!!)
config.put("api_key", CLOUDINARY_API_KEY!!)
config.put("api_secret", CLOUDINARY_API_SECRET!!)
cloudinary = Cloudinary(config);
}
private fun prepareSpacePicForPublishing(spacePic: SpacePic): SpacePic? {
println("preparing SpacePic ${DateTime(spacePic.originallyPublishedAt).toString(DATE_FORMAT)}...")
spacePic.status = SpacePicStatus.PUBLISHED
spacePic.publishedAt = DateTime().toDate()
try {
val uploadResult = cloudinary?.uploader()?.upload(
spacePic.originalApiImageUrl, ObjectUtils.emptyMap()) ?: return null
spacePic.hdImageUrl = uploadResult.get("url") as String
val resizedUrl = cloudinary?.url()?.transformation(
Transformation().width(320).height(320).crop("fill")
)?.generate(uploadResult.get("public_id") as String) ?: return null
spacePic.previewImageUrl = resizedUrl
return spacePic
} catch (e: Exception) {
e.printStackTrace()
return null
}
}
private fun getSpacePicsToPublish(): List<SpacePic> {
val toPublishQuery = em.createQuery(
"FROM SpacePic WHERE status = :status ORDER BY createdAt DESC")
toPublishQuery.setParameter("status", SpacePicStatus.CREATED)
return toPublishQuery.resultList as List<SpacePic>
}
// TODO refator all APOD-related logic to a different
// class as soon as there are other SpacePic sources
private fun downloadLatestAPODsMetadata(checkInterval: Int = 3): List<SpacePic> {
println("=== APOD ===")
println("checkInterval = $checkInterval")
println("Checking for already downloaded APOD pictures...")
val daysToFetch = getDaysThatNeedToFetchAPOD(checkInterval)
val spacePics = daysToFetch.map { downloadAPODMetadata(it) }.filterNotNull()
return spacePics
}
private fun downloadAPODMetadata(dayString: String): SpacePic? {
println("Downloading APOD metadata of $dayString")
val apodWebService = RetrofitFactory.get(APOD_BASE_URL)
.create(NasaAPODWebservice::class.java)
val response = apodWebService.getAPOD(APOD_API_KEY!!, false, dayString).execute()
if (!response.isSuccess) {
println("url ${response.raw().request().urlString()}")
println(response.errorBody().string())
return null
}
val apod = response.body()
val spacePic = SpacePic(
originalApiUrl = response.raw().request().urlString(),
originalApiImageUrl = apod.hdUrl ?: apod.url,
originallyPublishedAt = DateTimeFormat.forPattern(DATE_FORMAT)
.parseDateTime(dayString).toDate(),
title = apod.title,
createdAt = DateTime().toDate(),
status = SpacePicStatus.CREATED,
source = SpacePicSource.NASA_APOD,
description = apod.explanation,
hdImageUrl = "",
previewImageUrl = "",
publishedAt = null,
deletedAt = null,
updatedAt = null
)
if (apod.mediaType != "image") {
spacePic.status = SpacePicStatus.DELETED
spacePic.deletedAt = DateTime().toDate()
}
return spacePic
}
private fun getDaysThatNeedToFetchAPOD(checkInterval: Int): Set<String> {
val startDate = DateTime().minusDays(checkInterval - 1)
.withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0)
val latestQuery = em.createQuery(
"""
FROM SpacePic
WHERE source = :source
AND originallyPublishedAt >= :originallyPublishedAt
ORDER BY originallyPublishedAt DESC
""")
latestQuery.setParameter("source", SpacePicSource.NASA_APOD)
latestQuery.setParameter("originallyPublishedAt", startDate.toDate())
val latestPersistedAPODs = latestQuery.resultList as List<SpacePic>
val daysAlreadyFetchedAsDateStrings =
latestPersistedAPODs.map { DateTime(it.originallyPublishedAt).toString(DATE_FORMAT) }.toSet()
println("daysAlreadyFetched = $daysAlreadyFetchedAsDateStrings")
val daysThatShouldBeFetchedAsDateStrings = intervalToListOfDateStrings(startDate, DateTime())
println("daysThatShouldBeFetched = $daysThatShouldBeFetchedAsDateStrings")
val daysToFetch = daysThatShouldBeFetchedAsDateStrings.minus(daysAlreadyFetchedAsDateStrings)
println("daysToFetch = $daysToFetch")
return daysToFetch
}
// TODO refactor
private fun intervalToListOfDateStrings(startDate: DateTime, endDate: DateTime): Set<String> {
var dateStrings = linkedSetOf<String>()
var currDate = startDate
while (currDate <= endDate) {
dateStrings.add(currDate.toString(DATE_FORMAT))
currDate = currDate.plusDays(1)
}
return dateStrings
}
private fun persistNewSpacePic(spacePic: SpacePic) {
em.transaction.begin()
em.persist(spacePic)
em.transaction.commit()
}
fun insertTestData() {
val spacePics = getTestSpacePics()
spacePics.forEach { persistNewSpacePic(it) }
}
private fun getTestSpacePics(): List<SpacePic> {
val unpublishedSpacePic = SpacePic(
originalApiUrl = "https://api.nasa.gov/planetary/apod?concept_tags=True&api_key=DEMO_KEY",
originalApiImageUrl = "http://apod.nasa.gov/apod/image/1512/Refsdal_Hubble_1080.jpg",
originallyPublishedAt = DateTime().toDate(),
title = "SN Refsdal: The First Predicted Supernova Image",
createdAt = DateTime().toDate(),
status = SpacePicStatus.CREATED,
source = SpacePicSource.NASA_APOD
)
val spacePic = SpacePic(
originalApiUrl = "https://api.nasa.gov/planetary/apod?concept_tags=True&api_key=DEMO_KEY",
originalApiImageUrl = "http://apod.nasa.gov/apod/image/1512/Refsdal_Hubble_1080.jpg",
originallyPublishedAt = DateTime().toDate(),
title = "SN Refsdal: The First Predicted Supernova Image",
createdAt = DateTime().toDate(),
status = SpacePicStatus.PUBLISHED,
source = SpacePicSource.NASA_APOD,
description = "It's back. Never before has an observed supernova been predicted. " +
"The unique astronomical event occurred in the field of galaxy cluster MACS J1149.5+2223. " +
"Most bright spots in the featured image are galaxies in this cluster. The actual " +
"supernova, dubbed Supernova Refsdal, occurred just once far across the universe and well " +
"behind this massive galaxy cluster. Gravity caused the cluster to act as a massive " +
"gravitational lens, splitting the image of Supernova Refsdal into multiple bright images. " +
"One of these images arrived at Earth about ten years ago, likely in the upper red circle, " +
"and was missed. Four more bright images peaked in April in the lowest red circle, spread " +
"around a massive galaxy in the cluster as the first Einstein Cross supernova. But there " +
"was more. Analyses revealed that a sixth bright supernova image was likely still on its " +
"way to Earth and likely to arrive within the next year. Earlier this month -- right on " +
"schedule -- this sixth bright image was recovered, in the middle red circle, as predicted. " +
" Studying image sequences like this help humanity to understand how matter is distributed " +
"in galaxies and clusters, how fast the universe expands, and how massive stars explode. " +
" Follow APOD on: Facebook, Google Plus, or Twitter",
hdImageUrl = "",
previewImageUrl = "",
publishedAt = DateTime().toDate(),
deletedAt = null,
updatedAt = DateTime().toDate()
)
return listOf(spacePic, unpublishedSpacePic)
}
fun close() {
if (em.isOpen) {
em.entityManagerFactory.close()
}
}
}
| src/main/java/br/com/dgimenes/nasapiccontentfetcher/DownloadLatestPics.kt | 1767297333 |
package {{ cookiecutter.core_package_name }}.utils.injection
import dagger.Module
import dagger.Provides
import okhttp3.OkHttpClient
import {{ cookiecutter.core_package_name }}.utils.configuration.StringConstants
import retrofit2.CallAdapter
import retrofit2.Converter
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module
abstract class BaseNetworkModule {
@Singleton
@Provides
fun converterFactory(): Converter.Factory =
GsonConverterFactory.create()
@Singleton
@Provides
fun callAdapterFactory(): CallAdapter.Factory =
RxJava2CallAdapterFactory.create()
@Singleton
@Provides
fun retrofit(
httpClient: OkHttpClient,
converterFactory: Converter.Factory,
callAdapterFactory: CallAdapter.Factory
): Retrofit =
Retrofit.Builder()
.baseUrl(StringConstants.BASE_URL)
.client(httpClient)
.addConverterFactory(converterFactory)
.addCallAdapterFactory(callAdapterFactory)
.build()
} | {{ cookiecutter.repo_name }}/core/src/main/java/{{ cookiecutter.core_package_dir }}/utils/injection/BaseNetworkModule.kt | 245487247 |
/*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.project
import javafx.css.Styleable
import javafx.geometry.Side
import javafx.scene.Node
import javafx.scene.control.Button
import javafx.scene.control.ContextMenu
import javafx.scene.control.TextField
import javafx.scene.control.ToolBar
import javafx.scene.input.KeyEvent
import javafx.scene.input.MouseEvent
import javafx.scene.layout.BorderPane
import javafx.scene.layout.StackPane
import uk.co.nickthecoder.paratask.ParaTaskApp
import uk.co.nickthecoder.paratask.SidePanel
import uk.co.nickthecoder.paratask.Tool
import uk.co.nickthecoder.paratask.gui.CompoundButtons
import uk.co.nickthecoder.paratask.gui.MySplitPane
import uk.co.nickthecoder.paratask.gui.ShortcutHelper
import uk.co.nickthecoder.paratask.util.RequestFocus
import uk.co.nickthecoder.paratask.util.Stoppable
class HalfTab_Impl(override var toolPane: ToolPane)
: MySplitPane(), HalfTab {
val mainArea = BorderPane()
override val toolBars = BorderPane()
private val toolBar = ToolBar()
private val shortcuts = ShortcutHelper("HalfTab", this)
override val optionsField = TextField()
override lateinit var projectTab: ProjectTab
val stopButton: Button
val runButton: Button
override val history = History(this)
val optionsContextMenu = ContextMenu()
var sidePanel: SidePanel? = null
set(v) {
if (right != null && left is Styleable) {
(left as Styleable).styleClass.remove("sidebar")
}
if (v == null) {
right = null
left = mainArea
} else {
left = v.node
right = mainArea
if (v is Styleable) {
v.styleClass.add("sidebar")
}
}
field = v
}
val sidePanelToggleButton = ParataskActions.SIDE_PANEL_TOGGLE.createButton(shortcuts) { toggleSidePanel() }
init {
this.dividerRatio = 0.3
toolBars.center = toolBar
toolBar.styleClass.add("bottom")
left = mainArea
with(mainArea) {
center = toolPane as Node
bottom = toolBars
}
with(optionsField) {
prefColumnCount = 6
addEventHandler(KeyEvent.KEY_PRESSED, { optionsFieldKeyPressed(it) })
addEventHandler(MouseEvent.MOUSE_PRESSED, { optionFieldMouse(it) })
addEventHandler(MouseEvent.MOUSE_RELEASED, { optionFieldMouse(it) })
contextMenu = optionsContextMenu
}
val historyGroup = CompoundButtons()
val backButton = ParataskActions.HISTORY_BACK.createButton(shortcuts) { history.undo() }
val forwardButton = ParataskActions.HISTORY_FORWARD.createButton(shortcuts) { history.redo() }
backButton.disableProperty().bind(history.canUndoProperty.not())
forwardButton.disableProperty().bind(history.canRedoProperty.not())
historyGroup.children.addAll(backButton, forwardButton)
val runStopStack = StackPane()
stopButton = ParataskActions.TOOL_STOP.createButton(shortcuts) { onStop() }
runButton = ParataskActions.TOOL_RUN.createButton(shortcuts) { onRun() }
runStopStack.children.addAll(stopButton, runButton)
sidePanelToggleButton.isDisable = !toolPane.tool.hasSidePanel
toolBar.items.addAll(
optionsField,
runStopStack,
ParataskActions.TOOL_SELECT.createToolButton(shortcuts) { tool -> onSelectTool(tool) },
historyGroup,
sidePanelToggleButton,
ParataskActions.TAB_SPLIT_TOGGLE.createButton(shortcuts) { projectTab.splitToggle() },
ParataskActions.TAB_MERGE_TOGGLE.createButton(shortcuts) { projectTab.mergeToggle() },
ParataskActions.TOOL_CLOSE.createButton(shortcuts) { close() })
bindButtons()
shortcuts.add(ParataskActions.PARAMETERS_SHOW) { onShowParameters() }
shortcuts.add(ParataskActions.RESULTS_SHOW) { onShowResults() }
shortcuts.add(ParataskActions.RESULTS_TAB_CLOSE) { onCloseResults() }
}
override fun attached(projectTab: ProjectTab) {
this.projectTab = projectTab
ParaTaskApp.logAttach("HalfTab.attaching ToolPane")
toolPane.attached(this)
ParaTaskApp.logAttach("HalfTab.attached ToolPane")
}
override fun detaching() {
ParaTaskApp.logAttach("HalfTab.detaching ToolPane")
toolPane.detaching()
mainArea.center = null
mainArea.bottom = null
left = null
right = null
toolBars.children.clear()
toolBar.items.clear()
shortcuts.clear()
optionsContextMenu.items.clear()
ParaTaskApp.logAttach("HalfTab.detached ToolPane")
}
override fun isLeft() = projectTab.left === this
override fun otherHalf(): HalfTab? {
if (isLeft()) {
return projectTab.right
} else {
return projectTab.left
}
}
fun bindButtons() {
runButton.disableProperty().bind(toolPane.tool.taskRunner.disableRunProperty)
runButton.visibleProperty().bind(toolPane.tool.taskRunner.showRunProperty)
stopButton.visibleProperty().bind(toolPane.tool.taskRunner.showStopProperty)
}
override fun changeTool(tool: Tool, prompt: Boolean) {
val showSidePanel = right != null
sidePanel = null
toolPane.detaching()
children.remove(toolPane as Node)
toolPane = ToolPane_Impl(tool)
mainArea.center = toolPane as Node
toolPane.attached(this)
projectTab.changed()
bindButtons()
history.push(tool)
if (!prompt) {
try {
tool.check()
} catch(e: Exception) {
return
}
toolPane.parametersPane.run()
}
sidePanelToggleButton.isDisable = !tool.hasSidePanel
if (tool.hasSidePanel && showSidePanel) {
toggleSidePanel()
}
}
override fun onStop() {
val tool = toolPane.tool
if (tool is Stoppable) {
tool.stop()
}
}
override fun onRun() {
toolPane.parametersPane.run()
}
fun onSelectTool(tool: Tool) {
val newTool = tool.copy()
newTool.resolveParameters(projectTab.projectTabs.projectWindow.project.resolver)
changeTool(newTool)
}
override fun close() {
projectTab.remove(toolPane)
}
override fun pushHistory() {
history.push(toolPane.tool)
}
override fun pushHistory(tool: Tool) {
history.push(tool)
}
fun optionsFieldKeyPressed(event: KeyEvent) {
var done = false
val tool = toolPane.resultsTool()
val runner = tool.optionsRunner
if (ParataskActions.OPTION_RUN.match(event)) {
done = runner.runNonRow(optionsField.text, prompt = false, newTab = false)
} else if (ParataskActions.OPTION_RUN_NEW_TAB.match(event)) {
done = runner.runNonRow(optionsField.text, prompt = false, newTab = true)
} else if (ParataskActions.OPTION_PROMPT.match(event)) {
done = runner.runNonRow(optionsField.text, prompt = true, newTab = false)
} else if (ParataskActions.OPTION_PROMPT_NEW_TAB.match(event)) {
done = runner.runNonRow(optionsField.text, prompt = true, newTab = true)
} else if (ParataskActions.CONTEXT_MENU.match(event)) {
onOptionsContextMenu()
event.consume()
}
if (done) {
optionsField.text = ""
}
}
fun optionFieldMouse(event: MouseEvent) {
if (event.isPopupTrigger) {
onOptionsContextMenu()
event.consume()
}
}
private fun onOptionsContextMenu() {
val tool = toolPane.resultsTool()
tool.optionsRunner.createNonRowOptionsMenu(optionsContextMenu)
optionsContextMenu.show(optionsField, Side.BOTTOM, 0.0, 0.0)
}
fun onShowParameters() {
toolPane.parametersTab.isSelected = true
}
fun onShowResults() {
toolPane.tabPane.selectionModel.select(0)
}
fun onCloseResults() {
val minorTab = toolPane.tabPane.selectedTab
if (minorTab != null && minorTab.canClose && minorTab is ResultsTab) {
minorTab.close()
if ( toolPane.tabPane.tabs.filterIsInstance<ResultsTab>().isEmpty() ) {
close()
}
}
}
override fun focusOption() {
ParaTaskApp.logFocus("HalfTab_Impl focusOption. RequestFocus.requestFocus(optionsField)")
RequestFocus.requestFocus(optionsField)
}
override fun focusOtherHalf() {
val other = if (projectTab.left === this) projectTab.right else projectTab.left
other?.toolPane?.focusResults()
}
fun toggleSidePanel() {
if (sidePanel == null) {
sidePanel = toolPane.tool.getSidePanel()
} else {
sidePanel = null
}
}
}
| paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/project/HalfTab_Impl.kt | 185652616 |
import org.apollo.game.model.Position
import org.apollo.game.model.World
import org.apollo.game.model.entity.Player
import org.apollo.game.plugin.testing.assertions.verifyAfter
import org.apollo.game.plugin.testing.junit.ApolloTestingExtension
import org.apollo.game.plugin.testing.junit.api.ActionCapture
import org.apollo.game.plugin.testing.junit.api.annotations.TestMock
import org.apollo.game.plugin.testing.junit.api.interactions.interactWith
import org.apollo.game.plugin.testing.junit.api.interactions.spawnNpc
import org.apollo.game.plugin.testing.junit.api.interactions.spawnObject
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
@ExtendWith(ApolloTestingExtension::class)
class OpenBankTest {
companion object {
const val BANK_BOOTH_ID = 2213
const val BANK_TELLER_ID = 166
val BANK_POSITION = Position(3200, 3200, 0)
}
@TestMock
lateinit var action: ActionCapture
@TestMock
lateinit var player: Player
@TestMock
lateinit var world: World
@Test
fun `Interacting with a bank teller should open the players bank`() {
val bankTeller = world.spawnNpc(BANK_TELLER_ID, BANK_POSITION)
// @todo - these option numbers only match by coincidence, we should be looking up the correct ones
player.interactWith(bankTeller, option = 2)
verifyAfter(action.complete()) { player.openBank() }
}
@Test
fun `Interacting with a bank booth object should open the players bank`() {
val bankBooth = world.spawnObject(BANK_BOOTH_ID, BANK_POSITION)
player.interactWith(bankBooth, option = 2)
verifyAfter(action.complete()) { player.openBank() }
}
} | game/plugin/bank/test/OpenBankTest.kt | 2253485731 |
package com.example.alexeyglushkov.taskmanager
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.util.Log
import androidx.annotation.WorkerThread
import com.example.alexeyglushkov.streamlib.progress.ProgressListener
import com.example.alexeyglushkov.taskmanager.coordinators.TaskManagerCoordinator
import com.example.alexeyglushkov.taskmanager.pool.ListTaskPool
import com.example.alexeyglushkov.taskmanager.pool.TaskPool
import com.example.alexeyglushkov.taskmanager.providers.PriorityTaskProvider
import com.example.alexeyglushkov.taskmanager.providers.TaskProvider
import com.example.alexeyglushkov.taskmanager.providers.TaskProviders
import com.example.alexeyglushkov.taskmanager.runners.InstantThreadRunner
import com.example.alexeyglushkov.taskmanager.runners.ScopeThreadRunner
import com.example.alexeyglushkov.taskmanager.runners.ThreadRunner
import com.example.alexeyglushkov.taskmanager.task.*
import com.example.alexeyglushkov.taskmanager.tools.*
import com.example.alexeyglushkov.tools.CancelError
import com.example.alexeyglushkov.tools.HandlerTools
import org.junit.Assert
import java.lang.ref.WeakReference
import java.util.ArrayList
import java.util.Comparator
import java.util.Date
import kotlinx.coroutines.*
import kotlinx.coroutines.android.asCoroutineDispatcher
/**
* Created by alexeyglushkov on 20.09.14.
*/
open class SimpleTaskManager : TaskManager, TaskPool.Listener {
companion object {
internal val TAG = "SimpleTaskManager"
const val WaitingTaskProviderId = "WaitingTaskProviderId"
}
var _threadRunner: ThreadRunner = InstantThreadRunner()
// TODO: try to use channel instead of a single thread
override var threadRunner: ThreadRunner
get() = _threadRunner
set(value) {
_threadRunner = value
loadingTasks.threadRunner = value
for (provider in _taskProviders) {
provider.threadRunner = value
}
}
private lateinit var callbackHandler: Handler
override var userData: Any? = null
private var listeners = WeakRefList<TaskManager.Listener>()
private var _taskScope: CoroutineScope? = null
private var taskScope: CoroutineScope
get() = _taskScope!!
set(value) {
_taskScope = value
}
private lateinit var loadingTasks: TaskPool
private lateinit var waitingTasks: TaskProvider
private var taskToJobMap = HashMap<Task, Job>()
// TODO: check out how we can avoid using SafeList or another solution
// TODO: think about weakref
private lateinit var _taskProviders: SafeList<TaskProvider>
override val taskProviders: List<TaskProvider>
get() {
return if (threadRunner.isOnThread())
_taskProviders.originalList
else
_taskProviders.safeList
}
private lateinit var _coordinator: TaskManagerCoordinator
override var taskManagerCoordinator: TaskManagerCoordinator
set(value) {
// it's experimental
// TODO: need to handle it properly
setupCoordinator(value)
}
get() = _coordinator
override fun getLoadingTaskCount(): Int {
return loadingTasks.getTaskCount()
}
@WorkerThread
override fun getTaskCount(): Int {
return threadRunner.run {
var taskCount = loadingTasks.getTaskCount()
for (provider in _taskProviders) {
taskCount += provider.getTaskCount()
}
return@run taskCount
}
}
@WorkerThread
override fun getTasks(): List<Task> {
val tasks = ArrayList<Task>()
tasks.addAll(loadingTasks.getTasks())
for (provider in _taskProviders) {
tasks.addAll(provider.getTasks())
}
return tasks
}
constructor(inCoordinator: TaskManagerCoordinator) {
init(inCoordinator, null, null)
}
constructor(inCoordinator: TaskManagerCoordinator, scope: CoroutineScope, taskScope: CoroutineScope) {
init(inCoordinator, scope, taskScope)
}
private fun init(inCoordinator: TaskManagerCoordinator, inScope: CoroutineScope?, inTaskScope: CoroutineScope?) {
initScope(inScope)
initTaskSope(inTaskScope)
setupCoordinator(inCoordinator)
callbackHandler = Handler(Looper.myLooper())
loadingTasks = ListTaskPool(threadRunner)
loadingTasks.addListener(this)
_taskProviders = createTaskProviders()
createWaitingTaskProvider()
}
private fun initScope(inScope: CoroutineScope?) {
val scope = if (inScope != null) {
inScope
} else {
val localHandlerThread = HandlerThread("SimpleTaskManager Thread")
localHandlerThread.start()
val handler = Handler(localHandlerThread.looper)
val dispatcher = handler.asCoroutineDispatcher("SimpleTaskManager handler dispatcher")
CoroutineScope(dispatcher + SupervisorJob())
}
_threadRunner = ScopeThreadRunner(scope, "SimpleTaskManagerScopeTheadId")
scope.launch {
threadRunner.setup()
}
}
private fun setupCoordinator(aCooridinator: TaskManagerCoordinator) {
_coordinator = aCooridinator
_coordinator.threadRunner = threadRunner
}
private fun initTaskSope(inScope: CoroutineScope?) {
taskScope = inScope ?: CoroutineScope(Dispatchers.IO + SupervisorJob())
}
private fun createTaskProviders(): SafeList<TaskProvider> {
val sortedList = SortedList(Comparator<TaskProvider> { lhs, rhs ->
if (lhs.priority == rhs.priority) {
return@Comparator 0
}
if (lhs.priority > rhs.priority) {
-1
} else 1
})
return SafeList(sortedList, callbackHandler)
}
private fun createWaitingTaskProvider() {
waitingTasks = PriorityTaskProvider(threadRunner, WaitingTaskProviderId)
waitingTasks.addListener(this)
_taskProviders.add(waitingTasks)
}
override fun addTask(task: Task) {
if (task !is TaskBase) { assert(false); return }
if (TaskProviders.addTaskCheck(task, TAG)) {
threadRunner.launch {
// task will be launched in onTaskAdded method
waitingTasks.addTask(task)
}
}
}
override fun startImmediately(task: Task) {
threadRunner.launchSuspend {
if (handleTaskLoadPolicy(task, null)) {
startTaskOnThread(task)
}
}
}
override fun cancel(task: Task, info: Any?) {
threadRunner.launch {
cancelTaskOnThread(task, info)
}
}
override fun addTaskProvider(provider: TaskProvider) {
Assert.assertEquals(provider.threadRunner, threadRunner)
Assert.assertNotNull(provider.taskProviderId)
threadRunner.launch {
addTaskProviderOnThread(provider)
}
}
@WorkerThread
private fun addTaskProviderOnThread(provider: TaskProvider) {
threadRunner.checkThread()
val oldTaskProvider = getTaskProvider(provider.taskProviderId)
if (oldTaskProvider != null) {
removeTaskProviderOnThread(oldTaskProvider)
}
provider.addListener(this)
_taskProviders.add(provider)
provider.taskFilter = taskManagerCoordinator.taskFilter
}
override fun setTaskProviderPriority(provider: TaskProvider, priority: Int) {
threadRunner.launch {
setTaskProviderPriorityOnThread(provider, priority)
}
}
@WorkerThread
private fun setTaskProviderPriorityOnThread(provider: TaskProvider, priority: Int) {
threadRunner.checkThread()
provider.priority = priority
(_taskProviders.originalList as SortedList<*>).updateSortedOrder()
}
override fun getTaskProvider(id: String): TaskProvider? {
return findProvider(taskProviders, id)
}
private fun findProvider(providers: List<TaskProvider>, id: String): TaskProvider? {
for (taskProvider in providers) {
if (taskProvider.taskProviderId == id) {
return taskProvider
}
}
return null
}
// == TaskPool.TaskPoolListener
@WorkerThread
override fun onTaskConflict(pool: TaskPool, newTask: Task, oldTask: Task): Task {
threadRunner.checkThread()
Assert.assertTrue(pool != loadingTasks)
return threadRunner.run {
resolveTaskConflict(newTask, oldTask)
}
}
@WorkerThread
override fun onTaskAdded(pool: TaskPool, task: Task) {
threadRunner.launch {
val isLoadingPool = pool === loadingTasks
if (isLoadingPool) {
taskManagerCoordinator.onTaskStartedLoading(pool, task)
}
logTask(task, "onTaskAdded $isLoadingPool")
triggerOnTaskAddedOnThread(task, isLoadingPool)
if (!isLoadingPool) {
if (handleTaskLoadPolicy(task, pool)) {
checkTasksToRunOnThread()
}
}
}
}
@WorkerThread
override fun onTaskRemoved(pool: TaskPool, task: Task) {
threadRunner.launch {
val isLoadingPool = pool === loadingTasks
if (isLoadingPool) {
taskManagerCoordinator.onTaskFinishedLoading(pool, task)
}
logTask(task, "onTaskRemoved $isLoadingPool")
triggerOnTaskRemovedOnThread(task, isLoadingPool)
}
}
@WorkerThread
override fun onTaskCancelled(pool: TaskPool, task: Task, info: Any?) {
threadRunner.launch {
cancelTaskOnThread(task, info)
}
}
// == TaskPool interface
override fun cancelTask(task: Task, info: Any?) {
cancel(task, info)
}
override fun removeTask(task: Task) {
cancel(task, null)
}
@WorkerThread
override fun getTask(taskId: String): Task? {
threadRunner.checkThread()
return threadRunner.run {
var task: Task? = loadingTasks.getTask(taskId)
if (task == null) {
for (provider in _taskProviders) {
task = provider.getTask(taskId)
if (task != null) {
break
}
}
}
return@run task
}
}
override fun removeListener(listener: TaskManager.Listener) {
listeners.removeValue(listener)
}
override fun addListener(listener: TaskManager.Listener) {
listeners.add(WeakReference(listener))
}
override fun addListener(listener: TaskPool.Listener) {
//unnecessary
}
override fun removeListener(listener: TaskPool.Listener) {
//unnecessary
}
override fun onTaskStatusChanged(task: Task, oldStatus: Task.Status, newStatus: Task.Status) {
//unnecessary
}
@WorkerThread
private fun triggerOnTaskAddedOnThread(task: Task, isLoadingQueue: Boolean) {
threadRunner.checkThread()
for (listener in listeners) {
listener.get()?.onTaskAdded(this, task, isLoadingQueue)
}
}
@WorkerThread
private fun triggerOnTaskRemovedOnThread(task: Task, isLoadingQueue: Boolean) {
threadRunner.checkThread()
for (listener in listeners) {
listener.get()?.onTaskRemoved(this, task, isLoadingQueue)
}
}
@WorkerThread
private fun triggerOnTaskStatusChangedOnThread(task: Task, oldStatus: Task.Status) {
threadRunner.checkThread()
for (listener in listeners) {
listener.get()?.onTaskStatusChanged(task, oldStatus)
}
}
// ==
override fun removeTaskProvider(provider: TaskProvider) {
threadRunner.launch {
removeTaskProviderOnThread(provider)
}
}
@WorkerThread
private fun removeTaskProviderOnThread(provider: TaskProvider) {
threadRunner.checkThread()
// cancel all tasks
for (task in ArrayList(provider.getTasks())) {
cancelTaskOnThread(task, null)
}
_taskProviders.remove(provider)
provider.taskFilter = null
}
fun setWaitingTaskProvider(provider: TaskProvider) {
Assert.assertEquals(provider.threadRunner, threadRunner)
provider.taskProviderId = WaitingTaskProviderId
addTaskProvider(provider)
}
// Private
// returns true when load policy checks pass
@WorkerThread
private fun handleTaskLoadPolicy(newTask: Task, taskPool: TaskPool?): Boolean {
threadRunner.checkThread()
if (newTask.isBlocked()) {
return false
}
val taskId = newTask.taskId
if (taskId != null) {
val pools = ArrayList<TaskPool>(taskProviders) + loadingTasks
for (pool in pools) {
if (pool != taskPool) {
val oldTask = pool.getTask(taskId)
if (oldTask != null) {
assert(oldTask != newTask)
val resultTask = resolveTaskConflict(newTask, oldTask)
if (resultTask == oldTask) {
return false // quit when task fails
}
}
}
if (newTask.isBlocked()) {
return false
}
}
}
return true
}
// returns newTask if we allow adding it in a provider
@WorkerThread
private fun resolveTaskConflict(newTask: Task, currentTask: Task): Task {
threadRunner.checkThread()
return when (newTask.loadPolicy) {
Task.LoadPolicy.AddDependencyIfAlreadyAdded -> {
logTask(newTask, "Conflict: wait until the current task finishes")
logTask(currentTask, "Conflict: the current task")
// TODO: we need to call addTaskDependency for all other tasks with this id or probably create a list to store all such dependant tasks
newTask.addTaskDependency(currentTask)
newTask
}
Task.LoadPolicy.CompleteWhenAlreadyAddedCompletes -> {
logTask(newTask, "Conflict: this task will complete with the current task")
logTask(currentTask, "Conflict: the current task")
connectTaskCompletions(newTask, currentTask)
newTask
}
Task.LoadPolicy.CancelPreviouslyAdded -> {
logTask(currentTask, "Conflict: this current task is cancelled")
logTask(newTask, "Conflict: the new task")
cancelTaskOnThread(currentTask, null)
newTask
}
Task.LoadPolicy.SkipIfAlreadyAdded -> {
logTask(newTask, "Conflict: this task was skipped as there is another task already")
logTask(currentTask, "Conflict: another task")
cancelTaskOnThread(newTask, null)
currentTask
}
}
}
// completes aTask when toTask completes with setting taskResult
// syncs progress state too
@WorkerThread
private fun connectTaskCompletions(newTask: Task, currentTask: Task) {
addTaskBlockedDependency(newTask, currentTask)
currentTask.addTaskProgressListener(ProgressListener { _, progressInfo ->
progressInfo?.let {
newTask as TaskBase
newTask.private.triggerProgressListeners(progressInfo)
}
})
currentTask.addTaskStatusListener(object : Task.StatusListener {
override fun onTaskStatusChanged(task: Task, oldStatus: Task.Status, newStatus: Task.Status) {
if (task.isFinished()) {
currentTask.removeTaskStatusListener(this)
if (task.taskStatus != Task.Status.Cancelled) {
newTask as TaskBase
newTask.private.taskResult = currentTask.taskResult
handleTaskFinishOnThread(newTask, false)
} else {
setTaskStatus(newTask, Task.Status.Waiting)
}
}
}
})
}
@WorkerThread
private fun addTaskBlockedDependency(newTask: Task, currentTask: Task) {
setTaskStatus(newTask, Task.Status.Blocked)
newTask.addTaskDependency(currentTask)
}
private fun setTaskStatus(task: Task, status: Task.Status) {
val oldStatus = task.taskStatus
task as TaskBase
task.private.taskStatus = status
threadRunner.launch {
triggerOnTaskStatusChangedOnThread(task, oldStatus)
}
}
@WorkerThread
private fun checkTasksToRunOnThread() {
threadRunner.checkThread()
threadRunner.launchSuspend {
if (taskManagerCoordinator.canAddMoreTasks()) {
val task = takeTaskToRunOnThread()
if (task != null) {
logTask(task, "Have taken task")
startTaskOnThread(task)
}
}
}
}
@WorkerThread
private fun takeTaskToRunOnThread(): Task? {
threadRunner.checkThread()
var topTaskProvider: TaskProvider? = null
var topPriorityTask: Task? = null
var topPriority = -1
for (provider in _taskProviders) {
val t = provider.getTopTask()
if (t != null && t.taskPriority > topPriority) {
topPriorityTask = t
topPriority = t.taskPriority
topTaskProvider = provider
}
}
return if (topTaskProvider != null && topPriorityTask != null) {
topTaskProvider.takeTopTask()
} else {
null
}
}
@WorkerThread
private suspend fun startTaskOnThread(task: Task) {
if (task !is TaskBase) { assert(false); return }
threadRunner.checkThread()
Assert.assertTrue(task.isReadyToStart())
logTask(task, "Task started")
setTaskStatus(task, Task.Status.Started)
task.private.setTaskStartDate(Date())
addLoadingTaskOnThread(task)
val job = SupervisorJob()
taskToJobMap[task] = job
var isCancelled = false
withContext(taskScope.coroutineContext + job) {
try {
task.startTask()
} catch (e: Throwable) {
isCancelled = job.isCancelled
}
}
logTask(task, "Task onCompleted" + if (isCancelled) " (Cancelled)" else "")
taskToJobMap.remove(task)
if (!isCancelled) {
handleTaskFinishOnThread(task, false)
}
}
@WorkerThread
private fun addLoadingTaskOnThread(task: Task) {
threadRunner.checkThread()
loadingTasks.addTask(task)
Log.d(TAG, "loading task count " + loadingTasks.getTaskCount())
}
@WorkerThread
private fun handleTaskFinishOnThread(task: Task, isCancelled: Boolean) {
if (task !is TaskBase) { assert(false); return }
threadRunner.checkThread()
val status = if (isCancelled) Task.Status.Cancelled else Task.Status.Completed
if (isCancelled) {
task.private.taskError = CancelError()
}
// the task will be removed from the provider automatically
logTask(task, "finished")
setTaskStatus(task, status)
task.private.clearAllListeners()
// TODO: use callback scope
task.finishCallback?.let { finishCallback ->
HandlerTools.runOnHandlerThread(callbackHandler) {
finishCallback.onCompleted(isCancelled)
}
}
//TODO: for another status like cancelled new task won't be started
//but we cant't just call checkTasksToRunOnThread because of Task.LoadPolicy.CancelAdded
//because we want to have new task already in waiting queue but now it isn't
if (task.taskStatus == Task.Status.Completed) {
checkTasksToRunOnThread()
}
}
@WorkerThread
private fun cancelTaskOnThread(task: Task, info: Any?) {
if (task !is TaskBase) { assert(false); return }
threadRunner.checkThread()
if (!task.private.needCancelTask && !task.isFinished()) {
val st = task.taskStatus
task.private.cancelTask(info)
val canBeCancelledImmediately = task.private.canBeCancelledImmediately()
if (task.isReadyToStart()) {
handleTaskFinishOnThread(task, true)
logTask(task, "Cancelled")
} else if (canBeCancelledImmediately) {
if (st == Task.Status.Started) {
if (canBeCancelledImmediately) {
handleTaskFinishOnThread(task, true)
logTask(task, "Immediately Cancelled")
taskToJobMap[task]?.cancel()
} // else wait until the task handles needCancelTask
} // else ignore, the callback is already called
}
// TODO: support taskToJobMap[task]?.cancel() call in else block here
// TODO: as we support coroutines now we can do that
// TODO: but it seems we need to call job.join to wait until a task coroutine catches cancellation
}
}
/// Helpers
private fun logTask(task: Task, prefix: String) {
task.log(TAG, prefix)
}
}
| taskmanager/src/main/java/com/example/alexeyglushkov/taskmanager/SimpleTaskManager.kt | 4003927390 |
/*
* Copyright 2021 Brackeys IDE contributors.
*
* 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.brackeys.ui.language.c.parser
import com.brackeys.ui.language.base.exception.ParseException
import com.brackeys.ui.language.base.model.ParseResult
import com.brackeys.ui.language.base.parser.LanguageParser
class CParser private constructor() : LanguageParser {
companion object {
private var cParser: CParser? = null
fun getInstance(): CParser {
return cParser ?: CParser().also {
cParser = it
}
}
}
override fun execute(name: String, source: String): ParseResult {
// TODO Implement parser
val parseException = ParseException("Unable to parse unsupported language", 0, 0)
return ParseResult(parseException)
}
} | languages/language-c/src/main/kotlin/com/brackeys/ui/language/c/parser/CParser.kt | 1129388704 |
package com.rickshory.vegnab.ui
import android.content.Context
import androidx.fragment.app.Fragment
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.rickshory.vegnab.R
import com.rickshory.vegnab.VisitsListOpts
import com.rickshory.vegnab.adapters.VisitsListAdapter
import com.rickshory.vegnab.viewmodels.VNRoomViewModel
import kotlinx.android.synthetic.main.fragment_visits.*
import org.koin.dsl.module.applicationContext
/**
* A simple [Fragment] subclass.
* Activities that contain this fragment must implement the
* [FragmentVisitsList.VisitsListInterface] interface
* to handle interaction events.
* Use the [FragmentVisitsList.newInstance] factory method to
* create an instance of this fragment.
*/
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_VIS_LIST_OPTS = "visListOpts"
private lateinit var vnRoomViewModel: VNRoomViewModel
private lateinit var vlRecycView: RecyclerView
private lateinit var viewManager: RecyclerView.LayoutManager
class FragmentVisitsList : Fragment() {
private lateinit var vlAdapter: RecyclerView.Adapter<*>
private val TAG = this::class.java.simpleName
private var visitsListOpts: VisitsListOpts? = null
// private var param2: String? = null
private var listener: VisitsListInterface? = null
override fun onCreate(savedInstanceState: Bundle?) {
Log.d(TAG, "onCreate: starts")
super.onCreate(savedInstanceState)
visitsListOpts = arguments?.getParcelable(ARG_VIS_LIST_OPTS)
// arguments?.let {
// visit = it.getString(ARG_VISIT)
// param2 = it.getString(ARG_PARAM2)
// }
vnRoomViewModel = activity?.let {
ViewModelProviders.of(this).get(VNRoomViewModel::class.java)
} ?: throw Exception("Invalid Activity")
vnRoomViewModel.allVis.observe(this, Observer {visits_list ->
// update the cached copy of visits in the adapter
visits_list?.let{{vlAdapter.setVisits(it)}}
}) //left?.let { node -> queue.add(node) }
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
Log.d(TAG, "onCreateView: starts")
// Inflate the layout for this fragment
val fragView = inflater.inflate(R.layout.fragment_visits, container, false)
vlRecycView = fragView.findViewById<RecyclerView>(R.id.visits_list)
return fragView
}
// // TODO: Rename method, update argument and hook method into UI event
// fun onButtonPressed(uri: Uri) {
// listener?.onGoClicked(uri)
// }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
Log.d(TAG, "onAttach: starts")
super.onViewCreated(view, savedInstanceState)
vlRecycView.adapter = vlAdapter
vlRecycView.layoutManager = LinearLayoutManager(context)
}
override fun onAttach(context: Context) {
Log.d(TAG, "onAttach: starts")
super.onAttach(context)
vlAdapter = VisitsListAdapter()
if (context is VisitsListInterface) {
listener = context
} else {
throw RuntimeException(context.toString() + " must implement VisitsListInterface")
}
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
// back button is up arrow
if (listener is AppCompatActivity) {
val actionbar = (listener as AppCompatActivity?)?.supportActionBar
actionbar?.setDisplayHomeAsUpEnabled(true)
}
fab_new_visit.setOnClickListener { view ->
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show()
Log.d(TAG, "fab_new_visit action: start")
listener?.visitsListOnGoClicked()
Log.d(TAG, "fab_new_visit action: exit")
}
vlAdapter = VisitsListAdapter()
// vlAdapter.setVisits()
vlRecycView.adapter = vlAdapter
}
override fun onDetach() {
Log.d(TAG, "onDetach: starts")
super.onDetach()
listener = null
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
*
*
* See the Android Training lesson [Communicating with Other Fragments]
* (http://developer.android.com/training/basics/fragments/communicating.html)
* for more information.
*/
interface VisitsListInterface {
// TODO: Update argument type and name
// fun onGoClicked(uri: Uri)
fun visitsListOnGoClicked()
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param visit The visit to edit, or null to add a new visit
* @return A new instance of fragment FragmentVisitAddEdit.
*/
@JvmStatic
fun newInstance(visitsListOpts: VisitsListOpts?) =
FragmentVisitsList().apply {
arguments = Bundle().apply {
putParcelable(ARG_VIS_LIST_OPTS, visitsListOpts)
// putString(ARG_PARAM2, param2)
}
}
}
} | app/src/main/java/com/rickshory/vegnab/ui/FragmentVisitsList.kt | 1246793867 |
package io.gitlab.arturbosch.detekt.rules.naming
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.config
import io.gitlab.arturbosch.detekt.api.internal.Configuration
import io.gitlab.arturbosch.detekt.rules.identifierName
import org.jetbrains.kotlin.psi.KtNamedFunction
/**
* Reports when very long function names are used.
*/
class FunctionMaxLength(config: Config = Config.empty) : Rule(config) {
override val issue = Issue(
javaClass.simpleName,
Severity.Style,
"Function names should not be longer than the maximum set in the project configuration.",
debt = Debt.FIVE_MINS
)
@Configuration("maximum name length")
private val maximumFunctionNameLength: Int by config(30)
override fun visitNamedFunction(function: KtNamedFunction) {
if (function.identifierName().length > maximumFunctionNameLength) {
report(
CodeSmell(
issue,
Entity.atName(function),
message = "Function names should be at most $maximumFunctionNameLength characters long."
)
)
}
}
companion object {
const val MAXIMUM_FUNCTION_NAME_LENGTH = "maximumFunctionNameLength"
}
}
| detekt-rules-naming/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/naming/FunctionMaxLength.kt | 812173578 |
package io.gitlab.arturbosch.detekt.core.config
import io.github.detekt.tooling.api.spec.ConfigSpec
import io.github.detekt.tooling.api.spec.ProcessingSpec
import io.gitlab.arturbosch.detekt.api.Config
import java.net.URI
import java.net.URL
import java.nio.file.FileSystemNotFoundException
import java.nio.file.FileSystems
import java.nio.file.Path
internal fun ProcessingSpec.loadConfiguration(): Config = with(configSpec) {
var declaredConfig: Config? = when {
configPaths.isNotEmpty() -> parsePathConfig(configPaths)
resources.isNotEmpty() -> parseResourceConfig(resources)
else -> null
}
if (useDefaultConfig) {
declaredConfig = if (declaredConfig == null) {
DefaultConfig.newInstance()
} else {
CompositeConfig(declaredConfig, DefaultConfig.newInstance())
}
}
return declaredConfig ?: DefaultConfig.newInstance()
}
private fun parseResourceConfig(urls: Collection<URL>): Config =
if (urls.size == 1) {
YamlConfig.loadResource(urls.first())
} else {
urls.asSequence()
.map { YamlConfig.loadResource(it) }
.reduce { composite, config -> CompositeConfig(config, composite) }
}
private fun parsePathConfig(paths: Collection<Path>): Config =
if (paths.size == 1) {
YamlConfig.load(paths.first())
} else {
paths.asSequence()
.map { YamlConfig.load(it) }
.reduce { composite, config -> CompositeConfig(config, composite) }
}
internal fun ConfigSpec.extractUris(): Collection<URI> {
fun initFileSystem(uri: URI) {
runCatching {
@Suppress("SwallowedException") // Create file system inferred from URI if it does not exist.
try {
FileSystems.getFileSystem(uri)
} catch (e: FileSystemNotFoundException) {
FileSystems.newFileSystem(uri, mapOf("create" to "true"))
}
}
}
val pathUris = configPaths.map(Path::toUri)
val resourceUris = resources.map(URL::toURI)
resourceUris.forEach(::initFileSystem)
return resourceUris + pathUris
}
| detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/config/Configurations.kt | 2685769327 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.