content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.build.output
import com.intellij.build.FilePosition
import com.intellij.build.events.BuildEvent
import com.intellij.build.events.BuildEventsNls
import com.intellij.build.events.MessageEvent
import com.intellij.build.events.impl.FileMessageEventImpl
import com.intellij.build.events.impl.MessageEventImpl
import com.intellij.lang.LangBundle
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.annotations.Contract
import org.jetbrains.annotations.NonNls
import java.io.File
import java.net.URI
import java.util.function.Consumer
import java.util.regex.Matcher
import java.util.regex.Pattern
import kotlin.io.path.toPath
/**
* Parses kotlinc's output.
*/
class KotlincOutputParser : BuildOutputParser {
companion object {
private val COMPILER_MESSAGES_GROUP: @BuildEventsNls.Title String
@BuildEventsNls.Title
get() = LangBundle.message("build.event.title.kotlin.compiler")
private val WINDOWS_PATH = "^\\s*.:(/|\\\\)".toRegex()
private val WINDOWS_URI = "^\\s*file:/+.:(/|\\\\)".toRegex()
private val UNIX_URI = "^\\s*file:/".toRegex()
fun extractPath(line: String): String? {
if (!line.contains(":")) return null
val systemPrefixLen = listOf(WINDOWS_PATH, WINDOWS_URI, UNIX_URI).firstNotNullOfOrNull {
it.find(line)?.groups?.last()?.range?.endInclusive
} ?: 0
val colonIndex = line.indexOf(':', systemPrefixLen)
if (colonIndex < 0) return null
return line.substring(0, colonIndex)
}
}
override fun parse(line: String, reader: BuildOutputInstantReader, consumer: Consumer<in BuildEvent>): Boolean {
val colonIndex1 = line.colon()
val severity = if (colonIndex1 >= 0) line.substringBeforeAndTrim(colonIndex1) else return false
if (!severity.startsWithSeverityPrefix()) return false
val lineWoSeverity = line.substringAfterAndTrim(colonIndex1)
var path = extractPath(lineWoSeverity) ?: return false
val file = if (path.startsWith("file:")) {
try {
URI(path).toPath().toFile()
} catch (_: Exception){
File(path)
}
} else {
File(path)
}
val fileExtension = file.extension.toLowerCase()
if (!file.isFile || (fileExtension != "kt" && fileExtension != "kts" && fileExtension != "java")) { //NON-NLS
@NlsSafe
val combinedMessage = lineWoSeverity.amendNextLinesIfNeeded(reader)
return addMessage(createMessage(reader.parentEventId, getMessageKind(severity), lineWoSeverity, combinedMessage), consumer)
}
val lineWoPath = lineWoSeverity.substringAfterAndTrim(path.length)
var lineWoPositionIndex = -1
var matcher: Matcher? = null
if (lineWoPath.startsWith('(')) {
val colonIndex3 = lineWoPath.colon()
if (colonIndex3 >= 0) {
lineWoPositionIndex = colonIndex3
}
if (lineWoPositionIndex >= 0) {
val position = lineWoPath.substringBeforeAndTrim(lineWoPositionIndex)
matcher = KOTLIN_POSITION_PATTERN.matcher(position).takeIf { it.matches() } ?: JAVAC_POSITION_PATTERN.matcher(position)
}
} else if (URI_POSITION_PATTERN.toRegex().find(lineWoPath) != null) {
val parts = URI_POSITION_PATTERN.toRegex().find(lineWoPath)!!
println(parts)
val position = parts.groupValues.first()
lineWoPositionIndex = position.length
matcher = URI_POSITION_PATTERN.matcher(position)
} else {
val colonIndex4 = lineWoPath.colon(1)
if (colonIndex4 >= 0) {
lineWoPositionIndex = colonIndex4
}
else {
lineWoPositionIndex = lineWoPath.colon()
}
if (lineWoPositionIndex >= 0) {
val position = lineWoPath.substringBeforeAndTrim(colonIndex4)
matcher = LINE_COLON_COLUMN_POSITION_PATTERN.matcher(position).takeIf { it.matches() } ?: JAVAC_POSITION_PATTERN.matcher(position)
}
}
if (lineWoPositionIndex >= 0) {
val relatedNextLines = "".amendNextLinesIfNeeded(reader)
val message = lineWoPath.substringAfterAndTrim(lineWoPositionIndex) + relatedNextLines
val details = line + relatedNextLines
if (matcher != null && matcher.matches()) {
val lineNumber = matcher.group(1)
val symbolNumber = if (matcher.groupCount() >= 2) matcher.group(2) else "1"
if (lineNumber != null) {
val symbolNumberText = symbolNumber.toInt()
return addMessage(createMessageWithLocation(
reader.parentEventId, getMessageKind(severity), message, file, lineNumber.toInt(), symbolNumberText, details), consumer)
}
}
return addMessage(createMessage(reader.parentEventId, getMessageKind(severity), message, details), consumer)
}
else {
@NlsSafe
val combinedMessage = lineWoSeverity.amendNextLinesIfNeeded(reader)
return addMessage(createMessage(reader.parentEventId, getMessageKind(severity), lineWoSeverity, combinedMessage), consumer)
}
}
private val COLON = ":"
private val KOTLIN_POSITION_PATTERN = Pattern.compile("\\(([0-9]*), ([0-9]*)\\)")
private val URI_POSITION_PATTERN = Pattern.compile("^([0-9]*):([0-9]*)")
private val JAVAC_POSITION_PATTERN = Pattern.compile("([0-9]+)")
private val LINE_COLON_COLUMN_POSITION_PATTERN = Pattern.compile("([0-9]*):([0-9]*)")
private fun String.amendNextLinesIfNeeded(reader: BuildOutputInstantReader): String {
var nextLine = reader.readLine()
val builder = StringBuilder(this)
while (nextLine != null) {
if (nextLine.isNextMessage()) {
reader.pushBack()
break
}
else {
builder.append("\n").append(nextLine)
nextLine = reader.readLine()
}
}
return builder.toString()
}
private fun String.isNextMessage(): Boolean {
val colonIndex1 = indexOf(COLON)
return colonIndex1 == 0
|| (colonIndex1 >= 0 && substring(0, colonIndex1).startsWithSeverityPrefix()) // Next Kotlin message
|| StringUtil.startsWith(this, "Note: ") // Next javac info message candidate //NON-NLS
|| StringUtil.startsWith(this, "> Task :") // Next gradle message candidate //NON-NLS
|| StringUtil.containsIgnoreCase(this, "FAILURE") //NON-NLS
|| StringUtil.containsIgnoreCase(this, "FAILED") //NON-NLS
}
private fun String.startsWithSeverityPrefix() = getMessageKind(this) != MessageEvent.Kind.SIMPLE
@NonNls
private fun getMessageKind(kind: @NonNls String) = when (kind) {
"e" -> MessageEvent.Kind.ERROR
"w" -> MessageEvent.Kind.WARNING
"i" -> MessageEvent.Kind.INFO
"v" -> MessageEvent.Kind.SIMPLE
else -> MessageEvent.Kind.SIMPLE
}
@Contract(pure = true)
private fun String.substringAfterAndTrim(index: Int) = substring(index + 1).trim()
@Contract(pure = true)
private fun String.substringBeforeAndTrim(index: Int) = substring(0, index).trim()
private fun String.colon() = indexOf(COLON)
private fun String.colon(skip: Int): Int {
var index = -1
repeat(skip + 1) {
index = indexOf(COLON, index + 1)
if (index < 0) return index
}
return index
}
private val KAPT_ERROR_WHILE_ANNOTATION_PROCESSING_MARKER_TEXT
get() =
// KaptError::class.java.canonicalName + ": " + KaptError.Kind.ERROR_RAISED.message
"org.jetbrains.kotlin.kapt3.diagnostic.KaptError" + ": " + LangBundle.message("kapterror.error.while.annotation.processing")
private fun isKaptErrorWhileAnnotationProcessing(message: MessageEvent): Boolean {
if (message.kind != MessageEvent.Kind.ERROR) return false
val messageText = message.message
return messageText.startsWith(IllegalStateException::class.java.name)
&& messageText.contains(KAPT_ERROR_WHILE_ANNOTATION_PROCESSING_MARKER_TEXT)
}
private fun addMessage(message: MessageEvent, consumer: Consumer<in MessageEvent>): Boolean {
// Ignore KaptError.ERROR_RAISED message from kapt. We already processed all errors from annotation processing
if (isKaptErrorWhileAnnotationProcessing(message)) return true
consumer.accept(message)
return true
}
private fun createMessage(parentId: Any,
messageKind: MessageEvent.Kind,
text: @BuildEventsNls.Message String,
detail: @BuildEventsNls.Description String): MessageEvent {
return MessageEventImpl(parentId, messageKind, COMPILER_MESSAGES_GROUP, text.trim(), detail) //NON-NLS
}
private fun createMessageWithLocation(
parentId: Any,
messageKind: MessageEvent.Kind,
text: @BuildEventsNls.Message String,
file: File,
lineNumber: Int,
columnIndex: Int,
detail: @BuildEventsNls.Description String
): FileMessageEventImpl {
return FileMessageEventImpl(parentId, messageKind, COMPILER_MESSAGES_GROUP, text.trim(), detail, //NON-NLS
FilePosition(file, lineNumber - 1, columnIndex - 1))
}
} | platform/lang-impl/src/com/intellij/build/output/KotlincOutputParser.kt | 3313981197 |
fun test() {
var a = 1
a as
<caret>
}
// SET_TRUE: ALIGN_MULTILINE_BINARY_OPERATION
// WITHOUT_CUSTOM_LINE_INDENT_PROVIDER | plugins/kotlin/idea/tests/testData/indentationOnNewline/emptyParenthesisInBinaryExpression/BinaryWithTypeExpressions.after.kt | 1977501265 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.fileActions.utils
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.ProcessOutput
import com.intellij.execution.util.ExecUtil
import com.intellij.ide.actions.OpenFileAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.impl.VirtualFileImpl
import com.intellij.psi.PsiManager
import com.intellij.refactoring.RefactoringBundle
import com.intellij.ui.TextFieldWithHistoryWithBrowseButton
import com.intellij.ui.layout.*
import com.intellij.util.ModalityUiUtil
import org.intellij.plugins.markdown.MarkdownBundle
import org.intellij.plugins.markdown.MarkdownNotifier
import org.intellij.plugins.markdown.fileActions.export.MarkdownDocxExportProvider
import org.intellij.plugins.markdown.lang.MarkdownFileType
import org.intellij.plugins.markdown.settings.pandoc.PandocApplicationSettings
import org.intellij.plugins.markdown.ui.actions.MarkdownActionUtil
import org.intellij.plugins.markdown.ui.preview.MarkdownPreviewFileEditor
import org.intellij.plugins.markdown.ui.preview.jcef.JCEFHtmlPanelProvider
import java.io.File
/**
* Utilities used mainly for import/export from markdown.
*/
object MarkdownImportExportUtils {
/**
* Returns the preview of markdown file or null if the preview editor or project is null.
*/
fun getPreviewEditor(event: AnActionEvent, fileType: String): MarkdownPreviewFileEditor? {
val project = event.project ?: return null
val previewEditor = MarkdownActionUtil.findMarkdownPreviewEditor(event)
if (previewEditor == null) {
MarkdownNotifier.notifyIfConvertFailed(
project,
MarkdownBundle.message("markdown.export.validation.failure.msg", fileType)
)
return null
}
return previewEditor
}
/**
* recursively refreshes the specified directory in the project tree,
* if the directory is not specified, the base directory of the project is refreshed.
*/
fun refreshProjectDirectory(project: Project, refreshPath: String) {
ModalityUiUtil.invokeLaterIfNeeded(
{
LocalFileSystem
.getInstance()
.refreshAndFindFileByIoFile(File(refreshPath))
?.refresh(true, true)
},
ModalityState.defaultModalityState()
)
}
/**
* suggests a minimally conflicting name when importing a file,
* checking for the existence of both docx and markdown files.
*/
fun suggestFileNameToCreate(project: Project, fileToImport: VirtualFile, dataContext: DataContext): String {
val defaultFileName = fileToImport.nameWithoutExtension
val dirToImport = when (val selectedVirtualFile = CommonDataKeys.VIRTUAL_FILE.getData(dataContext)) {
null -> File(project.basePath!!)
is VirtualFileImpl -> File(selectedVirtualFile.parent.path)
else -> File(selectedVirtualFile.path)
}
val suggestMdFile = FileUtil.createSequentFileName(dirToImport, defaultFileName, MarkdownFileType.INSTANCE.defaultExtension)
val suggestFileName = File(suggestMdFile).nameWithoutExtension
val suggestDocxFile = FileUtil.createSequentFileName(dirToImport, suggestFileName, MarkdownDocxExportProvider.format.extension)
return FileUtil.join(dirToImport.path, suggestDocxFile)
}
/**
* converts the specified docx file using the pandoc utility,
* and also calls the copy method for it to the same directory if the conversion was successful.
*/
fun copyAndConvertToMd(project: Project,
vFileToImport: VirtualFile,
selectedFileUrl: String,
@NlsContexts.DialogTitle taskTitle: String) {
object : Task.Modal(project, taskTitle, true) {
private lateinit var createdFilePath: String
private lateinit var output: ProcessOutput
private val dirToImport = File(selectedFileUrl).parent
private val newFileName = File(selectedFileUrl).nameWithoutExtension
private val resourcesDir = PandocApplicationSettings.getInstance().state.myPathToImages ?: project.basePath!!
override fun run(indicator: ProgressIndicator) {
val filePath = FileUtil.join(dirToImport, "${newFileName}.${MarkdownFileType.INSTANCE.defaultExtension}")
val cmd = getConvertDocxToMdCommandLine(vFileToImport, resourcesDir, filePath)
output = ExecUtil.execAndGetOutput(cmd)
createdFilePath = filePath
}
override fun onCancel() {
val mdFile = File(createdFilePath)
if (mdFile.exists()) FileUtil.delete(mdFile)
}
override fun onThrowable(error: Throwable) {
MarkdownNotifier.notifyIfConvertFailed(project, "[${vFileToImport.name}] ${error.localizedMessage}")
}
override fun onSuccess() {
if (output.stderrLines.isEmpty()) {
vFileToImport.copySelectedFile(project, dirToImport, newFileName)
OpenFileAction.openFile(createdFilePath, project)
}
else {
MarkdownNotifier.notifyIfConvertFailed(project, "[${vFileToImport.name}] ${output.stderrLines.joinToString("\n")}")
}
}
}.queue()
}
/**
* Copies the selected file to the specified directory.
* If the copying failed, sends a notification to the user about it.
*/
private fun VirtualFile.copySelectedFile(project: Project, dirToImport: String, newFileName: String) {
val fileNameWithExtension = "$newFileName.${MarkdownDocxExportProvider.format.extension}"
try {
val localFS = LocalFileSystem.getInstance()
val dirToImportVF = localFS.findFileByPath(dirToImport) ?: localFS.findFileByPath(project.basePath!!)!!
runWriteAction {
val directory = PsiManager.getInstance(project).findDirectory(dirToImportVF)!!
val file = PsiManager.getInstance(project).findFile(this)!!
directory.copyFileFrom(fileNameWithExtension, file)
}
}
catch (exception: Throwable) {
MarkdownNotifier.notifyIfConvertFailed(project, "[$fileNameWithExtension] ${exception.localizedMessage}")
}
}
private const val TARGET_FORMAT_NAME = "markdown"
/**
* returns a platform-independent cmd to perform the converting of docx to markdown using pandoc.
*/
private fun getConvertDocxToMdCommandLine(file: VirtualFile, mediaSrc: String, targetFile: String) = GeneralCommandLine(
"pandoc",
"--extract-media=$mediaSrc",
file.path,
"-f",
MarkdownDocxExportProvider.format.extension,
"-t",
TARGET_FORMAT_NAME,
"-s",
"-o",
targetFile
)
/**
* Checks whether the JCEF panel, which is needed for exporting to HTML and PDF, is open in the markdown editor.
*/
fun isJCEFPanelOpen(editor: MarkdownPreviewFileEditor): Boolean {
return editor.lastPanelProviderInfo?.className == JCEFHtmlPanelProvider::class.java.name
}
/**
* Checks the directory selection field and returns an error if it is not filled in.
*/
fun ValidationInfoBuilder.validateTargetDir(field: TextFieldWithHistoryWithBrowseButton): ValidationInfo? {
return when {
field.childComponent.text.isNullOrEmpty() -> error(RefactoringBundle.message("no.target.directory.specified"))
else -> null
}
}
fun notifyAndRefreshIfExportSuccess(file: File, project: Project) {
MarkdownNotifier.notifyOfSuccessfulExport(
project,
MarkdownBundle.message("markdown.export.success.msg", file.name)
)
val dirToExport = file.parent
refreshProjectDirectory(project, dirToExport)
}
}
| plugins/markdown/src/org/intellij/plugins/markdown/fileActions/utils/MarkdownImportExportUtils.kt | 1759516420 |
/*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
@file:Suppress("UNUSED_VARIABLE")
package kotlinx.cli
import kotlinx.cli.ArgParser
import kotlinx.cli.ArgType
import kotlin.test.*
class ArgumentsTests {
@Test
fun testPositionalArguments() {
val argParser = ArgParser("testParser")
val debugMode by argParser.option(ArgType.Boolean, "debug", "d", "Debug mode")
val input by argParser.argument(ArgType.String, "input", "Input file")
val output by argParser.argument(ArgType.String, "output", "Output file")
argParser.parse(arrayOf("-d", "input.txt", "out.txt"))
assertEquals(true, debugMode)
assertEquals("out.txt", output)
assertEquals("input.txt", input)
}
@Test
fun testArgumetsWithAnyNumberOfValues() {
val argParser = ArgParser("testParser")
val output by argParser.argument(ArgType.String, "output", "Output file")
val inputs by argParser.argument(ArgType.String, description = "Input files").vararg()
argParser.parse(arrayOf("out.txt", "input1.txt", "input2.txt", "input3.txt",
"input4.txt"))
assertEquals("out.txt", output)
assertEquals(4, inputs.size)
}
@Test
fun testArgumetsWithSeveralValues() {
val argParser = ArgParser("testParser")
val addendums by argParser.argument(ArgType.Int, "addendums", description = "Addendums").multiple(2)
val output by argParser.argument(ArgType.String, "output", "Output file")
val debugMode by argParser.option(ArgType.Boolean, "debug", "d", "Debug mode")
argParser.parse(arrayOf("2", "-d", "3", "out.txt"))
assertEquals("out.txt", output)
val (first, second) = addendums
assertEquals(2, addendums.size)
assertEquals(2, first)
assertEquals(3, second)
}
@Test
fun testSkippingExtraArguments() {
val argParser = ArgParser("testParser", skipExtraArguments = true)
val addendums by argParser.argument(ArgType.Int, "addendums", description = "Addendums").multiple(2)
val output by argParser.argument(ArgType.String, "output", "Output file")
val debugMode by argParser.option(ArgType.Boolean, "debug", "d", "Debug mode")
argParser.parse(arrayOf("2", "-d", "3", "out.txt", "something", "else", "in", "string"))
assertEquals("out.txt", output)
}
}
| endorsedLibraries/kotlinx.cli/src/tests/ArgumentsTests.kt | 597747649 |
package com.github.kerubistan.kerub.model
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class VersionTest {
private fun params(): List<Pair<Version, String>> {
return listOf(
Pair(Version("1", "2", "3"), "1.2.3"),
Pair(Version("0", "8", "13"), "0.8-13.fc20.x86_64"),
Pair(Version("1", "0", "19"), "1.0.19-1.fc20.x86_64"),
Pair(Version("1", "2", null), "1.2"),
Pair(Version("1", null, null), "1")
)
}
@Test
fun compare() {
for (pair in params()) {
val parsed = Version.fromVersionString(pair.second)
assertEquals(pair.first.major, parsed.major)
assertEquals(pair.first.minor, parsed.minor)
assertEquals(pair.first.build, parsed.build)
}
}
@Test
fun testToString() {
for(pair in params()) {
assertNotNull(pair.first.toString())
}
assertEquals("1.0", Version("1","0",null).toString())
assertEquals("1", Version("1",null,null).toString())
assertEquals("1.0.0", Version("1","0","0").toString())
}
} | src/test/kotlin/com/github/kerubistan/kerub/model/VersionTest.kt | 1338010959 |
fun usage(a: JAnn) {
a.first
} | plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/members/javaAnnotationWithSeveralParameters/Usage.kt | 368220616 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.refactoring.rename.impl
import com.intellij.model.Pointer
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiFile
import com.intellij.psi.SmartPointerManager
import com.intellij.psi.SmartPsiFileRange
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.rename.api.PsiRenameUsage
import com.intellij.refactoring.rename.api.RenameConflict
import com.intellij.refactoring.rename.api.RenameUsage
/**
* If [RenameUsage] is not defined for a reference,
* then the platform treats the reference as a non-renameable [RenameUsage]
* by creating an instance of this class.
*/
internal class DefaultReferenceUsage(
override val file: PsiFile,
override val range: TextRange
) : PsiRenameUsage {
override val declaration: Boolean get() = false
override fun conflicts(newName: String): List<RenameConflict> {
return listOf(RenameConflict.fromText(RefactoringBundle.message("rename.usage.unmodifiable")))
}
override fun createPointer(): Pointer<out DefaultReferenceUsage> = DefaultReferenceUsagePointer(file, range)
private class DefaultReferenceUsagePointer(file: PsiFile, range: TextRange) : Pointer<DefaultReferenceUsage> {
private val rangePointer: SmartPsiFileRange = SmartPointerManager.getInstance(file.project).createSmartPsiFileRangePointer(file, range)
override fun dereference(): DefaultReferenceUsage? {
val file: PsiFile = rangePointer.element ?: return null
val range: TextRange = rangePointer.range?.let(TextRange::create) ?: return null
return DefaultReferenceUsage(file, range)
}
}
}
| platform/lang-impl/src/com/intellij/refactoring/rename/impl/DefaultReferenceUsage.kt | 4225218416 |
package com.heed.justquotes.data.remote.quotesapis
/**
* @author Howard.
* * See: <a href>https://en.wikiquote.org/w/api.php</a>
* * and <a href>http://codepen.io/mikelduffy/pen/EPdYMp</a>
*/
interface WikiQuoteService
| app/src/main/java/com/heed/justquotes/data/remote/quotesapis/WikiQuoteService.kt | 3772307648 |
class <caret>A {
val x: Int = 1
} | plugins/kotlin/idea/tests/testData/refactoring/pullUp/k2k/noSuperClass.kt | 1674079487 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.gradleJava.configuration
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.*
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.roots.DependencyScope
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.io.FileUtil
import org.gradle.api.artifacts.Dependency
import org.gradle.internal.impldep.org.apache.commons.lang.math.RandomUtils
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.kotlin.idea.gradle.configuration.KotlinGradleProjectData
import org.jetbrains.kotlin.idea.gradle.configuration.KotlinGradleSourceSetData
import org.jetbrains.kotlin.idea.gradle.configuration.kotlinGradleSourceSetDataNodes
import org.jetbrains.kotlin.idea.gradle.statistics.KotlinGradleFUSLogger
import org.jetbrains.kotlin.idea.gradleJava.inspections.getDependencyModules
import org.jetbrains.kotlin.idea.gradleTooling.*
import org.jetbrains.kotlin.idea.projectModel.KotlinTarget
import org.jetbrains.kotlin.idea.statistics.KotlinIDEGradleActionsFUSCollector
import org.jetbrains.kotlin.idea.util.NotNullableCopyableDataNodeUserDataProperty
import org.jetbrains.kotlin.idea.util.PsiPrecedences
import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty
import org.jetbrains.plugins.gradle.model.ExternalProjectDependency
import org.jetbrains.plugins.gradle.model.ExternalSourceSet
import org.jetbrains.plugins.gradle.model.FileCollectionDependency
import org.jetbrains.plugins.gradle.model.ProjectImportModelProvider
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension
import org.jetbrains.plugins.gradle.service.project.GradleProjectResolver
import org.jetbrains.plugins.gradle.service.project.GradleProjectResolverUtil
import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext
import java.io.File
import java.util.*
val DataNode<out ModuleData>.kotlinGradleProjectDataNodeOrNull: DataNode<KotlinGradleProjectData>?
get() = when (this.data) {
is GradleSourceSetData -> ExternalSystemApiUtil.findParent(this, ProjectKeys.MODULE)?.kotlinGradleProjectDataNodeOrNull
else -> ExternalSystemApiUtil.find(this, KotlinGradleProjectData.KEY)
}
val DataNode<out ModuleData>.kotlinGradleProjectDataNodeOrFail: DataNode<KotlinGradleProjectData>
get() = kotlinGradleProjectDataNodeOrNull
?: error("Failed to find KotlinGradleProjectData node for $this")
val DataNode<out ModuleData>.kotlinGradleProjectDataOrNull: KotlinGradleProjectData?
get() = when (this.data) {
is GradleSourceSetData -> ExternalSystemApiUtil.findParent(this, ProjectKeys.MODULE)?.kotlinGradleProjectDataOrNull
else -> kotlinGradleProjectDataNodeOrNull?.data
}
val DataNode<out ModuleData>.kotlinGradleProjectDataOrFail: KotlinGradleProjectData
get() = kotlinGradleProjectDataOrNull
?: error("Failed to find KotlinGradleProjectData for $this")
@Deprecated("Use KotlinGradleSourceSetData#isResolved instead", level = DeprecationLevel.ERROR)
var DataNode<out ModuleData>.isResolved: Boolean
get() = kotlinGradleProjectDataOrFail.isResolved
set(value) {
kotlinGradleProjectDataOrFail.isResolved = value
}
@Deprecated("Use KotlinGradleSourceSetData#hasKotlinPlugin instead", level = DeprecationLevel.ERROR)
var DataNode<out ModuleData>.hasKotlinPlugin: Boolean
get() = kotlinGradleProjectDataOrFail.hasKotlinPlugin
set(value) {
kotlinGradleProjectDataOrFail.hasKotlinPlugin = value
}
@Suppress("TYPEALIAS_EXPANSION_DEPRECATION")
@Deprecated("Use KotlinGradleSourceSetData#compilerArgumentsBySourceSet instead", level = DeprecationLevel.ERROR)
var DataNode<out ModuleData>.compilerArgumentsBySourceSet: CompilerArgumentsBySourceSet?
@Suppress("DEPRECATION_ERROR")
get() = compilerArgumentsBySourceSet()
set(value) = throw UnsupportedOperationException("Changing of compilerArguments is available only through GradleSourceSetData.")
@Suppress("TYPEALIAS_EXPANSION_DEPRECATION", "DEPRECATION_ERROR")
fun DataNode<out ModuleData>.compilerArgumentsBySourceSet(): CompilerArgumentsBySourceSet? =
ExternalSystemApiUtil.findAllRecursively(this, KotlinGradleSourceSetData.KEY).ifNotEmpty {
map { it.data }.filter { it.sourceSetName != null }.associate { it.sourceSetName!! to it.compilerArguments }
}
@Deprecated("Use KotlinGradleSourceSetData#additionalVisibleSourceSets instead", level = DeprecationLevel.ERROR)
var DataNode<out ModuleData>.additionalVisibleSourceSets: AdditionalVisibleSourceSetsBySourceSet
@Suppress("DEPRECATION_ERROR")
get() = ExternalSystemApiUtil.findAllRecursively(this, KotlinGradleSourceSetData.KEY)
.map { it.data }
.filter { it.sourceSetName != null }
.associate { it.sourceSetName!! to it.additionalVisibleSourceSets }
set(value) {
ExternalSystemApiUtil.findAllRecursively(this, KotlinGradleSourceSetData.KEY).filter { it.data.sourceSetName != null }.forEach {
if (value.containsKey(it.data.sourceSetName!!))
it.data.additionalVisibleSourceSets = value.getValue(it.data.sourceSetName!!)
}
}
@Deprecated("Use KotlinGradleSourceSetData#coroutines instead", level = DeprecationLevel.ERROR)
var DataNode<out ModuleData>.coroutines: String?
get() = kotlinGradleProjectDataOrFail.coroutines
set(value) {
kotlinGradleProjectDataOrFail.coroutines = value
}
@Deprecated("Use KotlinGradleSourceSetData#isHmpp instead", level = DeprecationLevel.ERROR)
var DataNode<out ModuleData>.isHmpp: Boolean
get() = kotlinGradleProjectDataOrFail.isHmpp
set(value) {
kotlinGradleProjectDataOrFail.isHmpp = value
}
@Deprecated("Use KotlinGradleSourceSetData#platformPluginId instead", level = DeprecationLevel.ERROR)
var DataNode<out ModuleData>.platformPluginId: String?
get() = kotlinGradleProjectDataOrFail.platformPluginId
set(value) {
kotlinGradleProjectDataOrFail.platformPluginId = value
}
@Deprecated("Use KotlinGradleSourceSetData#kotlinNativeHome instead", level = DeprecationLevel.ERROR)
var DataNode<out ModuleData>.kotlinNativeHome: String
get() = kotlinGradleProjectDataOrFail.kotlinNativeHome
set(value) {
kotlinGradleProjectDataOrFail.kotlinNativeHome = value
}
@Deprecated("Use KotlinGradleSourceSetData#implementedModuleNames instead", level = DeprecationLevel.ERROR)
var DataNode<out ModuleData>.implementedModuleNames: List<String>
@Suppress("DEPRECATION_ERROR")
get() = when (data) {
is GradleSourceSetData -> ExternalSystemApiUtil.find(this, KotlinGradleSourceSetData.KEY)?.data?.implementedModuleNames
?: error("Failed to find KotlinGradleSourceSetData for $this")
else -> ExternalSystemApiUtil.find(this@implementedModuleNames, KotlinGradleProjectData.KEY)?.data?.implementedModuleNames
?: error("Failed to find KotlinGradleProjectData for $this")
}
set(value) = throw UnsupportedOperationException("Changing of implementedModuleNames is available only through KotlinGradleSourceSetData.")
@Deprecated("Use KotlinGradleSourceSetData#dependenciesCache instead", level = DeprecationLevel.ERROR)
// Project is usually the same during all import, thus keeping Map Project->Dependencies makes model a bit more complicated but allows to avoid future problems
var DataNode<out ModuleData>.dependenciesCache: MutableMap<DataNode<ProjectData>, Collection<DataNode<out ModuleData>>>
get() = kotlinGradleProjectDataOrFail.dependenciesCache
set(value) = with(kotlinGradleProjectDataOrFail.dependenciesCache) {
clear()
putAll(value)
}
@Deprecated("Use KotlinGradleSourceSetData#implementedModuleNames instead", level = DeprecationLevel.ERROR)
var DataNode<out ModuleData>.pureKotlinSourceFolders: MutableCollection<String>
get() = kotlinGradleProjectDataOrFail.pureKotlinSourceFolders
set(value) = with(kotlinGradleProjectDataOrFail.pureKotlinSourceFolders) {
clear()
addAll(value)
}
class KotlinGradleProjectResolverExtension : AbstractProjectResolverExtension() {
val isAndroidProjectKey = Key.findKeyByName("IS_ANDROID_PROJECT_KEY")
private val cacheManager = KotlinCompilerArgumentsCacheMergeManager
override fun getToolingExtensionsClasses(): Set<Class<out Any>> {
return setOf(KotlinGradleModelBuilder::class.java, KotlinTarget::class.java, RandomUtils::class.java, Unit::class.java)
}
override fun getExtraProjectModelClasses(): Set<Class<out Any>> {
error("getModelProvider() is overridden instead")
}
override fun getModelProvider(): ProjectImportModelProvider {
val isAndroidPluginRequestingKotlinGradleModelKey = Key.findKeyByName("IS_ANDROID_PLUGIN_REQUESTING_KOTLIN_GRADLE_MODEL_KEY")
val isAndroidPluginRequestingKotlinGradleModel =
isAndroidPluginRequestingKotlinGradleModelKey != null && resolverCtx.getUserData(isAndroidPluginRequestingKotlinGradleModelKey) != null
return AndroidAwareGradleModelProvider(KotlinGradleModel::class.java, isAndroidPluginRequestingKotlinGradleModel)
}
override fun createModule(gradleModule: IdeaModule, projectDataNode: DataNode<ProjectData>): DataNode<ModuleData>? {
return super.createModule(gradleModule, projectDataNode)?.also {
cacheManager.mergeCache(gradleModule, resolverCtx)
initializeModuleData(gradleModule, it, projectDataNode, resolverCtx)
}
}
private fun initializeModuleData(
gradleModule: IdeaModule,
mainModuleNode: DataNode<ModuleData>,
projectDataNode: DataNode<ProjectData>,
resolverCtx: ProjectResolverContext
) {
LOG.logDebugIfEnabled("Start initialize data for Gradle module: [$gradleModule], Ide module: [$mainModuleNode], Ide project: [$projectDataNode]")
val mppModel = resolverCtx.getMppModel(gradleModule)
val project = resolverCtx.externalSystemTaskId.findProject()
if (mppModel != null) {
mppModel.targets.forEach { target ->
KotlinIDEGradleActionsFUSCollector.logImport(
project,
"MPP.${target.platform.id + (target.presetName?.let { ".$it" } ?: "")}")
}
return
}
val gradleModel = resolverCtx.getExtraProject(gradleModule, KotlinGradleModel::class.java) ?: return
if (gradleModel.hasKotlinPlugin) {
KotlinIDEGradleActionsFUSCollector.logImport(project, gradleModel.kotlinTarget ?: "unknown")
}
KotlinGradleProjectData().apply {
isResolved = true
kotlinTarget = gradleModel.kotlinTarget
hasKotlinPlugin = gradleModel.hasKotlinPlugin
coroutines = gradleModel.coroutines
platformPluginId = gradleModel.platformPluginId
pureKotlinSourceFolders.addAll(
gradleModel.kotlinTaskProperties.flatMap { it.value.pureKotlinSourceFolders ?: emptyList() }.map { it.absolutePath }
)
mainModuleNode.createChild(KotlinGradleProjectData.KEY, this)
}
if (gradleModel.hasKotlinPlugin) {
initializeGradleSourceSetsData(gradleModel, mainModuleNode)
}
}
private fun initializeGradleSourceSetsData(kotlinModel: KotlinGradleModel, mainModuleNode: DataNode<ModuleData>) {
kotlinModel.cachedCompilerArgumentsBySourceSet.forEach { (sourceSetName, cachedArgs) ->
KotlinGradleSourceSetData(sourceSetName).apply {
cachedArgsInfo = cachedArgs
additionalVisibleSourceSets = kotlinModel.additionalVisibleSourceSets.getValue(sourceSetName)
kotlinPluginVersion = kotlinModel.kotlinTaskProperties.getValue(sourceSetName).pluginVersion
mainModuleNode.kotlinGradleProjectDataNodeOrFail.createChild(KotlinGradleSourceSetData.KEY, this)
}
}
}
private fun useModulePerSourceSet(): Boolean {
// See AndroidGradleProjectResolver
if (isAndroidProjectKey != null && resolverCtx.getUserData(isAndroidProjectKey) == true) {
return false
}
return resolverCtx.isResolveModulePerSourceSet
}
private fun getDependencyByFiles(
files: Collection<File>,
outputToSourceSet: Map<String, com.intellij.openapi.util.Pair<String, ExternalSystemSourceType>>?,
sourceSetByName: Map<String, com.intellij.openapi.util.Pair<DataNode<GradleSourceSetData>, ExternalSourceSet>>?
) = files
.mapTo(HashSet()) {
val path = FileUtil.toSystemIndependentName(it.path)
val targetSourceSetId = outputToSourceSet?.get(path)?.first ?: return@mapTo null
sourceSetByName?.get(targetSourceSetId)?.first
}
.singleOrNull()
private fun DataNode<out ModuleData>.getDependencies(ideProject: DataNode<ProjectData>): Collection<DataNode<out ModuleData>> {
val cache = kotlinGradleProjectDataOrNull?.dependenciesCache ?: dependencyCacheFallback
if (cache.containsKey(ideProject)) {
return cache.getValue(ideProject)
}
val outputToSourceSet = ideProject.getUserData(GradleProjectResolver.MODULES_OUTPUTS)
val sourceSetByName = ideProject.getUserData(GradleProjectResolver.RESOLVED_SOURCE_SETS) ?: return emptySet()
val externalSourceSet = sourceSetByName[data.id]?.second ?: return emptySet()
val result = externalSourceSet.dependencies.mapNotNullTo(LinkedHashSet()) { dependency ->
when (dependency) {
is ExternalProjectDependency -> {
if (dependency.configurationName == Dependency.DEFAULT_CONFIGURATION) {
@Suppress("UNCHECKED_CAST") val targetModuleNode = ExternalSystemApiUtil.findFirstRecursively(ideProject) {
(it.data as? ModuleData)?.id == dependency.projectPath
} as DataNode<ModuleData>? ?: return@mapNotNullTo null
ExternalSystemApiUtil.findAll(targetModuleNode, GradleSourceSetData.KEY)
.firstOrNull { it.sourceSetName == "main" }
} else {
getDependencyByFiles(dependency.projectDependencyArtifacts, outputToSourceSet, sourceSetByName)
}
}
is FileCollectionDependency -> {
getDependencyByFiles(dependency.files, outputToSourceSet, sourceSetByName)
}
else -> null
}
}
cache[ideProject] = result
return result
}
private fun addTransitiveDependenciesOnImplementedModules(
gradleModule: IdeaModule,
ideModule: DataNode<ModuleData>,
ideProject: DataNode<ProjectData>
) {
val moduleNodesToProcess = if (useModulePerSourceSet()) {
ExternalSystemApiUtil.findAll(ideModule, GradleSourceSetData.KEY)
} else listOf(ideModule)
val ideaModulesByGradlePaths = gradleModule.project.modules.groupBy { it.gradleProject.path }
var dirtyDependencies = true
for (currentModuleNode in moduleNodesToProcess) {
val toProcess = ArrayDeque<DataNode<out ModuleData>>().apply { add(currentModuleNode) }
val discovered = HashSet<DataNode<out ModuleData>>().apply { add(currentModuleNode) }
while (toProcess.isNotEmpty()) {
val moduleNode = toProcess.pollLast()
val moduleNodeForGradleModel = if (useModulePerSourceSet()) {
ExternalSystemApiUtil.findParent(moduleNode, ProjectKeys.MODULE)
} else moduleNode
val ideaModule = if (moduleNodeForGradleModel != ideModule) {
moduleNodeForGradleModel?.data?.id?.let { ideaModulesByGradlePaths[it]?.firstOrNull() }
} else gradleModule
val implementsModuleIds = resolverCtx.getExtraProject(ideaModule, KotlinGradleModel::class.java)?.implements
?: emptyList()
for (implementsModuleId in implementsModuleIds) {
val targetModule = findModuleById(ideProject, gradleModule, implementsModuleId) ?: continue
if (useModulePerSourceSet()) {
val targetSourceSetsByName = ExternalSystemApiUtil
.findAll(targetModule, GradleSourceSetData.KEY)
.associateBy { it.sourceSetName }
val targetMainSourceSet = targetSourceSetsByName["main"] ?: targetModule
val targetSourceSet = targetSourceSetsByName[currentModuleNode.sourceSetName]
if (targetSourceSet != null) {
addDependency(currentModuleNode, targetSourceSet)
}
if (currentModuleNode.sourceSetName == "test" && targetMainSourceSet != targetSourceSet) {
addDependency(currentModuleNode, targetMainSourceSet)
}
} else {
dirtyDependencies = true
addDependency(currentModuleNode, targetModule)
}
}
val dependencies = if (useModulePerSourceSet()) {
moduleNode.getDependencies(ideProject)
} else {
if (dirtyDependencies) getDependencyModules(ideModule, gradleModule.project).also {
dirtyDependencies = false
} else emptyList()
}
// queue only those dependencies that haven't been discovered earlier
dependencies.filterTo(toProcess, discovered::add)
}
}
}
override fun populateModuleDependencies(
gradleModule: IdeaModule,
ideModule: DataNode<ModuleData>,
ideProject: DataNode<ProjectData>
) {
LOG.logDebugIfEnabled("Start populate module dependencies. Gradle module: [$gradleModule], Ide module: [$ideModule], Ide project: [$ideProject]")
val mppModel = resolverCtx.getMppModel(gradleModule)
if (mppModel != null) {
return super.populateModuleDependencies(gradleModule, ideModule, ideProject)
}
val gradleModel = resolverCtx.getExtraProject(gradleModule, KotlinGradleModel::class.java)
?: return super.populateModuleDependencies(gradleModule, ideModule, ideProject)
if (!useModulePerSourceSet()) {
super.populateModuleDependencies(gradleModule, ideModule, ideProject)
}
addTransitiveDependenciesOnImplementedModules(gradleModule, ideModule, ideProject)
addImplementedModuleNames(gradleModule, ideModule, ideProject, gradleModel)
if (useModulePerSourceSet()) {
super.populateModuleDependencies(gradleModule, ideModule, ideProject)
}
LOG.logDebugIfEnabled("Finish populating module dependencies. Gradle module: [$gradleModule], Ide module: [$ideModule], Ide project: [$ideProject]")
}
private fun addImplementedModuleNames(
gradleModule: IdeaModule,
dependentModule: DataNode<ModuleData>,
ideProject: DataNode<ProjectData>,
gradleModel: KotlinGradleModel
) {
val implementedModules = gradleModel.implements.mapNotNull { findModuleById(ideProject, gradleModule, it) }
val kotlinGradleProjectDataNode = dependentModule.kotlinGradleProjectDataNodeOrFail
val kotlinGradleProjectData = kotlinGradleProjectDataNode.data
val kotlinGradleSourceSetDataList = kotlinGradleProjectDataNode.kotlinGradleSourceSetDataNodes.map { it.data }
if (useModulePerSourceSet() && kotlinGradleProjectData.hasKotlinPlugin) {
val dependentSourceSets = dependentModule.getSourceSetsMap()
val implementedSourceSetMaps = implementedModules.map { it.getSourceSetsMap() }
for ((sourceSetName, _) in dependentSourceSets) {
kotlinGradleSourceSetDataList.find { it.sourceSetName == sourceSetName }?.implementedModuleNames =
implementedSourceSetMaps.mapNotNull { it[sourceSetName]?.data?.internalName }
}
} else {
kotlinGradleProjectData.implementedModuleNames = implementedModules.map { it.data.internalName }
}
}
private fun findModuleById(ideProject: DataNode<ProjectData>, gradleModule: IdeaModule, moduleId: String): DataNode<ModuleData>? {
val isCompositeProject = resolverCtx.models.ideaProject != gradleModule.project
val compositePrefix =
if (isCompositeProject && moduleId.startsWith(":")) gradleModule.project.name
else ""
val fullModuleId = compositePrefix + moduleId
@Suppress("UNCHECKED_CAST")
return ideProject.children.find { (it.data as? ModuleData)?.id == fullModuleId } as DataNode<ModuleData>?
}
override fun populateModuleContentRoots(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) {
nextResolver.populateModuleContentRoots(gradleModule, ideModule)
val moduleNamePrefix = GradleProjectResolverUtil.getModuleId(resolverCtx, gradleModule)
resolverCtx.getExtraProject(gradleModule, KotlinGradleModel::class.java)?.let { gradleModel ->
KotlinGradleFUSLogger.populateGradleUserDir(gradleModel.gradleUserHome)
val gradleSourceSets = ExternalSystemApiUtil.findAll(ideModule, GradleSourceSetData.KEY)
for (gradleSourceSetNode in gradleSourceSets) {
val propertiesForSourceSet =
gradleModel.kotlinTaskProperties.filter { (k, _) -> gradleSourceSetNode.data.id == "$moduleNamePrefix:$k" }
.toList().singleOrNull()
gradleSourceSetNode.children.forEach { dataNode ->
val data = dataNode.data as? ContentRootData
if (data != null) {
/*
Code snippet for setting in content root properties
if (propertiesForSourceSet?.second?.pureKotlinSourceFolders?.contains(File(data.rootPath)) == true) {
@Suppress("UNCHECKED_CAST")
(dataNode as DataNode<ContentRootData>).isPureKotlinSourceFolder = true
}*/
val packagePrefix = propertiesForSourceSet?.second?.packagePrefix
if (packagePrefix != null) {
ExternalSystemSourceType.values().filter { !(it.isResource || it.isGenerated) }.forEach { type ->
val paths = data.getPaths(type)
val newPaths = paths.map { ContentRootData.SourceRoot(it.path, packagePrefix) }
paths.clear()
paths.addAll(newPaths)
}
}
}
}
}
}
}
companion object {
private val LOG = Logger.getInstance(PsiPrecedences::class.java)
private fun Logger.logDebugIfEnabled(message: String) {
if (isDebugEnabled) debug(message)
}
private fun DataNode<ModuleData>.getSourceSetsMap() =
ExternalSystemApiUtil.getChildren(this, GradleSourceSetData.KEY).associateBy { it.sourceSetName }
private val DataNode<out ModuleData>.sourceSetName
get() = (data as? GradleSourceSetData)?.id?.substringAfterLast(':')
private fun addDependency(ideModule: DataNode<out ModuleData>, targetModule: DataNode<out ModuleData>) {
val moduleDependencyData = ModuleDependencyData(ideModule.data, targetModule.data)
moduleDependencyData.scope = DependencyScope.COMPILE
moduleDependencyData.isExported = false
moduleDependencyData.isProductionOnTestDependency = targetModule.sourceSetName == "test"
ideModule.createChild(ProjectKeys.MODULE_DEPENDENCY, moduleDependencyData)
}
private var DataNode<out ModuleData>.dependencyCacheFallback by NotNullableCopyableDataNodeUserDataProperty(
Key.create<MutableMap<DataNode<ProjectData>, Collection<DataNode<out ModuleData>>>>("MODULE_DEPENDENCIES_CACHE"),
hashMapOf()
)
}
}
| plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/KotlinGradleProjectResolverExtension.kt | 3919507375 |
// "Create local variable 'foo'" "true"
fun test(n: Int) {
val i = 1
test(i)
test(i + 1)
test(<caret>foo)
} | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createVariable/localVariable/positionNextToUsage.kt | 1854833351 |
package foo
internal expect abstract class ExpectBase() {
abstract fun foo(cause: Throwable?)
}
interface I {
fun foo(cause: Throwable?)
}
internal abstract class CommonAbstract : ExpectBase()
| plugins/kotlin/idea/tests/testData/multiModuleHighlighting/multiplatform/internalInheritanceToCommon/a_common_dep(stdlib)/common.kt | 3790911739 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea
import com.intellij.openapi.util.Iconable
import com.intellij.ui.icons.RowIcon
import com.intellij.util.PsiIconUtil
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import javax.swing.Icon
class KotlinIconProviderTest: KotlinLightCodeInsightFixtureTestCase() {
fun testPublicClassFile() {
createFileAndCheckIcon("Foo.kt", "class Foo", "org/jetbrains/kotlin/idea/icons/classKotlin.svg", "nodes/c_public.svg")
}
fun testFileSingleFunction() {
createFileAndCheckIcon("Foo.kt", "fun foo() = TODO()", "org/jetbrains/kotlin/idea/icons/kotlin_file.svg")
}
fun testClassAndPrivateFunction() {
val fileBody = """
class Foo
private fun bar() {}
""".trimIndent()
createFileAndCheckIcon("Foo.kt", fileBody, "org/jetbrains/kotlin/idea/icons/classKotlin.svg", "nodes/c_public.svg")
}
fun testClassAndInternalFunction() {
val fileBody = """
class Foo
internal fun bar() {}
""".trimIndent()
createFileAndCheckIcon("Foo.kt", fileBody, "org/jetbrains/kotlin/idea/icons/kotlin_file.svg")
}
private fun createFileAndCheckIcon(fileName: String, fileBody: String, vararg icons: String) {
val psiFile = myFixture.configureByText(fileName, fileBody)
val icon = PsiIconUtil.getProvidersIcon(psiFile, Iconable.ICON_FLAG_VISIBILITY or Iconable.ICON_FLAG_READ_STATUS)
val iconString = (icon.safeAs<RowIcon>()?.allIcons?.joinToString(transform = Icon::toString) ?: icon)?.toString()
assertEquals(icons.joinToString(), iconString)
}
} | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/KotlinIconProviderTest.kt | 2147560095 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.search.usagesSearch.operators
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.search.SearchRequestCollector
import com.intellij.psi.search.SearchScope
import com.intellij.util.Processor
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions
import org.jetbrains.kotlin.lexer.KtSingleValueToken
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtUnaryExpression
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance
class UnaryOperatorReferenceSearcher(
targetFunction: PsiElement,
private val operationToken: KtSingleValueToken,
searchScope: SearchScope,
consumer: Processor<in PsiReference>,
optimizer: SearchRequestCollector,
options: KotlinReferencesSearchOptions
) : OperatorReferenceSearcher<KtUnaryExpression>(
targetFunction,
searchScope,
consumer,
optimizer,
options,
wordsToSearch = listOf(operationToken.value)
) {
override fun processPossibleReceiverExpression(expression: KtExpression) {
val unaryExpression = expression.parent as? KtUnaryExpression ?: return
if (unaryExpression.operationToken != operationToken) return
processReferenceElement(unaryExpression)
}
override fun isReferenceToCheck(ref: PsiReference): Boolean {
if (ref !is KtSimpleNameReference) return false
val element = ref.element
if (element.parent !is KtUnaryExpression) return false
return element.getReferencedNameElementType() == operationToken
}
override fun extractReference(element: KtElement): PsiReference? {
val unaryExpression = element as? KtUnaryExpression ?: return null
if (unaryExpression.operationToken != operationToken) return null
return unaryExpression.operationReference.references.firstIsInstance<KtSimpleNameReference>()
}
} | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/usagesSearch/operators/UnaryOperatorReferenceSearcher.kt | 858420415 |
/*
* Copyright 2020 Google 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.google.android.apps.muzei.api.internal
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.annotation.RequiresApi
import com.google.android.apps.muzei.api.internal.ProtocolConstants.KEY_COMMAND
import com.google.android.apps.muzei.api.internal.ProtocolConstants.KEY_COMMAND_ARTWORK_ID
import com.google.android.apps.muzei.api.internal.ProtocolConstants.KEY_COMMAND_AUTHORITY
import com.google.android.apps.muzei.api.internal.ProtocolConstants.METHOD_TRIGGER_COMMAND
import com.google.android.apps.muzei.api.provider.ProviderContract
/**
* A [BroadcastReceiver] specifically for maintaining backward compatibility with the
* `getCommands()` and `onCommand()` APIs for apps that upgrade to the latest version
* of the Muzei API without updating their `MuzeiArtProvider` to use the new
* [com.google.android.apps.muzei.api.provider.MuzeiArtProvider.getCommandActions].
*/
@RequiresApi(Build.VERSION_CODES.KITKAT)
public class RemoteActionBroadcastReceiver : BroadcastReceiver() {
public companion object {
/**
* Construct a [PendingIntent] suitable for passing to
* [androidx.core.app.RemoteActionCompat] that will trigger the
* `onCommand()` API of the `MuzeiArtProvider` associated with
* the [authority].
*
* When building your own [androidx.core.app.RemoteActionCompat], you
* should **not** use this method. Instead, register your own
* [BroadcastReceiver], [android.app.Service], or directly launch
* an [android.app.Activity] as needed by your command rather than go
* through the inefficiency of starting this receiver just to trigger
* your [com.google.android.apps.muzei.api.provider.MuzeiArtProvider].
*/
public fun createPendingIntent(
context: Context,
authority: String,
artworkId: Long,
id: Int
): PendingIntent {
val intent = Intent(context, RemoteActionBroadcastReceiver::class.java).apply {
putExtra(KEY_COMMAND_AUTHORITY, authority)
putExtra(KEY_COMMAND_ARTWORK_ID, artworkId)
putExtra(KEY_COMMAND, id)
}
return PendingIntent.getBroadcast(context,
id + 1000 * artworkId.toInt(),
intent,
PendingIntent.FLAG_UPDATE_CURRENT)
}
}
override fun onReceive(context: Context, intent: Intent?) {
val authority = intent?.getStringExtra(KEY_COMMAND_AUTHORITY)
if (authority != null) {
val contentUri = ContentUris.withAppendedId(
ProviderContract.getContentUri(authority),
intent.getLongExtra(KEY_COMMAND_ARTWORK_ID, -1))
val id = intent.getIntExtra(KEY_COMMAND, -1)
val pendingResult = goAsync()
try {
context.contentResolver.call(contentUri,
METHOD_TRIGGER_COMMAND,
contentUri.toString(),
Bundle().apply { putInt(KEY_COMMAND, id) })
} finally {
pendingResult.finish()
}
}
}
}
| muzei-api/src/main/java/com/google/android/apps/muzei/api/internal/RemoteActionBroadcastReceiver.kt | 2278469589 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.stash.ui
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.AnActionExtensionProvider
import com.intellij.openapi.vcs.changes.actions.ShowDiffWithLocalAction
import com.intellij.openapi.vcs.changes.actions.diff.ShowDiffAction
import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase
class GitCompareWithLocalFromStashAction: AnActionExtensionProvider {
override fun isActive(e: AnActionEvent): Boolean {
return e.getData(GitStashUi.GIT_STASH_UI) != null &&
e.getData(ChangesBrowserBase.DATA_KEY) == null
}
override fun update(e: AnActionEvent) {
val project = e.project
val stashUi = e.getData(GitStashUi.GIT_STASH_UI)
if (project == null || stashUi == null) {
e.presentation.isEnabledAndVisible = false
return
}
e.presentation.isVisible = true
e.presentation.isEnabled = stashUi.changesBrowser.changes.any { change ->
ShowDiffWithLocalAction.getChangeWithLocal(change, false) != null
}
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val changes = e.getRequiredData(GitStashUi.GIT_STASH_UI).changesBrowser.changes
val changesWithLocal = changes.mapNotNull { change ->
ShowDiffWithLocalAction.getChangeWithLocal(change, false)
}
ShowDiffAction.showDiffForChange(project, changesWithLocal)
}
} | plugins/git4idea/src/git4idea/stash/ui/GitCompareWithLocalFromStashAction.kt | 680241613 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.editorconfig.language.codeinsight.inspections
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.vfs.VfsUtilCore
import org.editorconfig.core.EditorConfigAutomatonBuilder.getCachedHeaderRunAutomaton
import org.editorconfig.language.codeinsight.quickfixes.EditorConfigRemoveSectionQuickFix
import org.editorconfig.language.messages.EditorConfigBundle
import org.editorconfig.language.psi.EditorConfigHeader
import org.editorconfig.language.psi.EditorConfigVisitor
import org.editorconfig.language.util.EditorConfigPsiTreeUtil
class EditorConfigNoMatchingFilesInspection : LocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : EditorConfigVisitor() {
override fun visitHeader(header: EditorConfigHeader) {
if (!header.isValidGlob) return
val runAutomaton = getCachedHeaderRunAutomaton(header)
val folder = EditorConfigPsiTreeUtil.getOriginalFile(header.containingFile)?.virtualFile?.parent ?: return
var pass = 0
val found = !VfsUtilCore.iterateChildrenRecursively(folder, null) {
pass += 1
if (pass % CancellationCheckFrequency == 0) ProgressManager.checkCanceled()
!(it.isValid && runAutomaton.run(it.path))
}
if (found) return
val message = EditorConfigBundle.get("inspection.no-matching-files.message", folder.name)
holder.registerProblem(header, message, ProblemHighlightType.LIKE_UNUSED_SYMBOL, EditorConfigRemoveSectionQuickFix())
}
}
private companion object {
private const val CancellationCheckFrequency = 20
}
}
| plugins/editorconfig/src/org/editorconfig/language/codeinsight/inspections/EditorConfigNoMatchingFilesInspection.kt | 1507233251 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.feedback.notification
import com.intellij.feedback.bundle.FeedbackBundle
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
/**
* Basic notification for Kotlin feedback requests
*/
class RequestFeedbackNotification : Notification(
"Project Creation Feedback",
FeedbackBundle.message("notification.request.feedback.title"),
FeedbackBundle.message("notification.request.feedback.content"),
NotificationType.INFORMATION
) | platform/feedback/src/com/intellij/feedback/notification/RequestFeedbackNotification.kt | 81347384 |
fun f() {
if (1 is Int) {
}
} | plugins/kotlin/idea/tests/testData/formatter/Is.kt | 113731698 |
package com.intellij.aws.cloudformation.model
class CfnResourcePropertiesNode(name: CfnScalarValueNode?, val properties: List<CfnResourcePropertyNode>) : CfnNamedNode(name)
class CfnResourceDependsOnNode(name: CfnScalarValueNode?, val dependsOn: List<CfnScalarValueNode>) : CfnNamedNode(name)
class CfnResourceConditionNode(name: CfnScalarValueNode?, val condition: CfnScalarValueNode?) : CfnNamedNode(name)
| src/main/kotlin/com/intellij/aws/cloudformation/model/CfnResourcePropertiesNode.kt | 1686875351 |
package com.xmartlabs.template.model
import com.xmartlabs.template.BuildConfig
import com.xmartlabs.bigbang.core.model.BuildInfo as CoreBuildInfo
class BuildInfo : CoreBuildInfo {
override val isDebug = BuildConfig.DEBUG
override val isStaging = BuildConfig.FLAVOR == BuildType.STAGING.toString()
override val isProduction = BuildConfig.FLAVOR == BuildType.PRODUCTION.toString()
}
| app/src/main/java/com/xmartlabs/template/model/BuildInfo.kt | 835201705 |
// GENERATED
package com.fkorotkov.kubernetes.networking.v1
import io.fabric8.kubernetes.api.model.LabelSelector as model_LabelSelector
import io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyPeer as v1_NetworkPolicyPeer
fun v1_NetworkPolicyPeer.`namespaceSelector`(block: model_LabelSelector.() -> Unit = {}) {
if(this.`namespaceSelector` == null) {
this.`namespaceSelector` = model_LabelSelector()
}
this.`namespaceSelector`.block()
}
| DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/networking/v1/namespaceSelector.kt | 1230280799 |
package com.excref.kotblog.blog.service.user
import com.excref.kotblog.blog.service.test.AbstractServiceIntegrationTest
import com.excref.kotblog.blog.service.user.domain.UserRole
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.springframework.beans.factory.annotation.Autowired
/**
* @author Arthur Asatryan
* @since 6/8/17 1:21 AM
*/
class UserServiceIntegrationTest : AbstractServiceIntegrationTest() {
//region Dependencies
@Autowired
private lateinit var userService: UserService
//endregion
//region Test methods
@Test
fun testCreate() {
// given
val email = "[email protected]"
val password = "you can't even guess me! :P"
val role = UserRole.USER
// when
val result = userService.create(email, password, role)
// then
assertThat(result).isNotNull().extracting("email", "password", "role").containsOnly(email, password, role)
}
@Test
fun testGetByUuid() {
// given
val user = helper.persistUser()
val uuid = user.uuid
// when
val result = userService.getByUuid(uuid)
// then
assertThat(result).isNotNull().isEqualTo(user)
}
@Test
fun testExistsForEmail() {
// given
val email = "[email protected]"
helper.persistUser(email = email)
// when
val existsForEmail = userService.existsForEmail(email)
assertThat(existsForEmail).isTrue()
}
//endregion
} | blog/service/impl/src/test/kotlin/com/excref/kotblog/blog/service/user/UserServiceIntegrationTest.kt | 2807483805 |
package com.doomspork.helloworld.health
import com.codahale.metrics.health.HealthCheck
import com.codahale.metrics.health.HealthCheck.Result
class TemplateHealthCheck(val template: String) : HealthCheck() {
override fun check() : Result {
val saying = java.lang.String.format(template, "TEST")
if (!saying.contains("TEST")) {
return Result.unhealthy("template doesn't include a name")
}
return Result.healthy()
}
}
| src/main/kotlin/com/doomspork/helloworld/health/TemplateHealthCheck.kt | 455303527 |
// Copyright (c) 2020 Google LLC All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package com.google.idea.gn.psi.builtin
import com.google.idea.gn.completion.CompletionIdentifier
import com.google.idea.gn.psi.Function
import com.google.idea.gn.psi.GnCall
import com.google.idea.gn.psi.GnValue
import com.google.idea.gn.psi.scope.Scope
class SetDefaultToolchain : Function {
// TODO implement
override fun execute(call: GnCall, targetScope: Scope): GnValue? = null
override val isBuiltin: Boolean
get() = true
override val identifierName: String
get() = NAME
override val identifierType: CompletionIdentifier.IdentifierType
get() = CompletionIdentifier.IdentifierType.FUNCTION
companion object {
const val NAME = "set_default_toolchain"
}
}
| src/main/java/com/google/idea/gn/psi/builtin/SetDefaultToolchain.kt | 827850047 |
package hook.javassist
fun main(args: Array<String>) {
TestIm().ab.name
} | HttpTest3/src/main/java/hook/javassist/Testllll.kt | 4254729930 |
package com.wackalooon.value.data.repository
import com.wackalooon.value.data.model.ValueDatabaseEntity
import com.wackalooon.value.data.storage.ValueDao
import com.wackalooon.value.domain.model.Value
import com.wackalooon.value.domain.repository.ValueRepository
import java.util.Date
class ValueRepositoryImpl(private val valueDao: ValueDao) : ValueRepository {
override fun getValuesForMeterId(meterId: Long): List<Value> {
return listOf(
Value(0, Date().time - 90000, 30.0),
Value(1, Date().time - 6000, 30.0),
Value(2, Date().time - 3000, 30.0)
)
// return valueDao.getAll(meterId).map { it.toValue() }
}
override fun addValueForMeterId(value: Value, meterId: Long) {
valueDao.insert(value.toValueDaoEntity(meterId))
}
override fun updateValue(valueId: Long, newValue: Double) {
valueDao.update(valueId, newValue)
}
override fun deleteValue(valueId: Long) {
valueDao.delete(valueId)
}
private fun ValueDatabaseEntity.toValue(): Value {
return Value(id, creationTime, value)
}
private fun Value.toValueDaoEntity(meterId: Long): ValueDatabaseEntity {
return ValueDatabaseEntity(id, creationTime, meterId, value)
}
}
| value-data/src/main/java/com/wackalooon/value/data/repository/ValueRepositoryImpl.kt | 3540167950 |
package com.foo.graphql.nullableInput
import com.foo.graphql.nullableInput.type.Flower
import org.springframework.stereotype.Component
@Component
open class DataRepository {
//flowersNullInNullOut(id: [Int]): Flower
fun findFlowersNullInNullOut(id: Array<Int?>?): Flower? {
return if (id == null) null
else
if (id.all { it != null }) Flower(0, "flowerNameX") else null
}
//flowersNullIn(id: [Int]!): Flower
fun findFlowersNullIn(id: Array<Int?>): Flower? {
return if (id.all { it != null }) Flower(0, "flowerNameX") else null
}
//flowersNullOut(id: [Int!]): Flower
fun findFlowersNullOut(id: Array<Int>?): Flower? {
return if (id == null) null
else Flower(0, "flowerNameX")
}
// flowersNotNullInOut(id: [Int!]!): Flower
fun findFlowersNotNullInOut(id: Array<Int>): Flower? {
return Flower(0, "flowerNameX")
}
fun findFlowersScalarNullable(id: Boolean?): Flower? {
return if (id == null) null else
if (id) Flower(1, "flowerNameIdTrue")
else Flower(0, "flowerNameIdFalse")
}
fun findFlowersScalarNotNullable(id: Boolean): Flower? {
return if (id) Flower(1, "flowerNameIdTrue")
else Flower(0, "flowerNameIdFalse")
}
}
| e2e-tests/spring-graphql/src/main/kotlin/com/foo/graphql/nullableInput/DataRepository.kt | 20183876 |
/*
* Copyright (C) 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.sqldelight.intellij
import com.bugsnag.Bugsnag
import com.bugsnag.Severity
import com.intellij.diagnostic.AbstractMessage
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.diagnostic.ErrorReportSubmitter
import com.intellij.openapi.diagnostic.IdeaLoggingEvent
import com.intellij.openapi.diagnostic.SubmittedReportInfo
import com.intellij.util.Consumer
import com.squareup.sqldelight.VERSION
import java.awt.Component
class SqlDelightErrorHandler : ErrorReportSubmitter() {
val bugsnag = Bugsnag(BUGSNAG_KEY, false)
init {
bugsnag.setAutoCaptureSessions(false)
bugsnag.startSession()
bugsnag.setAppVersion(VERSION)
bugsnag.setProjectPackages("com.squareup.sqldelight")
bugsnag.addCallback {
it.addToTab("Device", "osVersion", System.getProperty("os.version"))
it.addToTab("Device", "JRE", System.getProperty("java.version"))
it.addToTab("Device", "IDE Version", ApplicationInfo.getInstance().fullVersion)
it.addToTab("Device", "IDE Build #", ApplicationInfo.getInstance().build)
PluginManagerCore.getPlugins().forEach { plugin ->
it.addToTab("Plugins", plugin.name, "${plugin.pluginId} : ${plugin.version}")
}
}
}
override fun getReportActionText() = "Send to Square"
override fun submit(
events: Array<out IdeaLoggingEvent>,
additionalInfo: String?,
parentComponent: Component,
consumer: Consumer<SubmittedReportInfo>
): Boolean {
for (event in events) {
if (BUGSNAG_KEY.isNotBlank()) {
val throwable = (event.data as? AbstractMessage)?.throwable ?: event.throwable
bugsnag.notify(throwable, Severity.ERROR) {
it.addToTab("Data", "message", event.message)
it.addToTab("Data", "additional info", additionalInfo)
it.addToTab("Data", "stacktrace", event.throwableText)
}
}
}
return true
}
}
| sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/SqlDelightErrorHandler.kt | 1886259909 |
/*
* Copyright (C) 2016/2022 Litote
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.litote.kmongo.rxjava2
import com.mongodb.client.model.FindOneAndUpdateOptions
import com.mongodb.client.model.ReturnDocument.AFTER
import org.bson.Document
import org.bson.types.ObjectId
import org.junit.Test
import org.litote.kmongo.MongoOperator.set
import org.litote.kmongo.MongoOperator.setOnInsert
import org.litote.kmongo.json
import org.litote.kmongo.model.ExposableFriend
import org.litote.kmongo.model.Friend
import kotlin.test.assertEquals
import kotlin.test.assertNull
/**
*
*/
class FindOneAndModifyTest : KMongoRxBaseTest<Friend>() {
@Test
fun canFindAndUpdateOne() {
col.insertOne(Friend("John", "22 Wall Street Avenue")).blockingAwait()
col.findOneAndUpdate("{name:'John'}", "{$set: {address: 'A better place'}}").blockingGet() ?: throw AssertionError("Value cannot null!")
val savedFriend = col.findOne("{name:'John'}").blockingGet() ?: throw AssertionError("Value cannot null!")
assertEquals("John", savedFriend.name)
assertEquals("A better place", savedFriend.address)
}
@Test
fun canFindAndUpdateWithNullValue() {
col.insertOne(Friend("John", "22 Wall Street Avenue")).blockingAwait()
col.findOneAndUpdate("{name:'John'}", "{$set: {address: null}}").blockingGet() ?: throw AssertionError("Value cannot null!")
val friend = col.findOne("{name:'John'}").blockingGet() ?: throw AssertionError("Value cannot null!")
assertEquals("John", friend.name)
assertNull(friend.address)
}
@Test
fun canFindAndUpdateWithDocument() {
val col2 = col.withDocumentClass<Document>()
col.insertOne(Friend("John", "22 Wall Street Avenue")).blockingAwait()
col2.findOneAndUpdate("{name:'John'}", "{$set: {address: 'A better place'}}").blockingGet() ?: throw AssertionError("Value cannot null!")
val friend = col2.findOne("{name:'John'}").blockingGet() ?: throw AssertionError("Value cannot null!")
assertEquals("John", friend["name"])
assertEquals("A better place", friend["address"])
}
@Test
fun canUpsertByObjectId() {
val expected = Friend(ObjectId(), "John")
val friend = col.findOneAndUpdate(
"{_id:${expected._id!!.json}}",
"{$setOnInsert: {name: 'John'}}",
FindOneAndUpdateOptions().upsert(true).returnDocument(AFTER)).blockingGet() ?: throw AssertionError("Value cannot null!")
assertEquals(expected, friend)
}
@Test
fun canUpsertByStringId() {
val expected = ExposableFriend(ObjectId().toString(), "John")
val friend = col.withDocumentClass<ExposableFriend>().findOneAndUpdate(
"{_id:${expected._id.json}}",
"{$setOnInsert: {name: 'John'}}",
FindOneAndUpdateOptions().upsert(true).returnDocument(AFTER)).blockingGet()
assertEquals(expected, friend)
}
} | kmongo-rxjava2-core-tests/src/main/kotlin/org/litote/kmongo/rxjava2/FindOneAndModifyTest.kt | 4179120412 |
package org.evomaster.core.output
import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType
import org.evomaster.core.EMConfig
import org.evomaster.core.database.DbAction
import org.evomaster.core.database.schema.Column
import org.evomaster.core.database.schema.ColumnDataType
import org.evomaster.core.database.schema.Table
import org.evomaster.core.output.EvaluatedIndividualBuilder.Companion.buildEvaluatedIndividual
import org.evomaster.core.output.service.PartialOracles
import org.evomaster.core.output.service.RestTestCaseWriter
import org.evomaster.core.search.gene.ObjectGene
import org.evomaster.core.search.gene.sql.SqlXMLGene
import org.evomaster.core.search.gene.string.StringGene
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
class WriteXMLTest {
private fun getConfig(format: OutputFormat): EMConfig {
val config = EMConfig()
config.outputFormat = format
config.expectationsActive = false
config.testTimeout = -1
return config
}
@Test
fun testEmptyXML() {
val xmlColumn = Column("xmlColumn", ColumnDataType.XML, 10, primaryKey = false, autoIncrement = false, databaseType = DatabaseType.POSTGRES)
val table = Table("Table0", setOf(xmlColumn), setOf())
val objectGene = ObjectGene("anElement", listOf())
val sqlXMLGene = SqlXMLGene("xmlColumn", objectGene)
val insert = DbAction(table, setOf(xmlColumn), 0L, listOf(sqlXMLGene))
val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(mutableListOf(insert))
val config = getConfig(format)
val test = TestCase(test = ei, name = "test")
val writer = RestTestCaseWriter(config, PartialOracles())
val lines = writer.convertToCompilableTestCode(test, baseUrlOfSut)
val expectedLines = Lines().apply {
add("@Test")
add("public void test() throws Exception {")
indent()
add("List<InsertionDto> insertions = sql().insertInto(\"Table0\", 0L)")
indent()
indent()
add(".d(\"xmlColumn\", \"\\\"<anElement></anElement>\\\"\")")
deindent()
add(".dtos();")
deindent()
add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);")
deindent()
add("}")
}
Assertions.assertEquals(expectedLines.toString(), lines.toString())
}
@Test
fun testChildrenXML() {
val xmlColumn = Column("xmlColumn", ColumnDataType.XML, 10, primaryKey = false, autoIncrement = false,
databaseType = DatabaseType.POSTGRES)
val table = Table("Table0", setOf(xmlColumn), setOf())
val child0 = ObjectGene("child", listOf())
val child1 = ObjectGene("child", listOf())
val child2 = ObjectGene("child", listOf())
val child3 = ObjectGene("child", listOf())
val objectGene = ObjectGene("anElement", listOf(child0, child1, child2, child3))
val sqlXMLGene = SqlXMLGene("xmlColumn", objectGene)
val insert = DbAction(table, setOf(xmlColumn), 0L, listOf(sqlXMLGene))
val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(mutableListOf(insert))
val config = getConfig(format)
val test = TestCase(test = ei, name = "test")
val writer = RestTestCaseWriter(config, PartialOracles())
val lines = writer.convertToCompilableTestCode( test, baseUrlOfSut)
val expectedLines = Lines().apply {
add("@Test")
add("public void test() throws Exception {")
indent()
add("List<InsertionDto> insertions = sql().insertInto(\"Table0\", 0L)")
indent()
indent()
add(".d(\"xmlColumn\", \"\\\"<anElement><child></child><child></child><child></child><child></child></anElement>\\\"\")")
deindent()
add(".dtos();")
deindent()
add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);")
deindent()
add("}")
}
Assertions.assertEquals(expectedLines.toString(), lines.toString())
}
@Test
fun testString() {
val xmlColumn = Column("xmlColumn", ColumnDataType.XML, 10, primaryKey = false, autoIncrement = false,
databaseType = DatabaseType.POSTGRES)
val table = Table("Table0", setOf(xmlColumn), setOf())
val stringGene = StringGene("stringValue", value = "</element>")
val objectGene = ObjectGene("anElement", listOf(stringGene))
val sqlXMLGene = SqlXMLGene("xmlColumn", objectGene)
val insert = DbAction(table, setOf(xmlColumn), 0L, listOf(sqlXMLGene))
val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(mutableListOf(insert))
val config = getConfig(format)
val test = TestCase(test = ei, name = "test")
val writer = RestTestCaseWriter(config, PartialOracles())
val lines = writer.convertToCompilableTestCode( test, baseUrlOfSut)
val expectedLines = Lines().apply {
add("@Test")
add("public void test() throws Exception {")
indent()
add("List<InsertionDto> insertions = sql().insertInto(\"Table0\", 0L)")
indent()
indent()
add(".d(\"xmlColumn\", \"\\\"<anElement></element></anElement>\\\"\")")
deindent()
add(".dtos();")
deindent()
add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);")
deindent()
add("}")
}
Assertions.assertEquals(expectedLines.toString(), lines.toString())
}
}
| core/src/test/kotlin/org/evomaster/core/output/WriteXMLTest.kt | 3468683709 |
package com.sonnyrodriguez.fittrainer.fittrainerbasic.adapters
import android.support.v4.content.ContextCompat
import android.view.Gravity
import android.view.ViewGroup
import com.sonnyrodriguez.fittrainer.fittrainerbasic.R
import org.jetbrains.anko.*
class ExerciseItemUi: AnkoComponent<ViewGroup> {
override fun createView(ui: AnkoContext<ViewGroup>) = with(ui) {
relativeLayout {
backgroundDrawable = ContextCompat.getDrawable(ctx, R.drawable.list_background_white)
lparams(width = matchParent, height = wrapContent) {
horizontalMargin = dip(16)
verticalPadding = dip(8)
}
verticalLayout {
themedTextView(R.style.BasicListItemTitle) {
id = R.id.exercise_item_title
}.lparams(width = matchParent, height = wrapContent) {
gravity = Gravity.CENTER
}
themedTextView(R.style.BasicListItemStyle) {
id = R.id.exercise_item_muscle
}.lparams(width = matchParent, height = wrapContent) {
gravity = Gravity.BOTTOM
}
}
}
}
}
| mobile/src/main/java/com/sonnyrodriguez/fittrainer/fittrainerbasic/adapters/ExerciseItemUi.kt | 403437928 |
package com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi
import com.intellij.psi.PsiNameIdentifierOwner
/*
* Copyright 2016 Blue Box Ware
*
* 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.
*/
interface SkinNamedElement : SkinElement, PsiNameIdentifierOwner
| src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/skin/psi/SkinNamedElement.kt | 278841499 |
package life.shank.android
import android.app.Application
import android.content.ContentProvider
import android.content.ContentValues
import android.database.Cursor
import android.net.Uri
class ShankContentProvider : ContentProvider() {
override fun onCreate(): Boolean {
(context!!.applicationContext as Application).registerActivityLifecycleCallbacks(AutoScopedActivityLifecycleCallbacks)
AppContextModule.apply { context = [email protected]!!.applicationContext }
return true
}
override fun query(uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor? = null
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int = 0
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int = 0
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
override fun getType(uri: Uri): String? = ""
} | android/src/main/java/life/shank/android/ShankContentProvider.kt | 2136784216 |
package fr.free.nrw.commons.mwapi
import com.google.gson.Gson
import fr.free.nrw.commons.mwapi.model.Page
import fr.free.nrw.commons.mwapi.model.PageCategory
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
class CategoryApiTest {
private lateinit var server: MockWebServer
private lateinit var url: String
private lateinit var categoryApi: CategoryApi
@Before
fun setUp() {
server = MockWebServer()
url = "http://${server.hostName}:${server.port}/"
categoryApi = CategoryApi(OkHttpClient.Builder().build(), Gson(), HttpUrl.parse(url))
}
@After
fun teardown() {
server.shutdown()
}
@Test
fun apiReturnsEmptyListWhenError() {
server.enqueue(MockResponse().setResponseCode(400).setBody(""))
assertTrue(categoryApi.request("foo").blockingGet().isEmpty())
}
@Test
fun apiReturnsEmptyWhenTheresNoQuery() {
server.success(emptyMap())
assertTrue(categoryApi.request("foo").blockingGet().isEmpty())
}
@Test
fun apiReturnsEmptyWhenQueryHasNoPages() {
server.success(mapOf("query" to emptyMap<String, Any>()))
assertTrue(categoryApi.request("foo").blockingGet().isEmpty())
}
@Test
fun apiReturnsEmptyWhenQueryHasPagesButTheyreEmpty() {
server.success(mapOf("query" to
mapOf("pages" to emptyList<String>())))
assertTrue(categoryApi.request("foo").blockingGet().isEmpty())
}
@Test
fun singlePageSingleCategory() {
server.success(mapOf("query" to
mapOf("pages" to listOf(
page(listOf("one"))
))))
val response = categoryApi.request("foo").blockingGet()
assertEquals(1, response.size)
assertEquals("one", response[0])
}
@Test
fun multiplePagesSingleCategory() {
server.success(mapOf("query" to
mapOf("pages" to listOf(
page(listOf("one")),
page(listOf("two"))
))))
val response = categoryApi.request("foo").blockingGet()
assertEquals(2, response.size)
assertEquals("one", response[0])
assertEquals("two", response[1])
}
@Test
fun singlePageMultipleCategories() {
server.success(mapOf("query" to
mapOf("pages" to listOf(
page(listOf("one", "two"))
))))
val response = categoryApi.request("foo").blockingGet()
assertEquals(2, response.size)
assertEquals("one", response[0])
assertEquals("two", response[1])
}
@Test
fun multiplePagesMultipleCategories() {
server.success(mapOf("query" to
mapOf("pages" to listOf(
page(listOf("one", "two")),
page(listOf("three", "four"))
))))
val response = categoryApi.request("foo").blockingGet()
assertEquals(4, response.size)
assertEquals("one", response[0])
assertEquals("two", response[1])
assertEquals("three", response[2])
assertEquals("four", response[3])
}
@Test
fun multiplePagesMultipleCategories_duplicatesRemoved() {
server.success(mapOf("query" to
mapOf("pages" to listOf(
page(listOf("one", "two", "three")),
page(listOf("three", "four", "one"))
))))
val response = categoryApi.request("foo").blockingGet()
assertEquals(4, response.size)
assertEquals("one", response[0])
assertEquals("two", response[1])
assertEquals("three", response[2])
assertEquals("four", response[3])
}
@Test
fun requestSendsWhatWeExpect() {
server.success(mapOf("query" to mapOf("pages" to emptyList<String>())))
val coords = "foo,bar"
categoryApi.request(coords).blockingGet()
server.takeRequest().let { request ->
assertEquals("GET", request.method)
assertEquals("/w/api.php", request.requestUrl.encodedPath())
request.requestUrl.let { url ->
assertEquals("query", url.queryParameter("action"))
assertEquals("categories|coordinates|pageprops", url.queryParameter("prop"))
assertEquals("json", url.queryParameter("format"))
assertEquals("!hidden", url.queryParameter("clshow"))
assertEquals("type|name|dim|country|region|globe", url.queryParameter("coprop"))
assertEquals(coords, url.queryParameter("codistancefrompoint"))
assertEquals("geosearch", url.queryParameter("generator"))
assertEquals(coords, url.queryParameter("ggscoord"))
assertEquals("10000", url.queryParameter("ggsradius"))
assertEquals("10", url.queryParameter("ggslimit"))
assertEquals("6", url.queryParameter("ggsnamespace"))
assertEquals("type|name|dim|country|region|globe", url.queryParameter("ggsprop"))
assertEquals("all", url.queryParameter("ggsprimary"))
assertEquals("2", url.queryParameter("formatversion"))
}
}
}
private fun page(catList: List<String>) = Page().apply {
categories = catList.map {
PageCategory().apply {
title = "Category:$it"
}
}.toTypedArray()
}
}
fun MockWebServer.success(response: Map<String, Any>) {
enqueue(MockResponse().setResponseCode(200).setBody(Gson().toJson(response)))
} | app/src/test/kotlin/fr/free/nrw/commons/mwapi/CategoryApiTest.kt | 1330923025 |
package com.vicpin.krealmextensions
import android.support.test.runner.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import com.vicpin.krealmextensions.model.TestEntity
import com.vicpin.krealmextensions.model.TestEntityPK
import com.vicpin.krealmextensions.util.TestRealmConfigurationFactory
import io.reactivex.disposables.Disposable
import io.realm.Realm
import io.realm.Sort
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.CountDownLatch
/**
* Created by victor on 10/1/17.
*/
@RunWith(AndroidJUnit4::class)
class KRealmExtensionsRxTests {
@get:Rule var configFactory = TestRealmConfigurationFactory()
lateinit var realm: Realm
lateinit var latch: CountDownLatch
var latchReleased = false
var disposable: Disposable? = null
@Before fun setUp() {
val realmConfig = configFactory.createConfiguration()
realm = Realm.getInstance(realmConfig)
latch = CountDownLatch(1)
}
@After fun tearDown() {
TestEntity().deleteAll()
TestEntityPK().deleteAll()
realm.close()
latchReleased = false
disposable = null
}
/**
* SINGLE AND FLOWABLE TESTS
*/
@Test fun testQueryAllAsFlowable() {
var itemsCount = 5
var disposable: Disposable? = null
populateDBWithTestEntity(numItems = itemsCount)
block {
disposable = TestEntity().queryAllAsFlowable().subscribe({
assertThat(it).hasSize(itemsCount)
release()
}, { it.printStackTrace() })
}
block {
//Add one item more to db
++itemsCount
populateDBWithTestEntity(numItems = 1)
}
disposable?.dispose()
}
@Test fun testQueryAllAsFlowableManaged() {
var itemsCount = 5
var disposable: Disposable? = null
populateDBWithTestEntity(numItems = itemsCount)
block {
disposable = TestEntity().queryAllAsFlowable(managed = true).subscribe({
assertThat(it).hasSize(itemsCount)
it.forEach { assertThat(it.isManaged).isTrue() }
release()
}, { it.printStackTrace() })
}
block {
//Add one item more to db
++itemsCount
populateDBWithTestEntity(numItems = 1)
}
disposable?.dispose()
}
@Test fun testQueryAsFlowable() {
populateDBWithTestEntityPK(numItems = 5)
block {
disposable = TestEntityPK().queryAsFlowable { equalToValue("id", 1) }.subscribe({
assertThat(it).hasSize(1)
assertThat(it[0].isManaged).isFalse()
release()
}, { it.printStackTrace() })
}
disposable?.dispose()
}
@Test fun testQueryAsFlowableManaged() {
populateDBWithTestEntityPK(numItems = 5)
block {
disposable = TestEntityPK().queryAsFlowable(managed = true) { equalToValue("id", 1) }.subscribe({
assertThat(it).hasSize(1)
it.forEach { assertThat(it.isManaged).isTrue() }
release()
}, { it.printStackTrace() })
}
disposable?.dispose()
}
@Test fun testQueryAllAsSingle() {
var itemsCount = 5
populateDBWithTestEntity(numItems = itemsCount)
block {
disposable = TestEntity().queryAllAsSingle().subscribe({ result ->
assertThat(result).hasSize(itemsCount)
assertThat(result[0].isManaged).isFalse()
release()
}, { it.printStackTrace() })
}
assertThat(disposable?.isDisposed ?: false).isTrue()
}
@Test fun testQueryAsSingle() {
populateDBWithTestEntityPK(numItems = 5)
block {
disposable = TestEntityPK().queryAsSingle { equalToValue("id", 1) }.subscribe({ it ->
assertThat(it).hasSize(1)
assertThat(it[0].isManaged).isFalse()
release()
}, { it.printStackTrace() })
}
assertThat(disposable?.isDisposed ?: false).isTrue()
}
@Test fun testQuerySortedAsFlowable() {
populateDBWithTestEntityPK(numItems = 5)
block {
disposable = TestEntityPK().querySortedAsFlowable("id", Sort.DESCENDING).subscribe({
assertThat(it).hasSize(5)
assertThat(it[0].isManaged).isFalse()
assertThat(it[0].id).isEqualTo(4)
release()
}, { it.printStackTrace() })
}
disposable?.dispose()
}
@Test fun testQuerySortedAsFlowableManaged() {
populateDBWithTestEntityPK(numItems = 5)
block {
disposable = TestEntityPK().querySortedAsFlowable("id", Sort.DESCENDING, managed = true).subscribe({
assertThat(it).hasSize(5)
it.forEach { assertThat(it.isManaged).isTrue() }
assertThat(it[0].id).isEqualTo(4)
release()
}, { it.printStackTrace() })
}
disposable?.dispose()
}
@Test fun testQuerySortedAsFlowableWithQuery() {
populateDBWithTestEntityPK(numItems = 5)
block {
disposable = TestEntityPK().querySortedAsFlowable("id", Sort.DESCENDING) { equalToValue("id", 1) }.subscribe({
assertThat(it).hasSize(1)
assertThat(it[0].isManaged).isFalse()
assertThat(it[0].id).isEqualTo(1)
release()
}, { it.printStackTrace() })
}
disposable?.dispose()
}
@Test fun testQuerySortedAsFlowableManagedWithQuery() {
populateDBWithTestEntityPK(numItems = 5)
block {
disposable = TestEntityPK().querySortedAsFlowable("id", Sort.DESCENDING, managed = true) { equalToValue("id", 1) }.subscribe({
assertThat(it).hasSize(1)
it.forEach { assertThat(it.isManaged).isTrue() }
assertThat(it[0].id).isEqualTo(1)
release()
}, { it.printStackTrace() })
}
disposable?.dispose()
}
@Test fun testQuerySortedAsSingle() {
populateDBWithTestEntityPK(numItems = 5)
block {
disposable = TestEntityPK().querySortedAsSingle("id", Sort.DESCENDING).subscribe({ it ->
assertThat(it).hasSize(5)
assertThat(it[0].isManaged).isFalse()
assertThat(it[0].id).isEqualTo(4)
release()
}, { it.printStackTrace() })
}
assertThat(disposable?.isDisposed ?: false).isTrue()
}
@Test fun testQuerySortedAsSingleWithQuery() {
populateDBWithTestEntityPK(numItems = 5)
block {
disposable = TestEntityPK().querySortedAsSingle("id", Sort.DESCENDING) { equalToValue("id", 1) }.subscribe({ it ->
assertThat(it).hasSize(1)
assertThat(it[0].isManaged).isFalse()
assertThat(it[0].id).isEqualTo(1)
release()
}, { it.printStackTrace() })
}
assertThat(disposable?.isDisposed ?: false).isTrue()
}
/**
* UTILITY TEST METHODS
*/
private fun populateDBWithTestEntity(numItems: Int) {
(0 until numItems).forEach { TestEntity().save() }
}
private fun populateDBWithTestEntityPK(numItems: Int) {
(0 until numItems).forEach { TestEntityPK(it.toLong()).save() }
}
private fun blockLatch() {
if (!latchReleased) {
latch.await()
}
}
private fun release() {
latchReleased = true
latch.countDown()
latch = CountDownLatch(1)
}
fun block(closure: () -> Unit) {
latchReleased = false
closure()
blockLatch()
}
}
| library-base/src/androidTest/java/com/vicpin/krealmextensions/KRealmExtensionsRxTests.kt | 2085826646 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2017-2019 Nephy Project Team
*
* 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.
*/
@file:Suppress("UNUSED", "PublicApiImplicitType")
package jp.nephy.penicillin.endpoints.users
import jp.nephy.penicillin.core.request.action.JsonObjectApiAction
import jp.nephy.penicillin.core.request.parameters
import jp.nephy.penicillin.core.session.get
import jp.nephy.penicillin.endpoints.Option
import jp.nephy.penicillin.endpoints.Users
import jp.nephy.penicillin.models.UserSuggestion
/**
* Access the users in a given category of the Twitter suggested user list.
* It is recommended that applications cache this data for no more than one hour.
*
* [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-suggestions-slug)
*
* @param slug The short name of list or a category
* @param lang Restricts the suggested categories to the requested language. The language must be specified by the appropriate two letter ISO 639-1 representation. Currently supported languages are provided by the [GET help/languages](https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-suggestions) API request. Unsupported language codes will receive English (en) results. If you use lang in this request, ensure you also include it when requesting the [GET users/suggestions/:slug](https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-suggestions) list.
* @param options Optional. Custom parameters of this request.
* @receiver [Users] endpoint instance.
* @return [JsonObjectApiAction] for [UserSuggestion] model.
*/
fun Users.userSuggestions(
slug: String,
lang: String? = null,
vararg options: Option
) = client.session.get("/1.1/users/suggestions/$slug.json") {
parameters(
"lang" to lang,
*options
)
}.jsonObject<UserSuggestion>()
| src/main/kotlin/jp/nephy/penicillin/endpoints/users/UserSuggestions.kt | 893593776 |
package com.tonyodev.fetchmigrator.fetch1
import com.tonyodev.fetch2.Download
data class DownloadTransferPair(val newDownload: Download, val oldID: Long) | fetchmigrator/src/main/java/com/tonyodev/fetchmigrator/fetch1/DownloadTransferPair.kt | 1192525349 |
package vip.frendy.model.net
import android.content.Context
import com.google.gson.Gson
import vip.frendy.model.entity.*
import vip.frendy.model.util.DeviceInfo
/**
* Created by iiMedia on 2017/6/2.
*/
class Request(val context: Context, val gson: Gson = Gson()) {
fun init(): UserID {
val params: ReqInit = ReqInit(DeviceInfo.getAndroidID(context))
val url = RequestCommon.INIT_URL + gson.toJson(params)
val jsonStr = RequestCommon(url).run()
return gson.fromJson(jsonStr, RespInit::class.java).data
}
fun getChannelList(uid: String, type: Int = 0): ArrayList<Channel> {
val url = RequestCommon.GET_CHANNEL + "×tamp=" + System.currentTimeMillis() + "&uid=" + uid + "&news_type=" + type
val jsonStr = RequestCommon(url).run()
return gson.fromJson(jsonStr, RespGetChannel::class.java).data.channel_list
}
fun getNewsList(uid: String, cid: String): ArrayList<News> {
val url = RequestCommon.GET_NEWS_LIST + "&uid=" + uid + "&type_id=" + cid
val jsonStr = RequestCommon(url).run()
return gson.fromJson(jsonStr, RespGetNews::class.java).data
}
fun getVideoList(uid: String, cid: String): ArrayList<News> {
val url = RequestCommon.GET_VIDEO_LIST + "&uid=" + uid + "&type_id=" + cid
val jsonStr = RequestCommon(url).run()
return gson.fromJson(jsonStr, RespGetNews::class.java).data
}
} | model/src/main/java/vip/frendy/model/net/Request.kt | 2974984009 |
/*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package sandbox.subscene
import com.almasb.fxgl.dsl.FXGL
import com.almasb.fxgl.scene.SubScene
import javafx.event.EventHandler
import javafx.scene.paint.Color
class AboutSubScene : SubScene() {
init {
var top = 30.0
val title = FXGL.getUIFactoryService().newText("About Screen", Color.BLACK, 22.0)
title.translateX = LEFT
title.translateY = top
contentRoot.children.add(title)
top += VERTICAL_GAP
val exitButton = FXGL.getUIFactoryService().newButton("Main Menu")
exitButton.translateX = LEFT
exitButton.translateY = top
exitButton.onAction = EventHandler {
FXGL.getEventBus().fireEvent(NavigateEvent(MAIN_VIEW))
}
contentRoot.children.add(exitButton)
}
}
| fxgl-samples/src/main/kotlin/sandbox/subscene/AboutSubScene.kt | 1811741969 |
/*
* Copyright 2017 Alexey Shtanko
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.shtanko.picasagallery.data.db
class DatabaseManagerImpl : DatabaseManager {
} | app/src/main/kotlin/io/shtanko/picasagallery/data/db/DatabaseManagerImpl.kt | 3929122638 |
package com.kalemao.library.base
import android.Manifest
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import butterknife.ButterKnife
import com.kalemao.library.R
import com.kalemao.library.utils.ActivityManager
import org.jetbrains.anko.alert
import org.jetbrains.anko.toast
/**
* Created by dim on 2017/5/27 10:07
* 邮箱:[email protected]
*/
abstract class BaseActivity : AppCompatActivity() {
// 检测SD卡权限
val WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 1
// 相机权限
val CAMERA_REQUEST_CODE = 2
// 电话权限
val CALL_PHONE_REQUEST_CODE = 3
// READ_PHONE_STATE
val READ_PHONE_STATE = 4
// 精准定位服务
val ACCESS_FINE_LOCATION = 5
// 大致定位服务
val ACCESS_COARSE_LOCATION = 6
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
ActivityManager.getInstance().addActivity(this)
beforeInit()
if (getContentViewLayoutID() != 0) {
setContentView(getContentViewLayoutID())
}
//绑定activity
ButterKnife.bind( this ) ;
initView(savedInstanceState)
}
override fun onDestroy() {
super.onDestroy()
ActivityManager.getInstance().popOneActivity(this)
}
/**
* 界面初始化前期准备
*/
protected fun beforeInit() {}
/**
* 获取布局ID
* @return 布局id
*/
abstract protected fun getContentViewLayoutID(): Int
/**
* 初始化布局以及View控件
*/
protected abstract fun initView(savedInstanceState: Bundle?)
/**
* 申请对应的权限
*/
protected fun doesNeedCheckoutPermission(requestCode: Int): Boolean {
if (Build.VERSION.SDK_INT >= 23) {
// 申请WRITE_EXTERNAL_STORAGE权限
if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST_CODE && ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
// 申请WRITE_EXTERNAL_STORAGE权限
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), WRITE_EXTERNAL_STORAGE_REQUEST_CODE)
} else if (requestCode == CAMERA_REQUEST_CODE && ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
// 申请CAMERA权限
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), CAMERA_REQUEST_CODE)
} else if (requestCode == CALL_PHONE_REQUEST_CODE && ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// 申请电话权限
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CALL_PHONE), CALL_PHONE_REQUEST_CODE)
} else if (requestCode == READ_PHONE_STATE && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
// 申请READ_PHONE_STATE权限
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_PHONE_STATE), READ_PHONE_STATE)
} else if (requestCode == ACCESS_FINE_LOCATION && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// 申请精准定位服务
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), ACCESS_FINE_LOCATION)
} else if (requestCode == ACCESS_COARSE_LOCATION && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// 申请大致定位服务
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION), ACCESS_COARSE_LOCATION)
} else {
return false
}
return true
} else {
// Pre-Marshmallow
return false
}
}
/**
* 是否具有某种权限
* @param requestCode
* *
* @return
*/
protected fun doesHaveCheckoutPermission(requestCode: Int): Boolean {
if (Build.VERSION.SDK_INT >= 23) {
if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST_CODE && ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
} else if (requestCode == CAMERA_REQUEST_CODE && ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
} else if (requestCode == CALL_PHONE_REQUEST_CODE && ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
} else if (requestCode == READ_PHONE_STATE && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
} else if (requestCode == ACCESS_FINE_LOCATION && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
} else if (requestCode == ACCESS_COARSE_LOCATION && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
} else {
return false
}
return true
} else {
// Pre-Marshmallow
return false
}
}
/**
* 是否需要申请SD卡权限
* @return
*/
protected fun doesNeedCheckoutPermissionWriteExternalStorage(): Boolean {
return doesNeedCheckoutPermission(WRITE_EXTERNAL_STORAGE_REQUEST_CODE)
}
/**
* 是否需要申请相机权限
* @return
*/
protected fun doesNeedCheckoutPermissionCamera(): Boolean {
return doesNeedCheckoutPermission(CAMERA_REQUEST_CODE)
}
/**
* 是否需要申请READ_PHONE_STATE权限
* @return
*/
protected fun doesNeedCheckoutPermissionPhotoState(): Boolean {
return doesNeedCheckoutPermission(READ_PHONE_STATE)
}
/**
* 是否需要申请打电话权限
* @return
*/
protected fun doesNeedCheckoutPermissionCallPhone(): Boolean {
return doesNeedCheckoutPermission(CALL_PHONE_REQUEST_CODE)
}
/**
* 是否需要打开精准定位服务
* @return
*/
protected fun doesNeedCheckoutPermissionPreciseLocation(): Boolean {
return doesNeedCheckoutPermission(ACCESS_FINE_LOCATION)
}
/**
* 是否需要打开大致定位服务
* @return
*/
protected fun doesNeedCheckoutPermissionApproximateLocation(): Boolean {
return doesNeedCheckoutPermission(ACCESS_COARSE_LOCATION)
}
/**
* 是否具有大致定位服务
* @return
*/
protected fun doesHaveCheckoutPermissionApproximateLocation(): Boolean {
return doesHaveCheckoutPermission(ACCESS_COARSE_LOCATION)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
doRequestPermissionsNext(requestCode, grantResults)
}
/*
* 处理申请权限返回判断
*/
protected fun doRequestPermissionsNext(requestCode: Int, grantResults: IntArray) {
if (grantResults.size != 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission Granted 允许
onRequestPermissionsGranted(requestCode)
} else {
// Permission Denied 拒绝
onRequestPermissionsDenied(requestCode)
}
}
}
/**
* 申请权限同意返回的
* @param requestCode
* * 当前权限类型
*/
protected fun onRequestPermissionsGranted(requestCode: Int) {
toast(resources.getString(R.string.permission_ok))
}
/**
* 申请权限拒绝了返回的
* @param requestCode
* * 当前权限类型
*/
protected fun onRequestPermissionsDenied(requestCode: Int) {
showDeniedPermissionsAlert(requestCode)
}
/**
* 申请权限初次取消再次弹窗提示然后弹窗消失的时候的回调
* @param requestCode
*/
protected fun onRequestPermissionsDialogDismiss(requestCode: Int, goToSet: Boolean) {}
/**
* 申请权限拒绝之后的提醒对话框
* @param requestCode
*/
protected fun showDeniedPermissionsAlert(requestCode: Int) {
if (requestCode == 65543) {
return
}
var toastMessageRequest = ""
var toastMessage: String
// 申请WRITE_EXTERNAL_STORAGE权限
if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST_CODE) {
toastMessageRequest = resources.getString(R.string.request_write_external_storage)
} else if (requestCode == CAMERA_REQUEST_CODE) {
toastMessageRequest = resources.getString(R.string.request_camera)
} else if (requestCode == CALL_PHONE_REQUEST_CODE) {
toastMessageRequest = resources.getString(R.string.request_call_phone)
} else if (requestCode == ACCESS_FINE_LOCATION) {
toastMessageRequest = resources.getString(R.string.request_access_fine_location)
} else if (requestCode == ACCESS_COARSE_LOCATION) {
toastMessageRequest = resources.getString(R.string.request_access_fine_location)
} else if (requestCode == READ_PHONE_STATE) {
toastMessageRequest = resources.getString(R.string.request_read_phone)
} else {
return
}
toastMessage = String.format("%s%s%s%s%s%s", resources.getString(R.string.request_access_left), getApplicationName(), toastMessageRequest, resources.getString(R.string.request_access_right_1),
getApplicationName(), resources.getString(R.string.request_access_right_2))
alert(toastMessage, resources.getString(R.string.permission_need)) {
positiveButton(resources.getString(R.string.go_set)) {
gotoSetPermissions()
[email protected]()
onRequestPermissionsDialogDismiss(requestCode, true)
}
negativeButton(resources.getString(R.string.cancel)) {
[email protected]()
onRequestPermissionsDialogDismiss(requestCode, false)
doesNeedFinish()
}
}.show()
}
protected fun doesNeedFinish(){
}
/**
* 获取当前应用的名称
*/
protected fun getApplicationName(): String {
var packageManager: PackageManager? = null
var applicationInfo: ApplicationInfo? = null
try {
packageManager = applicationContext.packageManager
applicationInfo = packageManager!!.getApplicationInfo(packageName, 0)
} catch (e: PackageManager.NameNotFoundException) {
applicationInfo = null
}
val applicationName = packageManager!!.getApplicationLabel(applicationInfo) as String
return applicationName
}
/**
* 打开权限设置界面
*/
protected fun gotoSetPermissions() {
val intent = Intent(Settings.ACTION_APPLICATION_SETTINGS)
startActivity(intent)
}
override fun onBackPressed() {
super.onBackPressed()
[email protected]()
}
} | KLMLibrary/library/src/main/java/com/kalemao/library/base/BaseActivity.kt | 1565898607 |
package io.magnaura.server.storage
import io.magnaura.server.KeyValue
val CONTEXT_STORAGE = KeyValue<String>("Context") | server/src/io/magnaura/server/storage/context.kt | 3788887163 |
/*
Tickle
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.tickle
import org.joml.Matrix4f
import uk.co.nickthecoder.tickle.graphics.Renderer
import uk.co.nickthecoder.tickle.util.Rectd
import uk.co.nickthecoder.tickle.util.string
/**
* Tiles a single Pose to build an image of the required width and height.
* This is useful for creating rectangular objects that can have an arbitrary size, such as floors and walls
* as well as patterned backgrounds.
*
* Note that rendering is done by repeatedly drawing the Pose, so if the Pose is small compared to the Actor's size,
* then it will be somewhat slow. So if you want to tile a small pattern, consider making the Pose have multiple copies
* of the pattern.
*/
class TiledAppearance(actor: Actor, val pose: Pose) : ResizeAppearance(actor) {
override val directionRadians: Double
get() = pose.direction.radians
private val poseWidth = pose.rect.width
private val poseHeight = pose.rect.height
private val partPose = pose.copy()
init {
size.x = pose.rect.width.toDouble()
size.y = pose.rect.height.toDouble()
oldSize.set(size)
sizeAlignment.x = pose.offsetX / pose.rect.width
sizeAlignment.y = pose.offsetY / pose.rect.height
oldAlignment.set(sizeAlignment)
}
override fun draw(renderer: Renderer) {
//println("Drawing tiled")
val left = actor.x - sizeAlignment.x * width()
val bottom = actor.y - sizeAlignment.y * height()
val simple = actor.isSimpleImage()
val modelMatrix: Matrix4f?
if (!simple) {
modelMatrix = actor.calculateModelMatrix()
} else {
modelMatrix = null
}
// Draw all of the complete pieces (i.e. where the pose does not need clipping).
var y = 0.0
while (y < size.y - poseHeight) {
var x = 0.0
while (x < size.x - poseWidth) {
//println("Drawing whole part from ${pose.rect}")
drawPart(
renderer,
left + x, bottom + y, left + x + poseWidth, bottom + y + poseHeight,
pose.rectd,
modelMatrix)
x += poseWidth
}
y += poseHeight
}
val rightEdge = size.x - if (size.x % poseWidth == 0.0) poseWidth.toDouble() else size.x % poseWidth
val topEdge = y
val partWidth = size.x - rightEdge
val partHeight = size.y - topEdge
//println("Size.x = ${size.x} rightEdge = $rightEdge partWidth = ${partWidth} topEdge = ")
// Draw the partial pieces on the right edge
y = 0.0
partPose.rect.top = pose.rect.top
partPose.rect.right = (pose.rect.left + partWidth).toInt()
partPose.updateRectd()
while (y < size.y - poseHeight) {
//println("Drawing right edge from ${partPose.rect}")
drawPart(renderer,
left + rightEdge, bottom + y, left + size.x, bottom + y + poseHeight,
partPose.rectd,
modelMatrix)
y += poseHeight
}
// Draw the partial pieces on the top edge
var x = 0.0
partPose.rect.top = (pose.rect.bottom - partHeight).toInt()
partPose.rect.right = pose.rect.right
partPose.updateRectd()
while (x < size.x - poseWidth) {
//println("Drawing top edge from ${partPose.rect}")
drawPart(renderer,
left + x, bottom + topEdge, left + x + poseWidth, bottom + size.y,
partPose.rectd,
modelMatrix)
x += poseWidth
}
// Draw the partial piece in the top right corner
if (rightEdge < size.x && topEdge < size.y) {
partPose.rect.right = (pose.rect.left + partWidth).toInt()
partPose.rect.top = (pose.rect.bottom - partHeight).toInt()
partPose.updateRectd()
// println("Drawing corner from ${partPose.rect}")
drawPart(renderer,
left + rightEdge, bottom + topEdge, left + size.x, bottom + size.y,
partPose.rectd,
modelMatrix)
}
// println("Done tiled\n")
}
fun drawPart(renderer: Renderer, x0: Double, y0: Double, x1: Double, y1: Double, srcRect: Rectd, modelMatrix: Matrix4f?) {
if (modelMatrix == null) {
renderer.drawTexture(pose.texture, x0, y0, x1, y1, srcRect, actor.color)
} else {
renderer.drawTexture(pose.texture, x0, y0, x1, y1, srcRect, actor.color, modelMatrix)
}
}
override fun toString() = "TiledAppearance pose=$pose size=${size.string()}"
}
| tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/TiledAppearance.kt | 945129177 |
package com.fwdekker.randomness.fixedlength
import com.fwdekker.randomness.Bundle
import com.fwdekker.randomness.SchemeDecorator
/**
* Forces generated strings to be exactly [length] characters.
*
* @property enabled Whether to apply this decorator.
* @property length The enforced length.
* @property filler The character to pad strings that are too short with.
*/
data class FixedLengthDecorator(
var enabled: Boolean = DEFAULT_ENABLED,
var length: Int = DEFAULT_LENGTH,
var filler: String = DEFAULT_FILLER
) : SchemeDecorator() {
override val decorators: List<SchemeDecorator> = emptyList()
override val name = Bundle("fixed_length.title")
override fun generateUndecoratedStrings(count: Int): List<String> =
if (enabled) generator(count).map { it.take(length).padStart(length, filler[0]) }
else generator(count)
override fun doValidate() =
if (length < MIN_LENGTH) Bundle("fixed_length.error.length_too_low", MIN_LENGTH)
else if (filler.length != 1) Bundle("fixed_length.error.filler_length")
else null
override fun deepCopy(retainUuid: Boolean) = copy().also { if (retainUuid) it.uuid = this.uuid }
/**
* Holds constants.
*/
companion object {
/**
* The default value of the [enabled] field.
*/
const val DEFAULT_ENABLED = false
/**
* The minimum valid value of the [length] field.
*/
const val MIN_LENGTH = 1
/**
* The default value of the [length] field.
*/
const val DEFAULT_LENGTH = 3
/**
* The default value of the [filler] field.
*/
const val DEFAULT_FILLER = "0"
}
}
| src/main/kotlin/com/fwdekker/randomness/fixedlength/FixedLengthDecorator.kt | 984283913 |
package coil.util
import coil.ImageLoader
import coil.RealImageLoader
import coil.decode.BitmapFactoryDecoder.Companion.DEFAULT_MAX_PARALLELISM
import coil.decode.ExifOrientationPolicy
/**
* Private configuration options used by [RealImageLoader].
*
* @see ImageLoader.Builder
*/
internal class ImageLoaderOptions(
val addLastModifiedToFileCacheKey: Boolean = true,
val networkObserverEnabled: Boolean = true,
val respectCacheHeaders: Boolean = true,
val bitmapFactoryMaxParallelism: Int = DEFAULT_MAX_PARALLELISM,
val bitmapFactoryExifOrientationPolicy: ExifOrientationPolicy = ExifOrientationPolicy.RESPECT_PERFORMANCE
) {
fun copy(
addLastModifiedToFileCacheKey: Boolean = this.addLastModifiedToFileCacheKey,
networkObserverEnabled: Boolean = this.networkObserverEnabled,
respectCacheHeaders: Boolean = this.respectCacheHeaders,
bitmapFactoryMaxParallelism: Int = this.bitmapFactoryMaxParallelism,
bitmapFactoryExifOrientationPolicy: ExifOrientationPolicy = this.bitmapFactoryExifOrientationPolicy,
) = ImageLoaderOptions(
addLastModifiedToFileCacheKey,
networkObserverEnabled,
respectCacheHeaders,
bitmapFactoryMaxParallelism,
bitmapFactoryExifOrientationPolicy
)
}
| coil-base/src/main/java/coil/util/ImageLoaderOptions.kt | 2920691690 |
package com.bracketcove.postrainer.settings
/**
* Created by Ryan on 05/03/2017.
*/
class SettingsPresenter
constructor(private val view: SettingsContract.View) {
fun start() {
}
fun stop() {
}
}
| app/src/main/java/com/bracketcove/postrainer/settings/SettingsPresenter.kt | 1943024056 |
package com.andrey7mel.realm_example.view.fragments.realm_list
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.andrey7mel.realm_example.App
import com.andrey7mel.realm_example.R
import com.andrey7mel.realm_example.presenter.RealmResultsPresenter
import kotlinx.android.synthetic.main.list_fragment.*
import javax.inject.Inject
class RealmListFragment : Fragment() {
@Inject
lateinit var presenter: RealmResultsPresenter
private var adapter: RealmListAdapter? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.list_fragment, container, false)
(activity.application as App).component.inject(this)
return view
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fab.setOnClickListener { presenter.addObject() }
presenter.onCreate()
adapter = RealmListAdapter(presenter.getObjects(), presenter)
recycler_view.layoutManager = LinearLayoutManager(context)
recycler_view.adapter = adapter
type.text = "Type: RealmListFragment"
empty.visibility = View.GONE
}
override fun onDestroyView() {
super.onDestroyView()
presenter.onDestroy()
}
}
| app/src/main/java/com/andrey7mel/realm_example/view/fragments/realm_list/RealmListFragment.kt | 677994597 |
package de.maibornwolff.codecharta.importer.sourcecodeparser.metrics
class ProjectMetrics {
val projectMetrics = mutableMapOf<String, FileMetricMap>()
// TODO remove because it is only used in tests
fun addFile(file: String): ProjectMetrics {
projectMetrics[file] = FileMetricMap()
return this
}
// TODO remove because it is only used in tests
fun addMetricToFile(file: String, metric: String, value: Number) {
projectMetrics[file]?.add(metric, value)
}
fun addFileMetricMap(file: String, fileMetricMap: FileMetricMap) {
projectMetrics[file] = fileMetricMap
}
fun getFileMetricMap(file: String): FileMetricMap? {
return projectMetrics[file]
}
fun merge(newProjectMetrics: ProjectMetrics): ProjectMetrics {
projectMetrics.putAll(newProjectMetrics.projectMetrics)
return this
}
fun getRandomFileName(): String? {
if (this.projectMetrics.isEmpty()) return null
return this.projectMetrics.keys.iterator().next()
}
}
| analysis/import/SourceCodeParser/src/main/kotlin/de/maibornwolff/codecharta/importer/sourcecodeparser/metrics/ProjectMetrics.kt | 852408355 |
package de.maibornwolff.codecharta.importer.svnlogparser.input.metrics
import de.maibornwolff.codecharta.importer.svnlogparser.input.Commit
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import java.time.OffsetDateTime
import java.time.ZoneOffset
class SuccessiveWeeksWithCommitsTest {
private val zoneOffset = ZoneOffset.UTC
@Test
fun initial_value_zero() {
// when
val metric = SuccessiveWeeksWithCommits()
// then
assertThat(metric.value()).isEqualTo(0)
}
@Test
fun single_modification() {
// given
val metric = SuccessiveWeeksWithCommits()
// when
val date = OffsetDateTime.of(2016, 4, 2, 12, 0, 0, 0, zoneOffset)
metric.registerCommit(Commit("author", emptyList(), date))
// then
assertThat(metric.value()).isEqualTo(1)
}
@Test
fun additional_modification_in_same_calendar_week() {
// given
val metric = SuccessiveWeeksWithCommits()
// when
val date1 = OffsetDateTime.of(2016, 4, 2, 12, 0, 0, 0, zoneOffset)
metric.registerCommit(Commit("author", emptyList(), date1))
val date2 = OffsetDateTime.of(2016, 4, 3, 12, 0, 0, 0, zoneOffset)
metric.registerCommit(Commit("author", emptyList(), date2))
// then
assertThat(metric.value()).isEqualTo(1)
}
@Test
fun additional_modification_in_successive_calendar_week() {
// given
val metric = SuccessiveWeeksWithCommits()
// when
val date1 = OffsetDateTime.of(2016, 4, 3, 12, 0, 0, 0, zoneOffset)
metric.registerCommit(Commit("author", emptyList(), date1))
val date2 = OffsetDateTime.of(2016, 4, 4, 12, 0, 0, 0, zoneOffset)
metric.registerCommit(Commit("author", emptyList(), date2))
// then
assertThat(metric.value()).isEqualTo(2)
}
@Test
fun additional_modification_in_non_successive_calendar_week() {
// given
val metric = SuccessiveWeeksWithCommits()
// when
val date1 = OffsetDateTime.of(2016, 4, 3, 12, 0, 0, 0, zoneOffset)
metric.registerCommit(Commit("author", emptyList(), date1))
val date2 = OffsetDateTime.of(2016, 4, 11, 12, 0, 0, 0, zoneOffset)
metric.registerCommit(Commit("author", emptyList(), date2))
// then
assertThat(metric.value()).isEqualTo(1)
}
}
| analysis/import/SVNLogParser/src/test/kotlin/de/maibornwolff/codecharta/importer/svnlogparser/input/metrics/SuccessiveWeeksWithCommitsTest.kt | 3239183504 |
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.undertale.textbox.characters
import dev.kord.rest.builder.component.SelectMenuBuilder
import net.perfectdreams.i18nhelper.core.I18nContext
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.undertale.declarations.UndertaleCommand
object UndertaleSans : CharacterData() {
override fun menuOptions(i18nContext: I18nContext, activePortrait: String, builder: SelectMenuBuilder) {
builder.optionAndAutomaticallySetDefault(i18nContext.get(UndertaleCommand.I18N_TEXTBOX_PREFIX.Portraits.Neutral), "undertale/sans/neutral", activePortrait)
builder.optionAndAutomaticallySetDefault(i18nContext.get(UndertaleCommand.I18N_TEXTBOX_PREFIX.Portraits.BlueEye), "undertale/sans/blue_eye", activePortrait)
builder.optionAndAutomaticallySetDefault(i18nContext.get(UndertaleCommand.I18N_TEXTBOX_PREFIX.Portraits.YellowEye), "undertale/sans/yellow_eye", activePortrait)
builder.optionAndAutomaticallySetDefault(i18nContext.get(UndertaleCommand.I18N_TEXTBOX_PREFIX.Portraits.ClosedEyes), "undertale/sans/closed_eyes", activePortrait)
builder.optionAndAutomaticallySetDefault(i18nContext.get(UndertaleCommand.I18N_TEXTBOX_PREFIX.Portraits.Confused), "undertale/sans/confused", activePortrait)
builder.optionAndAutomaticallySetDefault(i18nContext.get(UndertaleCommand.I18N_TEXTBOX_PREFIX.Portraits.Chuckling), "undertale/sans/chuckling", activePortrait)
builder.optionAndAutomaticallySetDefault(i18nContext.get(UndertaleCommand.I18N_TEXTBOX_PREFIX.Portraits.Hurt), "undertale/sans/hurt", activePortrait)
builder.optionAndAutomaticallySetDefault(i18nContext.get(UndertaleCommand.I18N_TEXTBOX_PREFIX.Portraits.LookingAway), "undertale/sans/looking_away", activePortrait)
builder.optionAndAutomaticallySetDefault(i18nContext.get(UndertaleCommand.I18N_TEXTBOX_PREFIX.Portraits.LookingDown), "undertale/sans/looking_down", activePortrait)
builder.optionAndAutomaticallySetDefault(i18nContext.get(UndertaleCommand.I18N_TEXTBOX_PREFIX.Portraits.NoEyes), "undertale/sans/no_eyes", activePortrait)
builder.optionAndAutomaticallySetDefault(i18nContext.get(UndertaleCommand.I18N_TEXTBOX_PREFIX.Portraits.SemiClosedEyes), "undertale/sans/semi_closed_eyes", activePortrait)
builder.optionAndAutomaticallySetDefault(i18nContext.get(UndertaleCommand.I18N_TEXTBOX_PREFIX.Portraits.Wink), "undertale/sans/wink", activePortrait)
builder.optionAndAutomaticallySetDefault(i18nContext.get(UndertaleCommand.I18N_TEXTBOX_PREFIX.Portraits.BleedingClosedEyes), "undertale/sans/bleeding_closed_eyes", activePortrait)
builder.optionAndAutomaticallySetDefault(i18nContext.get(UndertaleCommand.I18N_TEXTBOX_PREFIX.Portraits.BleedingConfused), "undertale/sans/bleeding_confused", activePortrait)
builder.optionAndAutomaticallySetDefault(i18nContext.get(UndertaleCommand.I18N_TEXTBOX_PREFIX.Portraits.BleedingChuckling), "undertale/sans/bleeding_chuckling", activePortrait)
builder.optionAndAutomaticallySetDefault(i18nContext.get(UndertaleCommand.I18N_TEXTBOX_PREFIX.Portraits.BleedingLookingDown), "undertale/sans/bleeding_looking_down", activePortrait)
builder.optionAndAutomaticallySetDefault(i18nContext.get(UndertaleCommand.I18N_TEXTBOX_PREFIX.Portraits.BleedingNeutral), "undertale/sans/bleeding_neutral", activePortrait)
builder.optionAndAutomaticallySetDefault(i18nContext.get(UndertaleCommand.I18N_TEXTBOX_PREFIX.Portraits.BleedingWink), "undertale/sans/bleeding_wink", activePortrait)
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/undertale/textbox/characters/UndertaleSans.kt | 945616123 |
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.transactions.transactiontransformers
import net.perfectdreams.i18nhelper.core.I18nContext
import net.perfectdreams.loritta.common.utils.WebsiteVoteSource
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.declarations.SonhosCommand
import net.perfectdreams.loritta.cinnamon.pudding.data.BotVoteSonhosTransaction
import net.perfectdreams.loritta.cinnamon.pudding.data.CachedUserInfo
import net.perfectdreams.loritta.cinnamon.pudding.data.UserId
object BotVoteTransactionTransformer : SonhosTransactionTransformer<BotVoteSonhosTransaction> {
override suspend fun transform(
loritta: LorittaBot,
i18nContext: I18nContext,
cachedUserInfo: CachedUserInfo,
cachedUserInfos: MutableMap<UserId, CachedUserInfo?>,
transaction: BotVoteSonhosTransaction
): suspend StringBuilder.() -> (Unit) = {
when (transaction.websiteSource) {
WebsiteVoteSource.TOP_GG -> {
appendMoneyEarnedEmoji()
append(
i18nContext.get(
SonhosCommand.TRANSACTIONS_I18N_PREFIX.Types.BotVote.TopGg(transaction.sonhos)
)
)
}
}
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/economy/transactions/transactiontransformers/BotVoteTransactionTransformer.kt | 2738061926 |
package com.rartworks.engine.android.services.integrations
import android.app.Activity
import android.content.Intent
import android.view.ViewGroup
/**
* A generic integration with the [app].
*/
abstract class Integration(protected val app : Activity) {
open fun onCreating(layout: ViewGroup) { }
open fun onCreated() { }
open fun onStart() { }
open fun onStop() { }
open fun onDestroy() { }
open fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { }
}
| android/src/com/rartworks/engine/android/services/integrations/Integration.kt | 2497732991 |
package be.digitalia.fosdem.db.entities
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Fts4
import androidx.room.PrimaryKey
@Fts4
@Entity(tableName = EventTitles.TABLE_NAME)
class EventTitles(
@PrimaryKey
@ColumnInfo(name = "rowid")
val id: Long,
val title: String?,
@ColumnInfo(name = "subtitle")
val subTitle: String?
) {
companion object {
const val TABLE_NAME = "events_titles"
}
} | app/src/main/java/be/digitalia/fosdem/db/entities/EventTitles.kt | 967439954 |
package io.tronalddump.app.search
import io.swagger.v3.oas.annotations.Operation
import io.tronalddump.app.Url
import io.tronalddump.app.exception.EntityNotFoundException
import io.tronalddump.app.quote.QuoteEntity
import io.tronalddump.app.quote.QuoteRepository
import io.tronalddump.app.tag.TagRepository
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Pageable
import org.springframework.hateoas.MediaTypes
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.*
import org.springframework.web.server.ResponseStatusException
import org.springframework.web.servlet.ModelAndView
@RequestMapping(value = [Url.SEARCH])
@RestController
class SearchController(
private val assembler: PageModelAssembler,
private val quoteRepository: QuoteRepository,
private val tagRepository: TagRepository
) {
@Operation(summary = "Search quotes by query or tags", tags = ["quote"])
@ResponseBody
@RequestMapping(
headers = [
"${HttpHeaders.ACCEPT}=${MediaType.APPLICATION_JSON_VALUE}",
"${HttpHeaders.ACCEPT}=${MediaType.TEXT_HTML_VALUE}",
"${HttpHeaders.ACCEPT}=${MediaTypes.HAL_JSON_VALUE}"
],
method = [RequestMethod.GET],
produces = [
MediaType.APPLICATION_JSON_VALUE,
MediaType.TEXT_HTML_VALUE
],
value = ["/quote"]
)
fun quote(
@RequestHeader(HttpHeaders.ACCEPT) acceptHeader: String,
@RequestParam("query", required = false, defaultValue = "") query: String,
@RequestParam("tag", required = false, defaultValue = "") tag: String,
@RequestParam(value = "page", defaultValue = "0") pageNumber: Int
): Any {
val page: Pageable = PageRequest.of(pageNumber, 10)
if (query.isNotEmpty()) {
val result: Page<QuoteEntity> = quoteRepository.findByValueIgnoreCaseContaining(query, page)
val model: PageModel = assembler.toModel(result)
val linkBuilder: WebMvcLinkBuilder = linkTo(this::class.java)
model.add(linkBuilder.slash("quote/?query=${query}&page=${pageNumber}").withSelfRel())
model.add(linkBuilder.slash("quote/?query=${query}&page=${page.first().pageNumber}").withRel("first"))
model.add(linkBuilder.slash("quote/?query=${query}&page=${page.previousOrFirst().pageNumber}").withRel("prev"))
model.add(linkBuilder.slash("quote/?query=${query}&page=${page.next().pageNumber}").withRel("next"))
model.add(linkBuilder.slash("quote/?query=${query}&page=${result.totalPages}").withRel("last"))
if (acceptHeader.contains(MediaType.TEXT_HTML_VALUE)) {
return ModelAndView("search")
.addObject("model", model)
.addObject("query", query)
.addObject("result", result)
}
return model
}
if (tag.isNotEmpty()) {
val entity = tagRepository.findByValue(tag).orElseThrow {
EntityNotFoundException("Tag with value \"$tag\" not found.")
}
val result: Page<QuoteEntity> = quoteRepository.findByTagsEquals(entity, page)
val model: PageModel = assembler.toModel(result)
val linkBuilder: WebMvcLinkBuilder = linkTo(this::class.java)
model.add(linkBuilder.slash("quote/?tag=${tag}&page=${pageNumber}").withSelfRel())
model.add(linkBuilder.slash("quote/?tag=${tag}&page=${page.first().pageNumber}").withRel("first"))
model.add(linkBuilder.slash("quote/?tag=${tag}&page=${page.previousOrFirst().pageNumber}").withRel("prev"))
model.add(linkBuilder.slash("quote/?tag=${tag}&page=${page.next().pageNumber}").withRel("next"))
model.add(linkBuilder.slash("quote/?tag=${tag}&page=${result.totalPages}").withRel("last"))
return model
}
throw ResponseStatusException(
HttpStatus.BAD_REQUEST,
"Either a query or tag parameter must be provided"
)
}
}
| src/main/kotlin/io/tronalddump/app/search/SearchController.kt | 2900565146 |
package io.kotest.matchers.uri
import io.kotest.matchers.Matcher
import io.kotest.matchers.MatcherResult
import io.kotest.matchers.should
import io.kotest.matchers.shouldNot
import java.net.URI
fun URI.shouldBeOpaque() = this should beOpaque()
fun URI.shouldNotBeOpaque() = this shouldNot beOpaque()
fun beOpaque() = object : Matcher<URI> {
override fun test(value: URI) = MatcherResult(
value.isOpaque,
"Uri $value should be opaque",
"Uri $value should not be opaque"
)
}
infix fun URI.shouldHaveScheme(scheme: String) = this should haveScheme(scheme)
infix fun URI.shouldNotHaveScheme(scheme: String) = this shouldNot haveScheme(scheme)
fun haveScheme(scheme: String) = object : Matcher<URI> {
override fun test(value: URI) = MatcherResult(
value.scheme == scheme,
"Uri $value should have scheme $scheme but was ${value.scheme}",
"Uri $value should not have scheme $scheme"
)
}
infix fun URI.shouldHavePort(port: Int) = this should havePort(port)
infix fun URI.shouldNotHavePort(port: Int) = this shouldNot havePort(port)
fun havePort(port: Int) = object : Matcher<URI> {
override fun test(value: URI) = MatcherResult(
value.port == port,
"Uri $value should have port $port but was ${value.port}",
"Uri $value should not have port $port"
)
}
infix fun URI.shouldHaveHost(host: String) = this should haveHost(host)
infix fun URI.shouldNotHaveHost(host: String) = this shouldNot haveHost(host)
fun haveHost(host: String) = object : Matcher<URI> {
override fun test(value: URI) = MatcherResult(
value.host == host,
"Uri $value should have host $host but was ${value.host}",
"Uri $value should not have host $host"
)
}
infix fun URI.shouldHaveQuery(q: String) = this should haveQuery(q)
infix fun URI.shouldNotHaveQuery(q: String) = this shouldNot haveQuery(q)
fun haveQuery(q: String) = object : Matcher<URI> {
override fun test(value: URI) = MatcherResult(
value.query == q,
"Uri $value should have query $q but was ${value.query}",
"Uri $value should not have query $q"
)
}
infix fun URI.shouldHaveAuthority(authority: String) = this should haveAuthority(authority)
infix fun URI.shouldNotHaveAuthority(authority: String) = this shouldNot haveAuthority(authority)
fun haveAuthority(authority: String) = object : Matcher<URI> {
override fun test(value: URI) = MatcherResult(
value.authority == authority,
"Uri $value should have authority $authority but was ${value.authority}",
"Uri $value should not have authority $authority"
)
}
infix fun URI.shouldHavePath(path: String) = this should havePath(path)
infix fun URI.shouldNotHavePath(path: String) = this shouldNot havePath(path)
fun havePath(path: String) = object : Matcher<URI> {
override fun test(value: URI) = MatcherResult(
value.path == path,
"Uri $value should have path $path but was ${value.path}",
"Uri $value should not have path $path"
)
}
infix fun URI.shouldHaveParameter(key: String) = this should haveParameter(key)
infix fun URI.shouldNotHaveParameter(key: String) = this shouldNot haveParameter(key)
fun haveParameter(key: String) = object : Matcher<URI> {
override fun test(value: URI) = MatcherResult(
value.query.split("&").any { it.split("=").first() == key },
"Uri $value should have query parameter $key",
"Uri $value should not have query parameter $key"
)
}
infix fun URI.shouldHaveFragment(fragment: String) = this should haveFragment(fragment)
infix fun URI.shouldNotHaveFragment(fragment: String) = this shouldNot haveFragment(fragment)
fun haveFragment(fragment: String) = object : Matcher<URI> {
override fun test(value: URI) = MatcherResult(
value.fragment == fragment,
"Uri $value should have fragment $fragment",
"Uri $value should not fragment $fragment"
)
}
| kotest-assertions/src/jvmMain/kotlin/io/kotest/matchers/uri/matchers.kt | 693912724 |
package melquelolea.vefexchange.models
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
class DolarToday {
@SerializedName("USD")
@Expose
var usd: USD = USD()
}
| mobile/src/main/java/melquelolea/vefexchange/models/DolarToday.kt | 3551108967 |
package io.kotest.property.arbitrary
import io.kotest.property.Shrinker
/**
* Returns an [Arb] where each generated value is a map, with the entries of the map
* drawn from the given pair generating arb. The size of each
* generated map is a random value between the specified min and max bounds.
*
* There are no edgecases.
*
* This arbitrary uses a [Shrinker] which will reduce the size of a failing map by
* removing elements from the failed case until it is empty.
*
* @see MapShrinker
*/
fun <K, V> Arb.Companion.map(
arb: Arb<Pair<K, V>>,
minSize: Int = 1,
maxSize: Int = 100
): Arb<Map<K, V>> = arb(MapShrinker()) { random ->
val size = random.random.nextInt(minSize, maxSize)
val pairs = List(size) { arb.single(random) }
pairs.toMap()
}
/**
* Returns an [Arb] where each generated value is a map, with the entries of the map
* drawn by combining values from the key gen and value gen. The size of each
* generated map is a random value between the specified min and max bounds.
*
* There are no edgecases.
*
* This arbitrary uses a [Shrinker] which will reduce the size of a failing map by
* removing elements until they map is empty.
*
* @see MapShrinker
*
*/
fun <K, V> Arb.Companion.map(
keyArb: Arb<K>,
valueArb: Arb<V>,
minSize: Int = 1,
maxSize: Int = 100
): Arb<Map<K, V>> {
require(minSize >= 0) { "minSize must be positive" }
require(maxSize >= 0) { "maxSize must be positive" }
return arb(MapShrinker()) { random ->
val size = random.random.nextInt(minSize, maxSize)
val pairs = List(size) {
keyArb.single(random) to valueArb.single(random)
}
pairs.toMap()
}
}
class MapShrinker<K, V> : Shrinker<Map<K, V>> {
override fun shrink(value: Map<K, V>): List<Map<K, V>> {
return when (value.size) {
0 -> emptyList()
1 -> listOf(emptyMap())
else -> listOf(
value.toList().take(value.size / 2).toMap(),
value.toList().drop(1).toMap()
)
}
}
}
fun <K, V> Arb.Companion.pair(k: Arb<K>, v: Arb<V>) = arb {
k.single(it) to v.single(it)
}
| kotest-property/src/commonMain/kotlin/io/kotest/property/arbitrary/maps.kt | 1620694054 |
package se.ansman.kotshi.kapt
import com.google.auto.service.AutoService
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableSetMultimap
import com.google.common.collect.Multimaps
import com.google.common.collect.SetMultimap
import com.squareup.kotlinpoet.asClassName
import com.squareup.kotlinpoet.metadata.classinspectors.ElementsClassInspector
import net.ltgt.gradle.incap.IncrementalAnnotationProcessor
import net.ltgt.gradle.incap.IncrementalAnnotationProcessorType.AGGREGATING
import se.ansman.kotshi.Errors
import se.ansman.kotshi.Options
import se.ansman.kotshi.model.GeneratedAdapter
import se.ansman.kotshi.model.GeneratedAnnotation
import javax.annotation.processing.*
import javax.lang.model.SourceVersion
import javax.lang.model.element.Element
import javax.lang.model.element.TypeElement
import javax.lang.model.util.Elements
import javax.lang.model.util.Types
@AutoService(Processor::class)
@IncrementalAnnotationProcessor(AGGREGATING)
class KotshiProcessor : AbstractProcessor() {
private var createAnnotationsUsingConstructor: Boolean? = null
private var useLegacyDataClassRenderer: Boolean = false
private var generatedAnnotation: GeneratedAnnotation? = null
private lateinit var elements: Elements
private lateinit var types: Types
private lateinit var metadataAccessor: MetadataAccessor
private lateinit var steps: ImmutableList<out ProcessingStep>
override fun getSupportedSourceVersion(): SourceVersion = SourceVersion.latestSupported()
private fun initSteps(): Iterable<ProcessingStep> {
val adapters: MutableList<GeneratedAdapter> = mutableListOf()
return listOf(
AdaptersProcessingStep(
processor = this,
metadataAccessor = metadataAccessor,
messager = processingEnv.messager,
filer = processingEnv.filer,
adapters = adapters,
types = types,
elements = processingEnv.elementUtils,
generatedAnnotation = generatedAnnotation,
createAnnotationsUsingConstructor = createAnnotationsUsingConstructor,
useLegacyDataClassRenderer = useLegacyDataClassRenderer,
),
FactoryProcessingStep(
processor = this,
messager = processingEnv.messager,
filer = processingEnv.filer,
types = processingEnv.typeUtils,
elements = processingEnv.elementUtils,
generatedAnnotation = generatedAnnotation,
generatedAdapters = adapters,
metadataAccessor = metadataAccessor,
createAnnotationsUsingConstructor = createAnnotationsUsingConstructor,
)
)
}
@Synchronized
override fun init(processingEnv: ProcessingEnvironment) {
super.init(processingEnv)
createAnnotationsUsingConstructor = processingEnv.options[Options.createAnnotationsUsingConstructor]?.toBooleanStrict()
useLegacyDataClassRenderer = processingEnv.options[Options.useLegacyDataClassRenderer]?.toBooleanStrict() ?: useLegacyDataClassRenderer
generatedAnnotation = processingEnv.options[Options.generatedAnnotation]
?.let { name ->
Options.possibleGeneratedAnnotations[name] ?: run {
processingEnv.messager.logKotshiError(Errors.invalidGeneratedAnnotation(name), element = null)
null
}
}
?.let { GeneratedAnnotation(it, KotshiProcessor::class.asClassName()) }
elements = processingEnv.elementUtils
types = processingEnv.typeUtils
metadataAccessor = MetadataAccessor(ElementsClassInspector.create(elements, processingEnv.typeUtils))
steps = ImmutableList.copyOf(initSteps())
}
private fun getSupportedAnnotationClasses(): Set<Class<out Annotation>> =
steps.flatMapTo(mutableSetOf()) { it.annotations }
/**
* Returns the set of supported annotation types as a collected from registered
* [processing steps][ProcessingStep].
*/
override fun getSupportedAnnotationTypes(): Set<String> =
getSupportedAnnotationClasses().mapTo(mutableSetOf()) { it.canonicalName }
override fun getSupportedOptions(): Set<String> = setOf("kotshi.createAnnotationsUsingConstructor")
override fun process(annotations: Set<TypeElement>, roundEnv: RoundEnvironment): Boolean {
if (!roundEnv.processingOver()) {
process(validElements(roundEnv), roundEnv)
}
return false
}
private fun validElements(roundEnv: RoundEnvironment): ImmutableSetMultimap<Class<out Annotation>, Element> {
val validElements = ImmutableSetMultimap.builder<Class<out Annotation>, Element>()
for (annotationClass in getSupportedAnnotationClasses()) {
validElements.putAll(annotationClass, roundEnv.getElementsAnnotatedWith(annotationClass))
}
return validElements.build()
}
/** Processes the valid elements, including those previously deferred by each step. */
private fun process(validElements: ImmutableSetMultimap<Class<out Annotation>, Element>, roundEnv: RoundEnvironment) {
for (step in steps) {
val stepElements = Multimaps.filterKeys(validElements) { it in step.annotations }
if (!stepElements.isEmpty) {
step.process(stepElements, roundEnv)
}
}
}
interface ProcessingStep {
val annotations: Set<Class<out Annotation>>
fun process(elementsByAnnotation: SetMultimap<Class<out Annotation>, Element>, roundEnv: RoundEnvironment)
}
abstract class GeneratingProcessingStep : ProcessingStep {
protected abstract val filer: Filer
protected abstract val processor: KotshiProcessor
}
} | compiler/src/main/kotlin/se/ansman/kotshi/kapt/KotshiProcessor.kt | 305902990 |
package com.chrynan.sample.ui.adapter.core
import com.chrynan.aaaah.DiffDispatcher
import com.chrynan.aaaah.DiffProcessor
import com.chrynan.aaaah.DiffResult
import com.chrynan.sample.coroutine.CoroutineDispatchers
import com.chrynan.sample.viewmodel.AdapterItemViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import javax.inject.Inject
class BaseAdapterItemHandler<VM : AdapterItemViewModel> @Inject constructor(
private val diffProcessor: DiffProcessor<VM>,
private val diffDispatcher: DiffDispatcher<VM>,
private val coroutineDispatchers: CoroutineDispatchers
) : AdapterItemHandler<VM> {
@ExperimentalCoroutinesApi
override fun Flow<Collection<VM>>.calculateAndDispatchDiff(): Flow<DiffResult<VM>> =
map(diffProcessor::processDiff)
.flowOn(coroutineDispatchers.io)
.onEach { diffDispatcher.dispatchDiff(it) }
.flowOn(coroutineDispatchers.main)
} | sample/src/main/java/com/chrynan/sample/ui/adapter/core/BaseAdapterItemHandler.kt | 3738780854 |
/*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* 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 io.lumeer.core.adapter
import io.lumeer.api.model.ResourceType
import io.lumeer.storage.api.dao.ResourceCommentDao
class ResourceCommentAdapter(val resourceCommentDao: ResourceCommentDao) {
fun getCommentsCount(resourceType: ResourceType, resourceId: String): Long = resourceCommentDao.getCommentsCount(resourceType, resourceId)
fun getCommentsCounts(resourceType: ResourceType, resourceIds: Set<String>): Map<String, Int> = resourceCommentDao.getCommentsCounts(resourceType, resourceIds)
fun getCommentsCountsByParent(resourceType: ResourceType, parentId: String): Map<String, Int> = resourceCommentDao.getCommentsCounts(resourceType, parentId)
} | lumeer-core/src/main/kotlin/io/lumeer/core/adapter/ResourceCommentAdapter.kt | 3643713650 |
/*
* Copyright @ 2018 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.nlj.transform.node.outgoing
import io.kotest.core.spec.IsolationMode
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.core.test.TestCase
import io.kotest.matchers.shouldBe
import io.kotest.matchers.types.instanceOf
import org.jitsi.nlj.PacketInfo
import org.jitsi.nlj.format.RtxPayloadType
import org.jitsi.nlj.resources.logging.StdoutLogger
import org.jitsi.nlj.resources.node.onOutput
import org.jitsi.nlj.rtp.SsrcAssociationType
import org.jitsi.nlj.util.RemoteSsrcAssociation
import org.jitsi.nlj.util.StreamInformationStoreImpl
import org.jitsi.rtp.rtp.RtpPacket
class RetransmissionSenderTest : ShouldSpec() {
override fun isolationMode(): IsolationMode? = IsolationMode.InstancePerLeaf
private val originalPayloadType = 100
private val rtxPayloadType = 96
private val originalSsrc = 1234L
private val rtxSsrc = 5678L
private val streamInformationStore = StreamInformationStoreImpl()
// NOTE(brian): unfortunately i ran into issues trying to use mock frameworks to mock
// a packet, notably i ran into issues when trying to mock the byte[] property in
// the parent java class, mocking frameworks seem to struggle with this
private val dummyPacket = RtpPacket(ByteArray(1500), 0, 1500).apply {
version = 2
hasPadding = false
hasExtensions = false
isMarked = false
payloadType = originalPayloadType
sequenceNumber = 123
timestamp = 456L
ssrc = originalSsrc
}
private val dummyPacketInfo = PacketInfo(dummyPacket)
private val retransmissionSender = RetransmissionSender(streamInformationStore, StdoutLogger())
override suspend fun beforeTest(testCase: TestCase) {
super.beforeTest(testCase)
// Setup: add the rtx payload type and the rtx ssrc association
streamInformationStore.addRtpPayloadType(
RtxPayloadType(rtxPayloadType.toByte(), mapOf("apt" to originalPayloadType.toString()))
)
streamInformationStore.addSsrcAssociation(
RemoteSsrcAssociation(originalSsrc, rtxSsrc, SsrcAssociationType.RTX)
)
}
init {
context("retransmitting a packet") {
context("which has an associated rtx stream") {
should("rewrite the payload type and ssrc correctly") {
retransmissionSender.onOutput {
it.packet shouldBe instanceOf(RtpPacket::class)
it.packetAs<RtpPacket>().let { rtpPacket ->
rtpPacket.ssrc shouldBe rtxSsrc
rtpPacket.payloadType shouldBe rtxPayloadType
}
}
retransmissionSender.processPacket(dummyPacketInfo)
}
}
context("which does not have an associated rtx stream") {
val noRtxPacket = dummyPacket.clone().apply {
payloadType = 99
ssrc = 9876L
}
retransmissionSender.onOutput {
it.packetAs<RtpPacket>().let { rtpPacket ->
rtpPacket.ssrc shouldBe 9876L
rtpPacket.payloadType shouldBe 99
}
}
retransmissionSender.processPacket(PacketInfo(noRtxPacket))
}
}
}
}
| jitsi-media-transform/src/test/kotlin/org/jitsi/nlj/transform/node/outgoing/RetransmissionSenderTest.kt | 454315668 |
package com.cout970.magneticraft.api.internal.registries.fuel
import com.cout970.magneticraft.api.registries.fuel.IFluidFuel
import com.cout970.magneticraft.api.registries.fuel.IFluidFuelManager
import net.minecraftforge.fluids.FluidStack
import java.util.*
object FluidFuelManager : IFluidFuelManager {
/**
* This field determines if the mod should use it's own FluidFuelManager or use a wrapper around
* another fluid fuel provider like BuildcraftFuelRegistry.fuel
*
* This field is changed in preInit if buildcraft api is found, so all registrations must be done at init
*/
@JvmField
internal var FLUID_FUEL_MANAGER: IFluidFuelManager = FluidFuelManager
private val fuels = mutableListOf<IFluidFuel>()
override fun findFuel(fluidStack: FluidStack): IFluidFuel? = fuels.firstOrNull { it.matches(fluidStack) }
override fun getFuels(): MutableList<IFluidFuel> = Collections.unmodifiableList(fuels)
override fun registerFuel(recipe: IFluidFuel): Boolean {
if (findFuel(recipe.fluid) != null) return false
if (recipe.totalBurningTime <= 0.0) return false
if (recipe.powerPerCycle <= 0.0) return false
fuels += recipe
return true
}
override fun removeFuel(recipe: IFluidFuel): Boolean = fuels.remove(recipe)
override fun createFuel(fluidStack: FluidStack, burningTime: Int, powerPerCycle: Double): IFluidFuel {
return FluidFuel(fluidStack, burningTime, powerPerCycle)
}
} | src/main/kotlin/com/cout970/magneticraft/api/internal/registries/fuel/FluidFuelManager.kt | 2216843223 |
package de.ph1b.audiobook.data.repo
import de.ph1b.audiobook.data.Chapter2
import de.ph1b.audiobook.data.repo.internals.dao.Chapter2Dao
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import timber.log.Timber
import java.time.Instant
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ChapterRepo
@Inject constructor(
private val dao: Chapter2Dao
) {
private val cache = mutableMapOf<Chapter2.Id, Chapter2?>()
private val _chapterChanged = MutableSharedFlow<Chapter2.Id>()
val chapterChanged: Flow<Chapter2.Id> get() = _chapterChanged
suspend fun get(id: Chapter2.Id, lastModified: Instant? = null): Chapter2? {
if (!cache.containsKey(id)) {
cache[id] = dao.chapter(id).also {
Timber.d("Chapter for $id wasn't in the map, fetched $it")
}
}
return cache[id]?.takeIf {
lastModified == null || it.fileLastModified == lastModified
}
}
suspend fun put(chapter: Chapter2) {
dao.insert(chapter)
val oldChapter = cache[chapter.id]
cache[chapter.id] = chapter
if (oldChapter != chapter) {
_chapterChanged.emit(chapter.id)
}
}
suspend inline fun getOrPut(id: Chapter2.Id, lastModified: Instant, defaultValue: () -> Chapter2?): Chapter2? {
return get(id, lastModified)
?: defaultValue()?.also { put(it) }
}
}
| data/src/main/kotlin/de/ph1b/audiobook/data/repo/ChapterRepo.kt | 1803936358 |
/**
* Wire
* Copyright (C) 2018 Wire Swiss GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.waz.zclient.markdown.utils
import org.commonmark.internal.renderer.text.ListHolder
import org.commonmark.internal.renderer.text.OrderedListHolder
import org.commonmark.node.*
/**
* Helper extention properties and methods.
*/
/**
* The paragraph node is the root or the direct child of a Document node.
*/
val Paragraph.isOuterMost: Boolean get() = parent is Document?
/**
* The block quote's direct parent is also a BlockQuote node.
*/
val BlockQuote.isNested: Boolean get() = parent is BlockQuote
/**
* The block quote node is the root or the direct child of a Document node.
*/
val BlockQuote.isOuterMost: Boolean get() = parent is Document?
/**
* The number of parents of this list holder.
*/
val ListHolder.depth: Int get() {
var depth = 0
var next = parent
while (next != null) { depth++; next = next.parent }
return depth
}
/**
* True if the list holder has no parents.
*/
val ListHolder.isRoot: Boolean get() = depth == 0
/**
* The number of direct children of this node.
*/
val Node.numberOfChildren: Int get() {
var count = 0
var child: Node? = firstChild
while (child != null) { count++; child = child.next }
return count
}
/**
* Returns true if the list item contains a line break. If `includeSoft` is true,
* soft line breaks will be considered.
*/
fun ListItem.hasLineBreak(includeSoft: Boolean = false): Boolean {
// the sole child of a list item is a paragraph
var node = firstChild
if (node !is Paragraph) return false
// iterate through children of paragraph
node = node.firstChild
while (node != null) {
// return true on first occurence of line break
if (node is HardLineBreak || (includeSoft && node is SoftLineBreak)) return true
node = node.next
}
return false
}
/**
* The number of items in this list. Note, this assumes that each item is a direct child
* of this node.
*/
val OrderedList.numberOfItems: Int get() = numberOfChildren
/**
* The prefix number of the last item in the list.
*/
val OrderedList.largestPrefix: Int get() = startNumber + numberOfItems - 1
/**
* The number of digits in this number.
*/
val Int.numberOfDigits: Int get() {
var e = 1
while (this.toDouble() >= Math.pow(10.0, e.toDouble())) e++
return e
}
| app/src/main/java/com/waz/zclient/markdown/utils/Extensions.kt | 3834592938 |
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.support
import org.gradle.api.Project
import org.gradle.api.initialization.Settings
import org.gradle.api.invocation.Gradle
import org.gradle.kotlin.dsl.KotlinBuildScript
import org.gradle.kotlin.dsl.KotlinInitScript
import org.gradle.kotlin.dsl.KotlinSettingsScript
import org.gradle.kotlin.dsl.ScriptHandlerScope
/**
* Base class for `buildscript` block evaluation on scripts targeting Project.
*/
abstract class KotlinBuildscriptBlock(host: KotlinScriptHost<Project>) : KotlinBuildScript(host) {
/**
* Configures the build script classpath for this project.
*
* @see [Project.buildscript]
*/
override fun buildscript(block: ScriptHandlerScope.() -> Unit) {
buildscript.configureWith(block)
}
}
/**
* Base class for `buildscript` block evaluation on scripts targeting Settings.
*/
abstract class KotlinSettingsBuildscriptBlock(host: KotlinScriptHost<Settings>) : KotlinSettingsScript(host) {
/**
* Configures the build script classpath for settings.
*
* @see [Settings.buildscript]
*/
override fun buildscript(block: ScriptHandlerScope.() -> Unit) {
buildscript.configureWith(block)
}
}
/**
* Base class for `initscript` block evaluation on scripts targeting Gradle.
*/
abstract class KotlinInitscriptBlock(host: KotlinScriptHost<Gradle>) : KotlinInitScript(host) {
/**
* Configures the classpath of the init script.
*/
override fun initscript(block: ScriptHandlerScope.() -> Unit) {
initscript.configureWith(block)
}
}
| subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/support/KotlinBuildscriptBlock.kt | 292116136 |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.samples.litho.kotlin.documentation
import com.facebook.litho.ClickEvent
import com.facebook.litho.annotations.OnEvent
import com.facebook.litho.sections.Children
import com.facebook.litho.sections.SectionContext
import com.facebook.litho.sections.annotations.GroupSectionSpec
import com.facebook.litho.sections.annotations.OnCreateChildren
import com.facebook.litho.sections.common.SingleComponentSection
import com.facebook.litho.widget.Text
// start_example
@GroupSectionSpec
object EventHandlerSectionSpec {
@OnCreateChildren
fun onCreateChildren(c: SectionContext): Children =
Children.create()
.child(
SingleComponentSection.create(c)
.component(
Text.create(c)
.text("Say Hello")
.clickHandler(EventHandlerSection.onClick(c))
.build()))
.build()
@OnEvent(ClickEvent::class)
fun onClick(c: SectionContext) {
println("Hello World!")
}
}
// end_example
| sample/src/main/java/com/facebook/samples/litho/kotlin/documentation/EventHandlerSectionSpec.kt | 1208109090 |
package com.wenhaiz.himusic.module.artist.detail
import com.wenhaiz.himusic.data.LoadArtistDetailCallback
import com.wenhaiz.himusic.data.LoadArtistHotSongsCallback
import com.wenhaiz.himusic.data.MusicRepository
import com.wenhaiz.himusic.data.bean.Artist
import com.wenhaiz.himusic.data.bean.Song
internal class ArtistDetailPresenter(val view: ArtistDetailContract.View) : ArtistDetailContract.Presenter {
private val musicRepository: MusicRepository = MusicRepository.getInstance(view.getViewContext())
init {
view.setPresenter(this)
}
override fun loadArtistHotSongs(artist: Artist, page: Int) {
musicRepository.loadArtistHotSongs(artist, page, object : LoadArtistHotSongsCallback {
override fun onStart() {
}
override fun onFailure(msg: String) {
view.onFailure(msg)
}
override fun onSuccess(hotSongs: List<Song>) {
if (hotSongs.isNotEmpty()) {
view.onHotSongsLoad(hotSongs)
}
}
})
}
override fun loadArtistDetail(artist: Artist) {
musicRepository.loadArtistDetail(artist, object : LoadArtistDetailCallback {
override fun onStart() {
}
override fun onFailure(msg: String) {
view.onFailure(msg)
}
override fun onSuccess(artistDetail: Artist) {
view.onArtistDetail(artistDetail)
}
})
}
} | app/src/main/java/com/wenhaiz/himusic/module/artist/detail/ArtistDetailPresenter.kt | 2576549706 |
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.samples.donuttracker.core.model
import androidx.room.Entity
import androidx.room.PrimaryKey
/**
* This class holds the data that we are tracking for each donut: its name, a description, and
* a rating.
*/
@Entity
data class Donut(
@PrimaryKey(autoGenerate = true) val id: Long,
val name: String,
val description: String = "",
val rating: Int
)
| DonutTracker/NestedGraphs_Include/core/src/main/java/com/android/samples/donuttracker/core/model/Donut.kt | 2946033521 |
package org.gravidence.gravifon.playback.backend.gstreamer
import org.gravidence.gravifon.domain.track.VirtualTrack
class TrackQueue(
private var activeTrack: VirtualTrack? = null, // queue is inactive initially
private val nextTracks: ArrayDeque<VirtualTrack> = ArrayDeque()
) {
private fun makeNextActive(): VirtualTrack? {
activeTrack = nextTracks.removeFirstOrNull()
return activeTrack
}
fun peekActive(): VirtualTrack? {
return activeTrack
}
fun pollActive(): Pair<VirtualTrack?, VirtualTrack?> {
return Pair(
peekActive(),
makeNextActive()
)
}
fun pushNext(track: VirtualTrack) {
nextTracks += track
}
fun peekNext(): VirtualTrack? {
return nextTracks.firstOrNull()
}
fun pollNext(): VirtualTrack? {
val nextTrack = nextTracks.firstOrNull()
nextTracks.clear()
return nextTrack
}
} | gravifon/src/main/kotlin/org/gravidence/gravifon/playback/backend/gstreamer/TrackQueue.kt | 1714907129 |
package workflow.request
import com.fasterxml.jackson.annotation.JsonProperty
import model.base.BaseRequest
import model.base.BaseWebserviceResponse
import model.base.WSCode
import org.jetbrains.annotations.NotNull
import org.springframework.http.HttpStatus
import utils.WSRegex
import utils.WSString
class RegisterUserRequest(@JsonProperty("username") @NotNull val username: String,
@JsonProperty("password") @NotNull val password: String,
@JsonProperty("companyCode") @NotNull val companyCode: String,
@JsonProperty("name") @NotNull val name: String,
@JsonProperty("lastName") @NotNull val lastName: String) : BaseRequest() {
override fun checkIfRequestIsValid(): BaseWebserviceResponse {
if (isUsernameValid(username).not()) {
return BaseWebserviceResponse(HttpStatus.BAD_REQUEST, WSCode.ERROR_WRONG_FIELD, WSCode.ERROR_WRONG_FIELD.code, WSString.REGISTER_USER_USERNAME_INVALID.tag)
}
if (isPasswordValid(password).not()) {
return BaseWebserviceResponse(HttpStatus.BAD_REQUEST, WSCode.ERROR_WRONG_FIELD, WSCode.ERROR_WRONG_FIELD.code, WSString.REGISTER_USER_PASSWORD_INVALID.tag)
}
if (companyCode.isNullOrEmpty()) {
return BaseWebserviceResponse(HttpStatus.BAD_REQUEST, WSCode.ERROR_WRONG_FIELD, WSCode.ERROR_WRONG_FIELD.code, WSString.REGISTER_USER_COMPANY_ID_INVALID.tag)
}
if (name.isNullOrEmpty()) {
return BaseWebserviceResponse(HttpStatus.BAD_REQUEST, WSCode.ERROR_WRONG_FIELD, WSCode.ERROR_WRONG_FIELD.code, WSString.REGISTER_USER_NAME_INVALID.tag)
}
if (lastName.isNullOrEmpty()) {
return BaseWebserviceResponse(HttpStatus.BAD_REQUEST, WSCode.ERROR_WRONG_FIELD, WSCode.ERROR_WRONG_FIELD.code, WSString.REGISTER_USER_LAST_NAME_INVALID.tag)
}
return super.checkIfRequestIsValid()
}
private fun isUsernameValid(username: String) =
username.isNullOrEmpty().not() && username.length > 3
private fun isPasswordValid(password: String) =
password.isNullOrEmpty().not() && password.contains(WSRegex.PASSWORD_REGEX.regex.toRegex())
} | src/main/kotlin/workflow/request/RegisterUserRequest.kt | 2215040661 |
package siosio.doma.inspection.dao
import com.intellij.codeInsight.daemon.impl.quickfix.*
import com.intellij.openapi.project.*
import com.intellij.psi.*
import com.intellij.psi.impl.source.*
import com.intellij.psi.search.*
import siosio.doma.extension.*
import siosio.doma.psi.*
val batchInsertMethodRule =
rule {
sql(false)
// check parameter count
parameterRule {
message = "inspection.dao.batch-insert.param-size-error"
rule = {
when (size) {
1 -> true
else -> false
}
}
}
// check parameter type(sqlなし)
parameterRule {
message = "inspection.dao.batch-insert.param-error"
rule = { daoMethod ->
if (size == 1 && daoMethod.useSqlFile().not()) {
firstOrNull()?.let {
val type = it.type as PsiClassReferenceType
isIterableType(daoMethod.project, type) && type.reference.typeParameters.first().isEntity()
} ?: true
} else {
true
}
}
}
// check parameter type(sqlあり)
parameterRule {
message = "inspection.dao.batch-insert.use-sql.param-error"
rule = { daoMethod ->
if (size == 1 && daoMethod.useSqlFile()) {
firstOrNull()?.type?.let {
isIterableType(daoMethod.project, it)
} ?: true
} else {
true
}
}
}
// return type(not immutable entity)
returnRule {
message = "inspection.dao.batch-insert.mutable-insert-return-type"
rule = block@{ daoMethod ->
quickFix = { MethodReturnTypeFix(daoMethod.psiMethod, PsiType.INT.createArrayType(), false) }
if (daoMethod.parameters.size == 1) {
// 最初のパラメータの型パラメータを取得してチェックする
val typeParameter = getFirstParametersTypeParameter(daoMethod) ?: return@block true
if (typeParameter.isImmutableEntity().not()) {
type.isAssignableFrom(PsiType.INT.createArrayType())
} else {
true
}
} else {
true
}
}
}
// return type( immutable entity)
returnRule {
message = "inspection.dao.batch-insert.immutable-insert-return-type"
rule = block@{ daoMethod ->
if (daoMethod.parameters.size == 1) {
// 最初のパラメータの型パラメータを取得してチェックする
val typeParameter = getFirstParametersTypeParameter(daoMethod) ?: return@block true
quickFix = {
MethodReturnTypeFix(
daoMethod.psiMethod,
PsiType.getTypeByName(
"org.seasar.doma.jdbc.BatchResult<${typeParameter.canonicalText}>", project, resolveScope), false)
}
if (typeParameter.isImmutableEntity()) {
messageArgs = arrayOf(typeParameter.canonicalText)
type.isAssignableFrom(PsiType.getTypeByName("org.seasar.doma.jdbc.BatchResult", daoMethod.project, resolveScope))
} else {
true
}
} else {
true
}
}
}
}
private fun getFirstParametersTypeParameter(daoMethod: PsiDaoMethod): PsiType? {
val parameterType = daoMethod.parameterList.parameters.first().type as PsiClassReferenceType
return parameterType.reference.typeParameters.firstOrNull()
}
private fun isIterableType(project: Project, psiType: PsiType): Boolean {
val iterableType = PsiType.getTypeByName("java.lang.Iterable", project, GlobalSearchScope.allScope(project))
return psiType.superTypes.any { iterableType.isAssignableFrom(it) }
}
| src/main/java/siosio/doma/inspection/dao/BatchInsertMethodRule.kt | 2591730729 |
package app.lawnchair.bugreport
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import android.util.Log
import androidx.core.content.getSystemService
import app.lawnchair.LawnchairApp
import com.android.launcher3.BuildConfig
import com.android.launcher3.R
import com.android.launcher3.util.MainThreadInitializedObject
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
class LawnchairBugReporter(private val context: Context) {
private val notificationManager = context.getSystemService<NotificationManager>()!!
private val logsFolder by lazy { File(context.cacheDir, "logs").apply { mkdirs() } }
private val appName by lazy { context.getString(R.string.derived_app_name) }
init {
notificationManager.createNotificationChannel(
NotificationChannel(
BugReportReceiver.notificationChannelId,
context.getString(R.string.bugreport_channel_name),
NotificationManager.IMPORTANCE_HIGH
)
)
notificationManager.createNotificationChannel(
NotificationChannel(
BugReportReceiver.statusChannelId,
context.getString(R.string.status_channel_name),
NotificationManager.IMPORTANCE_NONE
)
)
val defaultHandler = Thread.getDefaultUncaughtExceptionHandler()
Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
sendNotification(throwable)
defaultHandler?.uncaughtException(thread, throwable)
}
removeDismissedLogs()
}
private fun removeDismissedLogs() {
val activeIds = notificationManager.activeNotifications
.mapTo(mutableSetOf()) { String.format("%x", it.id) }
(logsFolder.listFiles() as Array<File>)
.filter { it.name !in activeIds }
.forEach { it.deleteRecursively() }
}
private fun sendNotification(throwable: Throwable) {
val bugReport = Report(BugReport.TYPE_UNCAUGHT_EXCEPTION, throwable)
.generateBugReport() ?: return
val notifications = notificationManager.activeNotifications
val hasNotification = notifications.any { it.id == bugReport.notificationId }
if (hasNotification || notifications.size > 3) {
return
}
BugReportReceiver.notify(context, bugReport)
}
inner class Report(val error: String, val throwable: Throwable? = null) {
private val fileName = "$appName bug report ${SimpleDateFormat.getDateTimeInstance().format(Date())}"
fun generateBugReport(): BugReport? {
val contents = writeContents()
val contentsWithHeader = "$fileName\n$contents"
val id = contents.hashCode()
val reportFile = save(contentsWithHeader, id)
return BugReport(id, error, getDescription(throwable ?: return null), contentsWithHeader, reportFile)
}
private fun getDescription(throwable: Throwable): String {
return "${throwable::class.java.name}: ${throwable.message}"
}
private fun save(contents: String, id: Int): File? {
val dest = File(logsFolder, String.format("%x", id))
dest.mkdirs()
val file = File(dest, "$fileName.txt")
if (!file.createNewFile()) return null
file.writeText(contents)
return file
}
private fun writeContents() = StringBuilder()
.appendLine("version: ${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})")
.appendLine("commit: ${BuildConfig.COMMIT_HASH}")
.appendLine("build.brand: ${Build.BRAND}")
.appendLine("build.device: ${Build.DEVICE}")
.appendLine("build.display: ${Build.DISPLAY}")
.appendLine("build.fingerprint: ${Build.FINGERPRINT}")
.appendLine("build.hardware: ${Build.HARDWARE}")
.appendLine("build.id: ${Build.ID}")
.appendLine("build.manufacturer: ${Build.MANUFACTURER}")
.appendLine("build.model: ${Build.MODEL}")
.appendLine("build.product: ${Build.PRODUCT}")
.appendLine("build.type: ${Build.TYPE}")
.appendLine("version.codename: ${Build.VERSION.CODENAME}")
.appendLine("version.incremental: ${Build.VERSION.INCREMENTAL}")
.appendLine("version.release: ${Build.VERSION.RELEASE}")
.appendLine("version.sdk_int: ${Build.VERSION.SDK_INT}")
.appendLine("display.density_dpi: ${context.resources.displayMetrics.densityDpi}")
.appendLine("isRecentsEnabled: ${LawnchairApp.isRecentsEnabled}")
.appendLine()
.appendLine("error: $error")
.also {
if (throwable != null) {
it
.appendLine()
.appendLine(Log.getStackTraceString(throwable))
}
}
.toString()
}
companion object {
val INSTANCE = MainThreadInitializedObject(::LawnchairBugReporter)
}
}
| lawnchair/src/app/lawnchair/bugreport/LawnchairBugReporter.kt | 871429043 |
package org.koin.sample.androidx.components.sdk
import androidx.lifecycle.ViewModel
class SDKVIewModel(val sdkService: SDKService) : ViewModel() | koin-projects/examples/androidx-samples/src/main/java/org/koin/sample/androidx/components/sdk/SDKVIewModel.kt | 1549733727 |
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.psi.uast
import com.intellij.lang.Language
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.util.parents
import org.jetbrains.plugins.groovy.GroovyLanguage
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes
import org.jetbrains.plugins.groovy.lang.psi.GrQualifiedReference
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationNameValuePair
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.uast.*
/**
* This is a very limited implementation of UastPlugin for Groovy,
* provided only to make Groovy play with UAST-based reference contributors and spring class annotators
*/
class GroovyUastPlugin : UastLanguagePlugin {
override fun convertElement(element: PsiElement, parent: UElement?, requiredType: Class<out UElement>?): UElement? =
convertElementWithParent(element, { parent }, requiredType)
override fun convertElementWithParent(element: PsiElement, requiredType: Class<out UElement>?): UElement? =
convertElementWithParent(element, { makeUParent(element) }, requiredType)
private fun convertElementWithParent(element: PsiElement,
parentProvider: () -> UElement?,
requiredType: Class<out UElement>?): UElement? =
when (element) {
is GroovyFile -> GrUFile(element, this)
is GrLiteral -> GrULiteral(element, parentProvider)
is GrAnnotationNameValuePair -> GrUNamedExpression(element, parentProvider)
is GrAnnotation -> GrUAnnotation(element, parentProvider)
is GrTypeDefinition -> GrUClass(element, parentProvider)
is GrMethod -> GrUMethod(element, parentProvider)
is GrParameter -> GrUParameter(element, parentProvider)
is GrQualifiedReference<*> -> GrUReferenceExpression(element, parentProvider)
is LeafPsiElement -> if (element.elementType == GroovyTokenTypes.mIDENT) LazyParentUIdentifier(element, null) else null
else -> null
}?.takeIf { requiredType?.isAssignableFrom(it.javaClass) ?: true }
private fun makeUParent(element: PsiElement) =
element.parent.parents().mapNotNull { convertElementWithParent(it, null) }.firstOrNull()
override fun getMethodCallExpression(element: PsiElement,
containingClassFqName: String?,
methodName: String): UastLanguagePlugin.ResolvedMethod? = null //not implemented
override fun getConstructorCallExpression(element: PsiElement,
fqName: String): UastLanguagePlugin.ResolvedConstructor? = null //not implemented
override fun isExpressionValueUsed(element: UExpression): Boolean = TODO("not implemented")
override val priority = 0
override fun isFileSupported(fileName: String) = fileName.endsWith(".groovy", ignoreCase = true)
override val language: Language = GroovyLanguage
}
class GrULiteral(val grElement: GrLiteral, val parentProvider: () -> UElement?) : ULiteralExpression, JvmDeclarationUElement {
override val value: Any?
get() = grElement.value
override val uastParent by lazy(parentProvider)
override val psi: PsiElement? = grElement
override val annotations: List<UAnnotation> = emptyList() //not implemented
}
class GrUNamedExpression(val grElement: GrAnnotationNameValuePair, val parentProvider: () -> UElement?) : UNamedExpression, JvmDeclarationUElement {
override val name: String?
get() = grElement.name
override val expression: UExpression
get() = grElement.value.toUElementOfType() ?: GrUnknownUExpression(grElement.value, this)
override val uastParent by lazy(parentProvider)
override val psi = grElement
override val annotations: List<UAnnotation> = emptyList() //not implemented
}
class GrUAnnotation(val grElement: GrAnnotation,
val parentProvider: () -> UElement?) : UAnnotationEx, JvmDeclarationUElement, UAnchorOwner {
override val javaPsi: PsiAnnotation = grElement
override val qualifiedName: String?
get() = grElement.qualifiedName
override fun resolve(): PsiClass? = grElement.nameReferenceElement?.resolve() as PsiClass?
override val uastAnchor: UIdentifier?
get() = grElement.classReference.referenceNameElement?.let { UIdentifier(it, this) }
override val attributeValues: List<UNamedExpression> by lazy {
grElement.parameterList.attributes.map {
GrUNamedExpression(it, { this })
}
}
override fun findAttributeValue(name: String?): UExpression? = null //not implemented
override fun findDeclaredAttributeValue(name: String?): UExpression? = null //not implemented
override val uastParent by lazy(parentProvider)
override val psi: PsiElement? = grElement
}
class GrUnknownUExpression(override val psi: PsiElement?, override val uastParent: UElement?) : UExpression, JvmDeclarationUElement {
override fun asLogString(): String = "GrUnknownUExpression(grElement)"
override val annotations: List<UAnnotation> = emptyList() //not implemented
} | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/uast/GroovyUastPlugin.kt | 85526072 |
package io.innofang.kotlindemo
import android.R
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
/**
* Author: Inno Fang
* Time: 2017/6/24 11:35
* Description:
*/
public class RvAdapter(var list: List<Int>) : RecyclerView.Adapter<RvAdapter.RvViewHolder>() {
var action: ((text: String) -> Unit)? = null
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RvViewHolder {
return RvViewHolder(LayoutInflater.from(parent!!.context)
.inflate(R.layout.simple_list_item_1, parent, false))
}
override fun onBindViewHolder(holder: RvViewHolder?, position: Int) {
holder!!.infoTextView.text = list[position].toString()
holder.itemView.setOnClickListener { action?.invoke(list[position].toString()) }
}
override fun getItemCount(): Int = list?.let { list.size } ?: 0
inner class RvViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val infoTextView: TextView by lazy { itemView.findViewById(android.R.id.text1) as TextView }
}
}
| KotlinDemo/app/src/main/java/io/innofang/kotlindemo/RvAdapter.kt | 2731772468 |
package org.jetbrains.dokka.versioning
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import org.jetbrains.dokka.plugability.DokkaContext
import org.jetbrains.dokka.plugability.configuration
import java.io.File
data class VersionDirs(val src: File, val dst: File)
data class CurrentVersion(val name: String, val dir: File)
interface VersioningStorage {
val previousVersions: Map<VersionId, VersionDirs>
val currentVersion: CurrentVersion
fun createVersionFile()
}
typealias VersionId = String
class DefaultVersioningStorage(val context: DokkaContext) : VersioningStorage {
private val mapper = ObjectMapper()
private val configuration = configuration<VersioningPlugin, VersioningConfiguration>(context)
override val previousVersions: Map<VersionId, VersionDirs> by lazy {
configuration?.let { versionsConfiguration ->
getPreviousVersions(versionsConfiguration.allOlderVersions(), context.configuration.outputDir)
} ?: emptyMap()
}
override val currentVersion: CurrentVersion by lazy {
configuration?.let { versionsConfiguration ->
CurrentVersion(versionsConfiguration.versionFromConfigurationOrModule(context),
context.configuration.outputDir)
}?: CurrentVersion(context.configuration.moduleVersion.orEmpty(), context.configuration.outputDir)
}
override fun createVersionFile() {
mapper.writeValue(
currentVersion.dir.resolve(VersioningConfiguration.VERSIONS_FILE),
Version(currentVersion.name)
)
}
private fun getPreviousVersions(olderVersions: List<File>, output: File): Map<String, VersionDirs> =
versionsFrom(olderVersions).associate { (key, srcDir) ->
key to VersionDirs(srcDir, output.resolve(VersioningConfiguration.OLDER_VERSIONS_DIR).resolve(key))
}
private fun versionsFrom(olderVersions: List<File>) =
olderVersions.mapNotNull { versionDir ->
versionDir.listFiles { _, name -> name == VersioningConfiguration.VERSIONS_FILE }?.firstOrNull()
?.let { file ->
val versionsContent = mapper.readValue<Version>(file)
Pair(versionsContent.version, versionDir)
}.also {
if (it == null) context.logger.warn("Failed to find versions file named ${VersioningConfiguration.VERSIONS_FILE} in $versionDir")
}
}
private data class Version(
@JsonProperty("version") val version: String,
)
}
| plugins/versioning/src/main/kotlin/org/jetbrains/dokka/versioning/VersioningStorage.kt | 1227745573 |
package org.jetbrains.dokka.allModulesPage
import org.jetbrains.dokka.CoreExtensions
import org.jetbrains.dokka.DokkaConfiguration
import org.jetbrains.dokka.DokkaGenerator
import org.jetbrains.dokka.pages.RootPageNode
import org.jetbrains.dokka.plugability.DokkaContext
import org.jetbrains.dokka.plugability.DokkaPlugin
import org.jetbrains.dokka.testApi.logger.TestLogger
import org.jetbrains.dokka.testApi.testRunner.AbstractTest
import org.jetbrains.dokka.testApi.testRunner.DokkaTestGenerator
import org.jetbrains.dokka.testApi.testRunner.TestBuilder
import org.jetbrains.dokka.testApi.testRunner.TestMethods
import org.jetbrains.dokka.utilities.DokkaConsoleLogger
import org.jetbrains.dokka.utilities.DokkaLogger
class MultiModuleDokkaTestGenerator(
configuration: DokkaConfiguration,
logger: DokkaLogger,
testMethods: MultiModuleTestMethods,
additionalPlugins: List<DokkaPlugin> = emptyList()
) : DokkaTestGenerator<MultiModuleTestMethods>(
configuration,
logger,
testMethods,
additionalPlugins + AllModulesPagePlugin()
) {
override fun generate() = with(testMethods) {
val dokkaGenerator = DokkaGenerator(configuration, logger)
val context =
dokkaGenerator.initializePlugins(configuration, logger, additionalPlugins + AllModulesPagePlugin())
pluginsSetupStage(context)
val generation = context.single(CoreExtensions.generation) as AllModulesPageGeneration
val generationContext = generation.processSubmodules()
submoduleProcessingStage(context)
val allModulesPage = generation.createAllModulesPage(generationContext)
allModulesPageCreationStage(allModulesPage)
val transformedPages = generation.transformAllModulesPage(allModulesPage)
pagesTransformationStage(transformedPages)
generation.render(transformedPages)
renderingStage(transformedPages, context)
generation.processMultiModule(transformedPages)
processMultiModule(transformedPages)
generation.finishProcessingSubmodules()
finishProcessingSubmodules(context)
}
}
open class MultiModuleTestMethods(
open val pluginsSetupStage: (DokkaContext) -> Unit,
open val allModulesPageCreationStage: (RootPageNode) -> Unit,
open val pagesTransformationStage: (RootPageNode) -> Unit,
open val renderingStage: (RootPageNode, DokkaContext) -> Unit,
open val submoduleProcessingStage: (DokkaContext) -> Unit,
open val processMultiModule: (RootPageNode) -> Unit,
open val finishProcessingSubmodules: (DokkaContext) -> Unit,
) : TestMethods
class MultiModuleTestBuilder : TestBuilder<MultiModuleTestMethods>() {
var pluginsSetupStage: (DokkaContext) -> Unit = {}
var allModulesPageCreationStage: (RootPageNode) -> Unit = {}
var pagesTransformationStage: (RootPageNode) -> Unit = {}
var renderingStage: (RootPageNode, DokkaContext) -> Unit = { _, _ -> }
var submoduleProcessingStage: (DokkaContext) -> Unit = {}
var processMultiModule: (RootPageNode) -> Unit = {}
var finishProcessingSubmodules: (DokkaContext) -> Unit = {}
override fun build() = MultiModuleTestMethods(
pluginsSetupStage,
allModulesPageCreationStage,
pagesTransformationStage,
renderingStage,
submoduleProcessingStage,
processMultiModule,
finishProcessingSubmodules
)
}
abstract class MultiModuleAbstractTest(logger: TestLogger = TestLogger(DokkaConsoleLogger())) :
AbstractTest<MultiModuleTestMethods, MultiModuleTestBuilder, MultiModuleDokkaTestGenerator>(
::MultiModuleTestBuilder,
::MultiModuleDokkaTestGenerator,
logger,
)
| plugins/all-modules-page/src/test/kotlin/MultiModuleDokkaTestGenerator.kt | 2581924238 |
package filter
import org.jetbrains.dokka.DokkaDefaults
import org.jetbrains.dokka.PackageOptionsImpl
import org.jetbrains.dokka.base.testApi.testRunner.BaseAbstractTest
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
class DeprecationFilterTest : BaseAbstractTest() {
@Test
fun `should skip hidden deprecated level regardless of skipDeprecated`() {
val configuration = dokkaConfiguration {
sourceSets {
sourceSet {
sourceRoots = listOf("src/main/kotlin/basic/Test.kt")
skipDeprecated = false
perPackageOptions = mutableListOf(
PackageOptionsImpl(
"example.*",
true,
false,
false,
false,
DokkaDefaults.documentedVisibilities
)
)
}
}
}
testInline(
"""
|/src/main/kotlin/basic/Test.kt
|package example
|
|@Deprecated("dep", level = DeprecationLevel.HIDDEN)
|fun testFunction() { }
|
""".trimMargin(),
configuration
) {
preMergeDocumentablesTransformationStage = {
Assertions.assertTrue(
it.first().packages.first().functions.isEmpty()
)
}
}
}
@Test
fun `function with false global skipDeprecated`() {
val configuration = dokkaConfiguration {
sourceSets {
sourceSet {
skipDeprecated = false
sourceRoots = listOf("src/main/kotlin/basic/Test.kt")
}
}
}
testInline(
"""
|/src/main/kotlin/basic/Test.kt
|package example
|
|fun testFunction() { }
|
|
|
""".trimMargin(),
configuration
) {
preMergeDocumentablesTransformationStage = {
Assertions.assertTrue(
it.first().packages.first().functions.size == 1
)
}
}
}
@Test
fun `deprecated function with false global skipDeprecated`() {
val configuration = dokkaConfiguration {
sourceSets {
sourceSet {
skipDeprecated = false
sourceRoots = listOf("src/main/kotlin/basic/Test.kt")
}
}
}
testInline(
"""
|/src/main/kotlin/basic/Test.kt
|package example
|
|@Deprecated("dep")
|fun testFunction() { }
|
|
""".trimMargin(),
configuration
) {
preMergeDocumentablesTransformationStage = {
Assertions.assertTrue(
it.first().packages.first().functions.size == 1
)
}
}
}
@Test
fun `deprecated function with true global skipDeprecated`() {
val configuration = dokkaConfiguration {
sourceSets {
sourceSet {
sourceRoots = listOf("src/main/kotlin/basic/Test.kt")
skipDeprecated = true
}
}
}
testInline(
"""
|/src/main/kotlin/basic/Test.kt
|package example
|
|@Deprecated("dep")
|fun testFunction() { }
|
|
""".trimMargin(),
configuration
) {
preMergeDocumentablesTransformationStage = {
Assertions.assertTrue(
it.first().packages.first().functions.isEmpty()
)
}
}
}
@Test
fun `should skip deprecated companion object`() {
val configuration = dokkaConfiguration {
sourceSets {
sourceSet {
sourceRoots = listOf("src/main/kotlin/basic/Test.kt")
skipDeprecated = true
}
}
}
testInline(
"""
|/src/main/kotlin/basic/Test.kt
|package example
|
|class Test {
| @Deprecated("dep")
| companion object {
| fun method() {}
| }
|}
|
|
""".trimMargin(),
configuration
) {
preMergeDocumentablesTransformationStage = {
Assertions.assertTrue(
it.first().packages.first().classlikes.first().classlikes.isEmpty()
)
}
}
}
@Test
fun `deprecated function with false global true package skipDeprecated`() {
val configuration = dokkaConfiguration {
sourceSets {
sourceSet {
sourceRoots = listOf("src/main/kotlin/basic/Test.kt")
skipDeprecated = false
perPackageOptions = mutableListOf(
PackageOptionsImpl(
"example.*",
true,
false,
true,
false,
DokkaDefaults.documentedVisibilities
)
)
}
}
}
testInline(
"""
|/src/main/kotlin/basic/Test.kt
|package example
|
|@Deprecated("dep")
|fun testFunction() { }
|
|
""".trimMargin(),
configuration
) {
preMergeDocumentablesTransformationStage = {
Assertions.assertTrue(
it.first().packages.first().functions.isEmpty()
)
}
}
}
@Test
fun `deprecated function with true global false package skipDeprecated`() {
val configuration = dokkaConfiguration {
sourceSets {
sourceSet {
sourceRoots = listOf("src/main/kotlin/basic/Test.kt")
skipDeprecated = true
perPackageOptions = mutableListOf(
PackageOptionsImpl("example",
false,
false,
false,
false,
DokkaDefaults.documentedVisibilities
)
)
}
}
}
testInline(
"""
|/src/main/kotlin/basic/Test.kt
|package example
|
|@Deprecated("dep")
|fun testFunction() { }
|
|
""".trimMargin(),
configuration
) {
preMergeDocumentablesTransformationStage = {
Assertions.assertTrue(
it.first().packages.first().functions.size == 1
)
}
}
}
}
| plugins/base/src/test/kotlin/filter/DeprecationFilterTest.kt | 2105072320 |
package com.octo.mob.octomeuh.countdown.manager
import android.content.SharedPreferences
import com.octo.mob.octomeuh.countdown.model.RepetitionMode
import java.util.*
interface PreferencesPersistor {
fun saveInitialDuration(initialDurationSeconds: Int)
fun getInitialDuration(): Int
fun getRepetitionMode(): RepetitionMode
fun saveRepetitionMode(repetitionMode: RepetitionMode)
}
class PreferencesPersistorImpl(val sharedPreferences: SharedPreferences) : PreferencesPersistor {
// ---------------------------------
// CONSTANTS
// ---------------------------------
companion object {
internal val INITIAL_DURATION_KEY = "INITIAL_DURATION_KEY"
internal val REPETITION_MODE_KEY = "REPETITION_MODE_KEY"
internal val DEFAULT_COUNTDOWN_DURATION_SECONDS = 60
internal val DEFAULT_REPETITION_MODE = RepetitionMode.STEP_BY_STEP
}
// ---------------------------------
// INTERFACE IMPLEM
// ---------------------------------
override fun getInitialDuration(): Int {
try {
return sharedPreferences.getInt(INITIAL_DURATION_KEY, DEFAULT_COUNTDOWN_DURATION_SECONDS)
} catch (exception: ClassCastException) {
return DEFAULT_COUNTDOWN_DURATION_SECONDS
}
}
override fun saveInitialDuration(initialDurationSeconds: Int) {
sharedPreferences.edit()
.putInt(INITIAL_DURATION_KEY, initialDurationSeconds)
.apply()
}
override fun getRepetitionMode(): RepetitionMode {
return extractEnumValue(RepetitionMode.values(), REPETITION_MODE_KEY, DEFAULT_REPETITION_MODE)
}
override fun saveRepetitionMode(repetitionMode: RepetitionMode) {
sharedPreferences.edit()
.putString(REPETITION_MODE_KEY, repetitionMode.name)
.apply()
}
// ---------------------------------
// PRIVATE METHOD
// ---------------------------------
private fun <T : kotlin.Enum<T>> extractEnumValue(valueLists: Array<T>, key: String, defaultValue: T): T {
val extractedValue: T
try {
extractedValue = valueLists.first { it.name == sharedPreferences.getString(key, defaultValue.name) }
} catch (exception: NoSuchElementException) {
extractedValue = defaultValue
}
return extractedValue
}
} | app/src/main/kotlin/com/octo/mob/octomeuh/countdown/manager/PreferencesPersistor.kt | 3039909563 |
/**
* Copyright (C) 2017 Damien Chazoule
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package com.doomy.seeya
import android.app.Activity
import android.content.Context
import android.provider.Settings
import android.support.design.widget.Snackbar
import android.view.View
import android.widget.TextView
object Utils {
fun mapValueFromRangeToRange(value: Double, fromLow: Double, fromHigh: Double, toLow: Double, toHigh: Double): Double {
return toLow + (value - fromLow) / (fromHigh - fromLow) * (toHigh - toLow)
}
fun clamp(value: Double, low: Double, high: Double): Double {
return Math.min(Math.max(value, low), high)
}
fun hasAccessGranted(context: Context): Boolean {
val mContentResolver = context.contentResolver
val mEnabledNotificationListeners = Settings.Secure.getString(mContentResolver, "enabled_notification_listeners")
val mPackageName = context.packageName
// Check To See If The 'mEnabledNotificationListeners' String Contains Our Package Name
return !(mEnabledNotificationListeners == null || !mEnabledNotificationListeners.contains(mPackageName))
}
fun makeText(context: Context, message: String, duration: Int): Snackbar {
val mActivity = context as Activity
val mLayout: View
val mSnackBar = Snackbar.make(mActivity.findViewById(android.R.id.content), message, duration)
mLayout = mSnackBar.view
// Customize Colors
mLayout.setBackgroundColor(context.getResources().getColor(R.color.colorPrimaryDark))
val mTextView = mLayout.findViewById<TextView>(android.support.design.R.id.snackbar_text)
mTextView.setTextColor(context.getResources().getColor(R.color.colorLight))
return mSnackBar
}
}
| app/src/main/java/com/doomy/seeya/Utils.kt | 2157855436 |
package com.github.shynixn.blockball.api.bukkit.event
import com.github.shynixn.blockball.api.business.proxy.BallProxy
/**
* Event which gets sent when the ball is requested to get removed.
*/
class BallDeathEvent(ball: BallProxy) : BallEvent(ball)
| blockball-bukkit-api/src/main/java/com/github/shynixn/blockball/api/bukkit/event/BallDeathEvent.kt | 461229138 |
package org.stt.validation
import org.stt.query.Criteria
import org.stt.query.TimeTrackingItemQueries
import org.stt.time.DateTimes
import org.stt.time.until
import java.time.LocalDateTime
import javax.inject.Inject
class ItemAndDateValidator @Inject
constructor(private val timeTrackingItemQueries: TimeTrackingItemQueries) {
fun validateItemIsFirstItemAndLater(start: LocalDateTime): Boolean {
if (!DateTimes.isToday(start)) {
return true
}
val startOfDay = start.toLocalDate().atStartOfDay()
val searchInterval = startOfDay until start
val criteria = Criteria()
criteria.withStartBetween(searchInterval)
val hasEarlierItem = timeTrackingItemQueries.queryItems(criteria)
.findAny()
.isPresent
return hasEarlierItem || !LocalDateTime.now().isBefore(start)
}
}
| src/main/kotlin/org/stt/validation/ItemAndDateValidator.kt | 517748804 |
package com.garpr.android.data.database
import com.garpr.android.test.BaseTest
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test
import org.koin.test.inject
class MapOfStringToStringConverterTest : BaseTest() {
private lateinit var jsonAdapter: JsonAdapter<Map<String, String>>
private val converter = MapOfStringToStringConverter()
protected val moshi: Moshi by inject()
@Before
override fun setUp() {
super.setUp()
jsonAdapter = moshi.adapter(Types.newParameterizedType(Map::class.java,
String::class.java, String::class.java))
}
@Test
fun testMapOfStringToStringFromString() {
val map = converter.mapOfStringToStringFromString(JSON)
assertNotNull(map)
assertEquals(1, map?.size)
assertEquals("World", map?.get("Hello"))
}
@Test
fun testMapOfStringToStringFromStringWithEmptyString() {
assertNull(converter.mapOfStringToStringFromString(""))
}
@Test
fun testMapOfStringToStringFromStringWithNull() {
assertNull(converter.mapOfStringToStringFromString(null))
}
@Test
fun testStringFromMapOfStringToString() {
val string = converter.stringFromMapOfStringToString(MAP)
assertFalse(string.isNullOrBlank())
val map = jsonAdapter.fromJson(string!!)
assertEquals(1, map?.size)
assertEquals("World", map?.get("Hello"))
}
@Test
fun testStringFromMapOfStringToStringWithEmptyMap() {
assertNull(converter.stringFromMapOfStringToString(emptyMap()))
}
@Test
fun testStringFromMapOfStringToStringWithNull() {
assertNull(converter.stringFromMapOfStringToString(null))
}
companion object {
private val MAP = mapOf(
"Hello" to "World"
)
private const val JSON = "{\"Hello\":\"World\"}"
}
}
| smash-ranks-android/app/src/test/java/com/garpr/android/data/database/MapOfStringToStringConverterTest.kt | 2206614946 |
package net.tlalka.fiszki.domain.controllers
import net.tlalka.fiszki.core.annotations.ActivityScope
import net.tlalka.fiszki.domain.services.CacheService
import net.tlalka.fiszki.domain.services.LessonService
import net.tlalka.fiszki.domain.services.StorageService
import net.tlalka.fiszki.domain.services.WordService
import net.tlalka.fiszki.domain.utils.ValidUtils
import net.tlalka.fiszki.model.dto.parcel.LessonDto
import net.tlalka.fiszki.model.entities.Lesson
import net.tlalka.fiszki.model.entities.Word
import net.tlalka.fiszki.model.types.LanguageType
import java.util.ArrayList
import java.util.Random
import javax.inject.Inject
@ActivityScope
class TestController
@Inject constructor(cacheService: CacheService, storageService: StorageService, lessonDto: LessonDto) {
@Inject
lateinit var lessonService: LessonService
@Inject
lateinit var wordService: WordService
private val lesson: Lesson = cacheService.getLesson(lessonDto.lessonId)
private val words: MutableList<Word> = cacheService.getWords(lesson).toMutableList()
private val language: LanguageType = storageService.language
private var translation: LanguageType = storageService.translation
private var answers: MutableList<String> = emptyList<String>().toMutableList()
private var correctAnswer: String = ""
private var activeWord: Word = Word()
private var correctScore: Int = 0
private var incorrectScore: Int = 0
var wordIndex: Int = 0
private set
init {
this.randomiseCollection(words)
}
fun getLanguages(): List<LanguageType> {
val languages = this.wordService.getLanguages(this.activeWord).toMutableList()
languages.remove(this.language)
languages.remove(this.translation)
return languages
}
fun getNextWord(): String {
this.activeWord = this.words[wordIndex++]
return this.activeWord.value
}
fun getTestSize(): Int {
return this.words.size
}
fun getThisAnswers(): List<String> {
val answer = this.getTranslateWord(this.activeWord)
return if (ValidUtils.isNotNull(answer)) {
this.correctAnswer = answer.value
this.answers = ArrayList()
this.answers.add(correctAnswer)
this.generateAnswers(answers, 3)
this.randomiseCollection(answers)
answers
} else {
emptyList()
}
}
private fun generateAnswers(answers: MutableList<String>, size: Int) {
if (size > 0 && this.generateAnswer(answers, 100)) {
this.generateAnswers(answers, size - 1)
}
}
private fun generateAnswer(answers: MutableList<String>, repetitions: Int): Boolean {
val word = words[Random().nextInt(words.size)]
val value = this.getTranslateWord(word).value
return if (repetitions - 1 > 0) {
if (answers.contains(value)) generateAnswer(answers, repetitions - 1) else answers.add(value)
} else {
answers.add("...")
}
}
private fun getTranslateWord(word: Word): Word {
return this.wordService.getTranslation(word, this.translation)
}
private fun randomiseCollection(list: MutableList<*>) {
list.shuffle()
}
fun setTranslation(translation: LanguageType) {
this.translation = translation
}
fun hasNextWord(): Boolean {
return this.wordIndex < this.words.size
}
fun validAnswer(index: Int): Boolean {
return if (this.answers.indexOf(this.correctAnswer) == index) {
this.correctScore++
true
} else {
this.incorrectScore++
false
}
}
fun updateLessonDto(lessonDto: LessonDto) {
lessonDto.setScoreValues(calculateScore(), correctScore, incorrectScore)
}
fun updateBestScore() {
val newScore = this.calculateScore()
if (newScore > this.lesson.score) {
this.lessonService.updateScore(lesson, newScore)
}
}
private fun calculateScore(): Int {
return Math.round(Math.max((correctScore - incorrectScore).toFloat(), 0.0f) * 100 / correctScore)
}
}
| app/src/main/kotlin/net/tlalka/fiszki/domain/controllers/TestController.kt | 3835466546 |
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ /*
Copyright (c) 2011 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jtransc.compression.jzlib
import com.jtransc.annotation.JTranscInvisible
import java.io.EOFException
import java.io.FilterInputStream
import java.io.IOException
import java.lang.IndexOutOfBoundsException
import java.lang.NullPointerException
@JTranscInvisible
class InflaterInputStream(
`in`: java.io.InputStream?,
inflater: Inflater?,
size: Int, close_in: Boolean
) : FilterInputStream(`in`) {
protected val inflater: Inflater
protected var buf: ByteArray
private var closed = false
private var eof = false
private val close_in = true
@JvmOverloads
constructor(`in`: java.io.InputStream?, nowrap: Boolean = false) : this(`in`, Inflater(nowrap)) {
myinflater = true
}
constructor(`in`: java.io.InputStream?, inflater: Inflater?) : this(`in`, inflater, DEFAULT_BUFSIZE) {}
constructor(
`in`: java.io.InputStream?,
inflater: Inflater?, size: Int
) : this(`in`, inflater, size, true) {
}
protected var myinflater = false
private val byte1 = ByteArray(1)
@Throws(IOException::class)
override fun read(): Int {
if (closed) {
throw IOException("Stream closed")
}
return if (read(byte1, 0, 1) == -1) -1 else byte1[0] and 0xff
}
@Throws(IOException::class)
override fun read(b: ByteArray, off: Int, len: Int): Int {
var off = off
if (closed) {
throw IOException("Stream closed")
}
if (b == null) {
throw NullPointerException()
} else if (off < 0 || len < 0 || len > b.size - off) {
throw IndexOutOfBoundsException()
} else if (len == 0) {
return 0
} else if (eof) {
return -1
}
var n = 0
inflater.setOutput(b, off, len)
while (!eof) {
if (inflater.avail_in === 0) fill()
val err: Int = inflater.inflate(JZlib.Z_NO_FLUSH)
n += inflater.next_out_index - off
off = inflater.next_out_index
when (err) {
JZlib.Z_DATA_ERROR -> throw IOException(inflater.msg)
JZlib.Z_STREAM_END, JZlib.Z_NEED_DICT -> {
eof = true
if (err == JZlib.Z_NEED_DICT) return -1
}
else -> {
}
}
if (inflater.avail_out === 0) break
}
return n
}
@Throws(IOException::class)
override fun available(): Int {
if (closed) {
throw IOException("Stream closed")
}
return if (eof) {
0
} else {
1
}
}
private val b = ByteArray(512)
@Throws(IOException::class)
override fun skip(n: Long): Long {
if (n < 0) {
throw java.lang.IllegalArgumentException("negative skip length")
}
if (closed) {
throw IOException("Stream closed")
}
val max = java.lang.Math.min(n, Int.MAX_VALUE.toLong()) as Int
var total = 0
while (total < max) {
var len = max - total
if (len > b.size) {
len = b.size
}
len = read(b, 0, len)
if (len == -1) {
eof = true
break
}
total += len
}
return total.toLong()
}
@Throws(IOException::class)
override fun close() {
if (!closed) {
if (myinflater) inflater.end()
if (close_in) `in`.close()
closed = true
}
}
@Throws(IOException::class)
protected fun fill() {
if (closed) {
throw IOException("Stream closed")
}
var len: Int = `in`.read(buf, 0, buf.size)
if (len == -1) {
if (inflater.istate.wrap === 0 &&
!inflater.finished()
) {
buf[0] = 0
len = 1
} else if (inflater.istate.was !== -1) { // in reading trailer
throw IOException("footer is not found")
} else {
throw EOFException("Unexpected end of ZLIB input stream")
}
}
inflater.setInput(buf, 0, len, true)
}
override fun markSupported(): Boolean {
return false
}
@Synchronized
override fun mark(readlimit: Int) {
}
@Synchronized
@Throws(IOException::class)
override fun reset() {
throw IOException("mark/reset not supported")
}
val totalIn: Long
get() = inflater.getTotalIn()
val totalOut: Long
get() = inflater.getTotalOut()
val availIn: ByteArray?
get() {
if (inflater.avail_in <= 0) return null
val tmp = ByteArray(inflater.avail_in)
java.lang.System.arraycopy(
inflater.next_in, inflater.next_in_index,
tmp, 0, inflater.avail_in
)
return tmp
}
@Throws(IOException::class)
fun readHeader() {
val empty: ByteArray = "".toByteArray()
inflater.setInput(empty, 0, 0, false)
inflater.setOutput(empty, 0, 0)
var err: Int = inflater.inflate(JZlib.Z_NO_FLUSH)
if (!inflater.istate.inParsingHeader()) {
return
}
val b1 = ByteArray(1)
do {
val i: Int = `in`.read(b1)
if (i <= 0) throw IOException("no input")
inflater.setInput(b1)
err = inflater.inflate(JZlib.Z_NO_FLUSH)
if (err != 0 /*Z_OK*/) throw IOException(inflater.msg)
} while (inflater.istate.inParsingHeader())
}
fun getInflater(): Inflater {
return inflater
}
companion object {
protected const val DEFAULT_BUFSIZE = 512
}
init {
if (`in` == null || inflater == null) {
throw NullPointerException()
} else if (size <= 0) {
throw java.lang.IllegalArgumentException("buffer size must be greater than 0")
}
this.inflater = inflater
buf = ByteArray(size)
this.close_in = close_in
}
} | benchmark_kotlin_mpp/wip/jzlib/InflaterInputStream.kt | 3187441361 |
/*
* Copyright (c) 2020. Rei Matsushita
*
* 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 me.rei_m.hyakuninisshu.state.application.action
import me.rei_m.hyakuninisshu.domain.karuta.model.KarutaRepository
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ApplicationActionCreator @Inject constructor(
private val karutaRepository: KarutaRepository
) {
/**
* 百人一首の情報を準備してアプリの利用を開始する.
*
* @return StartApplicationAction
*/
suspend fun start() = try {
karutaRepository.initialize()
StartApplicationAction.Success()
} catch (e: Exception) {
StartApplicationAction.Failure(e)
}
}
| state/src/main/java/me/rei_m/hyakuninisshu/state/application/action/ApplicationActionCreator.kt | 326270123 |
/*-
* #%L
* Restrulz
* %%
* Copyright (C) 2017 GantSign Ltd.
* %%
* 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.
* #L%
*/
package com.gantsign.restrulz.json.model.json.reader.impl
import com.fasterxml.jackson.core.JsonFactory
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.core.JsonToken
import com.gantsign.restrulz.json.model.TestEntity
import com.gantsign.restrulz.json.reader.JsonObjectReader
import java.io.InputStream
import kotlin.test.assertEquals
object TestEntityReader : JsonObjectReader<TestEntity> {
private fun readObject(parser: JsonParser): TestEntity {
assertEquals(expected = JsonToken.START_OBJECT, actual = parser.currentToken())
assertEquals(expected = JsonToken.FIELD_NAME, actual = parser.nextToken())
assertEquals(expected = JsonToken.VALUE_STRING, actual = parser.nextToken())
val id = parser.text
assertEquals(expected = JsonToken.END_OBJECT, actual = parser.nextToken())
return TestEntity(id)
}
override fun readObject(input: InputStream): TestEntity {
val jsonFactory = JsonFactory()
val parser = jsonFactory.createParser(input)
parser.nextToken()
return readObject(parser)
}
override fun readArray(input: InputStream): List<TestEntity> {
val jsonFactory = JsonFactory()
val parser = jsonFactory.createParser(input)
val results: MutableList<TestEntity> = mutableListOf()
assertEquals(expected = JsonToken.START_ARRAY, actual = parser.nextToken())
while (JsonToken.END_ARRAY !== parser.nextToken()) {
results.add(readObject(parser))
}
return results.toList()
}
}
| com.gantsign.restrulz.json/src/test/kotlin/com/gantsign/restrulz/json/model/json/reader/impl/TestEntityReader.kt | 4111796523 |
package com.geckour.egret.util
import android.databinding.BindingAdapter
import android.util.Patterns
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import jp.wasabeef.glide.transformations.RoundedCornersTransformation
import java.util.*
class DataBindingAdapter {
companion object {
@JvmStatic
@BindingAdapter("bind:imageUrl")
fun loadImage(view: ImageView, url: String?) {
if (url != null && Patterns.WEB_URL.matcher(url).matches()) {
Glide.with(view.context).load(url).apply(RequestOptions.bitmapTransform(RoundedCornersTransformation(view.context, 8, 0))).into(view)
}
}
@JvmStatic
@BindingAdapter("android:text")
fun setText(view: TextView, time: Date) {
view.text = Common.getReadableDateString(time.time)
}
@JvmStatic
@BindingAdapter("android:text")
fun setText(view: EditText, value: String) {
view.setText(value)
view.setSelection(value.length)
}
}
} | app/src/main/java/com/geckour/egret/util/DataBindingAdapter.kt | 2300126192 |
package org.http4k.security.oauth.server
import dev.forkhandles.result4k.Failure
import dev.forkhandles.result4k.Success
import dev.forkhandles.result4k.get
import dev.forkhandles.result4k.map
import dev.forkhandles.result4k.mapFailure
import org.http4k.core.Filter
import org.http4k.core.HttpHandler
import org.http4k.security.ResponseType
class ClientValidationFilter(
private val authoriseRequestValidator: AuthoriseRequestValidator,
private val errorRenderer: AuthoriseRequestErrorRender,
private val extractor: AuthRequestExtractor
) : Filter {
override fun invoke(next: HttpHandler): HttpHandler =
{
if (!validResponseTypes.contains(it.query("response_type"))) {
errorRenderer.errorFor(it, UnsupportedResponseType(it.query("response_type").orEmpty()))
} else {
extractor.extract(it).map { authorizationRequest ->
when (val result =
MustHaveRedirectUri(authoriseRequestValidator).validate(it, authorizationRequest)) {
is Success -> next(result.value)
is Failure -> errorRenderer.errorFor(it, result.reason)
}
}.mapFailure { error -> errorRenderer.errorFor(it, error) }.get()
}
}
companion object {
val validResponseTypes = ResponseType.values().map { it.queryParameterValue }
}
}
| http4k-security/oauth/src/main/kotlin/org/http4k/security/oauth/server/ClientValidationFilter.kt | 2546783518 |
package org.http4k.format
import com.beust.klaxon.Converter
import com.beust.klaxon.JsonValue
import org.http4k.lens.BiDiMapping
import java.math.BigDecimal
import java.math.BigInteger
import com.beust.klaxon.Klaxon as KKlaxon
fun KKlaxon.asConfigurable(klaxon: KKlaxon): AutoMappingConfiguration<KKlaxon> = object : AutoMappingConfiguration<KKlaxon> {
override fun <OUT> boolean(mapping: BiDiMapping<Boolean, OUT>) = apply {
addConverter(mapping)
}
override fun <OUT> int(mapping: BiDiMapping<Int, OUT>) = apply {
addConverter(mapping)
}
override fun <OUT> long(mapping: BiDiMapping<Long, OUT>) = apply {
addConverter(mapping)
}
override fun <OUT> double(mapping: BiDiMapping<Double, OUT>) = apply {
addConverter(mapping)
}
override fun <OUT> bigInteger(mapping: BiDiMapping<BigInteger, OUT>) = apply {
addConverter(mapping)
}
override fun <OUT> bigDecimal(mapping: BiDiMapping<BigDecimal, OUT>) = apply {
addConverter(mapping)
}
override fun <OUT> text(mapping: BiDiMapping<String, OUT>) = apply {
addConverter(mapping)
}
private fun <IN, OUT> addConverter(mapping: BiDiMapping<IN, OUT>,) {
klaxon.converter(object : Converter {
override fun canConvert(cls: Class<*>) = cls == mapping.clazz
@Suppress("UNCHECKED_CAST")
override fun fromJson(jv: JsonValue) = mapping.asOut(jv.inside as IN)
@Suppress("UNCHECKED_CAST")
override fun toJson(value: Any): String {
val asIn = mapping.asIn(value as OUT)
return if (asIn is String) """"$asIn"""" else asIn.toString()
}
})
}
override fun done(): KKlaxon = klaxon
}
| http4k-format/klaxon/src/main/kotlin/org/http4k/format/klaxonExtensions.kt | 1581767697 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore
import com.intellij.externalDependencies.DependencyOnPlugin
import com.intellij.externalDependencies.ExternalDependenciesManager
import com.intellij.externalDependencies.ProjectExternalDependency
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ex.PathManagerEx
import com.intellij.openapi.components.*
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.util.JDOMUtil
import com.intellij.testFramework.*
import com.intellij.testFramework.assertions.Assertions.assertThat
import com.intellij.testFramework.rules.InMemoryFsRule
import com.intellij.util.io.delete
import com.intellij.util.io.getDirectoryTree
import com.intellij.util.isEmpty
import com.intellij.util.loadElement
import kotlinx.coroutines.runBlocking
import org.jdom.Element
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import java.nio.file.Paths
private const val TEST_COMPONENT_NAME = "DefaultProjectStoreTestComponent"
@State(name = TEST_COMPONENT_NAME, storages = [(Storage(value = "testSchemes", stateSplitter = TestStateSplitter::class))])
private class TestComponent : PersistentStateComponent<Element> {
private var element = Element("state")
override fun getState() = element.clone()
override fun loadState(state: Element) {
element = state.clone()
}
}
internal class DefaultProjectStoreTest {
companion object {
@JvmField
@ClassRule
val projectRule = ProjectRule()
}
@JvmField
@Rule
val fsRule = InMemoryFsRule()
private val tempDirManager = TemporaryDirectory()
private val requiredPlugins = listOf<ProjectExternalDependency>(DependencyOnPlugin("fake", "0", "1"))
@JvmField
@Rule
val ruleChain = RuleChain(
tempDirManager,
WrapRule {
val path = Paths.get(ApplicationManager.getApplication().stateStore.storageManager.expandMacros(APP_CONFIG))
return@WrapRule {
path.delete()
}
}
)
@Test
fun `new project from default - file-based storage`() = runBlocking {
val externalDependenciesManager = ProjectManager.getInstance().defaultProject.service<ExternalDependenciesManager>()
externalDependenciesManager.allDependencies = requiredPlugins
try {
createProjectAndUseInLoadComponentStateMode(tempDirManager) {
assertThat(it.service<ExternalDependenciesManager>().allDependencies).isEqualTo(requiredPlugins)
}
}
finally {
externalDependenciesManager.allDependencies = emptyList()
}
}
@Test
fun `new project from default - directory-based storage`() = runBlocking {
val defaultProject = ProjectManager.getInstance().defaultProject
val defaultTestComponent = TestComponent()
defaultTestComponent.loadState(JDOMUtil.load("""
<component>
<main name="$TEST_COMPONENT_NAME"/><sub name="foo" /><sub name="bar" />
</component>""".trimIndent()))
val stateStore = defaultProject.stateStore as ComponentStoreImpl
stateStore.initComponent(defaultTestComponent, true)
try {
// obviously, project must be directory-based also
createProjectAndUseInLoadComponentStateMode(tempDirManager, directoryBased = true) {
val component = TestComponent()
it.stateStore.initComponent(component, true)
assertThat(component.state).isEqualTo(defaultTestComponent.state)
}
}
finally {
// clear state
defaultTestComponent.loadState(Element("empty"))
defaultProject.stateStore.save()
stateStore.removeComponent(TEST_COMPONENT_NAME)
}
}
@Test
fun `new project from default - remove workspace component configuration`() {
val testData = Paths.get(PathManagerEx.getCommunityHomePath(), "platform/configuration-store-impl/testData")
val element = loadElement(testData.resolve("testData1.xml"))
val tempDir = fsRule.fs.getPath("")
normalizeDefaultProjectElement(ProjectManager.getInstance().defaultProject, element, tempDir)
assertThat(element.isEmpty()).isTrue()
val directoryTree = tempDir.getDirectoryTree()
assertThat(directoryTree.trim()).isEqualTo(testData.resolve("testData1.txt"))
}
@Test
fun `new IPR project from default - remove workspace component configuration`() {
val testData = Paths.get(PathManagerEx.getCommunityHomePath(), "platform/configuration-store-impl/testData")
val element = loadElement(testData.resolve("testData1.xml"))
val tempDir = fsRule.fs.getPath("")
moveComponentConfiguration(ProjectManager.getInstance().defaultProject, element) { if (it == "workspace.xml") tempDir.resolve("test.iws") else tempDir.resolve("test.ipr") }
assertThat(element).isEqualTo(loadElement(testData.resolve("normalize-ipr.xml")))
val directoryTree = tempDir.getDirectoryTree()
assertThat(directoryTree.trim()).isEqualTo(testData.resolve("testData1-ipr.txt"))
}
} | platform/configuration-store-impl/testSrc/DefaultProjectStoreTest.kt | 3200865444 |
package kodando.elmish
interface Component<in TArg, TModel, TMessage> {
fun init(data: TArg): Result<TModel, TMessage>
fun update(model: TModel, message: TMessage): Result<TModel, TMessage>
fun render(model: TModel, dispatch: Dispatch<TMessage>): View
}
| kodando-elmish/src/main/kotlin/kodando/elmish/Component.kt | 2818402553 |
package me.sweetll.tucao.business.video.model
class ReplyResponse(
val commentid: String,
val title: String,
val total: String,
val url: String,
val lastupdate: String,
val data: Map<String, Reply>
)
| app/src/main/kotlin/me/sweetll/tucao/business/video/model/ReplyResponse.kt | 2153738121 |
/*
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.context.properties.bind;
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatIllegalStateException
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
/**
* Tests for `DefaultBindConstructorProvider`.
*
* @author Madhura Bhave
*/
@Suppress("unused")
class KotlinDefaultBindConstructorProviderTests {
private val constructorProvider = DefaultBindConstructorProvider()
@Test
fun `type with default constructor should register java bean`() {
val bindConstructor = this.constructorProvider.getBindConstructor(FooProperties::class.java, false)
assertThat(bindConstructor).isNull()
}
@Test
fun `type with no primary constructor should register java bean`() {
val bindConstructor = this.constructorProvider.getBindConstructor(MultipleAmbiguousConstructors::class.java, false)
assertThat(bindConstructor).isNull()
}
@Test
fun `type with primary and secondary annotated constructor should use secondary constructor for binding`() {
val bindConstructor = this.constructorProvider.getBindConstructor(ConstructorBindingOnSecondaryWithPrimaryConstructor::class.java, false)
assertThat(bindConstructor).isNotNull();
}
@Test
fun `type with primary constructor with autowired should not use constructor binding`() {
val bindConstructor = this.constructorProvider.getBindConstructor(AutowiredPrimaryProperties::class.java, false)
assertThat(bindConstructor).isNull()
}
@Test
fun `type with primary and secondary constructor with autowired should not use constructor binding`() {
val bindConstructor = this.constructorProvider.getBindConstructor(PrimaryWithAutowiredSecondaryProperties::class.java, false)
assertThat(bindConstructor).isNull()
}
@Test
fun `type with autowired secondary constructor should not use constructor binding`() {
val bindConstructor = this.constructorProvider.getBindConstructor(AutowiredSecondaryProperties::class.java, false)
assertThat(bindConstructor).isNull()
}
@Test
fun `type with autowired primary and constructor binding on secondary constructor should throw exception`() {
assertThatIllegalStateException().isThrownBy {
this.constructorProvider.getBindConstructor(ConstructorBindingOnSecondaryAndAutowiredPrimaryProperties::class.java, false)
}
}
@Test
fun `type with autowired secondary and constructor binding on primary constructor should throw exception`() {
assertThatIllegalStateException().isThrownBy {
this.constructorProvider.getBindConstructor(ConstructorBindingOnPrimaryAndAutowiredSecondaryProperties::class.java, false)
}
}
@Test
fun `type with primary constructor and no annotation should use constructor binding`() {
val bindConstructor = this.constructorProvider.getBindConstructor(ConstructorBindingPrimaryConstructorNoAnnotation::class.java, false)
assertThat(bindConstructor).isNotNull()
}
@Test
fun `type with secondary constructor and no annotation should use constructor binding`() {
val bindConstructor = this.constructorProvider.getBindConstructor(ConstructorBindingSecondaryConstructorNoAnnotation::class.java, false)
assertThat(bindConstructor).isNotNull()
}
@Test
fun `type with multiple constructors`() {
val bindConstructor = this.constructorProvider.getBindConstructor(ConstructorBindingMultipleConstructors::class.java, false)
assertThat(bindConstructor).isNotNull()
}
@Test
fun `type with multiple annotated constructors should throw exception`() {
assertThatIllegalStateException().isThrownBy {
this.constructorProvider.getBindConstructor(ConstructorBindingMultipleAnnotatedConstructors::class.java, false)
}
}
@Test
fun `type with secondary and primary annotated constructors should throw exception`() {
assertThatIllegalStateException().isThrownBy {
this.constructorProvider.getBindConstructor(ConstructorBindingSecondaryAndPrimaryAnnotatedConstructors::class.java, false)
}
}
@Test
fun `data class with default values should use constructor binding`() {
val bindConstructor = this.constructorProvider.getBindConstructor(ConstructorBindingDataClassWithDefaultValues::class.java, false)
assertThat(bindConstructor).isNotNull();
}
class FooProperties
class PrimaryWithAutowiredSecondaryProperties constructor(val name: String?, val counter: Int = 42) {
@Autowired
constructor(@Suppress("UNUSED_PARAMETER") foo: String) : this(foo, 21)
}
class AutowiredSecondaryProperties {
@Autowired
constructor(@Suppress("UNUSED_PARAMETER") foo: String)
}
class AutowiredPrimaryProperties @Autowired constructor(val name: String?, val counter: Int = 42) {
}
class ConstructorBindingOnSecondaryAndAutowiredPrimaryProperties @Autowired constructor(val name: String?, val counter: Int = 42) {
@ConstructorBinding
constructor(@Suppress("UNUSED_PARAMETER") foo: String) : this(foo, 21)
}
class ConstructorBindingOnPrimaryAndAutowiredSecondaryProperties @ConstructorBinding constructor(val name: String?, val counter: Int = 42) {
@Autowired
constructor(@Suppress("UNUSED_PARAMETER") foo: String) : this(foo, 21)
}
class ConstructorBindingOnSecondaryWithPrimaryConstructor constructor(val name: String?, val counter: Int = 42) {
@ConstructorBinding
constructor(@Suppress("UNUSED_PARAMETER") foo: String) : this(foo, 21)
}
class ConstructorBindingOnPrimaryWithSecondaryConstructor @ConstructorBinding constructor(val name: String?, val counter: Int = 42) {
constructor(@Suppress("UNUSED_PARAMETER") foo: String) : this(foo, 21)
}
class ConstructorBindingPrimaryConstructorNoAnnotation(val name: String?, val counter: Int = 42)
class ConstructorBindingSecondaryConstructorNoAnnotation {
constructor(@Suppress("UNUSED_PARAMETER") foo: String)
}
class MultipleAmbiguousConstructors {
constructor()
constructor(@Suppress("UNUSED_PARAMETER") foo: String)
}
class ConstructorBindingMultipleConstructors {
constructor(@Suppress("UNUSED_PARAMETER") bar: Int)
@ConstructorBinding
constructor(@Suppress("UNUSED_PARAMETER") foo: String)
}
class ConstructorBindingMultipleAnnotatedConstructors {
@ConstructorBinding
constructor(@Suppress("UNUSED_PARAMETER") bar: Int)
@ConstructorBinding
constructor(@Suppress("UNUSED_PARAMETER") foo: String)
}
class ConstructorBindingSecondaryAndPrimaryAnnotatedConstructors @ConstructorBinding constructor(val name: String?, val counter: Int = 42) {
@ConstructorBinding
constructor(@Suppress("UNUSED_PARAMETER") foo: String) : this(foo, 21)
}
data class ConstructorBindingDataClassWithDefaultValues(val name: String = "Joan", val counter: Int = 42)
} | spring-boot-project/spring-boot/src/test/kotlin/org/springframework/boot/context/properties/bind/KotlinDefaultBindConstructorProviderTests.kt | 1418577391 |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.ktfmt.format
import com.google.common.base.Throwables
import com.google.common.collect.ImmutableList
import com.google.googlejavaformat.Doc
import com.google.googlejavaformat.FormattingError
import com.google.googlejavaformat.Indent
import com.google.googlejavaformat.Indent.Const.ZERO
import com.google.googlejavaformat.OpsBuilder
import com.google.googlejavaformat.Output
import com.google.googlejavaformat.Output.BreakTag
import java.util.ArrayDeque
import java.util.Optional
import org.jetbrains.kotlin.com.intellij.psi.PsiComment
import org.jetbrains.kotlin.com.intellij.psi.PsiElement
import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtAnnotatedExpression
import org.jetbrains.kotlin.psi.KtAnnotation
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtAnnotationUseSiteTarget
import org.jetbrains.kotlin.psi.KtArrayAccessExpression
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtBinaryExpressionWithTypeRHS
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtBreakExpression
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtCallableReferenceExpression
import org.jetbrains.kotlin.psi.KtCatchClause
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtClassInitializer
import org.jetbrains.kotlin.psi.KtClassLiteralExpression
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtCollectionLiteralExpression
import org.jetbrains.kotlin.psi.KtConstantExpression
import org.jetbrains.kotlin.psi.KtConstructorDelegationCall
import org.jetbrains.kotlin.psi.KtContainerNode
import org.jetbrains.kotlin.psi.KtContinueExpression
import org.jetbrains.kotlin.psi.KtDelegatedSuperTypeEntry
import org.jetbrains.kotlin.psi.KtDestructuringDeclaration
import org.jetbrains.kotlin.psi.KtDestructuringDeclarationEntry
import org.jetbrains.kotlin.psi.KtDoWhileExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtDynamicType
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtEnumEntry
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtFileAnnotationList
import org.jetbrains.kotlin.psi.KtFinallySection
import org.jetbrains.kotlin.psi.KtForExpression
import org.jetbrains.kotlin.psi.KtFunctionType
import org.jetbrains.kotlin.psi.KtIfExpression
import org.jetbrains.kotlin.psi.KtImportDirective
import org.jetbrains.kotlin.psi.KtImportList
import org.jetbrains.kotlin.psi.KtIntersectionType
import org.jetbrains.kotlin.psi.KtIsExpression
import org.jetbrains.kotlin.psi.KtLabelReferenceExpression
import org.jetbrains.kotlin.psi.KtLabeledExpression
import org.jetbrains.kotlin.psi.KtLambdaArgument
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.psi.KtModifierList
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtNullableType
import org.jetbrains.kotlin.psi.KtPackageDirective
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtParameterList
import org.jetbrains.kotlin.psi.KtParenthesizedExpression
import org.jetbrains.kotlin.psi.KtPostfixExpression
import org.jetbrains.kotlin.psi.KtPrefixExpression
import org.jetbrains.kotlin.psi.KtPrimaryConstructor
import org.jetbrains.kotlin.psi.KtProjectionKind
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPropertyAccessor
import org.jetbrains.kotlin.psi.KtPropertyDelegate
import org.jetbrains.kotlin.psi.KtQualifiedExpression
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.psi.KtReturnExpression
import org.jetbrains.kotlin.psi.KtScript
import org.jetbrains.kotlin.psi.KtSecondaryConstructor
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
import org.jetbrains.kotlin.psi.KtSuperExpression
import org.jetbrains.kotlin.psi.KtSuperTypeCallEntry
import org.jetbrains.kotlin.psi.KtSuperTypeList
import org.jetbrains.kotlin.psi.KtThisExpression
import org.jetbrains.kotlin.psi.KtThrowExpression
import org.jetbrains.kotlin.psi.KtTreeVisitorVoid
import org.jetbrains.kotlin.psi.KtTryExpression
import org.jetbrains.kotlin.psi.KtTypeAlias
import org.jetbrains.kotlin.psi.KtTypeArgumentList
import org.jetbrains.kotlin.psi.KtTypeConstraint
import org.jetbrains.kotlin.psi.KtTypeConstraintList
import org.jetbrains.kotlin.psi.KtTypeParameter
import org.jetbrains.kotlin.psi.KtTypeParameterList
import org.jetbrains.kotlin.psi.KtTypeProjection
import org.jetbrains.kotlin.psi.KtTypeReference
import org.jetbrains.kotlin.psi.KtUserType
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.psi.KtValueArgumentList
import org.jetbrains.kotlin.psi.KtWhenConditionInRange
import org.jetbrains.kotlin.psi.KtWhenConditionIsPattern
import org.jetbrains.kotlin.psi.KtWhenConditionWithExpression
import org.jetbrains.kotlin.psi.KtWhenExpression
import org.jetbrains.kotlin.psi.KtWhileExpression
import org.jetbrains.kotlin.psi.psiUtil.children
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.psi.psiUtil.startsWithComment
/** An AST visitor that builds a stream of {@link Op}s to format. */
class KotlinInputAstVisitor(
private val options: FormattingOptions,
private val builder: OpsBuilder
) : KtTreeVisitorVoid() {
private val isGoogleStyle = options.style == FormattingOptions.Style.GOOGLE
/** Standard indentation for a block */
private val blockIndent: Indent.Const = Indent.Const.make(options.blockIndent, 1)
/**
* Standard indentation for a long expression or function call, it is different than block
* indentation on purpose
*/
private val expressionBreakIndent: Indent.Const = Indent.Const.make(options.continuationIndent, 1)
private val blockPlusExpressionBreakIndent: Indent.Const =
Indent.Const.make(options.blockIndent + options.continuationIndent, 1)
private val doubleExpressionBreakIndent: Indent.Const =
Indent.Const.make(options.continuationIndent, 2)
private val expressionBreakNegativeIndent: Indent.Const =
Indent.Const.make(-options.continuationIndent, 1)
/** A record of whether we have visited into an expression. */
private val inExpression = ArrayDeque(ImmutableList.of(false))
/** Tracks whether we are handling an import directive */
private var inImport = false
/** Example: `fun foo(n: Int) { println(n) }` */
override fun visitNamedFunction(function: KtNamedFunction) {
builder.sync(function)
builder.block(ZERO) {
visitFunctionLikeExpression(
function.modifierList,
"fun",
function.typeParameterList,
function.receiverTypeReference,
function.nameIdentifier?.text,
true,
function.valueParameterList,
function.typeConstraintList,
function.bodyBlockExpression,
function.bodyExpression,
function.typeReference,
function.bodyBlockExpression?.lBrace != null)
}
}
/** Example `Int`, `(String)` or `() -> Int` */
override fun visitTypeReference(typeReference: KtTypeReference) {
builder.sync(typeReference)
// Normally we'd visit the children nodes through accessors on 'typeReference', and we wouldn't
// loop over children.
// But, in this case the modifier list can either be inside the parenthesis:
// ... (@Composable (x) -> Unit)
// or outside of them:
// ... @Composable ((x) -> Unit)
val modifierList = typeReference.modifierList
val typeElement = typeReference.typeElement
for (child in typeReference.node.children()) {
when {
child.psi == modifierList -> visit(modifierList)
child.psi == typeElement -> visit(typeElement)
child.elementType == KtTokens.LPAR -> builder.token("(")
child.elementType == KtTokens.RPAR -> builder.token(")")
}
}
}
override fun visitDynamicType(type: KtDynamicType) {
builder.token("dynamic")
}
/** Example: `String?` or `((Int) -> Unit)?` */
override fun visitNullableType(nullableType: KtNullableType) {
builder.sync(nullableType)
val innerType = nullableType.innerType
val addParenthesis = innerType is KtFunctionType
if (addParenthesis) {
builder.token("(")
}
visit(nullableType.modifierList)
visit(innerType)
if (addParenthesis) {
builder.token(")")
}
builder.token("?")
}
/** Example: `String` or `List<Int>`, */
override fun visitUserType(type: KtUserType) {
builder.sync(type)
if (type.qualifier != null) {
visit(type.qualifier)
builder.token(".")
}
visit(type.referenceExpression)
val typeArgumentList = type.typeArgumentList
if (typeArgumentList != null) {
builder.block(expressionBreakIndent) { visit(typeArgumentList) }
}
}
/** Example: `A & B`, */
override fun visitIntersectionType(type: KtIntersectionType) {
builder.sync(type)
// TODO(strulovich): Should this have the same indentation behaviour as `x && y`?
visit(type.getLeftTypeRef())
builder.space()
builder.token("&")
builder.space()
visit(type.getRightTypeRef())
}
/** Example `<Int, String>` in `List<Int, String>` */
override fun visitTypeArgumentList(typeArgumentList: KtTypeArgumentList) {
builder.sync(typeArgumentList)
visitEachCommaSeparated(
typeArgumentList.arguments,
typeArgumentList.trailingComma != null,
prefix = "<",
postfix = ">",
)
}
override fun visitTypeProjection(typeProjection: KtTypeProjection) {
builder.sync(typeProjection)
val typeReference = typeProjection.typeReference
when (typeProjection.projectionKind) {
KtProjectionKind.IN -> {
builder.token("in")
builder.space()
visit(typeReference)
}
KtProjectionKind.OUT -> {
builder.token("out")
builder.space()
visit(typeReference)
}
KtProjectionKind.STAR -> builder.token("*")
KtProjectionKind.NONE -> visit(typeReference)
}
}
/**
* @param keyword e.g., "fun" or "class".
* @param typeOrDelegationCall for functions, the return typeOrDelegationCall; for classes, the
* list of supertypes.
*/
private fun visitFunctionLikeExpression(
modifierList: KtModifierList?,
keyword: String,
typeParameters: KtTypeParameterList?,
receiverTypeReference: KtTypeReference?,
name: String?,
emitParenthesis: Boolean,
parameterList: KtParameterList?,
typeConstraintList: KtTypeConstraintList?,
bodyBlockExpression: KtBlockExpression?,
nonBlockBodyExpressions: KtExpression?,
typeOrDelegationCall: KtElement?,
emitBraces: Boolean
) {
builder.block(ZERO) {
if (modifierList != null) {
visitModifierList(modifierList)
}
builder.token(keyword)
if (typeParameters != null) {
builder.space()
builder.block(ZERO) { visit(typeParameters) }
}
if (name != null || receiverTypeReference != null) {
builder.space()
}
builder.block(ZERO) {
if (receiverTypeReference != null) {
visit(receiverTypeReference)
builder.breakOp(Doc.FillMode.INDEPENDENT, "", expressionBreakIndent)
builder.token(".")
}
if (name != null) {
builder.token(name)
}
}
if (emitParenthesis) {
builder.token("(")
}
var paramBlockNeedsClosing = false
builder.block(ZERO) {
if (parameterList != null && parameterList.parameters.isNotEmpty()) {
paramBlockNeedsClosing = true
builder.open(expressionBreakIndent)
builder.breakOp(Doc.FillMode.UNIFIED, "", expressionBreakIndent)
visit(parameterList)
}
if (emitParenthesis) {
if (parameterList != null && parameterList.parameters.isNotEmpty()) {
builder.breakOp(Doc.FillMode.UNIFIED, "", expressionBreakNegativeIndent)
}
builder.token(")")
} else {
if (paramBlockNeedsClosing) {
builder.close()
}
}
if (typeOrDelegationCall != null) {
builder.block(ZERO) {
if (typeOrDelegationCall is KtConstructorDelegationCall) {
builder.space()
}
builder.token(":")
if (parameterList?.parameters.isNullOrEmpty()) {
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", expressionBreakIndent)
builder.block(expressionBreakIndent) { visit(typeOrDelegationCall) }
} else {
builder.space()
builder.block(expressionBreakNegativeIndent) { visit(typeOrDelegationCall) }
}
}
}
}
if (paramBlockNeedsClosing) {
builder.close()
}
if (typeConstraintList != null) {
builder.space()
visit(typeConstraintList)
}
if (bodyBlockExpression != null) {
builder.space()
visitBlockBody(bodyBlockExpression, emitBraces)
} else if (nonBlockBodyExpressions != null) {
builder.space()
builder.block(ZERO) {
builder.token("=")
if (isLambdaOrScopingFunction(nonBlockBodyExpressions)) {
visitLambdaOrScopingFunction(nonBlockBodyExpressions)
} else {
builder.block(expressionBreakIndent) {
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", ZERO)
builder.block(ZERO) { visit(nonBlockBodyExpressions) }
}
}
}
}
builder.guessToken(";")
}
if (name != null) {
builder.forcedBreak()
}
}
private fun genSym(): Output.BreakTag {
return Output.BreakTag()
}
private fun visitBlockBody(bodyBlockExpression: PsiElement, emitBraces: Boolean) {
if (emitBraces) {
builder.token("{", Doc.Token.RealOrImaginary.REAL, blockIndent, Optional.of(blockIndent))
}
val statements = bodyBlockExpression.children
if (statements.isNotEmpty()) {
builder.block(blockIndent) {
builder.forcedBreak()
builder.blankLineWanted(OpsBuilder.BlankLineWanted.PRESERVE)
visitStatements(statements)
}
builder.forcedBreak()
builder.blankLineWanted(OpsBuilder.BlankLineWanted.NO)
}
if (emitBraces) {
builder.token("}", blockIndent)
}
}
private fun visitStatement(statement: PsiElement) {
builder.block(ZERO) { visit(statement) }
builder.guessToken(";")
}
private fun visitStatements(statements: Array<PsiElement>) {
var first = true
builder.guessToken(";")
for (statement in statements) {
builder.forcedBreak()
if (!first) {
builder.blankLineWanted(OpsBuilder.BlankLineWanted.PRESERVE)
}
first = false
visitStatement(statement)
}
}
override fun visitProperty(property: KtProperty) {
builder.sync(property)
builder.block(ZERO) {
declareOne(
kind = DeclarationKind.FIELD,
modifiers = property.modifierList,
valOrVarKeyword = property.valOrVarKeyword.text,
typeParameters = property.typeParameterList,
receiver = property.receiverTypeReference,
name = property.nameIdentifier?.text,
type = property.typeReference,
typeConstraintList = property.typeConstraintList,
delegate = property.delegate,
initializer = property.initializer,
accessors = property.accessors)
}
builder.guessToken(";")
if (property.parent !is KtWhenExpression) {
builder.forcedBreak()
}
}
/**
* Example: "com.facebook.bla.bla" in imports or "a.b.c.d" in expressions.
*
* There's a few cases that are different. We deal with imports by keeping them on the same line.
* For regular chained expressions we go the left most descendant so we can start indentation only
* before the first break (a `.` or `?.`), and keep the seem indentation for this chain of calls.
*/
override fun visitQualifiedExpression(expression: KtQualifiedExpression) {
builder.sync(expression)
val receiver = expression.receiverExpression
when {
inImport -> {
visit(receiver)
val selectorExpression = expression.selectorExpression
if (selectorExpression != null) {
builder.token(".")
visit(selectorExpression)
}
}
receiver is KtStringTemplateExpression -> {
val isMultiline = receiver.text.contains('\n')
builder.block(if (isMultiline) expressionBreakIndent else ZERO) {
visit(receiver)
if (isMultiline) {
builder.forcedBreak()
}
builder.token(expression.operationSign.value)
visit(expression.selectorExpression)
}
}
receiver is KtWhenExpression -> {
builder.block(ZERO) {
visit(receiver)
builder.token(expression.operationSign.value)
visit(expression.selectorExpression)
}
}
else -> {
emitQualifiedExpression(expression)
}
}
}
/** Extra data to help [emitQualifiedExpression] know when to open and close a group */
private class GroupingInfo {
var groupOpenCount = 0
var shouldCloseGroup = false
}
/**
* Handles a chain of qualified expressions, i.e. `a[5].b!!.c()[4].f()`
*
* This is by far the most complicated part of this formatter. We start by breaking the expression
* to the steps it is executed in (which are in the opposite order of how the syntax tree is
* built).
*
* We then calculate information to know which parts need to be groups, and finally go part by
* part, emitting it to the [builder] while closing and opening groups.
*/
private fun emitQualifiedExpression(expression: KtExpression) {
val parts = breakIntoParts(expression)
// whether we want to make a lambda look like a block, this make Kotlin DSLs look as expected
val useBlockLikeLambdaStyle = parts.last().isLambda() && parts.count { it.isLambda() } == 1
val groupingInfos = computeGroupingInfo(parts, useBlockLikeLambdaStyle)
builder.block(expressionBreakIndent) {
val nameTag = genSym() // allows adjusting arguments indentation if a break will be made
for ((index, ktExpression) in parts.withIndex()) {
if (ktExpression is KtQualifiedExpression) {
builder.breakOp(Doc.FillMode.UNIFIED, "", ZERO, Optional.of(nameTag))
}
repeat(groupingInfos[index].groupOpenCount) { builder.open(ZERO) }
when (ktExpression) {
is KtQualifiedExpression -> {
builder.token(ktExpression.operationSign.value)
val selectorExpression = ktExpression.selectorExpression
if (selectorExpression !is KtCallExpression) {
// selector is a simple field access
visit(selectorExpression)
if (groupingInfos[index].shouldCloseGroup) {
builder.close()
}
} else {
// selector is a function call, we may close a group after its name
// emit `doIt` from `doIt(1, 2) { it }`
visit(selectorExpression.calleeExpression)
// close groups according to instructions
if (groupingInfos[index].shouldCloseGroup) {
builder.close()
}
// close group due to last lambda to allow block-like style in `as.forEach { ... }`
val isTrailingLambda = useBlockLikeLambdaStyle && index == parts.size - 1
if (isTrailingLambda) {
builder.close()
}
val argsIndentElse = if (index == parts.size - 1) ZERO else expressionBreakIndent
val lambdaIndentElse = if (isTrailingLambda) expressionBreakNegativeIndent else ZERO
val negativeLambdaIndentElse = if (isTrailingLambda) expressionBreakIndent else ZERO
// emit `(1, 2) { it }` from `doIt(1, 2) { it }`
visitCallElement(
null,
selectorExpression.typeArgumentList,
selectorExpression.valueArgumentList,
selectorExpression.lambdaArguments,
argumentsIndent = Indent.If.make(nameTag, expressionBreakIndent, argsIndentElse),
lambdaIndent = Indent.If.make(nameTag, ZERO, lambdaIndentElse),
negativeLambdaIndent = Indent.If.make(nameTag, ZERO, negativeLambdaIndentElse),
)
}
}
is KtArrayAccessExpression -> {
visitArrayAccessBrackets(ktExpression)
builder.close()
}
is KtPostfixExpression -> {
builder.token(ktExpression.operationReference.text)
builder.close()
}
else -> {
check(index == 0)
visit(ktExpression)
}
}
}
}
}
/**
* Decomposes a qualified expression into parts, so `rainbow.red.orange.yellow` becomes `[rainbow,
* rainbow.red, rainbow.red.orange, rainbow.orange.yellow]`
*/
private fun breakIntoParts(expression: KtExpression): List<KtExpression> {
val parts = ArrayDeque<KtExpression>()
// use an ArrayDeque and add elements to the beginning so the innermost expression comes first
// foo.bar.yay -> [yay, bar.yay, foo.bar.yay]
var node: KtExpression? = expression
while (node != null) {
parts.addFirst(node)
node =
when (node) {
is KtQualifiedExpression -> node.receiverExpression
is KtArrayAccessExpression -> node.arrayExpression
is KtPostfixExpression -> node.baseExpression
else -> null
}
}
return parts.toList()
}
/**
* Generates the [GroupingInfo] array to go with an array of [KtQualifiedExpression] parts
*
* For example, the expression `a.b[2].c.d()` is made of four expressions:
* 1. [KtQualifiedExpression] `a.b[2].c . d()` (this will be `parts[4]`)
* 1. [KtQualifiedExpression] `a.b[2] . c` (this will be `parts[3]`)
* 2. [KtArrayAccessExpression] `a.b [2]` (this will be `parts[2]`)
* 3. [KtQualifiedExpression] `a . b` (this will be `parts[1]`)
* 4. [KtSimpleNameExpression] `a` (this will be `parts[0]`)
*
* Once in parts, these are in the reverse order. To render the array correct we need to make sure
* `b` and [2] are in a group so we avoid splitting them. To do so we need to open a group for `b`
* (that will be done in part 2), and always close a group for an array.
*
* Here is the same expression, with justified braces marking the groupings it will get:
* ```
* a . b [2] . c . d ()
* {a . b} --> Grouping `a.b` because it can be a package name or simple field access so we add 1
* to the number of groups to open at groupingInfos[0], and mark to close a group at
* groupingInfos[1]
* {a . b [2]} --> Grouping `a.b` with `[2]`, since otherwise we may break inside the brackets
* instead of preferring breaks before dots. So we open a group at [0], but since
* we always close a group after brackets, we don't store that information.
* {c . d} --> another group to attach the first function name to the fields before it
* this time we don't start the group in the beginning, and use
* lastIndexToOpen to track the spot after the last time we stopped
* grouping.
* ```
* The final expression with groupings:
* ```
* {{a.b}[2]}.{c.d}()
* ```
*/
private fun computeGroupingInfo(
parts: List<KtExpression>,
useBlockLikeLambdaStyle: Boolean
): List<GroupingInfo> {
val groupingInfos = List(parts.size) { GroupingInfo() }
var lastIndexToOpen = 0
for ((index, part) in parts.withIndex()) {
when (part) {
is KtQualifiedExpression -> {
val receiverExpression = part.receiverExpression
val previous =
(receiverExpression as? KtQualifiedExpression)?.selectorExpression
?: receiverExpression
val current = checkNotNull(part.selectorExpression)
if (lastIndexToOpen == 0 &&
shouldGroupPartWithPrevious(parts, part, index, previous, current)) {
// this and the previous items should be grouped for better style
// we add another group to open in index 0
groupingInfos[0].groupOpenCount++
// we don't always close a group when emitting this node, so we need this flag to
// mark if we need to close a group
groupingInfos[index].shouldCloseGroup = true
} else {
// use this index in to open future groups for arrays and postfixes
// we will also stop grouping field access to the beginning of the expression
lastIndexToOpen = index
}
}
is KtArrayAccessExpression,
is KtPostfixExpression -> {
// we group these with the last item with a name, and we always close them
groupingInfos[lastIndexToOpen].groupOpenCount++
}
}
}
if (useBlockLikeLambdaStyle) {
// a trailing lambda adds a group that we stop before emitting the lambda
groupingInfos[0].groupOpenCount++
}
return groupingInfos
}
/** Decide whether a [KtQualifiedExpression] part should be grouped with the previous part */
private fun shouldGroupPartWithPrevious(
parts: List<KtExpression>,
part: KtExpression,
index: Int,
previous: KtExpression,
current: KtExpression
): Boolean {
// this is the second, and the first is short, avoid `.` "hanging in air"
if (index == 1 && previous.text.length < options.continuationIndent) {
return true
}
// the previous part is `this` or `super`
if (previous is KtSuperExpression || previous is KtThisExpression) {
return true
}
// this and the previous part are a package name, type name, or property
if (previous is KtSimpleNameExpression &&
current is KtSimpleNameExpression &&
part is KtDotQualifiedExpression) {
return true
}
// this is `Foo` in `com.facebook.Foo`, so everything before it is a package name
if (current.text.first().isUpperCase() &&
current is KtSimpleNameExpression &&
part is KtDotQualifiedExpression) {
return true
}
// this is the `foo()` in `com.facebook.Foo.foo()` or in `Foo.foo()`
if (current is KtCallExpression &&
(previous !is KtCallExpression) &&
previous.text?.firstOrNull()?.isUpperCase() == true) {
return true
}
// this is an invocation and the last item, and the previous it not, i.e. `a.b.c()`
// keeping it grouped and splitting the arguments makes `a.b(...)` feel like `aab()`
return current is KtCallExpression &&
previous !is KtCallExpression &&
index == parts.indices.last
}
/** Returns true if the expression represents an invocation that is also a lambda */
private fun KtExpression.isLambda(): Boolean {
return extractCallExpression(this)?.lambdaArguments?.isNotEmpty() ?: false
}
/**
* emitQualifiedExpression formats call expressions that are either part of a qualified
* expression, or standing alone. This method makes it easier to handle both cases uniformly.
*/
private fun extractCallExpression(expression: KtExpression): KtCallExpression? {
val ktExpression = (expression as? KtQualifiedExpression)?.selectorExpression ?: expression
return ktExpression as? KtCallExpression
}
override fun visitCallExpression(callExpression: KtCallExpression) {
builder.sync(callExpression)
with(callExpression) {
visitCallElement(
calleeExpression,
typeArgumentList,
valueArgumentList,
lambdaArguments,
)
}
}
/**
* Examples `foo<T>(a, b)`, `foo(a)`, `boo()`, `super(a)`
*
* @param lambdaIndent how to indent [lambdaArguments], if present
* @param negativeLambdaIndent the negative indentation of [lambdaIndent]
*/
private fun visitCallElement(
callee: KtExpression?,
typeArgumentList: KtTypeArgumentList?,
argumentList: KtValueArgumentList?,
lambdaArguments: List<KtLambdaArgument>,
argumentsIndent: Indent = expressionBreakIndent,
lambdaIndent: Indent = ZERO,
negativeLambdaIndent: Indent = ZERO,
) {
// Apply the lambda indent to the callee, type args, value args, and the lambda.
// This is undone for the first three by the negative lambda indent.
// This way they're in one block, and breaks in the argument list cause a break in the lambda.
builder.block(lambdaIndent) {
// Used to keep track of whether or not we need to indent the lambda
// This is based on if there is a break in the argument list
var brokeBeforeBrace: BreakTag? = null
builder.block(negativeLambdaIndent) {
visit(callee)
builder.block(argumentsIndent) {
builder.block(ZERO) { visit(typeArgumentList) }
if (argumentList != null) {
brokeBeforeBrace = visitValueArgumentListInternal(argumentList)
}
}
}
if (lambdaArguments.isNotEmpty()) {
builder.space()
visitArgumentInternal(
lambdaArguments.single(),
wrapInBlock = false,
brokeBeforeBrace = brokeBeforeBrace,
)
}
}
}
/** Example (`1, "hi"`) in a function call */
override fun visitValueArgumentList(list: KtValueArgumentList) {
visitValueArgumentListInternal(list)
}
/**
* Example (`1, "hi"`) in a function call
*
* @return a [BreakTag] which can tell you if a break was taken, but only when the list doesn't
* terminate in a negative closing indent. See [visitEachCommaSeparated] for examples.
*/
private fun visitValueArgumentListInternal(list: KtValueArgumentList): BreakTag? {
builder.sync(list)
val arguments = list.arguments
val isSingleUnnamedLambda =
arguments.size == 1 &&
arguments.first().getArgumentExpression() is KtLambdaExpression &&
arguments.first().getArgumentName() == null
val hasTrailingComma = list.trailingComma != null
val wrapInBlock: Boolean
val breakBeforePostfix: Boolean
val leadingBreak: Boolean
val breakAfterPrefix: Boolean
if (isSingleUnnamedLambda) {
wrapInBlock = true
breakBeforePostfix = false
leadingBreak = arguments.isNotEmpty() && hasTrailingComma
breakAfterPrefix = false
} else {
wrapInBlock = !isGoogleStyle
breakBeforePostfix = isGoogleStyle && arguments.isNotEmpty()
leadingBreak = arguments.isNotEmpty()
breakAfterPrefix = arguments.isNotEmpty()
}
return visitEachCommaSeparated(
list.arguments,
hasTrailingComma,
wrapInBlock = wrapInBlock,
breakBeforePostfix = breakBeforePostfix,
leadingBreak = leadingBreak,
prefix = "(",
postfix = ")",
breakAfterPrefix = breakAfterPrefix,
)
}
/** Example `{ 1 + 1 }` (as lambda) or `{ (x, y) -> x + y }` */
override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) {
visitLambdaExpressionInternal(lambdaExpression, brokeBeforeBrace = null)
}
/**
* The internal version of [visitLambdaExpression].
*
* @param brokeBeforeBrace used for tracking if a break was taken right before the lambda
* expression. Useful for scoping functions where we want good looking indentation. For example,
* here we have correct indentation before `bar()` and `car()` because we can detect the break
* after the equals:
* ```
* fun foo() =
* coroutineScope { x ->
* bar()
* car()
* }
* ```
*/
private fun visitLambdaExpressionInternal(
lambdaExpression: KtLambdaExpression,
brokeBeforeBrace: BreakTag?,
) {
builder.sync(lambdaExpression)
val valueParams = lambdaExpression.valueParameters
val hasParams = valueParams.isNotEmpty()
val statements = (lambdaExpression.bodyExpression ?: fail()).children
val hasStatements = statements.isNotEmpty()
val hasArrow = lambdaExpression.functionLiteral.arrow != null
fun ifBrokeBeforeBrace(onTrue: Indent, onFalse: Indent): Indent {
if (brokeBeforeBrace == null) return onFalse
return Indent.If.make(brokeBeforeBrace, onTrue, onFalse)
}
/**
* Enable correct formatting of the `fun foo() = scope {` syntax.
*
* We can't denote the lambda (+ scope function) as a block, since (for multiline lambdas) the
* rectangle rule would force the entire lambda onto a lower line. Instead, we conditionally
* indent all the interior levels of the lambda based on whether we had to break before the
* opening brace (or scope function). This mimics the look of a block when the break is taken.
*
* These conditional indents should not be used inside interior blocks, since that would apply
* the condition twice.
*/
val bracePlusBlockIndent = ifBrokeBeforeBrace(blockPlusExpressionBreakIndent, blockIndent)
val bracePlusExpressionIndent =
ifBrokeBeforeBrace(doubleExpressionBreakIndent, expressionBreakIndent)
val bracePlusZeroIndent = ifBrokeBeforeBrace(expressionBreakIndent, ZERO)
builder.token("{")
if (hasParams || hasArrow) {
builder.space()
builder.block(bracePlusExpressionIndent) { visitEachCommaSeparated(valueParams) }
builder.block(bracePlusBlockIndent) {
if (lambdaExpression.functionLiteral.valueParameterList?.trailingComma != null) {
builder.token(",")
builder.forcedBreak()
} else if (hasParams) {
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", ZERO)
}
builder.token("->")
}
builder.breakOp(Doc.FillMode.UNIFIED, "", bracePlusZeroIndent)
}
if (hasStatements) {
builder.breakOp(Doc.FillMode.UNIFIED, " ", bracePlusBlockIndent)
builder.block(bracePlusBlockIndent) {
builder.blankLineWanted(OpsBuilder.BlankLineWanted.NO)
if (statements.size == 1 &&
statements.first() !is KtReturnExpression &&
lambdaExpression.bodyExpression?.startsWithComment() != true) {
visitStatement(statements[0])
} else {
visitStatements(statements)
}
}
}
if (hasParams || hasArrow || hasStatements) {
// If we had to break in the body, ensure there is a break before the closing brace
builder.breakOp(Doc.FillMode.UNIFIED, " ", bracePlusZeroIndent)
builder.blankLineWanted(OpsBuilder.BlankLineWanted.NO)
}
builder.block(bracePlusZeroIndent) {
// If there are closing comments, make sure they and the brace are indented together
// The comments will indent themselves, so consume the previous break as a blank line
builder.breakOp(Doc.FillMode.INDEPENDENT, "", ZERO)
builder.token("}", blockIndent)
}
}
/** Example `this` or `this@Foo` */
override fun visitThisExpression(expression: KtThisExpression) {
builder.sync(expression)
builder.token("this")
visit(expression.getTargetLabel())
}
/** Example `Foo` or `@Foo` */
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
builder.sync(expression)
when (expression) {
is KtLabelReferenceExpression -> {
if (expression.text[0] == '@') {
builder.token("@")
builder.token(expression.getIdentifier()?.text ?: fail())
} else {
builder.token(expression.getIdentifier()?.text ?: fail())
builder.token("@")
}
}
else -> {
if (expression.text.isNotEmpty()) {
builder.token(expression.text)
}
}
}
}
/** e.g., `a: Int, b: Int, c: Int` in `fun foo(a: Int, b: Int, c: Int) { ... }`. */
override fun visitParameterList(list: KtParameterList) {
visitEachCommaSeparated(list.parameters, list.trailingComma != null, wrapInBlock = false)
}
/**
* Visit each element in [list], with comma (,) tokens in-between.
*
* Example:
* ```
* a, b, c, 3, 4, 5
* ```
*
* Either the entire list fits in one line, or each element is put on its own line:
* ```
* a,
* b,
* c,
* 3,
* 4,
* 5
* ```
*
* Optionally include a prefix and postfix:
* ```
* (
* a,
* b,
* c,
* )
* ```
*
* @param hasTrailingComma if true, each element is placed on its own line (even if they could've
* fit in a single line), and a trailing comma is emitted.
*
* Example:
* ```
* a,
* b,
* ```
*
* @param wrapInBlock if true, place all the elements in a block. When there's no [leadingBreak],
* this will be negatively indented. Note that the [prefix] and [postfix] aren't included in the
* block.
* @param leadingBreak if true, break before the first element.
* @param prefix if provided, emit this before the first element.
* @param postfix if provided, emit this after the last element (or trailing comma).
* @param breakAfterPrefix if true, emit a break after [prefix], but before the start of the
* block.
* @param breakBeforePostfix if true, place a break after the last element. Redundant when
* [hasTrailingComma] is true.
* @return a [BreakTag] which can tell you if a break was taken, but only when the list doesn't
* terminate in a negative closing indent.
*
* Example 1, this returns a BreakTag which tells you a break wasn't taken:
* ```
* (arg1, arg2)
* ```
*
* Example 2, this returns a BreakTag which tells you a break WAS taken:
* ```
* (
* arg1,
* arg2)
* ```
*
* Example 3, this returns null:
* ```
* (
* arg1,
* arg2,
* )
* ```
*
* Example 4, this also returns null (similar to example 2, but Google style):
* ```
* (
* arg1,
* arg2
* )
* ```
*/
private fun visitEachCommaSeparated(
list: Iterable<PsiElement>,
hasTrailingComma: Boolean = false,
wrapInBlock: Boolean = true,
leadingBreak: Boolean = true,
prefix: String? = null,
postfix: String? = null,
breakAfterPrefix: Boolean = true,
breakBeforePostfix: Boolean = isGoogleStyle,
): BreakTag? {
val breakAfterLastElement = hasTrailingComma || (postfix != null && breakBeforePostfix)
val nameTag = if (breakAfterLastElement) null else genSym()
if (prefix != null) {
builder.token(prefix)
if (breakAfterPrefix) {
builder.breakOp(Doc.FillMode.UNIFIED, "", ZERO, Optional.ofNullable(nameTag))
}
}
val breakType = if (hasTrailingComma) Doc.FillMode.FORCED else Doc.FillMode.UNIFIED
fun emitComma() {
builder.token(",")
builder.breakOp(breakType, " ", ZERO)
}
val indent = if (leadingBreak) ZERO else expressionBreakNegativeIndent
builder.block(indent, isEnabled = wrapInBlock) {
if (leadingBreak) {
builder.breakOp(breakType, "", ZERO)
}
var first = true
for (value in list) {
if (!first) emitComma()
first = false
visit(value)
}
if (hasTrailingComma) {
emitComma()
}
}
if (breakAfterLastElement) {
// a negative closing indent places the postfix to the left of the elements
// see examples 2 and 4 in the docstring
builder.breakOp(breakType, "", expressionBreakNegativeIndent)
}
if (postfix != null) {
builder.token(postfix)
}
return nameTag
}
/** Example `a` in `foo(a)`, or `*a`, or `limit = 50` */
override fun visitArgument(argument: KtValueArgument) {
visitArgumentInternal(
argument,
wrapInBlock = true,
brokeBeforeBrace = null,
)
}
/**
* The internal version of [visitArgument].
*
* @param wrapInBlock if true places the argument expression in a block.
*/
private fun visitArgumentInternal(
argument: KtValueArgument,
wrapInBlock: Boolean,
brokeBeforeBrace: BreakTag?,
) {
builder.sync(argument)
val hasArgName = argument.getArgumentName() != null
val isLambda = argument.getArgumentExpression() is KtLambdaExpression
if (hasArgName) {
visit(argument.getArgumentName())
builder.space()
builder.token("=")
if (isLambda) {
builder.space()
}
}
val indent = if (hasArgName && !isLambda) expressionBreakIndent else ZERO
builder.block(indent, isEnabled = wrapInBlock) {
if (hasArgName && !isLambda) {
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", ZERO)
}
if (argument.isSpread) {
builder.token("*")
}
if (isLambda) {
visitLambdaExpressionInternal(
argument.getArgumentExpression() as KtLambdaExpression,
brokeBeforeBrace = brokeBeforeBrace,
)
} else {
visit(argument.getArgumentExpression())
}
}
}
override fun visitReferenceExpression(expression: KtReferenceExpression) {
builder.sync(expression)
builder.token(expression.text)
}
override fun visitReturnExpression(expression: KtReturnExpression) {
builder.sync(expression)
builder.token("return")
visit(expression.getTargetLabel())
val returnedExpression = expression.returnedExpression
if (returnedExpression != null) {
builder.space()
visit(returnedExpression)
}
builder.guessToken(";")
}
/**
* For example `a + b`, `a + b + c` or `a..b`
*
* The extra handling here drills to the left most expression and handles it for long chains of
* binary expressions that are formatted not accordingly to the associative values That is, we
* want to think of `a + b + c` as `(a + b) + c`, whereas the AST parses it as `a + (b + c)`
*/
override fun visitBinaryExpression(expression: KtBinaryExpression) {
builder.sync(expression)
val op = expression.operationToken
if (KtTokens.ALL_ASSIGNMENTS.contains(op) && isLambdaOrScopingFunction(expression.right)) {
// Assignments are statements in Kotlin; we don't have to worry about compound assignment.
visit(expression.left)
builder.space()
builder.token(expression.operationReference.text)
visitLambdaOrScopingFunction(expression.right)
return
}
val parts =
ArrayDeque<KtBinaryExpression>().apply {
var current: KtExpression? = expression
while (current is KtBinaryExpression && current.operationToken == op) {
addFirst(current)
current = current.left
}
}
val leftMostExpression = parts.first()
visit(leftMostExpression.left)
for (leftExpression in parts) {
when (leftExpression.operationToken) {
KtTokens.RANGE -> {}
KtTokens.ELVIS -> builder.breakOp(Doc.FillMode.INDEPENDENT, " ", expressionBreakIndent)
else -> builder.space()
}
builder.token(leftExpression.operationReference.text)
val isFirst = leftExpression === leftMostExpression
if (isFirst) {
builder.open(expressionBreakIndent)
}
when (leftExpression.operationToken) {
KtTokens.RANGE -> {}
KtTokens.ELVIS -> builder.space()
else -> builder.breakOp(Doc.FillMode.UNIFIED, " ", ZERO)
}
visit(leftExpression.right)
}
builder.close()
}
override fun visitPostfixExpression(expression: KtPostfixExpression) {
builder.sync(expression)
builder.block(ZERO) {
val baseExpression = expression.baseExpression
val operator = expression.operationReference.text
visit(baseExpression)
if (baseExpression is KtPostfixExpression &&
baseExpression.operationReference.text.last() == operator.first()) {
builder.space()
}
builder.token(operator)
}
}
override fun visitPrefixExpression(expression: KtPrefixExpression) {
builder.sync(expression)
builder.block(ZERO) {
val baseExpression = expression.baseExpression
val operator = expression.operationReference.text
builder.token(operator)
if (baseExpression is KtPrefixExpression &&
operator.last() == baseExpression.operationReference.text.first()) {
builder.space()
}
visit(baseExpression)
}
}
override fun visitLabeledExpression(expression: KtLabeledExpression) {
builder.sync(expression)
visit(expression.labelQualifier)
if (expression.baseExpression !is KtLambdaExpression) {
builder.space()
}
visit(expression.baseExpression)
}
internal enum class DeclarationKind {
FIELD,
PARAMETER
}
/**
* Declare one variable or variable-like thing.
*
* Examples:
* - `var a: Int = 5`
* - `a: Int`
* - `private val b:
*/
private fun declareOne(
kind: DeclarationKind,
modifiers: KtModifierList?,
valOrVarKeyword: String?,
typeParameters: KtTypeParameterList? = null,
receiver: KtTypeReference? = null,
name: String?,
type: KtTypeReference?,
typeConstraintList: KtTypeConstraintList? = null,
initializer: KtExpression?,
delegate: KtPropertyDelegate? = null,
accessors: List<KtPropertyAccessor>? = null
): Int {
val verticalAnnotationBreak = genSym()
val isField = kind == DeclarationKind.FIELD
if (isField) {
builder.blankLineWanted(OpsBuilder.BlankLineWanted.conditional(verticalAnnotationBreak))
}
visit(modifiers)
builder.block(ZERO) {
builder.block(ZERO) {
if (valOrVarKeyword != null) {
builder.token(valOrVarKeyword)
builder.space()
}
if (typeParameters != null) {
visit(typeParameters)
builder.space()
}
// conditionally indent the name and initializer +4 if the type spans
// multiple lines
if (name != null) {
if (receiver != null) {
visit(receiver)
builder.token(".")
}
builder.token(name)
builder.op("")
}
}
if (name != null) {
builder.open(expressionBreakIndent) // open block for named values
}
// For example `: String` in `val thisIsALongName: String` or `fun f(): String`
if (type != null) {
if (name != null) {
builder.token(":")
builder.breakOp(Doc.FillMode.UNIFIED, " ", ZERO)
}
visit(type)
}
}
// For example `where T : Int` in a generic method
if (typeConstraintList != null) {
builder.space()
visit(typeConstraintList)
builder.space()
}
// for example `by lazy { compute() }`
if (delegate != null) {
builder.space()
builder.token("by")
if (isLambdaOrScopingFunction(delegate.expression)) {
builder.space()
visit(delegate)
} else {
builder.breakOp(Doc.FillMode.UNIFIED, " ", expressionBreakIndent)
builder.block(expressionBreakIndent) { visit(delegate) }
}
} else if (initializer != null) {
builder.space()
builder.token("=")
if (isLambdaOrScopingFunction(initializer)) {
visitLambdaOrScopingFunction(initializer)
} else {
builder.breakOp(Doc.FillMode.UNIFIED, " ", expressionBreakIndent)
builder.block(expressionBreakIndent) { visit(initializer) }
}
}
if (name != null) {
builder.close() // close block for named values
}
// for example `private set` or `get = 2 * field`
if (accessors?.isNotEmpty() == true) {
builder.block(blockIndent) {
for (accessor in accessors) {
builder.forcedBreak()
// The semicolon must come after the newline, or the output code will not parse.
builder.guessToken(";")
builder.block(ZERO) {
visitFunctionLikeExpression(
accessor.modifierList,
accessor.namePlaceholder.text,
null,
null,
null,
accessor.bodyExpression != null || accessor.bodyBlockExpression != null,
accessor.parameterList,
null,
accessor.bodyBlockExpression,
accessor.bodyExpression,
accessor.returnTypeReference,
accessor.bodyBlockExpression?.lBrace != null)
}
}
}
}
builder.guessToken(";")
if (isField) {
builder.blankLineWanted(OpsBuilder.BlankLineWanted.conditional(verticalAnnotationBreak))
}
return 0
}
/**
* Returns whether an expression is a lambda or initializer expression in which case we will want
* to avoid indenting the lambda block
*
* Examples:
* 1. '... = { ... }' is a lambda expression
* 2. '... = Runnable { ... }' is considered a scoping function
* 3. '... = scope { ... }' '... = apply { ... }' is a scoping function
*
* but not:
* 1. '... = foo() { ... }' due to the empty parenthesis
* 2. '... = Runnable @Annotation { ... }' due to the annotation
*/
private fun isLambdaOrScopingFunction(expression: KtExpression?): Boolean {
if (expression is KtLambdaExpression) {
return true
}
if (expression is KtCallExpression &&
expression.valueArgumentList?.leftParenthesis == null &&
expression.lambdaArguments.isNotEmpty() &&
expression.typeArgumentList?.arguments.isNullOrEmpty() &&
expression.lambdaArguments.first().getArgumentExpression() is KtLambdaExpression) {
return true
}
return false
}
/** See [isLambdaOrScopingFunction] for examples. */
private fun visitLambdaOrScopingFunction(expr: PsiElement?) {
val breakToExpr = genSym()
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", expressionBreakIndent, Optional.of(breakToExpr))
val lambdaExpression =
when (expr) {
is KtLambdaExpression -> expr
is KtCallExpression -> {
visit(expr.calleeExpression)
builder.space()
expr.lambdaArguments[0].getLambdaExpression() ?: fail()
}
else -> throw AssertionError(expr)
}
visitLambdaExpressionInternal(lambdaExpression, brokeBeforeBrace = breakToExpr)
}
override fun visitClassOrObject(classOrObject: KtClassOrObject) {
builder.sync(classOrObject)
val modifierList = classOrObject.modifierList
builder.block(ZERO) {
if (modifierList != null) {
visitModifierList(modifierList)
}
val declarationKeyword = classOrObject.getDeclarationKeyword()
if (declarationKeyword != null) {
builder.token(declarationKeyword.text ?: fail())
}
val name = classOrObject.nameIdentifier
if (name != null) {
builder.space()
builder.token(name.text)
visit(classOrObject.typeParameterList)
}
visit(classOrObject.primaryConstructor)
val superTypes = classOrObject.getSuperTypeList()
if (superTypes != null) {
builder.space()
builder.block(ZERO) {
builder.token(":")
builder.breakOp(Doc.FillMode.UNIFIED, " ", expressionBreakIndent)
visit(superTypes)
}
}
builder.space()
val typeConstraintList = classOrObject.typeConstraintList
if (typeConstraintList != null) {
if (superTypes?.entries?.lastOrNull() is KtDelegatedSuperTypeEntry) {
builder.forcedBreak()
}
visit(typeConstraintList)
builder.space()
}
val body = classOrObject.body
if (classOrObject.hasModifier(KtTokens.ENUM_KEYWORD)) {
visitEnumBody(classOrObject as KtClass)
} else if (body != null) {
visitBlockBody(body, true)
}
}
if (classOrObject.nameIdentifier != null) {
builder.forcedBreak()
}
}
/** Example `{ RED, GREEN; fun foo() { ... } }` for an enum class */
private fun visitEnumBody(enumClass: KtClass) {
val body = enumClass.body
if (body == null) {
return
}
builder.token("{", Doc.Token.RealOrImaginary.REAL, blockIndent, Optional.of(blockIndent))
builder.open(ZERO)
builder.block(blockIndent) {
builder.breakOp(Doc.FillMode.UNIFIED, "", ZERO)
val (enumEntries, nonEnumEntryStatements) = body.children.partition { it is KtEnumEntry }
builder.forcedBreak()
visitEnumEntries(enumEntries)
if (nonEnumEntryStatements.isNotEmpty()) {
builder.forcedBreak()
builder.blankLineWanted(OpsBuilder.BlankLineWanted.PRESERVE)
visitStatements(nonEnumEntryStatements.toTypedArray())
}
}
builder.forcedBreak()
builder.blankLineWanted(OpsBuilder.BlankLineWanted.NO)
builder.token("}", blockIndent)
builder.close()
}
/** Example `RED, GREEN, BLUE,` in an enum class, or `RED, GREEN;` */
private fun visitEnumEntries(enumEntries: List<PsiElement>) {
builder.block(ZERO) {
builder.breakOp(Doc.FillMode.UNIFIED, "", ZERO)
for (value in enumEntries) {
visit(value)
if (builder.peekToken() == Optional.of(",")) {
builder.token(",")
builder.forcedBreak()
}
}
}
builder.guessToken(";")
}
override fun visitPrimaryConstructor(constructor: KtPrimaryConstructor) {
builder.sync(constructor)
builder.block(ZERO) {
if (constructor.hasConstructorKeyword()) {
builder.open(ZERO)
builder.breakOp(Doc.FillMode.UNIFIED, " ", ZERO)
visit(constructor.modifierList)
builder.token("constructor")
}
builder.block(ZERO) {
builder.token("(")
builder.block(expressionBreakIndent) {
builder.breakOp(Doc.FillMode.UNIFIED, "", expressionBreakIndent)
visit(constructor.valueParameterList)
builder.breakOp(Doc.FillMode.UNIFIED, "", expressionBreakNegativeIndent)
if (constructor.hasConstructorKeyword()) {
builder.close()
}
}
builder.token(")")
}
}
}
/** Example `private constructor(n: Int) : this(4, 5) { ... }` inside a class's body */
override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor) {
val delegationCall = constructor.getDelegationCall()
val bodyExpression = constructor.bodyExpression
builder.sync(constructor)
visitFunctionLikeExpression(
constructor.modifierList,
"constructor",
null,
null,
null,
true,
constructor.valueParameterList,
null,
bodyExpression,
null,
if (!delegationCall.isImplicit) delegationCall else null,
true)
}
override fun visitConstructorDelegationCall(call: KtConstructorDelegationCall) {
// Work around a misfeature in kotlin-compiler: call.calleeExpression.accept doesn't call
// visitReferenceExpression, but calls visitElement instead.
builder.block(ZERO) {
builder.token(if (call.isCallToThis) "this" else "super")
visitCallElement(
null,
call.typeArgumentList,
call.valueArgumentList,
call.lambdaArguments,
)
}
}
override fun visitClassInitializer(initializer: KtClassInitializer) {
builder.sync(initializer)
builder.token("init")
builder.space()
visit(initializer.body)
}
override fun visitConstantExpression(expression: KtConstantExpression) {
builder.sync(expression)
builder.token(expression.text)
}
/** Example `(1 + 1)` */
override fun visitParenthesizedExpression(expression: KtParenthesizedExpression) {
builder.sync(expression)
builder.token("(")
visit(expression.expression)
builder.token(")")
}
override fun visitPackageDirective(directive: KtPackageDirective) {
builder.sync(directive)
if (directive.packageKeyword == null) {
return
}
builder.token("package")
builder.space()
var first = true
for (packageName in directive.packageNames) {
if (first) {
first = false
} else {
builder.token(".")
}
builder.token(packageName.getIdentifier()?.text ?: packageName.getReferencedName())
}
builder.guessToken(";")
builder.forcedBreak()
}
/** Example `import com.foo.A; import com.bar.B` */
override fun visitImportList(importList: KtImportList) {
builder.sync(importList)
importList.imports.forEach { visit(it) }
}
/** Example `import com.foo.A` */
override fun visitImportDirective(directive: KtImportDirective) {
builder.sync(directive)
builder.token("import")
builder.space()
val importedReference = directive.importedReference
if (importedReference != null) {
inImport = true
visit(importedReference)
inImport = false
}
if (directive.isAllUnder) {
builder.token(".")
builder.token("*")
}
// Possible alias.
val alias = directive.alias?.nameIdentifier
if (alias != null) {
builder.space()
builder.token("as")
builder.space()
builder.token(alias.text ?: fail())
}
// Force a newline afterwards.
builder.guessToken(";")
builder.forcedBreak()
}
/** For example `@Magic private final` */
override fun visitModifierList(list: KtModifierList) {
builder.sync(list)
var onlyAnnotationsSoFar = true
for (child in list.node.children()) {
val psi = child.psi
if (psi is PsiWhiteSpace) {
continue
}
if (child.elementType is KtModifierKeywordToken) {
onlyAnnotationsSoFar = false
builder.token(child.text)
} else {
visit(psi)
}
if (onlyAnnotationsSoFar) {
builder.breakOp(Doc.FillMode.UNIFIED, " ", ZERO)
} else {
builder.space()
}
}
}
/**
* Example:
* ```
* @SuppressLint("MagicNumber")
* print(10)
* ```
*
* in
*
* ```
* fun f() {
* @SuppressLint("MagicNumber")
* print(10)
* }
* ```
*/
override fun visitAnnotatedExpression(expression: KtAnnotatedExpression) {
builder.sync(expression)
builder.block(ZERO) {
val baseExpression = expression.baseExpression
builder.block(ZERO) {
val annotationEntries = expression.annotationEntries
for (annotationEntry in annotationEntries) {
if (annotationEntry !== annotationEntries.first()) {
builder.breakOp(Doc.FillMode.UNIFIED, " ", ZERO)
}
visit(annotationEntry)
}
}
// Binary expressions in a block have a different meaning according to their formatting.
// If there in the line above, they refer to the entire expression, if they're in the same
// line then only to the first operand of the operator.
// We force a break to avoid such semantic changes
when {
(baseExpression is KtBinaryExpression || baseExpression is KtBinaryExpressionWithTypeRHS) &&
expression.parent is KtBlockExpression -> builder.forcedBreak()
baseExpression is KtLambdaExpression -> builder.space()
else -> builder.breakOp(Doc.FillMode.UNIFIED, " ", ZERO)
}
visit(expression.baseExpression)
}
}
/**
* For example, @field:[Inject Named("WEB_VIEW")]
*
* A KtAnnotation is used only to group multiple annotations with the same use-site-target. It
* only appears in a modifier list since annotated expressions do not have use-site-targets.
*/
override fun visitAnnotation(annotation: KtAnnotation) {
builder.sync(annotation)
builder.block(ZERO) {
builder.token("@")
val useSiteTarget = annotation.useSiteTarget
if (useSiteTarget != null) {
visit(useSiteTarget)
builder.token(":")
}
builder.block(expressionBreakIndent) {
builder.token("[")
builder.block(ZERO) {
var first = true
builder.breakOp(Doc.FillMode.UNIFIED, "", ZERO)
for (value in annotation.entries) {
if (!first) {
builder.breakOp(Doc.FillMode.UNIFIED, " ", ZERO)
}
first = false
visit(value)
}
}
}
builder.token("]")
}
builder.forcedBreak()
}
/** For example, 'field' in @field:[Inject Named("WEB_VIEW")] */
override fun visitAnnotationUseSiteTarget(
annotationTarget: KtAnnotationUseSiteTarget,
data: Void?
): Void? {
builder.token(annotationTarget.getAnnotationUseSiteTarget().renderName)
return null
}
/** For example `@Magic` or `@Fred(1, 5)` */
override fun visitAnnotationEntry(annotationEntry: KtAnnotationEntry) {
builder.sync(annotationEntry)
if (annotationEntry.atSymbol != null) {
builder.token("@")
}
val useSiteTarget = annotationEntry.useSiteTarget
if (useSiteTarget != null && useSiteTarget.parent == annotationEntry) {
visit(useSiteTarget)
builder.token(":")
}
visitCallElement(
annotationEntry.calleeExpression,
null, // Type-arguments are included in the annotation's callee expression.
annotationEntry.valueArgumentList,
listOf())
}
override fun visitFileAnnotationList(
fileAnnotationList: KtFileAnnotationList,
data: Void?
): Void? {
for (child in fileAnnotationList.node.children()) {
if (child is PsiElement) {
continue
}
visit(child.psi)
builder.forcedBreak()
}
return null
}
override fun visitSuperTypeList(list: KtSuperTypeList) {
builder.sync(list)
builder.block(expressionBreakIndent) { visitEachCommaSeparated(list.entries) }
}
override fun visitSuperTypeCallEntry(call: KtSuperTypeCallEntry) {
builder.sync(call)
visitCallElement(call.calleeExpression, null, call.valueArgumentList, call.lambdaArguments)
}
/**
* Example `Collection<Int> by list` in `class MyList(list: List<Int>) : Collection<Int> by list`
*/
override fun visitDelegatedSuperTypeEntry(specifier: KtDelegatedSuperTypeEntry) {
builder.sync(specifier)
visit(specifier.typeReference)
builder.space()
builder.token("by")
builder.space()
visit(specifier.delegateExpression)
}
override fun visitWhenExpression(expression: KtWhenExpression) {
builder.sync(expression)
builder.block(ZERO) {
emitKeywordWithCondition("when", expression.subjectExpression)
builder.space()
builder.token("{", Doc.Token.RealOrImaginary.REAL, blockIndent, Optional.of(blockIndent))
expression.entries.forEach { whenEntry ->
builder.block(blockIndent) {
builder.forcedBreak()
if (whenEntry.isElse) {
builder.token("else")
} else {
builder.block(ZERO) {
val conditions = whenEntry.conditions
for ((index, condition) in conditions.withIndex()) {
visit(condition)
builder.guessToken(",")
if (index != conditions.lastIndex) {
builder.forcedBreak()
}
}
}
}
val whenExpression = whenEntry.expression
builder.space()
builder.token("->")
if (whenExpression is KtBlockExpression) {
builder.space()
visit(whenExpression)
} else {
builder.block(expressionBreakIndent) {
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", ZERO)
visit(whenExpression)
}
}
builder.guessToken(";")
}
builder.forcedBreak()
}
builder.token("}")
}
}
override fun visitBlockExpression(expression: KtBlockExpression) {
builder.sync(expression)
visitBlockBody(expression, true)
}
override fun visitWhenConditionWithExpression(condition: KtWhenConditionWithExpression) {
builder.sync(condition)
visit(condition.expression)
}
override fun visitWhenConditionIsPattern(condition: KtWhenConditionIsPattern) {
builder.sync(condition)
builder.token(if (condition.isNegated) "!is" else "is")
builder.space()
visit(condition.typeReference)
}
/** Example `in 1..2` as part of a when expression */
override fun visitWhenConditionInRange(condition: KtWhenConditionInRange) {
builder.sync(condition)
// TODO: replace with 'condition.isNegated' once https://youtrack.jetbrains.com/issue/KT-34395
// is fixed.
val isNegated = condition.firstChild?.node?.findChildByType(KtTokens.NOT_IN) != null
builder.token(if (isNegated) "!in" else "in")
builder.space()
visit(condition.rangeExpression)
}
override fun visitIfExpression(expression: KtIfExpression) {
builder.sync(expression)
builder.block(ZERO) {
emitKeywordWithCondition("if", expression.condition)
if (expression.then is KtBlockExpression) {
builder.space()
builder.block(ZERO) { visit(expression.then) }
} else {
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", expressionBreakIndent)
builder.block(expressionBreakIndent) { visit(expression.then) }
}
if (expression.elseKeyword != null) {
if (expression.then is KtBlockExpression) {
builder.space()
} else {
builder.breakOp(Doc.FillMode.UNIFIED, " ", ZERO)
}
builder.block(ZERO) {
builder.token("else")
if (expression.`else` is KtBlockExpression || expression.`else` is KtIfExpression) {
builder.space()
builder.block(ZERO) { visit(expression.`else`) }
} else {
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", expressionBreakIndent)
builder.block(expressionBreakIndent) { visit(expression.`else`) }
}
}
}
}
}
/** Example `a[3]`, `b["a", 5]` or `a.b.c[4]` */
override fun visitArrayAccessExpression(expression: KtArrayAccessExpression) {
builder.sync(expression)
if (expression.arrayExpression is KtQualifiedExpression) {
emitQualifiedExpression(expression)
} else {
visit(expression.arrayExpression)
visitArrayAccessBrackets(expression)
}
}
/**
* Example `[3]` in `a[3]` or `a[3].b` Separated since it needs to be used from a top level array
* expression (`a[3]`) and from within a qualified chain (`a[3].b)
*/
private fun visitArrayAccessBrackets(expression: KtArrayAccessExpression) {
builder.block(ZERO) {
builder.token("[")
builder.breakOp(Doc.FillMode.UNIFIED, "", expressionBreakIndent)
builder.block(expressionBreakIndent) {
visitEachCommaSeparated(
expression.indexExpressions, expression.trailingComma != null, wrapInBlock = true)
}
}
builder.token("]")
}
/** Example `val (a, b: Int) = Pair(1, 2)` */
override fun visitDestructuringDeclaration(destructuringDeclaration: KtDestructuringDeclaration) {
builder.sync(destructuringDeclaration)
val valOrVarKeyword = destructuringDeclaration.valOrVarKeyword
if (valOrVarKeyword != null) {
builder.token(valOrVarKeyword.text)
builder.space()
}
val hasTrailingComma = destructuringDeclaration.trailingComma != null
builder.block(ZERO) {
builder.token("(")
builder.breakOp(Doc.FillMode.UNIFIED, "", expressionBreakIndent)
builder.block(expressionBreakIndent) {
visitEachCommaSeparated(
destructuringDeclaration.entries, hasTrailingComma, wrapInBlock = true)
}
}
builder.token(")")
val initializer = destructuringDeclaration.initializer
if (initializer != null) {
builder.space()
builder.token("=")
if (hasTrailingComma) {
builder.space()
} else {
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", expressionBreakIndent)
}
builder.block(expressionBreakIndent, !hasTrailingComma) { visit(initializer) }
}
}
/** Example `a: String` which is part of `(a: String, b: String)` */
override fun visitDestructuringDeclarationEntry(
multiDeclarationEntry: KtDestructuringDeclarationEntry
) {
builder.sync(multiDeclarationEntry)
declareOne(
initializer = null,
kind = DeclarationKind.PARAMETER,
modifiers = multiDeclarationEntry.modifierList,
name = multiDeclarationEntry.nameIdentifier?.text ?: fail(),
type = multiDeclarationEntry.typeReference,
valOrVarKeyword = null,
)
}
/** Example `"Hello $world!"` or `"""Hello world!"""` */
override fun visitStringTemplateExpression(expression: KtStringTemplateExpression) {
builder.sync(expression)
builder.token(WhitespaceTombstones.replaceTrailingWhitespaceWithTombstone(expression.text))
}
/** Example `super` in `super.doIt(5)` or `super<Foo>` in `super<Foo>.doIt(5)` */
override fun visitSuperExpression(expression: KtSuperExpression) {
builder.sync(expression)
builder.token("super")
val superTypeQualifier = expression.superTypeQualifier
if (superTypeQualifier != null) {
builder.token("<")
visit(superTypeQualifier)
builder.token(">")
}
visit(expression.labelQualifier)
}
/** Example `<T, S>` */
override fun visitTypeParameterList(list: KtTypeParameterList) {
builder.sync(list)
builder.block(ZERO) {
builder.token("<")
val parameters = list.parameters
if (parameters.isNotEmpty()) {
// Break before args.
builder.breakOp(Doc.FillMode.UNIFIED, "", expressionBreakIndent)
builder.block(expressionBreakIndent) {
visitEachCommaSeparated(list.parameters, list.trailingComma != null, wrapInBlock = true)
}
}
builder.token(">")
}
}
override fun visitTypeParameter(parameter: KtTypeParameter) {
builder.sync(parameter)
visit(parameter.modifierList)
builder.token(parameter.nameIdentifier?.text ?: "")
val extendsBound = parameter.extendsBound
if (extendsBound != null) {
builder.space()
builder.token(":")
builder.space()
visit(extendsBound)
}
}
/** Example `where T : View, T : Listener` */
override fun visitTypeConstraintList(list: KtTypeConstraintList) {
builder.token("where")
builder.space()
builder.sync(list)
visitEachCommaSeparated(list.constraints)
}
/** Example `T : Foo` */
override fun visitTypeConstraint(constraint: KtTypeConstraint) {
builder.sync(constraint)
// TODO(nreid260): What about annotations on the type reference? `where @A T : Int`
visit(constraint.subjectTypeParameterName)
builder.space()
builder.token(":")
builder.space()
visit(constraint.boundTypeReference)
}
/** Example `for (i in items) { ... }` */
override fun visitForExpression(expression: KtForExpression) {
builder.sync(expression)
builder.block(ZERO) {
builder.token("for")
builder.space()
builder.token("(")
visit(expression.loopParameter)
builder.space()
builder.token("in")
builder.block(ZERO) {
builder.breakOp(Doc.FillMode.UNIFIED, " ", expressionBreakIndent)
builder.block(expressionBreakIndent) { visit(expression.loopRange) }
}
builder.token(")")
builder.space()
visit(expression.body)
}
}
/** Example `while (a < b) { ... }` */
override fun visitWhileExpression(expression: KtWhileExpression) {
builder.sync(expression)
emitKeywordWithCondition("while", expression.condition)
builder.space()
visit(expression.body)
}
/** Example `do { ... } while (a < b)` */
override fun visitDoWhileExpression(expression: KtDoWhileExpression) {
builder.sync(expression)
builder.token("do")
builder.space()
if (expression.body != null) {
visit(expression.body)
builder.space()
}
emitKeywordWithCondition("while", expression.condition)
}
/** Example `break` or `break@foo` in a loop */
override fun visitBreakExpression(expression: KtBreakExpression) {
builder.sync(expression)
builder.token("break")
visit(expression.labelQualifier)
}
/** Example `continue` or `continue@foo` in a loop */
override fun visitContinueExpression(expression: KtContinueExpression) {
builder.sync(expression)
builder.token("continue")
visit(expression.labelQualifier)
}
/** Example `f: String`, or `private val n: Int` or `(a: Int, b: String)` (in for-loops) */
override fun visitParameter(parameter: KtParameter) {
builder.sync(parameter)
builder.block(ZERO) {
val destructuringDeclaration = parameter.destructuringDeclaration
val typeReference = parameter.typeReference
if (destructuringDeclaration != null) {
builder.block(ZERO) {
visit(destructuringDeclaration)
if (typeReference != null) {
builder.token(":")
builder.space()
visit(typeReference)
}
}
} else {
declareOne(
kind = DeclarationKind.PARAMETER,
modifiers = parameter.modifierList,
valOrVarKeyword = parameter.valOrVarKeyword?.text,
name = parameter.nameIdentifier?.text,
type = typeReference,
initializer = parameter.defaultValue)
}
}
}
/** Example `String::isNullOrEmpty` */
override fun visitCallableReferenceExpression(expression: KtCallableReferenceExpression) {
builder.sync(expression)
visit(expression.receiverExpression)
// For some reason, expression.receiverExpression doesn't contain the question-mark token in
// case of a nullable type, e.g., in String?::isNullOrEmpty.
// Instead, KtCallableReferenceExpression exposes a method that looks for the QUEST token in
// its children.
if (expression.hasQuestionMarks) {
builder.token("?")
}
builder.block(expressionBreakIndent) {
builder.token("::")
builder.breakOp(Doc.FillMode.INDEPENDENT, "", ZERO)
visit(expression.callableReference)
}
}
override fun visitClassLiteralExpression(expression: KtClassLiteralExpression) {
builder.sync(expression)
val receiverExpression = expression.receiverExpression
if (receiverExpression is KtCallExpression) {
visitCallElement(
receiverExpression.calleeExpression,
receiverExpression.typeArgumentList,
receiverExpression.valueArgumentList,
receiverExpression.lambdaArguments)
} else {
visit(receiverExpression)
}
builder.token("::")
builder.token("class")
}
override fun visitFunctionType(type: KtFunctionType) {
builder.sync(type)
val receiver = type.receiver
if (receiver != null) {
visit(receiver)
builder.token(".")
}
builder.block(expressionBreakIndent) {
val parameterList = type.parameterList
if (parameterList != null) {
visitEachCommaSeparated(
parameterList.parameters,
prefix = "(",
postfix = ")",
hasTrailingComma = parameterList.trailingComma != null,
)
}
}
builder.space()
builder.token("->")
builder.space()
builder.block(expressionBreakIndent) { visit(type.returnTypeReference) }
}
/** Example `a is Int` or `b !is Int` */
override fun visitIsExpression(expression: KtIsExpression) {
builder.sync(expression)
val openGroupBeforeLeft = expression.leftHandSide !is KtQualifiedExpression
if (openGroupBeforeLeft) builder.open(ZERO)
visit(expression.leftHandSide)
if (!openGroupBeforeLeft) builder.open(ZERO)
val parent = expression.parent
if (parent is KtValueArgument ||
parent is KtParenthesizedExpression ||
parent is KtContainerNode) {
builder.breakOp(Doc.FillMode.UNIFIED, " ", expressionBreakIndent)
} else {
builder.space()
}
visit(expression.operationReference)
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", expressionBreakIndent)
builder.block(expressionBreakIndent) { visit(expression.typeReference) }
builder.close()
}
/** Example `a as Int` or `a as? Int` */
override fun visitBinaryWithTypeRHSExpression(expression: KtBinaryExpressionWithTypeRHS) {
builder.sync(expression)
val openGroupBeforeLeft = expression.left !is KtQualifiedExpression
if (openGroupBeforeLeft) builder.open(ZERO)
visit(expression.left)
if (!openGroupBeforeLeft) builder.open(ZERO)
builder.breakOp(Doc.FillMode.UNIFIED, " ", expressionBreakIndent)
visit(expression.operationReference)
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", expressionBreakIndent)
builder.block(expressionBreakIndent) { visit(expression.right) }
builder.close()
}
/**
* Example:
* ```
* fun f() {
* val a: Array<Int> = [1, 2, 3]
* }
* ```
*/
override fun visitCollectionLiteralExpression(expression: KtCollectionLiteralExpression) {
builder.sync(expression)
builder.block(expressionBreakIndent) {
visitEachCommaSeparated(
expression.getInnerExpressions(),
expression.trailingComma != null,
prefix = "[",
postfix = "]",
wrapInBlock = true)
}
}
override fun visitTryExpression(expression: KtTryExpression) {
builder.sync(expression)
builder.token("try")
builder.space()
visit(expression.tryBlock)
for (catchClause in expression.catchClauses) {
visit(catchClause)
}
visit(expression.finallyBlock)
}
override fun visitCatchSection(catchClause: KtCatchClause) {
builder.sync(catchClause)
builder.space()
builder.token("catch")
builder.space()
builder.block(ZERO) {
builder.token("(")
builder.block(expressionBreakIndent) {
builder.breakOp(Doc.FillMode.UNIFIED, "", ZERO)
visit(catchClause.catchParameter)
builder.guessToken(",")
}
}
builder.token(")")
builder.space()
visit(catchClause.catchBody)
}
override fun visitFinallySection(finallySection: KtFinallySection) {
builder.sync(finallySection)
builder.space()
builder.token("finally")
builder.space()
visit(finallySection.finalExpression)
}
override fun visitThrowExpression(expression: KtThrowExpression) {
builder.sync(expression)
builder.token("throw")
builder.space()
visit(expression.thrownExpression)
}
/** Example `RED(0xFF0000)` in an enum class */
override fun visitEnumEntry(enumEntry: KtEnumEntry) {
builder.sync(enumEntry)
builder.block(ZERO) {
visit(enumEntry.modifierList)
builder.token(enumEntry.nameIdentifier?.text ?: fail())
enumEntry.initializerList?.initializers?.forEach { visit(it) }
val body = enumEntry.body
if (body != null) {
builder.space()
visitBlockBody(body, true)
}
}
}
/** Example `private typealias TextChangedListener = (string: String) -> Unit` */
override fun visitTypeAlias(typeAlias: KtTypeAlias) {
builder.sync(typeAlias)
builder.block(ZERO) {
visit(typeAlias.modifierList)
builder.token("typealias")
builder.space()
builder.token(typeAlias.nameIdentifier?.text ?: fail())
visit(typeAlias.typeParameterList)
builder.space()
builder.token("=")
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", expressionBreakIndent)
builder.block(expressionBreakIndent) {
visit(typeAlias.getTypeReference())
visit(typeAlias.typeConstraintList)
builder.guessToken(";")
}
builder.forcedBreak()
}
}
/**
* visitElement is called for almost all types of AST nodes. We use it to keep track of whether
* we're currently inside an expression or not.
*
* @throws FormattingError
*/
override fun visitElement(element: PsiElement) {
inExpression.addLast(element is KtExpression || inExpression.peekLast())
val previous = builder.depth()
try {
super.visitElement(element)
} catch (e: FormattingError) {
throw e
} catch (t: Throwable) {
throw FormattingError(builder.diagnostic(Throwables.getStackTraceAsString(t)))
} finally {
inExpression.removeLast()
}
builder.checkClosed(previous)
}
override fun visitKtFile(file: KtFile) {
markForPartialFormat()
var importListEmpty = false
var isFirst = true
for (child in file.children) {
if (child.text.isBlank()) {
importListEmpty = child is KtImportList
continue
}
if (!isFirst && child !is PsiComment && (child !is KtScript || !importListEmpty)) {
builder.blankLineWanted(OpsBuilder.BlankLineWanted.YES)
}
visit(child)
isFirst = false
}
markForPartialFormat()
}
override fun visitScript(script: KtScript) {
markForPartialFormat()
var lastChildHadBlankLineBefore = false
var first = true
for (child in script.blockExpression.children) {
if (child.text.isBlank()) {
continue
}
builder.forcedBreak()
val childGetsBlankLineBefore = child !is KtProperty
if (first) {
builder.blankLineWanted(OpsBuilder.BlankLineWanted.PRESERVE)
} else if (child !is PsiComment &&
(childGetsBlankLineBefore || lastChildHadBlankLineBefore)) {
builder.blankLineWanted(OpsBuilder.BlankLineWanted.YES)
}
visit(child)
builder.guessToken(";")
lastChildHadBlankLineBefore = childGetsBlankLineBefore
first = false
}
markForPartialFormat()
}
private fun inExpression(): Boolean {
return inExpression.peekLast()
}
/**
* markForPartialFormat is used to delineate the smallest areas of code that must be formatted
* together.
*
* When only parts of the code are being formatted, the requested area is expanded until it's
* covered by an area marked by this method.
*/
private fun markForPartialFormat() {
if (!inExpression()) {
builder.markForPartialFormat()
}
}
/**
* Emit a [Doc.Token].
*
* @param token the [String] to wrap in a [Doc.Token]
* @param plusIndentCommentsBefore extra block for comments before this token
*/
private fun OpsBuilder.token(token: String, plusIndentCommentsBefore: Indent = ZERO) {
token(
token,
Doc.Token.RealOrImaginary.REAL,
plusIndentCommentsBefore,
/* breakAndIndentTrailingComment */ Optional.empty())
}
/**
* Opens a new level, emits into it and closes it.
*
* This is a helper method to make it easier to keep track of [OpsBuilder.open] and
* [OpsBuilder.close] calls
*
* @param plusIndent the block level to pass to the block
* @param block a code block to be run in this block level
*/
private inline fun OpsBuilder.block(
plusIndent: Indent,
isEnabled: Boolean = true,
block: () -> Unit
) {
if (isEnabled) {
open(plusIndent)
}
block()
if (isEnabled) {
close()
}
}
/** Helper method to sync the current offset to match any element in the AST */
private fun OpsBuilder.sync(psiElement: PsiElement) {
sync(psiElement.startOffset)
}
/**
* Throws a formatting error
*
* This is used as `expr ?: fail()` to avoid using the !! operator and provide better error
* messages.
*/
private fun fail(message: String = "Unexpected"): Nothing {
throw FormattingError(builder.diagnostic(message))
}
/** Helper function to improve readability */
private fun visit(element: PsiElement?) {
element?.accept(this)
}
/** Emits a key word followed by a condition, e.g. `if (b)` or `while (c < d )` */
private fun emitKeywordWithCondition(keyword: String, condition: KtExpression?) {
if (condition == null) {
builder.token(keyword)
return
}
builder.block(ZERO) {
builder.token(keyword)
builder.space()
builder.token("(")
if (isGoogleStyle) {
builder.block(expressionBreakIndent) {
builder.breakOp(Doc.FillMode.UNIFIED, "", ZERO)
visit(condition)
builder.breakOp(Doc.FillMode.UNIFIED, "", expressionBreakNegativeIndent)
}
} else {
builder.block(ZERO) { visit(condition) }
}
}
builder.token(")")
}
}
| core/src/main/java/com/facebook/ktfmt/format/KotlinInputAstVisitor.kt | 1312964971 |
package gl8080.lifegame.web.json
import gl8080.lifegame.web.resource.LifeGameDto
import javax.ws.rs.Produces
import javax.ws.rs.core.MediaType
import javax.ws.rs.ext.Provider
@Provider
@Produces(MediaType.APPLICATION_JSON)
class LifeGameDtoWriter: AbstractJsonWriter<LifeGameDto>() | src/main/kotlin/gl8080/lifegame/web/json/LifeGameDtoWriter.kt | 4022716932 |
package com.lbbento.pitchupwear.main
import com.lbbento.pitchuptuner.service.TunerResult
import javax.inject.Inject
class TunerServiceMapper @Inject constructor() {
fun tunerResultToViewModel(tunerResult: TunerResult) =
TunerViewModel(tunerResult.note,
tunerResult.tuningStatus,
tunerResult.expectedFrequency,
tunerResult.diffFrequency,
tunerResult.diffCents)
} | wear2/src/main/kotlin/com/lbbento/pitchupwear/main/TunerServiceMapper.kt | 3824128101 |
/*
* Copyright (C) 2018, Alashov Berkeli
* All rights reserved.
*/
package tm.alashow.datmusic.di
import android.app.Application
import android.content.Context
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import java.util.concurrent.TimeUnit
import javax.inject.Named
import javax.inject.Singleton
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
import okhttp3.Cache
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import okhttp3.logging.HttpLoggingInterceptor.*
import okhttp3.logging.HttpLoggingInterceptor.Level as LogLevel
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import tm.alashow.Config
import tm.alashow.datmusic.util.AppHeadersInterceptor
import tm.alashow.datmusic.util.RewriteCachesInterceptor
import tm.alashow.domain.models.DEFAULT_JSON_FORMAT
@InstallIn(SingletonComponent::class)
@Module
class NetworkModule {
private fun getBaseBuilder(cache: Cache): OkHttpClient.Builder {
return OkHttpClient.Builder()
.cache(cache)
.readTimeout(Config.API_TIMEOUT, TimeUnit.MILLISECONDS)
.writeTimeout(Config.API_TIMEOUT, TimeUnit.MILLISECONDS)
.retryOnConnectionFailure(true)
}
@Provides
@Singleton
fun okHttpCache(app: Application) = Cache(app.cacheDir, 10 * 1024 * 1024)
@Provides
@Singleton
fun httpLoggingInterceptor(): HttpLoggingInterceptor {
val interceptor = HttpLoggingInterceptor()
interceptor.level = LogLevel.BASIC
return interceptor
}
@Provides
@Singleton
@Named("AppHeadersInterceptor")
fun appHeadersInterceptor(@ApplicationContext context: Context): Interceptor = AppHeadersInterceptor(context)
@Provides
@Singleton
@Named("RewriteCachesInterceptor")
fun rewriteCachesInterceptor(): Interceptor = RewriteCachesInterceptor()
@Provides
@Singleton
fun okHttp(
cache: Cache,
loggingInterceptor: HttpLoggingInterceptor,
@Named("AppHeadersInterceptor") appHeadersInterceptor: Interceptor,
@Named("RewriteCachesInterceptor") rewriteCachesInterceptor: Interceptor
) = getBaseBuilder(cache)
.addInterceptor(appHeadersInterceptor)
.addInterceptor(rewriteCachesInterceptor)
.addInterceptor(loggingInterceptor)
.build()
@Provides
@Named("downloader")
fun downloaderOkHttp(
cache: Cache,
@Named("AppHeadersInterceptor") appHeadersInterceptor: Interceptor,
) = getBaseBuilder(cache)
.readTimeout(Config.DOWNLOADER_TIMEOUT, TimeUnit.MILLISECONDS)
.writeTimeout(Config.DOWNLOADER_TIMEOUT, TimeUnit.MILLISECONDS)
.addInterceptor(appHeadersInterceptor)
.addInterceptor(HttpLoggingInterceptor().apply { level = LogLevel.HEADERS })
.build()
@Provides
@Named("player")
fun playerOkHttp(
cache: Cache,
@Named("AppHeadersInterceptor") appHeadersInterceptor: Interceptor,
) = getBaseBuilder(cache)
.readTimeout(Config.PLAYER_TIMEOUT, TimeUnit.MILLISECONDS)
.writeTimeout(Config.PLAYER_TIMEOUT, TimeUnit.MILLISECONDS)
.connectTimeout(Config.PLAYER_TIMEOUT_CONNECT, TimeUnit.MILLISECONDS)
.addInterceptor(appHeadersInterceptor)
.addInterceptor(HttpLoggingInterceptor().apply { level = LogLevel.HEADERS })
.build()
@Provides
@Singleton
fun jsonConfigured() = DEFAULT_JSON_FORMAT
@Provides
@Singleton
@ExperimentalSerializationApi
fun retrofit(client: OkHttpClient, json: Json): Retrofit =
Retrofit.Builder()
.baseUrl(Config.API_BASE_URL)
.addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client)
.build()
}
| app/src/main/kotlin/tm/alashow/datmusic/di/NetworkModule.kt | 2779017322 |
package com.ariane.thirdlab.repositories
import com.ariane.thirdlab.domains.Post
import org.springframework.data.repository.CrudRepository
interface PostRepository : CrudRepository<Post, Long> {
fun findByParentId(parentId: Long): Iterable<Post>
fun findByTitleContaining(postParam: String): Iterable<Post>
fun findByTagId(tagId: Long): List<Post>
/**
* 统计特定tag的文章数量
*/
fun countByTagId(tagId: Long): Long
} | src/main/kotlin/com/ariane/thirdlab/repositories/PostRepository.kt | 3846321744 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.