content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package sen.yuan.dao.gluttony_realm
import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.util.Log
import io.realm.Realm
import io.realm.RealmConfiguration
import io.realm.log.LogLevel
import io.realm.log.RealmLog
/**
* Created by SenYuYuan on 2016/3/5.
*/
object Gluttony {
var isDebug = false
val realm: Realm by lazy { Realm.getDefaultInstance() }
fun init(baseApp: Application) {
Realm.init(baseApp)
Realm.setDefaultConfiguration(RealmConfiguration.Builder()
.name("gluttony")
.deleteRealmIfMigrationNeeded()
.schemaVersion(1)
.build())
RealmLog.setLevel(LogLevel.ALL)
}
} | gluttony-realm/src/main/java/sen/yuan/dao/gluttony_realm/Gluttony.kt | 1629364185 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight
import com.intellij.model.Symbol
import com.intellij.model.psi.ImplicitReferenceProvider
import com.intellij.model.psi.PsiSymbolService
import com.intellij.psi.*
import com.intellij.psi.LambdaUtil.resolveFunctionalInterfaceClass
import com.intellij.psi.util.PsiUtil.isJavaToken
import com.intellij.psi.util.PsiUtil.resolveClassInType
class JavaImplicitReferenceProvider : ImplicitReferenceProvider {
override fun resolveAsReference(element: PsiElement): Collection<Symbol> {
return listOfNotNull(
doResolveAsReference(element)
?.let(PsiSymbolService.getInstance()::asSymbol) // this line will be removed when PsiClass will implement Symbol
)
}
private fun doResolveAsReference(elementAtCaret: PsiElement): PsiClass? {
val parent = elementAtCaret.parent
if (parent is PsiFunctionalExpression && (isJavaToken(elementAtCaret, JavaTokenType.ARROW) ||
isJavaToken(elementAtCaret, JavaTokenType.DOUBLE_COLON))) {
return resolveFunctionalInterfaceClass(parent)
}
else if (elementAtCaret is PsiKeyword && parent is PsiTypeElement && parent.isInferredType) {
return resolveClassInType(parent.type)
}
else {
return null
}
}
}
| java/java-impl/src/com/intellij/codeInsight/JavaImplicitReferenceProvider.kt | 668974658 |
package a
import a.A.Inner
import a.A.Nested
class A {
inner class Inner {
}
class Nested {
}
fun foo() {
}
}
fun A.ext() {
}
fun f(body: A.() -> Unit) {
}
<selection>fun g() {
f {
Inner()
Nested()
foo()
ext()
}
}</selection> | plugins/kotlin/idea/tests/testData/copyPaste/imports/ImportableEntityInExtensionLiteral.kt | 1729599568 |
// FIR_IDENTICAL
// FIR_COMPARISON
fun test() {
fun aa() {}
val aaa = 10
<caret>
}
// EXIST: aa
// EXIST: aaa | plugins/kotlin/completion/tests/testData/basic/common/primitiveCompletion/localVariablesAndFunctions.kt | 4196229617 |
// FIR_IDENTICAL
// FIR_COMPARISON
fun foo(@kotlin.<caret>) { }
// INVOCATION_COUNT: 1
// EXIST: Suppress
// ABSENT: String
| plugins/kotlin/completion/tests/testData/basic/common/annotations/ParameterAnnotation7.kt | 1726897177 |
package three
class Nest | plugins/kotlin/completion/tests/testData/handlers/basic/ClassNameWithAliasConfict.dependency.kt | 3786768185 |
package katas.kotlin.leetcode.first_missing_positive
import datsok.shouldEqual
import org.junit.jupiter.api.Test
//
// https://leetcode.com/problems/first-missing-positive
//
// Given an unsorted integer array, find the smallest missing positive integer.
//
// Example 1:
// Input: [1,2,0]
// Output: 3
//
// Example 2:
// Input: [3,4,-1,1]
// Output: 2
//
// Example 3:
// Input: [7,8,9,11,12]
// Output: 1
//
// Follow up:
// Your algorithm should run in O(n) time and uses constant extra space.
//
fun firstMissingPositive(nums: IntArray): Int {
nums.indices.filter { nums[it] == 0 }.forEach { nums[it] = -1 }
nums.filter { it - 1 in nums.indices }.forEach { nums[it - 1] = 0 }
return (nums.indices.find { nums[it] != 0 } ?: nums.size) + 1
}
fun firstMissingPositive_2(nums: IntArray): Int {
val numbers = nums.sorted().filter { it > 0 }.toSet()
numbers.forEachIndexed { i, n ->
if (i + 1 != n) return i + 1
}
return (numbers.lastOrNull() ?: 0) + 1
}
fun firstMissingPositive_1(nums: IntArray): Int {
val positiveNumbers = nums.filter { it > 0 }
val max = positiveNumbers.maxOrNull() ?: 0
return 1.until(max).find { it !in positiveNumbers } ?: max + 1
}
fun firstMissingPositive_0(nums: IntArray): Int {
return (1..Int.MAX_VALUE).find { it !in nums } ?: -1
}
class FirstMissingPositiveTests {
private val f: (IntArray) -> Int = ::firstMissingPositive
@Test fun `some examples`() {
f(intArrayOf()) shouldEqual 1
f(intArrayOf(-1)) shouldEqual 1
f(intArrayOf(0)) shouldEqual 1
f(intArrayOf(123)) shouldEqual 1
f(intArrayOf(Int.MAX_VALUE)) shouldEqual 1
f(intArrayOf(1)) shouldEqual 2
f(intArrayOf(1, 2, 0)) shouldEqual 3
f(intArrayOf(1, 1, 2, 2, 0)) shouldEqual 3
f(intArrayOf(3, 4, -1, 1)) shouldEqual 2
f(intArrayOf(7, 8, 9, 11, 12)) shouldEqual 1
}
} | kotlin/src/katas/kotlin/leetcode/first_missing_positive/FirstMissingPositive.kt | 4174053405 |
package soutvoid.com.DsrWeatherApp.domain.triggers.condition
import com.google.gson.annotations.SerializedName
data class Condition(
@SerializedName("name")
val name: ConditionName,
@SerializedName("expression")
val expression: ConditionExpression,
@SerializedName("amount")
val amount: Double
) | app/src/main/java/soutvoid/com/DsrWeatherApp/domain/triggers/condition/Condition.kt | 1321904146 |
/*
* Copyright © 2019. Sir Wellington.
* 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 tech.sirwellington.alchemy.arguments.assertions
import org.hamcrest.Matchers.notNullValue
import org.junit.Assert.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import tech.sirwellington.alchemy.arguments.failedAssertion
import tech.sirwellington.alchemy.test.junit.ThrowableAssertion.assertThrows
import tech.sirwellington.alchemy.test.junit.runners.AlchemyTestRunner
import tech.sirwellington.alchemy.test.junit.runners.Repeat
/**
* @author SirWellington
*/
@Repeat(10)
@RunWith(AlchemyTestRunner::class)
class BooleanAssertionsTest
{
@Before
fun setUp()
{
}
@Test
fun testTrueStatement()
{
val assertion = trueStatement()
assertThat(assertion, notNullValue())
assertion.check(true)
assertThrows { assertion.check(false) }.failedAssertion()
assertThrows { assertion.check(null) }
.failedAssertion()
}
@Test
fun testFalseStatement()
{
val assertion = falseStatement()
assertThat(assertion, notNullValue())
assertion.check(false)
assertThrows { assertion.check(true) }.failedAssertion()
assertThrows { assertion.check(null) }
.failedAssertion()
}
} | src/test/java/tech/sirwellington/alchemy/arguments/assertions/BooleanAssertionsTest.kt | 859236115 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package openxr.templates
import org.lwjgl.generator.*
import openxr.*
val MNDX_egl_enable = "MNDXEGLEnable".nativeClassXR("MNDX_egl_enable", type = "instance", postfix = "MNDX") {
documentation =
"""
The $templateName extension.
"""
IntConstant(
"The extension specification version.",
"MNDX_egl_enable_SPEC_VERSION".."1"
)
StringConstant(
"The extension name.",
"MNDX_EGL_ENABLE_EXTENSION_NAME".."XR_MNDX_egl_enable"
)
EnumConstant(
"Extends {@code XrStructureType}.",
"TYPE_GRAPHICS_BINDING_EGL_MNDX".."1000048004"
)
} | modules/lwjgl/openxr/src/templates/kotlin/openxr/templates/MNDX_egl_enable.kt | 1611742519 |
package com.seancheey.scene.controller
import com.seancheey.game.Config
import com.seancheey.gui.RobotModelSlot
import com.seancheey.resources.Resources
import com.seancheey.scene.Scenes
import com.seancheey.scene.Stages
import javafx.fxml.FXML
import javafx.fxml.Initializable
import javafx.scene.control.Label
import javafx.scene.image.Image
import javafx.scene.image.ImageView
import javafx.scene.layout.VBox
import java.net.URL
import java.util.*
/**
* Created by Seancheey on 29/05/2017.
* GitHub: https://github.com/Seancheey
*/
class MenuController : Initializable {
@FXML
var botGroupBox: VBox? = null
@FXML
var playerLabel: Label? = null
@FXML
var titleImageView: ImageView? = null
override fun initialize(location: URL?, resources: ResourceBundle?) {
// set player label
playerLabel!!.text = "${Config.player.name}'s Robots"
// add player's first robot group
RobotModelSlot.addAllTo(botGroupBox!!.children, Config.player.robotGroups[0])
// put title image
titleImageView!!.image = Image(Resources.titleImageInStream)
}
fun startGameButtonPressed() {
Stages.switchScene(Scenes.battle)
if (Config.fullScreen)
Stages.primaryStage!!.isFullScreen = true
}
fun editRobotsButtonPressed() {
Stages.switchScene(Scenes.edit, 1080.0, 670.0)
if (Config.fullScreen)
Stages.primaryStage!!.isFullScreen = true
}
fun settingsButtonPressed() {
Stages.switchScene(Scenes.setting)
}
fun exitButtonPressed() {
Stages.primaryStage!!.close()
Config.programClosed = true
}
} | src/com/seancheey/scene/controller/MenuController.kt | 2372919966 |
package com.programming.kotlin.chapter03
import java.math.BigDecimal
open class Payment(val amount: BigDecimal) | Chapter03/inheritance/src/main/kotlin/com/programming/kotlin/chapter03/Payment.kt | 1063887471 |
package org.amshove.kluent.tests
data class Person(val name: String, val surname: String)
| common/src/test/kotlin/org/amshove/kluent/tests/DataClasses.kt | 1669304458 |
/*
* Copyright 2016 Michael Gnatz.
*
* 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 de.mg.stock.dto
import de.mg.stock.util.LocalDateTimeAdapter
import java.io.Serializable
import java.time.LocalDateTime
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter
class ChartItemDTO(@get:XmlJavaTypeAdapter(LocalDateTimeAdapter::class) var dateTime: LocalDateTime,
var minLong: Long? = null,
var maxLong: Long? = null,
var averageLong: Long?,
var instantPrice: Boolean) : Serializable {
val min: Double?
get() = if (minLong != null) minLong!! / 100.0 else null
val max: Double?
get() = if (maxLong != null) maxLong!! / 100.0 else null
val average: Double?
get() = if (averageLong != null) averageLong!! / 100.0 else null
val isValid: Boolean
get() {
var valid = true
if (minLong != null && maxLong != null)
valid = minLong!! <= maxLong!!
if (minLong != null && averageLong != null)
valid = valid && minLong!! <= averageLong!!
if (averageLong != null && maxLong != null)
valid = valid && averageLong!! <= maxLong!!
return valid
}
override fun toString(): String {
return "ChartItemDTO(dateTime=$dateTime, minLong=$minLong, maxLong=$maxLong, averageLong=$averageLong, instantPrice=$instantPrice)"
}
}
| stock-api/src/main/java/de/mg/stock/dto/ChartItemDTO.kt | 158018013 |
package com.elpassion.mainframerplugin.configuration
import com.intellij.openapi.command.impl.DummyProject
import org.junit.Assert.assertEquals
import org.junit.Test
class MainframerConfigurationFactoryTest {
val confFactory = MainframerConfigurationFactory(MainframerConfigurationType())
@Test
fun shouldHaveProperName() {
assertEquals("Factory for Mainframer configuration", confFactory.name)
}
@Test
fun shouldCreateProperRunConfiguration() {
assertEquals(MainframerRunConfiguration::class.java, confFactory.createTemplateConfiguration(DummyProject.getInstance()).javaClass)
}
}
| src/test/kotlin/com/elpassion/mainframerplugin/configuration/MainframerConfigurationFactoryTest.kt | 426039063 |
/*
* Kotlin version Copyright (c) 2014 Cazcade Limited (http://cazcade.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*
* Original Java codes was MIT License https://github.com/jeevatkm/digitalocean-api-java
*
* Copyright (c) 2010-2013 Jeevanandam M. (myjeeva.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package kontrol.doclient
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import kontrol.doclient.Action.*
import kontrol.doclient.*
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.utils.URIBuilder
import org.apache.http.conn.scheme.Scheme
import org.apache.http.conn.ssl.HackedSSLSocketFactory
import org.apache.http.impl.client.DefaultHttpClient
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.lang.reflect.Type
import java.net.URI
import com.google.gson.JsonElement
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
/**
* DigitalOcean API client wrapper methods Implementation
*
* @author Jeevanandam M. ([email protected])
*/
public class DigitalOceanClient(val clientId: String, val apiKey: String) : DigitalOcean {
public val TYPE_DROPLET_LIST: Type = object : TypeToken<MutableList<Droplet>>() {
}.getType()!!
public val TYPE_IMAGE_LIST: Type = object : TypeToken<MutableList<DropletImage>>() {
}.getType()!!
public val TYPE_REGION_LIST: Type = object : TypeToken<MutableList<Region>>() {
}.getType()!!
public val TYPE_SIZE_LIST: Type = object : TypeToken<MutableList<DropletSize>>() {
}.getType()!!
public val TYPE_DOMAIN_LIST: Type = object : TypeToken<MutableList<Domain>>() {
}.getType()!!
public val TYPE_DOMAIN_RECORD_LIST: Type = object : TypeToken<MutableList<DomainRecord>>() {
}.getType()!!
public val TYPE_SSH_KEY_LIST: Type = object : TypeToken<MutableList<SshKey>>() {
}.getType()!!
private val LOG: Logger = LoggerFactory.getLogger(javaClass<DigitalOceanClient>())!!
val gson: Gson = Gson()
public fun JsonElement.asClass(clazz: Class<*>): Any = gson.fromJson(this.toString(), clazz)!!
public fun JsonElement.asType(`type`: Type): Any = gson.fromJson(this.toString(), `type`)!!
/**
* Http client
*/
private var httpClient: DefaultHttpClient? = null
/**
* User's Client ID
*/
/**
* DigitalOcean API Host is <code>api.digitalocean.com</code>
*/
private var apiHost: String = "api.digitalocean.com"
public override fun droplets(): List<Droplet> = get(AVAILABLE_DROPLETS, TYPE_DROPLET_LIST) as List<Droplet>
public override fun createDroplet(droplet: Droplet, sshKeyIds: String?, backupsEnabled: Boolean, privateNetworking: Boolean): Droplet =
getWithParam(CREATE_DROPLET, javaClass<Droplet>(),
hashMapOf(
P_NAME to droplet.name,
P_SIZE_ID to droplet.size_id,
P_IMAGE_ID to droplet.image_id,
P_REGION_ID to droplet.region_id,
P_BACKUPS_ENABLED to backupsEnabled,
P_PRIVATE_NETWORKING to privateNetworking,
P_SSH_KEY_IDS to sshKeyIds
)
) as Droplet
override fun getDropletInfo(id: Int): Droplet = get(GET_DROPLET_INFO, javaClass<Droplet>(), id) as Droplet
override fun rebootDroplet(id: Int): Response = call(REBOOT_DROPLET, id)
override fun powerCyleDroplet(id: Int): Response = call(POWER_CYCLE_DROPLET, id)
override fun shutdownDroplet(id: Int): Response = call(SHUTDOWN_DROPLET, id)
override fun powerOffDroplet(id: Int): Response = call(POWER_OFF_DROPLET, id)
override fun powerOnDroplet(id: Int): Response = call(POWER_ON_DROPLET, id)
override fun resetDropletPassword(id: Int): Response = call(RESET_PASSWORD_DROPLET, id)
override fun resizeDroplet(id: Int, sizeId: Int): Response = callWithParam(RESIZE_DROPLET, hashMapOf(P_SIZE_ID to sizeId), id)
override fun takeDropletSnapshot(id: Int): Response = takeDropletSnapshot(id, null)
override fun takeDropletSnapshot(id: Int, name: String?): Response = when (name) {
null -> call(TAKE_DROPLET_SNAPSHOT, id)
else -> callWithParam(TAKE_DROPLET_SNAPSHOT, hashMapOf(P_NAME to name), id)
}
override fun restoreDroplet(id: Int, imageId: Int): Response = callWithParam(RESTORE_DROPLET, hashMapOf(P_IMAGE_ID to imageId), id)
override fun rebuildDroplet(id: Int, imageId: Int): Response = callWithParam(REBUILD_DROPLET, hashMapOf(P_IMAGE_ID to imageId), id)
override fun enableDropletBackups(id: Int): Response = call(ENABLE_AUTOMATIC_BACKUPS, id)
override fun disableDropletBackups(id: Int): Response = call(DISABLE_AUTOMATIC_BACKUPS, id)
override fun renameDroplet(id: Int, name: String): Response = callWithParam(RENAME_DROPLET, hashMapOf(P_NAME to name), id)
override fun deleteDroplet(id: Int): Response = call(DELETE_DROPLET, id)
override fun getAvailableRegions(): List<Region> = get(AVAILABLE_REGIONS, TYPE_REGION_LIST) as List<Region>
override fun getAvailableImages(): List<DropletImage> = get(AVAILABLE_IMAGES, TYPE_IMAGE_LIST) as List<DropletImage>
override fun getImageInfo(imageId: Int): DropletImage = get(GET_IMAGE_INFO, javaClass<DropletImage>(), imageId) as DropletImage
override fun deleteImage(imageId: Int): Response = call(DELETE_IMAGE, imageId)
override fun transferImage(imageId: Int, regionId: Int): Response = callWithParam(TRANSFER_IMAGE, hashMapOf(P_REGION_ID to regionId), imageId)
override fun getAvailableSshKeys(): List<SshKey> = get(AVAILABLE_SSH_KEYS, TYPE_SSH_KEY_LIST) as List<SshKey>
override fun getSshKeyInfo(sshKeyId: Int): SshKey = get(GET_SSH_KEY, javaClass<SshKey>(), sshKeyId) as SshKey
override fun addSshKey(name: String, publicKey: String): SshKey = get(CREATE_SSH_KEY, javaClass<SshKey>(), hashMapOf(P_NAME to name, P_PUBLIC_KEY to publicKey)) as SshKey
override fun editSshKey(sshKeyId: Int, newKey: String): SshKey = get(EDIT_SSH_KEY, javaClass<SshKey>(), hashMapOf(P_PUBLIC_KEY to newKey), sshKeyId) as SshKey
override fun deleteSshKey(sshKeyId: Int): Response = call(DELETE_SSH_KEY, sshKeyId)
override fun getAvailableSizes(): List<DropletSize> = get(AVAILABLE_SIZES, TYPE_SIZE_LIST) as List<DropletSize>
override fun getAvailableDomains(): List<Domain> = get(AVAILABLE_DOMAINS, TYPE_DOMAIN_LIST) as List<Domain>
override fun getDomainInfo(domainId: Int): Domain = get(GET_DOMAIN_INFO, javaClass<Domain>(), domainId) as Domain
override fun createDomain(domainName: String, ipAddress: String): Domain = get(CREATE_DOMAIN, javaClass<Domain>(), hashMapOf(P_NAME to domainName, PARAM_IP_ADDRESS to ipAddress)) as Domain
override fun deleteDomain(domainId: Int): Response = call(DELETE_DOMAIN, domainId)
override fun getDomainRecords(domainId: Int): List<DomainRecord> = get(GET_DOMAIN_RECORDS, TYPE_DOMAIN_RECORD_LIST, domainId) as List<DomainRecord>
override fun getDomainRecordInfo(domainId: Int, recordId: Int): DomainRecord = get(GET_DOMAIN_RECORD_INFO, javaClass<DomainRecord>(), array(domainId, recordId)) as DomainRecord
override fun createDomainRecord(domainRecord: DomainRecord): DomainRecord =
getWithParam(CREATE_DOMAIN_RECORD, javaClass<DomainRecord>(), domainRecord.asParams(), domainRecord.domain_id) as DomainRecord
override fun editDomainRecord(domainRecord: DomainRecord): DomainRecord = (getWithParam(EDIT_DOMAIN_RECORD, javaClass<DomainRecord>(), domainRecord.asParams(), array<Any>(domainRecord.domain_id?:-1, domainRecord.id?:-1)) as DomainRecord)
override fun deleteDomainRecord(domainId: Int, recordId: Int): Response = call(DELETE_DOMAIN_RECORD, array<Any>(domainId, recordId))
private fun performAction(action: Action, queryParams: Map<String, Any?>?, vararg pathParams: Any?): JsonObject {
try {
val uri = generateUri(action.mapPath, queryParams, *pathParams)
val obj = JsonParser().parse(execute(uri))?.getAsJsonObject()!!
if (obj.get(STATUS)?.getAsString()?.equalsIgnoreCase("OK")?:false) {
LOG.debug("JSON Respose Data: " + obj.toString())
return obj
} else {
throw RequestUnsuccessfulException("DigitalOcean API request unsuccessful, possible reason could be incorrect values [$uri].")
}
} catch (e: RequestUnsuccessfulException) {
throw e
} catch (e: Exception) {
throw RequestUnsuccessfulException(e.getMessage(), e)
}
}
private fun generateUri(path: String, queryParams: Map<String, Any?>?, vararg pathParams: Any?): URI {
val ub = URIBuilder()
.setScheme(HTTPS_SCHEME) ?.setHost(apiHost) ?.setPath(path.format(*pathParams))
?.setParameter(PARAM_CLIENT_ID, this.clientId) ?.setParameter(PARAM_API_KEY, this.apiKey)
queryParams?.entrySet()?.forEach { if (it.value != null) ub?.setParameter(it.key, it.value.toString()) }
return ub?.build()!!
}
private fun execute(uri: URI): String {
val httpGet = HttpGet(uri)
LOG.debug("DigitalOcean API Endpoint URI: " + uri)
try {
val httpResponse = httpClient?.execute(httpGet)
return when(httpResponse?.getStatusLine()?.getStatusCode()) {
401 -> throw AccessDeniedException("Request failed to authenticate into the DigitalOcean API successfully")
404 -> throw ResourceNotFoundException("Requested resource is not available DigitalOcean $uri")
else -> httpResponse?.getEntity()?.getContent()?.readFully()?:""
}
} finally {
httpGet.releaseConnection()
}
}
private fun call(action: Action, vararg pathParams: Any?): Response {
return performAction(action, null, *pathParams).asClass(javaClass<Response>()) as Response
}
private fun callWithParam(action: Action, queryParams: Map<String, Any?>?, vararg pathParams: Any?): Response {
return performAction(action, queryParams, *pathParams).asClass(javaClass<Response>()) as Response
}
private fun get(action: Action, clazz: Class<*>, vararg pathParams: Any?): Any? {
return performAction(action, null, *pathParams)[action.element]?.asClass(clazz)
}
private fun getWithParam(action: Action, clazz: Class<*>, queryParams: Map<String, Any?>?, vararg pathParams: Any?): Any? {
return performAction(action, queryParams, *pathParams)[action.element]?.asClass(clazz)
}
private fun get(action: Action, classType: Type, vararg pathParams: Any?): Any? {
return performAction(action, null, *pathParams)[action.element]?.asType(classType)
}
{
val base = DefaultHttpClient()
val ccm = base.getConnectionManager()
ccm?.getSchemeRegistry()?.register(Scheme("https", HackedSSLSocketFactory.newInstance(), 443))
this.httpClient = DefaultHttpClient(ccm, base.getParams())
}
}
| doclient/src/main/kotlin/DigitalOceanClient.kt | 3005856833 |
package com.alexstyl.specialdates.events.peopleevents
import com.alexstyl.specialdates.Strings
import com.alexstyl.specialdates.events.database.EventTypeId.TYPE_CUSTOM
class CustomEventType(private val name: String) : EventType {
override fun getEventName(strings: Strings): String = name
override val id: Int
get() = TYPE_CUSTOM
}
| memento/src/main/java/com/alexstyl/specialdates/events/peopleevents/CustomEventType.kt | 2485268779 |
package com.cv4j.app.fragment
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.cv4j.app.R
import com.cv4j.app.activity.CompareHistActivity
import com.cv4j.app.activity.HistogramDemoActivity
import com.cv4j.app.activity.HistogramEqualizationActivity
import com.cv4j.app.activity.ProjectHistActivity
import com.cv4j.app.app.BaseFragment
import kotlinx.android.synthetic.main.fragment_hist.*
/**
*
* @FileName:
* com.cv4j.app.fragment.HistFragment
* @author: Tony Shen
* @date: 2020-05-04 11:43
* @version: V1.0 <描述当前版本功能>
*/
class HistFragment : BaseFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = inflater.inflate(R.layout.fragment_hist, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
text1.setOnClickListener {
val i = Intent(mContext, HistogramEqualizationActivity::class.java)
i.putExtra("Title", text1.text.toString())
startActivity(i)
}
text2.setOnClickListener {
val i = Intent(mContext, HistogramDemoActivity::class.java)
i.putExtra("Title", text2.text.toString())
startActivity(i)
}
text3.setOnClickListener {
val i = Intent(mContext, CompareHistActivity::class.java)
i.putExtra("Title", text3.text.toString())
startActivity(i)
}
text4.setOnClickListener {
val i = Intent(mContext, ProjectHistActivity::class.java)
i.putExtra("Title", text4.text.toString())
startActivity(i)
}
}
} | app/src/main/java/com/cv4j/app/fragment/HistFragment.kt | 1558850749 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.nj2k.conversions
import com.intellij.psi.PsiEnumConstant
import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext
import org.jetbrains.kotlin.nj2k.symbols.*
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.psi.psiUtil.containingClass
class EnumFieldAccessConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) {
override fun applyToElement(element: JKTreeElement): JKTreeElement {
if (element !is JKFieldAccessExpression) return recurse(element)
if ((element.parent as? JKQualifiedExpression)?.selector == element) return recurse(element)
val enumsClassSymbol = element.identifier.enumClassSymbol() ?: return recurse(element)
return recurse(
JKQualifiedExpression(
JKClassAccessExpression(enumsClassSymbol),
JKFieldAccessExpression(element.identifier)
)
)
}
private fun JKFieldSymbol.enumClassSymbol(): JKClassSymbol? {
return when {
this is JKMultiverseFieldSymbol && target is PsiEnumConstant ->
symbolProvider.provideDirectSymbol(target.containingClass ?: return null) as? JKClassSymbol
this is JKMultiverseKtEnumEntrySymbol ->
symbolProvider.provideDirectSymbol(target.containingClass() ?: return null) as? JKClassSymbol
this is JKUniverseFieldSymbol && target is JKEnumConstant ->
symbolProvider.provideUniverseSymbol(target.parentOfType<JKClass>() ?: return null)
else -> null
}
}
} | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/EnumFieldAccessConversion.kt | 2826152397 |
/*
* 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.docs.web.reactive.webflux
import org.springframework.data.repository.reactive.ReactiveCrudRepository
import reactor.core.publisher.Flux
interface CustomerRepository : ReactiveCrudRepository<Customer?, Long?> {
fun findByUser(user: User?): Flux<Customer?>?
}
| spring-boot-project/spring-boot-docs/src/main/kotlin/org/springframework/boot/docs/web/reactive/webflux/CustomerRepository.kt | 23688255 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.util.isLineBreak
import org.jetbrains.kotlin.kdoc.psi.api.KDoc
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class RedundantSemicolonInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor {
return object : PsiElementVisitor() {
override fun visitElement(element: PsiElement) {
super.visitElement(element)
if (element.node.elementType == KtTokens.SEMICOLON && isRedundantSemicolon(element)) {
holder.registerProblem(
element,
KotlinBundle.message("redundant.semicolon"),
Fix
)
}
}
}
}
}
internal fun isRedundantSemicolon(semicolon: PsiElement): Boolean {
val nextLeaf = semicolon.nextLeaf { it !is PsiWhiteSpace && it !is PsiComment || it.isLineBreak() }
val isAtEndOfLine = nextLeaf == null || nextLeaf.isLineBreak()
if (!isAtEndOfLine) {
//when there is no imports parser generates empty import list with no spaces
if (semicolon.parent is KtPackageDirective && (nextLeaf as? KtImportList)?.imports?.isEmpty() == true) {
return true
}
if (semicolon.prevLeaf { it !is PsiWhiteSpace && it !is PsiComment || it.isLineBreak() } is PsiWhiteSpace &&
!semicolon.isBeforeLeftBrace()
) {
return true
}
return false
}
if (semicolon.prevLeaf()?.node?.elementType == KtNodeTypes.ELSE) return false
if (semicolon.parent is KtEnumEntry) return false
(semicolon.parent.parent as? KtClass)?.let { clazz ->
if (clazz.isEnum() && clazz.getChildrenOfType<KtEnumEntry>().isEmpty()) {
if (semicolon.prevLeaf {
it !is PsiWhiteSpace && it !is PsiComment && !it.isLineBreak()
}?.node?.elementType == KtTokens.LBRACE &&
clazz.declarations.isNotEmpty()
) {
//first semicolon in enum with no entries, but with some declarations
return false
}
}
}
(semicolon.prevLeaf()?.parent as? KtLoopExpression)?.let {
if (it !is KtDoWhileExpression && it.body == null)
return false
}
semicolon.prevLeaf()?.parent?.safeAs<KtIfExpression>()?.also { ifExpression ->
if (ifExpression.then == null)
return false
}
if (nextLeaf.isBeforeLeftBrace()) {
return false // case with statement starting with '{' and call on the previous line
}
return !isSemicolonRequired(semicolon)
}
private fun PsiElement?.isBeforeLeftBrace(): Boolean {
return this?.nextLeaf {
it !is PsiWhiteSpace && it !is PsiComment && it.getStrictParentOfType<KDoc>() == null &&
it.getStrictParentOfType<KtAnnotationEntry>() == null
}?.node?.elementType == KtTokens.LBRACE
}
private fun isSemicolonRequired(semicolon: PsiElement): Boolean {
if (isRequiredForCompanion(semicolon)) {
return true
}
val prevSibling = semicolon.getPrevSiblingIgnoringWhitespaceAndComments()
val nextSibling = semicolon.getNextSiblingIgnoringWhitespaceAndComments()
if (prevSibling.safeAs<KtNameReferenceExpression>()?.text in softModifierKeywords && nextSibling is KtDeclaration) {
// enum; class Foo
return true
}
if (nextSibling is KtPrefixExpression && nextSibling.operationToken == KtTokens.EXCL) {
val typeElement = semicolon.prevLeaf()?.getStrictParentOfType<KtTypeReference>()?.typeElement
if (typeElement != null) {
return typeElement !is KtNullableType // trailing '?' fixes parsing
}
}
return false
}
private fun isRequiredForCompanion(semicolon: PsiElement): Boolean {
val prev = semicolon.getPrevSiblingIgnoringWhitespaceAndComments() as? KtObjectDeclaration ?: return false
if (!prev.isCompanion()) return false
if (prev.nameIdentifier != null || prev.getChildOfType<KtClassBody>() != null) return false
val next = semicolon.getNextSiblingIgnoringWhitespaceAndComments() ?: return false
val firstChildNode = next.firstChild?.node ?: return false
if (KtTokens.KEYWORDS.contains(firstChildNode.elementType)) return false
return true
}
private object Fix : LocalQuickFix {
override fun getName() = KotlinBundle.message("fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
descriptor.psiElement.delete()
}
}
private val softModifierKeywords: List<String> = KtTokens.SOFT_KEYWORDS.types.mapNotNull { (it as? KtModifierKeywordToken)?.toString() }
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantSemicolonInspection.kt | 907249286 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gradle.service.project.open
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.externalSystem.importing.AbstractOpenProjectProvider
import com.intellij.openapi.externalSystem.importing.ImportSpecBuilder
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.internal.InternalExternalProjectInfo
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode.MODAL_SYNC
import com.intellij.openapi.externalSystem.service.project.ExternalProjectRefreshCallback
import com.intellij.openapi.externalSystem.service.project.ProjectDataManager
import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsManagerImpl
import com.intellij.openapi.externalSystem.service.ui.ExternalProjectDataSelectorDialog
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.plugins.gradle.settings.GradleSettings
import org.jetbrains.plugins.gradle.util.GradleConstants.BUILD_FILE_EXTENSIONS
import org.jetbrains.plugins.gradle.util.GradleConstants.SYSTEM_ID
import org.jetbrains.plugins.gradle.util.updateGradleJvm
import org.jetbrains.plugins.gradle.util.validateJavaHome
internal class GradleOpenProjectProvider : AbstractOpenProjectProvider() {
override val systemId = SYSTEM_ID
override fun isProjectFile(file: VirtualFile): Boolean {
return !file.isDirectory && BUILD_FILE_EXTENSIONS.any { file.name.endsWith(it) }
}
override fun linkToExistingProject(projectFile: VirtualFile, project: Project) {
LOG.debug("Link Gradle project '$projectFile' to existing project ${project.name}")
val projectPath = getProjectDirectory(projectFile).toNioPath()
val settings = createLinkSettings(projectPath, project)
validateJavaHome(project, projectPath, settings.resolveGradleVersion())
val externalProjectPath = settings.externalProjectPath
ExternalSystemApiUtil.getSettings(project, SYSTEM_ID).linkProject(settings)
if (!Registry.`is`("external.system.auto.import.disabled")) {
ExternalSystemUtil.refreshProject(
externalProjectPath,
ImportSpecBuilder(project, SYSTEM_ID)
.usePreviewMode()
.use(MODAL_SYNC)
)
ExternalProjectsManagerImpl.getInstance(project).runWhenInitialized {
ExternalSystemUtil.refreshProject(
externalProjectPath,
ImportSpecBuilder(project, SYSTEM_ID)
.callback(createFinalImportCallback(project, externalProjectPath))
)
}
}
}
private fun createFinalImportCallback(project: Project, externalProjectPath: String): ExternalProjectRefreshCallback {
return object : ExternalProjectRefreshCallback {
override fun onSuccess(externalProject: DataNode<ProjectData>?) {
if (externalProject == null) return
selectDataToImport(project, externalProjectPath, externalProject)
importData(project, externalProject)
updateGradleJvm(project, externalProjectPath)
}
}
}
private fun selectDataToImport(project: Project, externalProjectPath: String, externalProject: DataNode<ProjectData>) {
val settings = GradleSettings.getInstance(project)
val showSelectiveImportDialog = settings.showSelectiveImportDialogOnInitialImport()
val application = ApplicationManager.getApplication()
if (showSelectiveImportDialog && !application.isHeadlessEnvironment) {
application.invokeAndWait {
val projectInfo = InternalExternalProjectInfo(SYSTEM_ID, externalProjectPath, externalProject)
val dialog = ExternalProjectDataSelectorDialog(project, projectInfo)
if (dialog.hasMultipleDataToSelect()) {
dialog.showAndGet()
}
else {
Disposer.dispose(dialog.disposable)
}
}
}
}
private fun importData(project: Project, externalProject: DataNode<ProjectData>) {
ProjectDataManager.getInstance().importData(externalProject, project, false)
}
} | plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/open/GradleOpenProjectProvider.kt | 926966684 |
// 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.quickfix
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInspection.SuppressIntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.idea.base.fe10.codeInsight.KotlinBaseFe10CodeInsightBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.highlighter.AnnotationHostKind
import org.jetbrains.kotlin.idea.util.addAnnotation
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.psi.psiUtil.replaceFileAnnotationList
import org.jetbrains.kotlin.resolve.BindingContext
class KotlinSuppressIntentionAction(
suppressAt: KtElement,
private val suppressionKey: String,
private val kind: AnnotationHostKind
) : SuppressIntentionAction() {
val pointer = suppressAt.createSmartPointer()
val project = suppressAt.project
override fun getFamilyName() = KotlinBaseFe10CodeInsightBundle.message("intention.suppress.family")
override fun getText() = KotlinBaseFe10CodeInsightBundle.message("intention.suppress.text", suppressionKey, kind.kind, kind.name ?: "")
override fun isAvailable(project: Project, editor: Editor?, element: PsiElement) = element.isValid
override fun invoke(project: Project, editor: Editor?, element: PsiElement) {
if (!element.isValid) return
val suppressAt = pointer.element ?: return
if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return
val id = "\"$suppressionKey\""
when (suppressAt) {
is KtModifierListOwner -> suppressAt.addAnnotation(
StandardNames.FqNames.suppress,
id,
whiteSpaceText = if (kind.newLineNeeded) "\n" else " ",
addToExistingAnnotation = { entry ->
addArgumentToSuppressAnnotation(
entry,
id
); true
})
is KtAnnotatedExpression ->
suppressAtAnnotatedExpression(CaretBox(suppressAt, editor), id)
is KtExpression ->
suppressAtExpression(CaretBox(suppressAt, editor), id)
is KtFile ->
suppressAtFile(suppressAt, id)
}
}
private fun suppressAtFile(ktFile: KtFile, id: String) {
val psiFactory = KtPsiFactory(project)
val fileAnnotationList: KtFileAnnotationList? = ktFile.fileAnnotationList
if (fileAnnotationList == null) {
val newAnnotationList = psiFactory.createFileAnnotationListWithAnnotation(suppressAnnotationText(id, false))
val packageDirective = ktFile.packageDirective
val createAnnotationList = if (packageDirective != null && PsiTreeUtil.skipWhitespacesForward(packageDirective) == ktFile.importList) {
// packageDirective could be empty but suppression still should be added before it to generate consistent PSI
ktFile.addBefore(newAnnotationList, packageDirective) as KtFileAnnotationList
} else {
replaceFileAnnotationList(ktFile, newAnnotationList)
}
ktFile.addAfter(psiFactory.createWhiteSpace(kind), createAnnotationList)
return
}
val suppressAnnotation: KtAnnotationEntry? = findSuppressAnnotation(fileAnnotationList)
if (suppressAnnotation == null) {
val newSuppressAnnotation = psiFactory.createFileAnnotation(suppressAnnotationText(id, false))
fileAnnotationList.add(psiFactory.createWhiteSpace(kind))
fileAnnotationList.add(newSuppressAnnotation) as KtAnnotationEntry
return
}
addArgumentToSuppressAnnotation(suppressAnnotation, id)
}
private fun suppressAtAnnotatedExpression(suppressAt: CaretBox<KtAnnotatedExpression>, id: String) {
val entry = findSuppressAnnotation(suppressAt.expression)
if (entry != null) {
// already annotated with @suppress
addArgumentToSuppressAnnotation(entry, id)
} else {
suppressAtExpression(suppressAt, id)
}
}
private fun suppressAtExpression(caretBox: CaretBox<KtExpression>, id: String) {
val suppressAt = caretBox.expression
assert(suppressAt !is KtDeclaration) { "Declarations should have been checked for above" }
val placeholderText = "PLACEHOLDER_ID"
val annotatedExpression = KtPsiFactory(suppressAt).createExpression(suppressAnnotationText(id) + "\n" + placeholderText)
val copy = suppressAt.copy()!!
val afterReplace = suppressAt.replace(annotatedExpression) as KtAnnotatedExpression
val toReplace = afterReplace.findElementAt(afterReplace.textLength - 2)!!
assert(toReplace.text == placeholderText)
val result = toReplace.replace(copy)!!
caretBox.positionCaretInCopy(result)
}
private fun addArgumentToSuppressAnnotation(entry: KtAnnotationEntry, id: String) {
// add new arguments to an existing entry
val args = entry.valueArgumentList
val psiFactory = KtPsiFactory(entry)
val newArgList = psiFactory.createCallArguments("($id)")
when {
args == null -> // new argument list
entry.addAfter(newArgList, entry.lastChild)
args.arguments.isEmpty() -> // replace '()' with a new argument list
args.replace(newArgList)
else -> args.addArgument(newArgList.arguments[0])
}
}
private fun suppressAnnotationText(id: String, withAt: Boolean = true): String {
return "${if (withAt) "@" else ""}${StandardNames.FqNames.suppress.shortName()}($id)"
}
private fun findSuppressAnnotation(annotated: KtAnnotated): KtAnnotationEntry? {
val context = annotated.analyze()
return findSuppressAnnotation(context, annotated.annotationEntries)
}
private fun findSuppressAnnotation(annotationList: KtFileAnnotationList): KtAnnotationEntry? {
val context = annotationList.analyze()
return findSuppressAnnotation(context, annotationList.annotationEntries)
}
private fun findSuppressAnnotation(context: BindingContext, annotationEntries: List<KtAnnotationEntry>): KtAnnotationEntry? {
return annotationEntries.firstOrNull { entry ->
context.get(BindingContext.ANNOTATION, entry)?.fqName == StandardNames.FqNames.suppress
}
}
}
private fun KtPsiFactory.createWhiteSpace(kind: AnnotationHostKind): PsiElement {
return if (kind.newLineNeeded) createNewLine() else createWhiteSpace()
}
private class CaretBox<out E : KtExpression>(
val expression: E,
private val editor: Editor?
) {
private val offsetInExpression: Int = (editor?.caretModel?.offset ?: 0) - expression.textRange!!.startOffset
fun positionCaretInCopy(copy: PsiElement) {
if (editor == null) return
editor.caretModel.moveToOffset(copy.textOffset + offsetInExpression)
}
}
| plugins/kotlin/base/fe10/code-insight/src/org/jetbrains/kotlin/idea/quickfix/KotlinSuppressIntentionAction.kt | 68314343 |
@file:JvmName("SwagBot")
package xyz.swagbot
import discord4j.core.*
import discord4j.core.`object`.presence.*
import discord4j.core.event.*
import discord4j.core.event.domain.message.*
import discord4j.core.shard.*
import discord4j.gateway.intent.*
import discord4j.rest.response.*
import io.facet.common.*
import io.facet.common.dsl.*
import io.facet.core.*
import io.facet.core.features.*
import kotlinx.coroutines.*
import org.slf4j.*
import xyz.swagbot.commands.*
import xyz.swagbot.extensions.*
import xyz.swagbot.features.*
import xyz.swagbot.features.autoroles.*
import xyz.swagbot.features.bgw.*
import xyz.swagbot.features.games.*
import xyz.swagbot.features.guilds.*
import xyz.swagbot.features.music.*
import xyz.swagbot.features.permissions.*
import xyz.swagbot.features.system.*
import xyz.swagbot.util.*
val logger: Logger = LoggerFactory.getLogger(EnvVars.BOT_NAME)
fun main() {
logger.info("Starting SwagBot (v${EnvVars.CODE_VERSION})")
val client = DiscordClient.builder(EnvVars.BOT_TOKEN)
.onClientResponse(ResponseFunction.emptyIfNotFound())
.build()
client.gateway()
.setEnabledIntents(IntentSet.all())
.setSharding(ShardingStrategy.recommended())
.setInitialPresence { ClientPresence.online(ClientActivity.listening("~help")) }
.withPlugins(EventDispatcher::configure)
.withPlugins(GatewayDiscordClient::configure)
.block()
}
@OptIn(ObsoleteCoroutinesApi::class)
suspend fun EventDispatcher.configure(scope: CoroutineScope) {
install(scope, PostgresDatabase) {
databaseName = EnvVars.POSTGRES_DB
databaseUsername = EnvVars.POSTGRES_USER
databasePassword = EnvVars.POSTGRES_PASSWORD
}
install(scope, GuildStorage)
install(scope, ChatCommands) {
useDefaultHelpCommand = true
commandPrefix { guildId -> feature(GuildStorage).commandPrefixFor(guildId) }
registerCommands(
BringCommand,
CatCommand,
ChangePrefixCommand,
Clear,
Crewlink,
DogCommand,
InfoCommand,
JoinCommand,
LeaveCommand,
LeaverClear,
LmgtfyCommand,
NowPlayingCommand,
PauseResumeCommand,
Premium,
Queue,
SkipCommand,
)
}
install(scope, Permissions) {
developers = setOf(97341976214511616, 212311415455744000, 98200921950920704)
}
install(scope, Music)
install(scope, BotPresence)
install(scope, AutoAssignRole)
install(scope, ChatGames)
install(scope, Market)
install(scope, BestGroupWorldStuff)
install(scope, AmongUs)
}
@OptIn(ObsoleteCoroutinesApi::class)
suspend fun GatewayDiscordClient.configure(scope: CoroutineScope) {
listener<MessageCreateEvent>(scope) { event ->
if (event.message.userMentionIds.contains(selfId)) {
val prefix = commandPrefixFor(null)
event.message.reply(baseTemplate.and {
description = "Hi **${event.message.author.get().username}**! My command prefix is `$prefix`. To " +
"learn more about me, type `${prefix}info`, and to see my commands, type `${prefix}help`."
})
}
}
install(scope, ApplicationCommands) {
registerCommand(
ChangePermissionCommand,
DisconnectRouletteCommand,
MigrateCommand,
Ping,
Play,
Prune,
YouTubeSearch,
VolumeCommand,
VoteSkipCommand
)
}
scope.launch {
// logger.info(
// restClient.applicationService.getGlobalApplicationCommands(selfId.asLong()).await().toString()
// )
// logger.info(
// restClient.applicationService.getGuildApplicationCommands(selfId.asLong(), 97342233241464832).await().toString()
// )
}
//ApplicationCommandRequ{name=search, description=Search YouTube and select a video to play using reaction buttons., options=[ApplicationCommandOptionData{type=3, name=query, description=The search term to look up on YouTube., required=Possible{true}, choices=null, options=null}, ApplicationCommandOptionData{type=4, name=count, description=The number of results to show., required=Possible{false}, choices=[ApplicationCommandOptionChoiceData{name=Five results, value=5}, ApplicationCommandOptionChoiceData{name=Ten results, value=10}], options=null}], defaultPermission=Possible{true}}
//ApplicationCommandData{name=search, description=Search YouTube and select a video to play using reaction buttons., options=[ApplicationCommandOptionData{type=3, name=query, description=The search term to look up on YouTube., required=Possible{true}, choices=null, options=null}, ApplicationCommandOptionData{type=4, name=count, description=The number of results to show., required=Possible.absent, choices=[ApplicationCommandOptionChoiceData{name=Five results, value=5}, ApplicationCommandOptionChoiceData{name=Ten results, value=10}], options=null}], defaultPermission=Possible{true}}
}
| src/main/kotlin/SwagBot.kt | 1166211454 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.codeInsight.hints.declarative
import com.intellij.lang.Language
import com.intellij.openapi.project.Project
import javax.swing.JComponent
/**
* Provider of a custom settings page for the declarative inlay hints.
*
* Responsible for UI component creation.
*
* Doesn't apply changes immediately, only in [persistSettings]
*/
interface InlayHintsCustomSettingsProvider<T> {
companion object {
fun getCustomSettingsProvider(providerId: String, language: Language): InlayHintsCustomSettingsProvider<*>? {
for (extensionPoint in InlayHintsCustomSettingsProviderBean.EP.extensionList) {
val extensionLanguage = extensionPoint.language
if (extensionPoint.providerId == providerId && extensionLanguage != null && language.isKindOf(extensionLanguage)) {
return extensionPoint.instance
}
}
return null
}
}
fun createComponent(project: Project, language: Language) : JComponent
fun isDifferentFrom(project: Project, settings: T) : Boolean
fun getSettingsCopy() : T
fun putSettings(project: Project, settings: T, language: Language)
fun persistSettings(project: Project, settings: T, language: Language)
} | platform/lang-api/src/com/intellij/codeInsight/hints/declarative/InlayHintsCustomSettingsProvider.kt | 3349937175 |
package org.jetbrains.cabal.psi
import com.intellij.lang.ASTNode
import com.intellij.extapi.psi.ASTWrapperPsiElement
import org.jetbrains.cabal.parser.*
import org.jetbrains.cabal.psi.SingleValueField
open class BoolField(node: ASTNode) : SingleValueField(node) | plugin/src/org/jetbrains/cabal/psi/BoolField.kt | 4049748770 |
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.tests
import androidx.test.core.app.ApplicationProvider
import com.google.samples.apps.iosched.shared.data.prefs.PreferenceStorage
import com.google.samples.apps.iosched.shared.di.ApplicationScope
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.test.runTest
import org.junit.rules.TestWatcher
import org.junit.runner.Description
/**
* Rule to be used in tests that sets the preferences needed for avoiding onboarding flows,
* resetting filters, etc.
*/
class SetPreferencesRule : TestWatcher() {
@InstallIn(SingletonComponent::class)
@EntryPoint
interface SetPreferencesRuleEntryPoint {
fun preferenceStorage(): PreferenceStorage
@ApplicationScope
fun applicationScope(): CoroutineScope
}
override fun starting(description: Description?) {
super.starting(description)
EntryPointAccessors.fromApplication(
ApplicationProvider.getApplicationContext(),
SetPreferencesRuleEntryPoint::class.java
).preferenceStorage().apply {
runTest {
completeOnboarding(true)
showScheduleUiHints(true)
preferConferenceTimeZone(true)
selectFilters("")
sendUsageStatistics(false)
showNotificationsPreference(true)
}
}
}
override fun finished(description: Description) {
// At the end of every test, cancel the application scope
// So DataStore is closed
EntryPointAccessors.fromApplication(
ApplicationProvider.getApplicationContext(),
SetPreferencesRuleEntryPoint::class.java
).applicationScope().cancel()
super.finished(description)
}
}
| mobile/src/androidTest/java/com/google/samples/apps/iosched/tests/SetPreferencesRule.kt | 3108078600 |
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.shared.model
import com.google.samples.apps.iosched.model.ConferenceData
import com.google.samples.apps.iosched.model.ConferenceDay
import com.google.samples.apps.iosched.shared.data.ConferenceDataRepository
import com.google.samples.apps.iosched.shared.data.ConferenceDataSource
import com.google.samples.apps.iosched.test.data.TestData
import com.google.samples.apps.iosched.test.util.FakeAppDatabase
object TestDataSource : ConferenceDataSource {
override fun getRemoteConferenceData(): ConferenceData? {
return TestData.conferenceData
}
override fun getOfflineConferenceData(): ConferenceData? {
return TestData.conferenceData
}
}
/** ConferenceDataRepository for tests */
object TestDataRepository : ConferenceDataRepository(
TestDataSource,
TestDataSource,
FakeAppDatabase()
) {
override fun getConferenceDays(): List<ConferenceDay> = TestData.TestConferenceDays
}
| shared/src/test/java/com/google/samples/apps/iosched/shared/model/SharedTestData.kt | 597304006 |
// 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.fe10.testGenerator
import org.jetbrains.kotlin.AbstractDataFlowValueRenderingTest
import org.jetbrains.kotlin.addImport.AbstractAddImportTest
import org.jetbrains.kotlin.addImportAlias.AbstractAddImportAliasTest53
import org.jetbrains.kotlin.asJava.classes.AbstractUltraLightClassLoadingTest
import org.jetbrains.kotlin.asJava.classes.AbstractUltraLightClassSanityTest
import org.jetbrains.kotlin.asJava.classes.AbstractUltraLightFacadeClassTest15
import org.jetbrains.kotlin.asJava.classes.AbstractUltraLightScriptLoadingTest
import org.jetbrains.kotlin.checkers.*
import org.jetbrains.kotlin.copyright.AbstractUpdateKotlinCopyrightTest
import org.jetbrains.kotlin.findUsages.*
import org.jetbrains.kotlin.formatter.AbstractEnterHandlerTest
import org.jetbrains.kotlin.formatter.AbstractFormatterTest
import org.jetbrains.kotlin.idea.AbstractExpressionSelectionTest
import org.jetbrains.kotlin.idea.AbstractSmartSelectionTest
import org.jetbrains.kotlin.idea.AbstractWorkSelectionTest
import org.jetbrains.kotlin.idea.actions.AbstractGotoTestOrCodeActionTest
import org.jetbrains.kotlin.idea.base.plugin.artifacts.TestKotlinArtifacts
import org.jetbrains.kotlin.idea.caches.resolve.*
import org.jetbrains.kotlin.idea.codeInsight.*
import org.jetbrains.kotlin.idea.codeInsight.codevision.AbstractKotlinCodeVisionProviderTest
import org.jetbrains.kotlin.idea.codeInsight.generate.AbstractCodeInsightActionTest
import org.jetbrains.kotlin.idea.codeInsight.generate.AbstractGenerateHashCodeAndEqualsActionTest
import org.jetbrains.kotlin.idea.codeInsight.generate.AbstractGenerateTestSupportMethodActionTest
import org.jetbrains.kotlin.idea.codeInsight.generate.AbstractGenerateToStringActionTest
import org.jetbrains.kotlin.idea.codeInsight.hints.AbstractKotlinArgumentsHintsProviderTest
import org.jetbrains.kotlin.idea.codeInsight.hints.AbstractKotlinLambdasHintsProvider
import org.jetbrains.kotlin.idea.codeInsight.hints.AbstractKotlinRangesHintsProviderTest
import org.jetbrains.kotlin.idea.codeInsight.hints.AbstractKotlinReferenceTypeHintsProviderTest
import org.jetbrains.kotlin.idea.codeInsight.inspections.shared.AbstractSharedK1InspectionTest
import org.jetbrains.kotlin.idea.codeInsight.intentions.shared.AbstractSharedK1IntentionTest
import org.jetbrains.kotlin.idea.codeInsight.inspections.shared.AbstractSharedK1LocalInspectionTest
import org.jetbrains.kotlin.idea.codeInsight.inspections.shared.idea.kdoc.AbstractSharedK1KDocHighlightingTest
import org.jetbrains.kotlin.idea.codeInsight.moveUpDown.AbstractMoveLeftRightTest
import org.jetbrains.kotlin.idea.codeInsight.moveUpDown.AbstractMoveStatementTest
import org.jetbrains.kotlin.idea.codeInsight.postfix.AbstractPostfixTemplateProviderTest
import org.jetbrains.kotlin.idea.codeInsight.surroundWith.AbstractSurroundWithTest
import org.jetbrains.kotlin.idea.codeInsight.unwrap.AbstractUnwrapRemoveTest
import org.jetbrains.kotlin.idea.compilerPlugin.kotlinxSerialization.AbstractSerializationPluginIdeDiagnosticTest
import org.jetbrains.kotlin.idea.compilerPlugin.kotlinxSerialization.AbstractSerializationQuickFixTest
import org.jetbrains.kotlin.idea.completion.test.*
import org.jetbrains.kotlin.idea.completion.test.handlers.*
import org.jetbrains.kotlin.idea.completion.test.weighers.AbstractBasicCompletionWeigherTest
import org.jetbrains.kotlin.idea.completion.test.weighers.AbstractSmartCompletionWeigherTest
import org.jetbrains.kotlin.idea.configuration.AbstractGradleConfigureProjectByChangingFileTest
import org.jetbrains.kotlin.idea.conversion.copy.AbstractLiteralKotlinToKotlinCopyPasteTest
import org.jetbrains.kotlin.idea.conversion.copy.AbstractLiteralTextToKotlinCopyPasteTest
import org.jetbrains.kotlin.idea.coverage.AbstractKotlinCoverageOutputFilesTest
import org.jetbrains.kotlin.idea.debugger.evaluate.AbstractCodeFragmentAutoImportTest
import org.jetbrains.kotlin.idea.debugger.evaluate.AbstractCodeFragmentCompletionHandlerTest
import org.jetbrains.kotlin.idea.debugger.evaluate.AbstractCodeFragmentCompletionTest
import org.jetbrains.kotlin.idea.debugger.evaluate.AbstractCodeFragmentHighlightingTest
import org.jetbrains.kotlin.idea.debugger.test.*
import org.jetbrains.kotlin.idea.debugger.test.sequence.exec.AbstractSequenceTraceTestCase
import org.jetbrains.kotlin.idea.debugger.test.sequence.exec.AbstractSequenceTraceWithIREvaluatorTestCase
import org.jetbrains.kotlin.idea.decompiler.navigation.AbstractNavigateJavaToLibrarySourceTest
import org.jetbrains.kotlin.idea.decompiler.navigation.AbstractNavigateToDecompiledLibraryTest
import org.jetbrains.kotlin.idea.decompiler.navigation.AbstractNavigateToLibrarySourceTest
import org.jetbrains.kotlin.idea.decompiler.navigation.AbstractNavigateToLibrarySourceTestWithJS
import org.jetbrains.kotlin.idea.decompiler.stubBuilder.AbstractLoadJavaClsStubTest
import org.jetbrains.kotlin.idea.decompiler.textBuilder.AbstractCommonDecompiledTextFromJsMetadataTest
import org.jetbrains.kotlin.idea.decompiler.textBuilder.AbstractCommonDecompiledTextTest
import org.jetbrains.kotlin.idea.decompiler.textBuilder.AbstractJsDecompiledTextFromJsMetadataTest
import org.jetbrains.kotlin.idea.decompiler.textBuilder.AbstractJvmDecompiledTextTest
import org.jetbrains.kotlin.idea.editor.backspaceHandler.AbstractBackspaceHandlerTest
import org.jetbrains.kotlin.idea.editor.commenter.AbstractKotlinCommenterTest
import org.jetbrains.kotlin.idea.editor.quickDoc.AbstractQuickDocProviderTest
import org.jetbrains.kotlin.idea.externalAnnotations.AbstractExternalAnnotationTest
import org.jetbrains.kotlin.idea.folding.AbstractKotlinFoldingTest
import org.jetbrains.kotlin.idea.hierarchy.AbstractHierarchyTest
import org.jetbrains.kotlin.idea.hierarchy.AbstractHierarchyWithLibTest
import org.jetbrains.kotlin.idea.highlighter.*
import org.jetbrains.kotlin.idea.imports.AbstractAutoImportTest
import org.jetbrains.kotlin.idea.imports.AbstractFilteringAutoImportTest
import org.jetbrains.kotlin.idea.imports.AbstractJsOptimizeImportsTest
import org.jetbrains.kotlin.idea.imports.AbstractJvmOptimizeImportsTest
import org.jetbrains.kotlin.idea.index.AbstractKotlinTypeAliasByExpansionShortNameIndexTest
import org.jetbrains.kotlin.idea.inspections.AbstractLocalInspectionTest
import org.jetbrains.kotlin.idea.inspections.AbstractMultiFileLocalInspectionTest
import org.jetbrains.kotlin.idea.inspections.AbstractViewOfflineInspectionTest
import org.jetbrains.kotlin.idea.intentions.AbstractConcatenatedStringGeneratorTest
import org.jetbrains.kotlin.idea.intentions.AbstractK1IntentionTest
import org.jetbrains.kotlin.idea.intentions.AbstractK1IntentionTest2
import org.jetbrains.kotlin.idea.intentions.AbstractMultiFileIntentionTest
import org.jetbrains.kotlin.idea.intentions.declarations.AbstractJoinLinesTest
import org.jetbrains.kotlin.idea.internal.AbstractBytecodeToolWindowTest
import org.jetbrains.kotlin.idea.kdoc.AbstractKDocHighlightingTest
import org.jetbrains.kotlin.idea.kdoc.AbstractKDocTypingTest
import org.jetbrains.kotlin.idea.maven.AbstractKotlinMavenInspectionTest
import org.jetbrains.kotlin.idea.maven.configuration.AbstractMavenConfigureProjectByChangingFileTest
import org.jetbrains.kotlin.idea.navigation.*
import org.jetbrains.kotlin.idea.navigationToolbar.AbstractKotlinNavBarTest
import org.jetbrains.kotlin.idea.parameterInfo.AbstractParameterInfoTest
import org.jetbrains.kotlin.idea.perf.stats.AbstractPerformanceBasicCompletionHandlerStatNamesTest
import org.jetbrains.kotlin.idea.perf.stats.AbstractPerformanceHighlightingStatNamesTest
import org.jetbrains.kotlin.idea.perf.synthetic.*
import org.jetbrains.kotlin.idea.quickfix.*
import org.jetbrains.kotlin.idea.refactoring.AbstractNameSuggestionProviderTest
import org.jetbrains.kotlin.idea.refactoring.copy.AbstractCopyTest
import org.jetbrains.kotlin.idea.refactoring.copy.AbstractMultiModuleCopyTest
import org.jetbrains.kotlin.idea.refactoring.inline.AbstractInlineMultiFileTest
import org.jetbrains.kotlin.idea.refactoring.inline.AbstractInlineTest
import org.jetbrains.kotlin.idea.refactoring.inline.AbstractInlineTestWithSomeDescriptors
import org.jetbrains.kotlin.idea.refactoring.introduce.AbstractExtractionTest
import org.jetbrains.kotlin.idea.refactoring.move.AbstractMoveTest
import org.jetbrains.kotlin.idea.refactoring.move.AbstractMultiModuleMoveTest
import org.jetbrains.kotlin.idea.refactoring.pullUp.AbstractPullUpTest
import org.jetbrains.kotlin.idea.refactoring.pushDown.AbstractPushDownTest
import org.jetbrains.kotlin.idea.refactoring.rename.AbstractMultiModuleRenameTest
import org.jetbrains.kotlin.idea.refactoring.rename.AbstractRenameTest
import org.jetbrains.kotlin.idea.refactoring.safeDelete.AbstractMultiModuleSafeDeleteTest
import org.jetbrains.kotlin.idea.refactoring.safeDelete.AbstractSafeDeleteTest
import org.jetbrains.kotlin.idea.repl.AbstractIdeReplCompletionTest
import org.jetbrains.kotlin.idea.resolve.*
import org.jetbrains.kotlin.idea.scratch.AbstractScratchLineMarkersTest
import org.jetbrains.kotlin.idea.scratch.AbstractScratchRunActionTest
import org.jetbrains.kotlin.idea.script.*
import org.jetbrains.kotlin.idea.search.refIndex.AbstractFindUsagesWithCompilerReferenceIndexTest
import org.jetbrains.kotlin.idea.search.refIndex.AbstractKotlinCompilerReferenceTest
import org.jetbrains.kotlin.idea.slicer.AbstractSlicerLeafGroupingTest
import org.jetbrains.kotlin.idea.slicer.AbstractSlicerMultiplatformTest
import org.jetbrains.kotlin.idea.slicer.AbstractSlicerNullnessGroupingTest
import org.jetbrains.kotlin.idea.slicer.AbstractSlicerTreeTest
import org.jetbrains.kotlin.idea.structureView.AbstractKotlinFileStructureTest
import org.jetbrains.kotlin.idea.stubs.AbstractMultiFileHighlightingTest
import org.jetbrains.kotlin.idea.stubs.AbstractResolveByStubTest
import org.jetbrains.kotlin.idea.stubs.AbstractStubBuilderTest
import org.jetbrains.kotlin.nj2k.*
import org.jetbrains.kotlin.nj2k.inference.common.AbstractCommonConstraintCollectorTest
import org.jetbrains.kotlin.nj2k.inference.mutability.AbstractMutabilityInferenceTest
import org.jetbrains.kotlin.nj2k.inference.nullability.AbstractNullabilityInferenceTest
import org.jetbrains.kotlin.pacelize.ide.test.AbstractParcelizeCheckerTest
import org.jetbrains.kotlin.pacelize.ide.test.AbstractParcelizeQuickFixTest
import org.jetbrains.kotlin.psi.patternMatching.AbstractPsiUnifierTest
import org.jetbrains.kotlin.search.AbstractAnnotatedMembersSearchTest
import org.jetbrains.kotlin.search.AbstractInheritorsSearchTest
import org.jetbrains.kotlin.shortenRefs.AbstractShortenRefsTest
import org.jetbrains.kotlin.test.TargetBackend
import org.jetbrains.kotlin.testGenerator.generator.TestGenerator
import org.jetbrains.kotlin.testGenerator.model.*
import org.jetbrains.kotlin.testGenerator.model.Patterns.DIRECTORY
import org.jetbrains.kotlin.testGenerator.model.Patterns.JAVA
import org.jetbrains.kotlin.testGenerator.model.Patterns.KT
import org.jetbrains.kotlin.testGenerator.model.Patterns.KTS
import org.jetbrains.kotlin.testGenerator.model.Patterns.KT_OR_KTS
import org.jetbrains.kotlin.testGenerator.model.Patterns.KT_OR_KTS_WITHOUT_DOTS
import org.jetbrains.kotlin.testGenerator.model.Patterns.KT_WITHOUT_DOTS
import org.jetbrains.kotlin.testGenerator.model.Patterns.KT_WITHOUT_DOT_AND_FIR_PREFIX
import org.jetbrains.kotlin.testGenerator.model.Patterns.KT_WITHOUT_FIR_PREFIX
import org.jetbrains.kotlin.testGenerator.model.Patterns.TEST
import org.jetbrains.kotlin.testGenerator.model.Patterns.WS_KTS
import org.jetbrains.kotlin.tools.projectWizard.cli.AbstractProjectTemplateBuildFileGenerationTest
import org.jetbrains.kotlin.tools.projectWizard.cli.AbstractYamlBuildFileGenerationTest
import org.jetbrains.kotlin.tools.projectWizard.wizard.AbstractProjectTemplateNewWizardProjectImportTest
import org.jetbrains.kotlin.tools.projectWizard.wizard.AbstractYamlNewWizardProjectImportTest
import org.jetbrains.uast.test.kotlin.comparison.*
fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) {
generateK1Tests()
}
fun generateK1Tests(isUpToDateCheck: Boolean = false) {
System.setProperty("java.awt.headless", "true")
TestGenerator.write(assembleWorkspace(), isUpToDateCheck)
}
private fun assembleWorkspace(): TWorkspace = workspace {
val excludedFirPrecondition = fun(name: String) = !name.endsWith(".fir.kt") && !name.endsWith(".fir.kts")
testGroup("jvm-debugger/test") {
testClass<AbstractKotlinSteppingTest> {
model("stepping/stepIntoAndSmartStepInto", pattern = KT_WITHOUT_DOTS, testMethodName = "doStepIntoTest", testClassName = "StepInto")
model("stepping/stepIntoAndSmartStepInto", pattern = KT_WITHOUT_DOTS, testMethodName = "doSmartStepIntoTest", testClassName = "SmartStepInto")
model("stepping/stepInto", pattern = KT_WITHOUT_DOTS, testMethodName = "doStepIntoTest", testClassName = "StepIntoOnly")
model("stepping/stepOut", pattern = KT_WITHOUT_DOTS, testMethodName = "doStepOutTest")
model("stepping/stepOver", pattern = KT_WITHOUT_DOTS, testMethodName = "doStepOverTest")
model("stepping/filters", pattern = KT_WITHOUT_DOTS, testMethodName = "doStepIntoTest")
model("stepping/custom", pattern = KT_WITHOUT_DOTS, testMethodName = "doCustomTest")
}
testClass<AbstractIrKotlinSteppingTest> {
model("stepping/stepIntoAndSmartStepInto", pattern = KT_WITHOUT_DOTS, testMethodName = "doStepIntoTest", testClassName = "StepInto")
model("stepping/stepIntoAndSmartStepInto", pattern = KT_WITHOUT_DOTS, testMethodName = "doSmartStepIntoTest", testClassName = "SmartStepInto")
model("stepping/stepInto", pattern = KT_WITHOUT_DOTS, testMethodName = "doStepIntoTest", testClassName = "StepIntoOnly")
model("stepping/stepOut", pattern = KT_WITHOUT_DOTS, testMethodName = "doStepOutTest")
model("stepping/stepOver", pattern = KT_WITHOUT_DOTS, testMethodName = "doStepOverTest")
model("stepping/filters", pattern = KT_WITHOUT_DOTS, testMethodName = "doStepIntoTest")
model("stepping/custom", pattern = KT_WITHOUT_DOTS, testMethodName = "doCustomTest")
}
testClass<AbstractKotlinEvaluateExpressionTest> {
model("evaluation/singleBreakpoint", testMethodName = "doSingleBreakpointTest", targetBackend = TargetBackend.JVM_WITH_OLD_EVALUATOR)
model("evaluation/multipleBreakpoints", testMethodName = "doMultipleBreakpointsTest", targetBackend = TargetBackend.JVM_WITH_OLD_EVALUATOR)
}
testClass<AbstractIrKotlinEvaluateExpressionTest> {
model("evaluation/singleBreakpoint", testMethodName = "doSingleBreakpointTest", targetBackend = TargetBackend.JVM_IR_WITH_OLD_EVALUATOR)
model("evaluation/multipleBreakpoints", testMethodName = "doMultipleBreakpointsTest", targetBackend = TargetBackend.JVM_IR_WITH_OLD_EVALUATOR)
}
testClass<AbstractIrKotlinEvaluateExpressionWithIRFragmentCompilerTest> {
model("evaluation/singleBreakpoint", testMethodName = "doSingleBreakpointTest", targetBackend = TargetBackend.JVM_IR_WITH_IR_EVALUATOR)
model("evaluation/multipleBreakpoints", testMethodName = "doMultipleBreakpointsTest", targetBackend = TargetBackend.JVM_IR_WITH_IR_EVALUATOR)
}
testClass<AbstractKotlinEvaluateExpressionInMppTest> {
model("evaluation/singleBreakpoint", testMethodName = "doSingleBreakpointTest", targetBackend = TargetBackend.JVM_IR_WITH_OLD_EVALUATOR)
model("evaluation/multipleBreakpoints", testMethodName = "doMultipleBreakpointsTest", targetBackend = TargetBackend.JVM_IR_WITH_OLD_EVALUATOR)
model("evaluation/multiplatform", testMethodName = "doMultipleBreakpointsTest", targetBackend = TargetBackend.JVM_IR_WITH_IR_EVALUATOR)
}
testClass<AbstractSelectExpressionForDebuggerTestWithAnalysisApi> {
model("selectExpression")
}
testClass<AbstractSelectExpressionForDebuggerTestWithLegacyImplementation> {
model("selectExpression")
}
testClass<AbstractPositionManagerTest> {
model("positionManager", isRecursive = false, pattern = KT, testClassName = "SingleFile")
model("positionManager", isRecursive = false, pattern = DIRECTORY, testClassName = "MultiFile")
}
testClass<AbstractSmartStepIntoTest> {
model("smartStepInto")
}
testClass<AbstractBreakpointApplicabilityTest> {
model("breakpointApplicability")
}
testClass<AbstractFileRankingTest> {
model("fileRanking")
}
testClass<AbstractAsyncStackTraceTest> {
model("asyncStackTrace")
}
testClass<AbstractCoroutineDumpTest> {
model("coroutines")
}
testClass<AbstractSequenceTraceTestCase> { // TODO: implement mapping logic for terminal operations
model("sequence/streams/sequence", excludedDirectories = listOf("terminal"))
}
testClass<AbstractSequenceTraceWithIREvaluatorTestCase> { // TODO: implement mapping logic for terminal operations
model("sequence/streams/sequence", excludedDirectories = listOf("terminal"))
}
testClass<AbstractContinuationStackTraceTest> {
model("continuation")
}
testClass<AbstractKotlinVariablePrintingTest> {
model("variables")
}
testClass<AbstractXCoroutinesStackTraceTest> {
model("xcoroutines")
}
testClass<AbstractClassNameCalculatorTest> {
model("classNameCalculator")
}
testClass<AbstractKotlinExceptionFilterTest> {
model("exceptionFilter", pattern = Patterns.forRegex("""^([^.]+)$"""), isRecursive = false)
}
}
testGroup("copyright/tests") {
testClass<AbstractUpdateKotlinCopyrightTest> {
model("update", pattern = KT_OR_KTS, testMethodName = "doTest")
}
}
testGroup("coverage/tests") {
testClass<AbstractKotlinCoverageOutputFilesTest> {
model("outputFiles")
}
}
testGroup("idea/tests") {
testClass<AbstractAdditionalResolveDescriptorRendererTest> {
model("resolve/additionalLazyResolve")
}
testClass<AbstractPartialBodyResolveTest> {
model("resolve/partialBodyResolve")
}
testClass<AbstractResolveModeComparisonTest> {
model("resolve/resolveModeComparison")
}
testClass<AbstractKotlinHighlightVisitorTest> {
model("checker", isRecursive = false, pattern = KT.withPrecondition(excludedFirPrecondition))
model("checker/regression", pattern = KT.withPrecondition(excludedFirPrecondition))
model("checker/recovery", pattern = KT.withPrecondition(excludedFirPrecondition))
model("checker/rendering", pattern = KT.withPrecondition(excludedFirPrecondition))
model("checker/scripts", pattern = KTS.withPrecondition(excludedFirPrecondition))
model("checker/duplicateJvmSignature", pattern = KT.withPrecondition(excludedFirPrecondition))
model("checker/infos", testMethodName = "doTestWithInfos", pattern = KT.withPrecondition(excludedFirPrecondition))
model("checker/diagnosticsMessage", pattern = KT.withPrecondition(excludedFirPrecondition))
}
testClass<AbstractKotlinHighlightWolfPassTest> {
model("checker/wolf", isRecursive = false, pattern = KT.withPrecondition(excludedFirPrecondition))
}
testClass<AbstractJavaAgainstKotlinSourceCheckerTest> {
model("kotlinAndJavaChecker/javaAgainstKotlin")
model("kotlinAndJavaChecker/javaWithKotlin")
}
testClass<AbstractJavaAgainstKotlinBinariesCheckerTest> {
model("kotlinAndJavaChecker/javaAgainstKotlin")
}
testClass<AbstractPsiUnifierTest> {
model("unifier")
}
testClass<AbstractCodeFragmentHighlightingTest> {
model("checker/codeFragments", pattern = KT, isRecursive = false)
model("checker/codeFragments/imports", testMethodName = "doTestWithImport", pattern = KT)
}
testClass<AbstractCodeFragmentAutoImportTest> {
model("quickfix.special/codeFragmentAutoImport", pattern = KT, isRecursive = false)
}
testClass<AbstractJsCheckerTest> {
model("checker/js")
}
testClass<AbstractK1QuickFixTest> {
model("quickfix", pattern = Patterns.forRegex("^([\\w\\-_]+)\\.kt$"))
}
testClass<AbstractGotoSuperTest> {
model("navigation/gotoSuper", pattern = TEST, isRecursive = false)
}
testClass<AbstractGotoTypeDeclarationTest> {
model("navigation/gotoTypeDeclaration", pattern = TEST)
}
testClass<AbstractGotoDeclarationTest> {
model("navigation/gotoDeclaration", pattern = TEST)
}
testClass<AbstractParameterInfoTest> {
model(
"parameterInfo",
pattern = Patterns.forRegex("^([\\w\\-_]+)\\.kt$"),
isRecursive = true,
excludedDirectories = listOf("withLib1/sharedLib", "withLib2/sharedLib", "withLib3/sharedLib"),
)
}
testClass<AbstractKotlinGotoTest> {
model("navigation/gotoClass", testMethodName = "doClassTest")
model("navigation/gotoSymbol", testMethodName = "doSymbolTest")
}
testClass<AbstractNavigateToLibrarySourceTest> {
model("decompiler/navigation/usercode")
}
testClass<AbstractNavigateJavaToLibrarySourceTest> {
model("decompiler/navigation/userJavaCode", pattern = Patterns.forRegex("^(.+)\\.java$"))
}
testClass<AbstractNavigateToLibrarySourceTestWithJS> {
model("decompiler/navigation/usercode", testClassName = "UsercodeWithJSModule")
}
testClass<AbstractNavigateToDecompiledLibraryTest> {
model("decompiler/navigation/usercode")
}
testClass<AbstractKotlinGotoImplementationTest> {
model("navigation/implementations", isRecursive = false)
}
testClass<AbstractGotoTestOrCodeActionTest> {
model("navigation/gotoTestOrCode", pattern = Patterns.forRegex("^(.+)\\.main\\..+\$"))
}
testClass<AbstractInheritorsSearchTest> {
model("search/inheritance")
}
testClass<AbstractAnnotatedMembersSearchTest> {
model("search/annotations")
}
testClass<AbstractExternalAnnotationTest> {
model("externalAnnotations")
}
testClass<AbstractQuickFixMultiFileTest> {
model("quickfix", pattern = Patterns.forRegex("""^(\w+)\.((before\.Main\.\w+)|(test))$"""), testMethodName = "doTestWithExtraFile")
}
testClass<AbstractKotlinTypeAliasByExpansionShortNameIndexTest> {
model("typealiasExpansionIndex")
}
testClass<AbstractHighlightingTest> {
model("highlighter")
}
testClass<AbstractHighlightingMetaInfoTest> {
model("highlighterMetaInfo")
}
testClass<AbstractDslHighlighterTest> {
model("dslHighlighter")
}
testClass<AbstractUsageHighlightingTest> {
model("usageHighlighter")
}
testClass<AbstractKotlinFoldingTest> {
model("folding/noCollapse")
model("folding/checkCollapse", testMethodName = "doSettingsFoldingTest")
}
testClass<AbstractSurroundWithTest> {
model("codeInsight/surroundWith/if", testMethodName = "doTestWithIfSurrounder")
model("codeInsight/surroundWith/ifElse", testMethodName = "doTestWithIfElseSurrounder")
model("codeInsight/surroundWith/ifElseExpression", testMethodName = "doTestWithIfElseExpressionSurrounder")
model("codeInsight/surroundWith/ifElseExpressionBraces", testMethodName = "doTestWithIfElseExpressionBracesSurrounder")
model("codeInsight/surroundWith/not", testMethodName = "doTestWithNotSurrounder")
model("codeInsight/surroundWith/parentheses", testMethodName = "doTestWithParenthesesSurrounder")
model("codeInsight/surroundWith/stringTemplate", testMethodName = "doTestWithStringTemplateSurrounder")
model("codeInsight/surroundWith/when", testMethodName = "doTestWithWhenSurrounder")
model("codeInsight/surroundWith/tryCatch", testMethodName = "doTestWithTryCatchSurrounder")
model("codeInsight/surroundWith/tryCatchExpression", testMethodName = "doTestWithTryCatchExpressionSurrounder")
model("codeInsight/surroundWith/tryCatchFinally", testMethodName = "doTestWithTryCatchFinallySurrounder")
model("codeInsight/surroundWith/tryCatchFinallyExpression", testMethodName = "doTestWithTryCatchFinallyExpressionSurrounder")
model("codeInsight/surroundWith/tryFinally", testMethodName = "doTestWithTryFinallySurrounder")
model("codeInsight/surroundWith/functionLiteral", testMethodName = "doTestWithFunctionLiteralSurrounder")
model("codeInsight/surroundWith/withIfExpression", testMethodName = "doTestWithSurroundWithIfExpression")
model("codeInsight/surroundWith/withIfElseExpression", testMethodName = "doTestWithSurroundWithIfElseExpression")
}
testClass<AbstractJoinLinesTest> {
model("joinLines")
}
testClass<AbstractBreadcrumbsTest> {
model("codeInsight/breadcrumbs")
}
testClass<AbstractK1IntentionTest> {
model("intentions", pattern = Patterns.forRegex("^([\\w\\-_]+)\\.(kt|kts)$"))
}
testClass<AbstractK1IntentionTest2> {
model("intentions/loopToCallChain", pattern = Patterns.forRegex("^([\\w\\-_]+)\\.kt$"))
}
testClass<AbstractConcatenatedStringGeneratorTest> {
model("concatenatedStringGenerator", pattern = Patterns.forRegex("^([\\w\\-_]+)\\.kt$"))
}
testClass<AbstractInspectionTest> {
model("intentions", pattern = Patterns.forRegex("^(inspections\\.test)$"), flatten = true)
model("inspections", pattern = Patterns.forRegex("^(inspections\\.test)$"), flatten = true)
model("inspectionsLocal", pattern = Patterns.forRegex("^(inspections\\.test)$"), flatten = true)
}
testClass<AbstractLocalInspectionTest> {
model(
"inspectionsLocal", pattern = Patterns.forRegex("^([\\w\\-_]+)\\.(kt|kts)$"),
// In FE1.0, this is a quickfix rather than a local inspection
excludedDirectories = listOf("unusedVariable")
)
}
testClass<AbstractViewOfflineInspectionTest> {
model("inspectionsLocal", pattern = Patterns.forRegex("^([\\w\\-_]+)_report\\.(xml)$"))
}
testClass<AbstractHierarchyTest> {
model("hierarchy/class/type", pattern = DIRECTORY, isRecursive = false, testMethodName = "doTypeClassHierarchyTest")
model("hierarchy/class/super", pattern = DIRECTORY, isRecursive = false, testMethodName = "doSuperClassHierarchyTest")
model("hierarchy/class/sub", pattern = DIRECTORY, isRecursive = false, testMethodName = "doSubClassHierarchyTest")
model("hierarchy/calls/callers", pattern = DIRECTORY, isRecursive = false, testMethodName = "doCallerHierarchyTest")
model("hierarchy/calls/callersJava", pattern = DIRECTORY, isRecursive = false, testMethodName = "doCallerJavaHierarchyTest")
model("hierarchy/calls/callees", pattern = DIRECTORY, isRecursive = false, testMethodName = "doCalleeHierarchyTest")
model("hierarchy/overrides", pattern = DIRECTORY, isRecursive = false, testMethodName = "doOverrideHierarchyTest")
}
testClass<AbstractHierarchyWithLibTest> {
model("hierarchy/withLib", pattern = DIRECTORY, isRecursive = false)
}
testClass<AbstractMoveStatementTest> {
model("codeInsight/moveUpDown/classBodyDeclarations", pattern = KT_OR_KTS, testMethodName = "doTestClassBodyDeclaration")
model("codeInsight/moveUpDown/closingBraces", testMethodName = "doTestExpression")
model("codeInsight/moveUpDown/expressions", pattern = KT_OR_KTS, testMethodName = "doTestExpression")
model("codeInsight/moveUpDown/line", testMethodName = "doTestLine")
model("codeInsight/moveUpDown/parametersAndArguments", testMethodName = "doTestExpression")
model("codeInsight/moveUpDown/trailingComma", testMethodName = "doTestExpressionWithTrailingComma")
}
testClass<AbstractMoveLeftRightTest> {
model("codeInsight/moveLeftRight")
}
testClass<AbstractInlineTest> {
model("refactoring/inline", pattern = KT_WITHOUT_DOTS, excludedDirectories = listOf("withFullJdk"))
}
testClass<AbstractInlineTestWithSomeDescriptors> {
model("refactoring/inline/withFullJdk", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractInlineMultiFileTest> {
model("refactoring/inlineMultiFile", pattern = TEST, flatten = true)
}
testClass<AbstractUnwrapRemoveTest> {
model("codeInsight/unwrapAndRemove/removeExpression", testMethodName = "doTestExpressionRemover")
model("codeInsight/unwrapAndRemove/unwrapThen", testMethodName = "doTestThenUnwrapper")
model("codeInsight/unwrapAndRemove/unwrapElse", testMethodName = "doTestElseUnwrapper")
model("codeInsight/unwrapAndRemove/removeElse", testMethodName = "doTestElseRemover")
model("codeInsight/unwrapAndRemove/unwrapLoop", testMethodName = "doTestLoopUnwrapper")
model("codeInsight/unwrapAndRemove/unwrapTry", testMethodName = "doTestTryUnwrapper")
model("codeInsight/unwrapAndRemove/unwrapCatch", testMethodName = "doTestCatchUnwrapper")
model("codeInsight/unwrapAndRemove/removeCatch", testMethodName = "doTestCatchRemover")
model("codeInsight/unwrapAndRemove/unwrapFinally", testMethodName = "doTestFinallyUnwrapper")
model("codeInsight/unwrapAndRemove/removeFinally", testMethodName = "doTestFinallyRemover")
model("codeInsight/unwrapAndRemove/unwrapLambda", testMethodName = "doTestLambdaUnwrapper")
model("codeInsight/unwrapAndRemove/unwrapFunctionParameter", testMethodName = "doTestFunctionParameterUnwrapper")
}
testClass<AbstractExpressionTypeTest> {
model("codeInsight/expressionType")
}
testClass<AbstractRenderingKDocTest> {
model("codeInsight/renderingKDoc")
}
testClass<AbstractBackspaceHandlerTest> {
model("editor/backspaceHandler")
}
testClass<AbstractQuickDocProviderTest> {
model("editor/quickDoc", pattern = Patterns.forRegex("""^([^_]+)\.(kt|java)$"""))
}
testClass<AbstractSafeDeleteTest> {
model("refactoring/safeDelete/deleteClass/kotlinClass", testMethodName = "doClassTest")
model("refactoring/safeDelete/deleteClass/kotlinClassWithJava", testMethodName = "doClassTestWithJava")
model("refactoring/safeDelete/deleteClass/javaClassWithKotlin", pattern = JAVA, testMethodName = "doJavaClassTest")
model("refactoring/safeDelete/deleteObject/kotlinObject", testMethodName = "doObjectTest")
model("refactoring/safeDelete/deleteFunction/kotlinFunction", testMethodName = "doFunctionTest")
model("refactoring/safeDelete/deleteFunction/kotlinFunctionWithJava", testMethodName = "doFunctionTestWithJava")
model("refactoring/safeDelete/deleteFunction/javaFunctionWithKotlin", testMethodName = "doJavaMethodTest")
model("refactoring/safeDelete/deleteProperty/kotlinProperty", testMethodName = "doPropertyTest")
model("refactoring/safeDelete/deleteProperty/kotlinPropertyWithJava", testMethodName = "doPropertyTestWithJava")
model("refactoring/safeDelete/deleteProperty/javaPropertyWithKotlin", testMethodName = "doJavaPropertyTest")
model("refactoring/safeDelete/deleteTypeAlias/kotlinTypeAlias", testMethodName = "doTypeAliasTest")
model("refactoring/safeDelete/deleteTypeParameter/kotlinTypeParameter", testMethodName = "doTypeParameterTest")
model("refactoring/safeDelete/deleteTypeParameter/kotlinTypeParameterWithJava", testMethodName = "doTypeParameterTestWithJava")
model("refactoring/safeDelete/deleteValueParameter/kotlinValueParameter", testMethodName = "doValueParameterTest")
model("refactoring/safeDelete/deleteValueParameter/kotlinValueParameterWithJava", testMethodName = "doValueParameterTestWithJava")
model("refactoring/safeDelete/deleteValueParameter/javaParameterWithKotlin", pattern = JAVA, testMethodName = "doJavaParameterTest")
}
testClass<AbstractReferenceResolveTest> {
model("resolve/references", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractReferenceResolveInJavaTest> {
model("resolve/referenceInJava/binaryAndSource", pattern = JAVA)
model("resolve/referenceInJava/sourceOnly", pattern = JAVA)
}
testClass<AbstractReferenceToCompiledKotlinResolveInJavaTest> {
model("resolve/referenceInJava/binaryAndSource", pattern = JAVA)
}
testClass<AbstractReferenceResolveWithLibTest> {
model("resolve/referenceWithLib", isRecursive = false)
}
testClass<AbstractReferenceResolveInLibrarySourcesTest> {
model("resolve/referenceInLib", isRecursive = false)
}
testClass<AbstractReferenceToJavaWithWrongFileStructureTest> {
model("resolve/referenceToJavaWithWrongFileStructure", isRecursive = false)
}
testClass<AbstractFindUsagesTest> {
model("findUsages/kotlin", pattern = Patterns.forRegex("""^(.+)\.0\.kt$"""))
model("findUsages/java", pattern = Patterns.forRegex("""^(.+)\.0\.java$"""))
model("findUsages/propertyFiles", pattern = Patterns.forRegex("""^(.+)\.0\.properties$"""))
}
testClass<AbstractKotlinScriptFindUsagesTest> {
model("findUsages/kotlinScript", pattern = Patterns.forRegex("""^(.+)\.0\.kts$"""))
}
testClass<AbstractFindUsagesWithDisableComponentSearchTest> {
model("findUsages/kotlin/conventions/components", pattern = Patterns.forRegex("""^(.+)\.0\.(kt|kts)$"""))
}
testClass<AbstractKotlinFindUsagesWithLibraryTest> {
model("findUsages/libraryUsages", pattern = Patterns.forRegex("""^(.+)\.0\.kt$"""))
}
testClass<AbstractKotlinFindUsagesWithStdlibTest> {
model("findUsages/stdlibUsages", pattern = Patterns.forRegex("""^(.+)\.0\.kt$"""))
}
testClass<AbstractKotlinGroupUsagesBySimilarityTest> {
model("findUsages/similarity/grouping", pattern = KT)
}
testClass<AbstractKotlinGroupUsagesBySimilarityFeaturesTest> {
model("findUsages/similarity/features", pattern = KT)
}
testClass<AbstractMoveTest> {
model("refactoring/move", pattern = TEST, flatten = true)
}
testClass<AbstractCopyTest> {
model("refactoring/copy", pattern = TEST, flatten = true)
}
testClass<AbstractMultiModuleMoveTest> {
model("refactoring/moveMultiModule", pattern = TEST, flatten = true)
}
testClass<AbstractMultiModuleCopyTest> {
model("refactoring/copyMultiModule", pattern = TEST, flatten = true)
}
testClass<AbstractMultiModuleSafeDeleteTest> {
model("refactoring/safeDeleteMultiModule", pattern = TEST, flatten = true)
}
testClass<AbstractMultiFileIntentionTest> {
model("multiFileIntentions", pattern = TEST, flatten = true)
}
testClass<AbstractMultiFileLocalInspectionTest> {
model("multiFileLocalInspections", pattern = TEST, flatten = true)
}
testClass<AbstractMultiFileInspectionTest> {
model("multiFileInspections", pattern = TEST, flatten = true)
}
testClass<AbstractFormatterTest> {
model("formatter", pattern = Patterns.forRegex("""^([^.]+)\.after\.kt.*$"""))
model("formatter/trailingComma", pattern = Patterns.forRegex("""^([^.]+)\.call\.after\.kt.*$"""), testMethodName = "doTestCallSite", testClassName = "FormatterCallSite")
model("formatter", pattern = Patterns.forRegex("""^([^.]+)\.after\.inv\.kt.*$"""), testMethodName = "doTestInverted", testClassName = "FormatterInverted")
model(
"formatter/trailingComma",
pattern = Patterns.forRegex("""^([^.]+)\.call\.after\.inv\.kt.*$"""),
testMethodName = "doTestInvertedCallSite",
testClassName = "FormatterInvertedCallSite",
)
}
testClass<AbstractDiagnosticMessageTest> {
model("diagnosticMessage", isRecursive = false)
}
testClass<AbstractDiagnosticMessageJsTest> {
model("diagnosticMessage/js", isRecursive = false, targetBackend = TargetBackend.JS)
}
testClass<AbstractRenameTest> {
model("refactoring/rename", pattern = TEST, flatten = true)
}
testClass<AbstractMultiModuleRenameTest> {
model("refactoring/renameMultiModule", pattern = TEST, flatten = true)
}
testClass<AbstractOutOfBlockModificationTest> {
model("codeInsight/outOfBlock", pattern = Patterns.forRegex("^(.+)\\.(kt|kts|java)$"))
}
testClass<AbstractChangeLocalityDetectorTest> {
model("codeInsight/changeLocality", pattern = KT_OR_KTS)
}
testClass<AbstractDataFlowValueRenderingTest> {
model("dataFlowValueRendering")
}
testClass<AbstractLiteralTextToKotlinCopyPasteTest> {
model("copyPaste/plainTextLiteral", pattern = Patterns.forRegex("""^([^.]+)\.txt$"""))
}
testClass<AbstractLiteralKotlinToKotlinCopyPasteTest> {
model("copyPaste/literal", pattern = Patterns.forRegex("""^([^.]+)\.kt$"""))
}
testClass<AbstractInsertImportOnPasteTest> {
model("copyPaste/imports", pattern = KT_WITHOUT_DOTS, testMethodName = "doTestCopy", testClassName = "Copy", isRecursive = false)
model("copyPaste/imports", pattern = KT_WITHOUT_DOTS, testMethodName = "doTestCut", testClassName = "Cut", isRecursive = false)
}
testClass<AbstractMoveOnCutPasteTest> {
model("copyPaste/moveDeclarations", pattern = KT_WITHOUT_DOTS, testMethodName = "doTest")
}
testClass<AbstractHighlightExitPointsTest> {
model("exitPoints")
}
testClass<AbstractLineMarkersTest> {
model("codeInsight/lineMarker", pattern = Patterns.forRegex("^(\\w+)\\.(kt|kts)$"))
}
testClass<AbstractLightTestRunLineMarkersTest> {
model("codeInsight/lineMarker/runMarkers", pattern = Patterns.forRegex("^((jUnit|test)\\w*)\\.kt$"), testMethodName = "doLightTest", testClassName = "WithLightTestFramework")
model("codeInsight/lineMarker/runMarkers", pattern = Patterns.forRegex("^((jUnit|test)\\w*)\\.kt$"), testMethodName = "doPureTest", testClassName = "WithoutLightTestFramework")
}
testClass<AbstractLineMarkersTestInLibrarySources> {
model("codeInsightInLibrary/lineMarker", testMethodName = "doTestWithLibrary")
}
testClass<AbstractMultiModuleLineMarkerTest> {
model("multiModuleLineMarker", pattern = DIRECTORY, isRecursive = false)
}
testClass<AbstractShortenRefsTest> {
model("shortenRefs", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractAddImportTest> {
model("addImport", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractAddImportAliasTest53> {
model("addImportAlias", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractSmartSelectionTest> {
model("smartSelection", testMethodName = "doTestSmartSelection", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractWorkSelectionTest> {
model("wordSelection", pattern = DIRECTORY)
}
testClass<AbstractKotlinFileStructureTest> {
model("structureView/fileStructure", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractExpressionSelectionTest> {
model("expressionSelection", testMethodName = "doTestExpressionSelection", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractCommonDecompiledTextTest> {
model("decompiler/decompiledText", pattern = Patterns.forRegex("""^([^\.]+)$"""))
}
testClass<AbstractJvmDecompiledTextTest> {
model("decompiler/decompiledTextJvm", pattern = Patterns.forRegex("""^([^\.]+)$"""))
}
testClass<AbstractCommonDecompiledTextFromJsMetadataTest> {
model("decompiler/decompiledText", pattern = Patterns.forRegex("""^([^\.]+)$"""), targetBackend = TargetBackend.JS)
}
testClass<AbstractJsDecompiledTextFromJsMetadataTest> {
model("decompiler/decompiledTextJs", pattern = Patterns.forRegex("""^([^\.]+)$"""), targetBackend = TargetBackend.JS)
}
testClass<AbstractAutoImportTest> {
model("editor/autoImport", testMethodName = "doTest", testClassName = "WithAutoImport", pattern = DIRECTORY, isRecursive = false)
model("editor/autoImport", testMethodName = "doTestWithoutAutoImport", testClassName = "WithoutAutoImport", pattern = DIRECTORY, isRecursive = false)
}
testClass<AbstractFilteringAutoImportTest> {
model("editor/autoImportExtension", testMethodName = "doTest", testClassName = "WithAutoImport", pattern = DIRECTORY, isRecursive = false)
model("editor/autoImportExtension", testMethodName = "doTestWithoutAutoImport", testClassName = "WithoutAutoImport", pattern = DIRECTORY, isRecursive = false)
}
testClass<AbstractJvmOptimizeImportsTest> {
model("editor/optimizeImports/jvm", pattern = KT_OR_KTS_WITHOUT_DOTS)
model("editor/optimizeImports/common", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractJsOptimizeImportsTest> {
model("editor/optimizeImports/js", pattern = KT_WITHOUT_DOTS)
model("editor/optimizeImports/common", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractEnterHandlerTest> {
model("editor/enterHandler", pattern = Patterns.forRegex("""^([^.]+)\.after\.kt.*$"""), testMethodName = "doNewlineTest", testClassName = "DirectSettings")
model("editor/enterHandler", pattern = Patterns.forRegex("""^([^.]+)\.after\.inv\.kt.*$"""), testMethodName = "doNewlineTestWithInvert", testClassName = "InvertedSettings")
}
testClass<AbstractKotlinCommenterTest> {
model("editor/commenter", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractStubBuilderTest> {
model("stubs", pattern = KT)
}
testClass<AbstractMultiFileHighlightingTest> {
model("multiFileHighlighting", isRecursive = false)
}
testClass<AbstractMultiPlatformHighlightingTest> {
model("multiModuleHighlighting/multiplatform/", isRecursive = false, pattern = DIRECTORY)
}
testClass<AbstractMultiplatformAnalysisTest> {
model("multiplatform", isRecursive = false, pattern = DIRECTORY)
}
testClass<AbstractQuickFixMultiModuleTest> {
model("multiModuleQuickFix", pattern = DIRECTORY, depth = 1)
}
testClass<AbstractKotlinGotoImplementationMultiModuleTest> {
model("navigation/implementations/multiModule", isRecursive = false, pattern = DIRECTORY)
}
testClass<AbstractKotlinGotoRelatedSymbolMultiModuleTest> {
model("navigation/relatedSymbols/multiModule", isRecursive = false, pattern = DIRECTORY)
}
testClass<AbstractKotlinGotoSuperMultiModuleTest> {
model("navigation/gotoSuper/multiModule", isRecursive = false, pattern = DIRECTORY)
}
testClass<AbstractExtractionTest> {
model("refactoring/introduceVariable", pattern = KT_OR_KTS, testMethodName = "doIntroduceVariableTest")
model("refactoring/extractFunction", pattern = KT_OR_KTS, testMethodName = "doExtractFunctionTest", excludedDirectories = listOf("inplace"))
model("refactoring/introduceProperty", pattern = KT_OR_KTS, testMethodName = "doIntroducePropertyTest")
model("refactoring/introduceParameter", pattern = KT_OR_KTS, testMethodName = "doIntroduceSimpleParameterTest")
model("refactoring/introduceLambdaParameter", pattern = KT_OR_KTS, testMethodName = "doIntroduceLambdaParameterTest")
model("refactoring/introduceJavaParameter", pattern = JAVA, testMethodName = "doIntroduceJavaParameterTest")
model("refactoring/introduceTypeParameter", pattern = KT_OR_KTS, testMethodName = "doIntroduceTypeParameterTest")
model("refactoring/introduceTypeAlias", pattern = KT_OR_KTS, testMethodName = "doIntroduceTypeAliasTest")
model("refactoring/introduceConstant", pattern = KT_OR_KTS, testMethodName = "doIntroduceConstantTest")
model("refactoring/extractSuperclass", pattern = KT_OR_KTS_WITHOUT_DOTS, testMethodName = "doExtractSuperclassTest")
model("refactoring/extractInterface", pattern = KT_OR_KTS_WITHOUT_DOTS, testMethodName = "doExtractInterfaceTest")
}
testClass<AbstractPullUpTest> {
model("refactoring/pullUp/k2k", pattern = KT, flatten = true, testClassName = "K2K", testMethodName = "doKotlinTest")
model("refactoring/pullUp/k2j", pattern = KT, flatten = true, testClassName = "K2J", testMethodName = "doKotlinTest")
model("refactoring/pullUp/j2k", pattern = JAVA, flatten = true, testClassName = "J2K", testMethodName = "doJavaTest")
}
testClass<AbstractPushDownTest> {
model("refactoring/pushDown/k2k", pattern = KT, flatten = true, testClassName = "K2K", testMethodName = "doKotlinTest")
model("refactoring/pushDown/k2j", pattern = KT, flatten = true, testClassName = "K2J", testMethodName = "doKotlinTest")
model("refactoring/pushDown/j2k", pattern = JAVA, flatten = true, testClassName = "J2K", testMethodName = "doJavaTest")
}
testClass<AbstractBytecodeToolWindowTest> {
model("internal/toolWindow", isRecursive = false, pattern = DIRECTORY)
}
testClass<AbstractReferenceResolveTest>("org.jetbrains.kotlin.idea.kdoc.KdocResolveTestGenerated") {
model("kdoc/resolve")
}
testClass<AbstractKDocHighlightingTest> {
model("kdoc/highlighting")
}
testClass<AbstractKDocTypingTest> {
model("kdoc/typing")
}
testClass<AbstractGenerateTestSupportMethodActionTest> {
model("codeInsight/generate/testFrameworkSupport")
}
testClass<AbstractGenerateHashCodeAndEqualsActionTest> {
model("codeInsight/generate/equalsWithHashCode")
}
testClass<AbstractCodeInsightActionTest> {
model("codeInsight/generate/secondaryConstructors")
}
testClass<AbstractGenerateToStringActionTest> {
model("codeInsight/generate/toString")
}
testClass<AbstractIdeReplCompletionTest> {
model("repl/completion")
}
testClass<AbstractPostfixTemplateProviderTest> {
model("codeInsight/postfix")
}
testClass<AbstractKotlinArgumentsHintsProviderTest> {
model("codeInsight/hints/arguments")
}
testClass<AbstractKotlinReferenceTypeHintsProviderTest> {
model("codeInsight/hints/types")
}
testClass<AbstractKotlinLambdasHintsProvider> {
model("codeInsight/hints/lambda")
}
testClass<AbstractKotlinRangesHintsProviderTest> {
model("codeInsight/hints/ranges")
}
testClass<AbstractKotlinCodeVisionProviderTest> {
model("codeInsight/codeVision")
}
testClass<AbstractScriptConfigurationHighlightingTest> {
model("script/definition/highlighting", pattern = DIRECTORY, isRecursive = false)
model("script/definition/complex", pattern = DIRECTORY, isRecursive = false, testMethodName = "doComplexTest")
}
testClass<AbstractScriptConfigurationNavigationTest> {
model("script/definition/navigation", pattern = DIRECTORY, isRecursive = false)
}
testClass<AbstractScriptConfigurationCompletionTest> {
model("script/definition/completion", pattern = DIRECTORY, isRecursive = false)
}
testClass<AbstractScriptConfigurationInsertImportOnPasteTest> {
model("script/definition/imports", testMethodName = "doTestCopy", testClassName = "Copy", pattern = DIRECTORY, isRecursive = false)
model("script/definition/imports", testMethodName = "doTestCut", testClassName = "Cut", pattern = DIRECTORY, isRecursive = false)
}
testClass<AbstractScriptDefinitionsOrderTest> {
model("script/definition/order", pattern = DIRECTORY, isRecursive = false)
}
testClass<AbstractNameSuggestionProviderTest> {
model("refactoring/nameSuggestionProvider")
}
testClass<AbstractSlicerTreeTest> {
model("slicer", excludedDirectories = listOf("mpp"))
}
testClass<AbstractSlicerLeafGroupingTest> {
model("slicer/inflow", flatten = true)
}
testClass<AbstractSlicerNullnessGroupingTest> {
model("slicer/inflow", flatten = true)
}
testClass<AbstractSlicerMultiplatformTest> {
model("slicer/mpp", isRecursive = false, pattern = DIRECTORY)
}
testClass<AbstractKotlinNavBarTest> {
model("navigationToolbar", isRecursive = false)
}
}
testGroup("scripting-support") {
testClass<AbstractScratchRunActionTest> {
model("scratch", pattern = KTS, testMethodName = "doScratchCompilingTest", testClassName = "ScratchCompiling", isRecursive = false)
model("scratch", pattern = KTS, testMethodName = "doScratchReplTest", testClassName = "ScratchRepl", isRecursive = false)
model("scratch/multiFile", pattern = DIRECTORY, testMethodName = "doScratchMultiFileTest", testClassName = "ScratchMultiFile", isRecursive = false)
model("worksheet", pattern = WS_KTS, testMethodName = "doWorksheetCompilingTest", testClassName = "WorksheetCompiling", isRecursive = false)
model("worksheet", pattern = WS_KTS, testMethodName = "doWorksheetReplTest", testClassName = "WorksheetRepl", isRecursive = false)
model("worksheet/multiFile", pattern = DIRECTORY, testMethodName = "doWorksheetMultiFileTest", testClassName = "WorksheetMultiFile", isRecursive = false)
model("scratch/rightPanelOutput", pattern = KTS, testMethodName = "doRightPreviewPanelOutputTest", testClassName = "ScratchRightPanelOutput", isRecursive = false)
}
testClass<AbstractScratchLineMarkersTest> {
model("scratch/lineMarker", testMethodName = "doScratchTest", pattern = KT_OR_KTS)
}
testClass<AbstractScriptTemplatesFromDependenciesTest> {
model("script/templatesFromDependencies", pattern = DIRECTORY, isRecursive = false)
}
}
testGroup("maven/tests") {
testClass<AbstractMavenConfigureProjectByChangingFileTest> {
model("configurator/jvm", pattern = DIRECTORY, isRecursive = false, testMethodName = "doTestWithMaven")
model("configurator/js", pattern = DIRECTORY, isRecursive = false, testMethodName = "doTestWithJSMaven")
}
testClass<AbstractKotlinMavenInspectionTest> {
val mavenInspections = "maven-inspections"
val pattern = Patterns.forRegex("^([\\w\\-]+).xml$")
testDataRoot.resolve(mavenInspections).listFiles()!!.onEach { check(it.isDirectory) }.sorted().forEach {
model("$mavenInspections/${it.name}", pattern = pattern, flatten = true)
}
}
}
testGroup("gradle/gradle-java/tests", testDataPath = "../../../idea/tests/testData") {
testClass<AbstractGradleConfigureProjectByChangingFileTest> {
model("configuration/gradle", pattern = DIRECTORY, isRecursive = false, testMethodName = "doTestGradle")
model("configuration/gsk", pattern = DIRECTORY, isRecursive = false, testMethodName = "doTestGradle")
}
}
testGroup("idea/tests", testDataPath = TestKotlinArtifacts.compilerTestData("compiler/testData")) {
testClass<AbstractResolveByStubTest> {
model("loadJava/compiledKotlin")
}
testClass<AbstractLoadJavaClsStubTest> {
model("loadJava/compiledKotlin", testMethodName = "doTestCompiledKotlin")
}
testClass<AbstractIdeLightClassTest> {
model("asJava/lightClasses", excludedDirectories = listOf("delegation", "script"), pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractIdeLightClassForScriptTest> {
model("asJava/script/ide", pattern = KT_OR_KTS_WITHOUT_DOTS)
}
testClass<AbstractUltraLightClassSanityTest> {
model("asJava/lightClasses", pattern = KT_OR_KTS)
}
testClass<AbstractUltraLightClassLoadingTest> {
model("asJava/ultraLightClasses", pattern = KT_OR_KTS)
}
testClass<AbstractUltraLightScriptLoadingTest> {
model("asJava/ultraLightScripts", pattern = KT_OR_KTS)
}
testClass<AbstractUltraLightFacadeClassTest15> {
model("asJava/ultraLightFacades", pattern = KT_OR_KTS)
}
testClass<AbstractIdeCompiledLightClassTest> {
model("asJava/lightClasses", excludedDirectories = listOf("local", "compilationErrors", "ideRegression", "script"), pattern = KT_OR_KTS_WITHOUT_DOTS)
}
}
testGroup("compiler-plugins/parcelize/tests") {
testClass<AbstractParcelizeQuickFixTest> {
model("quickfix", pattern = Patterns.forRegex("^([\\w\\-_]+)\\.kt$"))
}
testClass<AbstractParcelizeCheckerTest> {
model("checker", pattern = KT)
}
}
testGroup("completion/tests-k1", testDataPath = "../testData") {
testClass<AbstractCompiledKotlinInJavaCompletionTest> {
model("injava", pattern = JAVA, isRecursive = false)
}
testClass<AbstractKotlinSourceInJavaCompletionTest> {
model("injava", pattern = JAVA, isRecursive = false)
}
testClass<AbstractKotlinStdLibInJavaCompletionTest> {
model("injava/stdlib", pattern = JAVA, isRecursive = false)
}
testClass<AbstractBasicCompletionWeigherTest> {
model("weighers/basic", pattern = KT_OR_KTS_WITHOUT_DOTS)
}
testClass<AbstractSmartCompletionWeigherTest> {
model("weighers/smart", pattern = KT_OR_KTS_WITHOUT_DOTS)
}
testClass<AbstractJSBasicCompletionTest> {
model("basic/common", pattern = KT_WITHOUT_FIR_PREFIX)
model("basic/js", pattern = KT_WITHOUT_FIR_PREFIX)
}
testClass<AbstractJvmBasicCompletionTest> {
model("basic/common", pattern = KT_WITHOUT_FIR_PREFIX)
model("basic/java", pattern = KT_WITHOUT_FIR_PREFIX)
}
testClass<AbstractJvmSmartCompletionTest> {
model("smart")
}
testClass<AbstractKeywordCompletionTest> {
model("keywords", isRecursive = false, pattern = KT.withPrecondition(excludedFirPrecondition))
}
testClass<AbstractJvmWithLibBasicCompletionTest> {
model("basic/withLib", isRecursive = false)
}
testClass<AbstractBasicCompletionHandlerTest> {
model("handlers/basic", pattern = KT_WITHOUT_DOT_AND_FIR_PREFIX)
}
testClass<AbstractSmartCompletionHandlerTest> {
model("handlers/smart", pattern = KT_WITHOUT_FIR_PREFIX)
}
testClass<AbstractKeywordCompletionHandlerTest> {
model("handlers/keywords", pattern = KT_WITHOUT_FIR_PREFIX)
}
testClass<AbstractJavaCompletionHandlerTest> {
model("handlers/injava", pattern = JAVA)
}
testClass<AbstractCompletionCharFilterTest> {
model("handlers/charFilter", pattern = KT_WITHOUT_DOT_AND_FIR_PREFIX)
}
testClass<AbstractMultiFileJvmBasicCompletionTest> {
model("basic/multifile", pattern = DIRECTORY, isRecursive = false)
}
testClass<AbstractMultiFileSmartCompletionTest> {
model("smartMultiFile", pattern = DIRECTORY, isRecursive = false)
}
testClass<AbstractJvmBasicCompletionTest>("org.jetbrains.kotlin.idea.completion.test.KDocCompletionTestGenerated") {
model("kdoc")
}
testClass<AbstractJava8BasicCompletionTest> {
model("basic/java8")
}
testClass<AbstractCompletionIncrementalResolveTest31> {
model("incrementalResolve")
}
testClass<AbstractMultiPlatformCompletionTest> {
model("multiPlatform", isRecursive = false, pattern = DIRECTORY)
}
}
testGroup("project-wizard/tests") {
fun MutableTSuite.allBuildSystemTests(relativeRootPath: String) {
for (testClass in listOf("GradleKts", "GradleGroovy", "Maven")) {
model(
relativeRootPath,
isRecursive = false,
pattern = DIRECTORY,
testMethodName = "doTest${testClass}",
testClassName = testClass,
)
}
}
testClass<AbstractYamlBuildFileGenerationTest> {
model("buildFileGeneration", isRecursive = false, pattern = DIRECTORY)
}
testClass<AbstractProjectTemplateBuildFileGenerationTest> {
model("projectTemplatesBuildFileGeneration", isRecursive = false, pattern = DIRECTORY)
}
testClass<AbstractYamlNewWizardProjectImportTest> {
allBuildSystemTests("buildFileGeneration")
}
testClass<AbstractProjectTemplateNewWizardProjectImportTest> {
allBuildSystemTests("projectTemplatesBuildFileGeneration")
}
}
testGroup("idea/tests", testDataPath = "../../completion/testData") {
testClass<AbstractCodeFragmentCompletionHandlerTest> {
model("handlers/runtimeCast")
}
testClass<AbstractCodeFragmentCompletionTest> {
model("basic/codeFragments", pattern = KT)
}
}
testGroup("j2k/new/tests") {
testClass<AbstractNewJavaToKotlinConverterSingleFileTest> {
model("newJ2k", pattern = Patterns.forRegex("""^([^.]+)\.java$"""))
}
testClass<AbstractPartialConverterTest> {
model("partialConverter", pattern = Patterns.forRegex("""^([^.]+)\.java$"""))
}
testClass<AbstractCommonConstraintCollectorTest> {
model("inference/common")
}
testClass<AbstractNullabilityInferenceTest> {
model("inference/nullability")
}
testClass<AbstractMutabilityInferenceTest> {
model("inference/mutability")
}
testClass<AbstractNewJavaToKotlinCopyPasteConversionTest> {
model("copyPaste", pattern = Patterns.forRegex("""^([^.]+)\.java$"""))
}
testClass<AbstractTextNewJavaToKotlinCopyPasteConversionTest> {
model("copyPastePlainText", pattern = Patterns.forRegex("""^([^.]+)\.txt$"""))
}
testClass<AbstractNewJavaToKotlinConverterMultiFileTest> {
model("multiFile", pattern = DIRECTORY, isRecursive = false)
}
}
testGroup("compiler-reference-index/tests") {
testClass<AbstractKotlinCompilerReferenceTest> {
model("compilerIndex", pattern = DIRECTORY, classPerTest = true)
}
}
testGroup("compiler-reference-index/tests", testDataPath = "../../idea/tests/testData") {
testClass<AbstractFindUsagesWithCompilerReferenceIndexTest> {
model("findUsages/kotlin", pattern = Patterns.forRegex("""^(.+)\.0\.kt$"""), classPerTest = true)
model("findUsages/java", pattern = Patterns.forRegex("""^(.+)\.0\.java$"""), classPerTest = true)
model("findUsages/propertyFiles", pattern = Patterns.forRegex("""^(.+)\.0\.properties$"""), classPerTest = true)
}
}
testGroup("compiler-plugins/kotlinx-serialization/tests") {
testClass<AbstractSerializationPluginIdeDiagnosticTest> {
model("diagnostics")
}
testClass<AbstractSerializationQuickFixTest> {
model("quickfix", pattern = Patterns.forRegex("^([\\w\\-_]+)\\.kt$"))
}
}
testGroup("uast/uast-kotlin/tests", testDataPath = "../../uast-kotlin-fir/testData") {
testClass<AbstractFE1UastDeclarationTest> {
model("declaration")
}
testClass<AbstractFE1UastTypesTest> {
model("type")
}
testClass<AbstractFE1UastValuesTest> {
model("value")
}
}
testGroup("uast/uast-kotlin/tests") {
testClass<AbstractFE1LegacyUastDeclarationTest> {
model("")
}
testClass<AbstractFE1LegacyUastIdentifiersTest> {
model("")
}
testClass<AbstractFE1LegacyUastResolveEverythingTest> {
model("")
}
testClass<AbstractFE1LegacyUastTypesTest> {
model("")
}
testClass<AbstractFE1LegacyUastValuesTest> {
model("")
}
}
testGroup("performance-tests", testDataPath = "../idea/tests/testData") {
testClass<AbstractPerformanceJavaToKotlinCopyPasteConversionTest> {
model("copyPaste/conversion", testMethodName = "doPerfTest", pattern = Patterns.forRegex("""^([^.]+)\.java$"""))
}
testClass<AbstractPerformanceNewJavaToKotlinCopyPasteConversionTest> {
model("copyPaste/conversion", testMethodName = "doPerfTest", pattern = Patterns.forRegex("""^([^.]+)\.java$"""))
}
testClass<AbstractPerformanceLiteralKotlinToKotlinCopyPasteTest> {
model("copyPaste/literal", testMethodName = "doPerfTest", pattern = Patterns.forRegex("""^([^.]+)\.kt$"""))
}
testClass<AbstractPerformanceHighlightingTest> {
model("highlighter", testMethodName = "doPerfTest")
}
testClass<AbstractPerformanceHighlightingStatNamesTest> {
model("highlighter", testMethodName = "doPerfTest", pattern = Patterns.forRegex("""^(InvokeCall)\.kt$"""))
}
testClass<AbstractPerformanceAddImportTest> {
model("addImport", testMethodName = "doPerfTest", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractPerformanceTypingIndentationTest> {
model("editor/enterHandler", pattern = Patterns.forRegex("""^([^.]+)\.after\.kt.*$"""), testMethodName = "doNewlineTest", testClassName = "DirectSettings")
model("editor/enterHandler", pattern = Patterns.forRegex("""^([^.]+)\.after\.inv\.kt.*$"""), testMethodName = "doNewlineTestWithInvert", testClassName = "InvertedSettings")
}
}
testGroup("performance-tests", testDataPath = "../completion/testData") {
testClass<AbstractPerformanceCompletionIncrementalResolveTest> {
model("incrementalResolve", testMethodName = "doPerfTest")
}
testClass<AbstractPerformanceBasicCompletionHandlerTest> {
model("handlers/basic", testMethodName = "doPerfTest", pattern = KT_WITHOUT_DOTS)
}
testClass<AbstractPerformanceBasicCompletionHandlerStatNamesTest> {
model("handlers/basic", testMethodName = "doPerfTest", pattern = Patterns.forRegex("""^(GetOperator)\.kt$"""))
}
testClass<AbstractPerformanceSmartCompletionHandlerTest> {
model("handlers/smart", testMethodName = "doPerfTest")
}
testClass<AbstractPerformanceKeywordCompletionHandlerTest> {
model("handlers/keywords", testMethodName = "doPerfTest")
}
testClass<AbstractPerformanceCompletionCharFilterTest> {
model("handlers/charFilter", testMethodName = "doPerfTest", pattern = KT_WITHOUT_DOTS)
}
}
testGroup("code-insight/intentions-shared/tests/k1", testDataPath = "../testData") {
testClass<AbstractSharedK1IntentionTest> {
model("intentions", pattern = Patterns.forRegex("^([\\w\\-_]+)\\.(kt|kts)$"))
}
}
testGroup("code-insight/inspections-shared/tests/k1", testDataPath = "../testData") {
testClass<AbstractSharedK1LocalInspectionTest> {
val pattern = Patterns.forRegex("^([\\w\\-_]+)\\.(kt|kts)$")
model("inspectionsLocal", pattern = pattern)
}
testClass<AbstractSharedK1InspectionTest> {
val pattern = Patterns.forRegex("^(inspections\\.test)$")
model("inspections", pattern = pattern)
model("inspectionsLocal", pattern = pattern)
}
testClass<AbstractSharedK1KDocHighlightingTest> {
val pattern = Patterns.forRegex("^([\\w\\-_]+)\\.(kt|kts)$")
model("kdoc/highlighting", pattern = pattern)
}
testClass<AbstractSharedK1QuickFixTest> {
model("quickfix", pattern = Patterns.forRegex("^([\\w\\-_]+)\\.kt$"))
}
}
}
| plugins/kotlin/util/test-generator-fe10/test/org/jetbrains/kotlin/fe10/testGenerator/Fe10GenerateTests.kt | 3874988952 |
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import kotlin.test.assertEquals
@RunWith(Parameterized::class)
class ScrabbleScoreTest(val input: String, val expectedOutput: Int) {
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{index}: scoreWord({0})={1}")
fun data() = listOf(
arrayOf("a", 1),
arrayOf("A", 1),
arrayOf("f", 4),
arrayOf("at", 2),
arrayOf("zoo", 12),
arrayOf("street", 6),
arrayOf("quirky", 22),
arrayOf("OxyphenButazone", 41),
arrayOf("pinata", 8),
arrayOf("", 0),
arrayOf("abcdefghijklmnopqrstuvwxyz", 87)
)
}
@Test
fun test() {
assertEquals(expectedOutput, ScrabbleScore.scoreWord(input))
}
}
| exercises/practice/scrabble-score/src/test/kotlin/ScrabbleScoreTest.kt | 1613198177 |
package org.stepik.android.domain.personal_deadlines.interactor
import io.reactivex.Completable
import io.reactivex.Maybe
import io.reactivex.Single
import ru.nobird.android.domain.rx.doCompletableOnSuccess
import org.stepic.droid.web.storage.model.StorageRecord
import org.stepik.android.domain.personal_deadlines.model.DeadlinesWrapper
import org.stepik.android.domain.personal_deadlines.model.LearningRate
import org.stepik.android.domain.personal_deadlines.repository.DeadlinesBannerRepository
import org.stepik.android.domain.personal_deadlines.repository.DeadlinesRepository
import org.stepik.android.domain.personal_deadlines.resolver.DeadlinesResolver
import org.stepik.android.view.personal_deadlines.notification.DeadlinesNotificationDelegate
import javax.inject.Inject
class DeadlinesInteractor
@Inject
constructor(
private val deadlinesRepository: DeadlinesRepository,
private val deadlinesBannerRepository: DeadlinesBannerRepository,
private val deadlinesResolver: DeadlinesResolver,
private val deadlinesNotificationDelegate: DeadlinesNotificationDelegate
) {
fun createPersonalDeadlines(courseId: Long, learningRate: LearningRate): Single<StorageRecord<DeadlinesWrapper>> =
deadlinesResolver
.calculateDeadlinesForCourse(courseId, learningRate)
.flatMap(deadlinesRepository::createDeadlineRecord)
.doOnSuccess { deadlinesNotificationDelegate.scheduleDeadlinesNotifications() }
fun updatePersonalDeadlines(record: StorageRecord<DeadlinesWrapper>): Single<StorageRecord<DeadlinesWrapper>> =
deadlinesRepository
.updateDeadlineRecord(record)
.doOnSuccess { deadlinesNotificationDelegate.scheduleDeadlinesNotifications() }
fun removePersonalDeadline(recordId: Long): Completable =
deadlinesRepository
.removeDeadlineRecord(recordId)
.doOnComplete { deadlinesNotificationDelegate.scheduleDeadlinesNotifications() }
fun getPersonalDeadlineByCourseId(courseId: Long): Maybe<StorageRecord<DeadlinesWrapper>> =
deadlinesRepository
.getDeadlineRecordByCourseId(courseId)
fun shouldShowDeadlinesBannerForCourse(courseId: Long): Single<Boolean> =
deadlinesBannerRepository
.hasCourseId(courseId)
.doCompletableOnSuccess {
deadlinesBannerRepository.addCourseId(courseId)
}
} | app/src/main/java/org/stepik/android/domain/personal_deadlines/interactor/DeadlinesInteractor.kt | 3216087075 |
package io.customerly.entity.ping
import android.content.Context
import io.customerly.R
import io.customerly.utils.ggkext.STimestamp
import io.customerly.utils.ggkext.getTyped
import io.customerly.utils.ggkext.nullOnException
import io.customerly.utils.ggkext.optTyped
import org.json.JSONObject
import java.util.*
/**
* Created by Gianni on 07/07/18.
* Project: Customerly-KAndroid-SDK
*/
internal fun JSONObject.parseNextOfficeHours(): ClyNextOfficeHours? {
return nullOnException {
ClyNextOfficeHours(
period = it.getTyped(name = "period"),
startUtc = it.optTyped(name = "start_utc", fallback = 0),
endUtc = it.optTyped(name = "end_utc", fallback = 0))
}
}
internal data class ClyNextOfficeHours(
val period: String,
@STimestamp private val startUtc: Int,
@STimestamp private val endUtc: Int) {
@Suppress("unused")
companion object {
private const val PERIOD_EVERYDAY = "everyday"
private const val PERIOD_WEEKENDS = "weekends"
private const val PERIOD_WEEKDAYS = "weekdays"
private const val PERIOD_MONDAY = "monday"
private const val PERIOD_TUESDAY = "tuesday"
private const val PERIOD_WEDNESDAY = "wednesday"
private const val PERIOD_THURSDAY = "thursday"
private const val PERIOD_FRIDAY = "friday"
private const val PERIOD_SATURDAY = "saturday"
private const val PERIOD_SUNDAY = "sunday"
private const val PERIOD_A_SINGLE_DAY = "a_day"
}
/**
* returns null if the office is open, returns this otherwise
*/
internal fun isOfficeOpen(): Boolean = this.startUtc < (System.currentTimeMillis() / 1000)
internal fun getBotMessage(context: Context): String? {
if(this.isOfficeOpen()) {
return null
}
val startLocalTz = Calendar.getInstance().also { it.timeInMillis = this.startUtc * 1000L }
val endLocalTz = Calendar.getInstance().also { it.timeInMillis = this.endUtc * 1000L }
val localDay = startLocalTz.get(Calendar.DAY_OF_WEEK)
val periodLocalized = when(this.period) {
PERIOD_WEEKENDS -> {
when(localDay) {
Calendar.SATURDAY,Calendar.SUNDAY -> PERIOD_WEEKENDS
else -> PERIOD_A_SINGLE_DAY
}
}
PERIOD_WEEKDAYS -> {
when(localDay) {
Calendar.MONDAY,Calendar.TUESDAY,Calendar.WEDNESDAY,Calendar.THURSDAY,Calendar.FRIDAY -> PERIOD_WEEKDAYS
else -> PERIOD_A_SINGLE_DAY
}
}
else -> PERIOD_A_SINGLE_DAY
}
val startTimeString: String = String.format(Locale.ITALIAN, "%d:%02d", startLocalTz.get(Calendar.HOUR_OF_DAY), startLocalTz.get(Calendar.MINUTE))
val endTimeString: String = String.format(Locale.ITALIAN, "%d:%02d", endLocalTz.get(Calendar.HOUR_OF_DAY), endLocalTz.get(Calendar.MINUTE))
return when(periodLocalized) {
PERIOD_WEEKENDS -> {
context.getString(R.string.io_customerly__outofoffice_weekends_fromx_toy, startTimeString, endTimeString)
}
PERIOD_WEEKDAYS -> {
context.getString(R.string.io_customerly__outofoffice_weekdays_fromx_toy, startTimeString, endTimeString)
}
else -> {
val todayLocalTz = Calendar.getInstance()
if(startLocalTz.get(Calendar.YEAR) == todayLocalTz.get(Calendar.YEAR) && startLocalTz.get(Calendar.MONTH) == todayLocalTz.get(Calendar.MONTH) && startLocalTz.get(Calendar.DAY_OF_MONTH) == todayLocalTz.get(Calendar.DAY_OF_MONTH)) {
//Next opening = Today
context.getString(R.string.io_customerly__outofoffice_today_atx, startTimeString)
} else {
val tomorrowLocalTz = todayLocalTz.apply { this.add(Calendar.DAY_OF_MONTH, 1) }
if(startLocalTz.get(Calendar.YEAR) == tomorrowLocalTz.get(Calendar.YEAR) && startLocalTz.get(Calendar.MONTH) == tomorrowLocalTz.get(Calendar.MONTH) && startLocalTz.get(Calendar.DAY_OF_MONTH) == tomorrowLocalTz.get(Calendar.DAY_OF_MONTH)) {
//Next opening = Tomorrow
context.getString(R.string.io_customerly__outofoffice_tomorrow_atx, startTimeString)
} else {
context.getString(when(localDay) {
Calendar.MONDAY -> R.string.io_customerly__outofoffice_monday_atx
Calendar.TUESDAY -> R.string.io_customerly__outofoffice_tuesday_atx
Calendar.WEDNESDAY -> R.string.io_customerly__outofoffice_wednesday_atx
Calendar.THURSDAY -> R.string.io_customerly__outofoffice_thursday_atx
Calendar.FRIDAY -> R.string.io_customerly__outofoffice_friday_atx
Calendar.SATURDAY -> R.string.io_customerly__outofoffice_saturday_atx
Calendar.SUNDAY -> R.string.io_customerly__outofoffice_sunday_atx
else -> R.string.io_customerly__outofoffice_tomorrow_atx
}, startTimeString)
}
}
}
}
}
} | customerly-android-sdk/src/main/java/io/customerly/entity/ping/ClyNextOfficeHours.kt | 4164374132 |
package com.nononsenseapps.feeder.db.room
import androidx.room.testing.MigrationTestHelper
import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@LargeTest
class MigrationFrom13To14 {
private val dbName = "testDb"
@Rule
@JvmField
val testHelper: MigrationTestHelper = MigrationTestHelper(
InstrumentationRegistry.getInstrumentation(),
AppDatabase::class.java.canonicalName,
FrameworkSQLiteOpenHelperFactory()
)
@Test
fun migrate13to14() {
var db = testHelper.createDatabase(dbName, 13)
db.use {
db.execSQL(
"""
INSERT INTO feeds(id, title, url, custom_title, tag, notify, last_sync, response_hash, fulltext_by_default)
VALUES(1, 'feed', 'http://url', '', '', 0, 0, 666, 0)
""".trimIndent()
)
db.execSQL(
"""
INSERT INTO feed_items(id, guid, title, plain_title, plain_snippet, unread, notified, feed_id, first_synced_time, primary_sort_time)
VALUES(8, 'http://item', 'title', 'ptitle', 'psnippet', 1, 0, 1, 0, 0)
""".trimIndent()
)
}
db = testHelper.runMigrationsAndValidate(dbName, 14, true, MIGRATION_13_14)
db.query(
"""
SELECT open_articles_with FROM feeds
""".trimIndent()
)!!.use {
assert(it.count == 1)
assert(it.moveToFirst())
assertEquals(0L, it.getLong(0))
}
}
}
| app/src/androidTest/java/com/nononsenseapps/feeder/db/room/MigrationFrom13To14.kt | 2281572342 |
package org.stepik.android.view.injection.step_quiz
import androidx.lifecycle.ViewModel
import dagger.Module
import dagger.Provides
import dagger.multibindings.IntoMap
import org.stepik.android.presentation.base.injection.ViewModelKey
import org.stepik.android.presentation.step_quiz.StepQuizFeature
import org.stepik.android.presentation.step_quiz.StepQuizViewModel
import org.stepik.android.presentation.step_quiz.dispatcher.StepQuizActionDispatcher
import org.stepik.android.presentation.step_quiz.reducer.StepQuizReducer
import org.stepik.android.presentation.step_quiz_review.StepQuizReviewFeature
import org.stepik.android.presentation.step_quiz_review.StepQuizReviewTeacherFeature
import org.stepik.android.presentation.step_quiz_review.StepQuizReviewTeacherViewModel
import org.stepik.android.presentation.step_quiz_review.StepQuizReviewViewModel
import org.stepik.android.presentation.step_quiz_review.dispatcher.StepQuizReviewActionDispatcher
import org.stepik.android.presentation.step_quiz_review.dispatcher.StepQuizReviewTeacherActionDispatcher
import org.stepik.android.presentation.step_quiz_review.reducer.StepQuizReviewReducer
import org.stepik.android.presentation.step_quiz_review.reducer.StepQuizReviewTeacherReducer
import ru.nobird.app.core.model.safeCast
import ru.nobird.app.presentation.redux.container.wrapWithViewContainer
import ru.nobird.app.presentation.redux.dispatcher.transform
import ru.nobird.app.presentation.redux.dispatcher.wrapWithActionDispatcher
import ru.nobird.app.presentation.redux.feature.ReduxFeature
@Module
object StepQuizPresentationModule {
/**
* Presentation
*/
@Provides
@IntoMap
@ViewModelKey(StepQuizViewModel::class)
internal fun provideStepQuizPresenter(
stepQuizReducer: StepQuizReducer,
stepQuizActionDispatcher: StepQuizActionDispatcher
): ViewModel =
StepQuizViewModel(
ReduxFeature(StepQuizFeature.State.Idle, stepQuizReducer)
.wrapWithActionDispatcher(stepQuizActionDispatcher)
.wrapWithViewContainer()
)
@Provides
@IntoMap
@ViewModelKey(StepQuizReviewViewModel::class)
internal fun provideStepQuizReviewPresenter(
stepQuizReviewReducer: StepQuizReviewReducer,
stepQuizReviewActionDispatcher: StepQuizReviewActionDispatcher,
stepQuizActionDispatcher: StepQuizActionDispatcher
): ViewModel =
StepQuizReviewViewModel(
ReduxFeature(StepQuizReviewFeature.State.Idle, stepQuizReviewReducer)
.wrapWithActionDispatcher(stepQuizReviewActionDispatcher)
.wrapWithActionDispatcher(
stepQuizActionDispatcher.transform(
transformAction = { it.safeCast<StepQuizReviewFeature.Action.StepQuizAction>()?.action },
transformMessage = StepQuizReviewFeature.Message::StepQuizMessage
)
)
.wrapWithViewContainer()
)
@Provides
@IntoMap
@ViewModelKey(StepQuizReviewTeacherViewModel::class)
internal fun provideStepQuizReviewTeacherViewModel(
stepQuizReviewTeacherReducer: StepQuizReviewTeacherReducer,
stepQuizReviewTeacherActionDispatcher: StepQuizReviewTeacherActionDispatcher,
stepQuizActionDispatcher: StepQuizActionDispatcher
): ViewModel =
StepQuizReviewTeacherViewModel(
ReduxFeature(StepQuizReviewTeacherFeature.State.Idle, stepQuizReviewTeacherReducer)
.wrapWithActionDispatcher(stepQuizReviewTeacherActionDispatcher)
.wrapWithActionDispatcher(
stepQuizActionDispatcher.transform(
transformAction = { it.safeCast<StepQuizReviewTeacherFeature.Action.StepQuizAction>()?.action },
transformMessage = StepQuizReviewTeacherFeature.Message::StepQuizMessage
)
)
.wrapWithViewContainer()
)
} | app/src/main/java/org/stepik/android/view/injection/step_quiz/StepQuizPresentationModule.kt | 1609843161 |
package com.glodanif.bluetoothchat.ui
import android.Manifest
import android.app.Activity
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.*
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.RootMatchers.withDecorView
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.filters.LargeTest
import androidx.test.runner.AndroidJUnit4
import androidx.test.runner.permission.PermissionRequester
import com.glodanif.bluetoothchat.R
import com.glodanif.bluetoothchat.data.internal.AutoresponderProxy
import com.glodanif.bluetoothchat.ui.UITestUtils.Companion.atPosition
import com.glodanif.bluetoothchat.ui.UITestUtils.Companion.withToolbarSubTitle
import org.hamcrest.Matchers.`is`
import org.hamcrest.Matchers.not
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@LargeTest
class BluetoothCommunicationInstrumentedTest {
private val autoResponderAddress = "AC:22:0B:A1:89:A8"
private val permissionRequester = PermissionRequester().apply {
addPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
private val textMessageDelay = 2500.toLong()
private val fileMessageDelay = 12500.toLong()
private lateinit var context: Activity
@Before
fun setup() {
permissionRequester.requestPermissions()
}
@Test
fun communication() {
checkNotConnected()
checkNotSendingTextIfDisconnected()
onView(withText(R.string.chat__connect)).perform(click())
checkOutcommingConnection()
checkTextMessageReceiving()
checkTextMessageReceiving()
checkFileMessageReceiving()
checkFileMessageReceivingAndCancelByPartner()
checkFileMessageReceiving()
checkFileMessageReceivingAndCancelByPartner()
checkTextMessageReceiving()
checkDisconnectionByPartner()
onView(withId(android.R.id.button2)).perform(click())
onView(withText(R.string.chat__connect)).perform(click())
checkOutcommingConnection()
checkDisconnectionByPartner()
onView(withId(android.R.id.button1)).perform(click())
checkOutcommingConnection()
checkDisconnectionByPartner()
onView(withId(android.R.id.button2)).perform(click())
checkNotConnected()
}
private fun checkOutcommingConnection() {
onView(withText(R.string.chat__waiting_for_device))
onView(withId(R.id.tb_toolbar)).check(matches(
withToolbarSubTitle(context.getString(R.string.chat__pending))))
Thread.sleep(textMessageDelay)
onView(withId(R.id.av_actions)).check(matches(not(isDisplayed())))
onView(withId(R.id.tb_toolbar)).check(matches(
withToolbarSubTitle(context.getString(R.string.chat__connected))))
}
private fun checkFileMessageReceiving() {
onView(withId(R.id.et_message)).perform(typeText(AutoresponderProxy.COMMAND_SEND_FILE))
onView(withId(R.id.ib_send)).perform(click())
Thread.sleep(textMessageDelay)
onView(withText(R.string.chat__receiving_images)).check(matches(isDisplayed()))
Thread.sleep(fileMessageDelay)
onView(withId(R.id.rv_chat))
.check(matches(atPosition(0, hasDescendant(withId(R.id.iv_image)))))
onView(withText(R.string.chat__receiving_images)).check(matches(not(isDisplayed())))
}
private fun checkFileMessageReceivingAndCancelByPartner() {
onView(withId(R.id.et_message)).perform(typeText(AutoresponderProxy.COMMAND_SEND_FILE_AND_CANCEL))
onView(withId(R.id.ib_send)).perform(click())
Thread.sleep(textMessageDelay * 2)
onView(withText(R.string.chat__partner_canceled_image_transfer))
.inRoot(withDecorView(not(`is`(context.window.decorView)))).check(matches(isDisplayed()))
onView(withText(R.string.chat__receiving_images)).check(matches(not(isDisplayed())))
onView(withId(R.id.rv_chat))
.check(matches(atPosition(0, not(hasDescendant(withText(AutoresponderProxy.RESPONSE_RECEIVED))))))
}
private fun checkNotSendingTextIfDisconnected() {
onView(withId(R.id.et_message)).perform(typeText(AutoresponderProxy.COMMAND_SEND_TEXT))
onView(withId(R.id.ib_send)).perform(click())
onView(withText(R.string.chat__not_connected_to_send))
.inRoot(withDecorView(not(`is`(context.window.decorView)))).check(matches(isDisplayed()))
onView(withId(R.id.et_message)).perform(clearText())
}
private fun checkTextMessageReceiving() {
onView(withId(R.id.et_message)).perform(typeText(AutoresponderProxy.COMMAND_SEND_TEXT))
onView(withId(R.id.ib_send)).perform(click())
Thread.sleep(textMessageDelay)
onView(withId(R.id.rv_chat))
.check(matches(atPosition(0, hasDescendant(withText(AutoresponderProxy.RESPONSE_RECEIVED)))))
}
private fun checkDisconnectionByPartner() {
onView(withId(R.id.et_message)).perform(typeText(AutoresponderProxy.COMMAND_DISCONNECT))
onView(withId(R.id.ib_send)).perform(click())
Thread.sleep(textMessageDelay)
onView(withText(R.string.chat__partner_disconnected)).check(matches(isDisplayed()))
}
private fun checkNotConnected() {
onView(withText(R.string.chat__not_connected_to_this_device))
.check(matches(isDisplayed()))
onView(withId(R.id.tb_toolbar)).check(matches(
withToolbarSubTitle(context.getString(R.string.chat__not_connected))))
}
}
| app/src/androidTest/kotlin/com/glodanif/bluetoothchat/ui/BluetoothCommunicationInstrumentedTest.kt | 3187917674 |
package com.aemtools.test.fixture
import com.aemtools.test.base.model.fixture.ITestFixture
/**
* @author Dmytro Troynikov
*/
interface OSGiFelixAnnotationsMixin {
/**
* Add Felix OSGi service annotation to current fixture.
*
* @receiver [ITestFixture]
*/
fun ITestFixture.addFelixServiceAnnotation() =
this.addClass("org/apache/felix/scr/annotations/Service.java", """
package org.apache.felix.scr.annotations;
public @interface Service {}
""")
/**
* Add Sling Filter annotation to current fixture.
*
* @receiver [ITestFixture]
*/
fun ITestFixture.addFelixSlingFilterAnnotation() =
this.addClass("org/apache/felix/src/annotations/sling/SlingFilter.java", """
package org.apache.felix.scr.annotations.sling;
public @interface SlingFilter {}
""")
/**
* Add Sling Servlet annotation to current fixture.
*
* @receiver [ITestFixture]
*/
fun ITestFixture.addFelixSlingServletAnnotation() =
this.addClass("org/apache/felix/scr/annotations/sling/SlingServlet.java", """
package org.apache.felix.scr.annotations.sling;
public @interface SlingServlet {}
""")
/**
* Add `org.apache.felix.scr.annotations.Property` annotation to current fixture.
*
* @receiver [ITestFixture]
*/
fun ITestFixture.addFelixPropertyAnnotation() =
this.addClass("org/apache/felix/scr/annotations/Property.java", """
package org.apache.felix.scr.annotations;
public @interface Property {}
""")
/**
* Add `org.apache.sling.hc.annotations.SlingHealthCheck` annotation to current fixture.
*
* @receiver [ITestFixture]
*/
fun ITestFixture.addSlingHealthCheckAnnotation() =
addClass("org/apache/sling/hc/annotations/SlingHealthCheck.java", """
package org.apache.sling.hc.annotations;
public @interface SlingHealthCheck {}
""")
}
| test-framework/src/main/kotlin/com/aemtools/test/fixture/OSGiFelixAnnotationsMixin.kt | 4280045163 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.wearable.wear.alwayson
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.core.content.getSystemService
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.repeatOnLifecycle
import androidx.wear.compose.material.MaterialTheme
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.time.Clock
import java.time.Duration
import java.time.Instant
import java.time.LocalTime
/**
* Duration between updates while in active mode.
*/
val ACTIVE_INTERVAL: Duration = Duration.ofSeconds(1)
/**
* Duration between updates while in ambient mode.
*/
val AMBIENT_INTERVAL: Duration = Duration.ofSeconds(10)
const val AMBIENT_UPDATE_ACTION = "com.example.android.wearable.wear.alwayson.action.AMBIENT_UPDATE"
/**
* Create a PendingIntent which we'll give to the AlarmManager to send ambient mode updates
* on an interval which we've define.
*/
private val ambientUpdateIntent = Intent(AMBIENT_UPDATE_ACTION)
@Composable
fun AlwaysOnApp(
ambientState: AmbientState,
ambientUpdateTimestamp: Instant,
clock: Clock,
activeDispatcher: CoroutineDispatcher
) {
val ambientUpdateAlarmManager = rememberAlarmManager()
val context = LocalContext.current
/**
* Retrieves a PendingIntent that will perform a broadcast. You could also use getActivity()
* to retrieve a PendingIntent that will start a new activity, but be aware that actually
* triggers onNewIntent() which causes lifecycle changes (onPause() and onResume()) which
* might trigger code to be re-executed more often than you want.
*
* If you do end up using getActivity(), also make sure you have set activity launchMode to
* singleInstance in the manifest.
*
* Otherwise, it is easy for the AlarmManager launch Intent to open a new activity
* every time the Alarm is triggered rather than reusing this Activity.
*/
val ambientUpdatePendingIntent = remember(context) {
PendingIntent.getBroadcast(
context,
0,
ambientUpdateIntent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
}
/**
* A ping used to set up a loopback side-effect loop, to continuously update the time.
*/
var updateDataTrigger by remember { mutableStateOf(0L) }
/**
* The current instant to display
*/
var currentInstant by remember { mutableStateOf(Instant.now(clock)) }
/**
* The current time to display
*/
var currentTime by remember { mutableStateOf(LocalTime.now(clock)) }
/**
* The number of times the current time and instant have been updated
*/
var drawCount by remember { mutableStateOf(0) }
fun updateData() {
updateDataTrigger++
currentInstant = Instant.now(clock)
currentTime = LocalTime.now(clock)
drawCount++
}
val lifecycleOwner = LocalLifecycleOwner.current
/**
* Construct a boolean indicating if we are resumed.
*/
val isResumed by produceState(initialValue = false) {
lifecycleOwner.repeatOnLifecycle(Lifecycle.State.RESUMED) {
value = true
try {
awaitCancellation()
} finally {
value = false
}
}
}
if (isResumed) {
when (ambientState) {
is AmbientState.Ambient -> {
// When we are resumed and ambient, setup the broadcast receiver
SystemBroadcastReceiver(systemAction = AMBIENT_UPDATE_ACTION) {
updateData()
}
DisposableEffect(ambientUpdateAlarmManager, ambientUpdatePendingIntent) {
onDispose {
// Upon leaving resumption or ambient, cancel any ongoing pending intents
ambientUpdateAlarmManager.cancel(ambientUpdatePendingIntent)
}
}
}
AmbientState.Interactive -> Unit
}
// Whenever we change ambient state (and initially) update the data.
LaunchedEffect(ambientState) {
updateData()
}
// Then, setup a ping to refresh data again: either via the alarm manager, or simply
// after a delay
LaunchedEffect(updateDataTrigger, ambientState) {
when (ambientState) {
is AmbientState.Ambient -> {
val triggerTime = currentInstant.getNextInstantWithInterval(
AMBIENT_INTERVAL
)
ambientUpdateAlarmManager.setExact(
AlarmManager.RTC_WAKEUP,
triggerTime.toEpochMilli(),
ambientUpdatePendingIntent
)
}
AmbientState.Interactive -> {
val delay = currentInstant.getDelayToNextInstantWithInterval(
ACTIVE_INTERVAL
)
withContext(activeDispatcher) {
// Delay on the active dispatcher for testability
delay(delay.toMillis())
}
updateData()
}
}
}
}
MaterialTheme {
AlwaysOnScreen(
ambientState = ambientState,
ambientUpdateTimestamp = ambientUpdateTimestamp,
drawCount = drawCount,
currentInstant = currentInstant,
currentTime = currentTime
)
}
}
/**
* Returns the delay from this [Instant] to the next one that is aligned with the given [interval].
*/
private fun Instant.getDelayToNextInstantWithInterval(interval: Duration): Duration =
Duration.ofMillis(interval.toMillis() - toEpochMilli() % interval.toMillis())
/**
* Returns the next [Instant] that is aligned with the given [interval].
*/
private fun Instant.getNextInstantWithInterval(interval: Duration): Instant =
plus(getDelayToNextInstantWithInterval(interval))
@Composable
fun rememberAlarmManager(): AlarmManager {
val context = LocalContext.current
return remember(context) {
context.getSystemService()!!
}
}
@Composable
fun SystemBroadcastReceiver(
systemAction: String,
onSystemEvent: (intent: Intent?) -> Unit
) {
// Grab the current context in this part of the UI tree
val context = LocalContext.current
// Safely use the latest onSystemEvent lambda passed to the function
val currentOnSystemEvent by rememberUpdatedState(onSystemEvent)
// If either context or systemAction changes, unregister and register again
DisposableEffect(context, systemAction) {
val intentFilter = IntentFilter(systemAction)
val broadcast = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
currentOnSystemEvent(intent)
}
}
context.registerReceiver(broadcast, intentFilter)
// When the effect leaves the Composition, remove the callback
onDispose {
context.unregisterReceiver(broadcast)
}
}
}
| AlwaysOnKotlin/compose/src/main/java/com/example/android/wearable/wear/alwayson/AlwaysOnApp.kt | 2294398826 |
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package benchmarks.flow
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import org.openjdk.jmh.annotations.*
import java.util.concurrent.*
@Warmup(iterations = 7, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 7, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(value = 1)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Benchmark)
open class FlatMapMergeBenchmark {
// Note: tests only absence of contention on downstream
@Param("10", "100", "1000")
private var iterations = 100
@Benchmark
fun flatMapUnsafe() = runBlocking {
benchmarks.flow.scrabble.flow {
repeat(iterations) { emit(it) }
}.flatMapMerge { value ->
flowOf(value)
}.collect {
if (it == -1) error("")
}
}
@Benchmark
fun flatMapSafe() = runBlocking {
kotlinx.coroutines.flow.flow {
repeat(iterations) { emit(it) }
}.flatMapMerge { value ->
flowOf(value)
}.collect {
if (it == -1) error("")
}
}
}
| benchmarks/src/jmh/kotlin/benchmarks/flow/FlatMapMergeBenchmark.kt | 3149880777 |
/*
* (C) Copyright 2020 Lukas Morawietz (https://github.com/F43nd1r)
*
* 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.faendir.acra.ui.ext
import com.github.appreciated.css.grid.sizes.Length
import com.github.appreciated.layout.GridLayout
fun GridLayout.setColumnGap(size: Int, unit: SizeUnit) {
setColumnGap(Length(size.toString() + unit.text))
} | acrarium/src/main/kotlin/com/faendir/acra/ui/ext/GridLayout.kt | 694142439 |
/*
* Westford Wayland Compositor.
* Copyright (C) 2016 Erik De Rijcke
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.westford.nativ.glibc
import org.freedesktop.jaccall.CType
import org.freedesktop.jaccall.Field
import org.freedesktop.jaccall.Struct
@Struct(Field(name = "c_iflag",
type = CType.UNSIGNED_INT),
Field(name = "c_oflag",
type = CType.UNSIGNED_INT),
Field(name = "c_cflag",
type = CType.UNSIGNED_INT),
Field(name = "c_lflag",
type = CType.UNSIGNED_INT),
Field(name = "c_line",
type = CType.UNSIGNED_CHAR),
Field(name = "c_cc",
type = CType.UNSIGNED_CHAR,
cardinality = Libc.NCCS),
Field(name = "c_ispeed",
type = CType.UNSIGNED_INT),
Field(name = "c_ospeed",
type = CType.UNSIGNED_INT)) class termios : Struct_termios()
| compositor/src/main/kotlin/org/westford/nativ/glibc/termios.kt | 2820653412 |
// 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.stats.completion.network.status
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.registry.Registry
object WebServiceStatusManager {
private const val USE_ANALYTICS_PLATFORM_REGISTRY = "completion.stats.analytics.platform.send"
private const val ANALYTICS_PLATFORM_URL_REGISTRY = "completion.stats.analytics.platform.url"
private val LOG = logger<WebServiceStatusManager>()
private val statuses: MutableMap<String, WebServiceStatus> = mutableMapOf()
init {
if (Registry.`is`(USE_ANALYTICS_PLATFORM_REGISTRY, false)) {
registerAnalyticsPlatformStatus()
}
}
fun getAllStatuses(): List<WebServiceStatus> = statuses.values.toList()
private fun registerAnalyticsPlatformStatus() {
try {
val registry = Registry.get(ANALYTICS_PLATFORM_URL_REGISTRY)
if (registry.isChangedFromDefault) {
register(AnalyticsPlatformServiceStatus(registry.asString()))
return
}
}
catch (e: Throwable) {
LOG.error("No url for Analytics Platform web status. Set registry: $ANALYTICS_PLATFORM_URL_REGISTRY")
}
register(AnalyticsPlatformServiceStatus.withDefaultUrl())
}
private fun register(status: WebServiceStatus) {
val old = statuses[status.id]
if (old != null) {
LOG.warn("Service status with id [${old.id}] already created.")
return
}
statuses[status.id] = status
}
} | plugins/stats-collector/src/com/intellij/stats/completion/network/status/WebServiceStatusManager.kt | 718053865 |
// 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.internal.statistic.actions
import com.intellij.execution.process.ProcessOutputType
import com.intellij.internal.statistic.actions.StatisticsEventLogToolWindow.Companion.buildLogMessage
import com.intellij.internal.statistic.eventLog.LogEvent
import com.intellij.internal.statistic.eventLog.LogEventAction
import com.intellij.internal.statistic.eventLog.validator.ValidationResultType.*
import com.intellij.testFramework.fixtures.BasePlatformTestCase
import com.intellij.util.text.DateFormatUtil
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class StatisticsEventLogToolWindowTest : BasePlatformTestCase() {
private val eventId = "third.party"
private val eventTime = 1564643114456
@Test
fun testShortenProjectId() {
val action = LogEventAction(eventId)
action.addData("project", "5410c65eafb1f0abd78c6d9bdf33752f13c17b17ed57c3ae26801ae6ee7d17ea")
action.addData("plugin_type", "PLATFORM")
val actual = buildLogMessage(buildLogEvent(action))
assertEquals("${DateFormatUtil.formatTimeWithSeconds(
eventTime)} - ['toolwindow', v21]: '$eventId' {\"plugin_type\":\"PLATFORM\", \"project\":\"5410c65e...ea\"}",
actual)
}
@Test
fun testNotShortenProjectId() {
val action = LogEventAction(eventId)
val projectId = "12345"
action.addData("project", projectId)
val actual = buildLogMessage(buildLogEvent(action))
assertEquals("${DateFormatUtil.formatTimeWithSeconds(eventTime)} - ['toolwindow', v21]: '$eventId' {\"project\":\"$projectId\"}",
actual)
}
@Test
fun testFilterSystemFields() {
val action = LogEventAction(eventId)
action.addData("last", "1564643442610")
action.addData("created", "1564643442610")
val actual = buildLogMessage(buildLogEvent(action))
assertEquals("${DateFormatUtil.formatTimeWithSeconds(eventTime)} - ['toolwindow', v21]: '$eventId' {}",
actual)
}
@Test
fun testLogIncorrectEventIdAsError() {
val incorrectEventId = INCORRECT_RULE.description
val action = LogEventAction(incorrectEventId)
val filterModel = StatisticsLogFilterModel()
val processingResult = filterModel.processLine(buildLogMessage(buildLogEvent(action)))
assertEquals(processingResult.key, ProcessOutputType.STDERR)
}
@Test
fun testLogIncorrectEventDataAsError() {
val action = LogEventAction(eventId)
action.addData("test", INCORRECT_RULE.description)
action.addData("project", UNDEFINED_RULE.description)
val filterModel = StatisticsLogFilterModel()
val processingResult = filterModel.processLine(buildLogMessage(buildLogEvent(action)))
assertEquals(processingResult.key, ProcessOutputType.STDERR)
}
@Test
fun testAllValidationTypesUsed() {
val correctValidationTypes = setOf(ACCEPTED, THIRD_PARTY)
for (resultType in values()) {
assertTrue("Don't forget to change toolWindow logic in case of a new value in ValidationResult",
StatisticsEventLogToolWindow.rejectedValidationTypes.contains(resultType) || correctValidationTypes.contains(resultType))
}
}
private fun buildLogEvent(action: LogEventAction) = LogEvent("2e5b2e32e061", "193.1801", "176", eventTime,
"toolwindow", "21", "32", action)
} | platform/statistics/devkit/testSrc/com/intellij/internal/statistic/actions/StatisticsEventLogToolWindowTest.kt | 389778973 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.progress.impl
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.util.ProgressWindowTestCase
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.use
import com.intellij.openapi.wm.impl.IdeFrameImpl
import com.intellij.openapi.wm.impl.ProjectFrameHelper
import com.intellij.openapi.wm.impl.status.IdeStatusBarImpl
import com.intellij.testFramework.SkipInHeadlessEnvironment
import com.intellij.util.concurrency.Semaphore
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
@SkipInHeadlessEnvironment
class BackgroundableProcessIndicatorTest : ProgressWindowTestCase<Pair<Task.Backgroundable, BackgroundableProcessIndicator>>() {
private lateinit var statusBar: IdeStatusBarImpl
override fun setUp(): Unit = super.setUp().also {
val frameHelper = ProjectFrameHelper(IdeFrameImpl(), null)
Disposer.register(testRootDisposable, frameHelper)
frameHelper.init()
statusBar = frameHelper.statusBar as IdeStatusBarImpl
}
override fun Pair<Task.Backgroundable, BackgroundableProcessIndicator>.use(block: () -> Unit) {
second.use { block() }
}
override fun createProcess(): Pair<Task.Backgroundable, BackgroundableProcessIndicator> {
val task = TestTask(project)
val indicator = BackgroundableProcessIndicator(task.project, task, statusBar)
return Pair(task, indicator)
}
override suspend fun runProcessOnEdt(process: Pair<Task.Backgroundable, BackgroundableProcessIndicator>, block: () -> Unit) {
ProgressManager.getInstance().runProcess(block, process.second)
}
override suspend fun createAndRunProcessOffEdt(deferredProcess: CompletableDeferred<Pair<Task.Backgroundable, BackgroundableProcessIndicator>>, mayComplete: Semaphore) {
suspendCancellableCoroutine<Unit> { cont ->
val task = object : TestTask(project) {
override fun run(indicator: ProgressIndicator) {
mayComplete.waitFor(TIMEOUT_MS)
cont.resume(Unit)
}
}
val indicator = BackgroundableProcessIndicator(task.project, task, statusBar)
cont.invokeOnCancellation { indicator.cancel() }
deferredProcess.complete(Pair(task, indicator))
ProgressManager.getInstance().runProcessWithProgressAsynchronously(task, indicator)
}
}
override fun showDialog(process: Pair<Task.Backgroundable, BackgroundableProcessIndicator>) {
process.second.showDialog()
}
override fun assertUninitialized(process: Pair<Task.Backgroundable, BackgroundableProcessIndicator>) {
assertEmpty("Unexpected background processes", statusBar.backgroundProcesses)
}
override fun assertInitialized(process: Pair<Task.Backgroundable, BackgroundableProcessIndicator>) {
assertContainsOrdered(statusBar.backgroundProcesses, process)
}
private open class TestTask(project: Project) : Task.Backgroundable(project, "Test Task") {
override fun run(indicator: ProgressIndicator): Unit = Unit
}
} | platform/platform-tests/testSrc/com/intellij/openapi/progress/impl/BackgroundableProcessIndicatorTest.kt | 1772033562 |
@file:Suppress("unused")
package com.jetbrains.packagesearch.intellij.plugin.util
import com.intellij.openapi.diagnostic.Logger
import com.jetbrains.packagesearch.intellij.plugin.PluginEnvironment
internal val logger = Logger.getInstance("#${PluginEnvironment.PLUGIN_ID}")
internal fun logError(contextName: String? = null, messageProvider: () -> String) {
logError(traceInfo = null, contextName = contextName, messageProvider = messageProvider)
}
internal fun logError(contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) {
logError(traceInfo = null, contextName = contextName, throwable = throwable, messageProvider = messageProvider)
}
internal fun logError(traceInfo: TraceInfo? = null, contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) {
logError(buildMessageFrom(traceInfo, contextName, messageProvider), throwable)
}
internal fun logError(message: String, throwable: Throwable? = null) {
logger.error(message, throwable)
}
internal fun logWarn(contextName: String? = null, messageProvider: () -> String) {
logWarn(traceInfo = null, contextName = contextName, messageProvider = messageProvider)
}
internal fun logWarn(contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) {
logWarn(traceInfo = null, contextName = contextName, throwable = throwable, messageProvider = messageProvider)
}
internal fun logWarn(traceInfo: TraceInfo? = null, contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) {
logWarn(buildMessageFrom(traceInfo, contextName, messageProvider), throwable)
}
internal fun logWarn(message: String, throwable: Throwable? = null) {
logger.warn(message, throwable)
}
internal fun logInfo(contextName: String? = null, messageProvider: () -> String) {
logInfo(traceInfo = null, contextName = contextName, messageProvider = messageProvider)
}
internal fun logInfo(contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) {
logInfo(traceInfo = null, contextName = contextName, throwable = throwable, messageProvider = messageProvider)
}
internal fun logInfo(traceInfo: TraceInfo? = null, contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) {
logInfo(buildMessageFrom(traceInfo, contextName, messageProvider), throwable)
}
internal fun logInfo(message: String, throwable: Throwable? = null) {
logger.info(message, throwable)
}
internal fun logDebug(contextName: String? = null, messageProvider: () -> String) {
logDebug(traceInfo = null, contextName = contextName, messageProvider = messageProvider)
}
internal fun logDebug(contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) {
logDebug(traceInfo = null, contextName = contextName, throwable = throwable, messageProvider = messageProvider)
}
internal fun logDebug(traceInfo: TraceInfo? = null, contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) {
logDebug(buildMessageFrom(traceInfo, contextName, messageProvider), throwable)
}
internal fun logDebug(message: String, throwable: Throwable? = null) {
if (!FeatureFlags.useDebugLogging) return
if (!logger.isDebugEnabled) warnNotLoggable()
logger.debug(message, throwable)
}
internal fun logTrace(contextName: String? = null, messageProvider: () -> String) {
logTrace(traceInfo = null, contextName = contextName, messageProvider = messageProvider)
}
internal fun logTrace(traceInfo: TraceInfo? = null, contextName: String? = null, messageProvider: () -> String) {
logTrace(buildMessageFrom(traceInfo, contextName, messageProvider))
}
internal fun logTrace(message: String) {
if (!FeatureFlags.useDebugLogging) return
if (!logger.isTraceEnabled) warnNotLoggable()
logger.trace(message)
}
internal fun logTrace(throwable: Throwable) {
if (!FeatureFlags.useDebugLogging) return
if (!logger.isTraceEnabled) warnNotLoggable()
logger.trace(throwable)
}
private fun warnNotLoggable() {
logger.warn(
"""
|!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|Debug logging not enabled. Make sure you have a line like this:
| #${PluginEnvironment.PLUGIN_ID}:trace
|in your debug log settings (Help | Diagnostic Tools | Debug Log Settings)
|then restart the IDE.
|!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|""".trimMargin()
)
}
private fun buildMessageFrom(
traceInfo: TraceInfo?,
contextName: String?,
messageProvider: () -> String
) = buildString {
if (traceInfo != null) {
append(traceInfo)
append(' ')
}
if (!contextName.isNullOrBlank()) {
append(contextName)
append(' ')
}
if (count() > 0) append("— ")
append(messageProvider())
}
| plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/util/LogExtensions.kt | 355380220 |
package com.frightanic.smn.api.geojson
/**
* Each feature has a 'Point' geometry with coordinates based on the selected CRS.
*/
class Geometry(val coordinates: Array<Number>) {
val type = "Point"
}
| src/main/kotlin/com/frightanic/smn/api/geojson/Geometry.kt | 693909579 |
fun box() =
if (getAndCheck({ 42 }, { 42 })) "OK" else "fail"
inline fun <T> getAndCheck(getFirst: () -> T, getSecond: () -> T) =
getFirst() == getSecond() | backend.native/tests/external/codegen/box/boxingOptimization/kt15871.kt | 3578098906 |
package net.ndrei.teslacorelib.compatibility
import cofh.redstoneflux.api.IEnergyReceiver
import net.minecraft.tileentity.TileEntity
import net.minecraft.util.EnumFacing
import net.minecraftforge.fml.common.Optional
/**
* Created by CF on 2017-07-10.
*/
object RFPowerProxy {
const val MODID = "redstoneflux"
var isRFAvailable: Boolean = false
@Optional.Method(modid = RFPowerProxy.MODID)
fun isRFAcceptor(te: TileEntity, facing: EnumFacing)
= (te is IEnergyReceiver) && te.canConnectEnergy(facing)
@Optional.Method(modid = RFPowerProxy.MODID)
fun givePowerTo(te: TileEntity, facing: EnumFacing, power: Long, simulate: Boolean = false): Long {
val receiver = (te as? IEnergyReceiver) ?: return 0
return if (receiver.canConnectEnergy(facing))
receiver.receiveEnergy(facing, power.toInt(), simulate).toLong()
else
0
}
fun getEnergyStored(te: TileEntity, facing: EnumFacing): Int {
val receiver = (te as? IEnergyReceiver) ?: return 0
return receiver.getEnergyStored(facing)
}
fun getMaxEnergyStored(te: TileEntity, facing: EnumFacing): Int {
val receiver = (te as? IEnergyReceiver) ?: return 0
return receiver.getMaxEnergyStored(facing)
}
}
| src/main/kotlin/net/ndrei/teslacorelib/compatibility/RFPowerProxy.kt | 2678551225 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.glance.appwidget.demos
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.glance.GlanceModifier
import androidx.glance.LocalContext
import androidx.glance.LocalSize
import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.appwidget.GlanceAppWidgetReceiver
import androidx.glance.appwidget.SizeMode
import androidx.glance.appwidget.background
import androidx.glance.appwidget.cornerRadius
import androidx.glance.color.ColorProvider
import androidx.glance.layout.Column
import androidx.glance.layout.fillMaxSize
import androidx.glance.layout.padding
import androidx.glance.text.FontWeight
import androidx.glance.text.Text
import androidx.glance.text.TextDecoration
import androidx.glance.text.TextStyle
import java.text.DecimalFormat
class ExactAppWidget : GlanceAppWidget() {
override val sizeMode: SizeMode = SizeMode.Exact
@Composable
override fun Content() {
val context = LocalContext.current
Column(
modifier = GlanceModifier
.fillMaxSize()
.background(day = Color.LightGray, night = Color.DarkGray)
.padding(R.dimen.external_padding)
.cornerRadius(R.dimen.corner_radius)
) {
Text(
context.getString(R.string.exact_widget_title),
style = TextStyle(
color = ColorProvider(day = Color.DarkGray, night = Color.LightGray),
fontWeight = FontWeight.Bold,
textDecoration = TextDecoration.Underline
),
)
val size = LocalSize.current
val dec = DecimalFormat("#.##")
val width = dec.format(size.width.value)
val height = dec.format(size.height.value)
Text("Current layout: ${width}dp x ${height}dp")
}
}
}
class ExactAppWidgetReceiver : GlanceAppWidgetReceiver() {
override val glanceAppWidget = ExactAppWidget()
}
| glance/glance-appwidget/integration-tests/demos/src/main/java/androidx/glance/appwidget/demos/ExactAppWidget.kt | 4003924153 |
package abi44_0_0.host.exp.exponent.modules.api.screens
import android.annotation.SuppressLint
import android.view.View
import abi44_0_0.com.facebook.react.bridge.ReactContext
import abi44_0_0.com.facebook.react.views.view.ReactViewGroup
@SuppressLint("ViewConstructor")
class ScreenStackHeaderSubview(context: ReactContext?) : ReactViewGroup(context) {
private var mReactWidth = 0
private var mReactHeight = 0
var type = Type.RIGHT
val config: ScreenStackHeaderConfig?
get() {
return (parent as? CustomToolbar)?.config
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY &&
MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY
) {
// dimensions provided by react
mReactWidth = MeasureSpec.getSize(widthMeasureSpec)
mReactHeight = MeasureSpec.getSize(heightMeasureSpec)
val parent = parent
if (parent != null) {
forceLayout()
(parent as View).requestLayout()
}
}
setMeasuredDimension(mReactWidth, mReactHeight)
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
// no-op
}
enum class Type {
LEFT, CENTER, RIGHT, BACK, SEARCH_BAR
}
}
| android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/host/exp/exponent/modules/api/screens/ScreenStackHeaderSubview.kt | 3802879596 |
// 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.grazie.ide.ui.proofreading.component.list
import com.intellij.grazie.jlanguage.Lang
import com.intellij.openapi.ui.popup.ListSeparator
import com.intellij.openapi.ui.popup.PopupStep
import com.intellij.openapi.ui.popup.util.BaseListPopupStep
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.NlsSafe
class GrazieLanguagesPopupStep(@NlsContexts.PopupTitle title: String, available: List<Lang>, toDownload: List<Lang>,
private val download: (Lang) -> Boolean, private val onResult: (Lang) -> Unit)
: BaseListPopupStep<Lang>(title, available + toDownload) {
private val firstOther = toDownload.firstOrNull()
override fun getSeparatorAbove(value: Lang) = if (value == firstOther) ListSeparator() else null
@NlsSafe
override fun getTextFor(value: Lang) = value.nativeName
override fun onChosen(selectedValue: Lang, finalChoice: Boolean): PopupStep<*>? {
return doFinalStep { if (download(selectedValue)) onResult(selectedValue) }
}
}
| plugins/grazie/src/main/kotlin/com/intellij/grazie/ide/ui/proofreading/component/list/GrazieLanguagesPopupStep.kt | 1119572200 |
fun some() {
val b = """<caret>
|hello
""".trimMargin()
}
// IGNORE_FORMATTER | plugins/kotlin/idea/tests/testData/editor/enterHandler/multilineString/spaces/EnterOnFirstLineWithPresentTrimMarginAndLine.kt | 639295365 |
class Java8Class {
fun foo0(r: Function0<String?>?) {}
fun foo1(r: Function1<Int, String?>?) {}
fun foo2(r: Function2<Int?, Int?, String?>?) {}
fun helper() {}
fun foo() {
foo0 { "42" }
foo0 { "42" }
foo0 {
helper()
"42"
}
foo1 { i: Int? -> "42" }
foo1 { i: Int? -> "42" }
foo1 { i: Int ->
helper()
if (i > 1) {
return@foo1 null
}
"43"
}
foo2 { i: Int?, j: Int? -> "42" }
foo2 { i: Int?, j: Int? ->
helper()
"42"
}
val f: Function2<Int, Int, String> = label@{ i: Int, k: Int? ->
helper()
if (i > 1) {
return@label "42"
}
"43"
}
val f1 = label@{ i1: Int, k1: Int ->
val f2: Function2<Int, Int, String> = label@{ i2: Int, k2: Int? ->
helper()
if (i2 > 1) {
return@label "42"
}
"43"
}
if (i1 > 1) {
return@label f.invoke(i1, k1)
}
f.invoke(i1, k1)
}
val runnable = Runnable {}
foo1 { i: Int ->
if (i > 1) {
return@foo1 "42"
}
foo0 {
if (true) {
return@foo0 "42"
}
"43"
}
"43"
}
}
} | plugins/kotlin/j2k/new/tests/testData/newJ2k/function/java8Lambdas.kt | 2894844820 |
package test
actual open class ExpectedChild : SimpleParent() {
actual override val bar: Int get() = 1
}
class ExpectedChildChildJvm : ExpectedChild() {
override val bar: Int get() = 1
} | plugins/kotlin/idea/tests/testData/navigation/implementations/multiModule/expectClassSuperclassProperty/jvm/jvm.kt | 593231004 |
// 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.uast.kotlin
import com.intellij.psi.PsiLanguageInjectionHost
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
import org.jetbrains.uast.*
import org.jetbrains.uast.expressions.UInjectionHost
class KotlinStringTemplateUPolyadicExpression(
override val sourcePsi: KtStringTemplateExpression,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent),
UPolyadicExpression,
KotlinUElementWithType,
KotlinEvaluatableUElement,
UInjectionHost {
override val operands: List<UExpression> by lz {
sourcePsi.entries.map {
KotlinConverter.convertEntry(
it,
this,
DEFAULT_EXPRESSION_TYPES_LIST
)!!
}.takeIf { it.isNotEmpty() } ?: listOf(KotlinStringULiteralExpression(sourcePsi, this, ""))
}
override val operator = UastBinaryOperator.PLUS
override val psiLanguageInjectionHost: PsiLanguageInjectionHost get() = sourcePsi
override val isString: Boolean get() = true
override fun asRenderString(): String = if (operands.isEmpty()) "\"\"" else super<UPolyadicExpression>.asRenderString()
override fun asLogString(): String = if (operands.isEmpty()) "UPolyadicExpression (value = \"\")" else super.asLogString()
}
| plugins/kotlin/uast/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinStringTemplateUPolyadicExpression.kt | 3118597246 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.starters.remote.wizard
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.ide.starters.JavaStartersBundle
import com.intellij.ide.starters.local.StarterModuleBuilder
import com.intellij.ide.starters.remote.*
import com.intellij.ide.starters.shared.*
import com.intellij.ide.starters.shared.ValidationFunctions.*
import com.intellij.ide.util.PropertiesComponent
import com.intellij.ide.util.projectWizard.ModuleNameGenerator
import com.intellij.ide.util.projectWizard.ModuleWizardStep
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.ide.wizard.AbstractWizard
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.observable.properties.GraphProperty
import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty
import com.intellij.openapi.observable.properties.PropertyGraph
import com.intellij.openapi.observable.properties.map
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectSdksModel
import com.intellij.openapi.roots.ui.configuration.sdkComboBox
import com.intellij.openapi.roots.ui.configuration.validateJavaVersion
import com.intellij.openapi.roots.ui.configuration.validateSdk
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.InputValidator
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.popup.IconButton
import com.intellij.openapi.util.Condition
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.io.FileUtil
import com.intellij.ui.InplaceButton
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.UIBundle
import com.intellij.ui.components.ActionLink
import com.intellij.ui.dsl.builder.EMPTY_LABEL
import com.intellij.ui.dsl.builder.SegmentedButton
import com.intellij.ui.layout.*
import com.intellij.util.concurrency.Semaphore
import com.intellij.util.ui.AsyncProcessIcon
import com.intellij.util.ui.UIUtil
import java.awt.event.ActionListener
import java.io.File
import java.io.IOException
import java.net.MalformedURLException
import java.net.URL
import java.util.concurrent.Future
import javax.swing.DefaultComboBoxModel
import javax.swing.JComponent
import javax.swing.JTextField
import javax.swing.SwingUtilities
open class WebStarterInitialStep(contextProvider: WebStarterContextProvider) : ModuleWizardStep() {
protected val moduleBuilder: WebStarterModuleBuilder = contextProvider.moduleBuilder
protected val wizardContext: WizardContext = contextProvider.wizardContext
protected val starterContext: WebStarterContext = contextProvider.starterContext
protected val starterSettings: StarterWizardSettings = contextProvider.settings
protected val parentDisposable: Disposable = contextProvider.parentDisposable
private val validatedTextComponents: MutableList<JTextField> = mutableListOf()
protected val propertyGraph: PropertyGraph = PropertyGraph()
private val entityNameProperty: GraphProperty<String> = propertyGraph.graphProperty(::suggestName)
private val locationProperty: GraphProperty<String> = propertyGraph.graphProperty(::suggestLocationByName)
private val groupIdProperty: GraphProperty<String> = propertyGraph.graphProperty { starterContext.group }
private val artifactIdProperty: GraphProperty<String> = propertyGraph.graphProperty { entityName }
private val packageNameProperty: GraphProperty<String> = propertyGraph.graphProperty { starterContext.packageName }
private val sdkProperty: GraphProperty<Sdk?> = propertyGraph.graphProperty { null }
private val projectTypeProperty: GraphProperty<StarterProjectType?> = propertyGraph.graphProperty { starterContext.projectType }
private val languageProperty: GraphProperty<StarterLanguage> = propertyGraph.graphProperty { starterContext.language }
private val packagingProperty: GraphProperty<StarterAppPackaging?> = propertyGraph.graphProperty { starterContext.packaging }
private val testFrameworkProperty: GraphProperty<StarterTestRunner?> = propertyGraph.graphProperty { starterContext.testFramework }
private val languageLevelProperty: GraphProperty<StarterLanguageLevel?> = propertyGraph.graphProperty { starterContext.languageLevel }
private val applicationTypeProperty: GraphProperty<StarterAppType?> = propertyGraph.graphProperty { starterContext.applicationType }
private val exampleCodeProperty: GraphProperty<Boolean> = propertyGraph.graphProperty { starterContext.includeExamples }
private val gitProperty: GraphProperty<Boolean> = propertyGraph.graphProperty { false }
private var entityName: String by entityNameProperty.map { it.trim() }
private var location: String by locationProperty
private var groupId: String by groupIdProperty.map { it.trim() }
private var artifactId: String by artifactIdProperty.map { it.trim() }
private var languageLevel: StarterLanguageLevel? by languageLevelProperty
private var packageName: String by packageNameProperty.map { it.trim() }
private val contentPanel: DialogPanel by lazy { createComponent() }
private val progressIcon: AsyncProcessIcon by lazy { AsyncProcessIcon(moduleBuilder.builderId + "ServerOptions") }
private val serverUrlLink: ActionLink by lazy { createServerUrlLink() }
private val retryButton: InplaceButton by lazy { createRetryButton() }
private val sdkModel: ProjectSdksModel = ProjectSdksModel()
private val languageLevelsModel: DefaultComboBoxModel<StarterLanguageLevel> = DefaultComboBoxModel<StarterLanguageLevel>()
private val applicationTypesModel: DefaultComboBoxModel<StarterAppType> = DefaultComboBoxModel<StarterAppType>()
private lateinit var projectTypesSelector: SegmentedButton<StarterProjectType?>
private lateinit var packagingTypesSelector: SegmentedButton<StarterAppPackaging?>
private lateinit var languagesSelector: SegmentedButton<StarterLanguage>
private var languages: List<StarterLanguage> = starterSettings.languages
private var applicationTypes: List<StarterAppType> = starterSettings.applicationTypes
private var projectTypes: List<StarterProjectType> = starterSettings.projectTypes
private var packagingTypes: List<StarterAppPackaging> = starterSettings.packagingTypes
@Volatile
private var serverOptions: WebStarterServerOptions? = null
@Volatile
private var currentRequest: Future<*>? = null
@Volatile
private var isDisposed: Boolean = false
private val serverOptionsLoadingSemaphore: Semaphore = Semaphore()
private val serverSettingsButton: InplaceButton = InplaceButton(
IconButton(JavaStartersBundle.message("button.tooltip.configure"), AllIcons.General.Gear, AllIcons.General.GearHover),
ActionListener {
configureServer()
}
)
init {
Disposer.register(parentDisposable, Disposable {
isDisposed = true
sdkModel.disposeUIResources()
currentRequest?.cancel(true)
})
}
override fun getComponent(): JComponent = contentPanel
override fun getHelpId(): String? = moduleBuilder.getHelpId()
override fun updateDataModel() {
starterContext.serverOptions = this.serverOptions!!
starterContext.projectType = projectTypeProperty.get()
starterContext.language = languageProperty.get()
starterContext.group = groupId
starterContext.artifact = artifactId
starterContext.name = entityName
starterContext.packageName = packageName
starterContext.packaging = packagingProperty.get()
starterContext.languageLevel = languageLevel
starterContext.testFramework = testFrameworkProperty.get()
starterContext.applicationType = applicationTypeProperty.get()
starterContext.includeExamples = exampleCodeProperty.get()
starterContext.gitIntegration = gitProperty.get()
wizardContext.projectName = entityName
wizardContext.setProjectFileDirectory(FileUtil.join(location, entityName))
val sdk = sdkProperty.get()
if (wizardContext.project == null) {
wizardContext.projectJdk = sdk
}
else {
moduleBuilder.moduleJdk = sdk
}
}
private fun suggestName(): String {
return suggestName(starterContext.artifact)
}
private fun suggestName(prefix: String): String {
val projectFileDirectory = File(wizardContext.projectFileDirectory)
return FileUtil.createSequentFileName(projectFileDirectory, prefix, "")
}
private fun suggestLocationByName(): String {
return wizardContext.projectFileDirectory
}
private fun suggestPackageName(): String {
return StarterModuleBuilder.suggestPackageName(groupId, artifactId)
}
private fun createComponent(): DialogPanel {
entityNameProperty.dependsOn(artifactIdProperty) { artifactId }
artifactIdProperty.dependsOn(entityNameProperty) { entityName }
packageNameProperty.dependsOn(artifactIdProperty, ::suggestPackageName)
packageNameProperty.dependsOn(groupIdProperty, ::suggestPackageName)
progressIcon.toolTipText = JavaStartersBundle.message("message.state.connecting.and.retrieving.options")
return panel {
row {
cell(isFullWidth = true) {
label(JavaStartersBundle.message("title.project.server.url.label"))
component(serverUrlLink)
component(serverSettingsButton)
component(retryButton)
component(progressIcon)
}
}.largeGapAfter()
row(JavaStartersBundle.message("title.project.name.label")) {
textField(entityNameProperty)
.growPolicy(GrowPolicy.SHORT_TEXT)
.withSpecialValidation(listOf(CHECK_NOT_EMPTY, CHECK_SIMPLE_NAME_FORMAT),
createLocationWarningValidator(locationProperty))
.focused()
for (nameGenerator in ModuleNameGenerator.EP_NAME.extensionList) {
val nameGeneratorUi = nameGenerator.getUi(moduleBuilder.builderId) { entityNameProperty.set(it) }
if (nameGeneratorUi != null) {
component(nameGeneratorUi).constraints(pushX)
}
}
}.largeGapAfter()
addProjectLocationUi()
addFieldsBefore(this)
if (starterSettings.languages.size > 1) {
row(JavaStartersBundle.message("title.project.language.label")) {
languagesSelector = segmentedButton(starterSettings.languages, languageProperty) { it.title }
}.largeGapAfter()
}
if (starterSettings.projectTypes.isNotEmpty()) {
val messages = starterSettings.customizedMessages
row(messages?.projectTypeLabel ?: JavaStartersBundle.message("title.project.type.label")) {
projectTypesSelector = segmentedButton(starterSettings.projectTypes, projectTypeProperty) { it?.title ?: "" }
}.largeGapAfter()
}
if (starterSettings.testFrameworks.isNotEmpty()) {
row(JavaStartersBundle.message("title.project.test.framework.label")) {
segmentedButton(starterSettings.testFrameworks, testFrameworkProperty) { it?.title ?: "" }
}.largeGapAfter()
}
row(JavaStartersBundle.message("title.project.group.label")) {
textField(groupIdProperty)
.growPolicy(GrowPolicy.SHORT_TEXT)
.withSpecialValidation(CHECK_NOT_EMPTY, CHECK_NO_WHITESPACES, CHECK_GROUP_FORMAT, CHECK_NO_RESERVED_WORDS)
}.largeGapAfter()
row(JavaStartersBundle.message("title.project.artifact.label")) {
textField(artifactIdProperty)
.growPolicy(GrowPolicy.SHORT_TEXT)
.withSpecialValidation(CHECK_NOT_EMPTY, CHECK_NO_WHITESPACES, CHECK_ARTIFACT_SIMPLE_FORMAT, CHECK_NO_RESERVED_WORDS)
}.largeGapAfter()
if (starterSettings.isPackageNameEditable) {
row(JavaStartersBundle.message("title.project.package.label")) {
textField(packageNameProperty)
.growPolicy(GrowPolicy.SHORT_TEXT)
.withSpecialValidation(CHECK_NOT_EMPTY, CHECK_NO_WHITESPACES, CHECK_NO_RESERVED_WORDS, CHECK_PACKAGE_NAME)
}.largeGapAfter()
}
if (starterSettings.applicationTypes.isNotEmpty()) {
row(JavaStartersBundle.message("title.project.app.type.label")) {
applicationTypesModel.addAll(starterSettings.applicationTypes)
comboBox(applicationTypesModel, applicationTypeProperty, SimpleListCellRenderer.create("") { it?.title ?: "" })
.growPolicy(GrowPolicy.SHORT_TEXT)
}.largeGapAfter()
}
row(JavaStartersBundle.message("title.project.sdk.label")) {
sdkComboBox(sdkModel, sdkProperty, wizardContext.project, moduleBuilder)
.growPolicy(GrowPolicy.SHORT_TEXT)
}.largeGapAfter()
if (starterSettings.languageLevels.isNotEmpty()) {
row(JavaStartersBundle.message("title.project.java.version.label")) {
languageLevelsModel.addAll(starterSettings.languageLevels)
comboBox(languageLevelsModel, languageLevelProperty, SimpleListCellRenderer.create("") { it?.title ?: "" })
}.largeGapAfter()
}
if (starterSettings.packagingTypes.isNotEmpty()) {
row(JavaStartersBundle.message("title.project.packaging.label")) {
packagingTypesSelector = segmentedButton(starterSettings.packagingTypes, packagingProperty) { it?.title ?: "" }
}.largeGapAfter()
}
if (starterSettings.isExampleCodeProvided) {
row {
checkBox(JavaStartersBundle.message("title.project.examples.label"), exampleCodeProperty)
}
}
addFieldsAfter(this)
}.withVisualPadding()
}
private fun createServerUrlLink(): ActionLink {
val result = ActionLink(urlPreview(starterContext.serverUrl)) {
BrowserUtil.browse(starterContext.serverUrl)
}
UIUtil.applyStyle(UIUtil.ComponentStyle.REGULAR, result)
return result
}
private fun createRetryButton(): InplaceButton {
return InplaceButton(IconButton(JavaStartersBundle.message("button.tooltip.retry"),
AllIcons.Nodes.ErrorIntroduction, AllIcons.Actions.ForceRefresh), ActionListener {
requestServerOptions()
}).apply {
isVisible = false
}
}
@NlsSafe
private fun urlPreview(serverUrl: String): String {
val url = serverUrl
.removePrefix("https://")
.removeSuffix("/")
if (url.length > 35) {
return url.take(30) + "..."
}
return url
}
override fun getPreferredFocusedComponent(): JComponent? {
return contentPanel.preferredFocusedComponent
}
override fun validate(): Boolean {
if (!validateFormFields(component, contentPanel, validatedTextComponents)) {
return false
}
if (!validateSdk(sdkProperty, sdkModel)) {
return false
}
val passTechnologyName = if (starterSettings.languageLevels.size > 1) null else moduleBuilder.presentableName
if (!validateJavaVersion(sdkProperty, languageLevel?.javaVersion, passTechnologyName)) {
return false
}
return checkServerOptionsLoaded()
}
private fun checkServerOptionsLoaded(): Boolean {
val request = currentRequest
if (serverOptions != null && request == null) {
return true
}
if (request == null) {
// failure? retry server options loading
requestServerOptions()
}
val newOptionsRef: Ref<WebStarterServerOptions> = Ref.create()
ProgressManager.getInstance().runProcessWithProgressSynchronously(Runnable {
val progressIndicator = ProgressManager.getInstance().progressIndicator
progressIndicator.isIndeterminate = true
for (i in 0 until 30) {
progressIndicator.checkCanceled()
if (serverOptionsLoadingSemaphore.waitFor(500)) {
serverOptions?.let {
newOptionsRef.set(it)
}
return@Runnable
}
}
}, JavaStartersBundle.message("message.state.connecting.and.retrieving.options"), true, wizardContext.project)
if (!newOptionsRef.isNull) {
updatePropertiesWithServerOptions(newOptionsRef.get())
}
return serverOptions != null
}
private fun LayoutBuilder.addProjectLocationUi() {
val locationRow = row(JavaStartersBundle.message("title.project.location.label")) {
projectLocationField(locationProperty, wizardContext)
.withSpecialValidation(CHECK_NOT_EMPTY, CHECK_LOCATION_FOR_ERROR)
}
if (wizardContext.isCreatingNewProject) {
// Git should not be enabled for single module
row(EMPTY_LABEL) {
checkBox(UIBundle.message("label.project.wizard.new.project.git.checkbox"), gitProperty)
}.largeGapAfter()
} else {
locationRow.largeGapAfter()
}
}
protected open fun addFieldsBefore(layout: LayoutBuilder) {}
protected open fun addFieldsAfter(layout: LayoutBuilder) {}
override fun _init() {
super._init()
if (serverOptions == null && currentRequest == null) {
@Suppress("HardCodedStringLiteral")
val serverUrlFromSettings = PropertiesComponent.getInstance().getValue(getServerUrlPropertyName())
if (serverUrlFromSettings != null) {
setServerUrl(serverUrlFromSettings)
}
// required on dialog opening to get correct modality state
SwingUtilities.invokeLater(this::requestServerOptions)
}
}
private fun setServerUrl(@NlsSafe url: String) {
starterContext.serverUrl = url
serverUrlLink.text = urlPreview(url)
serverUrlLink.toolTipText = url
}
private fun requestServerOptions() {
progressIcon.isVisible = true
retryButton.isVisible = false
progressIcon.resume()
serverOptionsLoadingSemaphore.down()
currentRequest = ApplicationManager.getApplication().executeOnPooledThread {
val readyServerOptions = try {
moduleBuilder.getServerOptions(starterContext.serverUrl)
}
catch (e: Exception) {
if (e is IOException || e is IllegalStateException) {
logger<WebStarterInitialStep>().info("Unable to get server options for " + moduleBuilder.builderId, e)
}
else {
logger<WebStarterInitialStep>().error("Unable to get server options for " + moduleBuilder.builderId, e)
}
ApplicationManager.getApplication().invokeLater(
{
if (component.isShowing) {
// only if the wizard is visible
Messages.showErrorDialog(
JavaStartersBundle.message("message.no.connection.with.error.content", starterContext.serverUrl, e.message),
JavaStartersBundle.message("message.title.error"))
}
}, getModalityState())
null
}
setServerOptions(readyServerOptions)
}
}
private fun setServerOptions(serverOptions: WebStarterServerOptions?) {
this.serverOptions = serverOptions
this.currentRequest = null
this.serverOptionsLoadingSemaphore.up()
ApplicationManager.getApplication().invokeLater(Runnable {
progressIcon.suspend()
progressIcon.isVisible = false
retryButton.isVisible = serverOptions == null
if (serverOptions != null) {
updatePropertiesWithServerOptions(serverOptions)
}
}, getModalityState(), getDisposed())
}
private fun getModalityState(): ModalityState {
return ModalityState.stateForComponent(wizardContext.getUserData(AbstractWizard.KEY)!!.contentComponent)
}
private fun getDisposed(): Condition<Any> = Condition<Any> { isDisposed }
private fun configureServer() {
val currentServerUrl = starterContext.serverUrl
val serverUrlTitle = starterSettings.customizedMessages?.serverUrlDialogTitle
?: JavaStartersBundle.message("title.server.url.dialog")
val newUrl = Messages.showInputDialog(component, null, serverUrlTitle, null, currentServerUrl, object : InputValidator {
override fun canClose(inputString: String?): Boolean = checkInput(inputString)
override fun checkInput(inputString: String?): Boolean {
try {
URL(inputString)
}
catch (e: MalformedURLException) {
return false
}
return true
}
})
// update
if (newUrl != null && starterContext.serverUrl != newUrl) {
setServerUrl(newUrl)
PropertiesComponent.getInstance().setValue(getServerUrlPropertyName(), newUrl)
requestServerOptions()
}
}
private fun getServerUrlPropertyName(): String {
return moduleBuilder.builderId + ".service.url.last"
}
protected open fun updatePropertiesWithServerOptions(serverOptions: WebStarterServerOptions) {
starterContext.frameworkVersion = serverOptions.frameworkVersions.find { it.isDefault }
?: serverOptions.frameworkVersions.firstOrNull()
val currentPackageName = packageName // remember package name before applying group and artifact
serverOptions.extractOption(SERVER_NAME_KEY) {
if (entityName == suggestName(DEFAULT_MODULE_NAME)) {
val newName = suggestName(it)
if (entityName != newName) {
entityNameProperty.set(newName)
}
}
}
serverOptions.extractOption(SERVER_GROUP_KEY) {
if (groupId == DEFAULT_MODULE_GROUP && groupId != it) {
groupIdProperty.set(it)
}
}
serverOptions.extractOption(SERVER_ARTIFACT_KEY) {
if (artifactId == DEFAULT_MODULE_ARTIFACT && artifactId != it) {
artifactIdProperty.set(it)
}
}
serverOptions.extractOption(SERVER_PACKAGE_NAME_KEY) {
if (currentPackageName == DEFAULT_PACKAGE_NAME && currentPackageName != it) {
packageNameProperty.set(it)
}
}
serverOptions.extractOption(SERVER_VERSION_KEY) {
starterContext.version = it
}
serverOptions.extractOption(SERVER_LANGUAGE_LEVELS_KEY) { levels ->
val selectedItem = languageLevelsModel.selectedItem
languageLevelsModel.removeAllElements()
languageLevelsModel.addAll(levels)
if (levels.contains(selectedItem)) {
languageLevelsModel.selectedItem = selectedItem
}
else {
languageLevel = levels.firstOrNull()
languageLevelsModel.selectedItem = languageLevel
}
}
serverOptions.extractOption(SERVER_LANGUAGE_LEVEL_KEY) { level ->
if (languageLevel == starterSettings.defaultLanguageLevel && languageLevel != level) {
languageLevelProperty.set(level)
}
}
serverOptions.extractOption(SERVER_PROJECT_TYPES) { types ->
if (types.isNotEmpty() && types != this.projectTypes && ::projectTypesSelector.isInitialized) {
val correspondingOption = types.find { it.id == projectTypeProperty.get()?.id }
projectTypeProperty.set(correspondingOption ?: types.first())
projectTypesSelector.items(types)
this.projectTypes = types
}
}
serverOptions.extractOption(SERVER_APPLICATION_TYPES) { types ->
if (types.isNotEmpty() && types != applicationTypes) {
applicationTypesModel.removeAllElements()
applicationTypesModel.addAll(types)
applicationTypesModel.selectedItem = types.firstOrNull()
this.applicationTypes = types
}
}
serverOptions.extractOption(SERVER_PACKAGING_TYPES) { types ->
if (types.isNotEmpty() && types != this.packagingTypes && ::packagingTypesSelector.isInitialized) {
val correspondingOption = types.find { it.id == packagingProperty.get()?.id }
packagingProperty.set(correspondingOption ?: types.first())
packagingTypesSelector.items(types)
this.packagingTypes = types
}
}
serverOptions.extractOption(SERVER_LANGUAGES) { languages ->
if (languages.isNotEmpty() && languages != this.languages && ::languagesSelector.isInitialized) {
val correspondingOption = languages.find { it.id == languageProperty.get().id }
languageProperty.set(correspondingOption ?: languages.first())
languagesSelector.items(languages)
this.languages = languages
}
}
contentPanel.revalidate()
}
@Suppress("SameParameterValue")
private fun <T : JComponent> CellBuilder<T>.withSpecialValidation(vararg errorValidations: TextValidationFunction): CellBuilder<T> {
return this.withSpecialValidation(errorValidations.asList(), null)
}
private fun <T : JComponent> CellBuilder<T>.withSpecialValidation(errorValidations: List<TextValidationFunction>,
warningValidation: TextValidationFunction?): CellBuilder<T> {
return withValidation(this, errorValidations, warningValidation, validatedTextComponents, parentDisposable)
}
}
| java/idea-ui/src/com/intellij/ide/starters/remote/wizard/WebStarterInitialStep.kt | 319310519 |
// WITH_STDLIB
fun foo() {
val x = (1..4).asSequence()
x.forEach<caret> { it.equals(1) }
} | plugins/kotlin/idea/tests/testData/intentions/convertForEachToForLoop/simpleSequence.kt | 1392843929 |
fun foo(s: String): String = s.ext<caret>
| plugins/kotlin/completion/tests/testData/handlers/multifile/smart/ImportExtensionFunction-1.kt | 1109372384 |
<caret>class C | plugins/kotlin/idea/tests/testData/intentions/changeVisibility/private/noModifierListClass.kt | 3364415342 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections.collections
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.config.ApiVersion
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtQualifiedExpression
import org.jetbrains.kotlin.psi.KtReturnExpression
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.DefaultValueArgument
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
abstract class AbstractCallChainChecker : AbstractKotlinInspection() {
protected fun findQualifiedConversion(
expression: KtQualifiedExpression,
conversionGroups: Map<ConversionId, List<Conversion>>,
additionalCallCheck: (Conversion, ResolvedCall<*>, ResolvedCall<*>, BindingContext) -> Boolean
): Conversion? {
val firstExpression = expression.receiverExpression
val firstCallExpression = getCallExpression(firstExpression) ?: return null
val firstCalleeExpression = firstCallExpression.calleeExpression ?: return null
val secondCallExpression = expression.selectorExpression as? KtCallExpression ?: return null
val secondCalleeExpression = secondCallExpression.calleeExpression ?: return null
val apiVersion by lazy { expression.languageVersionSettings.apiVersion }
val actualConversions = conversionGroups[ConversionId(firstCalleeExpression, secondCalleeExpression)]?.filter {
it.replaceableApiVersion == null || apiVersion >= it.replaceableApiVersion
}?.sortedByDescending { it.removeNotNullAssertion } ?: return null
val context = expression.analyze()
val firstResolvedCall = firstExpression.getResolvedCall(context) ?: return null
val secondResolvedCall = expression.getResolvedCall(context) ?: return null
val conversion = actualConversions.firstOrNull {
firstResolvedCall.isCalling(FqName(it.firstFqName)) && additionalCallCheck(it, firstResolvedCall, secondResolvedCall, context)
} ?: return null
// Do not apply for lambdas with return inside
val lambdaArgument = firstCallExpression.lambdaArguments.firstOrNull()
if (lambdaArgument?.anyDescendantOfType<KtReturnExpression>() == true) return null
if (!secondResolvedCall.isCalling(FqName(conversion.secondFqName))) return null
if (secondResolvedCall.valueArguments.any { (parameter, resolvedArgument) ->
parameter.type.isFunctionOfAnyKind() &&
resolvedArgument !is DefaultValueArgument
}
) return null
return conversion
}
protected fun List<Conversion>.group(): Map<ConversionId, List<Conversion>> =
groupBy { conversion -> conversion.id }
data class ConversionId(val firstFqName: String, val secondFqName: String) {
constructor(first: KtExpression, second: KtExpression) : this(first.text, second.text)
}
data class Conversion(
@NonNls val firstFqName: String,
@NonNls val secondFqName: String,
@NonNls val replacement: String,
@NonNls val additionalArgument: String? = null,
val addNotNullAssertion: Boolean = false,
val enableSuspendFunctionCall: Boolean = true,
val removeNotNullAssertion: Boolean = false,
val replaceableApiVersion: ApiVersion? = null,
) {
private fun String.convertToShort() = takeLastWhile { it != '.' }
val id: ConversionId get() = ConversionId(firstName, secondName)
val firstName = firstFqName.convertToShort()
val secondName = secondFqName.convertToShort()
fun withArgument(argument: String) = Conversion(firstFqName, secondFqName, replacement, argument)
}
companion object {
fun KtQualifiedExpression.firstCalleeExpression(): KtExpression? {
val firstExpression = receiverExpression
val firstCallExpression = getCallExpression(firstExpression) ?: return null
return firstCallExpression.calleeExpression
}
fun getCallExpression(firstExpression: KtExpression) =
(firstExpression as? KtQualifiedExpression)?.selectorExpression as? KtCallExpression
?: firstExpression as? KtCallExpression
}
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/AbstractCallChainChecker.kt | 3288845781 |
// PROBLEM: none
fun foo(): Int? = null
fun test() : Int? {
return foo() <caret>?: return 1
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantElvisReturnNull/notReturnNull.kt | 3851383323 |
// "Replace with 'newFun(p1, p2, p3)'" "true"
interface I {
@Deprecated("", ReplaceWith("newFun(p1, p2, p3)"))
fun oldFun(p1: String, p2: Int = 0, p3: Int = 1)
fun newFun(p1: String, p2: Int = 1, p3: Int = 1)
}
abstract class C : I {
override fun newFun(p1: String, p2: Int, p3: Int) { }
}
fun foo(c: C) {
c.<caret>oldFun("")
}
| plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/optionalParameters/overridingMethod.kt | 1766241071 |
class Foo {
fun method(b: Boolean,
elementComputable: Computable<String>,
processingContext: Any): WeighingComparable<String, ProximityLocation> {
return weigh(WEIGHER_KEY, elementComputable, ProximityLocation())
}
companion object {
fun <T, Loc> <caret>weigh(
key: Key<out Weigher<T, Loc>>?, element: Computable<T>, location: Loc
): WeighingComparable<T, Loc> {
return WeighingComparable(element, location, Array<Weigher<*, *>>(0) { null!! })
}
val WEIGHER_KEY: Key<ProximityWeigher>? = null
}
}
abstract class ProximityWeigher : Weigher<String, ProximityLocation>()
class ProximityLocation
class Key<P>
open class Weigher<A, B>
class Computable<O>
class WeighingComparable<T, Loc>(element: Computable<T>, location: Loc, weighers: Array<Weigher<*, *>>) : Comparable<WeighingComparable<T, Loc>> {
override fun compareTo(other: WeighingComparable<T, Loc>): Int {
return 0
}
private fun getWeight(index: Int): Comparable<*>? {
return null
}
}
| plugins/kotlin/idea/tests/testData/refactoring/inline/namedFunction/fromIntellij/Substitution.kt | 1872289463 |
package com.kickstarter.ui.viewholders.discoverydrawer
import androidx.core.content.res.ResourcesCompat
import com.kickstarter.R
import com.kickstarter.databinding.DiscoveryDrawerChildFilterViewBinding
import com.kickstarter.libs.utils.ObjectUtils
import com.kickstarter.ui.adapters.data.NavigationDrawerData
import com.kickstarter.ui.viewholders.KSViewHolder
import timber.log.Timber
class ChildFilterViewHolder(
private val binding: DiscoveryDrawerChildFilterViewBinding,
private val delegate: Delegate
) : KSViewHolder(binding.root) {
private val ksString = requireNotNull(environment().ksString())
private var item: NavigationDrawerData.Section.Row? = null
interface Delegate {
fun childFilterViewHolderRowClick(viewHolder: ChildFilterViewHolder, row: NavigationDrawerData.Section.Row)
}
@Throws(Exception::class)
override fun bindData(data: Any?) {
item = ObjectUtils.requireNonNull(data as NavigationDrawerData.Section.Row?, NavigationDrawerData.Section.Row::class.java)
}
override fun onBind() {
val context = context()
val category = item?.params()?.category()
if (category?.isRoot == true) {
binding.filterTextView.text = item?.params()?.filterString(context, ksString)
} else {
binding.filterTextView.text = item?.params()?.filterString(context, ksString)
}
val textColor = if (item?.selected() == true)
context.resources.getColor(R.color.accent, null)
else
context.resources.getColor(R.color.kds_support_700, null)
val iconDrawable = if (item?.selected() == true)
ResourcesCompat.getDrawable(context.resources, R.drawable.ic_label_green, null)
else
ResourcesCompat.getDrawable(context.resources, R.drawable.ic_label, null)
val backgroundDrawable = if (item?.selected() == true)
ResourcesCompat.getDrawable(context.resources, R.drawable.drawer_selected, null)
else
null
binding.filterTextView.apply {
setCompoundDrawablesRelativeWithIntrinsicBounds(iconDrawable, null, null, null)
setTextColor(textColor)
background = backgroundDrawable
setOnClickListener {
textViewClick()
}
}
}
fun textViewClick() {
Timber.d("DiscoveryDrawerChildParamsViewHolder topFilterViewHolderRowClick")
item?.let { delegate.childFilterViewHolderRowClick(this, it) }
}
}
| app/src/main/java/com/kickstarter/ui/viewholders/discoverydrawer/ChildFilterViewHolder.kt | 2770991688 |
package com.habitrpg.android.habitica.ui.fragments.inventory.customization
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.databinding.FragmentAvatarOverviewBinding
import com.habitrpg.android.habitica.extensions.subscribeWithErrorHandler
import com.habitrpg.android.habitica.helpers.MainNavigationController
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment
import io.reactivex.functions.Consumer
class AvatarOverviewFragment : BaseMainFragment(), AdapterView.OnItemSelectedListener {
private lateinit var binding: FragmentAvatarOverviewBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
binding = FragmentAvatarOverviewBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.avatarSizeSpinner.onItemSelectedListener = this
binding.avatarShirtView.setOnClickListener { displayCustomizationFragment("shirt", null) }
binding.avatarSkinView.setOnClickListener { displayCustomizationFragment("skin", null) }
binding.avatarChairView.setOnClickListener { displayCustomizationFragment("chair", null) }
binding.avatarGlassesView.setOnClickListener { displayEquipmentFragment("eyewear", "glasses") }
binding.avatarAnimalEarsView.setOnClickListener { displayEquipmentFragment("headAccessory", "animal") }
binding.avatarAnimalTailView.setOnClickListener { displayEquipmentFragment("back", "animal") }
binding.avatarHeadbandView.setOnClickListener { displayEquipmentFragment("headAccessory", "headband") }
binding.avatarHairColorView.setOnClickListener { displayCustomizationFragment("hair", "color") }
binding.avatarHairBangsView.setOnClickListener { displayCustomizationFragment("hair", "bangs") }
binding.avatarHairBaseView.setOnClickListener { displayCustomizationFragment("hair", "base") }
binding.avatarAccentView.setOnClickListener { displayCustomizationFragment("hair", "flower") }
binding.avatarHairBeardView.setOnClickListener { displayCustomizationFragment("hair", "beard") }
binding.avatarHairMustacheView.setOnClickListener { displayCustomizationFragment("hair", "mustache") }
binding.avatarBackgroundView.setOnClickListener { displayCustomizationFragment("background", null) }
compositeSubscription.add(userRepository.getUser().subscribeWithErrorHandler(Consumer {
updateUser(it)
}))
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
private fun displayCustomizationFragment(type: String, category: String?) {
MainNavigationController.navigate(AvatarOverviewFragmentDirections.openAvatarDetail(type, category ?: ""))
}
private fun displayEquipmentFragment(type: String, category: String?) {
MainNavigationController.navigate(AvatarOverviewFragmentDirections.openAvatarEquipment(type, category ?: ""))
}
fun updateUser(user: User) {
this.setSize(user.preferences?.size)
setCustomizations(user)
}
private fun setCustomizations(user: User) {
binding.avatarShirtView.customizationIdentifier = user.preferences?.size + "_shirt_" + user.preferences?.shirt
binding.avatarSkinView.customizationIdentifier = "skin_" + user.preferences?.skin
val chair = user.preferences?.chair
binding.avatarChairView.customizationIdentifier = if (chair?.startsWith("handleless") == true) "chair_$chair" else chair
binding.avatarGlassesView.equipmentIdentifier = user.equipped?.eyeWear
binding.avatarAnimalEarsView.equipmentIdentifier = user.equipped?.headAccessory
binding.avatarHeadbandView.equipmentIdentifier = user.equipped?.headAccessory
binding.avatarAnimalTailView.equipmentIdentifier = user.equipped?.back
binding.avatarHairColorView.customizationIdentifier = if (user.preferences?.hair?.color != null && user.preferences?.hair?.color != "") "hair_bangs_1_" + user.preferences?.hair?.color else ""
binding.avatarHairBangsView.customizationIdentifier = if (user.preferences?.hair?.bangs != null && user.preferences?.hair?.bangs != 0) "hair_bangs_" + user.preferences?.hair?.bangs + "_" + user.preferences?.hair?.color else ""
binding.avatarHairBaseView.customizationIdentifier = if (user.preferences?.hair?.base != null && user.preferences?.hair?.base != 0) "hair_base_" + user.preferences?.hair?.base + "_" + user.preferences?.hair?.color else ""
binding.avatarAccentView.customizationIdentifier = if (user.preferences?.hair?.flower != null && user.preferences?.hair?.flower != 0) "hair_flower_" + user.preferences?.hair?.flower else ""
binding.avatarHairBeardView.customizationIdentifier = if (user.preferences?.hair?.beard != null && user.preferences?.hair?.beard != 0) "hair_beard_" + user.preferences?.hair?.beard + "_" + user.preferences?.hair?.color else ""
binding.avatarHairMustacheView.customizationIdentifier = if (user.preferences?.hair?.mustache != null && user.preferences?.hair?.mustache != 0) "hair_mustache_" + user.preferences?.hair?.mustache + "_" + user.preferences?.hair?.color else ""
binding.avatarBackgroundView.customizationIdentifier = "background_" + user.preferences?.background
}
private fun setSize(size: String?) {
if (size == null) {
return
}
if (size == "slim") {
binding.avatarSizeSpinner.setSelection(0, false)
} else {
binding.avatarSizeSpinner.setSelection(1, false)
}
}
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
val newSize: String = if (position == 0) "slim" else "broad"
if (this.user?.isValid == true && this.user?.preferences?.size != newSize) {
compositeSubscription.add(userRepository.updateUser(user, "preferences.size", newSize)
.subscribe(Consumer { }, RxErrorHandler.handleEmptyError()))
}
}
override fun onNothingSelected(parent: AdapterView<*>) { /* no-on */ }
}
| Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/inventory/customization/AvatarOverviewFragment.kt | 475502255 |
package com.cout970.modeler.controller.tasks
import com.cout970.modeler.Program
import com.cout970.modeler.api.model.`object`.RootGroupRef
import com.cout970.modeler.api.model.selection.ISelection
import com.cout970.modeler.util.Nullable
/**
* Created by cout970 on 2017/07/19.
*/
class TaskUpdateModelSelection(val oldSelection: Nullable<ISelection>,
val newSelection: Nullable<ISelection>) : IUndoableTask {
override fun run(state: Program) {
state.gui.programState.modelSelectionHandler.setSelection(newSelection)
state.projectManager.selectedGroup = RootGroupRef
}
override fun undo(state: Program) {
state.gui.programState.modelSelectionHandler.setSelection(oldSelection)
}
} | src/main/kotlin/com/cout970/modeler/controller/tasks/TaskUpdateModelSelection.kt | 2844722442 |
package ftl.api
import ftl.adapter.GoogleAndroidDeviceModel
import ftl.adapter.GoogleIosDeviceModel
val fetchDeviceModelAndroid: DeviceModel.Android.Fetch get() = GoogleAndroidDeviceModel
val fetchDeviceModelIos: DeviceModel.Ios.Fetch get() = GoogleIosDeviceModel
object DeviceModel {
data class Android(
val id: String,
val name: String,
val tags: List<String>,
val screenX: Int,
val screenY: Int,
val formFactor: String,
val screenDensity: Int,
val supportedVersionIds: List<String>,
val form: String,
val brand: String,
val codename: String,
val manufacturer: String,
val thumbnailUrl: String,
val supportedAbis: List<String>,
val lowFpsVideoRecording: Boolean,
) {
data class Available(
val list: List<Android>
)
interface Fetch : (String) -> Available
}
data class Ios(
val id: String,
val name: String,
val tags: List<String>,
val screenX: Int,
val screenY: Int,
val formFactor: String,
val screenDensity: Int,
val supportedVersionIds: List<String>,
val deviceCapabilities: List<String>,
) {
data class Available(
val list: List<Ios>
)
interface Fetch : (String) -> Available
}
}
| test_runner/src/main/kotlin/ftl/api/DeviceModels.kt | 1554795288 |
package ftl.adapter
import ftl.adapter.google.toApiModel
import ftl.api.Locale
import ftl.api.Platform
import ftl.client.google.AndroidCatalog
import ftl.client.google.IosCatalog
object GoogleLocalesFetch :
Locale.Fetch,
(Locale.Identity) -> List<Locale> by { id ->
when (id.platform) {
Platform.ANDROID -> AndroidCatalog.getLocales(id.projectId).toApiModel()
Platform.IOS -> IosCatalog.getLocales(id.projectId).toApiModel()
}
}
| test_runner/src/main/kotlin/ftl/adapter/GoogleLocalesFetch.kt | 796685469 |
package com.kickstarter.libs
object ActivityRequestCodes {
const val LOGIN_FLOW = 5921
const val RESET_FLOW = 5922
const val CHECKOUT_ACTIVITY_WALLET_REQUEST = 59210
const val CHECKOUT_ACTIVITY_WALLET_CHANGE_REQUEST = 59211
const val CHECKOUT_ACTIVITY_WALLET_OBTAINED_FULL = 59212
const val SAVE_NEW_PAYMENT_METHOD = 59213
const val SHOW_REWARDS = 59214
}
| app/src/main/java/com/kickstarter/libs/ActivityRequestCodes.kt | 165043712 |
package a
inline fun a(body: () -> Unit) {
println("i'm inline function")
body()
}
| plugins/kotlin/jps/jps-plugin/tests/testData/incremental/multiModule/common/transitiveInlining/module1_a.kt | 3483676362 |
import java.io.File
val v = File::<caret>
// EXIST_JAVA_ONLY: { itemText: "getFreeSpace", tailText: "()", attributes: "bold" }
// ABSENT: freeSpace
// EXIST_JAVA_ONLY: { itemText: "isFile", tailText: "()", attributes: "bold" }
// ABSENT: { itemText: "isFile", tailText: " (from isFile())" }
| plugins/kotlin/completion/tests/testData/basic/common/callableReference/SyntheticExtensions.kt | 3897080723 |
// WITH_RUNTIME
fun foo(s: String) {
s.substring<caret>(0, s.indexOf('x'))
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceSubstring/withSubstringBefore/replaceWithSubstringBefore.kt | 722500369 |
// 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.refactoring.introduce.introduceParameter
import com.intellij.openapi.command.impl.FinishMarkAction
import com.intellij.openapi.command.impl.StartMarkAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.refactoring.ui.NameSuggestionsField
import com.intellij.refactoring.ui.RefactoringDialog
import com.intellij.ui.NonFocusableCheckBox
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.core.util.isMultiLine
import org.jetbrains.kotlin.idea.refactoring.introduce.extractFunction.ui.ExtractFunctionParameterTablePanel
import org.jetbrains.kotlin.idea.refactoring.introduce.extractFunction.ui.KotlinExtractFunctionDialog
import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.*
import org.jetbrains.kotlin.idea.refactoring.validateElement
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.application.executeCommand
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded
import org.jetbrains.kotlin.types.KotlinType
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import java.awt.Insets
import java.util.*
import javax.swing.JCheckBox
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
class KotlinIntroduceParameterDialog private constructor(
project: Project,
val editor: Editor,
val descriptor: IntroduceParameterDescriptor,
val lambdaExtractionDescriptor: ExtractableCodeDescriptor?,
nameSuggestions: Array<String>,
typeSuggestions: List<KotlinType>,
val helper: KotlinIntroduceParameterHelper
) : RefactoringDialog(project, true) {
constructor(
project: Project,
editor: Editor,
descriptor: IntroduceParameterDescriptor,
nameSuggestions: Array<String>,
typeSuggestions: List<KotlinType>,
helper: KotlinIntroduceParameterHelper
) : this(project, editor, descriptor, null, nameSuggestions, typeSuggestions, helper)
constructor(
project: Project,
editor: Editor,
introduceParameterDescriptor: IntroduceParameterDescriptor,
lambdaExtractionDescriptor: ExtractableCodeDescriptor,
helper: KotlinIntroduceParameterHelper
) : this(
project,
editor,
introduceParameterDescriptor,
lambdaExtractionDescriptor,
lambdaExtractionDescriptor.suggestedNames.toTypedArray(),
listOf(lambdaExtractionDescriptor.returnType),
helper
)
private val typeNameSuggestions =
typeSuggestions.map { IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(it) }.toTypedArray()
private val nameField = NameSuggestionsField(nameSuggestions, project, KotlinFileType.INSTANCE)
private val typeField = NameSuggestionsField(typeNameSuggestions, project, KotlinFileType.INSTANCE)
private var replaceAllCheckBox: JCheckBox? = null
private var defaultValueCheckBox: JCheckBox? = null
private val removeParamsCheckBoxes = LinkedHashMap<JCheckBox, KtElement>(descriptor.parametersToRemove.size)
private var parameterTablePanel: ExtractFunctionParameterTablePanel? = null
private val commandName = if (lambdaExtractionDescriptor != null) INTRODUCE_LAMBDA_PARAMETER else INTRODUCE_PARAMETER
init {
title = commandName
init()
nameField.addDataChangedListener { validateButtons() }
typeField.addDataChangedListener { validateButtons() }
}
override fun getPreferredFocusedComponent() = nameField.focusableComponent
private fun updateRemoveParamCheckBoxes() {
val enableParamRemove = (replaceAllCheckBox?.isSelected ?: true) && (!defaultValueCheckBox!!.isSelected)
removeParamsCheckBoxes.keys.forEach {
it.isEnabled = enableParamRemove
it.isSelected = enableParamRemove
}
}
override fun createNorthPanel(): JComponent? {
val gbConstraints = GridBagConstraints()
val panel = JPanel(GridBagLayout())
gbConstraints.anchor = GridBagConstraints.WEST
gbConstraints.fill = GridBagConstraints.NONE
gbConstraints.gridx = 0
gbConstraints.insets = Insets(4, 4, 4, 0)
gbConstraints.gridwidth = 1
gbConstraints.weightx = 0.0
gbConstraints.weighty = 0.0
gbConstraints.gridy = 0
val nameLabel = JLabel(KotlinBundle.message("text.parameter.name"))
nameLabel.labelFor = nameField
panel.add(nameLabel, gbConstraints)
gbConstraints.insets = Insets(4, 4, 4, 8)
gbConstraints.gridx++
gbConstraints.weightx = 1.0
gbConstraints.fill = GridBagConstraints.BOTH
panel.add(nameField, gbConstraints)
gbConstraints.insets = Insets(4, 4, 4, 8)
gbConstraints.gridwidth = 1
gbConstraints.weightx = 0.0
gbConstraints.gridx = 0
gbConstraints.gridy++
gbConstraints.fill = GridBagConstraints.NONE
val typeLabel = JLabel(
if (lambdaExtractionDescriptor != null)
KotlinBundle.message("text.lambda.return.type")
else
KotlinBundle.message("text.parameter.type")
)
typeLabel.labelFor = typeField
panel.add(typeLabel, gbConstraints)
gbConstraints.gridx++
gbConstraints.insets = Insets(4, 4, 4, 8)
gbConstraints.weightx = 1.0
gbConstraints.fill = GridBagConstraints.BOTH
panel.add(typeField, gbConstraints)
if (lambdaExtractionDescriptor != null && (lambdaExtractionDescriptor.parameters
.isNotEmpty() || lambdaExtractionDescriptor.receiverParameter != null)
) {
val parameterTablePanel = object : ExtractFunctionParameterTablePanel() {
override fun onEnterAction() {
doOKAction()
}
override fun onCancelAction() {
doCancelAction()
}
}
parameterTablePanel.init(lambdaExtractionDescriptor.receiverParameter, lambdaExtractionDescriptor.parameters)
gbConstraints.insets = Insets(4, 4, 4, 8)
gbConstraints.gridwidth = 1
gbConstraints.weightx = 0.0
gbConstraints.gridx = 0
gbConstraints.gridy++
gbConstraints.fill = GridBagConstraints.NONE
val parametersLabel = JLabel(KotlinBundle.message("text.lambda.parameters"))
parametersLabel.labelFor = parameterTablePanel
panel.add(parametersLabel, gbConstraints)
gbConstraints.gridx++
gbConstraints.insets = Insets(4, 4, 4, 8)
gbConstraints.weightx = 1.0
gbConstraints.fill = GridBagConstraints.BOTH
panel.add(parameterTablePanel, gbConstraints)
this.parameterTablePanel = parameterTablePanel
}
gbConstraints.fill = GridBagConstraints.HORIZONTAL
gbConstraints.gridx = 0
gbConstraints.insets = Insets(4, 0, 4, 8)
gbConstraints.gridwidth = 2
gbConstraints.gridy++
val defaultValueCheckBox = NonFocusableCheckBox(KotlinBundle.message("text.introduce.default.value"))
defaultValueCheckBox.isSelected = descriptor.withDefaultValue
defaultValueCheckBox.addActionListener { updateRemoveParamCheckBoxes() }
panel.add(defaultValueCheckBox, gbConstraints)
this.defaultValueCheckBox = defaultValueCheckBox
val occurrenceCount = descriptor.occurrencesToReplace.size
if (occurrenceCount > 1) {
gbConstraints.gridy++
val replaceAllCheckBox = NonFocusableCheckBox(
KotlinBundle.message("checkbox.text.replace.all.occurrences.0", occurrenceCount)
)
replaceAllCheckBox.isSelected = true
replaceAllCheckBox.addActionListener { updateRemoveParamCheckBoxes() }
panel.add(replaceAllCheckBox, gbConstraints)
this.replaceAllCheckBox = replaceAllCheckBox
}
if (replaceAllCheckBox != null) {
gbConstraints.insets = Insets(0, 16, 4, 8)
}
for (parameter in descriptor.parametersToRemove) {
val removeWhat = if (parameter is KtParameter)
KotlinBundle.message("text.parameter.0", parameter.name.toString())
else
KotlinBundle.message("text.receiver")
val cb = NonFocusableCheckBox(
KotlinBundle.message("text.remove.0.no.longer.used", removeWhat)
)
removeParamsCheckBoxes[cb] = parameter
cb.isSelected = true
gbConstraints.gridy++
panel.add(cb, gbConstraints)
}
return panel
}
override fun createCenterPanel() = null
override fun canRun() {
val psiFactory = KtPsiFactory(myProject)
psiFactory.createExpressionIfPossible(nameField.enteredName.quoteIfNeeded()).validateElement(
KotlinBundle.message("error.text.invalid.parameter.name"))
psiFactory.createTypeIfPossible(typeField.enteredName).validateElement(
KotlinBundle.message("error.text.invalid.parameter.type"))
}
override fun doAction() {
performRefactoring()
}
fun performRefactoring() {
close(DialogWrapper.OK_EXIT_CODE)
project.executeCommand(commandName) {
fun createLambdaForArgument(function: KtFunction): KtExpression {
val statement = function.bodyBlockExpression!!.statements.single()
val space = if (statement.isMultiLine()) "\n" else " "
val parameters = function.valueParameters
val parametersText = if (parameters.isNotEmpty()) {
" " + parameters.asSequence().map { it.name }.joinToString() + " ->"
} else ""
val text = "{$parametersText$space${statement.text}$space}"
return KtPsiFactory(myProject).createExpression(text)
}
val chosenName = nameField.enteredName.quoteIfNeeded()
var chosenType = typeField.enteredName
var newArgumentValue = descriptor.newArgumentValue
var newReplacer = descriptor.occurrenceReplacer
val startMarkAction = StartMarkAction.start(editor, myProject, [email protected])
lambdaExtractionDescriptor?.let { oldDescriptor ->
val newDescriptor = KotlinExtractFunctionDialog.createNewDescriptor(
oldDescriptor,
chosenName,
null,
parameterTablePanel?.selectedReceiverInfo,
parameterTablePanel?.selectedParameterInfos ?: listOf(),
null
)
val options = ExtractionGeneratorOptions.DEFAULT.copy(
target = ExtractionTarget.FAKE_LAMBDALIKE_FUNCTION,
allowExpressionBody = false
)
runWriteAction {
with(ExtractionGeneratorConfiguration(newDescriptor, options).generateDeclaration()) {
val function = declaration as KtFunction
val receiverType = function.receiverTypeReference?.text
val parameterTypes = function
.valueParameters.joinToString { it.typeReference!!.text }
val returnType = function.typeReference?.text ?: "Unit"
chosenType = (receiverType?.let { "$it." } ?: "") + "($parameterTypes) -> $returnType"
if (KtTokens.SUSPEND_KEYWORD in newDescriptor.modifiers) {
chosenType = "${KtTokens.SUSPEND_KEYWORD} $chosenType"
}
newArgumentValue = createLambdaForArgument(function)
newReplacer = { }
processDuplicates(duplicateReplacers, myProject, editor)
}
}
}
val descriptorToRefactor = descriptor.copy(
newParameterName = chosenName,
newParameterTypeText = chosenType,
argumentValue = newArgumentValue,
withDefaultValue = defaultValueCheckBox!!.isSelected,
occurrencesToReplace = with(descriptor) {
if (replaceAllCheckBox?.isSelected != false) {
occurrencesToReplace
} else {
Collections.singletonList(originalOccurrence)
}
},
parametersToRemove = removeParamsCheckBoxes.filter { it.key.isEnabled && it.key.isSelected }.map { it.value },
occurrenceReplacer = newReplacer
)
helper.configure(descriptorToRefactor).performRefactoring(
editor,
onExit = { FinishMarkAction.finish(myProject, editor, startMarkAction) }
)
}
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinIntroduceParameterDialog.kt | 539421320 |
/**
* Copyright 2017 Stealth2800 <http://stealthyone.com/>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stealthyone.mcml2
import org.bukkit.Bukkit
import org.bukkit.inventory.ItemStack
import java.lang.Exception
import java.lang.reflect.Method
/**
* Handles the conversion of a Bukkit ItemStack to JSON via reflection.
*/
object BukkitItemJsonSerializer : JsonSerializer(ItemStack::class.java) {
private const val FAIL_MESSAGE = "(failed to convert item to JSON)"
/**
* Serializes an ItemStack to JSON via reflection.
*
* This method will not throw an exception on failure. Rather, it will return [FAIL_MESSAGE].
*/
override fun serialize(obj: Any): String {
val item = obj as ItemStack
// NMS ItemStack
val nmsItem = cb_CraftItemStack_asNMSCopy?.invoke(null, item)
?: return FAIL_MESSAGE
// Empty NBTTagCompound
val compound = nms_NBTTagCompound?.newInstance()
?: return FAIL_MESSAGE
// Save ItemStack to compound and call toString to convert to JSON
return nms_ItemStack_save?.invoke(nmsItem, compound)?.toString()
?: FAIL_MESSAGE
}
//region Reflection Utilities
private fun getBukkitVersion(): String {
return Bukkit.getServer().javaClass.canonicalName.split(".")[3]
}
private fun getNMSClassName(name: String): String {
return "net.minecraft.server.${getBukkitVersion()}.$name"
}
private fun getNMSClass(name: String): Class<*> = Class.forName(getNMSClassName(name))
private fun getCBClassName(name: String): String {
return "org.bukkit.craftbukkit.${getBukkitVersion()}.$name"
}
private fun getCBClass(name: String): Class<*> = Class.forName(getCBClassName(name))
//endregion
//region Reflection Classes and Methods
private val cb_CraftItemStack_asNMSCopy: Method? by lazy {
try {
getCBClass("inventory.CraftItemStack").getMethod("asNMSCopy", ItemStack::class.java)
} catch (ex: Exception) {
ex.printStackTrace()
null
}
}
private val nms_NBTTagCompound: Class<*>? by lazy {
try {
getNMSClass("NBTTagCompound")
} catch (ex: Exception) {
ex.printStackTrace()
null
}
}
private val nms_ItemStack: Class<*>? by lazy {
try {
getNMSClass("ItemStack")
} catch (ex: Exception) {
ex.printStackTrace()
null
}
}
private val nms_ItemStack_save: Method? by lazy {
try {
nms_ItemStack?.getMethod("save", nms_NBTTagCompound)
} catch (ex: Exception) {
ex.printStackTrace()
null
}
}
//endregion
}
| src/main/kotlin/com/stealthyone/mcml2/BukkitJsonSerializer.kt | 1389373677 |
// COMPILER_ARGUMENTS: -XXLanguage:+NewInference
// IS_APPLICABLE: false
interface List<T>
class ArrayList<T> : List<T>
fun test() {
val list: List<*> = ArrayList<caret><Any?>()
} | plugins/kotlin/idea/tests/testData/intentions/removeExplicitTypeArguments/kt31441.kt | 1980083753 |
/*
* Copyright 2010-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 runtime.workers.freeze2
import kotlin.test.*
import kotlin.native.concurrent.*
data class Data(var int: Int)
@Test fun runTest() {
// Ensure that we can not mutate frozen objects and arrays.
val a0 = Data(2)
a0.int++
a0.freeze()
assertFailsWith<InvalidMutabilityException> {a0.int++ }
val a1 = ByteArray(2)
a1[1]++
a1.freeze()
assertFailsWith<InvalidMutabilityException> { a1[1]++ }
val a2 = ShortArray(2)
a2[1]++
a2.freeze()
assertFailsWith<InvalidMutabilityException> { a2[1]++ }
val a3 = IntArray(2)
a3[1]++
a3.freeze()
assertFailsWith<InvalidMutabilityException> { a3[1]++ }
val a4 = LongArray(2)
a4[1]++
a4.freeze()
assertFailsWith<InvalidMutabilityException> { a4[1]++ }
val a5 = BooleanArray(2)
a5[1] = true
a5.freeze()
assertFailsWith<InvalidMutabilityException> { a5[1] = false }
val a6 = CharArray(2)
a6[1] = 'a'
a6.freeze()
assertFailsWith<InvalidMutabilityException> { a6[1] = 'b' }
val a7 = FloatArray(2)
a7[1] = 1.0f
a7.freeze()
assertFailsWith<InvalidMutabilityException> { a7[1] = 2.0f }
val a8 = DoubleArray(2)
a8[1] = 1.0
a8.freeze()
assertFailsWith<InvalidMutabilityException> { a8[1] = 2.0 }
// Ensure that String and integral boxes are frozen by default, by passing local to the worker.
val worker = Worker.start()
var data: Any = "Hello" + " " + "world"
assert(data.isFrozen)
worker.execute(TransferMode.SAFE, { data } ) {
input -> println("Worker 1: $input")
}.result
data = 42
assert(data.isFrozen)
worker.execute(TransferMode.SAFE, { data } ) {
input -> println("Worker2: $input")
}.result
data = 239.0
assert(data.isFrozen)
worker.execute(TransferMode.SAFE, { data } ) {
input -> println("Worker3: $input")
}.result
data = 'a'
assert(data.isFrozen)
worker.execute(TransferMode.SAFE, { data } ) {
input -> println("Worker4: $input")
}.result
worker.requestTermination().result
println("OK")
} | backend.native/tests/runtime/workers/freeze2.kt | 3350024867 |
/*
* Copyright 2010-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 codegen.function.defaults9
import kotlin.test.*
class Foo {
inner class Bar(x: Int, val y: Int = 1) {
constructor() : this(42)
}
}
@Test fun runTest() = println(Foo().Bar().y)
| backend.native/tests/codegen/function/defaults9.kt | 3286512573 |
// 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.navigation
import com.intellij.openapi.editor.markup.TextAttributes
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
import java.awt.Color
import javax.swing.Icon
/**
* Represents presentation in target popup as follows:
* ```
* | $icon$ $presentableText$ $containerText$ spacer $locationText$ $locationIcon$ |
* ```
* Elements before spacer are aligned to the left, right text and right icon are aligned to the right.
*/
@ApiStatus.Experimental
@ApiStatus.NonExtendable
interface TargetPresentation {
companion object {
@JvmStatic
fun builder(@Nls presentableText: String): TargetPresentationBuilder {
return SymbolNavigationService.getInstance().presentationBuilder(presentableText)
}
/**
* @return a builder instance initialized from existing [presentation]
*/
@JvmStatic
fun builder(presentation: TargetPresentation): TargetPresentationBuilder {
// the only implementation is also a builder
return presentation as TargetPresentationBuilder
}
}
val backgroundColor: Color?
val icon: Icon?
val presentableText: @Nls String
/**
* Attributes to highlight [presentableText]
*/
val presentableTextAttributes: TextAttributes?
/**
* Presentable text of a container, e.g. containing class name for a method, or a parent directory name for a file
*/
val containerText: @Nls String?
/**
* Attributes to highlight [containerText]
*/
val containerTextAttributes: TextAttributes?
/**
* Presentable text of a location, e.g. a containing module, or a library, or an SDK
*/
val locationText: @Nls String?
/**
* Icon of a location, e.g. a containing module, or a library, or an SDK
*/
val locationIcon: Icon?
}
| platform/core-api/src/com/intellij/navigation/TargetPresentation.kt | 700191715 |
/*
* Copyright (C) 2015 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 okhttp3
import java.net.URI
import java.net.URL
import kotlin.test.assertFailsWith
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.UrlComponentEncodingTester.Encoding
import okhttp3.testing.PlatformRule
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
@Suppress("HttpUrlsUsage") // Don't warn if we should be using https://.
open class HttpUrlTest {
val platform = PlatformRule()
protected open fun parse(url: String): HttpUrl {
return url.toHttpUrl()
}
protected open fun assertInvalid(string: String, exceptionMessage: String?) {
assertThat(string.toHttpUrlOrNull()).overridingErrorMessage(string).isNull()
}
@Test
fun parseTrimsAsciiWhitespace() {
val expected = parse("http://host/")
// Leading.
assertThat(parse("http://host/\u000c\n\t \r")).isEqualTo(expected)
// Trailing.
assertThat(parse("\r\n\u000c \thttp://host/")).isEqualTo(expected)
// Both.
assertThat(parse(" http://host/ ")).isEqualTo(expected)
// Both.
assertThat(parse(" http://host/ ")).isEqualTo(expected)
assertThat(parse("http://host/").resolve(" ")).isEqualTo(expected)
assertThat(parse("http://host/").resolve(" . ")).isEqualTo(expected)
}
@Test
fun parseHostAsciiNonPrintable() {
val host = "host\u0001"
assertInvalid("http://$host/", "Invalid URL host: \"host\u0001\"")
// TODO make exception message escape non-printable characters
}
@Test
fun parseDoesNotTrimOtherWhitespaceCharacters() {
// Whitespace characters list from Google's Guava team: http://goo.gl/IcR9RD
// line tabulation
assertThat(parse("http://h/\u000b").encodedPath).isEqualTo("/%0B")
// information separator 4
assertThat(parse("http://h/\u001c").encodedPath).isEqualTo("/%1C")
// information separator 3
assertThat(parse("http://h/\u001d").encodedPath).isEqualTo("/%1D")
// information separator 2
assertThat(parse("http://h/\u001e").encodedPath).isEqualTo("/%1E")
// information separator 1
assertThat(parse("http://h/\u001f").encodedPath).isEqualTo("/%1F")
// next line
assertThat(parse("http://h/\u0085").encodedPath).isEqualTo("/%C2%85")
// non-breaking space
assertThat(parse("http://h/\u00a0").encodedPath).isEqualTo("/%C2%A0")
// ogham space mark
assertThat(parse("http://h/\u1680").encodedPath).isEqualTo("/%E1%9A%80")
// mongolian vowel separator
assertThat(parse("http://h/\u180e").encodedPath).isEqualTo("/%E1%A0%8E")
// en quad
assertThat(parse("http://h/\u2000").encodedPath).isEqualTo("/%E2%80%80")
// em quad
assertThat(parse("http://h/\u2001").encodedPath).isEqualTo("/%E2%80%81")
// en space
assertThat(parse("http://h/\u2002").encodedPath).isEqualTo("/%E2%80%82")
// em space
assertThat(parse("http://h/\u2003").encodedPath).isEqualTo("/%E2%80%83")
// three-per-em space
assertThat(parse("http://h/\u2004").encodedPath).isEqualTo("/%E2%80%84")
// four-per-em space
assertThat(parse("http://h/\u2005").encodedPath).isEqualTo("/%E2%80%85")
// six-per-em space
assertThat(parse("http://h/\u2006").encodedPath).isEqualTo("/%E2%80%86")
// figure space
assertThat(parse("http://h/\u2007").encodedPath).isEqualTo("/%E2%80%87")
// punctuation space
assertThat(parse("http://h/\u2008").encodedPath).isEqualTo("/%E2%80%88")
// thin space
assertThat(parse("http://h/\u2009").encodedPath).isEqualTo("/%E2%80%89")
// hair space
assertThat(parse("http://h/\u200a").encodedPath).isEqualTo("/%E2%80%8A")
// zero-width space
assertThat(parse("http://h/\u200b").encodedPath).isEqualTo("/%E2%80%8B")
// zero-width non-joiner
assertThat(parse("http://h/\u200c").encodedPath).isEqualTo("/%E2%80%8C")
// zero-width joiner
assertThat(parse("http://h/\u200d").encodedPath).isEqualTo("/%E2%80%8D")
// left-to-right mark
assertThat(parse("http://h/\u200e").encodedPath).isEqualTo("/%E2%80%8E")
// right-to-left mark
assertThat(parse("http://h/\u200f").encodedPath).isEqualTo("/%E2%80%8F")
// line separator
assertThat(parse("http://h/\u2028").encodedPath).isEqualTo("/%E2%80%A8")
// paragraph separator
assertThat(parse("http://h/\u2029").encodedPath).isEqualTo("/%E2%80%A9")
// narrow non-breaking space
assertThat(parse("http://h/\u202f").encodedPath).isEqualTo("/%E2%80%AF")
// medium mathematical space
assertThat(parse("http://h/\u205f").encodedPath).isEqualTo("/%E2%81%9F")
// ideographic space
assertThat(parse("http://h/\u3000").encodedPath).isEqualTo("/%E3%80%80")
}
@Test
fun scheme() {
assertThat(parse("http://host/")).isEqualTo(parse("http://host/"))
assertThat(parse("Http://host/")).isEqualTo(parse("http://host/"))
assertThat(parse("http://host/")).isEqualTo(parse("http://host/"))
assertThat(parse("HTTP://host/")).isEqualTo(parse("http://host/"))
assertThat(parse("https://host/")).isEqualTo(parse("https://host/"))
assertThat(parse("HTTPS://host/")).isEqualTo(parse("https://host/"))
assertInvalid(
"image640://480.png",
"Expected URL scheme 'http' or 'https' but was 'image640'"
)
assertInvalid("httpp://host/", "Expected URL scheme 'http' or 'https' but was 'httpp'")
assertInvalid(
"0ttp://host/",
"Expected URL scheme 'http' or 'https' but no scheme was found for 0ttp:/..."
)
assertInvalid("ht+tp://host/", "Expected URL scheme 'http' or 'https' but was 'ht+tp'")
assertInvalid("ht.tp://host/", "Expected URL scheme 'http' or 'https' but was 'ht.tp'")
assertInvalid("ht-tp://host/", "Expected URL scheme 'http' or 'https' but was 'ht-tp'")
assertInvalid("ht1tp://host/", "Expected URL scheme 'http' or 'https' but was 'ht1tp'")
assertInvalid("httpss://host/", "Expected URL scheme 'http' or 'https' but was 'httpss'")
}
@Test
fun parseNoScheme() {
assertInvalid(
"//host",
"Expected URL scheme 'http' or 'https' but no scheme was found for //host"
)
assertInvalid(
"://host",
"Expected URL scheme 'http' or 'https' but no scheme was found for ://hos..."
)
assertInvalid(
"/path",
"Expected URL scheme 'http' or 'https' but no scheme was found for /path"
)
assertInvalid(
"path",
"Expected URL scheme 'http' or 'https' but no scheme was found for path"
)
assertInvalid(
"?query",
"Expected URL scheme 'http' or 'https' but no scheme was found for ?query"
)
assertInvalid(
"#fragment",
"Expected URL scheme 'http' or 'https' but no scheme was found for #fragm..."
)
}
@Test
fun newBuilderResolve() {
// Non-exhaustive tests because implementation is the same as resolve.
val base = parse("http://host/a/b")
assertThat(base.newBuilder("https://host2")!!.build())
.isEqualTo(parse("https://host2/"))
assertThat(base.newBuilder("//host2")!!.build())
.isEqualTo(parse("http://host2/"))
assertThat(base.newBuilder("/path")!!.build())
.isEqualTo(parse("http://host/path"))
assertThat(base.newBuilder("path")!!.build())
.isEqualTo(parse("http://host/a/path"))
assertThat(base.newBuilder("?query")!!.build())
.isEqualTo(parse("http://host/a/b?query"))
assertThat(base.newBuilder("#fragment")!!.build())
.isEqualTo(parse("http://host/a/b#fragment"))
assertThat(base.newBuilder("")!!.build()).isEqualTo(parse("http://host/a/b"))
assertThat(base.newBuilder("ftp://b")).isNull()
assertThat(base.newBuilder("ht+tp://b")).isNull()
assertThat(base.newBuilder("ht-tp://b")).isNull()
assertThat(base.newBuilder("ht.tp://b")).isNull()
}
@Test
fun redactedUrl() {
val baseWithPasswordAndUsername = parse("http://username:password@host/a/b#fragment")
val baseWithUsernameOnly = parse("http://username@host/a/b#fragment")
val baseWithPasswordOnly = parse("http://password@host/a/b#fragment")
assertThat(baseWithPasswordAndUsername.redact()).isEqualTo("http://host/...")
assertThat(baseWithUsernameOnly.redact()).isEqualTo("http://host/...")
assertThat(baseWithPasswordOnly.redact()).isEqualTo("http://host/...")
}
@Test
fun resolveNoScheme() {
val base = parse("http://host/a/b")
assertThat(base.resolve("//host2")).isEqualTo(parse("http://host2/"))
assertThat(base.resolve("/path")).isEqualTo(parse("http://host/path"))
assertThat(base.resolve("path")).isEqualTo(parse("http://host/a/path"))
assertThat(base.resolve("?query")).isEqualTo(parse("http://host/a/b?query"))
assertThat(base.resolve("#fragment"))
.isEqualTo(parse("http://host/a/b#fragment"))
assertThat(base.resolve("")).isEqualTo(parse("http://host/a/b"))
assertThat(base.resolve("\\path")).isEqualTo(parse("http://host/path"))
}
@Test
fun resolveUnsupportedScheme() {
val base = parse("http://a/")
assertThat(base.resolve("ftp://b")).isNull()
assertThat(base.resolve("ht+tp://b")).isNull()
assertThat(base.resolve("ht-tp://b")).isNull()
assertThat(base.resolve("ht.tp://b")).isNull()
}
@Test
fun resolveSchemeLikePath() {
val base = parse("http://a/")
assertThat(base.resolve("http//b/")).isEqualTo(parse("http://a/http//b/"))
assertThat(base.resolve("ht+tp//b/")).isEqualTo(parse("http://a/ht+tp//b/"))
assertThat(base.resolve("ht-tp//b/")).isEqualTo(parse("http://a/ht-tp//b/"))
assertThat(base.resolve("ht.tp//b/")).isEqualTo(parse("http://a/ht.tp//b/"))
}
/**
* https://tools.ietf.org/html/rfc3986#section-5.4.1
*/
@Test
fun rfc3886NormalExamples() {
val url = parse("http://a/b/c/d;p?q")
// No 'g:' scheme in HttpUrl.
assertThat(url.resolve("g:h")).isNull()
assertThat(url.resolve("g")).isEqualTo(parse("http://a/b/c/g"))
assertThat(url.resolve("./g")).isEqualTo(parse("http://a/b/c/g"))
assertThat(url.resolve("g/")).isEqualTo(parse("http://a/b/c/g/"))
assertThat(url.resolve("/g")).isEqualTo(parse("http://a/g"))
assertThat(url.resolve("//g")).isEqualTo(parse("http://g"))
assertThat(url.resolve("?y")).isEqualTo(parse("http://a/b/c/d;p?y"))
assertThat(url.resolve("g?y")).isEqualTo(parse("http://a/b/c/g?y"))
assertThat(url.resolve("#s")).isEqualTo(parse("http://a/b/c/d;p?q#s"))
assertThat(url.resolve("g#s")).isEqualTo(parse("http://a/b/c/g#s"))
assertThat(url.resolve("g?y#s")).isEqualTo(parse("http://a/b/c/g?y#s"))
assertThat(url.resolve(";x")).isEqualTo(parse("http://a/b/c/;x"))
assertThat(url.resolve("g;x")).isEqualTo(parse("http://a/b/c/g;x"))
assertThat(url.resolve("g;x?y#s")).isEqualTo(parse("http://a/b/c/g;x?y#s"))
assertThat(url.resolve("")).isEqualTo(parse("http://a/b/c/d;p?q"))
assertThat(url.resolve(".")).isEqualTo(parse("http://a/b/c/"))
assertThat(url.resolve("./")).isEqualTo(parse("http://a/b/c/"))
assertThat(url.resolve("..")).isEqualTo(parse("http://a/b/"))
assertThat(url.resolve("../")).isEqualTo(parse("http://a/b/"))
assertThat(url.resolve("../g")).isEqualTo(parse("http://a/b/g"))
assertThat(url.resolve("../..")).isEqualTo(parse("http://a/"))
assertThat(url.resolve("../../")).isEqualTo(parse("http://a/"))
assertThat(url.resolve("../../g")).isEqualTo(parse("http://a/g"))
}
/**
* https://tools.ietf.org/html/rfc3986#section-5.4.2
*/
@Test
fun rfc3886AbnormalExamples() {
val url = parse("http://a/b/c/d;p?q")
assertThat(url.resolve("../../../g")).isEqualTo(parse("http://a/g"))
assertThat(url.resolve("../../../../g")).isEqualTo(parse("http://a/g"))
assertThat(url.resolve("/./g")).isEqualTo(parse("http://a/g"))
assertThat(url.resolve("/../g")).isEqualTo(parse("http://a/g"))
assertThat(url.resolve("g.")).isEqualTo(parse("http://a/b/c/g."))
assertThat(url.resolve(".g")).isEqualTo(parse("http://a/b/c/.g"))
assertThat(url.resolve("g..")).isEqualTo(parse("http://a/b/c/g.."))
assertThat(url.resolve("..g")).isEqualTo(parse("http://a/b/c/..g"))
assertThat(url.resolve("./../g")).isEqualTo(parse("http://a/b/g"))
assertThat(url.resolve("./g/.")).isEqualTo(parse("http://a/b/c/g/"))
assertThat(url.resolve("g/./h")).isEqualTo(parse("http://a/b/c/g/h"))
assertThat(url.resolve("g/../h")).isEqualTo(parse("http://a/b/c/h"))
assertThat(url.resolve("g;x=1/./y")).isEqualTo(parse("http://a/b/c/g;x=1/y"))
assertThat(url.resolve("g;x=1/../y")).isEqualTo(parse("http://a/b/c/y"))
assertThat(url.resolve("g?y/./x")).isEqualTo(parse("http://a/b/c/g?y/./x"))
assertThat(url.resolve("g?y/../x")).isEqualTo(parse("http://a/b/c/g?y/../x"))
assertThat(url.resolve("g#s/./x")).isEqualTo(parse("http://a/b/c/g#s/./x"))
assertThat(url.resolve("g#s/../x")).isEqualTo(parse("http://a/b/c/g#s/../x"))
// "http:g" also okay.
assertThat(url.resolve("http:g")).isEqualTo(parse("http://a/b/c/g"))
}
@Test
fun parseAuthoritySlashCountDoesntMatter() {
assertThat(parse("http:host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(parse("http:/host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(parse("http:\\host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(parse("http://host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(parse("http:\\/host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(parse("http:/\\host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(parse("http:\\\\host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(parse("http:///host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(parse("http:\\//host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(parse("http:/\\/host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(parse("http://\\host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(parse("http:\\\\/host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(parse("http:/\\\\host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(parse("http:\\\\\\host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(parse("http:////host/path"))
.isEqualTo(parse("http://host/path"))
}
@Test
fun resolveAuthoritySlashCountDoesntMatterWithDifferentScheme() {
val base = parse("https://a/b/c")
assertThat(base.resolve("http:host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http:/host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http:\\host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http://host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http:\\/host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http:/\\host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http:\\\\host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http:///host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http:\\//host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http:/\\/host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http://\\host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http:\\\\/host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http:/\\\\host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http:\\\\\\host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http:////host/path"))
.isEqualTo(parse("http://host/path"))
}
@Test
fun resolveAuthoritySlashCountMattersWithSameScheme() {
val base = parse("http://a/b/c")
assertThat(base.resolve("http:host/path"))
.isEqualTo(parse("http://a/b/host/path"))
assertThat(base.resolve("http:/host/path"))
.isEqualTo(parse("http://a/host/path"))
assertThat(base.resolve("http:\\host/path"))
.isEqualTo(parse("http://a/host/path"))
assertThat(base.resolve("http://host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http:\\/host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http:/\\host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http:\\\\host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http:///host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http:\\//host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http:/\\/host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http://\\host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http:\\\\/host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http:/\\\\host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http:\\\\\\host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(base.resolve("http:////host/path"))
.isEqualTo(parse("http://host/path"))
}
@Test
fun username() {
assertThat(parse("http://@host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(parse("http://user@host/path"))
.isEqualTo(parse("http://user@host/path"))
}
/**
* Given multiple '@' characters, the last one is the delimiter.
*/
@Test
fun authorityWithMultipleAtSigns() {
val httpUrl = parse("http://foo@bar@baz/path")
assertThat(httpUrl.username).isEqualTo("foo@bar")
assertThat(httpUrl.password).isEqualTo("")
assertThat(httpUrl).isEqualTo(parse("http://foo%40bar@baz/path"))
}
/**
* Given multiple ':' characters, the first one is the delimiter.
*/
@Test
fun authorityWithMultipleColons() {
val httpUrl = parse("http://foo:pass1@bar:pass2@baz/path")
assertThat(httpUrl.username).isEqualTo("foo")
assertThat(httpUrl.password).isEqualTo("pass1@bar:pass2")
assertThat(httpUrl).isEqualTo(parse("http://foo:pass1%40bar%3Apass2@baz/path"))
}
@Test
fun usernameAndPassword() {
assertThat(parse("http://username:password@host/path"))
.isEqualTo(parse("http://username:password@host/path"))
assertThat(parse("http://username:@host/path"))
.isEqualTo(parse("http://username@host/path"))
}
@Test
fun passwordWithEmptyUsername() {
// Chrome doesn't mind, but Firefox rejects URLs with empty usernames and non-empty passwords.
assertThat(parse("http://:@host/path"))
.isEqualTo(parse("http://host/path"))
assertThat(parse("http://:password@@host/path").encodedPassword)
.isEqualTo("password%40")
}
@Test
fun unprintableCharactersArePercentEncoded() {
assertThat(parse("http://host/\u0000").encodedPath).isEqualTo("/%00")
assertThat(parse("http://host/\u0008").encodedPath).isEqualTo("/%08")
assertThat(parse("http://host/\ufffd").encodedPath).isEqualTo("/%EF%BF%BD")
}
@Test
fun usernameCharacters() {
UrlComponentEncodingTester.newInstance()
.override(
Encoding.PERCENT,
'['.code,
']'.code,
'{'.code,
'}'.code,
'|'.code,
'^'.code,
'\''.code,
';'.code,
'='.code,
'@'.code
)
.override(
Encoding.SKIP,
':'.code,
'/'.code,
'\\'.code,
'?'.code,
'#'.code
)
.escapeForUri('%'.code)
.test(UrlComponentEncodingTester.Component.USER)
}
@Test
fun passwordCharacters() {
UrlComponentEncodingTester.newInstance()
.override(
Encoding.PERCENT,
'['.code,
']'.code,
'{'.code,
'}'.code,
'|'.code,
'^'.code,
'\''.code,
':'.code,
';'.code,
'='.code,
'@'.code
)
.override(
Encoding.SKIP,
'/'.code,
'\\'.code,
'?'.code,
'#'.code
)
.escapeForUri('%'.code)
.test(UrlComponentEncodingTester.Component.PASSWORD)
}
@Test
fun hostContainsIllegalCharacter() {
assertInvalid("http://\n/", "Invalid URL host: \"\n\"")
assertInvalid("http:// /", "Invalid URL host: \" \"")
assertInvalid("http://%20/", "Invalid URL host: \"%20\"")
}
@Test
fun hostnameLowercaseCharactersMappedDirectly() {
assertThat(parse("http://abcd").host).isEqualTo("abcd")
assertThat(parse("http://σ").host).isEqualTo("xn--4xa")
}
@Test
fun hostnameUppercaseCharactersConvertedToLowercase() {
assertThat(parse("http://ABCD").host).isEqualTo("abcd")
assertThat(parse("http://Σ").host).isEqualTo("xn--4xa")
}
@Test
fun hostnameIgnoredCharacters() {
// The soft hyphen () should be ignored.
assertThat(parse("http://AB\u00adCD").host).isEqualTo("abcd")
}
@Test
fun hostnameMultipleCharacterMapping() {
// Map the single character telephone symbol (℡) to the string "tel".
assertThat(parse("http://\u2121").host).isEqualTo("tel")
}
@Test
fun hostnameMappingLastMappedCodePoint() {
assertThat(parse("http://\uD87E\uDE1D").host).isEqualTo("xn--pu5l")
}
@Disabled("The java.net.IDN implementation doesn't ignore characters that it should.")
@Test
@Throws(
Exception::class
)
fun hostnameMappingLastIgnoredCodePoint() {
assertThat(parse("http://ab\uDB40\uDDEFcd").host).isEqualTo("abcd")
}
@Test
fun hostnameMappingLastDisallowedCodePoint() {
assertInvalid("http://\uDBFF\uDFFF", "Invalid URL host: \"\uDBFF\uDFFF\"")
}
@Test
fun hostnameUri() {
// Host names are special:
//
// * Several characters are forbidden and must throw exceptions if used.
// * They don't use percent escaping at all.
// * They use punycode for internationalization.
// * URI is much more strict that HttpUrl or URL on what's accepted.
//
// HttpUrl is quite lenient with what characters it accepts. In particular, characters like '{'
// and '"' are permitted but unlikely to occur in real-world URLs. Unfortunately we can't just
// lock it down due to URL templating: "http://{env}.{dc}.example.com".
UrlComponentEncodingTester.newInstance()
.nonPrintableAscii(Encoding.FORBIDDEN)
.nonAscii(Encoding.FORBIDDEN)
.override(
Encoding.FORBIDDEN,
'\t'.code,
'\n'.code,
'\u000c'.code,
'\r'.code,
' '.code
)
.override(
Encoding.FORBIDDEN,
'#'.code,
'%'.code,
'/'.code,
':'.code,
'?'.code,
'@'.code,
'['.code,
'\\'.code,
']'.code
)
.override(
Encoding.IDENTITY,
'\"'.code,
'<'.code,
'>'.code,
'^'.code,
'`'.code,
'{'.code,
'|'.code,
'}'.code
)
.stripForUri(
'\"'.code,
'<'.code,
'>'.code,
'^'.code,
'`'.code,
'{'.code,
'|'.code,
'}'.code
)
.test(UrlComponentEncodingTester.Component.HOST)
}
/**
* This one's ugly: the HttpUrl's host is non-empty, but the URI's host is null.
*/
@Test
fun hostContainsOnlyStrippedCharacters() {
val url = parse("http://>/")
assertThat(url.host).isEqualTo(">")
assertThat(url.toUri().host).isNull()
}
@Test
fun hostIpv6() {
// Square braces are absent from host()...
assertThat(parse("http://[::1]/").host).isEqualTo("::1")
// ... but they're included in toString().
assertThat(parse("http://[::1]/").toString()).isEqualTo("http://[::1]/")
// IPv6 colons don't interfere with port numbers or passwords.
assertThat(parse("http://[::1]:8080/").port).isEqualTo(8080)
assertThat(parse("http://user:password@[::1]/").password).isEqualTo("password")
assertThat(parse("http://user:password@[::1]:8080/").host).isEqualTo("::1")
// Permit the contents of IPv6 addresses to be percent-encoded...
assertThat(parse("http://[%3A%3A%31]/").host).isEqualTo("::1")
// Including the Square braces themselves! (This is what Chrome does.)
assertThat(parse("http://%5B%3A%3A1%5D/").host).isEqualTo("::1")
}
@Test
fun hostIpv6AddressDifferentFormats() {
// Multiple representations of the same address; see http://tools.ietf.org/html/rfc5952.
val a3 = "2001:db8::1:0:0:1"
assertThat(parse("http://[2001:db8:0:0:1:0:0:1]").host).isEqualTo(a3)
assertThat(parse("http://[2001:0db8:0:0:1:0:0:1]").host).isEqualTo(a3)
assertThat(parse("http://[2001:db8::1:0:0:1]").host).isEqualTo(a3)
assertThat(parse("http://[2001:db8::0:1:0:0:1]").host).isEqualTo(a3)
assertThat(parse("http://[2001:0db8::1:0:0:1]").host).isEqualTo(a3)
assertThat(parse("http://[2001:db8:0:0:1::1]").host).isEqualTo(a3)
assertThat(parse("http://[2001:db8:0000:0:1::1]").host).isEqualTo(a3)
assertThat(parse("http://[2001:DB8:0:0:1::1]").host).isEqualTo(a3)
}
@Test
fun hostIpv6AddressLeadingCompression() {
assertThat(parse("http://[::0001]").host).isEqualTo("::1")
assertThat(parse("http://[0000::0001]").host).isEqualTo("::1")
assertThat(parse("http://[0000:0000:0000:0000:0000:0000:0000:0001]").host)
.isEqualTo("::1")
assertThat(parse("http://[0000:0000:0000:0000:0000:0000::0001]").host)
.isEqualTo("::1")
}
@Test
fun hostIpv6AddressTrailingCompression() {
assertThat(parse("http://[0001:0000::]").host).isEqualTo("1::")
assertThat(parse("http://[0001::0000]").host).isEqualTo("1::")
assertThat(parse("http://[0001::]").host).isEqualTo("1::")
assertThat(parse("http://[1::]").host).isEqualTo("1::")
}
@Test
fun hostIpv6AddressTooManyDigitsInGroup() {
assertInvalid(
"http://[00000:0000:0000:0000:0000:0000:0000:0001]",
"Invalid URL host: \"[00000:0000:0000:0000:0000:0000:0000:0001]\""
)
assertInvalid("http://[::00001]", "Invalid URL host: \"[::00001]\"")
}
@Test
fun hostIpv6AddressMisplacedColons() {
assertInvalid(
"http://[:0000:0000:0000:0000:0000:0000:0000:0001]",
"Invalid URL host: \"[:0000:0000:0000:0000:0000:0000:0000:0001]\""
)
assertInvalid(
"http://[:::0000:0000:0000:0000:0000:0000:0000:0001]",
"Invalid URL host: \"[:::0000:0000:0000:0000:0000:0000:0000:0001]\""
)
assertInvalid("http://[:1]", "Invalid URL host: \"[:1]\"")
assertInvalid("http://[:::1]", "Invalid URL host: \"[:::1]\"")
assertInvalid(
"http://[0000:0000:0000:0000:0000:0000:0001:]",
"Invalid URL host: \"[0000:0000:0000:0000:0000:0000:0001:]\""
)
assertInvalid(
"http://[0000:0000:0000:0000:0000:0000:0000:0001:]",
"Invalid URL host: \"[0000:0000:0000:0000:0000:0000:0000:0001:]\""
)
assertInvalid(
"http://[0000:0000:0000:0000:0000:0000:0000:0001::]",
"Invalid URL host: \"[0000:0000:0000:0000:0000:0000:0000:0001::]\""
)
assertInvalid(
"http://[0000:0000:0000:0000:0000:0000:0000:0001:::]",
"Invalid URL host: \"[0000:0000:0000:0000:0000:0000:0000:0001:::]\""
)
assertInvalid("http://[1:]", "Invalid URL host: \"[1:]\"")
assertInvalid("http://[1:::]", "Invalid URL host: \"[1:::]\"")
assertInvalid("http://[1:::1]", "Invalid URL host: \"[1:::1]\"")
assertInvalid(
"http://[0000:0000:0000:0000::0000:0000:0000:0001]",
"Invalid URL host: \"[0000:0000:0000:0000::0000:0000:0000:0001]\""
)
}
@Test
fun hostIpv6AddressTooManyGroups() {
assertInvalid(
"http://[0000:0000:0000:0000:0000:0000:0000:0000:0001]",
"Invalid URL host: \"[0000:0000:0000:0000:0000:0000:0000:0000:0001]\""
)
}
@Test
fun hostIpv6AddressTooMuchCompression() {
assertInvalid(
"http://[0000::0000:0000:0000:0000::0001]",
"Invalid URL host: \"[0000::0000:0000:0000:0000::0001]\""
)
assertInvalid(
"http://[::0000:0000:0000:0000::0001]",
"Invalid URL host: \"[::0000:0000:0000:0000::0001]\""
)
}
@Test
fun hostIpv6ScopedAddress() {
// java.net.InetAddress parses scoped addresses. These aren't valid in URLs.
assertInvalid("http://[::1%2544]", "Invalid URL host: \"[::1%2544]\"")
}
@Test
fun hostIpv6AddressTooManyLeadingZeros() {
// Guava's been buggy on this case. https://github.com/google/guava/issues/3116
assertInvalid(
"http://[2001:db8:0:0:1:0:0:00001]",
"Invalid URL host: \"[2001:db8:0:0:1:0:0:00001]\""
)
}
@Test
fun hostIpv6WithIpv4Suffix() {
assertThat(parse("http://[::1:255.255.255.255]/").host)
.isEqualTo("::1:ffff:ffff")
assertThat(parse("http://[0:0:0:0:0:1:0.0.0.0]/").host).isEqualTo("::1:0:0")
}
@Test
fun hostIpv6WithIpv4SuffixWithOctalPrefix() {
// Chrome interprets a leading '0' as octal; Firefox rejects them. (We reject them.)
assertInvalid(
"http://[0:0:0:0:0:1:0.0.0.000000]/",
"Invalid URL host: \"[0:0:0:0:0:1:0.0.0.000000]\""
)
assertInvalid(
"http://[0:0:0:0:0:1:0.010.0.010]/",
"Invalid URL host: \"[0:0:0:0:0:1:0.010.0.010]\""
)
assertInvalid(
"http://[0:0:0:0:0:1:0.0.0.000001]/",
"Invalid URL host: \"[0:0:0:0:0:1:0.0.0.000001]\""
)
}
@Test
fun hostIpv6WithIpv4SuffixWithHexadecimalPrefix() {
// Chrome interprets a leading '0x' as hexadecimal; Firefox rejects them. (We reject them.)
assertInvalid(
"http://[0:0:0:0:0:1:0.0x10.0.0x10]/",
"Invalid URL host: \"[0:0:0:0:0:1:0.0x10.0.0x10]\""
)
}
@Test
fun hostIpv6WithMalformedIpv4Suffix() {
assertInvalid(
"http://[0:0:0:0:0:1:0.0:0.0]/",
"Invalid URL host: \"[0:0:0:0:0:1:0.0:0.0]\""
)
assertInvalid(
"http://[0:0:0:0:0:1:0.0-0.0]/",
"Invalid URL host: \"[0:0:0:0:0:1:0.0-0.0]\""
)
assertInvalid(
"http://[0:0:0:0:0:1:.255.255.255]/",
"Invalid URL host: \"[0:0:0:0:0:1:.255.255.255]\""
)
assertInvalid(
"http://[0:0:0:0:0:1:255..255.255]/",
"Invalid URL host: \"[0:0:0:0:0:1:255..255.255]\""
)
assertInvalid(
"http://[0:0:0:0:0:1:255.255..255]/",
"Invalid URL host: \"[0:0:0:0:0:1:255.255..255]\""
)
assertInvalid(
"http://[0:0:0:0:0:0:1:255.255]/",
"Invalid URL host: \"[0:0:0:0:0:0:1:255.255]\""
)
assertInvalid(
"http://[0:0:0:0:0:1:256.255.255.255]/",
"Invalid URL host: \"[0:0:0:0:0:1:256.255.255.255]\""
)
assertInvalid(
"http://[0:0:0:0:0:1:ff.255.255.255]/",
"Invalid URL host: \"[0:0:0:0:0:1:ff.255.255.255]\""
)
assertInvalid(
"http://[0:0:0:0:0:0:1:255.255.255.255]/",
"Invalid URL host: \"[0:0:0:0:0:0:1:255.255.255.255]\""
)
assertInvalid(
"http://[0:0:0:0:1:255.255.255.255]/",
"Invalid URL host: \"[0:0:0:0:1:255.255.255.255]\""
)
assertInvalid(
"http://[0:0:0:0:1:0.0.0.0:1]/",
"Invalid URL host: \"[0:0:0:0:1:0.0.0.0:1]\""
)
assertInvalid(
"http://[0:0.0.0.0:1:0:0:0:0:1]/",
"Invalid URL host: \"[0:0.0.0.0:1:0:0:0:0:1]\""
)
assertInvalid(
"http://[0.0.0.0:0:0:0:0:0:1]/",
"Invalid URL host: \"[0.0.0.0:0:0:0:0:0:1]\""
)
}
@Test
fun hostIpv6WithIncompleteIpv4Suffix() {
// To Chrome & Safari these are well-formed; Firefox disagrees. (We're consistent with Firefox).
assertInvalid(
"http://[0:0:0:0:0:1:255.255.255.]/",
"Invalid URL host: \"[0:0:0:0:0:1:255.255.255.]\""
)
assertInvalid(
"http://[0:0:0:0:0:1:255.255.255]/",
"Invalid URL host: \"[0:0:0:0:0:1:255.255.255]\""
)
}
@Test
fun hostIpv6Malformed() {
assertInvalid("http://[::g]/", "Invalid URL host: \"[::g]\"")
}
@Test
fun hostIpv6CanonicalForm() {
assertThat(parse("http://[abcd:ef01:2345:6789:abcd:ef01:2345:6789]/").host)
.isEqualTo("abcd:ef01:2345:6789:abcd:ef01:2345:6789")
assertThat(parse("http://[a:0:0:0:b:0:0:0]/").host).isEqualTo("a::b:0:0:0")
assertThat(parse("http://[a:b:0:0:c:0:0:0]/").host).isEqualTo("a:b:0:0:c::")
assertThat(parse("http://[a:b:0:0:0:c:0:0]/").host).isEqualTo("a:b::c:0:0")
assertThat(parse("http://[a:0:0:0:b:0:0:0]/").host).isEqualTo("a::b:0:0:0")
assertThat(parse("http://[0:0:0:a:b:0:0:0]/").host).isEqualTo("::a:b:0:0:0")
assertThat(parse("http://[0:0:0:a:0:0:0:b]/").host).isEqualTo("::a:0:0:0:b")
assertThat(parse("http://[0:a:b:c:d:e:f:1]/").host).isEqualTo("0:a:b:c:d:e:f:1")
assertThat(parse("http://[a:b:c:d:e:f:1:0]/").host).isEqualTo("a:b:c:d:e:f:1:0")
assertThat(parse("http://[FF01:0:0:0:0:0:0:101]/").host).isEqualTo("ff01::101")
assertThat(parse("http://[2001:db8::1]/").host).isEqualTo("2001:db8::1")
assertThat(parse("http://[2001:db8:0:0:0:0:2:1]/").host).isEqualTo("2001:db8::2:1")
assertThat(parse("http://[2001:db8:0:1:1:1:1:1]/").host).isEqualTo("2001:db8:0:1:1:1:1:1")
assertThat(parse("http://[2001:db8:0:0:1:0:0:1]/").host).isEqualTo("2001:db8::1:0:0:1")
assertThat(parse("http://[2001:0:0:1:0:0:0:1]/").host).isEqualTo("2001:0:0:1::1")
assertThat(parse("http://[1:0:0:0:0:0:0:0]/").host).isEqualTo("1::")
assertThat(parse("http://[0:0:0:0:0:0:0:1]/").host).isEqualTo("::1")
assertThat(parse("http://[0:0:0:0:0:0:0:0]/").host).isEqualTo("::")
assertThat(parse("http://[::ffff:c0a8:1fe]/").host).isEqualTo("192.168.1.254")
}
/**
* The builder permits square braces but does not require them.
*/
@Test
fun hostIpv6Builder() {
val base = parse("http://example.com/")
assertThat(base.newBuilder().host("[::1]").build().toString())
.isEqualTo("http://[::1]/")
assertThat(base.newBuilder().host("[::0001]").build().toString())
.isEqualTo("http://[::1]/")
assertThat(base.newBuilder().host("::1").build().toString())
.isEqualTo("http://[::1]/")
assertThat(base.newBuilder().host("::0001").build().toString())
.isEqualTo("http://[::1]/")
}
@Test
fun hostIpv4CanonicalForm() {
assertThat(parse("http://255.255.255.255/").host).isEqualTo("255.255.255.255")
assertThat(parse("http://1.2.3.4/").host).isEqualTo("1.2.3.4")
assertThat(parse("http://0.0.0.0/").host).isEqualTo("0.0.0.0")
}
@Test
fun hostWithTrailingDot() {
assertThat(parse("http://host./").host).isEqualTo("host.")
}
/**
* Strip unexpected characters when converting to URI (which is more strict).
* https://github.com/square/okhttp/issues/5667
*/
@Test
fun hostToUriStripsCharacters() {
val httpUrl = "http://example\".com/".toHttpUrl()
assertThat(httpUrl.toUri().toString()).isEqualTo("http://example.com/")
}
/**
* Confirm that URI retains other characters. https://github.com/square/okhttp/issues/5236
*/
@Test
fun hostToUriStripsCharacters2() {
val httpUrl = "http://\${tracker}/".toHttpUrl()
assertThat(httpUrl.toUri().toString()).isEqualTo("http://\$tracker/")
}
@Test
fun port() {
assertThat(parse("http://host:80/")).isEqualTo(parse("http://host/"))
assertThat(parse("http://host:99/")).isEqualTo(parse("http://host:99/"))
assertThat(parse("http://host:/")).isEqualTo(parse("http://host/"))
assertThat(parse("http://host:65535/").port).isEqualTo(65535)
assertInvalid("http://host:0/", "Invalid URL port: \"0\"")
assertInvalid("http://host:65536/", "Invalid URL port: \"65536\"")
assertInvalid("http://host:-1/", "Invalid URL port: \"-1\"")
assertInvalid("http://host:a/", "Invalid URL port: \"a\"")
assertInvalid("http://host:%39%39/", "Invalid URL port: \"%39%39\"")
}
@Test
fun pathCharacters() {
UrlComponentEncodingTester.newInstance()
.override(
Encoding.PERCENT,
'^'.code,
'{'.code,
'}'.code,
'|'.code
)
.override(
Encoding.SKIP,
'\\'.code,
'?'.code,
'#'.code
)
.escapeForUri('%'.code, '['.code, ']'.code)
.test(UrlComponentEncodingTester.Component.PATH)
}
@Test
fun queryCharacters() {
UrlComponentEncodingTester.newInstance()
.override(Encoding.IDENTITY, '?'.code, '`'.code)
.override(Encoding.PERCENT, '\''.code)
.override(Encoding.SKIP, '#'.code, '+'.code)
.escapeForUri(
'%'.code,
'\\'.code,
'^'.code,
'`'.code,
'{'.code,
'|'.code,
'}'.code
)
.test(UrlComponentEncodingTester.Component.QUERY)
}
@Test
fun queryValueCharacters() {
UrlComponentEncodingTester.newInstance()
.override(Encoding.IDENTITY, '?'.code, '`'.code)
.override(Encoding.PERCENT, '\''.code)
.override(Encoding.SKIP, '#'.code, '+'.code)
.escapeForUri(
'%'.code,
'\\'.code,
'^'.code,
'`'.code,
'{'.code,
'|'.code,
'}'.code
)
.test(UrlComponentEncodingTester.Component.QUERY_VALUE)
}
@Test
fun fragmentCharacters() {
UrlComponentEncodingTester.newInstance()
.override(
Encoding.IDENTITY,
' '.code,
'"'.code,
'#'.code,
'<'.code,
'>'.code,
'?'.code,
'`'.code
)
.escapeForUri(
'%'.code,
' '.code,
'"'.code,
'#'.code,
'<'.code,
'>'.code,
'\\'.code,
'^'.code,
'`'.code,
'{'.code,
'|'.code,
'}'.code
)
.nonAscii(Encoding.IDENTITY)
.test(UrlComponentEncodingTester.Component.FRAGMENT)
}
@Test
fun fragmentNonAscii() {
val url = parse("http://host/#Σ")
assertThat(url.toString()).isEqualTo("http://host/#Σ")
assertThat(url.fragment).isEqualTo("Σ")
assertThat(url.encodedFragment).isEqualTo("Σ")
assertThat(url.toUri().toString()).isEqualTo("http://host/#Σ")
}
@Test
fun fragmentNonAsciiThatOffendsJavaNetUri() {
val url = parse("http://host/#\u0080")
assertThat(url.toString()).isEqualTo("http://host/#\u0080")
assertThat(url.fragment).isEqualTo("\u0080")
assertThat(url.encodedFragment).isEqualTo("\u0080")
// Control characters may be stripped!
assertThat(url.toUri()).isEqualTo(URI("http://host/#"))
}
@Test
fun fragmentPercentEncodedNonAscii() {
val url = parse("http://host/#%C2%80")
assertThat(url.toString()).isEqualTo("http://host/#%C2%80")
assertThat(url.fragment).isEqualTo("\u0080")
assertThat(url.encodedFragment).isEqualTo("%C2%80")
assertThat(url.toUri().toString()).isEqualTo("http://host/#%C2%80")
}
@Test
fun fragmentPercentEncodedPartialCodePoint() {
val url = parse("http://host/#%80")
assertThat(url.toString()).isEqualTo("http://host/#%80")
// Unicode replacement character.
assertThat(url.fragment).isEqualTo("\ufffd")
assertThat(url.encodedFragment).isEqualTo("%80")
assertThat(url.toUri().toString()).isEqualTo("http://host/#%80")
}
@Test
fun relativePath() {
val base = parse("http://host/a/b/c")
assertThat(base.resolve("d/e/f")).isEqualTo(parse("http://host/a/b/d/e/f"))
assertThat(base.resolve("../../d/e/f")).isEqualTo(parse("http://host/d/e/f"))
assertThat(base.resolve("..")).isEqualTo(parse("http://host/a/"))
assertThat(base.resolve("../..")).isEqualTo(parse("http://host/"))
assertThat(base.resolve("../../..")).isEqualTo(parse("http://host/"))
assertThat(base.resolve(".")).isEqualTo(parse("http://host/a/b/"))
assertThat(base.resolve("././..")).isEqualTo(parse("http://host/a/"))
assertThat(base.resolve("c/d/../e/../")).isEqualTo(parse("http://host/a/b/c/"))
assertThat(base.resolve("..e/")).isEqualTo(parse("http://host/a/b/..e/"))
assertThat(base.resolve("e/f../")).isEqualTo(parse("http://host/a/b/e/f../"))
assertThat(base.resolve("%2E.")).isEqualTo(parse("http://host/a/"))
assertThat(base.resolve(".%2E")).isEqualTo(parse("http://host/a/"))
assertThat(base.resolve("%2E%2E")).isEqualTo(parse("http://host/a/"))
assertThat(base.resolve("%2e.")).isEqualTo(parse("http://host/a/"))
assertThat(base.resolve(".%2e")).isEqualTo(parse("http://host/a/"))
assertThat(base.resolve("%2e%2e")).isEqualTo(parse("http://host/a/"))
assertThat(base.resolve("%2E")).isEqualTo(parse("http://host/a/b/"))
assertThat(base.resolve("%2e")).isEqualTo(parse("http://host/a/b/"))
}
@Test
fun relativePathWithTrailingSlash() {
val base = parse("http://host/a/b/c/")
assertThat(base.resolve("..")).isEqualTo(parse("http://host/a/b/"))
assertThat(base.resolve("../")).isEqualTo(parse("http://host/a/b/"))
assertThat(base.resolve("../..")).isEqualTo(parse("http://host/a/"))
assertThat(base.resolve("../../")).isEqualTo(parse("http://host/a/"))
assertThat(base.resolve("../../..")).isEqualTo(parse("http://host/"))
assertThat(base.resolve("../../../")).isEqualTo(parse("http://host/"))
assertThat(base.resolve("../../../..")).isEqualTo(parse("http://host/"))
assertThat(base.resolve("../../../../")).isEqualTo(parse("http://host/"))
assertThat(base.resolve("../../../../a")).isEqualTo(parse("http://host/a"))
assertThat(base.resolve("../../../../a/..")).isEqualTo(parse("http://host/"))
assertThat(base.resolve("../../../../a/b/..")).isEqualTo(parse("http://host/a/"))
}
@Test
fun pathWithBackslash() {
val base = parse("http://host/a/b/c")
assertThat(base.resolve("d\\e\\f")).isEqualTo(parse("http://host/a/b/d/e/f"))
assertThat(base.resolve("../..\\d\\e\\f"))
.isEqualTo(parse("http://host/d/e/f"))
assertThat(base.resolve("..\\..")).isEqualTo(parse("http://host/"))
}
@Test
fun relativePathWithSameScheme() {
val base = parse("http://host/a/b/c")
assertThat(base.resolve("http:d/e/f")).isEqualTo(parse("http://host/a/b/d/e/f"))
assertThat(base.resolve("http:../../d/e/f"))
.isEqualTo(parse("http://host/d/e/f"))
}
@Test
fun decodeUsername() {
assertThat(parse("http://user@host/").username).isEqualTo("user")
assertThat(parse("http://%F0%9F%8D%A9@host/").username).isEqualTo("\uD83C\uDF69")
}
@Test
fun decodePassword() {
assertThat(parse("http://user:password@host/").password).isEqualTo("password")
assertThat(parse("http://user:@host/").password).isEqualTo("")
assertThat(parse("http://user:%F0%9F%8D%A9@host/").password)
.isEqualTo("\uD83C\uDF69")
}
@Test
fun decodeSlashCharacterInDecodedPathSegment() {
assertThat(parse("http://host/a%2Fb%2Fc").pathSegments).containsExactly("a/b/c")
}
@Test
fun decodeEmptyPathSegments() {
assertThat(parse("http://host/").pathSegments).containsExactly("")
}
@Test
fun percentDecode() {
assertThat(parse("http://host/%00").pathSegments).containsExactly("\u0000")
assertThat(parse("http://host/a/%E2%98%83/c").pathSegments)
.containsExactly("a", "\u2603", "c")
assertThat(parse("http://host/a/%F0%9F%8D%A9/c").pathSegments)
.containsExactly("a", "\uD83C\uDF69", "c")
assertThat(parse("http://host/a/%62/c").pathSegments)
.containsExactly("a", "b", "c")
assertThat(parse("http://host/a/%7A/c").pathSegments)
.containsExactly("a", "z", "c")
assertThat(parse("http://host/a/%7a/c").pathSegments)
.containsExactly("a", "z", "c")
}
@Test
fun malformedPercentEncoding() {
assertThat(parse("http://host/a%f/b").pathSegments).containsExactly("a%f", "b")
assertThat(parse("http://host/%/b").pathSegments).containsExactly("%", "b")
assertThat(parse("http://host/%").pathSegments).containsExactly("%")
assertThat(parse("http://github.com/%%30%30").pathSegments)
.containsExactly("%00")
}
@Test
fun malformedUtf8Encoding() {
// Replace a partial UTF-8 sequence with the Unicode replacement character.
assertThat(parse("http://host/a/%E2%98x/c").pathSegments)
.containsExactly("a", "\ufffdx", "c")
}
@Test
fun incompleteUrlComposition() {
val noHost = assertFailsWith<IllegalStateException> {
HttpUrl.Builder().scheme("http").build()
}
assertThat(noHost.message).isEqualTo("host == null")
val noScheme = assertFailsWith<IllegalStateException> {
HttpUrl.Builder().host("host").build()
}
assertThat(noScheme.message).isEqualTo("scheme == null")
}
@Test
fun builderToString() {
assertThat(parse("https://host.com/path").newBuilder().toString())
.isEqualTo("https://host.com/path")
}
@Test
fun incompleteBuilderToString() {
assertThat(HttpUrl.Builder().scheme("https").encodedPath("/path").toString())
.isEqualTo("https:///path")
assertThat(HttpUrl.Builder().host("host.com").encodedPath("/path").toString())
.isEqualTo("//host.com/path")
assertThat(
HttpUrl.Builder().host("host.com").encodedPath("/path").port(8080).toString()
)
.isEqualTo("//host.com:8080/path")
}
@Test
fun minimalUrlComposition() {
val url = HttpUrl.Builder().scheme("http").host("host").build()
assertThat(url.toString()).isEqualTo("http://host/")
assertThat(url.scheme).isEqualTo("http")
assertThat(url.username).isEqualTo("")
assertThat(url.password).isEqualTo("")
assertThat(url.host).isEqualTo("host")
assertThat(url.port).isEqualTo(80)
assertThat(url.encodedPath).isEqualTo("/")
assertThat(url.query).isNull()
assertThat(url.fragment).isNull()
}
@Test
fun fullUrlComposition() {
val url = HttpUrl.Builder()
.scheme("http")
.username("username")
.password("password")
.host("host")
.port(8080)
.addPathSegment("path")
.query("query")
.fragment("fragment")
.build()
assertThat(url.toString())
.isEqualTo("http://username:password@host:8080/path?query#fragment")
assertThat(url.scheme).isEqualTo("http")
assertThat(url.username).isEqualTo("username")
assertThat(url.password).isEqualTo("password")
assertThat(url.host).isEqualTo("host")
assertThat(url.port).isEqualTo(8080)
assertThat(url.encodedPath).isEqualTo("/path")
assertThat(url.query).isEqualTo("query")
assertThat(url.fragment).isEqualTo("fragment")
}
@Test
fun changingSchemeChangesDefaultPort() {
assertThat(
parse("http://example.com")
.newBuilder()
.scheme("https")
.build().port
).isEqualTo(443)
assertThat(
parse("https://example.com")
.newBuilder()
.scheme("http")
.build().port
).isEqualTo(80)
assertThat(
parse("https://example.com:1234")
.newBuilder()
.scheme("http")
.build().port
).isEqualTo(1234)
}
@Test
fun composeEncodesWhitespace() {
val url = HttpUrl.Builder()
.scheme("http")
.username("a\r\n\u000c\t b")
.password("c\r\n\u000c\t d")
.host("host")
.addPathSegment("e\r\n\u000c\t f")
.query("g\r\n\u000c\t h")
.fragment("i\r\n\u000c\t j")
.build()
assertThat(url.toString()).isEqualTo(
"http://a%0D%0A%0C%09%20b:c%0D%0A%0C%09%20d@host"
+ "/e%0D%0A%0C%09%20f?g%0D%0A%0C%09%20h#i%0D%0A%0C%09 j"
)
assertThat(url.username).isEqualTo("a\r\n\u000c\t b")
assertThat(url.password).isEqualTo("c\r\n\u000c\t d")
assertThat(url.pathSegments[0]).isEqualTo("e\r\n\u000c\t f")
assertThat(url.query).isEqualTo("g\r\n\u000c\t h")
assertThat(url.fragment).isEqualTo("i\r\n\u000c\t j")
}
@Test
fun composeFromUnencodedComponents() {
val url = HttpUrl.Builder()
.scheme("http")
.username("a:\u0001@/\\?#%b")
.password("c:\u0001@/\\?#%d")
.host("ef")
.port(8080)
.addPathSegment("g:\u0001@/\\?#%h")
.query("i:\u0001@/\\?#%j")
.fragment("k:\u0001@/\\?#%l")
.build()
assertThat(url.toString())
.isEqualTo(
"http://a%3A%01%40%2F%5C%3F%23%25b:c%3A%01%40%2F%5C%3F%23%25d@ef:8080/"
+ "g:%01@%2F%5C%3F%23%25h?i:%01@/\\?%23%25j#k:%01@/\\?#%25l"
)
assertThat(url.scheme).isEqualTo("http")
assertThat(url.username).isEqualTo("a:\u0001@/\\?#%b")
assertThat(url.password).isEqualTo("c:\u0001@/\\?#%d")
assertThat(url.pathSegments).containsExactly("g:\u0001@/\\?#%h")
assertThat(url.query).isEqualTo("i:\u0001@/\\?#%j")
assertThat(url.fragment).isEqualTo("k:\u0001@/\\?#%l")
assertThat(url.encodedUsername).isEqualTo("a%3A%01%40%2F%5C%3F%23%25b")
assertThat(url.encodedPassword).isEqualTo("c%3A%01%40%2F%5C%3F%23%25d")
assertThat(url.encodedPath).isEqualTo("/g:%01@%2F%5C%3F%23%25h")
assertThat(url.encodedQuery).isEqualTo("i:%01@/\\?%23%25j")
assertThat(url.encodedFragment).isEqualTo("k:%01@/\\?#%25l")
}
@Test
fun composeFromEncodedComponents() {
val url = HttpUrl.Builder()
.scheme("http")
.encodedUsername("a:\u0001@/\\?#%25b")
.encodedPassword("c:\u0001@/\\?#%25d")
.host("ef")
.port(8080)
.addEncodedPathSegment("g:\u0001@/\\?#%25h")
.encodedQuery("i:\u0001@/\\?#%25j")
.encodedFragment("k:\u0001@/\\?#%25l")
.build()
assertThat(url.toString())
.isEqualTo(
"http://a%3A%01%40%2F%5C%3F%23%25b:c%3A%01%40%2F%5C%3F%23%25d@ef:8080/"
+ "g:%01@%2F%5C%3F%23%25h?i:%01@/\\?%23%25j#k:%01@/\\?#%25l"
)
assertThat(url.scheme).isEqualTo("http")
assertThat(url.username).isEqualTo("a:\u0001@/\\?#%b")
assertThat(url.password).isEqualTo("c:\u0001@/\\?#%d")
assertThat(url.pathSegments).containsExactly("g:\u0001@/\\?#%h")
assertThat(url.query).isEqualTo("i:\u0001@/\\?#%j")
assertThat(url.fragment).isEqualTo("k:\u0001@/\\?#%l")
assertThat(url.encodedUsername).isEqualTo("a%3A%01%40%2F%5C%3F%23%25b")
assertThat(url.encodedPassword).isEqualTo("c%3A%01%40%2F%5C%3F%23%25d")
assertThat(url.encodedPath).isEqualTo("/g:%01@%2F%5C%3F%23%25h")
assertThat(url.encodedQuery).isEqualTo("i:%01@/\\?%23%25j")
assertThat(url.encodedFragment).isEqualTo("k:%01@/\\?#%25l")
}
@Test
fun composeWithEncodedPath() {
val url = HttpUrl.Builder()
.scheme("http")
.host("host")
.encodedPath("/a%2Fb/c")
.build()
assertThat(url.toString()).isEqualTo("http://host/a%2Fb/c")
assertThat(url.encodedPath).isEqualTo("/a%2Fb/c")
assertThat(url.pathSegments).containsExactly("a/b", "c")
}
@Test
fun composeMixingPathSegments() {
val url = HttpUrl.Builder()
.scheme("http")
.host("host")
.encodedPath("/a%2fb/c")
.addPathSegment("d%25e")
.addEncodedPathSegment("f%25g")
.build()
assertThat(url.toString()).isEqualTo("http://host/a%2fb/c/d%2525e/f%25g")
assertThat(url.encodedPath).isEqualTo("/a%2fb/c/d%2525e/f%25g")
assertThat(url.encodedPathSegments)
.containsExactly("a%2fb", "c", "d%2525e", "f%25g")
assertThat(url.pathSegments).containsExactly("a/b", "c", "d%25e", "f%g")
}
@Test
fun composeWithAddSegment() {
val base = parse("http://host/a/b/c")
assertThat(base.newBuilder()
.addPathSegment("")
.build().encodedPath)
.isEqualTo("/a/b/c/")
assertThat(base.newBuilder()
.addPathSegment("")
.addPathSegment("d")
.build().encodedPath)
.isEqualTo("/a/b/c/d")
assertThat(base.newBuilder()
.addPathSegment("..")
.build().encodedPath)
.isEqualTo("/a/b/")
assertThat(base.newBuilder()
.addPathSegment("")
.addPathSegment("..")
.build().encodedPath)
.isEqualTo("/a/b/")
assertThat(base.newBuilder()
.addPathSegment("")
.addPathSegment("")
.build().encodedPath)
.isEqualTo("/a/b/c/")
}
@Test
fun pathSize() {
assertThat(parse("http://host/").pathSize).isEqualTo(1)
assertThat(parse("http://host/a/b/c").pathSize).isEqualTo(3)
}
@Test
fun addPathSegments() {
val base = parse("http://host/a/b/c")
// Add a string with zero slashes: resulting URL gains one slash.
assertThat(base.newBuilder().addPathSegments("").build().encodedPath)
.isEqualTo("/a/b/c/")
assertThat(base.newBuilder().addPathSegments("d").build().encodedPath)
.isEqualTo("/a/b/c/d")
// Add a string with one slash: resulting URL gains two slashes.
assertThat(base.newBuilder().addPathSegments("/").build().encodedPath)
.isEqualTo("/a/b/c//")
assertThat(base.newBuilder().addPathSegments("d/").build().encodedPath)
.isEqualTo("/a/b/c/d/")
assertThat(base.newBuilder().addPathSegments("/d").build().encodedPath)
.isEqualTo("/a/b/c//d")
// Add a string with two slashes: resulting URL gains three slashes.
assertThat(base.newBuilder().addPathSegments("//").build().encodedPath)
.isEqualTo("/a/b/c///")
assertThat(base.newBuilder().addPathSegments("/d/").build().encodedPath)
.isEqualTo("/a/b/c//d/")
assertThat(base.newBuilder().addPathSegments("d//").build().encodedPath)
.isEqualTo("/a/b/c/d//")
assertThat(base.newBuilder().addPathSegments("//d").build().encodedPath)
.isEqualTo("/a/b/c///d")
assertThat(base.newBuilder().addPathSegments("d/e/f").build().encodedPath)
.isEqualTo("/a/b/c/d/e/f")
}
@Test
fun addPathSegmentsOntoTrailingSlash() {
val base = parse("http://host/a/b/c/")
// Add a string with zero slashes: resulting URL gains zero slashes.
assertThat(base.newBuilder().addPathSegments("").build().encodedPath)
.isEqualTo("/a/b/c/")
assertThat(base.newBuilder().addPathSegments("d").build().encodedPath)
.isEqualTo("/a/b/c/d")
// Add a string with one slash: resulting URL gains one slash.
assertThat(base.newBuilder().addPathSegments("/").build().encodedPath)
.isEqualTo("/a/b/c//")
assertThat(base.newBuilder().addPathSegments("d/").build().encodedPath)
.isEqualTo("/a/b/c/d/")
assertThat(base.newBuilder().addPathSegments("/d").build().encodedPath)
.isEqualTo("/a/b/c//d")
// Add a string with two slashes: resulting URL gains two slashes.
assertThat(base.newBuilder().addPathSegments("//").build().encodedPath)
.isEqualTo("/a/b/c///")
assertThat(base.newBuilder().addPathSegments("/d/").build().encodedPath)
.isEqualTo("/a/b/c//d/")
assertThat(base.newBuilder().addPathSegments("d//").build().encodedPath)
.isEqualTo("/a/b/c/d//")
assertThat(base.newBuilder().addPathSegments("//d").build().encodedPath)
.isEqualTo("/a/b/c///d")
assertThat(base.newBuilder().addPathSegments("d/e/f").build().encodedPath)
.isEqualTo("/a/b/c/d/e/f")
}
@Test
fun addPathSegmentsWithBackslash() {
val base = parse("http://host/")
assertThat(base.newBuilder().addPathSegments("d\\e").build().encodedPath)
.isEqualTo("/d/e")
assertThat(base.newBuilder().addEncodedPathSegments("d\\e").build().encodedPath)
.isEqualTo("/d/e")
}
@Test
fun addPathSegmentsWithEmptyPaths() {
val base = parse("http://host/a/b/c")
assertThat(base.newBuilder().addPathSegments("/d/e///f").build().encodedPath)
.isEqualTo("/a/b/c//d/e///f")
}
@Test
fun addEncodedPathSegments() {
val base = parse("http://host/a/b/c")
assertThat(
base.newBuilder().addEncodedPathSegments("d/e/%20/\n").build().encodedPath as Any
).isEqualTo("/a/b/c/d/e/%20/")
}
@Test
fun addPathSegmentDotDoesNothing() {
val base = parse("http://host/a/b/c")
assertThat(base.newBuilder().addPathSegment(".").build().encodedPath)
.isEqualTo("/a/b/c")
}
@Test
fun addPathSegmentEncodes() {
val base = parse("http://host/a/b/c")
assertThat(base.newBuilder().addPathSegment("%2e").build().encodedPath)
.isEqualTo("/a/b/c/%252e")
assertThat(base.newBuilder().addPathSegment("%2e%2e").build().encodedPath)
.isEqualTo("/a/b/c/%252e%252e")
}
@Test
fun addPathSegmentDotDotPopsDirectory() {
val base = parse("http://host/a/b/c")
assertThat(base.newBuilder().addPathSegment("..").build().encodedPath)
.isEqualTo("/a/b/")
}
@Test
fun addPathSegmentDotAndIgnoredCharacter() {
val base = parse("http://host/a/b/c")
assertThat(base.newBuilder().addPathSegment(".\n").build().encodedPath)
.isEqualTo("/a/b/c/.%0A")
}
@Test
fun addEncodedPathSegmentDotAndIgnoredCharacter() {
val base = parse("http://host/a/b/c")
assertThat(base.newBuilder().addEncodedPathSegment(".\n").build().encodedPath)
.isEqualTo("/a/b/c")
}
@Test
fun addEncodedPathSegmentDotDotAndIgnoredCharacter() {
val base = parse("http://host/a/b/c")
assertThat(base.newBuilder().addEncodedPathSegment("..\n").build().encodedPath)
.isEqualTo("/a/b/")
}
@Test
fun setPathSegment() {
val base = parse("http://host/a/b/c")
assertThat(base.newBuilder().setPathSegment(0, "d").build().encodedPath)
.isEqualTo("/d/b/c")
assertThat(base.newBuilder().setPathSegment(1, "d").build().encodedPath)
.isEqualTo("/a/d/c")
assertThat(base.newBuilder().setPathSegment(2, "d").build().encodedPath)
.isEqualTo("/a/b/d")
}
@Test
fun setPathSegmentEncodes() {
val base = parse("http://host/a/b/c")
assertThat(base.newBuilder().setPathSegment(0, "%25").build().encodedPath)
.isEqualTo("/%2525/b/c")
assertThat(base.newBuilder().setPathSegment(0, ".\n").build().encodedPath)
.isEqualTo("/.%0A/b/c")
assertThat(base.newBuilder().setPathSegment(0, "%2e").build().encodedPath)
.isEqualTo("/%252e/b/c")
}
@Test
fun setPathSegmentAcceptsEmpty() {
val base = parse("http://host/a/b/c")
assertThat(base.newBuilder().setPathSegment(0, "").build().encodedPath)
.isEqualTo("//b/c")
assertThat(base.newBuilder().setPathSegment(2, "").build().encodedPath)
.isEqualTo("/a/b/")
}
@Test
fun setPathSegmentRejectsDot() {
val base = parse("http://host/a/b/c")
assertFailsWith<IllegalArgumentException> {
base.newBuilder().setPathSegment(0, ".")
}
}
@Test
fun setPathSegmentRejectsDotDot() {
val base = parse("http://host/a/b/c")
assertFailsWith<IllegalArgumentException> {
base.newBuilder().setPathSegment(0, "..")
}
}
@Test
fun setPathSegmentWithSlash() {
val base = parse("http://host/a/b/c")
val url = base.newBuilder().setPathSegment(1, "/").build()
assertThat(url.encodedPath).isEqualTo("/a/%2F/c")
}
@Test
fun setPathSegmentOutOfBounds() {
assertFailsWith<IndexOutOfBoundsException> {
HttpUrl.Builder().setPathSegment(1, "a")
}
}
@Test
fun setEncodedPathSegmentEncodes() {
val base = parse("http://host/a/b/c")
assertThat(base.newBuilder().setEncodedPathSegment(0, "%25").build().encodedPath)
.isEqualTo("/%25/b/c")
}
@Test
fun setEncodedPathSegmentRejectsDot() {
val base = parse("http://host/a/b/c")
assertFailsWith<IllegalArgumentException> {
base.newBuilder().setEncodedPathSegment(0, ".")
}
}
@Test
fun setEncodedPathSegmentRejectsDotAndIgnoredCharacter() {
val base = parse("http://host/a/b/c")
assertFailsWith<IllegalArgumentException> {
base.newBuilder().setEncodedPathSegment(0, ".\n")
}
}
@Test
fun setEncodedPathSegmentRejectsDotDot() {
val base = parse("http://host/a/b/c")
assertFailsWith<IllegalArgumentException> {
base.newBuilder().setEncodedPathSegment(0, "..")
}
}
@Test
fun setEncodedPathSegmentRejectsDotDotAndIgnoredCharacter() {
val base = parse("http://host/a/b/c")
assertFailsWith<IllegalArgumentException> {
base.newBuilder().setEncodedPathSegment(0, "..\n")
}
}
@Test
fun setEncodedPathSegmentWithSlash() {
val base = parse("http://host/a/b/c")
val url = base.newBuilder().setEncodedPathSegment(1, "/").build()
assertThat(url.encodedPath).isEqualTo("/a/%2F/c")
}
@Test
fun setEncodedPathSegmentOutOfBounds() {
assertFailsWith<IndexOutOfBoundsException> {
HttpUrl.Builder().setEncodedPathSegment(1, "a")
}
}
@Test
fun removePathSegment() {
val base = parse("http://host/a/b/c")
val url = base.newBuilder()
.removePathSegment(0)
.build()
assertThat(url.encodedPath).isEqualTo("/b/c")
}
@Test
fun removePathSegmentDoesntRemovePath() {
val base = parse("http://host/a/b/c")
val url = base.newBuilder()
.removePathSegment(0)
.removePathSegment(0)
.removePathSegment(0)
.build()
assertThat(url.pathSegments).containsExactly("")
assertThat(url.encodedPath).isEqualTo("/")
}
@Test
fun removePathSegmentOutOfBounds() {
assertFailsWith<IndexOutOfBoundsException> {
HttpUrl.Builder().removePathSegment(1)
}
}
@Test
fun toJavaNetUrl() {
val httpUrl = parse("http://username:password@host/path?query#fragment")
val javaNetUrl = httpUrl.toUrl()
assertThat(javaNetUrl.toString())
.isEqualTo("http://username:password@host/path?query#fragment")
}
@Test
fun toUri() {
val httpUrl = parse("http://username:password@host/path?query#fragment")
val uri = httpUrl.toUri()
assertThat(uri.toString())
.isEqualTo("http://username:password@host/path?query#fragment")
}
@Test
fun toUriSpecialQueryCharacters() {
val httpUrl = parse("http://host/?d=abc!@[]^`{}|\\")
val uri = httpUrl.toUri()
assertThat(uri.toString()).isEqualTo("http://host/?d=abc!@[]%5E%60%7B%7D%7C%5C")
}
@Test
fun toUriWithUsernameNoPassword() {
val httpUrl = HttpUrl.Builder()
.scheme("http")
.username("user")
.host("host")
.build()
assertThat(httpUrl.toString()).isEqualTo("http://user@host/")
assertThat(httpUrl.toUri().toString()).isEqualTo("http://user@host/")
}
@Test
fun toUriUsernameSpecialCharacters() {
val url = HttpUrl.Builder()
.scheme("http")
.host("host")
.username("=[]:;\"~|?#@^/$%*")
.build()
assertThat(url.toString())
.isEqualTo("http://%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/")
assertThat(url.toUri().toString())
.isEqualTo("http://%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/")
}
@Test
fun toUriPasswordSpecialCharacters() {
val url = HttpUrl.Builder()
.scheme("http")
.host("host")
.username("user")
.password("=[]:;\"~|?#@^/$%*")
.build()
assertThat(url.toString())
.isEqualTo("http://user:%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/")
assertThat(url.toUri().toString())
.isEqualTo("http://user:%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/")
}
@Test
fun toUriPathSpecialCharacters() {
val url = HttpUrl.Builder()
.scheme("http")
.host("host")
.addPathSegment("=[]:;\"~|?#@^/$%*")
.build()
assertThat(url.toString())
.isEqualTo("http://host/=[]:;%22~%7C%3F%23@%5E%2F$%25*")
assertThat(url.toUri().toString())
.isEqualTo("http://host/=%5B%5D:;%22~%7C%3F%23@%5E%2F$%25*")
}
@Test
fun toUriQueryParameterNameSpecialCharacters() {
val url = HttpUrl.Builder()
.scheme("http")
.host("host")
.addQueryParameter("=[]:;\"~|?#@^/$%*", "a")
.build()
assertThat(url.toString())
.isEqualTo("http://host/?%3D%5B%5D%3A%3B%22%7E%7C%3F%23%40%5E%2F%24%25*=a")
assertThat(url.toUri().toString())
.isEqualTo("http://host/?%3D%5B%5D%3A%3B%22%7E%7C%3F%23%40%5E%2F%24%25*=a")
assertThat(url.queryParameter("=[]:;\"~|?#@^/$%*")).isEqualTo("a")
}
@Test
fun toUriQueryParameterValueSpecialCharacters() {
val url = HttpUrl.Builder()
.scheme("http")
.host("host")
.addQueryParameter("a", "=[]:;\"~|?#@^/$%*")
.build()
assertThat(url.toString())
.isEqualTo("http://host/?a=%3D%5B%5D%3A%3B%22%7E%7C%3F%23%40%5E%2F%24%25*")
assertThat(url.toUri().toString())
.isEqualTo("http://host/?a=%3D%5B%5D%3A%3B%22%7E%7C%3F%23%40%5E%2F%24%25*")
assertThat(url.queryParameter("a")).isEqualTo("=[]:;\"~|?#@^/$%*")
}
@Test
fun toUriQueryValueSpecialCharacters() {
val url = HttpUrl.Builder()
.scheme("http")
.host("host")
.query("=[]:;\"~|?#@^/$%*")
.build()
assertThat(url.toString()).isEqualTo("http://host/?=[]:;%22~|?%23@^/$%25*")
assertThat(url.toUri().toString())
.isEqualTo("http://host/?=[]:;%22~%7C?%23@%5E/$%25*")
}
@Test
fun queryCharactersEncodedWhenComposed() {
val url = HttpUrl.Builder()
.scheme("http")
.host("host")
.addQueryParameter("a", "!$(),/:;?@[]\\^`{|}~")
.build()
assertThat(url.toString())
.isEqualTo("http://host/?a=%21%24%28%29%2C%2F%3A%3B%3F%40%5B%5D%5C%5E%60%7B%7C%7D%7E")
assertThat(url.queryParameter("a")).isEqualTo("!$(),/:;?@[]\\^`{|}~")
}
/**
* When callers use `addEncodedQueryParameter()` we only encode what's strictly required. We
* retain the encoded (or non-encoded) state of the input.
*/
@Test
fun queryCharactersNotReencodedWhenComposedWithAddEncoded() {
val url = HttpUrl.Builder()
.scheme("http")
.host("host")
.addEncodedQueryParameter("a", "!$(),/:;?@[]\\^`{|}~")
.build()
assertThat(url.toString()).isEqualTo("http://host/?a=!$(),/:;?@[]\\^`{|}~")
assertThat(url.queryParameter("a")).isEqualTo("!$(),/:;?@[]\\^`{|}~")
}
/**
* When callers parse a URL with query components that aren't encoded, we shouldn't convert them
* into a canonical form because doing so could be semantically different.
*/
@Test
fun queryCharactersNotReencodedWhenParsed() {
val url = parse("http://host/?a=!$(),/:;?@[]\\^`{|}~")
assertThat(url.toString()).isEqualTo("http://host/?a=!$(),/:;?@[]\\^`{|}~")
assertThat(url.queryParameter("a")).isEqualTo("!$(),/:;?@[]\\^`{|}~")
}
@Test
fun toUriFragmentSpecialCharacters() {
val url = HttpUrl.Builder()
.scheme("http")
.host("host")
.fragment("=[]:;\"~|?#@^/$%*")
.build()
assertThat(url.toString()).isEqualTo("http://host/#=[]:;\"~|?#@^/$%25*")
assertThat(url.toUri().toString())
.isEqualTo("http://host/#=[]:;%22~%7C?%23@%5E/$%25*")
}
@Test
fun toUriWithControlCharacters() {
// Percent-encoded in the path.
assertThat(parse("http://host/a\u0000b").toUri())
.isEqualTo(URI("http://host/a%00b"))
assertThat(parse("http://host/a\u0080b").toUri())
.isEqualTo(URI("http://host/a%C2%80b"))
assertThat(parse("http://host/a\u009fb").toUri())
.isEqualTo(URI("http://host/a%C2%9Fb"))
// Percent-encoded in the query.
assertThat(parse("http://host/?a\u0000b").toUri())
.isEqualTo(URI("http://host/?a%00b"))
assertThat(parse("http://host/?a\u0080b").toUri())
.isEqualTo(URI("http://host/?a%C2%80b"))
assertThat(parse("http://host/?a\u009fb").toUri())
.isEqualTo(URI("http://host/?a%C2%9Fb"))
// Stripped from the fragment.
assertThat(parse("http://host/#a\u0000b").toUri())
.isEqualTo(URI("http://host/#a%00b"))
assertThat(parse("http://host/#a\u0080b").toUri())
.isEqualTo(URI("http://host/#ab"))
assertThat(parse("http://host/#a\u009fb").toUri())
.isEqualTo(URI("http://host/#ab"))
}
@Test
fun toUriWithSpaceCharacters() {
// Percent-encoded in the path.
assertThat(parse("http://host/a\u000bb").toUri())
.isEqualTo(URI("http://host/a%0Bb"))
assertThat(parse("http://host/a b").toUri()).isEqualTo(URI("http://host/a%20b"))
assertThat(parse("http://host/a\u2009b").toUri())
.isEqualTo(URI("http://host/a%E2%80%89b"))
assertThat(parse("http://host/a\u3000b").toUri())
.isEqualTo(URI("http://host/a%E3%80%80b"))
// Percent-encoded in the query.
assertThat(parse("http://host/?a\u000bb").toUri())
.isEqualTo(URI("http://host/?a%0Bb"))
assertThat(parse("http://host/?a b").toUri())
.isEqualTo(URI("http://host/?a%20b"))
assertThat(parse("http://host/?a\u2009b").toUri())
.isEqualTo(URI("http://host/?a%E2%80%89b"))
assertThat(parse("http://host/?a\u3000b").toUri())
.isEqualTo(URI("http://host/?a%E3%80%80b"))
// Stripped from the fragment.
assertThat(parse("http://host/#a\u000bb").toUri())
.isEqualTo(URI("http://host/#a%0Bb"))
assertThat(parse("http://host/#a b").toUri())
.isEqualTo(URI("http://host/#a%20b"))
assertThat(parse("http://host/#a\u2009b").toUri())
.isEqualTo(URI("http://host/#ab"))
assertThat(parse("http://host/#a\u3000b").toUri())
.isEqualTo(URI("http://host/#ab"))
}
@Test
fun toUriWithNonHexPercentEscape() {
assertThat(parse("http://host/%xx").toUri()).isEqualTo(URI("http://host/%25xx"))
}
@Test
fun toUriWithTruncatedPercentEscape() {
assertThat(parse("http://host/%a").toUri()).isEqualTo(URI("http://host/%25a"))
assertThat(parse("http://host/%").toUri()).isEqualTo(URI("http://host/%25"))
}
@Test
fun fromJavaNetUrl() {
val javaNetUrl = URL("http://username:password@host/path?query#fragment")
val httpUrl = javaNetUrl.toHttpUrlOrNull()
assertThat(httpUrl.toString())
.isEqualTo("http://username:password@host/path?query#fragment")
}
@Test
fun fromJavaNetUrlUnsupportedScheme() {
// java.net.MalformedURLException: unknown protocol: mailto
platform.assumeNotAndroid()
// Accessing an URL protocol that was not enabled. The URL protocol mailto is not tested and
// might not work as expected. It can be enabled by adding the --enable-url-protocols=mailto
// option to the native-image command.
platform.assumeNotGraalVMImage()
val javaNetUrl = URL("mailto:[email protected]")
assertThat<HttpUrl>(javaNetUrl.toHttpUrlOrNull()).isNull()
}
@Test
fun fromUri() {
val uri = URI("http://username:password@host/path?query#fragment")
val httpUrl = uri.toHttpUrlOrNull()
assertThat(httpUrl.toString())
.isEqualTo("http://username:password@host/path?query#fragment")
}
@Test
fun fromUriUnsupportedScheme() {
val uri = URI("mailto:[email protected]")
assertThat<HttpUrl>(uri.toHttpUrlOrNull()).isNull()
}
@Test
fun fromUriPartial() {
val uri = URI("/path")
assertThat<HttpUrl>(uri.toHttpUrlOrNull()).isNull()
}
@Test
fun composeQueryWithComponents() {
val base = parse("http://host/")
val url = base.newBuilder().addQueryParameter("a+=& b", "c+=& d").build()
assertThat(url.toString())
.isEqualTo("http://host/?a%2B%3D%26%20b=c%2B%3D%26%20d")
assertThat(url.queryParameterValue(0)).isEqualTo("c+=& d")
assertThat(url.queryParameterName(0)).isEqualTo("a+=& b")
assertThat(url.queryParameter("a+=& b")).isEqualTo("c+=& d")
assertThat(url.queryParameterNames).isEqualTo(setOf("a+=& b"))
assertThat(url.queryParameterValues("a+=& b")).isEqualTo(listOf("c+=& d"))
assertThat(url.querySize).isEqualTo(1)
// Ambiguous! (Though working as designed.)
assertThat(url.query).isEqualTo("a+=& b=c+=& d")
assertThat(url.encodedQuery).isEqualTo("a%2B%3D%26%20b=c%2B%3D%26%20d")
}
@Test
fun composeQueryWithEncodedComponents() {
val base = parse("http://host/")
val url = base.newBuilder()
.addEncodedQueryParameter("a+=& b", "c+=& d")
.build()
assertThat(url.toString()).isEqualTo("http://host/?a+%3D%26%20b=c+%3D%26%20d")
assertThat(url.queryParameter("a =& b")).isEqualTo("c =& d")
}
@Test
fun composeQueryRemoveQueryParameter() {
val url = parse("http://host/").newBuilder()
.addQueryParameter("a+=& b", "c+=& d")
.removeAllQueryParameters("a+=& b")
.build()
assertThat(url.toString()).isEqualTo("http://host/")
assertThat(url.queryParameter("a+=& b")).isNull()
}
@Test
fun composeQueryRemoveEncodedQueryParameter() {
val url = parse("http://host/").newBuilder()
.addEncodedQueryParameter("a+=& b", "c+=& d")
.removeAllEncodedQueryParameters("a+=& b")
.build()
assertThat(url.toString()).isEqualTo("http://host/")
assertThat(url.queryParameter("a =& b")).isNull()
}
@Test
fun composeQuerySetQueryParameter() {
val url = parse("http://host/").newBuilder()
.addQueryParameter("a+=& b", "c+=& d")
.setQueryParameter("a+=& b", "ef")
.build()
assertThat(url.toString()).isEqualTo("http://host/?a%2B%3D%26%20b=ef")
assertThat(url.queryParameter("a+=& b")).isEqualTo("ef")
}
@Test
fun composeQuerySetEncodedQueryParameter() {
val url = parse("http://host/").newBuilder()
.addEncodedQueryParameter("a+=& b", "c+=& d")
.setEncodedQueryParameter("a+=& b", "ef")
.build()
assertThat(url.toString()).isEqualTo("http://host/?a+%3D%26%20b=ef")
assertThat(url.queryParameter("a =& b")).isEqualTo("ef")
}
@Test
fun composeQueryMultipleEncodedValuesForParameter() {
val url = parse("http://host/").newBuilder()
.addQueryParameter("a+=& b", "c+=& d")
.addQueryParameter("a+=& b", "e+=& f")
.build()
assertThat(url.toString())
.isEqualTo("http://host/?a%2B%3D%26%20b=c%2B%3D%26%20d&a%2B%3D%26%20b=e%2B%3D%26%20f")
assertThat(url.querySize).isEqualTo(2)
assertThat(url.queryParameterNames).isEqualTo(setOf("a+=& b"))
assertThat(url.queryParameterValues("a+=& b"))
.containsExactly("c+=& d", "e+=& f")
}
@Test
fun absentQueryIsZeroNameValuePairs() {
val url = parse("http://host/").newBuilder()
.query(null)
.build()
assertThat(url.querySize).isEqualTo(0)
}
@Test
fun emptyQueryIsSingleNameValuePairWithEmptyKey() {
val url = parse("http://host/").newBuilder()
.query("")
.build()
assertThat(url.querySize).isEqualTo(1)
assertThat(url.queryParameterName(0)).isEqualTo("")
assertThat(url.queryParameterValue(0)).isNull()
}
@Test
fun ampersandQueryIsTwoNameValuePairsWithEmptyKeys() {
val url = parse("http://host/").newBuilder()
.query("&")
.build()
assertThat(url.querySize).isEqualTo(2)
assertThat(url.queryParameterName(0)).isEqualTo("")
assertThat(url.queryParameterValue(0)).isNull()
assertThat(url.queryParameterName(1)).isEqualTo("")
assertThat(url.queryParameterValue(1)).isNull()
}
@Test
fun removeAllDoesNotRemoveQueryIfNoParametersWereRemoved() {
val url = parse("http://host/").newBuilder()
.query("")
.removeAllQueryParameters("a")
.build()
assertThat(url.toString()).isEqualTo("http://host/?")
}
@Test
fun queryParametersWithoutValues() {
val url = parse("http://host/?foo&bar&baz")
assertThat(url.querySize).isEqualTo(3)
assertThat(url.queryParameterNames).containsExactly("foo", "bar", "baz")
assertThat(url.queryParameterValue(0)).isNull()
assertThat(url.queryParameterValue(1)).isNull()
assertThat(url.queryParameterValue(2)).isNull()
assertThat(url.queryParameterValues("foo")).isEqualTo(listOf(null as String?))
assertThat(url.queryParameterValues("bar")).isEqualTo(listOf(null as String?))
assertThat(url.queryParameterValues("baz")).isEqualTo(listOf(null as String?))
}
@Test
fun queryParametersWithEmptyValues() {
val url = parse("http://host/?foo=&bar=&baz=")
assertThat(url.querySize).isEqualTo(3)
assertThat(url.queryParameterNames).containsExactly("foo", "bar", "baz")
assertThat(url.queryParameterValue(0)).isEqualTo("")
assertThat(url.queryParameterValue(1)).isEqualTo("")
assertThat(url.queryParameterValue(2)).isEqualTo("")
assertThat(url.queryParameterValues("foo")).isEqualTo(listOf(""))
assertThat(url.queryParameterValues("bar")).isEqualTo(listOf(""))
assertThat(url.queryParameterValues("baz")).isEqualTo(listOf(""))
}
@Test
fun queryParametersWithRepeatedName() {
val url = parse("http://host/?foo[]=1&foo[]=2&foo[]=3")
assertThat(url.querySize).isEqualTo(3)
assertThat(url.queryParameterNames).isEqualTo(setOf("foo[]"))
assertThat(url.queryParameterValue(0)).isEqualTo("1")
assertThat(url.queryParameterValue(1)).isEqualTo("2")
assertThat(url.queryParameterValue(2)).isEqualTo("3")
assertThat(url.queryParameterValues("foo[]")).containsExactly("1", "2", "3")
}
@Test
fun queryParameterLookupWithNonCanonicalEncoding() {
val url = parse("http://host/?%6d=m&+=%20")
assertThat(url.queryParameterName(0)).isEqualTo("m")
assertThat(url.queryParameterName(1)).isEqualTo(" ")
assertThat(url.queryParameter("m")).isEqualTo("m")
assertThat(url.queryParameter(" ")).isEqualTo(" ")
}
@Test
fun parsedQueryDoesntIncludeFragment() {
val url = parse("http://host/?#fragment")
assertThat(url.fragment).isEqualTo("fragment")
assertThat(url.query).isEqualTo("")
assertThat(url.encodedQuery).isEqualTo("")
}
@Test
fun roundTripBuilder() {
val url = HttpUrl.Builder()
.scheme("http")
.username("%")
.password("%")
.host("host")
.addPathSegment("%")
.query("%")
.fragment("%")
.build()
assertThat(url.toString()).isEqualTo("http://%25:%25@host/%25?%25#%25")
assertThat(url.newBuilder().build().toString())
.isEqualTo("http://%25:%25@host/%25?%25#%25")
assertThat(url.resolve("").toString()).isEqualTo("http://%25:%25@host/%25?%25")
}
/**
* Although HttpUrl prefers percent-encodings in uppercase, it should preserve the exact structure
* of the original encoding.
*/
@Test
fun rawEncodingRetained() {
val urlString = "http://%6d%6D:%6d%6D@host/%6d%6D?%6d%6D#%6d%6D"
val url = parse(urlString)
assertThat(url.encodedUsername).isEqualTo("%6d%6D")
assertThat(url.encodedPassword).isEqualTo("%6d%6D")
assertThat(url.encodedPath).isEqualTo("/%6d%6D")
assertThat(url.encodedPathSegments).containsExactly("%6d%6D")
assertThat(url.encodedQuery).isEqualTo("%6d%6D")
assertThat(url.encodedFragment).isEqualTo("%6d%6D")
assertThat(url.toString()).isEqualTo(urlString)
assertThat(url.newBuilder().build().toString()).isEqualTo(urlString)
assertThat(url.resolve("").toString())
.isEqualTo("http://%6d%6D:%6d%6D@host/%6d%6D?%6d%6D")
}
@Test
fun clearFragment() {
val url = parse("http://host/#fragment")
.newBuilder()
.fragment(null)
.build()
assertThat(url.toString()).isEqualTo("http://host/")
assertThat(url.fragment).isNull()
assertThat(url.encodedFragment).isNull()
}
@Test
fun clearEncodedFragment() {
val url = parse("http://host/#fragment")
.newBuilder()
.encodedFragment(null)
.build()
assertThat(url.toString()).isEqualTo("http://host/")
assertThat(url.fragment).isNull()
assertThat(url.encodedFragment).isNull()
}
@Test
fun topPrivateDomain() {
assertThat(parse("https://google.com").topPrivateDomain())
.isEqualTo("google.com")
assertThat(parse("https://adwords.google.co.uk").topPrivateDomain())
.isEqualTo("google.co.uk")
assertThat(parse("https://栃.栃木.jp").topPrivateDomain())
.isEqualTo("xn--ewv.xn--4pvxs.jp")
assertThat(parse("https://xn--ewv.xn--4pvxs.jp").topPrivateDomain())
.isEqualTo("xn--ewv.xn--4pvxs.jp")
assertThat(parse("https://co.uk").topPrivateDomain()).isNull()
assertThat(parse("https://square").topPrivateDomain()).isNull()
assertThat(parse("https://栃木.jp").topPrivateDomain()).isNull()
assertThat(parse("https://xn--4pvxs.jp").topPrivateDomain()).isNull()
assertThat(parse("https://localhost").topPrivateDomain()).isNull()
assertThat(parse("https://127.0.0.1").topPrivateDomain()).isNull()
// https://github.com/square/okhttp/issues/6109
assertThat(parse("http://a./").topPrivateDomain()).isNull()
assertThat(parse("http://squareup.com./").topPrivateDomain())
.isEqualTo("squareup.com")
}
@Test
fun unparseableTopPrivateDomain() {
assertInvalid("http://a../", "Invalid URL host: \"a..\"")
assertInvalid("http://..a/", "Invalid URL host: \"..a\"")
assertInvalid("http://a..b/", "Invalid URL host: \"a..b\"")
assertInvalid("http://.a/", "Invalid URL host: \".a\"")
assertInvalid("http://../", "Invalid URL host: \"..\"")
}
@Test
fun hostnameTelephone() {
// https://www.gosecure.net/blog/2020/10/27/weakness-in-java-tls-host-verification/
// Map the single character telephone symbol (℡) to the string "tel".
assertThat(parse("http://\u2121").host).isEqualTo("tel")
// Map the Kelvin symbol (K) to the string "k".
assertThat(parse("http://\u212A").host).isEqualTo("k")
}
@Test
fun quirks() {
assertThat(parse("http://facebook.com").host).isEqualTo("facebook.com")
assertThat(parse("http://facebooK.com").host).isEqualTo("facebook.com")
assertThat(parse("http://Facebook.com").host).isEqualTo("facebook.com")
assertThat(parse("http://FacebooK.com").host).isEqualTo("facebook.com")
}
@Test
fun trailingDotIsOkay() {
val name251 = "a.".repeat(125) + "a"
assertThat(parse("http://a./").toString()).isEqualTo("http://a./")
assertThat(parse("http://${name251}a./").toString()).isEqualTo("http://${name251}a./")
assertThat(parse("http://${name251}aa/").toString()).isEqualTo("http://${name251}aa/")
assertInvalid("http://${name251}aa./", "Invalid URL host: \"${name251}aa.\"")
}
@Test
fun labelIsEmpty() {
assertInvalid("http:///", "Invalid URL host: \"\"")
assertInvalid("http://a..b/", "Invalid URL host: \"a..b\"")
assertInvalid("http://.a/", "Invalid URL host: \".a\"")
assertInvalid("http://./", "Invalid URL host: \".\"")
assertInvalid("http://../", "Invalid URL host: \"..\"")
assertInvalid("http://.../", "Invalid URL host: \"...\"")
assertInvalid("http://…/", "Invalid URL host: \"…\"")
}
@Test
fun labelTooLong() {
val a63 = "a".repeat(63)
assertThat(parse("http://$a63/").toString()).isEqualTo("http://$a63/")
assertThat(parse("http://a.$a63/").toString()).isEqualTo("http://a.$a63/")
assertThat(parse("http://$a63.a/").toString()).isEqualTo("http://$a63.a/")
assertInvalid("http://a$a63/", "Invalid URL host: \"a$a63\"")
assertInvalid("http://a.a$a63/", "Invalid URL host: \"a.a$a63\"")
assertInvalid("http://a$a63.a/", "Invalid URL host: \"a$a63.a\"")
}
@Test
fun labelTooLongDueToAsciiExpansion() {
val a60 = "a".repeat(60)
assertThat(parse("http://\u2121$a60/").toString()).isEqualTo("http://tel$a60/")
assertInvalid("http://a\u2121$a60/", "Invalid URL host: \"a\u2121$a60\"")
}
@Test
fun hostnameTooLong() {
val dotA126 = "a.".repeat(126)
assertThat(parse("http://a$dotA126/").toString())
.isEqualTo("http://a$dotA126/")
assertInvalid("http://aa$dotA126/", "Invalid URL host: \"aa$dotA126\"")
}
}
| okhttp/src/jvmTest/java/okhttp3/HttpUrlTest.kt | 413544273 |
package org.example.domain
import org.example.service.LoadAgentAtRuntime
public class ExampleUsingPathProperties : LoadAgentAtRuntime() {
// public static void main(String[] args) {
//
//// new ExampleUsingPathProperties().runExample();
// new ExampleUsingPathProperties().runExampleUsingOrders();
// }
//
// public void runExample() {
//
//
//
// LoadExampleData.load();
//
// List<Customer> list2 = Customer.find
// .select("name")
// .fetch("contacts")
// .findList();
//
//
// PathProperties pathProperties = PathProperties.parse("(id,version,name,contacts(id,email,version))");
//
//
// Query<Customer> query = Customer.find.query();
// pathProperties.apply(query);
//
// List<Customer> list = query.findList();
//
// JsonContext jsonContext = Customer.find.db().createJsonContext();
//
// String jsonString = jsonContext.toJsonString(list, true);
// System.out.println(jsonString);
//
//
// for (Customer customer : list2) {
// customer.getName();
// List<Contact> contacts = customer.getContacts();
// if (contacts != null) {
// for (Contact contact : contacts) {
// System.out.println("contact: "+contact.getFirstName()+" "+contact.getLastName());
// }
// }
//
// }
// }
//
// public void runExampleUsingOrders() {
//
// LoadExampleData.load();
//
// PathProperties pathProperties = PathProperties.parse("(id,status,orderDate,customer(id,name),details(*,product(sku)))");
//
// Query<Order> query = Ebean.createQuery(Order.class);
// pathProperties.apply(query);
//
// List<Order> orders = query.where().gt("id", 1).findList();
//
// String rawJson = Ebean.createJsonContext().toJsonString(orders, true);
// System.out.println(rawJson);
// }
} | e-kotlin-maven/src/test/java/org/example/domain/ExampleUsingPathProperties.kt | 3276914025 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.datastore.core
/**
* A subclass of IOException that indicates that the file could not be de-serialized due
* to data format corruption. This exception should not be thrown when the IOException is
* due to a transient IO issue or permissions issue.
*/
public class CorruptionException(message: String, cause: Throwable? = null) :
IOException(message, cause) | datastore/datastore-core/src/commonMain/kotlin/androidx/datastore/core/CorruptionException.kt | 1648366537 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.platform
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.CommitTextCommand
import androidx.compose.ui.text.input.DeleteSurroundingTextInCodePointsCommand
import androidx.compose.ui.text.input.EditCommand
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.ImeOptions
import androidx.compose.ui.text.input.PlatformTextInputService
import androidx.compose.ui.text.input.SetComposingTextCommand
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.substring
import androidx.compose.ui.unit.Density
import java.awt.Point
import java.awt.Rectangle
import java.awt.event.InputMethodEvent
import java.awt.font.TextHitInfo
import java.awt.im.InputMethodRequests
import java.text.AttributedCharacterIterator
import java.text.AttributedString
import java.text.CharacterIterator
import java.util.Locale
import kotlin.math.max
import kotlin.math.min
internal actual interface PlatformInputComponent {
fun enableInput(inputMethodRequests: InputMethodRequests)
fun disableInput()
// Input service needs to know this information to implement Input Method support
val locationOnScreen: Point
val density: Density
}
internal actual class PlatformInput actual constructor(val component: PlatformComponent) :
PlatformTextInputService {
data class CurrentInput(
var value: TextFieldValue,
val onEditCommand: ((List<EditCommand>) -> Unit),
val onImeActionPerformed: ((ImeAction) -> Unit),
val imeAction: ImeAction,
var focusedRect: Rect? = null
)
var currentInput: CurrentInput? = null
// This is required to support input of accented characters using press-and-hold method (http://support.apple.com/kb/PH11264).
// JDK currently properly supports this functionality only for TextComponent/JTextComponent descendants.
// For our editor component we need this workaround.
// After https://bugs.openjdk.java.net/browse/JDK-8074882 is fixed, this workaround should be replaced with a proper solution.
var charKeyPressed: Boolean = false
var needToDeletePreviousChar: Boolean = false
override fun startInput(
value: TextFieldValue,
imeOptions: ImeOptions,
onEditCommand: (List<EditCommand>) -> Unit,
onImeActionPerformed: (ImeAction) -> Unit
) {
val input = CurrentInput(
value, onEditCommand, onImeActionPerformed, imeOptions.imeAction
)
currentInput = input
component.enableInput(methodRequestsForInput(input))
}
override fun stopInput() {
component.disableInput()
currentInput = null
}
override fun showSoftwareKeyboard() {
}
override fun hideSoftwareKeyboard() {
}
override fun updateState(oldValue: TextFieldValue?, newValue: TextFieldValue) {
currentInput?.let { input ->
input.value = newValue
}
}
@Deprecated("This method should not be called, used BringIntoViewRequester instead.")
override fun notifyFocusedRect(rect: Rect) {
currentInput?.let { input ->
input.focusedRect = rect
}
}
internal fun inputMethodCaretPositionChanged(
@Suppress("UNUSED_PARAMETER") event: InputMethodEvent
) {
// Which OSes and which input method could produce such events? We need to have some
// specific cases in mind before implementing this
}
internal fun replaceInputMethodText(event: InputMethodEvent) {
currentInput?.let { input ->
if (event.text == null) {
return
}
val committed = event.text.toStringUntil(event.committedCharacterCount)
val composing = event.text.toStringFrom(event.committedCharacterCount)
val ops = mutableListOf<EditCommand>()
if (needToDeletePreviousChar && isMac && input.value.selection.min > 0) {
needToDeletePreviousChar = false
ops.add(DeleteSurroundingTextInCodePointsCommand(1, 0))
}
// newCursorPosition == 1 leads to effectively ignoring of this parameter in EditCommands
// processing. the cursor will be set after the inserted text.
if (committed.isNotEmpty()) {
ops.add(CommitTextCommand(committed, 1))
}
if (composing.isNotEmpty()) {
ops.add(SetComposingTextCommand(composing, 1))
}
input.onEditCommand.invoke(ops)
}
}
fun methodRequestsForInput(input: CurrentInput) =
object : InputMethodRequests {
override fun getLocationOffset(x: Int, y: Int): TextHitInfo? {
if (input.value.composition != null) {
// TODO: to properly implement this method we need to somehow have access to
// Paragraph at this point
return TextHitInfo.leading(0)
}
return null
}
override fun cancelLatestCommittedText(
attributes: Array<AttributedCharacterIterator.Attribute>?
): AttributedCharacterIterator? {
return null
}
override fun getInsertPositionOffset(): Int {
val composedStartIndex = input.value.composition?.start ?: 0
val composedEndIndex = input.value.composition?.end ?: 0
val caretIndex = input.value.selection.start
if (caretIndex < composedStartIndex) {
return caretIndex
}
if (caretIndex < composedEndIndex) {
return composedStartIndex
}
return caretIndex - (composedEndIndex - composedStartIndex)
}
override fun getCommittedTextLength() =
input.value.text.length - (input.value.composition?.length ?: 0)
override fun getSelectedText(
attributes: Array<AttributedCharacterIterator.Attribute>?
): AttributedCharacterIterator {
if (charKeyPressed) {
needToDeletePreviousChar = true
}
val str = input.value.text.substring(input.value.selection)
return AttributedString(str).iterator
}
override fun getTextLocation(offset: TextHitInfo): Rectangle? {
return input.focusedRect?.let {
val x = (it.right / component.density.density).toInt() +
component.locationOnScreen.x
val y = (it.top / component.density.density).toInt() +
component.locationOnScreen.y
Rectangle(x, y, it.width.toInt(), it.height.toInt())
}
}
override fun getCommittedText(
beginIndex: Int,
endIndex: Int,
attributes: Array<AttributedCharacterIterator.Attribute>?
): AttributedCharacterIterator {
val comp = input.value.composition
val text = input.value.text
val range = TextRange(beginIndex, endIndex.coerceAtMost(text.length))
if (comp == null) {
val res = text.substring(range)
return AttributedString(res).iterator
}
val committed = text.substring(
TextRange(
min(range.min, comp.min),
max(range.max, comp.max).coerceAtMost(text.length)
)
)
return AttributedString(committed).iterator
}
}
}
private fun AttributedCharacterIterator.toStringUntil(index: Int): String {
val strBuf = StringBuffer()
var i = index
if (i > 0) {
var c: Char = setIndex(0)
while (i > 0) {
strBuf.append(c)
c = next()
i--
}
}
return String(strBuf)
}
private fun AttributedCharacterIterator.toStringFrom(index: Int): String {
val strBuf = StringBuffer()
var c: Char = setIndex(index)
while (c != CharacterIterator.DONE) {
strBuf.append(c)
c = next()
}
return String(strBuf)
}
private val isMac =
System.getProperty("os.name").lowercase(Locale.ENGLISH).startsWith("mac")
| compose/ui/ui/src/desktopMain/kotlin/androidx/compose/ui/platform/DesktopPlatformInput.desktop.kt | 922180 |
package data.tinder.login
import com.squareup.moshi.Json
internal class LoginResponseData private constructor(
@field:Json(name = "is_new_user")
val isNewUser: Boolean,
@field:Json(name = "api_token")
val apiToken: String)
| data/src/main/kotlin/data/tinder/login/LoginResponseData.kt | 3416257651 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.test.common
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UExpression
import org.jetbrains.uast.UFile
import org.jetbrains.uast.evaluation.MapBasedEvaluationContext
import org.jetbrains.uast.evaluation.UEvaluationContext
import org.jetbrains.uast.evaluation.UEvaluatorExtension
import org.jetbrains.uast.evaluation.analyzeAll
import org.jetbrains.uast.java.JavaUFile
import com.intellij.testFramework.assertEqualsToFile
import org.jetbrains.uast.visitor.UastVisitor
import java.io.File
interface ValuesTestBase {
fun getTestDataPath(): String
fun getEvaluatorExtension(): UEvaluatorExtension? = null
// TODO: when JavaUFile (and/or its constructor) becomes `internal`, this should move into JavaUFile.
private fun JavaUFile.copy() : JavaUFile = JavaUFile(sourcePsi, languagePlugin)
private fun UFile.analyzeAll() = analyzeAll(extensions = getEvaluatorExtension()?.let { listOf(it) } ?: emptyList())
private fun UFile.asLogValues(evaluationContext: UEvaluationContext, cachedOnly: Boolean) =
ValueLogger(evaluationContext, cachedOnly).apply {
[email protected](this)
}.toString()
fun check(testName: String, file: UFile) {
val valuesFile = File(getTestDataPath(), testName.substringBeforeLast('.') + ".values.txt")
val evaluationContext = file.analyzeAll()
assertEqualsToFile("Log values", valuesFile, file.asLogValues(evaluationContext, cachedOnly = false))
if (file is JavaUFile) {
val copyFile = file.copy()
assertEqualsToFile("Log cached values", valuesFile, copyFile.asLogValues(evaluationContext, cachedOnly = true))
}
}
class ValueLogger(private val evaluationContext: UEvaluationContext, private val cachedOnly: Boolean) : UastVisitor {
private val builder = StringBuilder()
private var level = 0
override fun visitElement(node: UElement): Boolean {
val initialLine = node.asLogString() + " [" + run {
val renderString = node.asRenderString().lines()
if (renderString.size == 1) {
renderString.single()
}
else {
renderString.first() + "..." + renderString.last()
}
} + "]"
(1..level).forEach { _ -> builder.append(" ") }
builder.append(initialLine)
if (node is UExpression) {
val value = if (cachedOnly) {
(evaluationContext as? MapBasedEvaluationContext)?.cachedValueOf(node)
}
else {
evaluationContext.valueOfIfAny(node)
}
builder.append(" = ").append(value ?: "NON-EVALUATED")
}
builder.appendln()
level++
return false
}
override fun afterVisitElement(node: UElement) {
level--
}
override fun toString(): String = builder.toString()
}
}
| uast/uast-tests/src/org/jetbrains/uast/test/common/ValuesTestBase.kt | 396436528 |
// "Change function signature to 'fun f(a: A)'" "true"
// ERROR: 'f' overrides nothing
import a.B
class A {}
class BB : B() {
<caret>override fun f() {}
}
| plugins/kotlin/idea/tests/testData/quickfix/override/nothingToOverride/twoPackages.before.Main.kt | 3818873526 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.typing
import com.intellij.psi.CommonClassNames.JAVA_LANG_OBJECT
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiType
import com.intellij.psi.PsiWildcardType
import com.intellij.psi.util.TypeConversionUtil
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil.createJavaLangClassType
import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments
class ObjectClassTypeCalculator : GrCallTypeCalculator {
override fun getType(receiver: PsiType?, method: PsiMethod, arguments: Arguments?, context: PsiElement): PsiType? {
if (receiver == null) return null
if (method.name != "getClass" || method.containingClass?.qualifiedName != JAVA_LANG_OBJECT) return null
return createJavaLangClassType(PsiWildcardType.createExtends(context.manager, TypeConversionUtil.erasure(receiver)), context)
}
}
| plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/typing/ObjectClassTypeCalculator.kt | 1896186627 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.lang.formatter
import com.intellij.formatting.SpacingBuilder
import com.intellij.psi.TokenType
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.util.applyIf
import org.intellij.plugins.markdown.lang.MarkdownElementTypes
import org.intellij.plugins.markdown.lang.MarkdownLanguage
import org.intellij.plugins.markdown.lang.MarkdownTokenTypeSets
import org.intellij.plugins.markdown.lang.MarkdownTokenTypes
import org.intellij.plugins.markdown.lang.formatter.blocks.MarkdownFormattingBlock
import org.intellij.plugins.markdown.lang.formatter.settings.MarkdownCustomCodeStyleSettings
/**
* Spacing model for Markdown files.
*
* It defines which elements should have blank-lines around, which should
* be prepended with spaces and so on.
*
* Note, that Spacing model works only with [TokenType.WHITE_SPACE] elements,
* if you need to format something INSIDE you should break it into few
* [MarkdownFormattingBlock]
*
* As a source of inspiration following styleguides were used:
* * [Google Markdown code style](https://github.com/google/styleguide/blob/gh-pages/docguide/style.md)
* * [The Arctic Ice Studio Markdown code style](https://github.com/arcticicestudio/styleguide-markdown)
*/
internal object MarkdownSpacingBuilder {
fun get(settings: CodeStyleSettings): SpacingBuilder {
val markdown = settings.getCustomSettings(MarkdownCustomCodeStyleSettings::class.java)
return SpacingBuilder(settings, MarkdownLanguage.INSTANCE)
//CODE
.aroundInside(MarkdownElementTypes.CODE_FENCE, MarkdownElementTypes.MARKDOWN_FILE)
.blankLinesRange(markdown.MIN_LINES_AROUND_BLOCK_ELEMENTS, markdown.MAX_LINES_AROUND_BLOCK_ELEMENTS)
.aroundInside(MarkdownElementTypes.CODE_BLOCK, MarkdownElementTypes.MARKDOWN_FILE)
.blankLinesRange(markdown.MIN_LINES_AROUND_BLOCK_ELEMENTS, markdown.MAX_LINES_AROUND_BLOCK_ELEMENTS)
//TABLE
.aroundInside(MarkdownElementTypes.TABLE, MarkdownElementTypes.MARKDOWN_FILE)
.blankLinesRange(markdown.MIN_LINES_AROUND_BLOCK_ELEMENTS, markdown.MAX_LINES_AROUND_BLOCK_ELEMENTS)
//LISTS
//we can't enforce one line between lists since from commonmark perspective
//one-line break does not break lists, but considered as a space between items
.between(MarkdownTokenTypeSets.LISTS, MarkdownTokenTypeSets.LISTS).blankLines(markdown.MIN_LINES_AROUND_BLOCK_ELEMENTS)
.aroundInside(MarkdownTokenTypeSets.LISTS, MarkdownElementTypes.LIST_ITEM).blankLines(0)
//but we can enforce one line around LISTS
.aroundInside(MarkdownTokenTypeSets.LISTS, MarkdownElementTypes.MARKDOWN_FILE)
.blankLinesRange(markdown.MIN_LINES_AROUND_BLOCK_ELEMENTS, markdown.MAX_LINES_AROUND_BLOCK_ELEMENTS)
.applyIf(markdown.FORCE_ONE_SPACE_AFTER_LIST_BULLET) {
between(MarkdownTokenTypeSets.LIST_MARKERS, MarkdownElementTypes.PARAGRAPH).spaces(1)
}
//HEADINGS
.aroundInside(MarkdownTokenTypeSets.ATX_HEADERS, MarkdownElementTypes.MARKDOWN_FILE)
.blankLinesRange(markdown.MIN_LINES_AROUND_HEADER, markdown.MAX_LINES_AROUND_HEADER)
.applyIf(markdown.FORCE_ONE_SPACE_AFTER_HEADER_SYMBOL) {
between(MarkdownTokenTypes.ATX_HEADER, MarkdownTokenTypes.ATX_CONTENT).spaces(1)
}
//BLOCKQUOTES
.applyIf(markdown.FORCE_ONE_SPACE_AFTER_BLOCKQUOTE_SYMBOL) {
after(MarkdownTokenTypes.BLOCK_QUOTE).spaces(1)
}
//LINKS
.before(MarkdownElementTypes.LINK_DEFINITION).blankLines(1)
// Ensure there is a single line after frontmatter header
.after(MarkdownElementTypes.FRONT_MATTER_HEADER)
.blankLines(1)
//PARAGRAPHS
.betweenInside(MarkdownElementTypes.PARAGRAPH, MarkdownElementTypes.PARAGRAPH, MarkdownElementTypes.MARKDOWN_FILE)
.blankLinesRange(markdown.MIN_LINES_BETWEEN_PARAGRAPHS, markdown.MAX_LINES_BETWEEN_PARAGRAPHS)
.apply {
val spaces = if (markdown.FORCE_ONE_SPACE_BETWEEN_WORDS) 1 else Integer.MAX_VALUE
between(MarkdownTokenTypes.TEXT, MarkdownTokenTypes.TEXT).spacing(1, spaces, 0, markdown.KEEP_LINE_BREAKS_INSIDE_TEXT_BLOCKS, 0)
}
}
private fun SpacingBuilder.RuleBuilder.blankLinesRange(from: Int, to: Int): SpacingBuilder {
return spacing(0, 0, to + 1, false, from)
}
}
| plugins/markdown/core/src/org/intellij/plugins/markdown/lang/formatter/MarkdownSpacingBuilder.kt | 3920562914 |
// "Add 'open val hoge: Int' to 'Foo'" "true"
open class Foo
class Bar: Foo() {
override<caret> val hoge = 3
} | plugins/kotlin/idea/tests/testData/quickfix/override/nothingToOverride/addPropertyOpenClass.kt | 3155664862 |
fun test() {
class Test {
operator fun plus(fn: () -> Test): Test = fn()
}
val test = Test()
test.pl<caret>us {
Test()
}
}
| plugins/kotlin/idea/tests/testData/inspectionsLocal/conventionNameCalls/replaceCallWithBinaryOperator/functionLiteralArgument.kt | 982040011 |
package module2
fun foo() {}
public class Module2Class | plugins/kotlin/jps/jps-plugin/tests/testData/general/KotlinJavaScriptProjectWithTwoModules/module2/src/module2.kt | 3503372239 |
fun foo(): String? = "foo"
fun main(args: Array<String>) {
foo()?.<caret>length
}
| plugins/kotlin/idea/tests/testData/intentions/branched/safeAccessToIfThen/callExpression.kt | 695374656 |
// 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.j2k
import com.intellij.psi.*
import com.intellij.psi.CommonClassNames.JAVA_LANG_OBJECT
import com.intellij.psi.CommonClassNames.JAVA_LANG_STRING
import com.intellij.psi.impl.PsiExpressionEvaluator
import org.jetbrains.kotlin.j2k.ast.*
import java.io.PrintStream
import java.util.*
enum class SpecialMethod(val qualifiedClassName: String?, val methodName: String, val parameterCount: Int?) {
CHAR_SEQUENCE_LENGTH(CharSequence::class.java.name, "length", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse()
},
COLLECTION_SIZE(Collection::class.java.name, "size", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse()
},
COLLECTION_TO_ARRAY(Collection::class.java.name, "toArray", 0) {
override fun ConvertCallData.convertCall() = convertWithChangedName("toTypedArray", argumentsNotNull())
},
COLLECTION_TO_ARRAY_WITH_ARG(Collection::class.java.name, "toArray", 1) {
override fun ConvertCallData.convertCall() = copy(arguments = emptyList()).convertWithChangedName("toTypedArray", emptyList())
},
MAP_SIZE(Map::class.java.name, "size", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse()
},
MAP_KEY_SET(Map::class.java.name, "keySet", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse("keys")
},
MAP_PUT_IF_ABSENT(Map::class.java.name, "putIfAbsent", 2) {
override fun ConvertCallData.convertCall() = convertWithReceiverCast()
},
MAP_REMOVE(Map::class.java.name, "remove", 2) {
override fun ConvertCallData.convertCall() = convertWithReceiverCast()
},
MAP_REPLACE(Map::class.java.name, "replace", 3) {
override fun ConvertCallData.convertCall() = convertWithReceiverCast()
},
MAP_REPLACE_ALL(Map::class.java.name, "replaceAll", 1) {
override fun ConvertCallData.convertCall() = convertWithReceiverCast()
},
MAP_COMPUTE(Map::class.java.name, "compute", 2) {
override fun ConvertCallData.convertCall() = convertWithReceiverCast()
},
MAP_COMPUTE_IF_ABSENT(Map::class.java.name, "computeIfAbsent", 2) {
override fun ConvertCallData.convertCall() = convertWithReceiverCast()
},
MAP_COMPUTE_IF_PRESENT(Map::class.java.name, "computeIfPresent", 2) {
override fun ConvertCallData.convertCall() = convertWithReceiverCast()
},
MAP_MERGE(Map::class.java.name, "merge", 3) {
override fun ConvertCallData.convertCall() = convertWithReceiverCast()
},
MAP_GET_OR_DEFAULT(Map::class.java.name, "getOrDefault", 2) {
override fun ConvertCallData.convertCall() = convertWithReceiverCast()
},
MAP_VALUES(Map::class.java.name, "values", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse()
},
MAP_ENTRY_SET(Map::class.java.name, "entrySet", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse("entries")
},
ENUM_NAME(Enum::class.java.name, "name", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse("name")
},
ENUM_ORDINAL(Enum::class.java.name, "ordinal", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse()
},
CHAR_AT(CharSequence::class.java.name, "charAt", 1) {
override fun ConvertCallData.convertCall() = convertWithChangedName("get", argumentsNotNull())
},
NUMBER_BYTE_VALUE(Number::class.java.name, "byteValue", 0) {
override fun ConvertCallData.convertCall() = convertWithChangedName("toByte", argumentsNotNull())
},
NUMBER_SHORT_VALUE(Number::class.java.name, "shortValue", 0) {
override fun ConvertCallData.convertCall() = convertWithChangedName("toShort", argumentsNotNull())
},
NUMBER_INT_VALUE(Number::class.java.name, "intValue", 0) {
override fun ConvertCallData.convertCall() = convertWithChangedName("toInt", argumentsNotNull())
},
NUMBER_LONG_VALUE(Number::class.java.name, "longValue", 0) {
override fun ConvertCallData.convertCall() = convertWithChangedName("toLong", argumentsNotNull())
},
NUMBER_FLOAT_VALUE(Number::class.java.name, "floatValue", 0) {
override fun ConvertCallData.convertCall() = convertWithChangedName("toFloat", argumentsNotNull())
},
NUMBER_DOUBLE_VALUE(Number::class.java.name, "doubleValue", 0) {
override fun ConvertCallData.convertCall() = convertWithChangedName("toDouble", argumentsNotNull())
},
LIST_REMOVE(List::class.java.name, "remove", 1) {
override fun matches(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher)
= super.matches(method, superMethodsSearcher) && method.parameterList.parameters.single().type.canonicalText == "int"
override fun ConvertCallData.convertCall() = convertWithChangedName("removeAt", argumentsNotNull())
},
THROWABLE_GET_MESSAGE(Throwable::class.java.name, "getMessage", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse("message")
},
THROWABLE_GET_CAUSE(Throwable::class.java.name, "getCause", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse("cause")
},
MAP_ENTRY_GET_KEY(Map::class.java.name + ".Entry", "getKey", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse("key")
},
MAP_ENTRY_GET_VALUE(Map::class.java.name + ".Entry", "getValue", 0) {
override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse("value")
},
OBJECT_EQUALS(null, "equals", 1) {
override fun matches(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher): Boolean
= super.matches(method, superMethodsSearcher) && method.parameterList.parameters.single().type.canonicalText == JAVA_LANG_OBJECT
override fun ConvertCallData.convertCall(): Expression? {
if (qualifier == null || qualifier is PsiSuperExpression) return null
return BinaryExpression(codeConverter.convertExpression(qualifier), codeConverter.convertExpression(arguments.single()), Operator.EQEQ)
}
},
OBJECT_GET_CLASS(JAVA_LANG_OBJECT, "getClass", 0) {
override fun ConvertCallData.convertCall(): Expression {
val identifier = Identifier.withNoPrototype("javaClass", isNullable = false)
return if (qualifier != null)
QualifiedExpression(codeConverter.convertExpression(qualifier), identifier, null)
else
identifier
}
},
OBJECTS_EQUALS("java.util.Objects", "equals", 2) {
override fun ConvertCallData.convertCall()
= BinaryExpression(codeConverter.convertExpression(arguments[0]), codeConverter.convertExpression(arguments[1]), Operator.EQEQ)
},
COLLECTIONS_EMPTY_LIST(Collections::class.java.name, "emptyList", 0) {
override fun ConvertCallData.convertCall()
= MethodCallExpression.buildNonNull(null, "emptyList", ArgumentList.withNoPrototype(), typeArgumentsConverted)
},
COLLECTIONS_EMPTY_SET(Collections::class.java.name, "emptySet", 0) {
override fun ConvertCallData.convertCall()
= MethodCallExpression.buildNonNull(null, "emptySet", ArgumentList.withNoPrototype(), typeArgumentsConverted)
},
COLLECTIONS_EMPTY_MAP(Collections::class.java.name, "emptyMap", 0) {
override fun ConvertCallData.convertCall()
= MethodCallExpression.buildNonNull(null, "emptyMap", ArgumentList.withNoPrototype(), typeArgumentsConverted)
},
COLLECTIONS_SINGLETON_LIST(Collections::class.java.name, "singletonList", 1) {
override fun ConvertCallData.convertCall(): MethodCallExpression {
val argumentList = ArgumentList.withNoPrototype(codeConverter.convertExpression(arguments.single()))
return MethodCallExpression.buildNonNull(null, "listOf", argumentList, typeArgumentsConverted)
}
},
COLLECTIONS_SINGLETON(Collections::class.java.name, "singleton", 1) {
override fun ConvertCallData.convertCall(): MethodCallExpression {
val argumentList = ArgumentList.withNoPrototype(codeConverter.convertExpression(arguments.single()))
return MethodCallExpression.buildNonNull(null, "setOf", argumentList, typeArgumentsConverted)
}
},
STRING_TRIM(JAVA_LANG_STRING, "trim", 0) {
override fun ConvertCallData.convertCall(): Expression? {
val comparison = BinaryExpression(Identifier.withNoPrototype("it", isNullable = false), LiteralExpression("' '").assignNoPrototype(), Operator(JavaTokenType.LE).assignNoPrototype()).assignNoPrototype()
val argumentList = ArgumentList.withNoPrototype(LambdaExpression(null, Block.of(comparison).assignNoPrototype()))
return MethodCallExpression.buildNonNull(codeConverter.convertExpression(qualifier), "trim", argumentList, dotPrototype = dot)
}
},
STRING_REPLACE_ALL(JAVA_LANG_STRING, "replaceAll", 2) {
override fun ConvertCallData.convertCall(): MethodCallExpression {
val argumentList = ArgumentList.withNoPrototype(
codeConverter.convertToRegex(arguments[0]),
codeConverter.convertExpression(arguments[1])
)
return MethodCallExpression.buildNonNull(codeConverter.convertExpression(qualifier), "replace", argumentList, dotPrototype = dot)
}
},
STRING_REPLACE_FIRST(JAVA_LANG_STRING, "replaceFirst", 2) {
override fun ConvertCallData.convertCall(): MethodCallExpression {
return MethodCallExpression.buildNonNull(
codeConverter.convertExpression(qualifier), "replaceFirst",
ArgumentList.withNoPrototype(
codeConverter.convertToRegex(arguments[0]),
codeConverter.convertExpression(arguments[1])
),
dotPrototype = dot
)
}
},
STRING_MATCHES(JAVA_LANG_STRING, "matches", 1) {
override fun ConvertCallData.convertCall(): MethodCallExpression {
val argumentList = ArgumentList.withNoPrototype(codeConverter.convertToRegex(arguments.single()))
return MethodCallExpression.buildNonNull(codeConverter.convertExpression(qualifier), "matches", argumentList, dotPrototype = dot)
}
},
STRING_SPLIT(JAVA_LANG_STRING, "split", 1) {
override fun ConvertCallData.convertCall(): Expression? {
val splitCall = MethodCallExpression.buildNonNull(
codeConverter.convertExpression(qualifier),
"split",
ArgumentList.withNoPrototype(codeConverter.convertToRegex(arguments.single())),
dotPrototype = dot
).assignNoPrototype()
val isEmptyCall = MethodCallExpression.buildNonNull(Identifier.withNoPrototype("it", isNullable = false), "isEmpty").assignNoPrototype()
val isEmptyCallBlock = Block.of(isEmptyCall).assignNoPrototype()
val dropLastCall = MethodCallExpression.buildNonNull(
splitCall,
"dropLastWhile",
ArgumentList.withNoPrototype(LambdaExpression(null, isEmptyCallBlock).assignNoPrototype())
).assignNoPrototype()
return MethodCallExpression.buildNonNull(dropLastCall, "toTypedArray")
}
},
STRING_SPLIT_LIMIT(JAVA_LANG_STRING, "split", 2) {
override fun ConvertCallData.convertCall(): Expression? {
val patternArgument = codeConverter.convertToRegex(arguments[0])
val limitArgument = codeConverter.convertExpression(arguments[1])
val evaluator = PsiExpressionEvaluator()
val limit = evaluator.computeConstantExpression(arguments[1], /* throwExceptionOnOverflow = */ false) as? Int
val splitArguments = when {
limit == null -> // not a constant
listOf(patternArgument, MethodCallExpression.buildNonNull(limitArgument, "coerceAtLeast", ArgumentList.withNoPrototype(LiteralExpression("0").assignNoPrototype())).assignNoPrototype())
limit < 0 -> // negative, same behavior as split(regex) in kotlin
listOf(patternArgument)
limit == 0 -> { // zero, same replacement as for split without limit
val newCallData = copy(arguments = listOf(arguments[0]))
return STRING_SPLIT.convertCall(newCallData)
}
else -> // positive, same behavior as split(regex, limit) in kotlin
listOf(patternArgument, limitArgument)
}
val splitCall = MethodCallExpression.buildNonNull(
codeConverter.convertExpression(qualifier),
"split",
ArgumentList.withNoPrototype(splitArguments),
dotPrototype = dot
).assignNoPrototype()
return MethodCallExpression.buildNonNull(splitCall, "toTypedArray")
}
},
STRING_JOIN(JAVA_LANG_STRING, "join", 2) {
override fun matches(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher): Boolean
= super.matches(method, superMethodsSearcher) && method.parameterList.parameters.last().type.canonicalText == "java.lang.Iterable<? extends java.lang.CharSequence>"
override fun ConvertCallData.convertCall(): Expression? {
val argumentList = ArgumentList.withNoPrototype(codeConverter.convertExpressionsInList(arguments.take(1)))
return MethodCallExpression.buildNonNull(codeConverter.convertExpression(arguments[1]), "joinToString", argumentList)
}
},
STRING_JOIN_VARARG(JAVA_LANG_STRING, "join", null) {
override fun matches(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher): Boolean
= super.matches(method, superMethodsSearcher) && method.parameterList.let { it.parametersCount == 2 && it.parameters.last().isVarArgs }
override fun ConvertCallData.convertCall(): Expression? {
return if (arguments.size == 2 && arguments.last().isAssignableToCharSequenceArray()) {
STRING_JOIN.convertCall(this)
}
else {
MethodCallExpression.buildNonNull(
MethodCallExpression.buildNonNull(null, "arrayOf", ArgumentList.withNoPrototype(codeConverter.convertExpressionsInList(arguments.drop(1)))).assignNoPrototype(),
"joinToString",
ArgumentList.withNoPrototype(codeConverter.convertExpressionsInList(arguments.take(1)))
)
}
}
private fun PsiExpression.isAssignableToCharSequenceArray(): Boolean {
val charSequenceType = PsiType.getTypeByName("java.lang.CharSequence", project, resolveScope)
return (type as? PsiArrayType)?.componentType?.let { charSequenceType.isAssignableFrom(it) } ?: false
}
},
STRING_CONCAT(JAVA_LANG_STRING, "concat", 1) {
override fun ConvertCallData.convertCall()
= BinaryExpression(codeConverter.convertExpression(qualifier), codeConverter.convertExpression(arguments.single()), Operator(JavaTokenType.PLUS).assignNoPrototype())
},
STRING_COMPARE_TO_IGNORE_CASE(JAVA_LANG_STRING, "compareToIgnoreCase", 1) {
override fun ConvertCallData.convertCall() = convertWithIgnoreCaseArgument("compareTo")
},
STRING_EQUALS_IGNORE_CASE(JAVA_LANG_STRING, "equalsIgnoreCase", 1) {
override fun ConvertCallData.convertCall() = convertWithIgnoreCaseArgument("equals")
},
STRING_REGION_MATCHES(JAVA_LANG_STRING, "regionMatches", 5) {
override fun ConvertCallData.convertCall()
= copy(arguments = arguments.drop(1)).convertWithIgnoreCaseArgument("regionMatches", ignoreCaseArgument = arguments.first())
},
STRING_GET_BYTES(JAVA_LANG_STRING, "getBytes", null) {
override fun ConvertCallData.convertCall(): MethodCallExpression {
val charsetArg = arguments.lastOrNull()?.takeIf { it.type?.canonicalText == JAVA_LANG_STRING }
val convertedArguments = codeConverter.convertExpressionsInList(arguments).map {
if (charsetArg != null && it.prototypes?.singleOrNull()?.element == charsetArg)
MethodCallExpression.buildNonNull(null, "charset", ArgumentList.withNoPrototype(it)).assignNoPrototype()
else
it
}
return MethodCallExpression.buildNonNull(
codeConverter.convertExpression(qualifier),
"toByteArray",
ArgumentList.withNoPrototype(convertedArguments),
dotPrototype = dot
)
}
},
STRING_GET_CHARS(JAVA_LANG_STRING, "getChars", 4) {
override fun ConvertCallData.convertCall(): MethodCallExpression {
// reorder parameters: srcBegin(0), srcEnd(1), dst(2), dstOffset(3) -> destination(2), destinationOffset(3), startIndex(0), endIndex(1)
val argumentList = ArgumentList.withNoPrototype(codeConverter.convertExpressionsInList(arguments.slice(listOf(2, 3, 0, 1))))
return MethodCallExpression.buildNonNull(
codeConverter.convertExpression(qualifier),
"toCharArray",
argumentList,
dotPrototype = dot
)
}
},
STRING_VALUE_OF_CHAR_ARRAY(JAVA_LANG_STRING, "valueOf", null) {
override fun matches(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher): Boolean {
return super.matches(method, superMethodsSearcher)
&& method.parameterList.parametersCount.let { it == 1 || it == 3}
&& method.parameterList.parameters.first().type.canonicalText == "char[]"
}
override fun ConvertCallData.convertCall()
= MethodCallExpression.buildNonNull(null, "String", ArgumentList.withNoPrototype(codeConverter.convertExpressionsInList(arguments)))
},
STRING_COPY_VALUE_OF_CHAR_ARRAY(JAVA_LANG_STRING, "copyValueOf", null) {
override fun matches(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher): Boolean {
return super.matches(method, superMethodsSearcher)
&& method.parameterList.parametersCount.let { it == 1 || it == 3 }
&& method.parameterList.parameters.first().type.canonicalText == "char[]"
}
override fun ConvertCallData.convertCall()
= STRING_VALUE_OF_CHAR_ARRAY.convertCall(this)
},
STRING_VALUE_OF(JAVA_LANG_STRING, "valueOf", 1) {
override fun ConvertCallData.convertCall()
= MethodCallExpression.buildNonNull(codeConverter.convertExpression(arguments.single(), shouldParenthesize = true), "toString")
},
SYSTEM_OUT_PRINTLN(PrintStream::class.java.name, "println", null) {
override fun ConvertCallData.convertCall() = convertSystemOutMethodCall(methodName)
},
SYSTEM_OUT_PRINT(PrintStream::class.java.name, "print", null) {
override fun ConvertCallData.convertCall() = convertSystemOutMethodCall(methodName)
};
open fun matches(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher): Boolean
= method.name == methodName && matchesClass(method, superMethodsSearcher) && matchesParameterCount(method)
protected fun matchesClass(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher): Boolean {
if (qualifiedClassName == null) return true
val superMethods = superMethodsSearcher.findDeepestSuperMethods(method)
return if (superMethods.isEmpty())
method.containingClass?.qualifiedName == qualifiedClassName
else
superMethods.any { it.containingClass?.qualifiedName == qualifiedClassName }
}
protected fun matchesParameterCount(method: PsiMethod) = parameterCount == null || parameterCount == method.parameterList.parametersCount
data class ConvertCallData(
val qualifier: PsiExpression?,
@Suppress("ArrayInDataClass") val arguments: List<PsiExpression>,
val typeArgumentsConverted: List<Type>,
val dot: PsiElement?,
val lPar: PsiElement?,
val rPar: PsiElement?,
val codeConverter: CodeConverter
)
@JvmName("convertCallPublic")
fun convertCall(data: ConvertCallData): Expression? = data.convertCall()
protected abstract fun ConvertCallData.convertCall(): Expression?
protected fun ConvertCallData.convertMethodCallToPropertyUse(propertyName: String = methodName): Expression {
val identifier = Identifier.withNoPrototype(propertyName, isNullable = false)
return if (qualifier != null)
QualifiedExpression(codeConverter.convertExpression(qualifier), identifier, dot)
else
identifier
}
protected fun ConvertCallData.argumentsNotNull() = arguments.map { Nullability.NotNull }
protected fun ConvertCallData.convertWithChangedName(name: String, argumentNullabilities: List<Nullability>): MethodCallExpression {
assert(argumentNullabilities.size == arguments.size)
val argumentsConverted = arguments.zip(argumentNullabilities).map {
codeConverter.convertExpression(it.first, null, it.second).assignPrototype(it.first, CommentsAndSpacesInheritance.LINE_BREAKS)
}
val argumentList = ArgumentList(argumentsConverted, LPar.withPrototype(lPar), RPar.withPrototype(rPar)).assignNoPrototype()
return MethodCallExpression.buildNonNull(
codeConverter.convertExpression(qualifier),
name,
argumentList,
typeArgumentsConverted,
dot)
}
protected fun ConvertCallData.convertWithReceiverCast(): MethodCallExpression? {
val convertedArguments = codeConverter.convertExpressionsInList(arguments)
val qualifierWithCast = castQualifierToType(codeConverter, qualifier!!, qualifiedClassName!!) ?: return null
return MethodCallExpression.buildNonNull(
qualifierWithCast,
methodName,
ArgumentList.withNoPrototype(convertedArguments),
typeArgumentsConverted,
dot)
}
private fun castQualifierToType(codeConverter: CodeConverter, qualifier: PsiExpression, type: String): TypeCastExpression? {
val convertedQualifier = codeConverter.convertExpression(qualifier)
val qualifierType = codeConverter.typeConverter.convertType(qualifier.type)
val typeArgs = (qualifierType as? ClassType)?.referenceElement?.typeArgs ?: emptyList()
val referenceElement = ReferenceElement(Identifier.withNoPrototype(type), typeArgs).assignNoPrototype()
val newType = ClassType(referenceElement, Nullability.Default, codeConverter.settings).assignNoPrototype()
return TypeCastExpression(newType, convertedQualifier).assignNoPrototype()
}
protected fun ConvertCallData.convertWithIgnoreCaseArgument(methodName: String, ignoreCaseArgument: PsiExpression? = null): Expression {
val ignoreCaseExpression = ignoreCaseArgument?.let { codeConverter.convertExpression(it) }
?: LiteralExpression("true").assignNoPrototype()
val ignoreCaseArgumentExpression = AssignmentExpression(Identifier.withNoPrototype("ignoreCase"), ignoreCaseExpression, Operator.EQ).assignNoPrototype()
val convertedArguments = arguments.map {
codeConverter.convertExpression(it, null, Nullability.NotNull).assignPrototype(it, CommentsAndSpacesInheritance.LINE_BREAKS)
} + ignoreCaseArgumentExpression
val argumentList = ArgumentList(convertedArguments, LPar.withPrototype(lPar), RPar.withPrototype(rPar)).assignNoPrototype()
return MethodCallExpression.buildNonNull(
codeConverter.convertExpression(qualifier),
methodName,
argumentList,
typeArgumentsConverted,
dot)
}
protected fun ConvertCallData.convertSystemOutMethodCall(methodName: String): Expression? {
if (qualifier !is PsiReferenceExpression) return null
val qqualifier = qualifier.qualifierExpression as? PsiReferenceExpression ?: return null
if (qqualifier.canonicalText != "java.lang.System") return null
if (qualifier.referenceName != "out") return null
if (typeArgumentsConverted.isNotEmpty()) return null
val argumentList = ArgumentList(
codeConverter.convertExpressionsInList(arguments),
LPar.withPrototype(lPar),
RPar.withPrototype(rPar)
).assignNoPrototype()
return MethodCallExpression.buildNonNull(null, methodName, argumentList)
}
protected fun CodeConverter.convertToRegex(expression: PsiExpression?): Expression
= MethodCallExpression.buildNonNull(convertExpression(expression, shouldParenthesize = true), "toRegex").assignNoPrototype()
companion object {
private val valuesByName = values().groupBy { it.methodName }
fun match(method: PsiMethod, argumentCount: Int, services: JavaToKotlinConverterServices): SpecialMethod? {
val candidates = valuesByName[method.name] ?: return null
return candidates
.firstOrNull { it.matches(method, services.superMethodsSearcher) }
?.takeIf { it.parameterCount == null || it.parameterCount == argumentCount } // if parameterCount is specified we should make sure that argument count is correct
}
}
}
| plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/SpecialMethod.kt | 2923345012 |
package org.papathanasiou.denis.ARMS
import org.glassfish.jersey.netty.httpserver.NettyHttpContainerProvider
import org.glassfish.jersey.server.ResourceConfig
import java.net.URI
import com.fasterxml.jackson.module.kotlin.*
import java.io.IOException
object AnotherRESTfulMongoService {
@JvmStatic
fun main(args: Array<String>) {
val mapper = jacksonObjectMapper()
val json = AnotherRESTfulMongoService.javaClass.classLoader.getResource(CONF_JSON)
?: throw IOException("Could not find or load $CONF_JSON from src/main/resources")
val conf = mapper.readValue<ARMSConfiguration>(json)
val connection = MongoConnection(conf.mongoURI)
val resourceConfig = ResourceConfig.forApplication(JaxRSApplication(RESTfulEndpoints(connection.getConnection(), conf.authenticate, conf.authSeeds, TimeBasedOneTimePassword.TOTP)))
val server = NettyHttpContainerProvider.createHttp2Server(URI.create(conf.serviceURI), resourceConfig, null)
Runtime.getRuntime().addShutdownHook(Thread(Runnable { server.close() }))
}
} | src/main/kotlin/org/papathanasiou/denis/ARMS/AnotherRESTfulMongoService.kt | 1900005708 |
package com.okta.oidc.net.response
import org.ccci.gto.android.common.util.getDeclaredFieldOrNull
import org.ccci.gto.android.common.util.getOrNull
private val expiresInField by lazy { getDeclaredFieldOrNull<TokenResponse>("expires_in") }
internal var TokenResponse.expires_in: String?
get() = expiresInField?.getOrNull<String>(this)
set(value) {
expiresInField?.set(this, value)
}
| gto-support-okta/src/main/kotlin/com/okta/oidc/net/response/TokenResponseInternals.kt | 619667996 |
// 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.vcs.log.ui.actions
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.vcs.VcsShowToolWindowTabAction
import com.intellij.vcs.log.VcsLogBundle
import com.intellij.vcs.log.impl.VcsLogContentProvider
import com.intellij.vcs.log.impl.VcsProjectLog
import com.intellij.vcs.log.util.VcsLogUtil
class VcsShowLogAction : VcsShowToolWindowTabAction() {
override val tabName: String get() = VcsLogContentProvider.TAB_NAME
override fun update(e: AnActionEvent) {
super.update(e)
val project = e.project
if (project != null) {
val providers = VcsProjectLog.getLogProviders(project)
val vcsName = VcsLogUtil.getVcsDisplayName(project, providers.values)
e.presentation.text = VcsLogBundle.message("action.Vcs.Show.Log.text.template", vcsName)
}
}
} | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/actions/VcsShowLogAction.kt | 1254364214 |
// "Create property 'foo' as constructor parameter" "true"
class A {
val test: Int get() {
return <caret>foo
}
} | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createVariable/parameter/inAccessorInClass.kt | 3366709714 |
// "Replace with safe (?.) call" "true"
// WITH_STDLIB
var i = 0
fun foo(s: String?) {
i = s<caret>.length
} | plugins/kotlin/idea/tests/testData/quickfix/replaceWithSafeCall/assignment.kt | 4224419289 |
// 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.codeInsight.hints
import com.intellij.codeInsight.hints.presentation.InlayPresentation
import com.intellij.codeInsight.hints.presentation.RootInlayPresentation
import org.jetbrains.annotations.ApiStatus
interface InlayHintsSink {
/**
* Adds inline element to underlying editor.
* @see [com.intellij.openapi.editor.InlayModel.addInlineElement]
* @param placeAtTheEndOfLine being placed at the end of a line hint doesn't allow to place a caret behind it
*/
fun addInlineElement(offset: Int, relatesToPrecedingText: Boolean, presentation: InlayPresentation, placeAtTheEndOfLine: Boolean)
// Left for binary compatibility
@Deprecated("Use addInlineElement(Int, Boolean, InlayPresentation, Boolean) instead",
ReplaceWith("addInlineElement(offset, relatesToPrecedingText, presentation, false)"))
@JvmDefault
fun addInlineElement(offset: Int, relatesToPrecedingText: Boolean, presentation: InlayPresentation) {
addInlineElement(offset, relatesToPrecedingText, presentation, false)
}
/**
* Adds block element to underlying editor.
* Offset doesn't affects position of the inlay in the line, it will be drawn in the very beginning of the line.
* Presentation must shift itself (see com.intellij.openapi.editor.ex.util.EditorUtil#getPlainSpaceWidth)
* @see [com.intellij.openapi.editor.InlayModel.addBlockElement]
*/
fun addBlockElement(offset: Int, relatesToPrecedingText: Boolean, showAbove: Boolean, priority: Int, presentation: InlayPresentation)
/**
* API can be changed in 2020.2!
*/
@ApiStatus.Experimental
fun addInlineElement(offset: Int, presentation: RootInlayPresentation<*>, constraints: HorizontalConstraints?)
/**
* API can be changed in 2020.2!
*/
@ApiStatus.Experimental
fun addBlockElement(logicalLine: Int, showAbove: Boolean, presentation: RootInlayPresentation<*>, constraints: BlockConstraints?)
} | platform/lang-api/src/com/intellij/codeInsight/hints/InlayHintsSink.kt | 2750149325 |
package k
import j.A.X as XX
fun bar(s: String) {
val t: XX = XX()
} | plugins/kotlin/idea/tests/testData/refactoring/move/java/moveClass/moveAsMember/moveClassToTopLevelClassOfAnotherPackage/before/k/specificClassMemberImport.kt | 3096795323 |
class C(filter: (String) -> Boolean)
fun foo(p: C) {
val c: C = <caret>
}
// COMPLETION_TYPE: SMART
// ELEMENT: C
// CHAR: {
| plugins/kotlin/completion/tests/testData/handlers/charFilter/ConstructorWithLambdaArg1.kt | 2721053128 |
// IS_APPLICABLE: false
val v = "a" + (<caret>1.hashCode() // comment
* 2) | plugins/kotlin/idea/tests/testData/intentions/convertToStringTemplate/endOfLineComment.kt | 2846204059 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.