content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package io.github.chrislo27.rhre3.entity.model.special import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.fasterxml.jackson.databind.node.ObjectNode import io.github.chrislo27.rhre3.editor.ClickOccupation import io.github.chrislo27.rhre3.editor.Editor import io.github.chrislo27.rhre3.entity.model.IStretchable import io.github.chrislo27.rhre3.entity.model.ModelEntity import io.github.chrislo27.rhre3.sfxdb.datamodel.impl.special.TextureModel import io.github.chrislo27.rhre3.theme.Theme import io.github.chrislo27.rhre3.track.Remix class TextureEntity(remix: Remix, datamodel: TextureModel) : ModelEntity<TextureModel>(remix, datamodel), IStretchable { var textureHash: String? = null override val isStretchable: Boolean = true override val renderText: String get() = if (textureHash != null) datamodel.name else "${datamodel.name}\n<no texture>" override val glassEffect: Boolean = false override val renderOnTop: Boolean = true init { this.bounds.height = 1f } override fun getRenderColor(editor: Editor, theme: Theme): Color { return theme.entities.cue } override fun renderWithGlass(editor: Editor, batch: SpriteBatch, glass: Boolean) { val textureHash = textureHash if (textureHash != null) { val tex = remix.textureCache[textureHash] ?: return super.render(editor, batch) val renderBacking = this.isSelected || editor.clickOccupation is ClickOccupation.CreatingSelection if (renderBacking) { super.renderWithGlass(editor, batch, glass) } if (this.isSelected) { batch.color = editor.theme.entities.selectionTint } if (renderBacking) { batch.color = batch.color.apply { a *= 0.25f } } val ratio = tex.height.toFloat() / tex.width batch.draw(tex, bounds.x + lerpDifference.x, bounds.y + lerpDifference.y, bounds.width + lerpDifference.width, (bounds.width + lerpDifference.height) * ratio / (Editor.ENTITY_HEIGHT / Editor.ENTITY_WIDTH)) batch.setColor(1f, 1f, 1f, 1f) } else { super.renderWithGlass(editor, batch, glass) } } override fun onStart() { } override fun whilePlaying() { } override fun onEnd() { } override fun saveData(objectNode: ObjectNode) { super.saveData(objectNode) objectNode.put("texHash", textureHash) } override fun readData(objectNode: ObjectNode) { super.readData(objectNode) textureHash = objectNode["texHash"].asText(null) } override fun copy(remix: Remix): TextureEntity { return TextureEntity(remix, datamodel).also { it.updateBounds { it.bounds.set([email protected]) } // Set image ID it.textureHash = [email protected] } } }
core/src/main/kotlin/io/github/chrislo27/rhre3/entity/model/special/TextureEntity.kt
3922767622
package org.stepik.android.view.course_info.ui.adapter.delegates import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import by.kirich1409.viewbindingdelegate.viewBinding import org.stepic.droid.R import org.stepic.droid.databinding.ViewCourseInfoInstructorsBlockBinding import org.stepik.android.model.user.User import org.stepik.android.view.course_info.model.CourseInfoItem import org.stepik.android.view.course_info.ui.adapter.delegates.instructors.CourseInfoInstructorDataAdapterDelegate import org.stepik.android.view.course_info.ui.adapter.delegates.instructors.CourseInfoInstructorPlaceholderAdapterDelegate import ru.nobird.android.ui.adapterdelegates.AdapterDelegate import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder import ru.nobird.android.ui.adapters.DefaultDelegateAdapter class CourseInfoInstructorsDelegate( private val onInstructorClicked: (User) -> Unit ) : AdapterDelegate<CourseInfoItem, DelegateViewHolder<CourseInfoItem>>() { override fun onCreateViewHolder(parent: ViewGroup): ViewHolder = ViewHolder(createView(parent, R.layout.view_course_info_instructors_block)) override fun isForViewType(position: Int, data: CourseInfoItem): Boolean = data is CourseInfoItem.WithTitle.InstructorsBlock inner class ViewHolder(root: View) : DelegateViewHolder<CourseInfoItem>(root) { private val viewBinding: ViewCourseInfoInstructorsBlockBinding by viewBinding { ViewCourseInfoInstructorsBlockBinding.bind(root) } private val adapter = DefaultDelegateAdapter<User?>() init { adapter += CourseInfoInstructorDataAdapterDelegate(onInstructorClicked) adapter += CourseInfoInstructorPlaceholderAdapterDelegate() viewBinding.blockInstructors.let { it.adapter = adapter it.layoutManager = LinearLayoutManager(root.context) it.isNestedScrollingEnabled = false } } override fun onBind(data: CourseInfoItem) { data as CourseInfoItem.WithTitle.InstructorsBlock viewBinding.blockHeader.blockIcon.setImageResource(data.type.icon) viewBinding.blockHeader.blockTitle.setText(data.type.title) adapter.items = data.instructors } } }
app/src/main/java/org/stepik/android/view/course_info/ui/adapter/delegates/CourseInfoInstructorsDelegate.kt
2538011178
package com.mikepenz.iconics.typeface.library.googlematerial import android.content.Context import com.mikepenz.iconics.typeface.ITypeface import com.mikepenz.iconics.typeface.IconicsHolder import com.mikepenz.iconics.typeface.IconicsInitializer class RoundedInitializer : androidx.startup.Initializer<ITypeface> { override fun create(context: Context): ITypeface { IconicsHolder.registerFont(RoundedGoogleMaterial) return RoundedGoogleMaterial } override fun dependencies(): List<Class<out androidx.startup.Initializer<*>>> { return listOf(IconicsInitializer::class.java) } }
google-material-typeface/google-material-typeface-rounded-library/src/main/java/com/mikepenz/iconics/typeface/library/googlematerial/RoundedInitializer.kt
3646171633
/* * Copyright (c) Oleg Sklyar 2017. License: MIT */ package nox.compilation import nox.manifest.OsgiManifest import org.gradle.api.Project import org.gradle.api.internal.project.ProjectInternal import org.gradle.jvm.tasks.Jar import java.net.URI import java.nio.file.* class ManifestUnpackingAction { private val manifestFile: Path constructor(target: Project) { val project = target as ProjectInternal this.manifestFile = Paths.get(project.projectDir.absolutePath, "META-INF", "MANIFEST.MF") val tasks = project.tasks val ext = project.extensions val platform = ext.findByType(OSGiExt::class.java)!! val jarTask = tasks.getByName("jar") as Jar // extension value has precedency over ext; default=unpack if ((jarTask.manifest as OsgiManifest).from != null) { return } else if (platform.unpackOSGiManifest != null) { if (!platform.unpackOSGiManifest!!) { return } } else { val extProps = ext.extraProperties if (extProps.has(unpackOSGiManifest)) { if (!java.lang.Boolean.valueOf(extProps.get(unpackOSGiManifest).toString())!!) { return } } } val assembleTask = tasks.getByName("assemble") val cleanTask = tasks.getByName("clean") assembleTask.doLast { _ -> unpack(jarTask) } cleanTask.doLast { _ -> clean() } } private fun unpack(jarTask: Jar) { // ignore failure here, will throw below manifestFile.parent.toFile().mkdirs() val jarUri = URI.create("jar:" + jarTask.archivePath.toURI()) FileSystems.newFileSystem(jarUri, mapOf<String, Any>()).use { jarfs -> val source = jarfs.getPath("META-INF", "MANIFEST.MF") Files.copy(source, manifestFile, StandardCopyOption.REPLACE_EXISTING) } } private fun clean() { manifestFile.toFile().delete() } companion object { /** * Add osgiUnpackManifest=false to gradle.properties to prevent copying */ private val unpackOSGiManifest = "unpackOSGiManifest" } }
src/main/kotlin/nox/compilation/ManifestUnpackingAction.kt
2490057088
package io.github.chrislo27.rhre3.editor.rendering import com.badlogic.gdx.graphics.OrthographicCamera import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.utils.Align import io.github.chrislo27.rhre3.RHRE3Application import io.github.chrislo27.rhre3.editor.Editor import io.github.chrislo27.rhre3.playalong.Playalong import io.github.chrislo27.rhre3.playalong.PlayalongChars import io.github.chrislo27.rhre3.theme.Theme import io.github.chrislo27.rhre3.util.scaleFont import io.github.chrislo27.rhre3.util.unscaleFont import io.github.chrislo27.toolboks.registry.AssetRegistry import io.github.chrislo27.toolboks.util.gdxutils.fillRect import io.github.chrislo27.toolboks.util.gdxutils.getTextHeight import io.github.chrislo27.toolboks.util.gdxutils.getTextWidth import io.github.chrislo27.toolboks.util.gdxutils.scaleMul import kotlin.math.roundToInt fun Editor.renderPlayalong(batch: SpriteBatch, beatRange: IntRange, alpha: Float) { remix.playalong.renderPlayalong(main, camera, theme, batch, beatRange, alpha) } fun Playalong.renderPlayalong(main: RHRE3Application, camera: OrthographicCamera, theme: Theme, batch: SpriteBatch, beatRange: IntRange, alpha: Float) { if (alpha <= 0f) return val largeFont = main.defaultBorderedFontLarge largeFont.scaleFont(camera) val playalong: Playalong = this val recommendedHeight = largeFont.getTextHeight(PlayalongChars.FILLED_A) val recommendedWidth = largeFont.getTextWidth(PlayalongChars.FILLED_A) val blockHeight = recommendedHeight * 1.5f val blockWidth = recommendedWidth * 1.1f val baseY = camera.position.y + 1.5f val skillStarInputPair = playalong.skillStarInput val skillStarInput = skillStarInputPair?.first for ((beatAt, list) in playalong.inputActionsByBeat) { val listSize = list.size if (skillStarInput != null && skillStarInput.beat == beatAt) { val bottomY = baseY + (blockHeight * listSize) / 2 - (-1 + 0.5f) * blockHeight largeFont.setColor(1f, 1f, 0f, 1f * alpha) val star = "β˜…" val width = largeFont.getTextWidth(star) val height = largeFont.getTextHeight(star) largeFont.draw(batch, star, skillStarInput.beat + (if (!skillStarInputPair.second) skillStarInput.duration else 0f) + width * 0.02f, bottomY + height / 2, 0f, Align.center, false) largeFont.setColor(1f, 1f, 1f, 1f) } list.forEachIndexed { index, inputAction -> if (inputAction.beat.roundToInt() > beatRange.last || (inputAction.beat + inputAction.duration).roundToInt() < beatRange.first) return@forEachIndexed largeFont.setColor(1f, 1f, 1f, 1f * alpha) val bottomY = baseY + (blockHeight * listSize) / 2 - (index + 0.5f) * blockHeight // Backing line if (!inputAction.isInstantaneous) { batch.setColor(theme.trackLine.r, theme.trackLine.g, theme.trackLine.b, theme.trackLine.a * alpha) batch.fillRect(inputAction.beat, bottomY - 0.5f, inputAction.duration, 1f) } val results = playalong.inputted[inputAction] val inProgress = playalong.inputsInProgress[inputAction] if (inProgress != null) largeFont.setColor(0.2f, 0.57f, 1f, 1f * alpha) if (results != null && results.results.isNotEmpty()) { if (!results.missed) { largeFont.setColor(0.2f, 1f, 0.2f, 1f * alpha) batch.setColor(0.2f, 1f, 0.2f, 1f * alpha) } else { largeFont.setColor(1f, 0.15f, 0.15f, 1f * alpha) batch.setColor(1f, 0.15f, 0.15f, 1f * alpha) } } else { // if (inputAction.method == PlayalongMethod.RELEASE_AND_HOLD) { // batch.setColor(0.75f, 0.35f, 1f, 1f * alpha) // largeFont.setColor(0.75f, 0.35f, 1f, 1f * alpha) // } } // For non-instantaneous inputs, draw a long line (progress) if (!inputAction.isInstantaneous) { val defWidth = inputAction.duration val width = if (inProgress != null) { batch.setColor(0.2f, 0.57f, 1f, 1f * alpha) largeFont.setColor(0.2f, 0.57f, 1f, 1f * alpha) remix.tempos.secondsToBeats(remix.tempos.beatsToSeconds((remix.beat - inputAction.beat)) - (if (inputAction.input.isTouchScreen) playalong.calibratedMouseOffset else playalong.calibratedKeyOffset)) } else if (results != null) { (defWidth + (remix.tempos.secondsToBeats(remix.tempos.beatsToSeconds(inputAction.beat + inputAction.duration) + results.results.last().offset) - (inputAction.beat + inputAction.duration))) } else 0f batch.fillRect(inputAction.beat, bottomY - 0.5f, width.coerceAtLeast(0f), 1f) } val x = inputAction.beat val y = bottomY val boxWidth = blockWidth val boxHeight = blockHeight val lastBatchColor = batch.packedColor // Backing box batch.setColor(0f, 0f, 0f, 0.4f * alpha) batch.fillRect(x - boxWidth / 2, y - boxHeight / 2, boxWidth, boxHeight) batch.setColor(1f, 1f, 1f, 0.75f * alpha) val thinWidth = boxWidth * 0.05f batch.fillRect(x - thinWidth / 2, y - boxHeight / 2, thinWidth, boxHeight) batch.setColor(1f, 1f, 1f, 1f * alpha) // Render text or texture val trackDisplayText = if (inputAction.method.isRelease) inputAction.input.releaseTrackDisplayText else inputAction.input.trackDisplayText val isTexID = if (inputAction.method.isRelease) inputAction.input.releaseTrackDisplayIsTexID else inputAction.input.trackDisplayIsTexID if (isTexID) { batch.packedColor = lastBatchColor batch.draw(AssetRegistry.get<Texture>(trackDisplayText), x - boxWidth / 2, y - boxHeight / 2, boxWidth, boxHeight) batch.setColor(1f, 1f, 1f, 1f) } else { val estHeight = largeFont.getTextHeight(trackDisplayText) val scaleY = if (estHeight > recommendedHeight) { recommendedHeight / estHeight } else 1f largeFont.scaleMul(scaleY) val estWidth = largeFont.getTextWidth(trackDisplayText) val scaleX = if (estWidth > recommendedWidth) { recommendedWidth / estWidth } else 1f largeFont.scaleMul(scaleX) // val width = largeFont.getTextWidth(trackDisplayText) val height = largeFont.getTextHeight(trackDisplayText) largeFont.draw(batch, trackDisplayText, x, y + height / 2, 0f, Align.center, false) largeFont.setColor(1f, 1f, 1f, 1f) largeFont.scaleMul(1f / scaleX) largeFont.scaleMul(1f / scaleY) } } } batch.setColor(1f, 1f, 1f, 1f) largeFont.unscaleFont() }
core/src/main/kotlin/io/github/chrislo27/rhre3/editor/rendering/PlayalongRendering.kt
1570605817
package tests.coding import io.fluidsonic.json.* import kotlin.reflect.* import kotlin.test.* class FixedCodecProviderTest { @Test fun testDecodingMatchesExactInterface() { expect( provider(UnrelatedDecoderCodec, ParentDecoderCodec, ChildDecoderCodec) .decoderCodecForType<Parent, Context>() ) .toBe(ParentDecoderCodec) } @Test fun testDecodingMatchesExactClass() { expect( provider(UnrelatedDecoderCodec, ChildDecoderCodec, ParentDecoderCodec) .decoderCodecForType<Child, Context>() ) .toBe(ChildDecoderCodec) } @Test fun testDecodingObeysOrderOfCodecs() { expect( provider(UnrelatedDecoderCodec, ChildDecoderCodec2, ChildDecoderCodec) .decoderCodecForType<Child, Context>() ) .toBe(ChildDecoderCodec2) } @Test fun testEncodingMatchesExactInterface() { expect( provider(UnrelatedEncoderCodec, ParentEncoderCodec, ChildEncoderCodec) .encoderCodecForClass(Parent::class) ) .toBe(ParentEncoderCodec) } @Test fun testEncodingMatchesExactClassType() { expect( provider(UnrelatedEncoderCodec, ChildEncoderCodec, ParentEncoderCodec) .encoderCodecForClass(Child::class) ) .toBe(ChildEncoderCodec) } @Test fun testEncodingMatchesArrayTypes() { expect( provider(ArrayJsonCodec) .encoderCodecForClass(Array<Any?>::class) ) .toBe(ArrayJsonCodec) expect( provider(ArrayJsonCodec) .encoderCodecForClass(Array<String>::class) ) .toBe(ArrayJsonCodec) } @Test fun testEncodingMatchesSubclasses() { expect( provider(UnrelatedEncoderCodec, ParentEncoderCodec, ChildEncoderCodec) .encoderCodecForClass(Child::class) ) .toBe(ParentEncoderCodec) } @Test fun testEncodingMatchesPrimitiveArrayTypes() { expect( provider(ArrayJsonCodec) .encoderCodecForClass(IntArray::class as KClass<*>) ) .toBe(null) } @Test fun testEncodingObeysOrderOfCodecs() { expect( provider(UnrelatedEncoderCodec, ParentEncoderCodec, ChildEncoderCodec) .encoderCodecForClass(Child::class) ) .toBe(ParentEncoderCodec) } private fun provider(vararg codecs: JsonDecoderCodec<*, Context>) = FixedCodecProvider(codecs.toList()) private fun provider(vararg codecs: JsonEncoderCodec<*, Context>) = FixedCodecProvider(codecs.toList()) interface Parent object Child : Parent object Context : JsonCodingContext interface Unrelated object ChildDecoderCodec : JsonDecoderCodec<Child, Context> { override fun JsonDecoder<Context>.decode(valueType: JsonCodingType<Child>) = error("dummy") override val decodableType = jsonCodingType<Child>() } object ChildDecoderCodec2 : JsonDecoderCodec<Child, Context> { override fun JsonDecoder<Context>.decode(valueType: JsonCodingType<Child>) = error("dummy") override val decodableType = jsonCodingType<Child>() } object ChildEncoderCodec : JsonEncoderCodec<Child, Context> { override fun JsonEncoder<Context>.encode(value: Child) = error("dummy") override val encodableClass = Child::class } object ParentDecoderCodec : JsonDecoderCodec<Parent, Context> { override fun JsonDecoder<Context>.decode(valueType: JsonCodingType<Parent>) = error("dummy") override val decodableType = jsonCodingType<Parent>() } object ParentEncoderCodec : JsonEncoderCodec<Parent, Context> { override fun JsonEncoder<Context>.encode(value: Parent) = error("dummy") override val encodableClass = Parent::class } object UnrelatedDecoderCodec : JsonDecoderCodec<Unrelated, Context> { override fun JsonDecoder<Context>.decode(valueType: JsonCodingType<Unrelated>) = error("dummy") override val decodableType = jsonCodingType<Unrelated>() } object UnrelatedEncoderCodec : JsonEncoderCodec<Unrelated, Context> { override fun JsonEncoder<Context>.encode(value: Unrelated) = error("dummy") override val encodableClass = Unrelated::class } }
coding/tests-jvm/FixedCodecProviderTest.kt
3409159834
// 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 git4idea.index.actions import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.vcs.VcsShowToolWindowTabAction import git4idea.index.GitStageContentProvider import git4idea.index.isStagingAreaAvailable class GitShowStagingAreaAction: VcsShowToolWindowTabAction() { override val tabName: String get() = GitStageContentProvider.STAGING_AREA_TAB_NAME override fun update(e: AnActionEvent) { super.update(e) e.project?.let { if (!isStagingAreaAvailable(it)) e.presentation.isEnabledAndVisible = false } } }
plugins/git4idea/src/git4idea/index/actions/GitShowStagingAreaAction.kt
4043286908
// 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.util.indexing.roots import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ContentIterator import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileFilter import com.intellij.util.indexing.IndexingBundle import com.intellij.util.indexing.roots.kind.ProjectFileOrDirOrigin import com.intellij.util.indexing.roots.kind.ProjectFileOrDirOriginImpl class ProjectIndexableFilesIteratorImpl(private val fileOrDir: VirtualFile) : ProjectIndexableFilesIterator { override fun getDebugName(): String = "Files under `${fileOrDir.path}`" override fun getIndexingProgressText(): String { return IndexingBundle.message("indexable.files.provider.indexing.fileOrDir.name", fileOrDir.name) } override fun getRootsScanningProgressText(): String { return IndexingBundle.message("indexable.files.provider.scanning.fileOrDir.name", fileOrDir.name) } override fun getOrigin(): ProjectFileOrDirOrigin = ProjectFileOrDirOriginImpl(fileOrDir) override fun iterateFiles( project: Project, fileIterator: ContentIterator, fileFilter: VirtualFileFilter ): Boolean = ProjectFileIndex.getInstance(project).iterateContentUnderDirectory(fileOrDir, fileIterator, fileFilter) }
platform/lang-impl/src/com/intellij/util/indexing/roots/ProjectIndexableFilesIteratorImpl.kt
3186772982
package graphics.scenery.proteins import graphics.scenery.Node import org.joml.Vector3f /** * This is the class which stores the calculation for a color vector along a Mesh. * * @author Justin Buerger <[email protected]> */ //TODO implement iteration depth that the number of children is flexible class Rainbow { /* Palette Rainbow colors palette has 7 HEX, RGB codes colors: HEX: #ff0000 RGB: (255, 0, 0), HEX: #ffa500 RGB: (255, 165, 0), HEX: #ffff00 RGB: (255, 255, 0), HEX: #008000 RGB: (0, 128, 0), HEX: #0000ff RGB: (0, 0, 255), HEX: #4b0082 RGB: (75, 0, 130), HEX: #ee82ee RGB: (238, 130, 238).* *see: https://colorswall.com/palette/102/ */ private val rainbowPaletteNotScaled = listOf(Vector3f(255f, 0f, 0f), Vector3f(255f, 165f, 0f), Vector3f(255f, 255f, 0f), Vector3f(0f, 128f, 0f), Vector3f(0f, 0f, 255f), Vector3f(75f, 0f, 135f), Vector3f(238f, 130f, 238f)) private val rainbowPalette = rainbowPaletteNotScaled.map { it.mul(1/255f) } /** * Assigns each child its color. */ fun colorVector(subProtein: Node) { var childrenSize = 0 subProtein.children.forEach { ss -> ss.children.forEach { childrenSize++ } } val childrenCount = childrenSize val sixth = (childrenCount/6) val colorList = ArrayList<Vector3f>(childrenCount) for(j in 1..6) { val dif = Vector3f() rainbowPalette[j].sub(rainbowPalette[j-1], dif) for(i in 0 until sixth) { val color = Vector3f() colorList.add(dif.mul(i.toFloat()/sixth.toFloat(), color).add(rainbowPalette[j-1], color)) } } for(k in 0 until (childrenCount - colorList.size)) { colorList.add(rainbowPalette[6]) } var listIndex = 0 subProtein.children.forEach { ss -> ss.children.forEach { it.ifMaterial { diffuse = colorList[listIndex] } listIndex++ } } } }
src/main/kotlin/graphics/scenery/proteins/Rainbow.kt
29463049
package tests.coding import java.time.* internal val monthDayData: TestData<MonthDay> = TestData( symmetric = mapOf( MonthDay.parse("--12-03") to "\"--12-03\"" ) )
coding-jdk8/tests-jvm/data/extended/monthDayData.kt
3304595197
// 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.openapi.vcs.ui.cloneDialog import com.intellij.openapi.application.ModalityState import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.project.Project import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import javax.swing.Icon /** * Extension point that provide an ability to add integration with specific cloud repository hosting/service (e.g "GitHub", "BitBucket", etc) */ @ApiStatus.OverrideOnly interface VcsCloneDialogExtension { companion object { val EP_NAME = ExtensionPointName.create<VcsCloneDialogExtension>("com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogExtension") } /** * Visible name of extension (e.g. "Repository URL", "GitHub", etc) */ @Nls fun getName(): String /** * Visible icon of extension */ fun getIcon(): Icon /** * Additional status lines, which may contain some info and actions related to authorized accounts, internal errors, etc */ fun getAdditionalStatusLines(): List<VcsCloneDialogExtensionStatusLine> = emptyList() /** * Optional tooltip for extension item */ @Nls fun getTooltip(): String? = null @Deprecated(message = "Implement createMainComponent(Project, ModalityState)") fun createMainComponent(project: Project): VcsCloneDialogExtensionComponent /** * Builds [VcsCloneDialogExtensionComponent] that would be displayed on center of get-from-vcs dialog when extension is selected. * Will be called lazily and once on first choosing of extension. */ @JvmDefault fun createMainComponent(project: Project, modalityState: ModalityState): VcsCloneDialogExtensionComponent { return createMainComponent(project) } }
platform/vcs-api/src/com/intellij/openapi/vcs/ui/cloneDialog/VcsCloneDialogExtension.kt
1696456737
// 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.facet import com.intellij.facet.impl.invalid.InvalidFacetManager import com.intellij.facet.mock.* import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.module.impl.ProjectLoadingErrorsHeadlessNotifier import com.intellij.openapi.util.JDOMUtil import com.intellij.testFramework.HeavyPlatformTestCase class FacetTypeUnloadingTest : HeavyPlatformTestCase() { fun `test unload and load facet`() { val facetManager = FacetManager.getInstance(module) val addedFacet = runWithRegisteredFacetTypes(MockFacetType()) { runWriteAction { val model = facetManager.createModifiableModel() val facet = MockFacet(module, "mock", MockFacetConfiguration("my data")) model.addFacet(facet) model.commit() assertTrue(facet.isInitialized) assertFalse(facet.isDisposed) assertEquals("mock", facetManager.getFacetsByType(MockFacetType.ID).single().name) return@runWriteAction facet } } assertTrue(facetManager.getFacetsByType(MockFacetType.ID).isEmpty()) assertTrue(addedFacet.isDisposed) val invalidFacet = InvalidFacetManager.getInstance(myProject).invalidFacets.single() assertEquals("mock", invalidFacet.name) assertEquals("<configuration data=\"my data\" />", JDOMUtil.write(invalidFacet.configuration.facetState.configuration)) registerFacetType(MockFacetType(), testRootDisposable) assertTrue(InvalidFacetManager.getInstance(myProject).invalidFacets.isEmpty()) val mockFacet = facetManager.getFacetsByType(MockFacetType.ID).single() assertEquals("mock", mockFacet.name) assertEquals("my data", mockFacet.configuration.data) assertTrue(mockFacet.isInitialized) assertFalse(mockFacet.isDisposed) } fun `test unload and load facet with sub facets`() { val facetManager = FacetManager.getInstance(module) runWithRegisteredFacetTypes(MockFacetType(), MockSubFacetType()) { runWriteAction { val model = facetManager.createModifiableModel() val facet = MockFacet(module, "mock") model.addFacet(facet) model.addFacet(MockSubFacetType.getInstance().createFacet(module, "sub-facet", MockFacetConfiguration(), facet)) model.commit() } assertEquals("mock", facetManager.getFacetsByType(MockFacetType.ID).single().name) assertEquals("sub-facet", facetManager.getFacetsByType(MockSubFacetType.ID).single().name) } assertTrue(facetManager.getFacetsByType(MockFacetType.ID).isEmpty()) assertTrue(facetManager.getFacetsByType(MockSubFacetType.ID).isEmpty()) val invalidFacet = InvalidFacetManager.getInstance(myProject).invalidFacets.single() assertEquals("mock", invalidFacet.name) val subFacetState = invalidFacet.configuration.facetState.subFacets.single() assertEquals("sub-facet", subFacetState.name) registerFacetType(MockFacetType(), testRootDisposable) registerFacetType(MockSubFacetType(), testRootDisposable) assertTrue(InvalidFacetManager.getInstance(myProject).invalidFacets.isEmpty()) val mockFacet = facetManager.getFacetsByType(MockFacetType.ID).single() assertEquals("mock", mockFacet.name) val mockSubFacet = facetManager.getFacetsByType(MockSubFacetType.ID).single() assertEquals("sub-facet", mockSubFacet.name) assertSame(mockFacet, mockSubFacet.underlyingFacet) } fun `test unload and load sub facet`() { val facetManager = FacetManager.getInstance(module) registerFacetType(MockFacetType(), testRootDisposable) runWithRegisteredFacetTypes(MockSubFacetType()) { runWriteAction { val model = facetManager.createModifiableModel() val facet = MockFacet(module, "mock") model.addFacet(facet) model.addFacet(MockSubFacetType.getInstance().createFacet(module, "sub-facet", MockFacetConfiguration(), facet)) model.commit() } assertEquals("mock", facetManager.getFacetsByType(MockFacetType.ID).single().name) assertEquals("sub-facet", facetManager.getFacetsByType(MockSubFacetType.ID).single().name) } val mockFacet = facetManager.getFacetsByType(MockFacetType.ID).single() assertEquals("mock", mockFacet.name) assertTrue(facetManager.getFacetsByType(MockSubFacetType.ID).isEmpty()) val invalidFacet = InvalidFacetManager.getInstance(myProject).invalidFacets.single() assertEquals("sub-facet", invalidFacet.name) assertSame(mockFacet, invalidFacet.underlyingFacet) registerFacetType(MockSubFacetType(), testRootDisposable) assertTrue(InvalidFacetManager.getInstance(myProject).invalidFacets.isEmpty()) val mockSubFacet = facetManager.getFacetsByType(MockSubFacetType.ID).single() assertEquals("sub-facet", mockSubFacet.name) assertSame(mockFacet, mockSubFacet.underlyingFacet) } override fun setUp() { super.setUp() //initialize facet types and register listeners FacetTypeRegistry.getInstance().facetTypes ProjectLoadingErrorsHeadlessNotifier.setErrorHandler({}, testRootDisposable) } }
java/idea-ui/testSrc/com/intellij/facet/FacetTypeUnloadingTest.kt
2555573153
// 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.util.ui.codereview import com.intellij.ide.ui.AntialiasingType import com.intellij.openapi.util.IconLoader import com.intellij.ui.BrowserHyperlinkListener import com.intellij.util.ui.GraphicsUtil import com.intellij.util.ui.JBHtmlEditorKit import com.intellij.util.ui.JBUI import org.jetbrains.annotations.Nls import java.awt.Graphics import java.awt.Shape import javax.swing.JEditorPane import javax.swing.SizeRequirements import javax.swing.text.DefaultCaret import javax.swing.text.Element import javax.swing.text.View import javax.swing.text.ViewFactory import javax.swing.text.html.HTML import javax.swing.text.html.InlineView import javax.swing.text.html.ParagraphView import kotlin.math.max private const val ICON_INLINE_ELEMENT_NAME = "icon-inline" // NON-NLS open class BaseHtmlEditorPane(iconsClass: Class<*>) : JEditorPane() { init { editorKit = object : JBHtmlEditorKit(true) { override fun getViewFactory() = createViewFactory(iconsClass) } isEditable = false isOpaque = false addHyperlinkListener(BrowserHyperlinkListener.INSTANCE) margin = JBUI.emptyInsets() GraphicsUtil.setAntialiasingType(this, AntialiasingType.getAAHintForSwingComponent()) val caret = caret as DefaultCaret caret.updatePolicy = DefaultCaret.NEVER_UPDATE } fun setBody(@Nls body: String) { if (body.isEmpty()) { text = "" } else { text = "<html><body>$body</body></html>" } } protected open fun createViewFactory(iconsClass: Class<*>): ViewFactory = HtmlEditorViewFactory(iconsClass) protected open class HtmlEditorViewFactory(private val iconsClass: Class<*>) : JBHtmlEditorKit.JBHtmlFactory() { override fun create(elem: Element): View { if (ICON_INLINE_ELEMENT_NAME == elem.name) { val icon = elem.attributes.getAttribute(HTML.Attribute.SRC) ?.let { IconLoader.getIcon(it as String, iconsClass) } if (icon != null) { return object : InlineView(elem) { override fun getPreferredSpan(axis: Int): Float { when (axis) { View.X_AXIS -> return icon.iconWidth.toFloat() + super.getPreferredSpan(axis) else -> return super.getPreferredSpan(axis) } } override fun paint(g: Graphics, allocation: Shape) { super.paint(g, allocation) icon.paintIcon(null, g, allocation.bounds.x, allocation.bounds.y) } } } } val view = super.create(elem) if (view is ParagraphView) { return MyParagraphView(elem) } return view } } protected open class MyParagraphView(elem: Element) : ParagraphView(elem) { override fun calculateMinorAxisRequirements(axis: Int, r: SizeRequirements?): SizeRequirements { var r = r if (r == null) { r = SizeRequirements() } r.minimum = layoutPool.getMinimumSpan(axis).toInt() r.preferred = max(r.minimum, layoutPool.getPreferredSpan(axis).toInt()) r.maximum = Integer.MAX_VALUE r.alignment = 0.5f return r } } }
platform/vcs-code-review/src/com/intellij/util/ui/codereview/BaseHtmlEditorPane.kt
1707262251
/* * Copyright 2002-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.web.reactive.function.server import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.reactor.awaitSingleOrNull import kotlinx.coroutines.reactive.awaitSingle import kotlinx.coroutines.reactive.asFlow import org.springframework.core.ParameterizedTypeReference import org.springframework.http.MediaType import org.springframework.http.codec.multipart.Part import org.springframework.util.CollectionUtils import org.springframework.util.MultiValueMap import org.springframework.web.server.WebSession import reactor.core.publisher.Flux import reactor.core.publisher.Mono import java.net.InetSocketAddress import java.security.Principal import kotlin.reflect.KClass /** * Extension for [ServerRequest.bodyToMono] providing a `bodyToMono<Foo>()` variant * leveraging Kotlin reified type parameters. This extension is not subject to type * erasure and retains actual generic type arguments. * * @author Sebastien Deleuze * @since 5.0 */ inline fun <reified T : Any> ServerRequest.bodyToMono(): Mono<T> = bodyToMono(object : ParameterizedTypeReference<T>() {}) /** * Extension for [ServerRequest.bodyToFlux] providing a `bodyToFlux<Foo>()` variant * leveraging Kotlin reified type parameters. This extension is not subject to type * erasure and retains actual generic type arguments. * * @author Sebastien Deleuze * @since 5.0 */ inline fun <reified T : Any> ServerRequest.bodyToFlux(): Flux<T> = bodyToFlux(object : ParameterizedTypeReference<T>() {}) /** * Coroutines [kotlinx.coroutines.flow.Flow] based variant of [ServerRequest.bodyToFlux]. * * @author Sebastien Deleuze * @since 5.2 */ inline fun <reified T : Any> ServerRequest.bodyToFlow(): Flow<T> = bodyToFlux<T>().asFlow() /** * `KClass` coroutines [kotlinx.coroutines.flow.Flow] based variant of [ServerRequest.bodyToFlux]. * Please consider `bodyToFlow<Foo>` variant if possible. * * @author Igor Manushin * @since 5.3 */ fun <T : Any> ServerRequest.bodyToFlow(clazz: KClass<T>): Flow<T> = bodyToFlux(clazz.java).asFlow() /** * Non-nullable Coroutines variant of [ServerRequest.bodyToMono]. * * @author Sebastien Deleuze * @since 5.2 */ suspend inline fun <reified T : Any> ServerRequest.awaitBody(): T = bodyToMono<T>().awaitSingle() /** * `KClass` non-nullable Coroutines variant of [ServerRequest.bodyToMono]. * Please consider `awaitBody<Foo>` variant if possible. * * @author Igor Manushin * @since 5.3 */ suspend fun <T : Any> ServerRequest.awaitBody(clazz: KClass<T>): T = bodyToMono(clazz.java).awaitSingle() /** * Nullable Coroutines variant of [ServerRequest.bodyToMono]. * * @author Sebastien Deleuze * @since 5.2 */ @Suppress("DEPRECATION") suspend inline fun <reified T : Any> ServerRequest.awaitBodyOrNull(): T? = bodyToMono<T>().awaitSingleOrNull() /** * `KClass` nullable Coroutines variant of [ServerRequest.bodyToMono]. * Please consider `awaitBodyOrNull<Foo>` variant if possible. * * @author Igor Manushin * @since 5.3 */ @Suppress("DEPRECATION") suspend fun <T : Any> ServerRequest.awaitBodyOrNull(clazz: KClass<T>): T? = bodyToMono(clazz.java).awaitSingleOrNull() /** * Coroutines variant of [ServerRequest.formData]. * * @author Sebastien Deleuze * @since 5.2 */ suspend fun ServerRequest.awaitFormData(): MultiValueMap<String, String> = formData().awaitSingle() /** * Coroutines variant of [ServerRequest.multipartData]. * * @author Sebastien Deleuze * @since 5.2 */ suspend fun ServerRequest.awaitMultipartData(): MultiValueMap<String, Part> = multipartData().awaitSingle() /** * Coroutines variant of [ServerRequest.principal]. * * @author Sebastien Deleuze * @since 5.2 */ @Suppress("DEPRECATION") suspend fun ServerRequest.awaitPrincipal(): Principal? = principal().awaitSingleOrNull() /** * Coroutines variant of [ServerRequest.session]. * * @author Sebastien Deleuze * @since 5.2 */ suspend fun ServerRequest.awaitSession(): WebSession = session().awaitSingle() /** * Nullable variant of [ServerRequest.remoteAddress] * * @author Sebastien Deleuze * @since 5.2.2 */ fun ServerRequest.remoteAddressOrNull(): InetSocketAddress? = remoteAddress().orElse(null) /** * Nullable variant of [ServerRequest.attribute] * * @author Sebastien Deleuze * @since 5.2.2 */ fun ServerRequest.attributeOrNull(name: String): Any? = attributes()[name] /** * Nullable variant of [ServerRequest.queryParam] * * @author Sebastien Deleuze * @since 5.2.2 */ fun ServerRequest.queryParamOrNull(name: String): String? { val queryParamValues = queryParams()[name] return if (CollectionUtils.isEmpty(queryParamValues)) { null } else { var value: String? = queryParamValues!![0] if (value == null) { value = "" } value } } /** * Nullable variant of [ServerRequest.Headers.contentLength] * * @author Sebastien Deleuze * @since 5.2.2 */ fun ServerRequest.Headers.contentLengthOrNull(): Long? = contentLength().run { if (isPresent) asLong else null } /** * Nullable variant of [ServerRequest.Headers.contentType] * * @author Sebastien Deleuze * @since 5.2.2 */ fun ServerRequest.Headers.contentTypeOrNull(): MediaType? = contentType().orElse(null)
spring-webflux/src/main/kotlin/org/springframework/web/reactive/function/server/ServerRequestExtensions.kt
2354732367
package com.example.minimaloboe.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 24.sp ), button = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.W500, fontSize = 20.sp ) )
samples/minimaloboe/src/main/java/com/example/minimaloboe/ui/theme/Type.kt
3357614474
// 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.completion.ml.common import com.intellij.codeInsight.completion.ml.CompletionEnvironment import com.intellij.codeInsight.completion.ml.ContextFeatureProvider import com.intellij.codeInsight.completion.ml.MLFeatureValue import com.intellij.completion.ngram.NGram import com.intellij.openapi.editor.ex.util.EditorUtil import com.intellij.openapi.project.DumbService import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.psi.PsiFileSystemItem import com.intellij.util.PlatformUtils class CommonLocationFeatures : ContextFeatureProvider { override fun getName(): String = "common" override fun calculateFeatures(environment: CompletionEnvironment): Map<String, MLFeatureValue> { val lookup = environment.lookup val editor = lookup.topLevelEditor val caretOffset = lookup.lookupStart val logicalPosition = editor.offsetToLogicalPosition(caretOffset) val lineStartOffset = editor.document.getLineStartOffset(logicalPosition.line) val linePrefix = editor.document.getText(TextRange(lineStartOffset, caretOffset)) putNGramScorer(environment) val result = mutableMapOf( "line_num" to MLFeatureValue.float(logicalPosition.line), "col_num" to MLFeatureValue.float(logicalPosition.column), "indent_level" to MLFeatureValue.float(LocationFeaturesUtil.indentLevel(linePrefix, EditorUtil.getTabSize(editor))), "is_in_line_beginning" to MLFeatureValue.binary(StringUtil.isEmptyOrSpaces(linePrefix)) ) if (DumbService.isDumb(lookup.project)) { result["dumb_mode"] = MLFeatureValue.binary(true) } result.addPsiParents(environment.parameters.position, 10) return result } private fun putNGramScorer(environment: CompletionEnvironment) { val scoringFunction = NGram.createScoringFunction(environment.parameters, 4) if(scoringFunction != null) { environment.putUserData(NGram.NGRAM_SCORER_KEY, scoringFunction) } } private fun MutableMap<String, MLFeatureValue>.addPsiParents(position: PsiElement, numParents: Int) { // First parent is always referenceExpression var curParent: PsiElement? = position.parent ?: return for (i in 1..numParents) { curParent = curParent?.parent ?: return val parentName = "parent_$i" this[parentName] = MLFeatureValue.className(curParent::class.java) if (curParent is PsiFileSystemItem) return } } }
plugins/stats-collector/src/com/intellij/completion/ml/common/CommonLocationFeatures.kt
870426033
/* * Copyright (c) 2015-2022 Hallin Information Technology AB * * 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 io.codekvast.intake.agent.service.impl import io.codekvast.common.customer.CustomerData /** * Manages agent state, making sure not too many agents are enabled at the same time. * * @author [email protected] */ interface AgentStateManager { /** * Checks whether a certain agent may proceed with uploading publications. */ fun updateAgentState( customerData: CustomerData, jvmUuid: String, appName: String, environment: String ): Boolean }
product/server/intake/src/main/kotlin/io/codekvast/intake/agent/service/impl/AgentStateManager.kt
4072317854
package com.jetbrains.packagesearch.intellij.plugin.extensions.maven.configuration.ui import com.intellij.openapi.project.Project import com.intellij.ui.DocumentAdapter import com.intellij.ui.RelativeFont import com.intellij.ui.TitledSeparator import com.intellij.util.ui.FormBuilder import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.extensibility.ConfigurableContributor import com.jetbrains.packagesearch.intellij.plugin.extensibility.ConfigurableContributorDriver import com.jetbrains.packagesearch.intellij.plugin.extensions.maven.configuration.PackageSearchMavenConfigurationDefaults import com.jetbrains.packagesearch.intellij.plugin.extensions.maven.configuration.packageSearchMavenConfigurationForProject import javax.swing.JLabel import javax.swing.JTextField import javax.swing.event.DocumentEvent class MavenConfigurableContributor(private val project: Project) : ConfigurableContributor { override fun createDriver() = MavenConfigurableContributorDriver(project) } class MavenConfigurableContributorDriver(project: Project) : ConfigurableContributorDriver { private var modified: Boolean = false private val configuration = packageSearchMavenConfigurationForProject(project) private val textFieldChangeListener = object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { modified = true } } private val mavenScopeEditor = JTextField() .apply { document.addDocumentListener(textFieldChangeListener) } override fun contributeUserInterface(builder: FormBuilder) { builder.addComponent( TitledSeparator(PackageSearchBundle.message("packagesearch.configuration.maven.title")), 0 ) builder.addLabeledComponent( PackageSearchBundle.message("packagesearch.configuration.maven.scopes.default"), mavenScopeEditor ) val label = JLabel( " ${PackageSearchBundle.message("packagesearch.configuration.maven.scopes")} " + PackageSearchMavenConfigurationDefaults.MavenScopes.replace(",", ", ") ) builder.addComponentToRightColumn( RelativeFont.TINY.install(RelativeFont.ITALIC.install(label)) ) } override fun isModified(): Boolean { return modified } override fun reset() { mavenScopeEditor.text = configuration.determineDefaultMavenScope() modified = false } override fun restoreDefaults() { mavenScopeEditor.text = PackageSearchMavenConfigurationDefaults.MavenScope modified = true } override fun apply() { configuration.defaultMavenScope = mavenScopeEditor.text } }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensions/maven/configuration/ui/MavenConfigurableContributor.kt
3759994785
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.refactoring.suggested import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.RefactoringFactory /** * A service performing actual changes in the code when user executes suggested refactoring. */ abstract class SuggestedRefactoringExecution(protected val refactoringSupport: SuggestedRefactoringSupport) { open fun rename(data: SuggestedRenameData, project: Project, editor: Editor) { val relativeCaretOffset = editor.caretModel.offset - anchorOffset(data.declaration) val newName = data.declaration.name!! runWriteAction { data.declaration.setName(data.oldName) } var refactoring = RefactoringFactory.getInstance(project).createRename(data.declaration, newName, true, true) refactoring.respectEnabledAutomaticRenames() val usages = refactoring.findUsages() if (usages.any { it.isNonCodeUsage } && !ApplicationManager.getApplication().isHeadlessEnvironment) { val question = RefactoringBundle.message( "suggested.refactoring.rename.comments.strings.occurrences", data.oldName, newName ) val result = Messages.showOkCancelDialog( project, question, RefactoringBundle.message("suggested.refactoring.rename.comments.strings.occurrences.title"), RefactoringBundle.message("suggested.refactoring.rename.with.preview.button.text"), RefactoringBundle.message("suggested.refactoring.ignore.button.text"), Messages.getQuestionIcon() ) if (result != Messages.OK) { refactoring = RefactoringFactory.getInstance(project).createRename(data.declaration, newName, false, false) refactoring.respectEnabledAutomaticRenames() } } refactoring.run() if (data.declaration.isValid) { editor.caretModel.moveToOffset(relativeCaretOffset + anchorOffset(data.declaration)) } } open fun changeSignature( data: SuggestedChangeSignatureData, newParameterValues: List<NewParameterValue>, project: Project, editor: Editor ) { val preparedData = prepareChangeSignature(data) val relativeCaretOffset = editor.caretModel.offset - anchorOffset(data.declaration) val restoreNewSignature = runWriteAction { data.restoreInitialState(refactoringSupport) } performChangeSignature(data, newParameterValues, preparedData) runWriteAction { PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document) restoreNewSignature() editor.caretModel.moveToOffset(relativeCaretOffset + anchorOffset(data.declaration)) } } /** * Prepares data for Change Signature refactoring while the declaration has state with user changes (the new signature). */ abstract fun prepareChangeSignature(data: SuggestedChangeSignatureData): Any? /** * Performs Change Signature refactoring. This method is invoked with the declaration reverted to its original state * before user changes (the old signature). The list of imports is also reverted to the original state. */ abstract fun performChangeSignature(data: SuggestedChangeSignatureData, newParameterValues: List<NewParameterValue>, preparedData: Any?) private fun anchorOffset(declaration: PsiElement): Int { return refactoringSupport.nameRange(declaration)?.startOffset ?: declaration.startOffset } /** * Use this implementation of [SuggestedRefactoringExecution], if only Rename refactoring is supported for the language. */ open class RenameOnly(refactoringSupport: SuggestedRefactoringSupport) : SuggestedRefactoringExecution(refactoringSupport) { override fun performChangeSignature( data: SuggestedChangeSignatureData, newParameterValues: List<NewParameterValue>, preparedData: Any? ) { throw UnsupportedOperationException() } override fun prepareChangeSignature(data: SuggestedChangeSignatureData): Any? { throw UnsupportedOperationException() } } /** * Class representing value for a new parameter to be used for updating arguments of calls. */ sealed class NewParameterValue { object None : NewParameterValue() data class Expression(val expression: PsiElement) : NewParameterValue() object AnyVariable : NewParameterValue() } }
platform/lang-api/src/com/intellij/refactoring/suggested/SuggestedRefactoringExecution.kt
780354319
/* * WiFiAnalyzer * Copyright (C) 2015 - 2022 VREM Software Development <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.vrem.util import java.util.* val String.Companion.EMPTY: String get() = "" val String.Companion.SPACE_SEPARATOR: String get() = " " fun String.specialTrim(): String = this.trim { it <= ' ' }.replace(" +".toRegex(), String.SPACE_SEPARATOR) fun String.toCapitalize(locale: Locale): String = this.replaceFirstChar { word -> word.uppercase(locale) }
app/src/main/kotlin/com/vrem/util/StringUtils.kt
3345019771
/** <slate_header> author: Kishore Reddy url: www.github.com/code-helix/slatekit copyright: 2015 Kishore Reddy license: www.github.com/code-helix/slatekit/blob/master/LICENSE.md desc: A tool-kit, utility library and server-backend usage: Please refer to license on github for more info. </slate_header> */ package slatekit.examples //<doc:import_required> import slatekit.common.smartvalues.Email import slatekit.results.Try import slatekit.results.Success //</doc:import_required> //<doc:import_examples> import slatekit.results.Outcome //</doc:import_examples> class Example_SmartValues : Command("results") { override fun execute(request: CommandRequest): Try<Any> { //<doc:examples> // Smart strings provide a way to store, validate and describe // a strongly typed/formatted string. This concept is called // a smart string and is designed to be used specifically at // application boundaries ( such as API endpoints ). // There are a few smart strings provided out of the box such as // 1. Email // 2. PhoneUS // 3. SSN // 4. ZipCode val email = Email.of("[email protected]") // Case 1: Get the actual value println("value: " + email.value) // Case 2: Check if valid println("valid?: " + Email.isValid("[email protected]")) // Case 3: Get the name / type of smart string println("name: " + email.meta.name) // Case 4: Description println("desc: " + email.meta.desc) // Case 4: Examples of valid string println("examples: " + email.meta.examples) // Case 5: Format of the string println("format(s): " + email.meta.formats) // Case 6: The regular expression representing string println("reg ex: " + email.meta.expressions) // Case 7: Get the first example println("example: " + email.meta.example) // Case 9: Using slatekit.result types // Try<Email> = Result<Email,Exception> val email2:Try<Email> = Email.attempt("[email protected]") // Outcome<Email> = Result<Email,Err> val email3:Outcome<Email> = Email.outcome("[email protected]") //</doc:examples> return Success("") } /* //<doc:output> {{< highlight yaml >}} value: [email protected] valid?: true name: Email desc: Email Address examples: [[email protected]] format(s): [xxxx@xxxxxxx] reg ex: [([\w\$\.\-_]+)@([\w\.]+)] example: [email protected] domain?: gotham.com dashed?: false {{< /highlight >}} //</doc:output> */ }
src/apps/kotlin/slatekit-examples/src/main/kotlin/slatekit/examples/Example_SmartValues.kt
2578877442
// 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.updateSettings.impl import com.intellij.openapi.updateSettings.UpdateStrategyCustomization import com.intellij.openapi.util.BuildNumber import org.assertj.core.api.Assertions.assertThat import org.junit.Assert.* import org.junit.Test // unless stated otherwise, the behavior described in cases is true for 162+ class UpdateStrategyTest { @Test fun `channel contains no builds`() { val result = check("IU-145.258", ChannelStatus.RELEASE, """<channel id="IDEA_Release" status="release" licensing="release"/>""") assertNull(result.newBuild) } @Test fun `already on the latest build`() { val result = check("IU-145.258", ChannelStatus.RELEASE, """ <channel id="IDEA15_Release" status="release" licensing="release"> <build number="143.2332" version="15.0.5"/> </channel> <channel id="IDEA_Release" status="release" licensing="release"> <build number="145.258" version="2016.1"/> </channel>""") assertNull(result.newBuild) } @Test fun `patch exclusions`() { val channels = """ <channel id="IDEA_Release" status="release" licensing="release"> <build number="145.597" version="2016.1.1"> <patch from="145.596"/> <patch from="145.258" exclusions="win,mac,unix"/> </build> </channel>""" assertNotNull(assertLoaded("IU-145.596", ChannelStatus.RELEASE, channels).patches) assertNull(assertLoaded("IU-145.258", ChannelStatus.RELEASE, channels).patches) } @Test fun `order of builds does not matter`() { val resultDesc = assertLoaded("IU-143.2332", ChannelStatus.RELEASE, """ <channel id="IDEA_Release" status="release" licensing="release"> <build number="145.597" version="2016.1.1"/> <build number="145.258" version="2016.1"/> </channel>""") assertBuild("145.597", resultDesc.newBuild) val resultAsc = assertLoaded("IU-143.2332", ChannelStatus.RELEASE, """ <channel id="IDEA_Release" status="release" licensing="release"> <build number="145.258" version="2016.1"/> <build number="145.597" version="2016.1.1"/> </channel>""") assertBuild("145.597", resultAsc.newBuild) } @Test fun `newer updates are preferred`() { val result = assertLoaded("IU-145.258", ChannelStatus.EAP, """ <channel id="IDEA_EAP" status="eap" licensing="eap"> <build number="145.596" version="2016.1.1 EAP"/> </channel> <channel id="IDEA_Release" status="release" licensing="release"> <build number="145.597" version="2016.1.1"/> </channel>""") assertBuild("145.597", result.newBuild) } @Test fun `newer updates are preferred over more stable ones`() { val result = assertLoaded("IU-145.257", ChannelStatus.EAP, """ <channel id="IDEA_EAP" status="eap" licensing="eap"> <build number="145.596" version="2016.1.1 EAP"/> </channel> <channel id="IDEA_Beta" status="beta" licensing="release"> <build number="145.257" version="2016.1 RC2"/> </channel> <channel id="IDEA_Release" status="release" licensing="release"> <build number="145.258" version="2016.1"/> </channel>""") assertBuild("145.596", result.newBuild) } @Test fun `newer updates from non-allowed channels are ignored`() { val channels = """ <channel id="IDEA_EAP" status="eap" licensing="eap"> <build number="145.596" version="2016.1.1 EAP"/> </channel> <channel id="IDEA_Beta" status="beta" licensing="release"> <build number="145.257" version="2016.1 RC2"/> </channel> <channel id="IDEA_Release" status="release" licensing="release"> <build number="145.258" version="2016.1"/> </channel>""" assertBuild("145.258", assertLoaded("IU-145.256", ChannelStatus.RELEASE, channels).newBuild) assertNull(check("IU-145.258", ChannelStatus.RELEASE, channels).newBuild) } @Test fun `ignored updates are excluded`() { val result = assertLoaded("IU-145.258", ChannelStatus.EAP, """ <channel id="IDEA_EAP" status="eap" licensing="eap"> <build number="145.596" version="2016.1.1 EAP"/> <build number="145.595" version="2016.1.1 EAP"/> </channel>""", listOf("145.596")) assertBuild("145.595", result.newBuild) } @Test fun `ignored same-baseline updates do not hide new major releases`() { val result = assertLoaded("IU-145.971", ChannelStatus.RELEASE, """ <channel id="IDEA_Release" status="release" licensing="release"> <build number="145.1617" version="2016.1.3"/> <build number="145.2070" version="2016.1.4"/> <build number="171.4424" version="2017.1.3"/> </channel>""", listOf("145.1617", "145.2070")) assertBuild("171.4424", result.newBuild) } @Test fun `updates can be targeted for specific builds (different builds)`() { val channels = """ <channel id="IDEA_EAP" status="eap" licensing="eap"> <build number="145.596" version="2016.1.1 EAP" targetSince="145.595" targetUntil="145.*"/> <!-- this build is not for everyone --> <build number="145.595" version="2016.1.1 EAP"/> </channel>""" assertBuild("145.595", assertLoaded("IU-145.258", ChannelStatus.EAP, channels).newBuild) assertBuild("145.596", assertLoaded("IU-145.595", ChannelStatus.EAP, channels).newBuild) } @Test fun `updates can be targeted for specific builds (same build)`() { val channels = """ <channel id="IDEA_EAP" status="release" licensing="release"> <build number="163.101" version="2016.3.1" targetSince="163.0" targetUntil="163.*"><message>bug fix</message></build> <build number="163.101" version="2016.3.1"><message>new release</message></build> </channel>""" assertEquals("new release", assertLoaded("IU-145.258", ChannelStatus.RELEASE, channels).newBuild.message) assertEquals("bug fix", assertLoaded("IU-163.50", ChannelStatus.RELEASE, channels).newBuild.message) } @Test fun `updates from the same baseline are preferred (unified channels)`() { val result = assertLoaded("IU-143.2287", ChannelStatus.EAP, """ <channel id="IDEA_EAP" status="eap" licensing="eap"> <build number="143.2330" version="15.0.5 EAP"/> <build number="145.600" version="2016.1.2 EAP"/> </channel> <channel id="IDEA_Release" status="release" licensing="release"> <build number="143.2332" version="15.0.5"/> <build number="145.597" version="2016.1.1"/> </channel>""") assertBuild("143.2332", result.newBuild) } /* * Since 163. */ @Test fun `updates from the same baseline are preferred (per-release channels)`() { val result = assertLoaded("IU-143.2287", ChannelStatus.EAP, """ <channel id="IDEA_143_EAP" status="eap" licensing="eap"> <build number="143.2330" version="15.0.5 EAP"/> </channel> <channel id="IDEA_143_Release" status="release" licensing="release"> <build number="143.2332" version="15.0.5"/> </channel> <channel id="IDEA_145_EAP" status="eap" licensing="eap"> <build number="145.600" version="2016.1.2 EAP"/> </channel> <channel id="IDEA_Release_145" status="release" licensing="release"> <build number="145.597" version="2016.1.1"/> </channel>""") assertBuild("143.2332", result.newBuild) } @Test fun `cross-baseline updates are perfectly legal`() { val result = assertLoaded("IU-143.2332", ChannelStatus.EAP, """ <channel id="IDEA_Release" status="release" licensing="release"> <build number="143.2332" version="15.0.5"/> <build number="145.597" version="2016.1.1"/> </channel>""") assertBuild("145.597", result.newBuild) } @Test fun `variable-length build numbers are supported`() { val channels = """ <channel id="IDEA_Release" status="release" licensing="release"> <build number="162.11.10" version="2016.2"/> </channel>""" assertBuild("162.11.10", assertLoaded("IU-145.597", ChannelStatus.RELEASE, channels).newBuild) assertBuild("162.11.10", assertLoaded("IU-162.7.23", ChannelStatus.RELEASE, channels).newBuild) assertNull(check("IU-162.11.11", ChannelStatus.RELEASE, channels).newBuild) val result = assertLoaded("IU-162.11.10", ChannelStatus.RELEASE, """ <channel id="IDEA_Release" status="release" licensing="release"> <build number="162.48" version="2016.2.1 EAP"/> </channel>""") assertBuild("162.48", result.newBuild) } @Test fun `for duplicate builds, first matching channel is preferred`() { val build = """<build number="163.9166" version="2016.3.1"/>""" val eap15 = """<channel id="IDEA15_EAP" status="eap" licensing="eap" majorVersion="15">$build</channel>""" val eap = """<channel id="IDEA_EAP" status="eap" licensing="eap" majorVersion="2016">$build</channel>""" val beta15 = """<channel id="IDEA15_Beta" status="beta" licensing="release" majorVersion="15">$build</channel>""" val beta = """<channel id="IDEA_Beta" status="beta" licensing="release" majorVersion="2016">$build</channel>""" val release15 = """<channel id="IDEA15_Release" status="release" licensing="release" majorVersion="15">$build</channel>""" val release = """<channel id="IDEA_Release" status="release" licensing="release" majorVersion="2016">$build</channel>""" // note: this is a test; in production, release builds should never be proposed via channels with EAP licensing assertEquals("IDEA15_EAP", assertLoaded("IU-163.1", ChannelStatus.EAP, (eap15 + eap + beta15 + beta + release15 + release)).updatedChannel.id) assertEquals("IDEA_EAP", assertLoaded("IU-163.1", ChannelStatus.EAP, (eap + eap15 + beta + beta15 + release + release15)).updatedChannel.id) assertEquals("IDEA15_EAP", assertLoaded("IU-163.1", ChannelStatus.EAP, (release15 + release + beta15 + beta + eap15 + eap)).updatedChannel.id) assertEquals("IDEA_EAP", assertLoaded("IU-163.1", ChannelStatus.EAP, (release + release15 + beta + beta15 + eap + eap15)).updatedChannel.id) assertEquals("IDEA15_Beta", assertLoaded("IU-163.1", ChannelStatus.BETA, (release15 + release + beta15 + beta + eap15 + eap)).updatedChannel.id) assertEquals("IDEA_Beta", assertLoaded("IU-163.1", ChannelStatus.BETA, (release + release15 + beta + beta15 + eap + eap15)).updatedChannel.id) assertEquals("IDEA15_Release", assertLoaded("IU-163.1", ChannelStatus.RELEASE, (eap15 + eap + beta15 + beta + release15 + release)).updatedChannel.id) assertEquals("IDEA_Release", assertLoaded("IU-163.1", ChannelStatus.RELEASE, (eap + eap15 + beta + beta15 + release + release15)).updatedChannel.id) assertEquals("IDEA15_Release", assertLoaded("IU-163.1", ChannelStatus.RELEASE, (release15 + release + beta15 + beta + eap15 + eap)).updatedChannel.id) assertEquals("IDEA_Release", assertLoaded("IU-163.1", ChannelStatus.RELEASE, (release + release15 + beta + beta15 + eap + eap15)).updatedChannel.id) } /* * Since 183. */ @Test fun `building linear patch chain`() { val result = assertLoaded("IU-182.3569.1", ChannelStatus.EAP, """ <channel id="IDEA_EAP" status="eap" licensing="eap"> <build number="182.3684.40" version="2018.2 RC2"> <patch from="182.3684.2" size="from 1 to 8"/> </build> <build number="182.3684.2" version="2018.2 RC"> <patch from="182.3569.1" size="2"/> </build> </channel>""") assertBuild("182.3684.40", result.newBuild) assertThat(result.patches?.chain).isEqualTo(listOf("182.3569.1", "182.3684.2", "182.3684.40").map(BuildNumber::fromString)) assertThat(result.patches?.size).isEqualTo("10") } @Test fun `building patch chain across channels`() { val result = assertLoaded("IU-182.3684.40", ChannelStatus.EAP, """ <channel id="IDEA_EAP" status="eap" licensing="eap"> <build number="182.3684.40" version="2018.2 RC2"> <patch from="182.3684.2"/> </build> </channel> <channel id="IDEA_Release" status="release" licensing="release"> <build number="182.3684.41" version="2018.2"> <patch from="182.3684.40"/> </build> </channel> <channel id="IDEA_Stable_EAP" status="eap" licensing="release"> <build number="182.3911.2" version="2018.2.1 EAP"> <patch from="182.3684.41"/> </build> </channel>""") assertBuild("182.3911.2", result.newBuild) assertThat(result.patches?.chain).isEqualTo(listOf("182.3684.40", "182.3684.41", "182.3911.2").map(BuildNumber::fromString)) assertThat(result.patches?.size).isNull() } @Test fun `allow ignored builds in the middle of a chain`() { val result = assertLoaded("IU-183.3795.13", ChannelStatus.EAP, """ <channel id="IDEA_EAP" status="eap" licensing="eap"> <build number="183.4139.22" version="2018.3 EAP"> <patch from="183.3975.18" size="1"/> </build> <build number="183.3975.18" version="2018.3 EAP"> <patch from="183.3795.13" size="1"/> </build> </channel>""", listOf("183.3975.18")) assertBuild("183.4139.22", result.newBuild) assertThat(result.patches?.chain).isEqualTo(listOf("183.3795.13", "183.3975.18", "183.4139.22").map(BuildNumber::fromString)) } private fun check( currentBuild: String, selectedChannel: ChannelStatus, testData: String, ignoredBuilds: List<String> = emptyList(), ): CheckForUpdateResult { val updatesInfoText = """ <products> <product name="IntelliJ IDEA"> <code>IU</code> ${testData} </product> </products>""" val settings = UpdateSettings() settings.selectedChannelStatus = selectedChannel settings.ignoredBuildNumbers += ignoredBuilds return UpdateStrategy( BuildNumber.fromString(currentBuild)!!, parseUpdateData(updatesInfoText, "IU"), settings, UpdateStrategyCustomization(), ).checkForUpdates() } private fun assertLoaded( currentBuild: String, selectedChannel: ChannelStatus, testData: String, ignoredBuilds: List<String> = emptyList(), ): CheckForUpdateResult.Loaded { val result = check(currentBuild, selectedChannel, testData, ignoredBuilds) assertThat(result is CheckForUpdateResult.Loaded) return result as CheckForUpdateResult.Loaded } private fun assertBuild(expected: String, build: BuildInfo) = assertEquals(expected, build.number.asStringWithoutProductCode()) }
platform/platform-tests/testSrc/com/intellij/openapi/updateSettings/impl/UpdateStrategyTest.kt
4176034704
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.data import com.intellij.openapi.Disposable import org.jetbrains.annotations.CalledInAwt import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestShort import java.util.concurrent.CompletableFuture internal interface GHPRListLoader : GHListLoader { @get:CalledInAwt val outdated: Boolean @get:CalledInAwt val filterNotEmpty: Boolean @CalledInAwt fun reloadData(request: CompletableFuture<out GHPullRequestShort>) @CalledInAwt fun findData(number: Long): GHPullRequestShort? @CalledInAwt fun resetFilter() @CalledInAwt fun addOutdatedStateChangeListener(disposable: Disposable, listener: () -> Unit) }
plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/GHPRListLoader.kt
1791582450
/* * Copyright (C) 2017 Darel Bitsy * 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.dbeginc.dbweatherdata.implementations.datasources.remote.weather import com.dbeginc.dbweatherdata.getFileAsStringJVM import com.dbeginc.dbweatherdata.implementations.datasources.remote.RemoteWeatherDataSource import okhttp3.OkHttpClient import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.junit.Before import org.junit.Test import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.simplexml.SimpleXmlConverterFactory class HttpApiWeatherDataSourceTest { private lateinit var server: MockWebServer private lateinit var weatherDataSource: RemoteWeatherDataSource @Before fun setup() { server = MockWebServer() server.start() val client = OkHttpClient.Builder().build() val rxJava2CallAdapterFactory = RxJava2CallAdapterFactory.create() val geoLocationApi = Retrofit.Builder() .baseUrl(server.url("/").toString()) .addConverterFactory(SimpleXmlConverterFactory.create()) .addCallAdapterFactory(rxJava2CallAdapterFactory) .client(client) .build() .create(LocationApi::class.java) weatherDataSource = HttpApiWeatherDataSource.create(mockLocationApi = geoLocationApi) } @Test fun `get random locations and check if xml parsing done properly`() { val serverResponse = MockResponse() serverResponse.apply { setResponseCode(200) setBody(getFileAsStringJVM("random_locations.xml")) } server.enqueue(serverResponse) weatherDataSource.getLocations("random") .test() .assertValue { it.size == 100 } .assertValue { it.any { it.name.isNotBlank() && it.countryCode.isNotBlank() } } .assertNoErrors() .assertComplete() server.enqueue(serverResponse.clone().setBody(getFileAsStringJVM("empty_locations.xml"))) weatherDataSource.getLocations("random") .test() .assertValue { it.isEmpty() } .assertNoErrors() .assertComplete() server.enqueue(serverResponse.clone().setBody(getFileAsStringJVM("full_locations.xml"))) weatherDataSource.getLocations("random") .test() .assertValue { it.size == 3 } .assertValue { it.any { it.name.isNotBlank() && it.countryCode.isNotBlank() } } .assertNoErrors() .assertComplete() } }
dbweatherdata/src/test/java/com/dbeginc/dbweatherdata/implementations/datasources/remote/weather/HttpApiWeatherDataSourceTest.kt
1095543464
package slatekit.apis import slatekit.apis.setup.Parentable /* ktlint-disable */ object Verbs { /** * This allows for automatically determining the verb based on the method name * e.g. * 1. getXX = "get" * 2. createXX = "post" * 3. updateXX = "put" * 4. deleteXX = "delete" * 5. patchXX = "patch" */ const val AUTO = "auto" /** * Core operations supported */ const val GET = "get" const val CREATE = "create" const val UPDATE = "update" const val DELETE = "delete" /** * Here for compatibility with HTTP/REST */ const val POST = "post" const val PUT = "put" const val PATCH = "patch" const val PARENT = ApiConstants.parent } sealed class Verb(override val name: String) : Parentable<Verb> { object Auto : Verb(Verbs.AUTO) object Get : Verb(Verbs.GET) object Create : Verb(Verbs.CREATE) object Update : Verb(Verbs.UPDATE) object Put : Verb(Verbs.PUT) object Post : Verb(Verbs.POST) object Patch : Verb(Verbs.PATCH) object Delete : Verb(Verbs.DELETE) object Parent : Verb(Verbs.PARENT) fun isMatch(other:String):Boolean = this.name == other companion object { fun parse(name:String): Verb { return when(name) { Verbs.AUTO -> Verb.Auto Verbs.GET -> Verb.Get Verbs.CREATE -> Verb.Create Verbs.UPDATE -> Verb.Update Verbs.PUT -> Verb.Put Verbs.POST -> Verb.Post Verbs.PATCH -> Verb.Patch Verbs.DELETE -> Verb.Delete Verbs.PARENT -> Verb.Parent else -> Verb.Auto } } } } /* ktlint-enable */
src/lib/kotlin/slatekit-apis/src/main/kotlin/slatekit/apis/Verbs.kt
1413262412
package com.intellij.configurationScript import com.intellij.configurationScript.providers.readComponentConfiguration import com.intellij.openapi.components.BaseState import com.intellij.testFramework.ProjectRule import com.intellij.testFramework.assertions.Assertions.assertThat import org.intellij.lang.annotations.Language import org.junit.ClassRule import org.junit.Test class ComponentStateTest { companion object { @JvmField @ClassRule val projectRule = ProjectRule() } @Test fun read() { val result = doReadComponentConfiguration("versionControl.git", """ versionControl: git: updateMethod: rebase """) assertThat(result!!.updateMethod).isEqualTo(UpdateMethod.REBASE) } } @Suppress("SameParameterValue") private fun doReadComponentConfiguration(namePath: String, @Language("YAML") data: String): TestState? { return readComponentConfiguration(findValueNodeByPath(namePath, doRead(data.trimIndent().reader())!!.value)!!, TestState::class.java) } private class TestState : BaseState() { var updateMethod by enum(UpdateMethod.BRANCH_DEFAULT) } private enum class UpdateMethod { BRANCH_DEFAULT, MERGE, REBASE }
plugins/configuration-script/test/ComponentStateTest.kt
4072841227
// 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.daemon import com.intellij.codeInspection.ex.ApplicationInspectionProfileManager import com.intellij.codeInspection.ex.DEFAULT_PROFILE_NAME import com.intellij.codeInspection.ex.InspectionProfileImpl import com.intellij.configurationStore.serializeObjectInto import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.util.JDOMUtil import com.intellij.util.xmlb.XmlSerializer.deserializeInto import org.jdom.Element @State(name = "DaemonCodeAnalyzerSettings", storages = [Storage("editor.xml"), Storage("editor.codeinsight.xml", deprecated = true)]) open class DaemonCodeAnalyzerSettingsImpl : DaemonCodeAnalyzerSettings(), PersistentStateComponent<Element>, Cloneable { override fun isCodeHighlightingChanged(oldSettings: DaemonCodeAnalyzerSettings): Boolean { return !JDOMUtil.areElementsEqual((oldSettings as DaemonCodeAnalyzerSettingsImpl).state, state) } public override fun clone(): DaemonCodeAnalyzerSettingsImpl { val settings = DaemonCodeAnalyzerSettingsImpl() settings.autoReparseDelay = autoReparseDelay settings.myShowAddImportHints = myShowAddImportHints settings.SHOW_METHOD_SEPARATORS = SHOW_METHOD_SEPARATORS settings.NO_AUTO_IMPORT_PATTERN = NO_AUTO_IMPORT_PATTERN return settings } override fun getState(): Element? { val element = Element("state") serializeObjectInto(this, element) val profile = ApplicationInspectionProfileManager.getInstanceImpl().rootProfileName if (DEFAULT_PROFILE_NAME != profile) { element.setAttribute("profile", profile) } return element } override fun loadState(state: Element) { deserializeInto(this, state) val profileManager = ApplicationInspectionProfileManager.getInstanceImpl() profileManager.converter.storeEditorHighlightingProfile(state, InspectionProfileImpl(InspectionProfileConvertor.OLD_HIGHTLIGHTING_SETTINGS_PROFILE)) profileManager.setRootProfile(state.getAttributeValue("profile") ?: "Default") } }
platform/lang-impl/src/com/intellij/codeInsight/daemon/DaemonCodeAnalyzerSettingsImpl.kt
2386356811
/* * This file is part of Blokada. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. * * Copyright Β© 2021 Blocka AB. All rights reserved. * * @author Karol Gusak ([email protected]) */ package model import com.squareup.moshi.JsonClass typealias AppId = String class App( val id: AppId, val name: String, val isBypassed: Boolean, val isSystem: Boolean ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as App if (id != other.id) return false return true } override fun hashCode(): Int { return id.hashCode() } } @JsonClass(generateAdapter = true) class BypassedAppIds( val ids: List<AppId> ) enum class AppState { Deactivated, Paused, Activated }
android5/app/src/main/java/model/AppModel.kt
478545765
fun Long.id() = this fun String.drop2() = if (length >= 2) subSequence(2, length) else null fun String.anyLength(): Any = length fun doSimple(s: String?) = 3 != s?.length fun doLongReceiver(x: Long) = 3L != x?.id() fun doChain(s: String?) = 1 != s?.drop2()?.length fun doIf(s: String?) = if (1 != s?.length) "A" else "B" fun doCmpWithAny(s: String?) = 3 != s?.anyLength() fun box(): String = when { !doSimple(null) -> "failed 1" !doSimple("1") -> "failed 2" doSimple("123") -> "failed 3" !doLongReceiver(2L) -> "failed 4" doLongReceiver(3L) -> "failed 5" !doChain(null) -> "failed 6" !doChain("1") -> "failed 7" doChain("123") -> "failed 7" doIf("1") == "A" -> "failed 8" doIf("123") == "B" -> "failed 9" doIf(null) == "B" -> "failed 10" !doCmpWithAny(null) -> "failed 11" !doCmpWithAny("1") -> "failed 12" doCmpWithAny("123") -> "failed 13" else -> "OK" }
backend.native/tests/external/codegen/box/safeCall/primitiveNotEqSafeCall.kt
1653382760
// WITH_RUNTIME val iterable: Iterable<Int> = listOf(1, 2, 3) fun box(): String = when { 0 in iterable -> "fail 1" 1 !in iterable -> "fail 2" else -> "OK" }
backend.native/tests/external/codegen/box/ranges/contains/inIterable.kt
2106019417
// IGNORE_BACKEND: NATIVE // FILE: 1.kt // WITH_REFLECT package test inline fun <reified T : Any> className() = T::class.java.simpleName // FILE: 2.kt import test.* fun box(): String { val z = className<String>() if (z != "String") return "fail: $z" return "OK" } // FILE: 2.smap SMAP 2.kt Kotlin *S Kotlin *F + 1 2.kt _2Kt + 2 1.kt test/_1Kt *L 1#1,12:1 6#2:13 *E *S KotlinDebug *F + 1 2.kt _2Kt *L 6#1:13 *E
backend.native/tests/external/codegen/boxInline/smap/inlineOnly/reified.kt
3632993172
// FILE: 1.kt package test class Foo { fun foo() = "O" } inline fun inlineFn(crossinline fn: () -> String, x: String = "X"): String { return fn() + x } // FILE: 2.kt import test.* private val foo = Foo() fun box(): String { return inlineFn(foo::foo, "K") }
backend.native/tests/external/codegen/boxInline/defaultValues/kt18689_3.kt
640333759
fun box(): String { if (!foo(1.toByte())) return "fail 1" if (!foo((1.toByte()).inc())) return "fail 2" return "OK" } fun foo(p: Any) = p is Byte
backend.native/tests/external/codegen/box/unaryOp/callWithCommonType.kt
3479363548
/* * Copyright (C) 2016 MGaetan89 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.kolumbus.extension import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import kotlin.test.assertEquals @RunWith(Parameterized::class) class StringExtensions_ToCamelCaseTest(val entry: String, val result: String) { @Test fun toCamelCase() { assertEquals(this.result, this.entry.toCamelCase()) } companion object { @JvmStatic @Parameterized.Parameters fun data(): Collection<Array<String>> { return listOf( arrayOf("", ""), arrayOf("helloworld", "Helloworld"), arrayOf("helloWorld", "Hello World"), arrayOf("Helloworld", "Helloworld"), arrayOf("HelloWorld", "Hello World"), arrayOf("helloWorldMyNameIsJack", "Hello World My Name Is Jack"), arrayOf("HelloWorldMyNameIsJack", "Hello World My Name Is Jack") ) } } }
kolumbus/src/test/kotlin/io/kolumbus/extension/StringExtensions_ToCamelCaseTest.kt
1645640969
/* * 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.test import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.SemanticsPropertyReceiver import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.testTag import androidx.compose.ui.semantics.text import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.text.AnnotatedString import androidx.test.filters.MediumTest import androidx.compose.testutils.expectError import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.editableText import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import androidx.test.ext.junit.runners.AndroidJUnit4 @MediumTest @RunWith(AndroidJUnit4::class) class FindersTest { @get:Rule val rule = createComposeRule() @Test fun findAll_zeroOutOfOne_findsNone() { rule.setContent { BoundaryNode { testTag = "not_myTestTag" } } rule.onAllNodes(hasTestTag("myTestTag")).assertCountEquals(0) } @Test fun findAll_oneOutOfTwo_findsOne() { rule.setContent { BoundaryNode { testTag = "myTestTag" } BoundaryNode { testTag = "myTestTag2" } } rule.onAllNodes(hasTestTag("myTestTag")) .assertCountEquals(1) .onFirst() .assert(hasTestTag("myTestTag")) } @Test fun findAll_twoOutOfTwo_findsTwo() { rule.setContent { BoundaryNode { testTag = "myTestTag" } BoundaryNode { testTag = "myTestTag" } } rule.onAllNodes(hasTestTag("myTestTag")) .assertCountEquals(2) .apply { get(0).assert(hasTestTag("myTestTag")) get(1).assert(hasTestTag("myTestTag")) } } @Test fun findByText_matches() { rule.setContent { BoundaryNode { text = AnnotatedString("Hello World") } } rule.onNodeWithText("Hello World").assertExists() } @Test fun findByText_withEditableText_matches() { rule.setContent { BoundaryNode { editableText = AnnotatedString("Hello World") } } rule.onNodeWithText("Hello World").assertExists() } @Test fun findByText_merged_matches() { rule.setContent { Box(Modifier.semantics(mergeDescendants = true) { }) { Text("Hello") Text("World") } } rule.onNodeWithText("Hello").assertExists() rule.onNodeWithText("World").assertExists() rule.onAllNodesWithText("Hello").assertCountEquals(1) rule.onAllNodesWithText("World").assertCountEquals(1) } @Test(expected = AssertionError::class) fun findByText_fails() { rule.setContent { BoundaryNode { text = AnnotatedString("Hello World") } } // Need to assert exists or it won't fail rule.onNodeWithText("World").assertExists() } @Test(expected = AssertionError::class) fun findByText_merged_fails() { rule.setContent { Box(Modifier.semantics(mergeDescendants = true) { }) { Text("Hello") Text("World") } } rule.onNodeWithText("Hello, World").assertExists() } @Test fun findBySubstring_matches() { rule.setContent { BoundaryNode { text = AnnotatedString("Hello World") } } rule.onNodeWithText("World", substring = true).assertExists() } @Test fun findBySubstring_merged_matches() { rule.setContent { Box(Modifier.semantics(mergeDescendants = true) { }) { Text("Hello") Text("World") } } rule.onNodeWithText("Wo", substring = true).assertExists() rule.onNodeWithText("He", substring = true).assertExists() } @Test fun findBySubstring_ignoreCase_matches() { rule.setContent { BoundaryNode { text = AnnotatedString("Hello World") } } rule.onNodeWithText("world", substring = true, ignoreCase = true).assertExists() } @Test fun findBySubstring_wrongCase_fails() { rule.setContent { BoundaryNode { text = AnnotatedString("Hello World") } } expectError<AssertionError> { // Need to assert exists or it won't fetch nodes rule.onNodeWithText("world", substring = true).assertExists() } } @Test fun findAllBySubstring() { rule.setContent { BoundaryNode { text = AnnotatedString("Hello World") } BoundaryNode { text = AnnotatedString("Wello Horld") } } rule.onAllNodesWithText("Yellow World", substring = true).assertCountEquals(0) rule.onAllNodesWithText("Hello", substring = true).assertCountEquals(1) rule.onAllNodesWithText("Wello", substring = true).assertCountEquals(1) rule.onAllNodesWithText("ello", substring = true).assertCountEquals(2) } @Test fun findByContentDescription_matches() { rule.setContent { BoundaryNode { contentDescription = "Hello World" } } rule.onNodeWithContentDescription("Hello World").assertExists() } @Test fun findByContentDescription_merged_matches() { rule.setContent { Box(Modifier.semantics(mergeDescendants = true) { }) { Box(Modifier.semantics { contentDescription = "Hello" }) Box(Modifier.semantics { contentDescription = "World" }) } } rule.onNodeWithContentDescription("Hello").assertExists() rule.onNodeWithContentDescription("World").assertExists() rule.onAllNodesWithContentDescription("Hello").assertCountEquals(1) rule.onAllNodesWithContentDescription("World").assertCountEquals(1) } @Test(expected = AssertionError::class) fun findByContentDescription_fails() { rule.setContent { BoundaryNode { contentDescription = "Hello World" } } rule.onNodeWithContentDescription("Hello").assertExists() } @Test(expected = AssertionError::class) fun findByContentDescription_merged_fails() { rule.setContent { Box(Modifier.semantics(mergeDescendants = true) { }) { Box(Modifier.semantics { contentDescription = "Hello" }) Box(Modifier.semantics { contentDescription = "World" }) } } rule.onNodeWithText("Hello, World").assertExists() } @Test fun findByContentDescription_substring_matches() { rule.setContent { BoundaryNode { contentDescription = "Hello World" } } rule.onNodeWithContentDescription("World", substring = true).assertExists() } @Test fun findByContentDescription_merged_substring_matches() { rule.setContent { Box(Modifier.semantics(mergeDescendants = true) { }) { Box(Modifier.semantics { contentDescription = "Hello" }) Box(Modifier.semantics { contentDescription = "World" }) } } rule.onNodeWithContentDescription("Wo", substring = true).assertExists() rule.onNodeWithContentDescription("He", substring = true).assertExists() } fun findByContentDescription_substring_noResult() { rule.setContent { BoundaryNode { contentDescription = "Hello World" } } rule.onNodeWithContentDescription("world", substring = true) .assertDoesNotExist() } @Test fun findByContentDescription_substring_ignoreCase_matches() { rule.setContent { BoundaryNode { contentDescription = "Hello World" } } rule.onNodeWithContentDescription("world", substring = true, ignoreCase = true) .assertExists() } @Composable fun BoundaryNode(props: (SemanticsPropertyReceiver.() -> Unit)) { Column(Modifier.semantics(properties = props)) {} } }
compose/ui/ui-test/src/androidAndroidTest/kotlin/androidx/compose/ui/test/FindersTest.kt
2097166897
// 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. @file:Suppress("UsePropertyAccessSyntax") package org.jetbrains.intellij.build.tasks import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.rules.InMemoryFsExtension import com.intellij.util.io.inputStream import com.intellij.util.lang.ImmutableZipFile import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import io.opentelemetry.api.trace.Span import org.apache.commons.compress.archivers.zip.ZipFile import org.assertj.core.api.Assertions.assertThat import org.jetbrains.intellij.build.io.zip import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.RegisterExtension import org.junit.jupiter.api.io.TempDir import java.nio.file.Files import java.nio.file.Path import java.util.concurrent.ForkJoinTask import java.util.zip.ZipEntry import kotlin.random.Random private val testDataPath: Path get() = Path.of(PlatformTestUtil.getPlatformTestDataPath(), "plugins/reorderJars") class ReorderJarsTest { @RegisterExtension @JvmField val fs = InMemoryFsExtension() @Test fun `keep all dirs with resources`() { // check that not only immediate parent of resource file is preserved, but also any dir in a path val random = Random(42) val rootDir = fs.root.resolve("dir") val dir = rootDir.resolve("dir2/dir3") Files.createDirectories(dir) Files.write(dir.resolve("resource.txt"), random.nextBytes(random.nextInt(128))) val dir2 = rootDir.resolve("anotherDir") Files.createDirectories(dir2) Files.write(dir2.resolve("resource2.txt"), random.nextBytes(random.nextInt(128))) val archiveFile = fs.root.resolve("archive.jar") zip(archiveFile, mapOf(rootDir to ""), compress = false, addDirEntries = true) doReorderJars(mapOf(archiveFile to emptyList()), archiveFile.parent, archiveFile.parent) ImmutableZipFile.load(archiveFile).use { zipFile -> assertThat(zipFile.getResource("anotherDir")).isNotNull() assertThat(zipFile.getResource("dir2")).isNotNull() assertThat(zipFile.getResource("dir2/dir3")).isNotNull() } ImmutableZipFile.load(archiveFile).use { zipFile -> assertThat(zipFile.getResource("anotherDir")).isNotNull() } } @Test fun testReordering(@TempDir tempDir: Path) { val path = testDataPath ZipFile("$path/annotations.jar").use { zipFile1 -> zipFile1.entries.toList() } Files.createDirectories(tempDir) doReorderJars(readClassLoadingLog(path.resolve("order.txt").inputStream(), path, "idea.jar"), path, tempDir) val files = tempDir.toFile().listFiles()!! assertThat(files).isNotNull() assertThat(files).hasSize(1) val file = files[0].toPath() assertThat(file.fileName.toString()).isEqualTo("annotations.jar") var data: ByteArray ZipFile(Files.newByteChannel(file)).use { zipFile2 -> val entries = zipFile2.entriesInPhysicalOrder.toList() val entry = entries[0] data = zipFile2.getInputStream(entry).readNBytes(entry.size.toInt()) assertThat(data).hasSize(548) assertThat(entry.name).isEqualTo("org/jetbrains/annotations/Nullable.class") assertThat(entries[1].name).isEqualTo("org/jetbrains/annotations/NotNull.class") assertThat(entries[2].name).isEqualTo("META-INF/MANIFEST.MF") } } @Test fun testPluginXml(@TempDir tempDir: Path) { Files.createDirectories(tempDir) val path = testDataPath doReorderJars(readClassLoadingLog(path.resolve("zkmOrder.txt").inputStream(), path, "idea.jar"), path, tempDir) val files = tempDir.toFile().listFiles()!! assertThat(files).isNotNull() val file = files[0] assertThat(file.name).isEqualTo("zkm.jar") ZipFile(file).use { zipFile -> val entries: List<ZipEntry> = zipFile.entries.toList() assertThat(entries.first().name).isEqualTo("META-INF/plugin.xml") } } } private fun doReorderJars(sourceToNames: Map<Path, List<String>>, sourceDir: Path, targetDir: Path) { ForkJoinTask.invokeAll(sourceToNames.mapNotNull { (jarFile, orderedNames) -> if (Files.notExists(jarFile)) { Span.current().addEvent("cannot find jar", Attributes.of(AttributeKey.stringKey("file"), sourceDir.relativize(jarFile).toString())) return@mapNotNull null } task(tracer.spanBuilder("reorder jar") .setAttribute("file", sourceDir.relativize(jarFile).toString())) { reorderJar(jarFile, orderedNames, if (targetDir == sourceDir) jarFile else targetDir.resolve(sourceDir.relativize(jarFile))) } }) }
build/tasks/test/org/jetbrains/intellij/build/tasks/ReorderJarsTest.kt
3812003614
import org.jetbrains.annotations.PropertyKey private val BUNDLE_NAME = "FooBundle" public fun message(@PropertyKey(resourceBundle = "FooBundle") key: String) = key public fun message2(@PropertyKey(resourceBundle = BUNDLE_NAME) key: String) = key fun test() { message("foo.bar") }
plugins/kotlin/idea/tests/testData/refactoring/rename/renameBundle/before/usages.kt
787833141
// WITH_STDLIB fun test(cn: Cn?): String? { var query: Q? = null var result: String? = null if (cn != null) { try { query = cn.query() result = query.data() } catch(e:Exception) {} finally { try { query?.close() } catch (e:Exception) {} } } return result } interface Cn { fun query(): Q } interface Q { fun data(): String fun close() }
plugins/kotlin/idea/tests/testData/inspections/dfa/TryCatchInsideFinally.kt
1381830015
// IS_APPLICABLE: false // ERROR: Unresolved reference: bar fun <caret>foo() = bar()
plugins/kotlin/idea/tests/testData/intentions/convertToBlockBody/implicitlyTypedFunWithUnresolvedType.kt
1663185491
val s4: String get() = /* before1 */ /* before2 */ <selection><caret>TODO</selection>("not implemented") /* after1 */ /* after2 */
plugins/kotlin/idea/tests/testData/wordSelection/DeclarationWithComment4/1.kt
4110061254
// "Change to constructor invocation" "false" // ACTION: Introduce import alias // ERROR: This type has a constructor, and thus must be initialized here // ERROR: This type is sealed, so it can be inherited by only its own nested classes or objects sealed class A fun test() { class B : A<caret> }
plugins/kotlin/idea/tests/testData/quickfix/supertypeInitialization/addParenthesisForInvalidSealedClass.kt
1285252597
fun main() { do { } while (true) do { } while (true) do { } while (true) do //eol comment { } while (true) do //eol comment { } while (true) } // SET_TRUE: LBRACE_ON_NEXT_LINE
plugins/kotlin/idea/tests/testData/formatter/DoWhileLineBreak.after.inv.kt
4059372644
// WITH_STDLIB // PROBLEM: none package kotlinx.coroutines suspend fun barAsync(): Deferred<String>? { return null } suspend fun foo() { " ".let <caret>{ barAsync() } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/coroutines/deferredIsResult/lambda.kt
2486866218
// 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.idea.maven.server.ui import com.intellij.execution.util.ListTableWithButtons import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.util.NlsContexts import com.intellij.ui.AnActionButton import com.intellij.ui.AnActionButtonRunnable import com.intellij.util.ui.ListTableModel import org.jetbrains.idea.maven.project.MavenConfigurableBundle import org.jetbrains.idea.maven.server.MavenServerConnector import org.jetbrains.idea.maven.server.MavenServerManager import org.jetbrains.idea.maven.statistics.MavenActionsUsagesCollector import javax.swing.ListSelectionModel import javax.swing.SortOrder class ConnectorTable : ListTableWithButtons<MavenServerConnector>() { val stop = object : AnActionButton(MavenConfigurableBundle.message("connector.ui.stop"), AllIcons.Debugger.KillProcess) { override fun actionPerformed(e: AnActionEvent) { MavenActionsUsagesCollector.trigger(e.project, MavenActionsUsagesCollector.KILL_MAVEN_CONNECTOR) val connector = tableView.selectedObject ?: return; connector.shutdown(true) [email protected]() } override fun updateButton(e: AnActionEvent) { val connector = tableView.selectedObject isEnabled = connector?.state == MavenServerConnector.State.RUNNING } } val refresh = object : AnActionButton(MavenConfigurableBundle.message("connector.ui.refresh"), AllIcons.Actions.Refresh) { override fun actionPerformed(e: AnActionEvent) { [email protected](createListModel()) [email protected]() } } init { tableView.selectionModel.selectionMode = ListSelectionModel.SINGLE_SELECTION tableView.selectionModel.addListSelectionListener { if (it.valueIsAdjusting) return@addListSelectionListener val connector = tableView.selectedObject stop.isEnabled = connector?.state == MavenServerConnector.State.RUNNING } } override fun createListModel(): ListTableModel<MavenServerConnector> { val project = TableColumn(MavenConfigurableBundle.message("connector.ui.project")) { it.project.name } val jdk = TableColumn(MavenConfigurableBundle.message("connector.ui.jdk")) { it.jdk.name } val vmopts = TableColumn(MavenConfigurableBundle.message("connector.ui.vmOptions")) { it.vmOptions } val dir = TableColumn(MavenConfigurableBundle.message("connector.ui.dir")) { it.multimoduleDirectories.joinToString(separator = ",") } val maven = TableColumn( MavenConfigurableBundle.message("connector.ui.maven")) { "${it.mavenDistribution.version} ${it.mavenDistribution.mavenHome}" } val state = TableColumn( MavenConfigurableBundle.message("connector.ui.state")) { it.state.toString() } val type = TableColumn( MavenConfigurableBundle.message("connector.ui.type")) { it.supportType } val columnInfos = arrayOf<TableColumn>(project, dir, type, maven, state) return ListTableModel<MavenServerConnector>(columnInfos, MavenServerManager.getInstance().allConnectors.toList(), 3, SortOrder.DESCENDING); } override fun createExtraActions(): Array<AnActionButton> { return arrayOf(refresh, stop) } private class TableColumn(@NlsContexts.ColumnName name: String, val supplier: (MavenServerConnector) -> String) : ElementsColumnInfoBase<MavenServerConnector>( name) { override fun getDescription(element: MavenServerConnector?): String? = null; override fun valueOf(item: MavenServerConnector) = supplier(item) } override fun createElement(): MavenServerConnector? { return null; } override fun isEmpty(element: MavenServerConnector?): Boolean { return element == null } override fun canDeleteElement(selection: MavenServerConnector): Boolean { return false } override fun createRemoveAction(): AnActionButtonRunnable? { return null } override fun createAddAction(): AnActionButtonRunnable? { return null } override fun cloneElement(variable: MavenServerConnector?): MavenServerConnector? { return null } }
plugins/maven/src/main/java/org/jetbrains/idea/maven/server/ui/ConnectorTable.kt
924218758
/* * Copyright 2016 Fabio Collini. * * 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 it.cosenonjaviste.daggermock.realworldappkotlin.main import dagger.Subcomponent @Subcomponent(modules = arrayOf(MainActivityModule::class)) interface MainActivityComponent { fun inject(mainActivity: MainActivity) @Subcomponent.Builder interface Builder { fun mainActivityModule(module: MainActivityModule): Builder fun build(): MainActivityComponent } }
RealWorldAppKotlin/src/main/java/it/cosenonjaviste/daggermock/realworldappkotlin/main/MainActivityComponent.kt
2493484266
/* * Copyright 2022 The TensorFlow Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.tensorflow.lite.examples.modelpersonalization.fragments import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.os.Bundle import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.navigation.Navigation import org.tensorflow.lite.examples.modelpersonalization.R private val PERMISSIONS_REQUIRED = arrayOf(Manifest.permission.CAMERA) class PermissionsFragment : Fragment() { private val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { isGranted: Boolean -> if (isGranted) { Toast.makeText(context, "Permission request granted", Toast.LENGTH_LONG).show() navigateToCamera() } else { Toast.makeText(context, "Permission request denied", Toast.LENGTH_LONG).show() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) when { ContextCompat.checkSelfPermission( requireContext(), Manifest.permission.CAMERA ) == PackageManager.PERMISSION_GRANTED -> { navigateToCamera() } else -> { requestPermissionLauncher.launch( Manifest.permission.CAMERA ) } } } private fun navigateToCamera() { lifecycleScope.launchWhenStarted { Navigation.findNavController(requireActivity(), R.id.fragment_container).navigate( PermissionsFragmentDirections.actionPermissionsToCamera() ) } } companion object { /** Convenience method used to check if all permissions required by this app are granted */ fun hasPermissions(context: Context) = PERMISSIONS_REQUIRED.all { ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED } } }
lite/examples/model_personalization/android/app/src/main/java/org/tensorflow/lite/examples/modelpersonalization/fragments/PermissionsFragment.kt
885055421
package info.nightscout.androidaps.core.di import dagger.Module import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.activities.BolusProgressHelperActivity import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.activities.TDDStatsActivity import info.nightscout.androidaps.dialogs.BolusProgressDialog import info.nightscout.androidaps.dialogs.ErrorDialog import info.nightscout.androidaps.dialogs.NtpProgressDialog import info.nightscout.androidaps.dialogs.ProfileViewerDialog import info.nightscout.androidaps.plugins.general.maintenance.activities.PrefImportListActivity @Module @Suppress("unused") abstract class CoreFragmentsModule { @ContributesAndroidInjector abstract fun contributesPrefImportListActivity(): PrefImportListActivity @ContributesAndroidInjector abstract fun contributesTDDStatsActivity(): TDDStatsActivity @ContributesAndroidInjector abstract fun contributeBolusProgressHelperActivity(): BolusProgressHelperActivity @ContributesAndroidInjector abstract fun contributeErrorHelperActivity(): ErrorHelperActivity @ContributesAndroidInjector abstract fun contributesBolusProgressDialog(): BolusProgressDialog @ContributesAndroidInjector abstract fun contributesErrorDialog(): ErrorDialog @ContributesAndroidInjector abstract fun contributesNtpProgressDialog(): NtpProgressDialog @ContributesAndroidInjector abstract fun contributesProfileViewerDialog(): ProfileViewerDialog }
core/src/main/java/info/nightscout/androidaps/core/di/CoreFragmentsModule.kt
2817044131
package com.intellij.metricsCollector.collector import com.intellij.metricsCollector.publishing.ApplicationMetricDto import com.intellij.openapi.util.BuildNumber import java.time.OffsetDateTime data class PerformanceMetrics( val buildNumber: BuildNumber, val generatedTime: OffsetDateTime, val projectName: String, val machineName: String, val branchName: String, val os: String, val metrics: List<Metric<*>> ) { sealed class MetricId<T: Number> { abstract val name: String /** * Metric used to measure duration of events in ms */ data class Duration(override val name: String) : MetricId<Long>() /** * Metric used to count the number of times an event has occurred */ data class Counter(override val name: String) : MetricId<Int>() } data class Metric<T: Number>(val id: MetricId<T>, val value: T) } fun PerformanceMetrics.Metric<*>.toJson() = ApplicationMetricDto( n = id.name, d = if (id is PerformanceMetrics.MetricId.Duration) (this.value as? Number)?.toLong() else null, c = if (id is PerformanceMetrics.MetricId.Counter) (this.value as? Number)?.toLong() else null )
tools/ideTestingFramework/intellij.tools.ide.metricsCollector/src/com/intellij/metricsCollector/collector/PerformanceMetrics.kt
3706780122
package ru.siksmfp.network.harness.implementation.nio.simple.server import java.nio.channels.SelectionKey interface SelectionHandler { fun handle(selectionKey: SelectionKey) fun close() }
src/main/kotlin/ru/siksmfp/network/harness/implementation/nio/simple/server/SelectionHandler.kt
1723129736
// 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.ide.plugins import com.intellij.platform.util.plugins.DataLoader import com.intellij.platform.util.plugins.LocalFsDataLoader import java.nio.file.Files internal class ClassPathXmlPathResolver(private val classLoader: ClassLoader, private val isRunningFromSources: Boolean) : PathResolver { override val isFlat: Boolean get() = true override fun loadXIncludeReference(readInto: RawPluginDescriptor, readContext: ReadModuleContext, dataLoader: DataLoader, base: String?, relativePath: String): Boolean { val path = PluginXmlPathResolver.toLoadPath(relativePath, base) readModuleDescriptor(inputStream = classLoader.getResourceAsStream(path) ?: return false, readContext = readContext, pathResolver = this, dataLoader = dataLoader, includeBase = PluginXmlPathResolver.getChildBase(base = base, relativePath = relativePath), readInto = readInto, locationSource = dataLoader.toString()) return true } override fun resolveModuleFile(readContext: ReadModuleContext, dataLoader: DataLoader, path: String, readInto: RawPluginDescriptor?): RawPluginDescriptor { var resource = classLoader.getResourceAsStream(path) if (resource == null) { if (path == "intellij.profiler.clion") { val descriptor = RawPluginDescriptor() descriptor.`package` = "com.intellij.profiler.clion" return descriptor } if (isRunningFromSources && path.startsWith("intellij.") && dataLoader is LocalFsDataLoader) { try { resource = Files.newInputStream(dataLoader.basePath.parent.resolve("${path.substring(0, path.length - 4)}/$path")) } catch (e: Exception) { throw RuntimeException("Cannot resolve $path (dataLoader=$dataLoader, classLoader=$classLoader). " + "Please ensure that project is built (Build -> Build Project).", e) } } if (resource == null) { throw RuntimeException("Cannot resolve $path (dataLoader=$dataLoader, classLoader=$classLoader)") } } return readModuleDescriptor(inputStream = resource, readContext = readContext, pathResolver = this, dataLoader = dataLoader, includeBase = null, readInto = readInto, locationSource = dataLoader.toString()) } override fun resolvePath(readContext: ReadModuleContext, dataLoader: DataLoader, relativePath: String, readInto: RawPluginDescriptor?): RawPluginDescriptor? { val path = PluginXmlPathResolver.toLoadPath(relativePath, null) val resource = classLoader.getResourceAsStream(path) return readModuleDescriptor(inputStream = resource ?: return null, readContext = readContext, pathResolver = this, dataLoader = dataLoader, includeBase = null, readInto = readInto, locationSource = dataLoader.toString()) } }
platform/core-impl/src/com/intellij/ide/plugins/ClassPathXmlPathResolver.kt
4189315469
class Inheritor : Base() { init { fooBa<caret> } }
plugins/kotlin/completion/tests/testData/handlers/multifile/StaticMethodFromGrandParent-1.kt
156213691
fun a() = try { // do smth } finally <caret>{ }
plugins/kotlin/idea/tests/testData/indentationOnNewline/controlFlowConstructions/Finally.after.kt
1059996606
package io.github.feelfreelinux.wykopmobilny.ui.modules.notifications.notificationsservice import io.github.feelfreelinux.wykopmobilny.base.BaseView import io.github.feelfreelinux.wykopmobilny.models.dataclass.Notification interface WykopNotificationsJobView : BaseView { fun showNotification(notification: Notification) fun showNotificationsCount(count: Int) fun cancelNotification() }
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/notifications/notificationsservice/WykopNotificationsJobView.kt
2175506250
package torille.fi.lurkforreddit.data.models.view import android.os.Parcelable import kotlinx.android.parcel.Parcelize /** * Data class for showing search result */ @Parcelize data class SearchResult( val title: CharSequence = "", val subscriptionInfo: String = "", val infoText: String = "", val description: CharSequence = "", val subreddit: Subreddit = Subreddit() ) : Parcelable
app/src/main/java/torille/fi/lurkforreddit/data/models/view/SearchResult.kt
170835810
package io.github.feelfreelinux.wykopmobilny.ui.widgets.buttons import android.content.Context import android.content.res.TypedArray import android.graphics.drawable.Drawable import android.util.AttributeSet import android.util.TypedValue import android.widget.ImageView import io.github.feelfreelinux.wykopmobilny.R import io.github.feelfreelinux.wykopmobilny.utils.getActivityContext class FavoriteButton @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.MirkoButtonStyle ) : ImageView(context, attrs, defStyleAttr) { var favoriteDrawable: Drawable var favoriteOutlineDrawable: Drawable var typedArray: TypedArray var isFavorite: Boolean get() = isSelected set(value) { if (value) { isSelected = true setImageDrawable(favoriteDrawable) } else { isSelected = false setImageDrawable(favoriteOutlineDrawable) } } init { val typedValue = TypedValue() getActivityContext()!!.theme?.resolveAttribute(R.attr.buttonStatelist, typedValue, true) setBackgroundResource(typedValue.resourceId) typedArray = context.obtainStyledAttributes( arrayOf( R.attr.favoriteDrawable ).toIntArray() ) favoriteDrawable = typedArray.getDrawable(0)!! typedArray.recycle() typedArray = context.obtainStyledAttributes(arrayOf(R.attr.favoriteOutlineDrawable).toIntArray()) favoriteOutlineDrawable = typedArray.getDrawable(0)!! typedArray.recycle() } }
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/widgets/buttons/FavoriteButton.kt
3293350131
// 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 training.ui import com.intellij.ide.util.PropertiesComponent import com.intellij.lang.Language import com.intellij.openapi.options.BoundConfigurable import com.intellij.openapi.ui.DialogPanel import com.intellij.ui.layout.* import training.lang.LangManager import training.learn.CourseManager import training.learn.LearnBundle import training.statistic.StatisticBase import training.util.SHOW_NEW_LESSONS_NOTIFICATION import training.util.getActionById import training.util.resetPrimaryLanguage import javax.swing.DefaultComboBoxModel private class FeaturesTrainerSettingsPanel : BoundConfigurable(LearnBundle.message("learn.options.panel.name"), null) { override fun createPanel(): DialogPanel = panel { val languagesExtensions = LangManager.getInstance().supportedLanguagesExtensions.sortedBy { it.language } if (languagesExtensions.isNotEmpty()) { row { label(LearnBundle.message("learn.option.main.language")) val options = languagesExtensions.mapNotNull { Language.findLanguageByID(it.language) } .map { LanguageOption(it) }.toTypedArray() comboBox<LanguageOption>(DefaultComboBoxModel(options), { val languageName = LangManager.getInstance().state.languageName options.find { it.id == languageName } ?: options[0] }, { language -> resetPrimaryLanguage(languagesExtensions.first { it.language == language?.id }.instance) } ) } } row { buttonFromAction(LearnBundle.message("learn.option.reset.progress"), "settings", getActionById("ResetLearningProgressAction")) } row { checkBox(LearnBundle.message("settings.checkbox.show.notifications.new.lessons"), { PropertiesComponent.getInstance().getBoolean(SHOW_NEW_LESSONS_NOTIFICATION, true) }, { StatisticBase.logShowNewLessonsNotificationState(-1, CourseManager.instance.previousOpenedVersion, it) PropertiesComponent.getInstance().setValue(SHOW_NEW_LESSONS_NOTIFICATION, it, true) }) } } private data class LanguageOption(val language: Language) { override fun toString(): String = language.displayName val id get() = language.id } }
plugins/ide-features-trainer/src/training/ui/FeaturesTrainerSettingsPanel.kt
4287243943
package com.github.kerubistan.kerub.utils.junix.virt.virsh data class NetTrafficStat( val bytes: Long, val packets: Long, val errors: Long, val drop: Long )
src/main/kotlin/com/github/kerubistan/kerub/utils/junix/virt/virsh/NetTrafficStat.kt
2529631206
package alraune.entity import alraune.* import aplight.GelFill import vgrechka.* @GelFill @LightEntity(table = "AlLogEntry") class AlLogEntry : LightEntityBase() { var dataPile by notNull<AlLogEntryDataPile>() object Meta } class AlLogEntryDataPile { var level by notNull<AlLog.Level>() var message by notNull<String>() var throwableStackTrace: String? = null var tags = listOf<String>() var incidentCode: String? = null } // TODO:vgrechka Generate this shit val AlLogEntry.Meta.table get() = "AlLogEntry" val AlLogEntry.Meta.id get() = "id" val AlLogEntry.Meta.dataPile get() = AlLogEntry::dataPile.name
alraune/alraune/src/main/java/alraune/entity/AlLogEntry.kt
3107170185
fun a() { <warning descr="SSR">when(10) { in 3..10 -> Unit else -> Unit }</warning> }
plugins/kotlin/idea/tests/testData/structuralsearch/whenExpression/whenRangeEntry.kt
941904944
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to You 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.internal.tls import java.io.ByteArrayInputStream import java.security.cert.CertificateFactory import java.security.cert.X509Certificate import java.util.stream.Stream import javax.net.ssl.SSLSession import javax.security.auth.x500.X500Principal import okhttp3.FakeSSLSession import okhttp3.OkHttpClient import okhttp3.internal.canParseAsIpAddress import okhttp3.internal.platform.Platform.Companion.isAndroid import okhttp3.testing.PlatformRule import okhttp3.tls.HeldCertificate import okhttp3.tls.internal.TlsUtil.localhost import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.RegisterExtension /** * Tests for our hostname verifier. Most of these tests are from AOSP, which itself includes tests * from the Apache HTTP Client test suite. */ class HostnameVerifierTest { private val verifier = OkHostnameVerifier @RegisterExtension var platform = PlatformRule() @Test fun verify() { val session = FakeSSLSession() assertThat(verifier.verify("localhost", session)).isFalse } @Test fun verifyCn() { // CN=foo.com val session = session( """ -----BEGIN CERTIFICATE----- MIIERjCCAy6gAwIBAgIJAIz+EYMBU6aQMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzE0MVoXDTI4MTEwNTE1MzE0MVowgaQx CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0 IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY 07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8 BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV JTxpTKqym93whYk93l3ocEe55c0CAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgB hvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYE FJ8Ud78/OrbKOIJCSBYs2tDLXofYMB8GA1UdIwQYMBaAFHua2o+QmU5S0qzbswNS yoemDT4NMA0GCSqGSIb3DQEBBQUAA4IBAQC3jRmEya6sQCkmieULcvx8zz1euCk9 fSez7BEtki8+dmfMXe3K7sH0lI8f4jJR0rbSCjpmCQLYmzC3NxBKeJOW0RcjNBpO c2JlGO9auXv2GDP4IYiXElLJ6VSqc8WvDikv0JmCCWm0Zga+bZbR/EWN5DeEtFdF 815CLpJZNcYwiYwGy/CVQ7w2TnXlG+mraZOz+owr+cL6J/ZesbdEWfjoS1+cUEhE HwlNrAu8jlZ2UqSgskSWlhYdMTAP9CPHiUv9N7FcT58Itv/I4fKREINQYjDpvQcx SaTYb9dr5sB4WLNglk7zxDtM80H518VvihTcP7FHL+Gn6g4j5fkI98+S -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("a.foo.com", session)).isFalse assertThat(verifier.verify("bar.com", session)).isFalse } @Test fun verifyNonAsciiCn() { // CN=&#x82b1;&#x5b50;.co.jp val session = session( """ -----BEGIN CERTIFICATE----- MIIESzCCAzOgAwIBAgIJAIz+EYMBU6aTMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1NDIxNVoXDTI4MTEwNTE1NDIxNVowgakx CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0 IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl cnRpZmljYXRlczEVMBMGA1UEAwwM6Iqx5a2QLmNvLmpwMSUwIwYJKoZIhvcNAQkB FhZqdWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A MIIBCgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjU g4pNjYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQc wHf0ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t 7iu1JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAn AxK6q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArD qUYxqJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwG CWCGSAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNV HQ4EFgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLS rNuzA1LKh6YNPg0wDQYJKoZIhvcNAQEFBQADggEBALJ27i3okV/KvlDp6KMID3gd ITl68PyItzzx+SquF8gahMh016NX73z/oVZoVUNdftla8wPUB1GwIkAnGkhQ9LHK spBdbRiCj0gMmLCsX8SrjFvr7cYb2cK6J/fJe92l1tg/7Y4o7V/s4JBe/cy9U9w8 a0ctuDmEBCgC784JMDtT67klRfr/2LlqWhlOEq7pUFxRLbhpquaAHSOjmIcWnVpw 9BsO7qe46hidgn39hKh1WjKK2VcL/3YRsC4wUi0PBtFW6ScMCuMhgIRXSPU55Rae UIlOdPjjr1SUNWGId1rD7W16Scpwnknn310FNxFMHVI0GTGFkNdkilNCFJcIoRA= -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("\u82b1\u5b50.co.jp", session)).isFalse assertThat(verifier.verify("a.\u82b1\u5b50.co.jp", session)).isFalse } @Test fun verifySubjectAlt() { // CN=foo.com, subjectAlt=bar.com val session = session( """ -----BEGIN CERTIFICATE----- MIIEXDCCA0SgAwIBAgIJAIz+EYMBU6aRMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzYyOVoXDTI4MTEwNTE1MzYyOVowgaQx CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0 IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY 07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8 BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV JTxpTKqym93whYk93l3ocEe55c0CAwEAAaOBkDCBjTAJBgNVHRMEAjAAMCwGCWCG SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz A1LKh6YNPg0wEgYDVR0RBAswCYIHYmFyLmNvbTANBgkqhkiG9w0BAQUFAAOCAQEA dQyprNZBmVnvuVWjV42sey/PTfkYShJwy1j0/jcFZR/ypZUovpiHGDO1DgL3Y3IP zVQ26uhUsSw6G0gGRiaBDe/0LUclXZoJzXX1qpS55OadxW73brziS0sxRgGrZE/d 3g5kkio6IED47OP6wYnlmZ7EKP9cqjWwlnvHnnUcZ2SscoLNYs9rN9ccp8tuq2by 88OyhKwGjJfhOudqfTNZcDzRHx4Fzm7UsVaycVw4uDmhEHJrAsmMPpj/+XRK9/42 2xq+8bc6HojdtbCyug/fvBZvZqQXSmU8m8IVcMmWMz0ZQO8ee3QkBHMZfCy7P/kr VbWx/uETImUu+NZg22ewEw== -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("a.foo.com", session)).isFalse assertThat(verifier.verify("bar.com", session)).isTrue assertThat(verifier.verify("a.bar.com", session)).isFalse } /** * Ignored due to incompatibilities between Android and Java on how non-ASCII subject alt names * are parsed. Android fails to parse these, which means we fall back to the CN. The RI does parse * them, so the CN is unused. */ @Test fun verifyNonAsciiSubjectAlt() { // Expecting actual: // ["bar.com", "花Γ₯­.co.jp"] // to contain exactly (and in same order): // ["bar.com", "οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½.co.jp"] platform.assumeNotBouncyCastle() // CN=foo.com, subjectAlt=bar.com, subjectAlt=&#x82b1;&#x5b50;.co.jp // (hanako.co.jp in kanji) val session = session( """ -----BEGIN CERTIFICATE----- MIIEajCCA1KgAwIBAgIJAIz+EYMBU6aSMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzgxM1oXDTI4MTEwNTE1MzgxM1owgaQx CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0 IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY 07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8 BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV JTxpTKqym93whYk93l3ocEe55c0CAwEAAaOBnjCBmzAJBgNVHRMEAjAAMCwGCWCG SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz A1LKh6YNPg0wIAYDVR0RBBkwF4IHYmFyLmNvbYIM6Iqx5a2QLmNvLmpwMA0GCSqG SIb3DQEBBQUAA4IBAQBeZs7ZIYyKtdnVxVvdLgwySEPOE4pBSXii7XYv0Q9QUvG/ ++gFGQh89HhABzA1mVUjH5dJTQqSLFvRfqTHqLpxSxSWqMHnvRM4cPBkIRp/XlMK PlXadYtJLPTgpbgvulA1ickC9EwlNYWnowZ4uxnfsMghW4HskBqaV+PnQ8Zvy3L0 12c7Cg4mKKS5pb1HdRuiD2opZ+Hc77gRQLvtWNS8jQvd/iTbh6fuvTKfAOFoXw22 sWIKHYrmhCIRshUNohGXv50m2o+1w9oWmQ6Dkq7lCjfXfUB4wIbggJjpyEtbNqBt j4MC2x5rfsLKKqToKmNE7pFEgqwe8//Aar1b+Qj+ -----END CERTIFICATE----- """.trimIndent() ) val peerCertificate = session.peerCertificates[0] as X509Certificate if (isAndroid || platform.isConscrypt()) { assertThat(certificateSANs(peerCertificate)).containsExactly("bar.com") } else { assertThat(certificateSANs(peerCertificate)).containsExactly("bar.com", "οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½.co.jp") } assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("a.foo.com", session)).isFalse // these checks test alternative subjects. The test data contains an // alternative subject starting with a japanese kanji character. This is // not supported by Android because the underlying implementation from // harmony follows the definition from rfc 1034 page 10 for alternative // subject names. This causes the code to drop all alternative subjects. assertThat(verifier.verify("bar.com", session)).isTrue assertThat(verifier.verify("a.bar.com", session)).isFalse assertThat(verifier.verify("a.\u82b1\u5b50.co.jp", session)).isFalse } @Test fun verifySubjectAltOnly() { // subjectAlt=foo.com val session = session( """ -----BEGIN CERTIFICATE----- MIIESjCCAzKgAwIBAgIJAIz+EYMBU6aYMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MjYxMFoXDTI4MTEwNTE2MjYxMFowgZIx CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0 IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl cnRpZmljYXRlczElMCMGCSqGSIb3DQEJARYWanVsaXVzZGF2aWVzQGdtYWlsLmNv bTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMhjr5aCPoyp0R1iroWA fnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2BlYho4O84X244QrZTRl8kQbYt xnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRyzerA/ZtrlUqf+lKo0uWcocxe Rc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY07hNKXAb2odnVqgzcYiDkLV8 ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8BqnGd87xQU3FVZI4tbtkB+Kz jD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiVJTxpTKqym93whYk93l3ocEe5 5c0CAwEAAaOBkDCBjTAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NM IEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUnxR3vz86tso4gkJIFiza 0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuzA1LKh6YNPg0wEgYDVR0RBAsw CYIHZm9vLmNvbTANBgkqhkiG9w0BAQUFAAOCAQEAjl78oMjzFdsMy6F1sGg/IkO8 tF5yUgPgFYrs41yzAca7IQu6G9qtFDJz/7ehh/9HoG+oqCCIHPuIOmS7Sd0wnkyJ Y7Y04jVXIb3a6f6AgBkEFP1nOT0z6kjT7vkA5LJ2y3MiDcXuRNMSta5PYVnrX8aZ yiqVUNi40peuZ2R8mAUSBvWgD7z2qWhF8YgDb7wWaFjg53I36vWKn90ZEti3wNCw qAVqixM+J0qJmQStgAc53i2aTMvAQu3A3snvH/PHTBo+5UL72n9S1kZyNCsVf1Qo n8jKTiRriEM+fMFlcgQP284EBFzYHyCXFb9O/hMjK2+6mY9euMB1U1aFFzM/Bg== -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("foo.com", session)).isTrue assertThat(verifier.verify("a.foo.com", session)).isFalse assertThat(verifier.verify("foo.com", session)).isTrue assertThat(verifier.verify("a.foo.com", session)).isFalse } @Test fun verifyMultipleCn() { // CN=foo.com, CN=bar.com, CN=&#x82b1;&#x5b50;.co.jp val session = session( """ -----BEGIN CERTIFICATE----- MIIEbzCCA1egAwIBAgIJAIz+EYMBU6aXMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTk0NVoXDTI4MTEwNTE2MTk0NVowgc0x CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0 IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl cnRpZmljYXRlczEQMA4GA1UEAwwHZm9vLmNvbTEQMA4GA1UEAwwHYmFyLmNvbTEV MBMGA1UEAwwM6Iqx5a2QLmNvLmpwMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp ZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyGOv loI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pNjYGViGjg7zhf bjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0ZHLN6sD9m2uV Sp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1JVjTuE0pcBva h2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6q/wGqcZ3zvFB TcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYxqJUlPGlMqrKb 3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQf Fh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUnxR3vz86 tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuzA1LKh6YNPg0w DQYJKoZIhvcNAQEFBQADggEBAGuZb8ai1NO2j4v3y9TLZvd5s0vh5/TE7n7RX+8U y37OL5k7x9nt0mM1TyAKxlCcY+9h6frue8MemZIILSIvMrtzccqNz0V1WKgA+Orf uUrabmn+CxHF5gpy6g1Qs2IjVYWA5f7FROn/J+Ad8gJYc1azOWCLQqSyfpNRLSvY EriQFEV63XvkJ8JrG62b+2OT2lqT4OO07gSPetppdlSa8NBSKP6Aro9RIX1ZjUZQ SpQFCfo02NO0uNRDPUdJx2huycdNb+AXHaO7eXevDLJ+QnqImIzxWiY6zLOdzjjI VBMkLHmnP7SjGSQ3XA4ByrQOxfOUTyLyE7NuemhHppuQPxE= -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("a.foo.com", session)).isFalse assertThat(verifier.verify("bar.com", session)).isFalse assertThat(verifier.verify("a.bar.com", session)).isFalse assertThat(verifier.verify("\u82b1\u5b50.co.jp", session)).isFalse assertThat(verifier.verify("a.\u82b1\u5b50.co.jp", session)).isFalse } @Test fun verifyWilcardCn() { // CN=*.foo.com val session = session( """ -----BEGIN CERTIFICATE----- MIIESDCCAzCgAwIBAgIJAIz+EYMBU6aUMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTU1NVoXDTI4MTEwNTE2MTU1NVowgaYx CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0 IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl cnRpZmljYXRlczESMBAGA1UEAxQJKi5mb28uY29tMSUwIwYJKoZIhvcNAQkBFhZq dWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB CgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pN jYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0 ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1 JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6 q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYx qJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwGCWCG SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz A1LKh6YNPg0wDQYJKoZIhvcNAQEFBQADggEBAH0ipG6J561UKUfgkeW7GvYwW98B N1ZooWX+JEEZK7+Pf/96d3Ij0rw9ACfN4bpfnCq0VUNZVSYB+GthQ2zYuz7tf/UY A6nxVgR/IjG69BmsBl92uFO7JTNtHztuiPqBn59pt+vNx4yPvno7zmxsfI7jv0ww yfs+0FNm7FwdsC1k47GBSOaGw38kuIVWqXSAbL4EX9GkryGGOKGNh0qvAENCdRSB G9Z6tyMbmfRY+dLSh3a9JwoEcBUso6EWYBakLbq4nG/nvYdYvG9ehrnLVwZFL82e l3Q/RK95bnA6cuRClGusLad0e6bjkBzx/VQ3VarDEpAkTLUGVAa0CLXtnyc= -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("www.foo.com", session)).isFalse assertThat(verifier.verify("\u82b1\u5b50.foo.com", session)).isFalse assertThat(verifier.verify("a.b.foo.com", session)).isFalse } @Test fun verifyWilcardCnOnTld() { // It's the CA's responsibility to not issue broad-matching certificates! // CN=*.co.jp val session = session( """ -----BEGIN CERTIFICATE----- MIIERjCCAy6gAwIBAgIJAIz+EYMBU6aVMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTYzMFoXDTI4MTEwNTE2MTYzMFowgaQx CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0 IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl cnRpZmljYXRlczEQMA4GA1UEAxQHKi5jby5qcDElMCMGCSqGSIb3DQEJARYWanVs aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY 07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8 BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV JTxpTKqym93whYk93l3ocEe55c0CAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgB hvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYE FJ8Ud78/OrbKOIJCSBYs2tDLXofYMB8GA1UdIwQYMBaAFHua2o+QmU5S0qzbswNS yoemDT4NMA0GCSqGSIb3DQEBBQUAA4IBAQA0sWglVlMx2zNGvUqFC73XtREwii53 CfMM6mtf2+f3k/d8KXhLNySrg8RRlN11zgmpPaLtbdTLrmG4UdAHHYr8O4y2BBmE 1cxNfGxxechgF8HX10QV4dkyzp6Z1cfwvCeMrT5G/V1pejago0ayXx+GPLbWlNeZ S+Kl0m3p+QplXujtwG5fYcIpaGpiYraBLx3Tadih39QN65CnAh/zRDhLCUzKyt9l UGPLEUDzRHMPHLnSqT1n5UU5UDRytbjJPXzF+l/+WZIsanefWLsxnkgAuZe/oMMF EJMryEzOjg4Tfuc5qM0EXoPcQ/JlheaxZ40p2IyHqbsWV4MRYuFH4bkM -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("foo.co.jp", session)).isFalse assertThat(verifier.verify("\u82b1\u5b50.co.jp", session)).isFalse } /** * Previously ignored due to incompatibilities between Android and Java on how non-ASCII subject * alt names are parsed. Android fails to parse these, which means we fall back to the CN. * The RI does parse them, so the CN is unused. */ @Test fun testWilcardNonAsciiSubjectAlt() { // Expecting actual: // ["*.bar.com", "*.花Γ₯­.co.jp"] // to contain exactly (and in same order): // ["*.bar.com", "*.οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½.co.jp"] platform.assumeNotBouncyCastle() // CN=*.foo.com, subjectAlt=*.bar.com, subjectAlt=*.&#x82b1;&#x5b50;.co.jp // (*.hanako.co.jp in kanji) val session = session( """ -----BEGIN CERTIFICATE----- MIIEcDCCA1igAwIBAgIJAIz+EYMBU6aWMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTczMVoXDTI4MTEwNTE2MTczMVowgaYx CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0 IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl cnRpZmljYXRlczESMBAGA1UEAxQJKi5mb28uY29tMSUwIwYJKoZIhvcNAQkBFhZq dWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB CgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pN jYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0 ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1 JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6 q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYx qJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo4GiMIGfMAkGA1UdEwQCMAAwLAYJ YIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0GA1Ud DgQWBBSfFHe/Pzq2yjiCQkgWLNrQy16H2DAfBgNVHSMEGDAWgBR7mtqPkJlOUtKs 27MDUsqHpg0+DTAkBgNVHREEHTAbggkqLmJhci5jb22CDiou6Iqx5a2QLmNvLmpw MA0GCSqGSIb3DQEBBQUAA4IBAQBobWC+D5/lx6YhX64CwZ26XLjxaE0S415ajbBq DK7lz+Rg7zOE3GsTAMi+ldUYnhyz0wDiXB8UwKXl0SDToB2Z4GOgqQjAqoMmrP0u WB6Y6dpkfd1qDRUzI120zPYgSdsXjHW9q2H77iV238hqIU7qCvEz+lfqqWEY504z hYNlknbUnR525ItosEVwXFBJTkZ3Yw8gg02c19yi8TAh5Li3Ad8XQmmSJMWBV4XK qFr0AIZKBlg6NZZFf/0dP9zcKhzSriW27bY0XfzA6GSiRDXrDjgXq6baRT6YwgIg pgJsDbJtZfHnV1nd3M6zOtQPm1TIQpNmMMMd/DPrGcUQerD3 -----END CERTIFICATE----- """.trimIndent() ) val peerCertificate = session.peerCertificates[0] as X509Certificate if (isAndroid || platform.isConscrypt()) { assertThat(certificateSANs(peerCertificate)).containsExactly("*.bar.com") } else { assertThat(certificateSANs(peerCertificate)) .containsExactly("*.bar.com", "*.οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½.co.jp") } // try the foo.com variations assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("www.foo.com", session)).isFalse assertThat(verifier.verify("\u82b1\u5b50.foo.com", session)).isFalse assertThat(verifier.verify("a.b.foo.com", session)).isFalse // these checks test alternative subjects. The test data contains an // alternative subject starting with a japanese kanji character. This is // not supported by Android because the underlying implementation from // harmony follows the definition from rfc 1034 page 10 for alternative // subject names. This causes the code to drop all alternative subjects. assertThat(verifier.verify("bar.com", session)).isFalse assertThat(verifier.verify("www.bar.com", session)).isTrue assertThat(verifier.verify("\u82b1\u5b50.bar.com", session)).isFalse assertThat(verifier.verify("a.b.bar.com", session)).isFalse } @Test fun subjectAltUsesLocalDomainAndIp() { // cat cert.cnf // [req] // distinguished_name=distinguished_name // req_extensions=req_extensions // x509_extensions=x509_extensions // [distinguished_name] // [req_extensions] // [x509_extensions] // subjectAltName=DNS:localhost.localdomain,DNS:localhost,IP:127.0.0.1 // // $ openssl req -x509 -nodes -days 36500 -subj '/CN=localhost' -config ./cert.cnf \ // -newkey rsa:512 -out cert.pem val certificate = certificate( """ -----BEGIN CERTIFICATE----- MIIBWDCCAQKgAwIBAgIJANS1EtICX2AZMA0GCSqGSIb3DQEBBQUAMBQxEjAQBgNV BAMTCWxvY2FsaG9zdDAgFw0xMjAxMDIxOTA4NThaGA8yMTExMTIwOTE5MDg1OFow FDESMBAGA1UEAxMJbG9jYWxob3N0MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAPpt atK8r4/hf4hSIs0os/BSlQLbRBaK9AfBReM4QdAklcQqe6CHsStKfI8pp0zs7Ptg PmMdpbttL0O7mUboBC8CAwEAAaM1MDMwMQYDVR0RBCowKIIVbG9jYWxob3N0Lmxv Y2FsZG9tYWlugglsb2NhbGhvc3SHBH8AAAEwDQYJKoZIhvcNAQEFBQADQQD0ntfL DCzOCv9Ma6Lv5o5jcYWVxvBSTsnt22hsJpWD1K7iY9lbkLwl0ivn73pG2evsAn9G X8YKH52fnHsCrhSD -----END CERTIFICATE----- """.trimIndent() ) assertThat(certificate.subjectX500Principal).isEqualTo( X500Principal("CN=localhost") ) val session = FakeSSLSession(certificate) assertThat(verifier.verify("localhost", session)).isTrue assertThat(verifier.verify("localhost.localdomain", session)).isTrue assertThat(verifier.verify("local.host", session)).isFalse assertThat(verifier.verify("127.0.0.1", session)).isTrue assertThat(verifier.verify("127.0.0.2", session)).isFalse } @Test fun wildcardsCannotMatchIpAddresses() { // openssl req -x509 -nodes -days 36500 -subj '/CN=*.0.0.1' -newkey rsa:512 -out cert.pem val session = session( """ -----BEGIN CERTIFICATE----- MIIBkjCCATygAwIBAgIJAMdemqOwd/BEMA0GCSqGSIb3DQEBBQUAMBIxEDAOBgNV BAMUByouMC4wLjEwIBcNMTAxMjIwMTY0NDI1WhgPMjExMDExMjYxNjQ0MjVaMBIx EDAOBgNVBAMUByouMC4wLjEwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAqY8c9Qrt YPWCvb7lclI+aDHM6fgbJcHsS9Zg8nUOh5dWrS7AgeA25wyaokFl4plBbbHQe2j+ cCjsRiJIcQo9HwIDAQABo3MwcTAdBgNVHQ4EFgQUJ436TZPJvwCBKklZZqIvt1Yt JjEwQgYDVR0jBDswOYAUJ436TZPJvwCBKklZZqIvt1YtJjGhFqQUMBIxEDAOBgNV BAMUByouMC4wLjGCCQDHXpqjsHfwRDAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEB BQUAA0EAk9i88xdjWoewqvE+iMC9tD2obMchgFDaHH0ogxxiRaIKeEly3g0uGxIt fl2WRY8hb4x+zRrwsFaLEpdEvqcjOQ== -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("127.0.0.1", session)).isFalse } /** * Earlier implementations of Android's hostname verifier required that wildcard names wouldn't * match "*.com" or similar. This was a nonstandard check that we've since dropped. It is the CA's * responsibility to not hand out certificates that match so broadly. */ @Test fun wildcardsDoesNotNeedTwoDots() { // openssl req -x509 -nodes -days 36500 -subj '/CN=*.com' -newkey rsa:512 -out cert.pem val session = session( """ -----BEGIN CERTIFICATE----- MIIBjDCCATagAwIBAgIJAOVulXCSu6HuMA0GCSqGSIb3DQEBBQUAMBAxDjAMBgNV BAMUBSouY29tMCAXDTEwMTIyMDE2NDkzOFoYDzIxMTAxMTI2MTY0OTM4WjAQMQ4w DAYDVQQDFAUqLmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDJd8xqni+h7Iaz ypItivs9kPuiJUqVz+SuJ1C05SFc3PmlRCvwSIfhyD67fHcbMdl+A/LrIjhhKZJe 1joO0+pFAgMBAAGjcTBvMB0GA1UdDgQWBBS4Iuzf5w8JdCp+EtBfdFNudf6+YzBA BgNVHSMEOTA3gBS4Iuzf5w8JdCp+EtBfdFNudf6+Y6EUpBIwEDEOMAwGA1UEAxQF Ki5jb22CCQDlbpVwkruh7jAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA0EA U6LFxmZr31lFyis2/T68PpjAppc0DpNQuA2m/Y7oTHBDi55Fw6HVHCw3lucuWZ5d qUYo4ES548JdpQtcLrW2sA== -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("google.com", session)).isFalse } @Test fun subjectAltName() { // $ cat ./cert.cnf // [req] // distinguished_name=distinguished_name // req_extensions=req_extensions // x509_extensions=x509_extensions // [distinguished_name] // [req_extensions] // [x509_extensions] // subjectAltName=DNS:bar.com,DNS:baz.com // // $ openssl req -x509 -nodes -days 36500 -subj '/CN=foo.com' -config ./cert.cnf \ // -newkey rsa:512 -out cert.pem val session = session( """ -----BEGIN CERTIFICATE----- MIIBPTCB6KADAgECAgkA7zoHaaqNGHQwDQYJKoZIhvcNAQEFBQAwEjEQMA4GA1UE AxMHZm9vLmNvbTAgFw0xMDEyMjAxODM5MzZaGA8yMTEwMTEyNjE4MzkzNlowEjEQ MA4GA1UEAxMHZm9vLmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQC+gmoSxF+8 hbV+rgRQqHIJd50216OWQJbU3BvdlPbca779NYO4+UZWTFdBM8BdQqs3H4B5Agvp y7HeSff1F7XRAgMBAAGjHzAdMBsGA1UdEQQUMBKCB2Jhci5jb22CB2Jhei5jb20w DQYJKoZIhvcNAQEFBQADQQBXpZZPOY2Dy1lGG81JTr8L4or9jpKacD7n51eS8iqI oTznPNuXHU5bFN0AAGX2ij47f/EahqTpo5RdS95P4sVm -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("bar.com", session)).isTrue assertThat(verifier.verify("baz.com", session)).isTrue assertThat(verifier.verify("a.foo.com", session)).isFalse assertThat(verifier.verify("quux.com", session)).isFalse } @Test fun subjectAltNameWithWildcard() { // $ cat ./cert.cnf // [req] // distinguished_name=distinguished_name // req_extensions=req_extensions // x509_extensions=x509_extensions // [distinguished_name] // [req_extensions] // [x509_extensions] // subjectAltName=DNS:bar.com,DNS:*.baz.com // // $ openssl req -x509 -nodes -days 36500 -subj '/CN=foo.com' -config ./cert.cnf \ // -newkey rsa:512 -out cert.pem val session = session( """ -----BEGIN CERTIFICATE----- MIIBPzCB6qADAgECAgkAnv/7Jv5r7pMwDQYJKoZIhvcNAQEFBQAwEjEQMA4GA1UE AxMHZm9vLmNvbTAgFw0xMDEyMjAxODQ2MDFaGA8yMTEwMTEyNjE4NDYwMVowEjEQ MA4GA1UEAxMHZm9vLmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDAz2YXnyog YdYLSFr/OEgSumtwqtZKJTB4wqTW/eKbBCEzxnyUMxWZIqUGu353PzwfOuWp2re3 nvVV+QDYQlh9AgMBAAGjITAfMB0GA1UdEQQWMBSCB2Jhci5jb22CCSouYmF6LmNv bTANBgkqhkiG9w0BAQUFAANBAB8yrSl8zqy07i0SNYx2B/FnvQY734pxioaqFWfO Bqo1ZZl/9aPHEWIwBrxYNVB0SGu/kkbt/vxqOjzzrkXukmI= -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("bar.com", session)).isTrue assertThat(verifier.verify("a.baz.com", session)).isTrue assertThat(verifier.verify("baz.com", session)).isFalse assertThat(verifier.verify("a.foo.com", session)).isFalse assertThat(verifier.verify("a.bar.com", session)).isFalse assertThat(verifier.verify("quux.com", session)).isFalse } @Test fun subjectAltNameWithIPAddresses() { // $ cat ./cert.cnf // [req] // distinguished_name=distinguished_name // req_extensions=req_extensions // x509_extensions=x509_extensions // [distinguished_name] // [req_extensions] // [x509_extensions] // subjectAltName=IP:0:0:0:0:0:0:0:1,IP:2a03:2880:f003:c07:face:b00c::2,IP:0::5,IP:192.168.1.1 // // $ openssl req -x509 -nodes -days 36500 -subj '/CN=foo.com' -config ./cert.cnf \ // -newkey rsa:512 -out cert.pem val session = session( """ -----BEGIN CERTIFICATE----- MIIBaDCCARKgAwIBAgIJALxN+AOBVGwQMA0GCSqGSIb3DQEBCwUAMBIxEDAOBgNV BAMMB2Zvby5jb20wIBcNMjAwMzIyMTEwNDI4WhgPMjEyMDAyMjcxMTA0MjhaMBIx EDAOBgNVBAMMB2Zvby5jb20wXDANBgkqhkiG9w0BAQEFAANLADBIAkEAlnVbVfQ9 4aYjrPCcFuxOpjXuvyOc9Hcha4K7TfXyfsrjhAvCjCBIT/TiLOUVF3sx4yoCAtX8 wmt404tTbKD6UwIDAQABo0kwRzBFBgNVHREEPjA8hxAAAAAAAAAAAAAAAAAAAAAB hxAqAyiA8AMMB/rOsAwAAAAChxAAAAAAAAAAAAAAAAAAAAAFhwTAqAEBMA0GCSqG SIb3DQEBCwUAA0EAPSOYHJh7hB4ElBqTCAFW+T5Y7mXsv9nQjBJ7w0YIw83V2PEI 3KbBIyGTrqHD6lG8QGZy+yNkIcRlodG8OfQRUg== -----END CERTIFICATE----- """.trimIndent() ) assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("::1", session)).isTrue assertThat(verifier.verify("::2", session)).isFalse assertThat(verifier.verify("::5", session)).isTrue assertThat(verifier.verify("2a03:2880:f003:c07:face:b00c::2", session)).isTrue assertThat(verifier.verify("2a03:2880:f003:c07:face:b00c:0:2", session)).isTrue assertThat(verifier.verify("2a03:2880:f003:c07:FACE:B00C:0:2", session)).isTrue assertThat(verifier.verify("2a03:2880:f003:c07:face:b00c:0:3", session)).isFalse assertThat(verifier.verify("127.0.0.1", session)).isFalse assertThat(verifier.verify("192.168.1.1", session)).isTrue assertThat(verifier.verify("::ffff:192.168.1.1", session)).isTrue assertThat(verifier.verify("0:0:0:0:0:FFFF:C0A8:0101", session)).isTrue } @Test fun generatedCertificate() { val heldCertificate = HeldCertificate.Builder() .commonName("Foo Corp") .addSubjectAlternativeName("foo.com") .build() val session = session(heldCertificate.certificatePem()) assertThat(verifier.verify("foo.com", session)).isTrue assertThat(verifier.verify("bar.com", session)).isFalse } @Test fun specialKInHostname() { // https://github.com/apache/httpcomponents-client/commit/303e435d7949652ea77a6c50df1c548682476b6e // https://www.gosecure.net/blog/2020/10/27/weakness-in-java-tls-host-verification/ val heldCertificate = HeldCertificate.Builder() .commonName("Foo Corp") .addSubjectAlternativeName("k.com") .addSubjectAlternativeName("tel.com") .build() val session = session(heldCertificate.certificatePem()) assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("bar.com", session)).isFalse assertThat(verifier.verify("k.com", session)).isTrue assertThat(verifier.verify("K.com", session)).isTrue assertThat(verifier.verify("\u2121.com", session)).isFalse assertThat(verifier.verify("β„‘.com", session)).isFalse // These should ideally be false, but we know that hostname is usually already checked by us assertThat(verifier.verify("\u212A.com", session)).isFalse // Kelvin character below assertThat(verifier.verify("β„ͺ.com", session)).isFalse } @Test fun specialKInCert() { // https://github.com/apache/httpcomponents-client/commit/303e435d7949652ea77a6c50df1c548682476b6e // https://www.gosecure.net/blog/2020/10/27/weakness-in-java-tls-host-verification/ val heldCertificate = HeldCertificate.Builder() .commonName("Foo Corp") .addSubjectAlternativeName("\u2121.com") .addSubjectAlternativeName("\u212A.com") .build() val session = session(heldCertificate.certificatePem()) assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("bar.com", session)).isFalse assertThat(verifier.verify("k.com", session)).isFalse assertThat(verifier.verify("K.com", session)).isFalse assertThat(verifier.verify("tel.com", session)).isFalse assertThat(verifier.verify("k.com", session)).isFalse } @Test fun specialKInExternalCert() { // OpenJDK related test. platform.assumeNotConscrypt() // Expecting actual: // ["҄‘.com", "Γ’Β„Βͺ.com"] // to contain exactly (and in same order): // ["οΏ½οΏ½οΏ½.com", "οΏ½οΏ½οΏ½.com"] platform.assumeNotBouncyCastle() // $ cat ./cert.cnf // [req] // distinguished_name=distinguished_name // req_extensions=req_extensions // x509_extensions=x509_extensions // [distinguished_name] // [req_extensions] // [x509_extensions] // subjectAltName=DNS:β„‘.com,DNS:β„ͺ.com // // $ openssl req -x509 -nodes -days 36500 -subj '/CN=foo.com' -config ./cert.cnf \ // -newkey rsa:512 -out cert.pem val session = session( """ -----BEGIN CERTIFICATE----- MIIBSDCB86ADAgECAhRLR4TGgXBegg0np90FZ1KPeWpDtjANBgkqhkiG9w0BAQsF ADASMRAwDgYDVQQDDAdmb28uY29tMCAXDTIwMTAyOTA2NTkwNVoYDzIxMjAxMDA1 MDY1OTA1WjASMRAwDgYDVQQDDAdmb28uY29tMFwwDQYJKoZIhvcNAQEBBQADSwAw SAJBALQcTVW9aW++ClIV9/9iSzijsPvQGEu/FQOjIycSrSIheZyZmR8bluSNBq0C 9fpalRKZb0S2tlCTi5WoX8d3K30CAwEAAaMfMB0wGwYDVR0RBBQwEoIH4oShLmNv bYIH4oSqLmNvbTANBgkqhkiG9w0BAQsFAANBAA1+/eDvSUGv78iEjNW+1w3OPAwt Ij1qLQ/YI8OogZPMk7YY46/ydWWp7UpD47zy/vKmm4pOc8Glc8MoDD6UADs= -----END CERTIFICATE----- """.trimIndent() ) val peerCertificate = session.peerCertificates[0] as X509Certificate if (isAndroid) { assertThat(certificateSANs(peerCertificate)).containsExactly() } else { assertThat(certificateSANs(peerCertificate)).containsExactly("οΏ½οΏ½οΏ½.com", "οΏ½οΏ½οΏ½.com") } assertThat(verifier.verify("tel.com", session)).isFalse assertThat(verifier.verify("k.com", session)).isFalse assertThat(verifier.verify("foo.com", session)).isFalse assertThat(verifier.verify("bar.com", session)).isFalse assertThat(verifier.verify("k.com", session)).isFalse assertThat(verifier.verify("K.com", session)).isFalse } private fun certificateSANs(peerCertificate: X509Certificate): Stream<String> { val subjectAlternativeNames = peerCertificate.subjectAlternativeNames return if (subjectAlternativeNames == null) { Stream.empty() } else { subjectAlternativeNames.stream().map { c: List<*> -> c[1] as String } } } @Test fun replacementCharacter() { // $ cat ./cert.cnf // [req] // distinguished_name=distinguished_name // req_extensions=req_extensions // x509_extensions=x509_extensions // [distinguished_name] // [req_extensions] // [x509_extensions] // subjectAltName=DNS:β„‘.com,DNS:β„ͺ.com // // $ openssl req -x509 -nodes -days 36500 -subj '/CN=foo.com' -config ./cert.cnf \ // -newkey rsa:512 -out cert.pem val session = session( """ -----BEGIN CERTIFICATE----- MIIBSDCB86ADAgECAhRLR4TGgXBegg0np90FZ1KPeWpDtjANBgkqhkiG9w0BAQsF ADASMRAwDgYDVQQDDAdmb28uY29tMCAXDTIwMTAyOTA2NTkwNVoYDzIxMjAxMDA1 MDY1OTA1WjASMRAwDgYDVQQDDAdmb28uY29tMFwwDQYJKoZIhvcNAQEBBQADSwAw SAJBALQcTVW9aW++ClIV9/9iSzijsPvQGEu/FQOjIycSrSIheZyZmR8bluSNBq0C 9fpalRKZb0S2tlCTi5WoX8d3K30CAwEAAaMfMB0wGwYDVR0RBBQwEoIH4oShLmNv bYIH4oSqLmNvbTANBgkqhkiG9w0BAQsFAANBAA1+/eDvSUGv78iEjNW+1w3OPAwt Ij1qLQ/YI8OogZPMk7YY46/ydWWp7UpD47zy/vKmm4pOc8Glc8MoDD6UADs= -----END CERTIFICATE----- """.trimIndent() ) // Replacement characters are deliberate, from certificate loading. assertThat(verifier.verify("οΏ½οΏ½οΏ½.com", session)).isFalse assertThat(verifier.verify("β„‘.com", session)).isFalse } @Test fun thatCatchesErrorsWithBadSession() { val localVerifier = OkHttpClient().hostnameVerifier // Since this is public API, okhttp3.internal.tls.OkHostnameVerifier.verify is also assertThat(verifier).isInstanceOf(OkHostnameVerifier::class.java) val session = localhost().sslContext().createSSLEngine().session assertThat(localVerifier.verify("\uD83D\uDCA9.com", session)).isFalse } @Test fun verifyAsIpAddress() { // IPv4 assertThat("127.0.0.1".canParseAsIpAddress()).isTrue assertThat("1.2.3.4".canParseAsIpAddress()).isTrue // IPv6 assertThat("::1".canParseAsIpAddress()).isTrue assertThat("2001:db8::1".canParseAsIpAddress()).isTrue assertThat("::192.168.0.1".canParseAsIpAddress()).isTrue assertThat("::ffff:192.168.0.1".canParseAsIpAddress()).isTrue assertThat("FEDC:BA98:7654:3210:FEDC:BA98:7654:3210".canParseAsIpAddress()).isTrue assertThat("1080:0:0:0:8:800:200C:417A".canParseAsIpAddress()).isTrue assertThat("1080::8:800:200C:417A".canParseAsIpAddress()).isTrue assertThat("FF01::101".canParseAsIpAddress()).isTrue assertThat("0:0:0:0:0:0:13.1.68.3".canParseAsIpAddress()).isTrue assertThat("0:0:0:0:0:FFFF:129.144.52.38".canParseAsIpAddress()).isTrue assertThat("::13.1.68.3".canParseAsIpAddress()).isTrue assertThat("::FFFF:129.144.52.38".canParseAsIpAddress()).isTrue // Hostnames assertThat("go".canParseAsIpAddress()).isFalse assertThat("localhost".canParseAsIpAddress()).isFalse assertThat("squareup.com".canParseAsIpAddress()).isFalse assertThat("www.nintendo.co.jp".canParseAsIpAddress()).isFalse } private fun certificate(certificate: String): X509Certificate { return CertificateFactory.getInstance("X.509") .generateCertificate(ByteArrayInputStream(certificate.toByteArray())) as X509Certificate } private fun session(certificate: String): SSLSession = FakeSSLSession(certificate(certificate)) }
okhttp/src/jvmTest/java/okhttp3/internal/tls/HostnameVerifierTest.kt
1273836973
package kotlinx.html.dom import kotlinx.html.* import kotlinx.html.consumers.* import org.w3c.dom.* import org.w3c.dom.events.* import org.xml.sax.* import java.io.* import java.util.* import javax.xml.parsers.* import javax.xml.transform.* import javax.xml.transform.dom.* import javax.xml.transform.stream.* class HTMLDOMBuilder(val document : Document) : TagConsumer<Element> { private val path = arrayListOf<Element>() private var lastLeaved : Element? = null private val documentBuilder: DocumentBuilder by lazy { DocumentBuilderFactory.newInstance().newDocumentBuilder() } override fun onTagStart(tag: Tag) { val element = when { tag.namespace != null -> document.createElementNS(tag.namespace!!, tag.tagName) else -> document.createElement(tag.tagName) } tag.attributesEntries.forEach { element.setAttribute(it.key, it.value) } if (path.isNotEmpty()) { path.last().appendChild(element) } path.add(element) } override fun onTagAttributeChange(tag: Tag, attribute: String, value: String?) { if (path.isEmpty()) { throw IllegalStateException("No current tag") } path.last().let { node -> if (value == null) { node.removeAttribute(attribute) } else { node.setAttribute(attribute, value) } } } override fun onTagEvent(tag: Tag, event: String, value: (Event) -> Unit) { throw UnsupportedOperationException("You can't assign lambda event handler on JVM") } override fun onTagEnd(tag: Tag) { if (path.isEmpty() || path.last().tagName.toLowerCase() != tag.tagName.toLowerCase()) { throw IllegalStateException("We haven't entered tag ${tag.tagName} but trying to leave") } val element = path.removeAt(path.lastIndex) element.setIdAttributeName() lastLeaved = element } override fun onTagContent(content: CharSequence) { if (path.isEmpty()) { throw IllegalStateException("No current DOM node") } path.last().appendChild(document.createTextNode(content.toString())) } override fun onTagComment(content: CharSequence) { if (path.isEmpty()) { throw IllegalStateException("No current DOM node") } path.last().appendChild(document.createComment(content.toString())) } override fun onTagContentEntity(entity: Entities) { if (path.isEmpty()) { throw IllegalStateException("No current DOM node") } path.last().appendChild(document.createEntityReference(entity.name)) } override fun finalize() = lastLeaved ?: throw IllegalStateException("No tags were emitted") override fun onTagContentUnsafe(block: Unsafe.() -> Unit) { UnsafeImpl.block() } private val UnsafeImpl = object : Unsafe { override operator fun String.unaryPlus() { val element = documentBuilder .parse(InputSource(StringReader("<unsafeRoot>" + this + "</unsafeRoot>"))) .documentElement val importNode = document.importNode(element, true) check(importNode.nodeName == "unsafeRoot") { "the document factory hasn't created an unsafeRoot node"} val last = path.last() while (importNode.hasChildNodes()) { last.appendChild(importNode.removeChild(importNode.firstChild)) } } } private fun Element.setIdAttributeName() { if (hasAttribute("id")) { setIdAttribute("id", true) } } } fun Document.createHTMLTree() : TagConsumer<Element> = HTMLDOMBuilder(this) val Document.create : TagConsumer<Element> get() = HTMLDOMBuilder(this) fun Node.append(block : TagConsumer<Element>.() -> Unit) : List<Element> = ArrayList<Element>().let { result -> ownerDocumentExt.createHTMLTree().onFinalize { it, partial -> if (!partial) { appendChild(it); result.add(it) } }.block() result } fun Node.prepend(block: TagConsumer<Element>.() -> Unit) : List<Element> = ArrayList<Element>().let { result -> ownerDocumentExt.createHTMLTree().onFinalize { it, partial -> if (!partial) { insertBefore(it, firstChild) result.add(it) } }.block() result } val Node.append: TagConsumer<Element> get() = ownerDocumentExt.createHTMLTree().onFinalize { it, partial -> if (!partial) { appendChild(it) } } val Node.prepend: TagConsumer<Element> get() = ownerDocumentExt.createHTMLTree().onFinalize { it, partial -> if (!partial) { insertBefore(it, firstChild) }} private val Node.ownerDocumentExt: Document get() = when { this is Document -> this else -> ownerDocument ?: throw IllegalArgumentException("node has no ownerDocument") } fun createHTMLDocument() : TagConsumer<Document> = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument().let { document -> HTMLDOMBuilder(document).onFinalizeMap { it, partial -> if (!partial) {document.appendChild(it)}; document } } inline fun document(block : Document.() -> Unit) : Document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument().let { document -> document.block() document } fun Writer.write(document : Document, prettyPrint : Boolean = true) : Writer { write("<!DOCTYPE html>\n") write(document.documentElement, prettyPrint) return this } fun Writer.write(element: Element, prettyPrint : Boolean = true) : Writer { val transformer = TransformerFactory.newInstance().newTransformer() transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes") transformer.setOutputProperty(OutputKeys.METHOD, "html") transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8") if (prettyPrint) { transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2") transformer.setOutputProperty(OutputKeys.INDENT, "yes") } transformer.transform(DOMSource(element), StreamResult(this)) return this } fun Element.serialize(prettyPrint : Boolean = true) : String = StringWriter().write(this, prettyPrint).toString() fun Document.serialize(prettyPrint : Boolean = true) : String = StringWriter().write(this, prettyPrint).toString()
src/jvmMain/kotlin/dom-jvm.kt
1866025492
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.health.services.client import androidx.health.services.client.data.DeltaDataType import androidx.health.services.client.data.MeasureCapabilities import com.google.common.util.concurrent.ListenableFuture import java.util.concurrent.Executor /** * Client which provides a way to make measurements of health data on a device. * * This is optimized for apps to register live callbacks on data which may be sampled at a faster * rate; this is not meant to be used for long-lived subscriptions to data (for this, consider using * [ExerciseClient] or [PassiveMonitoringClient] depending on your use case). * * Existing subscriptions made with the [PassiveMonitoringClient] are also expected to get the data * generated by this client. */ public interface MeasureClient { /** * Registers the app for live measurement of the specified [DeltaDataType]. * * The callback will be called on the main application thread. To move calls to an alternative * thread use [registerMeasureCallback]. * * Even if data is registered for live capture, it can still be sent out in batches depending on * the application processor state. * * Registering a [DeltaDataType] for live measurement capture is expected to increase the sample * rate on the associated sensor(s); this is typically used for one-off measurements. Do not use * this method for background capture or workout tracking. The client is responsible for * ensuring that their requested [DeltaDataType] is supported on this device by checking the * [MeasureCapabilities]. The returned future will fail if the request is not supported on a * given device. * * The callback will continue to be called until the app is killed or * [unregisterMeasureCallbackAsync] is called. * * If the same [callback] is already registered for the given [DeltaDataType], this operation is * a no-op. * * @param dataType the [DeltaDataType] that needs to be measured * @param callback the [MeasureCallback] to receive updates from Health Services */ public fun registerMeasureCallback(dataType: DeltaDataType<*, *>, callback: MeasureCallback) /** * Same as [registerMeasureCallback], except the [callback] is called on the given [Executor]. * * @param dataType the [DeltaDataType] that needs to be measured * @param executor the [Executor] on which [callback] will be invoked * @param callback the [MeasureCallback] to receive updates from Health Services */ public fun registerMeasureCallback( dataType: DeltaDataType<*, *>, executor: Executor, callback: MeasureCallback ) /** * Unregisters the given [MeasureCallback] for updates of the given [DeltaDataType]. * * @param dataType the [DeltaDataType] that needs to be unregistered * @param callback the [MeasureCallback] which was used in registration * @return a [ListenableFuture] that completes when the un-registration succeeds in Health * Services. This is a no-op if the callback has already been unregistered. */ public fun unregisterMeasureCallbackAsync( dataType: DeltaDataType<*, *>, callback: MeasureCallback ): ListenableFuture<Void> /** * Returns the [MeasureCapabilities] of this client for the device. * * This can be used to determine what [DeltaDataType]s this device supports for live * measurement. Clients should use the capabilities to inform their requests since Health * Services will typically reject requests made for [DeltaDataType]s which are not enabled for * measurement. * * @return a [ListenableFuture] containing the [MeasureCapabilities] for this device */ public fun getCapabilitiesAsync(): ListenableFuture<MeasureCapabilities> }
health/health-services-client/src/main/java/androidx/health/services/client/MeasureClient.kt
3755760660
package io.mstream.boardgameengine.game.tictactoe import io.mstream.boardgameengine.* import io.mstream.boardgameengine.move.* import org.junit.* class TicTacToeMovementTest { @Test fun shouldHandleValidMove() { val recordingEventSender = RecordingEventSender() val ticTacToe = TicTacToe(recordingEventSender) val moveResult = ticTacToe.makeMove(Select.fromCords(0, 0)) Assert.assertTrue("should return CorrectMove when the game is ongoing and an empty field is selected", moveResult.isCorrect()) } @Test fun shouldHandleUnsupportedMove() { val recordingEventSender = RecordingEventSender() val ticTacToe = TicTacToe(recordingEventSender) val moveResult = ticTacToe.makeMove( Drag(Position.fromCords(0, 0), Position.fromCords(1, 1))) Assert.assertEquals("should return UnsupportedMove when drag move is ordered", MoveResult.UNSUPPORTED, moveResult) } @Test fun shouldHandleOutOfBoundsMove() { val recordingEventSender = RecordingEventSender() val ticTacToe = TicTacToe(recordingEventSender) val moveResult = ticTacToe.makeMove(Select.fromCords(5, 5)) Assert.assertEquals("should return OutOfBoundsMove when non existing field is selected", MoveResult.OUT_OF_BOUNDS, moveResult) } @Test fun shouldHandleMoveAtOccupiedField() { val recordingEventSender = RecordingEventSender() val ticTacToe = TicTacToe(recordingEventSender) ticTacToe.makeMove(Select.fromCords(0, 0)) val moveResult = ticTacToe.makeMove(Select.fromCords(0, 0)) Assert.assertEquals("should return FieldOccupiedMove when non empty field is selected", MoveResult.FIELD_OCCUPIED, moveResult) } @Test fun shouldHandleMoveAfterGameEnd() { val recordingEventSender = RecordingEventSender() val ticTacToe = TicTacToe(recordingEventSender) ticTacToe.makeMove(Select.fromCords(0, 0)) ticTacToe.makeMove(Select.fromCords(1, 0)) ticTacToe.makeMove(Select.fromCords(0, 1)) ticTacToe.makeMove(Select.fromCords(1, 1)) ticTacToe.makeMove(Select.fromCords(0, 2)) val moveResult = ticTacToe.makeMove(Select.fromCords(1, 2)) Assert.assertEquals("should return GameFinished when move was made after the game end", MoveResult.GAME_IS_FINISHED, moveResult) } }
src/test/kotlin/io/mstream/boardgameengine/game/tictactoe/TicTacToeMovementTest.kt
3959023848
package io.github.fvasco.pinpoi.util import android.util.Log import io.github.fvasco.pinpoi.dao.AbstractDao import java.io.* import java.util.zip.ZipEntry import java.util.zip.ZipInputStream import java.util.zip.ZipOutputStream /** * Create and restore backup * @author Francesco Vasco */ class BackupManager(private vararg val daos: AbstractDao) { @Throws(IOException::class) fun create(outputStream: OutputStream) { Log.i(BackupManager::class.java.simpleName, "Create backup $outputStream") ZipOutputStream(outputStream).use { zipOutputStream -> for (dao in daos) { synchronized(dao) { val databaseFile: File dao.open() val database = dao.database!! try { databaseFile = File(database.path) } finally { database.close() dao.close() } val zipEntry = ZipEntry(databaseFile.name) zipOutputStream.putNextEntry(zipEntry) val databaseInputStream = FileInputStream(databaseFile) try { dao.lock() databaseInputStream.copyTo(zipOutputStream) } finally { try { databaseInputStream.close() } finally { dao.reset() } } zipOutputStream.closeEntry() } } } } @Throws(IOException::class) fun restore(fileInputStream: InputStream) { Log.i(BackupManager::class.java.simpleName, "Restore backup $fileInputStream") ZipInputStream(fileInputStream).use { zipInputStream -> var zipEntry = zipInputStream.nextEntry while (zipEntry != null) { for (dao in daos) { synchronized(dao) { val databasePath: File dao.open() val database = dao.database!! try { databasePath = File(database.path) } finally { database.close() dao.close() } val databaseName = databasePath.name if (databaseName == zipEntry.name) { try { Log.i(BackupManager::class.java.simpleName, "restore database $databaseName") FileOutputStream(databasePath).use { databaseOutputStream -> dao.lock() ZipGuardInputStream(zipInputStream).copyTo(databaseOutputStream) } } finally { dao.reset() } } } } zipEntry = zipInputStream.nextEntry } } } }
app/src/main/java/io/github/fvasco/pinpoi/util/BackupManager.kt
1755998207
import lib.KotlinClass fun test() = KotlinClass().foo(<caret>) // ABSENT: p0 // EXIST: { lookupString:"paramName =", itemText:"paramName =", icon: "Parameter"}
plugins/kotlin/completion/testData/basic/withLib/NamedArgumentsKotlin.kt
4204343631
// !CHECK_HIGHLIGHTING class Some
plugins/kotlin/idea/tests/testData/multiModuleLineMarker/transitiveCommon/base_common/base.kt
958139650
package com.intellij.ide.actions.searcheverywhere.ml.id import com.intellij.ide.ui.search.OptionDescription import com.intellij.ide.util.gotoByName.GotoActionModel import com.intellij.openapi.actionSystem.AnAction private class ActionKeyProvider: ElementKeyForIdProvider() { override fun getKey(element: Any): Any? { if (element is GotoActionModel.MatchedValue) { val elementValue = element.value return if (elementValue is GotoActionModel.ActionWrapper) { elementValue.action } else { elementValue } } if (element is GotoActionModel.ActionWrapper) { return element.action } else if (element is OptionDescription || element is AnAction) { return element } return null } }
plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/id/ActionKeyProvider.kt
3056753784
// 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.feedback.new_ui.state import com.intellij.openapi.components.* import com.intellij.openapi.util.registry.Registry import kotlinx.datetime.Clock import kotlinx.datetime.LocalDateTime import kotlinx.datetime.TimeZone import kotlinx.datetime.toLocalDateTime import kotlinx.serialization.Serializable @Service(Service.Level.APP) @State(name = "NewUIInfoState", storages = [Storage(StoragePathMacros.NON_ROAMABLE_FILE, deprecated = true), Storage("NewUIInfoService.xml")]) class NewUIInfoService : PersistentStateComponent<NewUIInfoState> { companion object { @JvmStatic fun getInstance(): NewUIInfoService = service() } private var state = NewUIInfoState() override fun getState(): NewUIInfoState = state override fun loadState(state: NewUIInfoState) { this.state = state } fun updateEnableNewUIDate() { if (state.enableNewUIDate == null) { state.enableNewUIDate = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()) } } fun updateDisableNewUIDate() { if (state.disableNewUIDate == null) { state.disableNewUIDate = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()) } } } @Serializable data class NewUIInfoState( var numberNotificationShowed: Int = 0, var feedbackSent: Boolean = false, var enableNewUIDate: LocalDateTime? = if (Registry.get("ide.experimental.ui").asBoolean()) Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()) else null, var disableNewUIDate: LocalDateTime? = null )
platform/feedback/src/com/intellij/feedback/new_ui/state/NewUIInfoService.kt
3676976101
// "Optimize imports" "false" // WITH_RUNTIME // ACTION: Introduce import alias package ppp import ppp.invoke<caret> object Bar object Foo { val bar = Bar } fun Foo.bar() = 1 operator fun Bar.invoke() = 2 fun main() { println(Foo.bar()) }
plugins/kotlin/idea/tests/testData/quickfix/optimizeImports/invoke.kt
1022961382
package com.dg.controls import android.content.Context import android.content.res.TypedArray import android.graphics.Paint import android.graphics.Typeface import android.util.AttributeSet import androidx.appcompat.widget.AppCompatButton import com.dg.R import com.dg.helpers.FontHelper @Suppress("unused") class ButtonEx : AppCompatButton { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { setCustomFontFamily(context, attrs) } constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { setCustomFontFamily(context, attrs) } private fun setCustomFontFamily(context: Context, attrs: AttributeSet) { if (isInEditMode) { return } val fontFamily: String? var styledAttributes: TypedArray? = null try { styledAttributes = context.obtainStyledAttributes(attrs, R.styleable.ButtonEx) fontFamily = styledAttributes!!.getString(R.styleable.ButtonEx_customFontFamily) } finally { styledAttributes?.recycle() } if (fontFamily != null && !fontFamily.isEmpty()) { paintFlags = this.paintFlags or Paint.SUBPIXEL_TEXT_FLAG or Paint.LINEAR_TEXT_FLAG setCustomFont(fontFamily) } } @Deprecated("This version was a mistake", replaceWith = ReplaceWith("setCustomFont(fontFamily)")) fun setCustomFont(context: Context, fontFamily: String): Boolean { return setCustomFont(fontFamily) } fun setCustomFont(fontFamily: String): Boolean { val typeface: Typeface? = FontHelper.getFont(context, fontFamily) return if (typeface != null) { setTypeface(typeface) true } else { false } } }
Helpers/src/main/java/com/dg/controls/ButtonEx.kt
3503306453
// FIR_COMPARISON package test fun `backticked~name`() {} fun test() { `ba<caret> } // ELEMENT: backticked~name
plugins/kotlin/completion/tests/testData/handlers/basic/KT19864.kt
481038026
package pl.srw.billcalculator.tester import android.content.Intent import android.support.test.espresso.intent.Intents.intended import android.support.test.espresso.intent.matcher.IntentMatchers.* import org.hamcrest.Matcher import org.hamcrest.Matchers.`is` import org.hamcrest.Matchers.allOf import pl.srw.billcalculator.R internal class AboutTester : Tester() { fun clickMailLink(): AboutTester { clickText(R.string.emailme) return this } fun clickGPlusLink(): AboutTester { clickText(R.string.link_gplus) return this } fun checkGPlusIntentSend(url: String) { intended(allOf( hasAction(Intent.ACTION_VIEW), hasData(url) )) } fun checkMailIntentSend(address: String, title: String) { intended(chooser(allOf( hasAction(Intent.ACTION_SENDTO), hasExtra(Intent.EXTRA_SUBJECT, title), hasData("mailto:$address") ))) } private fun chooser(matcher: Matcher<Intent>): Matcher<Intent> { return allOf( hasAction(Intent.ACTION_CHOOSER), hasExtra(`is`(Intent.EXTRA_INTENT), matcher)) } }
app/src/androidTest/java/pl/srw/billcalculator/tester/AboutTester.kt
1375079106
// "Create local variable 'defaultPreferencesName'" "false" // ACTION: Create parameter 'defaultPreferencesName' // ACTION: Create property 'defaultPreferencesName' // ACTION: Enable a trailing comma by default in the formatter // ACTION: Rename reference // ERROR: Unresolved reference: defaultPreferencesName // ERROR: Default value of annotation parameter must be a compile-time constant class AppModule { val defaultPreferencesName = "defaultPreferences" annotation class Preferences(val type: String = <caret>defaultPreferencesName) }
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createVariable/localVariable/inAnnotation.kt
2394663550
// Copyright 2000-2022 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.storage import com.intellij.openapi.application.PathManager import java.io.File import java.io.FileFilter import java.nio.file.Files /** * If you want to implement some other type of logging this is a goto class to temporarily store data locally, until it * will be sent to log service. * * @baseFileName, files will be named ${baseFileName}_{intIndex} * @rootDirectoryPath, root directory where folder named @logsDirectory will be created and all files will be stored * @logsDirectoryName, name of directory in root directory which will be used to store files */ open class UniqueFilesProvider(private val baseFileName: String, private val rootDirectoryPath: String, private val logsDirectoryName: String, private val storageSizeLimit: Int = MAX_STORAGE_SEND_SIZE) : FilePathProvider { companion object { private const val MAX_STORAGE_SEND_SIZE = 30 * 1024 * 1024 fun extractChunkNumber(filename: String): Int? { return filename.substringAfter("_").substringBefore(".gz").toIntOrNull() } } override fun cleanupOldFiles() { val files = getDataFiles() val storageSize = files.fold(0L) { totalSize, file -> totalSize + file.length() } if (storageSize > storageSizeLimit) { var currentSize = storageSize val iterator = files.iterator() while (iterator.hasNext() && currentSize > storageSizeLimit) { val file = iterator.next() val fileSize = file.length() Files.delete(file.toPath()) currentSize -= fileSize } } } override fun getUniqueFile(): File { val dir = getStatsDataDirectory() val currentMaxIndex = listChunks().maxOfOrNull { it.number } val newIndex = if (currentMaxIndex != null) currentMaxIndex + 1 else 0 return File(dir, "${baseFileName}_$newIndex.gz") } override fun getDataFiles(): List<File> { return listChunks().map { it.file } } override fun getStatsDataDirectory(): File { val dir = File(rootDirectoryPath, logsDirectoryName) if (!dir.exists()) { dir.mkdirs() } return dir } private fun listChunks(): List<Chunk> { return getStatsDataDirectory().filesOnly().mapNotNull { it.asChunk() }.sortedBy { it.number }.toList() } private fun File.filesOnly(): Sequence<File> { val files: Array<out File>? = this.listFiles(FileFilter { it.isFile }) if (files == null) { val diagnostics = when { !exists() -> "file does not exist" !isDirectory -> "file is not a directory" isFile -> "file should be a directory but it is a file" else -> "unknown error" } throw Exception("Invalid directory path: ${this.relativeTo(File(PathManager.getSystemPath()))}. Info: $diagnostics") } return files.asSequence() } private fun File.asChunk(): Chunk? { if (!isFile) return null val filename = name if (!filename.startsWith(baseFileName)) return null val number = extractChunkNumber(filename) return if (number == null) null else Chunk(this, number) } private data class Chunk(val file: File, val number: Int) }
plugins/stats-collector/src/com/intellij/stats/completion/storage/UniqueFilesProvider.kt
430647075
// 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.tools.projectWizard.settings.buildsystem import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle import org.jetbrains.kotlin.tools.projectWizard.core.* import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.BuildSystemIR import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.DependencyType import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.GradleRootProjectDependencyIR import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.ModuleDependencyIR import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.GradleBinaryExpressionIR import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.GradleByClassTasksCreateIR import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.GradleConfigureTaskIR import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.irsList import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.* import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.isGradle import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ModulesToIrConversionData import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.GradlePrinter import org.jetbrains.kotlin.tools.projectWizard.plugins.projectPath import org.jetbrains.kotlin.tools.projectWizard.plugins.templates.TemplatesPlugin import org.jetbrains.kotlin.tools.projectWizard.templates.FileTemplate import org.jetbrains.kotlin.tools.projectWizard.templates.FileTemplateDescriptor import java.nio.file.Path import kotlin.reflect.KClass sealed class ModuleDependencyType( val from: KClass<out ModuleConfigurator>, val to: KClass<out ModuleConfigurator> ) { fun accepts(from: Module, to: Module) = this.from.isInstance(from.configurator) && this.to.isInstance(to.configurator) && additionalAcceptanceChecker(from, to) open fun additionalAcceptanceChecker(from: Module, to: Module) = true open fun createDependencyIrs(from: Module, to: Module, data: ModulesToIrConversionData): List<BuildSystemIR> { val path = to.path val modulePomIr = data.pomIr.copy(artifactId = to.name) return when { data.isSingleRootModuleMode && to.path.parts.singleOrNull() == data.rootModules.single().name && data.buildSystemType.isGradle -> GradleRootProjectDependencyIR(DependencyType.MAIN) else -> ModuleDependencyIR( path.considerSingleRootModuleMode(data.isSingleRootModuleMode), modulePomIr, DependencyType.MAIN ) }.asSingletonList() } open fun runArbitraryTask( writer: Writer, from: Module, to: Module, toModulePath: Path, data: ModulesToIrConversionData ): TaskResult<Unit> = UNIT_SUCCESS open fun Writer.runArbitraryTaskBeforeIRsCreated( from: Module, to: Module, ): TaskResult<Unit> = UNIT_SUCCESS open fun Reader.createToIRs(from: Module, to: Module, data: ModulesToIrConversionData): TaskResult<List<BuildSystemIR>> = Success(emptyList()) object JVMSinglePlatformToJVMSinglePlatform : ModuleDependencyType( from = JvmSinglePlatformModuleConfigurator::class, to = JvmSinglePlatformModuleConfigurator::class ) object AndroidSinglePlatformToMPP : ModuleDependencyType( from = AndroidSinglePlatformModuleConfigurator::class, to = MppModuleConfigurator::class ) object AndroidTargetToMPP : ModuleDependencyType( from = AndroidTargetConfiguratorBase::class, to = MppModuleConfigurator::class ) object JVMSinglePlatformToMPP : ModuleDependencyType( from = JvmSinglePlatformModuleConfigurator::class, to = MppModuleConfigurator::class ) object JVMTargetToMPP : ModuleDependencyType( from = JvmTargetConfigurator::class, to = MppModuleConfigurator::class ) { override fun additionalAcceptanceChecker(from: Module, to: Module): Boolean = from !in to.subModules } abstract class IOSSinglePlatformToMPPBase( from: KClass<out IOSSinglePlatformModuleConfiguratorBase> ) : ModuleDependencyType( from, MppModuleConfigurator::class ) { private fun Writer.updateReference(from: Module, to: Module) = inContextOfModuleConfigurator(from) { IOSSinglePlatformModuleConfigurator.dependentModule.reference.update { IOSSinglePlatformModuleConfiguratorBase.DependentModuleReference(to).asSuccess() } } override fun runArbitraryTask( writer: Writer, from: Module, to: Module, toModulePath: Path, data: ModulesToIrConversionData ): TaskResult<Unit> = writer.updateReference(from, to) override fun additionalAcceptanceChecker(from: Module, to: Module): Boolean = to.iosTargetSafe() != null protected fun Module.iosTargetSafe(): Module? = subModules.firstOrNull { module -> module.configurator.safeAs<NativeTargetConfigurator>()?.isIosTarget == true } } object IOSSinglePlatformToMPP : IOSSinglePlatformToMPPBase(IOSSinglePlatformModuleConfiguratorBase::class) object IOSWithXcodeSinglePlatformToMPP : IOSSinglePlatformToMPPBase( from = IOSSinglePlatformModuleConfigurator::class, ) { override fun createDependencyIrs(from: Module, to: Module, data: ModulesToIrConversionData): List<BuildSystemIR> = emptyList() override fun runArbitraryTask( writer: Writer, from: Module, to: Module, toModulePath: Path, data: ModulesToIrConversionData ): TaskResult<Unit> = compute { super.runArbitraryTask(writer, from, to, toModulePath, data).ensure() writer.addDummyFileIfNeeded(to, toModulePath) } private fun Writer.addDummyFileIfNeeded( to: Module, toModulePath: Path, ): TaskResult<Unit> { val needDummyFile = false/*TODO*/ return if (needDummyFile) { val dummyFilePath = Defaults.SRC_DIR / "${to.iosTargetSafe()!!.name}Main" / to.configurator.kotlinDirectoryName / "dummyFile.kt" TemplatesPlugin.addFileTemplate.execute( FileTemplate( FileTemplateDescriptor("ios/dummyFile.kt", dummyFilePath), projectPath / toModulePath ) ) } else UNIT_SUCCESS } @OptIn(ExperimentalStdlibApi::class) override fun Reader.createToIRs(from: Module, to: Module, data: ModulesToIrConversionData): TaskResult<List<BuildSystemIR>> { val iosTargetName = to.iosTargetSafe()?.name ?: return Failure( InvalidModuleDependencyError( from, to, KotlinNewProjectWizardBundle.message("error.text.module.0.should.contain.at.least.one.ios.target", to.name) ) ) return irsList { +GradleConfigureTaskIR(GradleByClassTasksCreateIR("packForXcode", "Sync")) { "group" assign const("build") "mode" createValue GradleBinaryExpressionIR( raw { +"System.getenv("; +"CONFIGURATION".quotified; +")" }, "?:", const("DEBUG") ) "sdkName" createValue GradleBinaryExpressionIR( raw { +"System.getenv("; +"SDK_NAME".quotified; +")" }, "?:", const("iphonesimulator") ) "targetName" createValue raw { +iosTargetName.quotified when (dsl) { GradlePrinter.GradleDsl.KOTLIN -> +""" + if (sdkName.startsWith("iphoneos")) "Arm64" else "X64"""" GradlePrinter.GradleDsl.GROOVY -> +""" + (sdkName.startsWith('iphoneos') ? 'Arm64' : 'X64')""" } } "framework" createValue raw { +"kotlin.targets" when (dsl) { GradlePrinter.GradleDsl.KOTLIN -> +""".getByName<KotlinNativeTarget>(targetName)""" GradlePrinter.GradleDsl.GROOVY -> +"""[targetName]""" } +".binaries.getFramework(mode)" } addRaw { +"inputs.property(${"mode".quotified}, mode)" } addRaw("dependsOn(framework.linkTask)") "targetDir" createValue new("File", raw("buildDir"), const("xcode-frameworks")) addRaw("from({ framework.outputDirectory })") addRaw("into(targetDir)") } addRaw { +"""tasks.getByName(${"build".quotified}).dependsOn(packForXcode)""" } import("org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget") }.asSuccess() } } companion object { private val ALL = listOf( JVMSinglePlatformToJVMSinglePlatform, JVMSinglePlatformToMPP, AndroidSinglePlatformToMPP, AndroidTargetToMPP, JVMTargetToMPP, IOSWithXcodeSinglePlatformToMPP, IOSSinglePlatformToMPP, ) fun getPossibleDependencyType(from: Module, to: Module): ModuleDependencyType? = ALL.firstOrNull { it.accepts(from, to) } fun isDependencyPossible(from: Module, to: Module): Boolean = getPossibleDependencyType(from, to) != null } }
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/settings/buildsystem/ModuleDependency.kt
338165985
// 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.core import com.intellij.codeInsight.JavaProjectCodeInsightSettings import com.intellij.openapi.project.Project import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.psi.KtFile private val exclusions = listOf( "kotlin.jvm.internal", "kotlin.coroutines.experimental.intrinsics", "kotlin.coroutines.intrinsics", "kotlin.coroutines.experimental.jvm.internal", "kotlin.coroutines.jvm.internal", "kotlin.reflect.jvm.internal" ) private fun shouldBeHiddenAsInternalImplementationDetail(fqName: String, locationFqName: String) = exclusions.any { fqName.startsWith(it) } && (locationFqName.isBlank() || !fqName.startsWith(locationFqName)) /** * We do not want to show nothing from "kotlin.coroutines.experimental" when release coroutines are available, * since in 1.3 this package is obsolete. * * However, we still want to show this package when release coroutines are not available. */ private fun usesOutdatedCoroutinesPackage(fqName: String, inFile: KtFile): Boolean = fqName.startsWith("kotlin.coroutines.experimental.") && inFile.languageVersionSettings.supportsFeature(LanguageFeature.ReleaseCoroutines) fun DeclarationDescriptor.isExcludedFromAutoImport(project: Project, inFile: KtFile?): Boolean { val fqName = importableFqName?.asString() ?: return false return JavaProjectCodeInsightSettings.getSettings(project).isExcluded(fqName) || (inFile != null && usesOutdatedCoroutinesPackage(fqName, inFile)) || shouldBeHiddenAsInternalImplementationDetail(fqName, inFile?.packageFqName?.asString() ?: "") }
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/excludedFromImportsAndCompletion.kt
4162942823
// WITH_STDLIB fun test(list: List<Int>) { list.filter { it > 1 }.filter { it > 2 } .let<caret> { println(it) } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/complexRedundantLet/callChain2.kt
3079087646
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.ComponentManager import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.SettingsSavingComponent import com.intellij.openapi.components.impl.stores.IProjectStore import com.intellij.openapi.components.stateStore import com.intellij.openapi.options.Scheme import com.intellij.openapi.options.SchemeManager import com.intellij.openapi.options.SchemeManagerFactory import com.intellij.openapi.options.SchemeProcessor import com.intellij.openapi.project.Project import com.intellij.util.SmartList import com.intellij.util.containers.ContainerUtil import com.intellij.util.lang.CompoundRuntimeException import org.jetbrains.annotations.TestOnly import java.nio.file.Path import java.nio.file.Paths const val ROOT_CONFIG = "\$ROOT_CONFIG$" sealed class SchemeManagerFactoryBase : SchemeManagerFactory(), SettingsSavingComponent { private val managers = ContainerUtil.createLockFreeCopyOnWriteList<SchemeManagerImpl<Scheme, Scheme>>() protected open val componentManager: ComponentManager? = null override final fun <T : Any, MutableT : T> create(directoryName: String, processor: SchemeProcessor<T, MutableT>, presentableName: String?, roamingType: RoamingType, schemeNameToFileName: SchemeNameToFileName, streamProvider: StreamProvider?, directoryPath: Path?, autoSave: Boolean): SchemeManager<T> { val path = checkPath(directoryName) val manager = SchemeManagerImpl(path, processor, streamProvider ?: (componentManager?.stateStore?.stateStorageManager as? StateStorageManagerImpl)?.compoundStreamProvider, directoryPath ?: pathToFile(path), roamingType, presentableName, schemeNameToFileName, componentManager?.messageBus) if (autoSave) { @Suppress("UNCHECKED_CAST") managers.add(manager as SchemeManagerImpl<Scheme, Scheme>) } return manager } override fun dispose(schemeManager: SchemeManager<*>) { managers.remove(schemeManager) } open fun checkPath(originalPath: String): String { fun error(message: String) { // as error because it is not a new requirement if (ApplicationManager.getApplication().isUnitTestMode) throw AssertionError(message) else LOG.error(message) } when { originalPath.contains('\\') -> error("Path must be system-independent, use forward slash instead of backslash") originalPath.isEmpty() -> error("Path must not be empty") } return originalPath } abstract fun pathToFile(path: String): Path fun process(processor: (SchemeManagerImpl<Scheme, Scheme>) -> Unit) { for (manager in managers) { try { processor(manager) } catch (e: Throwable) { LOG.error("Cannot reload settings for ${manager.javaClass.name}", e) } } } override final fun save() { val errors = SmartList<Throwable>() for (registeredManager in managers) { try { registeredManager.save(errors) } catch (e: Throwable) { errors.add(e) } } CompoundRuntimeException.throwIfNotEmpty(errors) } @Suppress("unused") private class ApplicationSchemeManagerFactory : SchemeManagerFactoryBase() { override val componentManager: ComponentManager get() = ApplicationManager.getApplication() override fun checkPath(originalPath: String): String { var path = super.checkPath(originalPath) if (path.startsWith(ROOT_CONFIG)) { path = path.substring(ROOT_CONFIG.length + 1) val message = "Path must not contains ROOT_CONFIG macro, corrected: $path" if (ApplicationManager.getApplication().isUnitTestMode) throw AssertionError(message) else LOG.warn(message) } return path } override fun pathToFile(path: String) = Paths.get(ApplicationManager.getApplication().stateStore.stateStorageManager.expandMacros(ROOT_CONFIG), path)!! } @Suppress("unused") private class ProjectSchemeManagerFactory(private val project: Project) : SchemeManagerFactoryBase() { override val componentManager = project override fun pathToFile(path: String): Path { val projectFileDir = (project.stateStore as? IProjectStore)?.projectConfigDir if (projectFileDir == null) { return Paths.get(project.basePath, ".$path") } else { return Paths.get(projectFileDir, path) } } } @TestOnly class TestSchemeManagerFactory(private val basePath: Path) : SchemeManagerFactoryBase() { override fun pathToFile(path: String) = basePath.resolve(path)!! } }
platform/configuration-store-impl/src/SchemeManagerFactoryImpl.kt
2930553532
// 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.ide.ui.components.dsl.panel import com.intellij.grazie.ide.ui.components.utils.configure import com.intellij.grazie.jlanguage.Lang import com.intellij.openapi.util.NlsSafe import com.intellij.ui.JBColor import com.intellij.ui.popup.list.ListPopupImpl import com.intellij.ui.popup.list.PopupListElementRenderer import com.intellij.util.ui.JBUI import java.awt.BorderLayout import java.awt.Color import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JList class GrazieLanguagesPopupElementRenderer(list: ListPopupImpl) : PopupListElementRenderer<Lang>(list) { private lateinit var mySizeLabel: JLabel override fun createItemComponent(): JComponent { createLabel() createSizeLabel() val panel = panel(BorderLayout()) { add(myTextLabel, BorderLayout.CENTER) add(mySizeLabel, BorderLayout.EAST) } return layoutComponent(panel) } override fun customizeComponent(list: JList<out Lang>, lang: Lang, isSelected: Boolean) { @NlsSafe val size = lang.remote.size.takeUnless { lang.isAvailable() } ?: "" mySizeLabel.configure { text = size foreground = myTextLabel.foreground.takeIf { isSelected } ?: Color.GRAY } } private fun createSizeLabel() { mySizeLabel = JLabel().configure { border = JBUI.Borders.emptyLeft(5) foreground = JBColor.GRAY } } }
plugins/grazie/src/main/kotlin/com/intellij/grazie/ide/ui/proofreading/component/list/GrazieLanguagesPopupElementRenderer.kt
2236490153
// 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 org.jetbrains.kotlin.psi.KtLabeledExpression import org.jetbrains.uast.UElement import org.jetbrains.uast.UIdentifier import org.jetbrains.uast.ULabeledExpression import org.jetbrains.uast.kotlin.declarations.KotlinUIdentifier class KotlinULabeledExpression( override val sourcePsi: KtLabeledExpression, givenParent: UElement? ) : KotlinAbstractUExpression(givenParent), ULabeledExpression { override val label: String get() = sourcePsi.getLabelName().orAnonymous("label") override val labelIdentifier: UIdentifier? get() = sourcePsi.getTargetLabel()?.let { KotlinUIdentifier(it, this) } override val expression by lz { KotlinConverter.convertOrEmpty(sourcePsi.baseExpression, this) } }
plugins/kotlin/uast/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinULabeledExpression.kt
3994784593
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.ui.toolwindow.create import com.intellij.collaboration.async.CompletableFutureUtil.submitIOTask import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import java.nio.file.Files import java.nio.file.Paths import java.util.concurrent.CompletableFuture object GHPRTemplateLoader { private val LOG = logger<GHPRTemplateLoader>() private val paths = listOf( ".github/pull_request_template.md", "pull_request_template.md", "docs/pull_request_template.md" ) fun readTemplate(project: Project): CompletableFuture<String?> { return ProgressManager.getInstance().submitIOTask(EmptyProgressIndicator()) { doLoad(project) } } @RequiresBackgroundThread private fun doLoad(project: Project): String? { val basePath = project.basePath ?: return null try { val files = paths.map { Paths.get(basePath, it) } val fileContent = files.find(Files::exists)?.let(Files::readString) if (fileContent != null) return fileContent } catch (e: Exception) { LOG.warn("Failed to read PR template", e) } return null } }
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/toolwindow/create/GHPRTemplateLoader.kt
2487592171
// WITH_STDLIB fun test(list: List<Int>): List<Int> { return if (list.isNotEmpty<caret>()) { list } else { listOf(1) } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceIsEmptyWithIfEmpty/list/isNotEmpty.kt
197475060
// 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.openapi.roots.ui.configuration import com.intellij.core.JavaPsiBundle import com.intellij.ide.JavaUiBundle import com.intellij.ide.wizard.getCanonicalPath import com.intellij.ide.wizard.getPresentablePath import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty import com.intellij.openapi.observable.properties.PropertyGraph import com.intellij.openapi.observable.properties.transform import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.JavaSdk import com.intellij.openapi.roots.impl.LanguageLevelProjectExtensionImpl import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectSdksModel import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.pom.java.LanguageLevel import com.intellij.project.isDirectoryBased import com.intellij.ui.dsl.builder.* import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.util.ui.JBUI import javax.swing.JPanel internal class ProjectConfigurableUi(private val myProjectConfigurable: ProjectConfigurable, private val myProject: Project) { private val propertyGraph = PropertyGraph() private val nameProperty = propertyGraph.graphProperty { myProject.name } private val compilerOutputProperty = propertyGraph.graphProperty { "" } var projectName by nameProperty var projectCompilerOutput by compilerOutputProperty private lateinit var myProjectJdkConfigurable: ProjectJdkConfigurable private lateinit var myLanguageLevelCombo: LanguageLevelCombo private lateinit var myPanel: JPanel fun initComponents(modulesConfigurator: ModulesConfigurator, model: ProjectSdksModel) { myProjectJdkConfigurable = ProjectJdkConfigurable(modulesConfigurator.projectStructureConfigurable, model) myLanguageLevelCombo = object : LanguageLevelCombo(JavaPsiBundle.message("default.language.level.description")) { override fun getDefaultLevel(): LanguageLevel? { val sdk = myProjectJdkConfigurable.selectedProjectJdk ?: return null val version = JavaSdk.getInstance().getVersion(sdk) return version?.maxLanguageLevel } } buildPanel() myProjectJdkConfigurable.addChangeListener { myLanguageLevelCombo.sdkUpdated(myProjectJdkConfigurable.selectedProjectJdk, myProject.isDefault) } myLanguageLevelCombo.addActionListener { LanguageLevelProjectExtensionImpl.getInstanceImpl(myProject).currentLevel = myLanguageLevelCombo.selectedLevel } } private fun buildPanel() { myPanel = headerlessPanel() } fun Panel.titleAndNameField() { if (myProject.isDirectoryBased) { row { label(JavaUiBundle.message("project.structure.title")) .bold() .comment(JavaUiBundle.message("project.structure.comment"), 120) } .bottomGap(BottomGap.SMALL) row(JavaUiBundle.message("project.structure.name")) { textField() .bindText(nameProperty) .columns(28) } .bottomGap(BottomGap.SMALL) } } fun headerlessPanel(): JPanel = panel { titleAndNameField() row(JavaUiBundle.message("project.structure.sdk")) { cell(myProjectJdkConfigurable.createComponent()) } .bottomGap(BottomGap.SMALL) row(JavaUiBundle.message("module.module.language.level")) { cell(myLanguageLevelCombo) cell() } .layout(RowLayout.PARENT_GRID) .bottomGap(BottomGap.SMALL) row(JavaUiBundle.message("project.structure.compiler.output")) { textFieldWithBrowseButton() .bindText(compilerOutputProperty.transform(::getPresentablePath, ::getCanonicalPath)) .onIsModified { if (!myProjectConfigurable.isFrozen) LanguageLevelProjectExtensionImpl.getInstanceImpl(myProject).currentLevel = myLanguageLevelCombo.selectedLevel return@onIsModified true } .horizontalAlign(HorizontalAlign.FILL) .comment(JavaUiBundle.message("project.structure.compiler.output.comment"), 100) cell() } .layout(RowLayout.PARENT_GRID) }.apply { withBorder(JBUI.Borders.empty(20, 20)) } fun getPanel(): JPanel = myPanel fun getLanguageLevel(): LanguageLevel? = myLanguageLevelCombo.selectedLevel fun isDefaultLanguageLevel(): Boolean = myLanguageLevelCombo.isDefault fun isProjectJdkConfigurableModified(): Boolean = myProjectJdkConfigurable.isModified fun applyProjectJdkConfigurable() = myProjectJdkConfigurable.apply() fun reloadJdk() { myProjectJdkConfigurable.createComponent() } fun disposeUIResources() { myProjectJdkConfigurable.disposeUIResources() } fun reset(compilerOutput: String?) { myProjectJdkConfigurable.reset() if (compilerOutput != null) { projectCompilerOutput = FileUtil.toSystemDependentName(VfsUtilCore.urlToPath(compilerOutput)) } myLanguageLevelCombo.reset(myProject) projectName = myProject.name } }
java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ProjectConfigurableUi.kt
3885754923
// 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.find.findUsages import com.intellij.ide.util.scopeChooser.ScopeIdMapper import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.EventPair import com.intellij.internal.statistic.eventLog.events.ObjectEventData import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.openapi.project.Project import com.intellij.usages.impl.UsageViewStatisticsCollector class FindUsagesStatisticsCollector : CounterUsagesCollector() { override fun getGroup(): EventLogGroup = GROUP companion object { @JvmField val GROUP = EventLogGroup("find.usages", 2) const val OPTIONS_EVENT_ID = "options" private val SEARCHABLE_SCOPE_EVENT_FIELD = EventFields.StringValidatedByCustomRule("searchScope", UsageViewStatisticsCollector.SCOPE_RULE_ID) private val SEARCH_FOR_TEXT_OCCURRENCES_FIELD = EventFields.Boolean("isSearchForTextOccurrences") private val IS_USAGES_FIELD = EventFields.Boolean("isUsages") private val ADDITIONAL = EventFields.createAdditionalDataField(GROUP.id, OPTIONS_EVENT_ID) private val OPEN_IN_NEW_TAB = EventFields.Boolean("openInNewTab") private val FIND_USAGES_OPTIONS = GROUP.registerVarargEvent(OPTIONS_EVENT_ID, SEARCH_FOR_TEXT_OCCURRENCES_FIELD, IS_USAGES_FIELD, OPEN_IN_NEW_TAB, SEARCHABLE_SCOPE_EVENT_FIELD, ADDITIONAL) @JvmStatic fun logOptions(project: Project, options: FindUsagesOptions, openInNewTab: Boolean) { val data: MutableList<EventPair<*>> = mutableListOf( SEARCH_FOR_TEXT_OCCURRENCES_FIELD.with(options.isSearchForTextOccurrences), IS_USAGES_FIELD.with(options.isUsages), OPEN_IN_NEW_TAB.with(openInNewTab), SEARCHABLE_SCOPE_EVENT_FIELD.with(ScopeIdMapper.instance.getScopeSerializationId(options.searchScope.displayName)), ) if (options is FusAwareFindUsagesOptions) { data.add(ADDITIONAL.with(ObjectEventData(options.additionalUsageData))) } FIND_USAGES_OPTIONS.log(project, *data.toTypedArray()) } } }
platform/lang-impl/src/com/intellij/find/findUsages/FindUsagesStatisticsCollector.kt
885791491
// WITH_STDLIB fun foo(<caret>`a`: Int) { }
plugins/kotlin/idea/tests/testData/inspectionsLocal/removeRedundantBackticks/functionArgument.kt
3989660400
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.groovy.codeInsight.template.postfix.templates import com.intellij.codeInsight.template.postfix.templates.PostfixTemplateProvider import com.intellij.codeInsight.template.postfix.templates.PostfixTemplateWithExpressionSelector import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import org.jetbrains.plugins.groovy.codeInsight.template.postfix.GroovyPostfixTemplateUtils import org.jetbrains.plugins.groovy.refactoring.introduce.variable.GrIntroduceVariableHandler class GrIntroduceVariablePostfixTemplate(sequence: String, provider: PostfixTemplateProvider) : PostfixTemplateWithExpressionSelector( "groovy.postfix.template.$sequence", sequence, "def name = expr", GroovyPostfixTemplateUtils.getExpressionSelector(), provider) { override fun expandForChooseExpression(expression: PsiElement, editor: Editor) { val handler = GrIntroduceVariableHandler() handler.invoke(expression.project, editor, expression.containingFile, null) } }
plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/template/postfix/templates/GrIntroduceVariablePostfixTemplate.kt
4039572681
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.expectactual import com.intellij.codeInsight.intention.IntentionAction import com.intellij.ide.util.MemberChooser import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.ui.showOkNoDialog import com.intellij.openapi.util.NlsSafe import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticFactory import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.project.implementedModules import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.overrideImplement.makeActual import org.jetbrains.kotlin.idea.core.overrideImplement.makeNotActual import org.jetbrains.kotlin.idea.core.toDescriptor import org.jetbrains.kotlin.idea.core.util.DescriptorMemberChooserObject import org.jetbrains.kotlin.idea.quickfix.KotlinIntentionActionsFactory import org.jetbrains.kotlin.idea.quickfix.TypeAccessibilityChecker import org.jetbrains.kotlin.idea.refactoring.getExpressionShortText import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.liftToExpected import org.jetbrains.kotlin.idea.util.module import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.psi.psiUtil.getSuperNames import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier import org.jetbrains.kotlin.utils.addToStdlib.safeAs sealed class CreateExpectedFix<D : KtNamedDeclaration>( declaration: D, targetExpectedClass: KtClassOrObject?, commonModule: Module, generateIt: KtPsiFactory.(Project, TypeAccessibilityChecker, D) -> D? ) : AbstractCreateDeclarationFix<D>(declaration, commonModule, generateIt) { private val targetExpectedClassPointer = targetExpectedClass?.createSmartPointer() override fun getText() = KotlinBundle.message("create.expected.0.in.common.module.1", elementType, module.name) final override fun invoke(project: Project, editor: Editor?, file: KtFile) { val targetExpectedClass = targetExpectedClassPointer?.element val expectedFile = targetExpectedClass?.containingKtFile ?: getOrCreateImplementationFile() ?: return doGenerate(project, editor, originalFile = file, targetFile = expectedFile, targetClass = targetExpectedClass) } override fun findExistingFileToCreateDeclaration( originalFile: KtFile, originalDeclaration: KtNamedDeclaration ): KtFile? { for (otherDeclaration in originalFile.declarations) { if (otherDeclaration === originalDeclaration) continue if (!otherDeclaration.hasActualModifier()) continue val expectedDeclaration = otherDeclaration.liftToExpected() ?: continue if (expectedDeclaration.module != module) continue return expectedDeclaration.containingKtFile } return null } companion object : KotlinIntentionActionsFactory() { override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> { val d = DiagnosticFactory.cast(diagnostic, Errors.ACTUAL_WITHOUT_EXPECT) val declaration = d.psiElement as? KtNamedDeclaration ?: return emptyList() val compatibility = d.b // For function we allow it, because overloads are possible if (compatibility.isNotEmpty() && declaration !is KtFunction) return emptyList() val (actualDeclaration, expectedContainingClass) = findFirstActualWithExpectedClass(declaration) if (compatibility.isNotEmpty() && actualDeclaration !is KtFunction) return emptyList() // If there is already an expected class, we suggest only for its module, // otherwise we suggest for all relevant expected modules val expectedModules = expectedContainingClass?.module?.let { listOf(it) } ?: actualDeclaration.module?.implementedModules ?: return emptyList() return when (actualDeclaration) { is KtClassOrObject -> expectedModules.map { CreateExpectedClassFix(actualDeclaration, expectedContainingClass, it) } is KtProperty, is KtParameter, is KtFunction -> expectedModules.map { CreateExpectedCallableMemberFix( actualDeclaration as KtCallableDeclaration, expectedContainingClass, it ) } else -> emptyList() } } } } private tailrec fun findFirstActualWithExpectedClass(declaration: KtNamedDeclaration): Pair<KtNamedDeclaration, KtClassOrObject?> { val containingClass = declaration.containingClassOrObject val expectedContainingClass = containingClass?.liftToExpected() as? KtClassOrObject return if (containingClass != null && expectedContainingClass == null) findFirstActualWithExpectedClass(containingClass) else declaration to expectedContainingClass } class CreateExpectedClassFix( klass: KtClassOrObject, outerExpectedClass: KtClassOrObject?, commonModule: Module ) : CreateExpectedFix<KtClassOrObject>(klass, outerExpectedClass, commonModule, block@{ project, checker, element -> val originalElements = element.collectDeclarationsForAddActualModifier(withSelf = false).toList() val existingClasses = checker.findAndApplyExistingClasses(originalElements + klass) if (!checker.isCorrectAndHaveAccessibleModifiers(element, true)) return@block null val (members, declarationsWithNonExistentClasses) = originalElements.partition { checker.isCorrectAndHaveAccessibleModifiers(it) } if (!showUnknownTypeInDeclarationDialog(project, declarationsWithNonExistentClasses)) return@block null val membersForSelection = members.filter { !it.isAlwaysActual() && if (it is KtParameter) it.hasValOrVar() else true } val selectedElements = when { membersForSelection.all(KtDeclaration::hasActualModifier) -> membersForSelection isUnitTestMode() -> membersForSelection.filter(KtDeclaration::hasActualModifier) else -> { val prefix = klass.fqName?.asString()?.plus(".") ?: "" chooseMembers(project, membersForSelection, prefix) ?: return@block null } }.asSequence().plus(klass).plus(members.filter(KtNamedDeclaration::isAlwaysActual)).flatMap(KtNamedDeclaration::selected).toSet() val selectedClasses = checker.findAndApplyExistingClasses(selectedElements) val resultDeclarations = if (selectedClasses != existingClasses) { if (!checker.isCorrectAndHaveAccessibleModifiers(element, true)) return@block null val (resultDeclarations, withErrors) = selectedElements.partition { checker.isCorrectAndHaveAccessibleModifiers(it) } if (!showUnknownTypeInDeclarationDialog(project, withErrors)) return@block null resultDeclarations } else selectedElements project.executeWriteCommand(KotlinBundle.message("repair.actual.members")) { repairActualModifiers(originalElements + klass, resultDeclarations.toSet()) } generateClassOrObject(project, true, element, checker) }) private fun showUnknownTypeInDeclarationDialog( project: Project, declarationsWithNonExistentClasses: Collection<KtNamedDeclaration> ): Boolean { if (declarationsWithNonExistentClasses.isEmpty()) return true @NlsSafe val message = escapeXml( declarationsWithNonExistentClasses.joinToString( prefix = "${KotlinBundle.message("these.declarations.cannot.be.transformed")}\n", separator = "\n", transform = ::getExpressionShortText ) ) TypeAccessibilityChecker.testLog?.append("$message\n") return isUnitTestMode() || showOkNoDialog( KotlinBundle.message("unknown.types.title"), message, project ) } private fun KtDeclaration.canAddActualModifier() = when (this) { is KtEnumEntry, is KtClassInitializer -> false is KtParameter -> hasValOrVar() else -> true } /*** * @return null if close without OK */ private fun chooseMembers(project: Project, collection: Collection<KtNamedDeclaration>, prefixToRemove: String): List<KtNamedDeclaration>? { val classMembers = collection.mapNotNull { it.resolveToDescriptorIfAny()?.let { descriptor -> Member(prefixToRemove, it, descriptor) } } val filter = if (collection.any(KtDeclaration::hasActualModifier)) { { declaration: KtDeclaration -> declaration.hasActualModifier() } } else { { true } } return MemberChooser( classMembers.toTypedArray(), true, true, project ).run { title = KotlinBundle.message("choose.actual.members.title") setCopyJavadocVisible(false) selectElements(classMembers.filter { filter((it.element as KtNamedDeclaration)) }.toTypedArray()) show() if (!isOK) null else selectedElements?.map { it.element as KtNamedDeclaration }.orEmpty() } } private class Member(val prefix: String, element: KtElement, descriptor: DeclarationDescriptor) : DescriptorMemberChooserObject(element, descriptor) { override fun getText(): String { val text = super.getText() return if (descriptor is ClassDescriptor) { @NlsSafe val p = prefix text.removePrefix(p) } else { text } } } fun KtClassOrObject.collectDeclarationsForAddActualModifier(withSelf: Boolean = true): Sequence<KtNamedDeclaration> { val thisSequence: Sequence<KtNamedDeclaration> = if (withSelf) sequenceOf(this) else emptySequence() val primaryConstructorSequence: Sequence<KtNamedDeclaration> = primaryConstructorParameters.asSequence() + primaryConstructor.let { if (it != null) sequenceOf(it) else emptySequence() } return thisSequence + primaryConstructorSequence + declarations.asSequence().flatMap { if (it.canAddActualModifier()) when (it) { is KtClassOrObject -> it.collectDeclarationsForAddActualModifier() is KtNamedDeclaration -> sequenceOf(it) else -> emptySequence() } else emptySequence() } } private fun repairActualModifiers( originalElements: Collection<KtNamedDeclaration>, selectedElements: Collection<KtNamedDeclaration> ) { if (originalElements.size == selectedElements.size) for (original in originalElements) { original.makeActualWithParents() } else for (original in originalElements) { if (original in selectedElements) original.makeActualWithParents() else original.makeNotActual() } } private tailrec fun KtDeclaration.makeActualWithParents() { makeActual() containingClassOrObject?.takeUnless(KtDeclaration::hasActualModifier)?.makeActualWithParents() } private fun KtNamedDeclaration.selected(): Sequence<KtNamedDeclaration> { val additionalSequence = safeAs<KtParameter>()?.parent?.parent?.safeAs<KtPrimaryConstructor>()?.let { sequenceOf(it) } ?: emptySequence() return sequenceOf(this) + additionalSequence + containingClassOrObject?.selected().orEmpty() } class CreateExpectedCallableMemberFix( declaration: KtCallableDeclaration, targetExpectedClass: KtClassOrObject?, commonModule: Module ) : CreateExpectedFix<KtNamedDeclaration>(declaration, targetExpectedClass, commonModule, block@{ project, checker, element -> if (!checker.isCorrectAndHaveAccessibleModifiers(element, true)) return@block null val descriptor = element.toDescriptor() as? CallableMemberDescriptor checker.existingTypeNames = targetExpectedClass?.getSuperNames()?.toSet().orEmpty() descriptor?.let { generateCallable( project, true, element, descriptor, targetExpectedClass, checker = checker ) } })
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/expectactual/CreateExpectedFix.kt
2343424578
// AFTER-WARNING: Variable 'rabbit' is never used fun main() { val rabbit = true || false && 3 == 1 + 2 ||<caret> false }
plugins/kotlin/idea/tests/testData/intentions/swapBinaryExpression/multipleOperandsWithDifferentPrecedence4.kt
959542806
// 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.findUsages import com.intellij.find.findUsages.* import com.intellij.openapi.project.Project import com.intellij.psi.* import org.jetbrains.kotlin.idea.findUsages.KotlinClassFindUsagesOptions import org.jetbrains.kotlin.idea.findUsages.KotlinFunctionFindUsagesOptions import org.jetbrains.kotlin.idea.findUsages.KotlinPropertyFindUsagesOptions import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.test.InTextDirectivesUtils internal enum class OptionsParser { CLASS { override fun parse(text: String, project: Project): FindUsagesOptions { return KotlinClassFindUsagesOptions(project).apply { isUsages = false isSearchForTextOccurrences = false searchConstructorUsages = false for (s in InTextDirectivesUtils.findListWithPrefixes(text, "// OPTIONS: ")) { if (parseCommonOptions(this, s)) continue when (s) { "constructorUsages" -> searchConstructorUsages = true "derivedInterfaces" -> isDerivedInterfaces = true "derivedClasses" -> isDerivedClasses = true "functionUsages" -> isMethodsUsages = true "propertyUsages" -> isFieldsUsages = true "expected" -> searchExpected = true else -> throw IllegalStateException("Invalid option: $s") } } } } }, FUNCTION { override fun parse(text: String, project: Project): FindUsagesOptions { return KotlinFunctionFindUsagesOptions(project).apply { isUsages = false for (s in InTextDirectivesUtils.findListWithPrefixes(text, "// OPTIONS: ")) { if (parseCommonOptions(this, s)) continue when (s) { "overrides" -> { isOverridingMethods = true isImplementingMethods = true } "overloadUsages" -> { isIncludeOverloadUsages = true isUsages = true } "expected" -> { searchExpected = true isUsages = true } else -> throw IllegalStateException("Invalid option: $s") } } } } }, PROPERTY { override fun parse(text: String, project: Project): FindUsagesOptions { return KotlinPropertyFindUsagesOptions(project).apply { isUsages = false for (s in InTextDirectivesUtils.findListWithPrefixes(text, "// OPTIONS: ")) { if (parseCommonOptions(this, s)) continue when (s) { "overrides" -> searchOverrides = true "skipRead" -> isReadAccess = false "skipWrite" -> isWriteAccess = false "expected" -> searchExpected = true else -> throw IllegalStateException("Invalid option: $s") } } } } }, JAVA_CLASS { override fun parse(text: String, project: Project): FindUsagesOptions { return KotlinClassFindUsagesOptions(project).apply { isUsages = false searchConstructorUsages = false for (s in InTextDirectivesUtils.findListWithPrefixes(text, "// OPTIONS: ")) { if (parseCommonOptions(this, s)) continue when (s) { "derivedInterfaces" -> isDerivedInterfaces = true "derivedClasses" -> isDerivedClasses = true "implementingClasses" -> isImplementingClasses = true "methodUsages" -> isMethodsUsages = true "fieldUsages" -> isFieldsUsages = true else -> throw IllegalStateException("Invalid option: $s") } } } } }, JAVA_METHOD { override fun parse(text: String, project: Project): FindUsagesOptions { return JavaMethodFindUsagesOptions(project).apply { isUsages = false for (s in InTextDirectivesUtils.findListWithPrefixes(text, "// OPTIONS: ")) { if (parseCommonOptions(this, s)) continue when (s) { "overrides" -> { isOverridingMethods = true isImplementingMethods = true } else -> throw IllegalStateException("Invalid option: $s") } } } } }, JAVA_FIELD { override fun parse(text: String, project: Project): FindUsagesOptions { return JavaVariableFindUsagesOptions(project).apply { for (s in InTextDirectivesUtils.findListWithPrefixes(text, "// OPTIONS: ")) { if (parseCommonOptions(this, s)) continue when (s) { "skipRead" -> isReadAccess = false "skipWrite" -> isWriteAccess = false else -> throw IllegalStateException("Invalid option: `$s`") } } } } }, JAVA_PACKAGE { override fun parse(text: String, project: Project): FindUsagesOptions { return JavaPackageFindUsagesOptions(project).apply { for (s in InTextDirectivesUtils.findListWithPrefixes(text, "// OPTIONS: ")) { if (parseCommonOptions(this, s)) continue throw IllegalStateException("Invalid option: `$s`") } } } }, DEFAULT { override fun parse(text: String, project: Project): FindUsagesOptions { return FindUsagesOptions(project).apply { for (s in InTextDirectivesUtils.findListWithPrefixes(text, "// OPTIONS: ")) { if (parseCommonOptions(this, s)) continue throw IllegalStateException("Invalid option: `$s`") } } } }; abstract fun parse(text: String, project: Project): FindUsagesOptions companion object { protected fun parseCommonOptions(options: JavaFindUsagesOptions, s: String): Boolean { if (parseCommonOptions(options as FindUsagesOptions, s)) { return true } return when (s) { "skipImports" -> { options.isSkipImportStatements = true true } else -> false } } protected fun parseCommonOptions(options: FindUsagesOptions, s: String): Boolean { return when (s) { "usages" -> { options.isUsages = true true } "textOccurrences" -> { options.isSearchForTextOccurrences = true true } else -> false } } fun getParserByPsiElementClass(klass: Class<out PsiElement>): OptionsParser? { return when (klass) { KtNamedFunction::class.java -> FUNCTION KtProperty::class.java, KtParameter::class.java -> PROPERTY KtClass::class.java -> CLASS PsiMethod::class.java -> JAVA_METHOD PsiClass::class.java -> JAVA_CLASS PsiField::class.java -> JAVA_FIELD PsiPackage::class.java -> JAVA_PACKAGE KtTypeParameter::class.java -> DEFAULT else -> null } } } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/findUsages/OptionsParser.kt
930448634
package org.krauser.micropost import android.content.Context import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.text.InputType import android.view.Window import android.view.inputmethod.EditorInfo import android.widget.EditText import android.widget.TextView import android.widget.Toast import butterknife.BindView import butterknife.ButterKnife import butterknife.OnEditorAction import butterknife.OnTextChanged private const val MAX_POST_TEXT_LENGTH: Int = 300 private const val POST_TEXT_STORE_NAME: String = "POST_TEXT_STORE" private const val AUTH_TOKEN_STORE_NAME: String = "AUTH_TOKEN_STORE" class CreatePostActivity : AppCompatActivity(), CreatePostPresenter.View { @BindView(R.id.post_input) lateinit internal var postInput: EditText @BindView(R.id.length_view) lateinit internal var lengthView: TextView @BindView(R.id.token_input) lateinit internal var tokenInput: EditText lateinit private var presenter: CreatePostPresenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) requestWindowFeature(Window.FEATURE_NO_TITLE) setContentView(R.layout.activity_micro_post) val authTokenStore = PersistedStore(AUTH_TOKEN_STORE_NAME, getPreferences(Context.MODE_PRIVATE)) val postTextStore = PersistedStore(POST_TEXT_STORE_NAME, getPreferences(Context.MODE_PRIVATE)) presenter = CreatePostPresenter(authTokenStore, postTextStore) ButterKnife.bind(this) presenter.onAttach(this) postInput.imeOptions = EditorInfo.IME_ACTION_SEND postInput.setRawInputType( InputType.TYPE_TEXT_FLAG_CAP_SENTENCES or InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE or InputType.TYPE_TEXT_FLAG_AUTO_CORRECT) } @OnEditorAction(R.id.post_input) internal fun onEditorAction(actionId: Int): Boolean { if (actionId == EditorInfo.IME_ACTION_SEND) { postInput.isEnabled = false presenter.onSendAction() return true } else { return false } } @OnTextChanged(R.id.post_input) internal fun onPostInputChanged(text: CharSequence) { presenter.onPostTextChange(text.toString()) } @OnTextChanged(R.id.token_input) internal fun onTokenInputChanged(text: CharSequence) { presenter.onAuthTokenChange(text.toString()) } override fun showSendError() { Toast.makeText(this, R.string.send_failure_message, Toast.LENGTH_SHORT).show() postInput.isEnabled = true } override fun showNoTokenError() { postInput.isEnabled = true } override fun showEmptyMessageError() { postInput.isEnabled = true } override fun showSendSuccess() { finish() } override fun showPostText(postText: String) { postInput.setText(postText) } override fun showPostTextLength(length: Int) { lengthView.text = "${MAX_POST_TEXT_LENGTH - length}" } override fun showAuthToken(authToken: String) { tokenInput.setText(authToken) if (authToken.isEmpty()) { tokenInput.requestFocus() } else { postInput.requestFocus() } } }
app/src/main/java/org/krauser/micropost/CreatePostActivity.kt
3789799441
package lib.threejs.Extra import lib.threejs.Geometry @native("THREE.BoxGeometry") class BoxGeometry( x: Double, y: Double, z: Double ) : Geometry() @native("THREE.SphereGeometry") class SphereGeometry( radius: Double = noImpl, widthSegments: Int = noImpl, heightSegments: Int = noImpl, phiStart: Double = noImpl, phiLength: Double = noImpl, thetaStart: Double = noImpl, thetaLength: Double = noImpl ) : Geometry() @native("THREE.ShapeGeometry") class ShapeGeometry( shapes: Array<Shape>, options: Any = noImpl ) : Geometry() { fun addShapeList(shapes: Array<Shape>, options: Any): Unit = noImpl fun addShape(shapes: Array<Shape>, options: Any): Unit = noImpl }
client/src/lib/threejs/Extra/Geometries.kt
2131021031
package sk.styk.martin.apkanalyzer.manager.appanalysis import android.content.pm.FeatureInfo import android.content.pm.PackageInfo import androidx.annotation.WorkerThread import sk.styk.martin.apkanalyzer.model.detail.FeatureData import java.util.* import javax.inject.Inject @WorkerThread class FeaturesManager @Inject constructor() { fun get(packageInfo: PackageInfo): List<FeatureData> { val featureInfos = packageInfo.reqFeatures ?: return ArrayList(0) return featureInfos.mapTo(ArrayList<FeatureData>(featureInfos.size)) { FeatureData( name = it.name ?: it.glEsVersion, isRequired = (it.flags and FeatureInfo.FLAG_REQUIRED) > 0 ) } } }
app/src/main/java/sk/styk/martin/apkanalyzer/manager/appanalysis/FeaturesManager.kt
3365670549
package xyz.nulldev.ts.api.v3.models.extensions enum class WExtensionStatus { INSTALLED, UNTRUSTED, AVAILABLE }
TachiServer/src/main/java/xyz/nulldev/ts/api/v3/models/extensions/WExtensionStatus.kt
4102207244
package ch.rmy.android.http_shortcuts.activities.editor.basicsettings import android.os.Bundle import androidx.core.view.isVisible import androidx.lifecycle.lifecycleScope import ch.rmy.android.framework.extensions.bindViewModel import ch.rmy.android.framework.extensions.collectEventsWhileActive import ch.rmy.android.framework.extensions.collectViewStateWhileActive import ch.rmy.android.framework.extensions.doOnTextChanged import ch.rmy.android.framework.extensions.initialize import ch.rmy.android.framework.ui.BaseIntentBuilder import ch.rmy.android.framework.viewmodel.ViewModelEvent import ch.rmy.android.http_shortcuts.R import ch.rmy.android.http_shortcuts.activities.BaseActivity import ch.rmy.android.http_shortcuts.activities.editor.basicsettings.models.InstalledBrowser import ch.rmy.android.http_shortcuts.dagger.ApplicationComponent import ch.rmy.android.http_shortcuts.data.models.ShortcutModel import ch.rmy.android.http_shortcuts.databinding.ActivityBasicRequestSettingsBinding import kotlinx.coroutines.launch class BasicRequestSettingsActivity : BaseActivity() { private val viewModel: BasicRequestSettingsViewModel by bindViewModel() private lateinit var binding: ActivityBasicRequestSettingsBinding private var installedBrowsers: List<InstalledBrowser> = emptyList() set(value) { if (field != value) { field = value binding.inputBrowserPackageName.setItemsFromPairs( listOf(DEFAULT_BROWSER_OPTION to getString(R.string.placeholder_browser_package_name)) + value.map { it.packageName to (it.appName ?: it.packageName) } ) } } override fun inject(applicationComponent: ApplicationComponent) { applicationComponent.inject(this) } override fun onCreated(savedState: Bundle?) { viewModel.initialize() initViews() initUserInputBindings() initViewModelBindings() } private fun initViews() { binding = applyBinding(ActivityBasicRequestSettingsBinding.inflate(layoutInflater)) setTitle(R.string.section_basic_request) binding.inputMethod.setItemsFromPairs( METHODS.map { it to it } ) } private fun initUserInputBindings() { lifecycleScope.launch { binding.inputMethod.selectionChanges.collect(viewModel::onMethodChanged) } binding.inputUrl.doOnTextChanged { viewModel.onUrlChanged(binding.inputUrl.rawString) } lifecycleScope.launch { binding.inputBrowserPackageName.selectionChanges.collect { viewModel.onBrowserPackageNameChanged(it.takeUnless { it == DEFAULT_BROWSER_OPTION } ?: "") } } binding.variableButtonUrl.setOnClickListener { viewModel.onUrlVariableButtonClicked() } } private fun initViewModelBindings() { collectViewStateWhileActive(viewModel) { viewState -> binding.inputMethod.isVisible = viewState.methodVisible binding.inputMethod.selectedItem = viewState.method binding.inputUrl.rawString = viewState.url installedBrowsers = viewState.browserPackageNameOptions binding.inputBrowserPackageName.selectedItem = viewState.browserPackageName binding.inputBrowserPackageName.isVisible = viewState.browserPackageNameVisible setDialogState(viewState.dialogState, viewModel) } collectEventsWhileActive(viewModel, ::handleEvent) } override fun handleEvent(event: ViewModelEvent) { when (event) { is BasicRequestSettingsEvent.InsertVariablePlaceholder -> { binding.inputUrl.insertVariablePlaceholder(event.variablePlaceholder) } else -> super.handleEvent(event) } } override fun onBackPressed() { viewModel.onBackPressed() } class IntentBuilder : BaseIntentBuilder(BasicRequestSettingsActivity::class) companion object { private val METHODS = listOf( ShortcutModel.METHOD_GET, ShortcutModel.METHOD_POST, ShortcutModel.METHOD_PUT, ShortcutModel.METHOD_DELETE, ShortcutModel.METHOD_PATCH, ShortcutModel.METHOD_HEAD, ShortcutModel.METHOD_OPTIONS, ShortcutModel.METHOD_TRACE, ) private const val DEFAULT_BROWSER_OPTION = "default" } }
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/editor/basicsettings/BasicRequestSettingsActivity.kt
2707741639
package org.maxur.mserv.frame.runner import org.maxur.mserv.frame.domain.Holder import org.maxur.mserv.frame.service.properties.PropertiesFactoryHoconImpl import org.maxur.mserv.frame.service.properties.PropertiesFactoryJsonImpl import org.maxur.mserv.frame.service.properties.PropertiesFactoryYamlImpl object Kotlin { fun runner(init: KRunner.() -> Unit) = KRunner(init) } class KRunner() : MicroServiceRunner() { var name: String = "Anonymous" set(value) { nameHolder = Holder.string(value) } constructor(init: KRunner.() -> Unit) : this() { init() } fun withoutProperties() { properties += PropertiesBuilder.NullPropertiesBuilder } fun file(init: PropertiesBuilder.BasePropertiesBuilder.() -> Unit) = PropertiesBuilder.BasePropertiesBuilder().apply { init() } fun service(init: ServiceBuilder.() -> Unit) = ServiceBuilder().apply { init() } fun rest(init: ServiceBuilder.() -> Unit) = ServiceBuilder().apply { type = "Grizzly" properties = ":webapp" init() } } fun hocon(init: PredefinedPropertiesBuilder.() -> Unit = {}) = object : PredefinedPropertiesBuilder("hocon", PropertiesFactoryHoconImpl(), init) {} fun json(init: PredefinedPropertiesBuilder.() -> Unit = {}) = object : PredefinedPropertiesBuilder("json", PropertiesFactoryJsonImpl(), init) {} fun yaml(init: PredefinedPropertiesBuilder.() -> Unit = {}) = object : PredefinedPropertiesBuilder("yaml", PropertiesFactoryYamlImpl(), init) {}
maxur-mserv-core/src/main/kotlin/org/maxur/mserv/frame/runner/Kotlin.kt
94722504
package {{ cookiecutter.package_name }}.di.scope import javax.inject.Scope import kotlin.annotation.Retention; @Scope @Retention(AnnotationRetention.RUNTIME) annotation class ActivityScope
{{cookiecutter.repo_name}}/app/src/main/kotlin/di/scope/ActivityScope.kt
3938513615
package com.github.h0tk3y.betterParse.benchmark import com.github.h0tk3y.betterParse.combinators.* import com.github.h0tk3y.betterParse.lexer.* import com.github.h0tk3y.betterParse.grammar.Grammar import com.github.h0tk3y.betterParse.parser.Parser class NaiveJsonGrammar : Grammar<Any?>() { @Suppress("unused") private val whiteSpace by regexToken("[\r|\n]|\\s+", ignore = true) /* the regex "[^\\"]*(\\["nrtbf\\][^\\"]*)*" matches: * " – opening double quote, * [^\\"]* – any number of not escaped characters, nor double quotes * ( * \\["nrtbf\\] – backslash followed by special character (\", \n, \r, \\, etc.) * [^\\"]* – and any number of non-special characters * )* – repeating as a group any number of times * " – closing double quote */ private val stringLiteral by regexToken("\"[^\\\\\"]*(\\\\[\"nrtbf\\\\][^\\\\\"]*)*\"") private val comma by regexToken(",") private val colon by regexToken(":") private val openingBrace by regexToken("\\{") private val closingBrace by regexToken("}") private val openingBracket by regexToken("\\[") private val closingBracket by regexToken("]") private val nullToken by regexToken("\\bnull\\b") private val trueToken by regexToken("\\btrue\\b") private val falseToken by regexToken("\\bfalse\\b") private val num by regexToken("-?[0-9]*(?:\\.[0-9]*)?") private val jsonNull: Parser<Any?> by nullToken asJust null private val jsonBool: Parser<Boolean> by (trueToken asJust true) or (falseToken asJust false) private val string: Parser<String> by (stringLiteral use { text.substring(1, text.lastIndex) }) private val number: Parser<Double> by num use { text.toDouble() } private val jsonPrimitiveValue: Parser<Any?> by jsonNull or jsonBool or string or number private val jsonObject: Parser<Map<String, Any?>> by (-openingBrace * separated(string * -colon * this, comma, true) * -closingBrace) .map { mutableMapOf<String, Any?>().apply { it.terms.forEach { put(it.t1, it.t2) } } } private val jsonArray: Parser<List<Any?>> by (-openingBracket * separated(this, comma, true) * -closingBracket) .map { it.terms } override val rootParser by jsonPrimitiveValue or jsonObject or jsonArray }
benchmarks/src/commonMain/kotlin/NaiveJsonGrammar.kt
1216506696
package com.github.kerubistan.kerub.planner.steps.storage.lvm.duplicate import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonTypeName import com.github.kerubistan.kerub.model.Host import com.github.kerubistan.kerub.model.LvmStorageCapability import com.github.kerubistan.kerub.model.StorageCapability import com.github.kerubistan.kerub.model.VirtualStorageDevice import com.github.kerubistan.kerub.model.dynamic.VirtualStorageBlockDeviceAllocation import com.github.kerubistan.kerub.model.dynamic.VirtualStorageLvmAllocation import com.github.kerubistan.kerub.planner.steps.storage.block.duplicate.AbstractBlockDuplicate @JsonTypeName("duplicate-to-lvm") data class DuplicateToLvm( override val virtualStorageDevice: VirtualStorageDevice, override val source: VirtualStorageBlockDeviceAllocation, override val sourceHost: Host, override val target: VirtualStorageLvmAllocation, override val targetHost: Host) : AbstractBlockDuplicate<VirtualStorageLvmAllocation>() { @get:JsonIgnore override val targetCapability: StorageCapability get() = requireNotNull(targetHost.capabilities).storageCapabilities .single { it is LvmStorageCapability && target.vgName == it.volumeGroupName } }
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/lvm/duplicate/DuplicateToLvm.kt
3860316939
package basic fun main(args: Array<String>) { var x = 1 println("for simples") for (x in 1..10) { println(x) } println("for down") for (x in 10 downTo 1) { println(x) } println("for step") for (x in 10 downTo 1 step 2) { println(x) } println("while simples") x = 1 while (x < 5) { println(x) x++ } }
Curso Dev Kotlin/src/loop.kt
3031618784
package com.cout970.modelloader.api import net.minecraft.client.renderer.model.IBakedModel import net.minecraft.client.renderer.model.IUnbakedModel import net.minecraft.client.renderer.model.ModelResourceLocation import net.minecraft.client.renderer.model.ModelRotation import net.minecraft.util.Direction import net.minecraft.util.ResourceLocation /** * Configuration that tells the library how to load a model. */ data class ModelConfig @JvmOverloads constructor( val location: ResourceLocation, val itemTransforms: ItemTransforms = ItemTransforms.DEFAULT, val rotation: ModelRotation = ModelRotation.X0_Y0, val bake: Boolean = true, val animate: Boolean = false, val mutable: Boolean = false, val itemRenderer: Boolean = false, val preBake: ((ModelResourceLocation, IUnbakedModel) -> IUnbakedModel)? = null, val postBake: ((ModelResourceLocation, IBakedModel) -> IBakedModel)? = null, val partFilter: ((String)-> Boolean)? = null ) { /** * Marks the location where the model file is stored */ fun withLocation(location: ResourceLocation) = copy(location = location) /** * Marks the transformations to apply in several item views */ fun withItemTransforms(itemTransforms: ItemTransforms) = copy(itemTransforms = itemTransforms) /** * Marks a rotation to apply to the model before baking */ fun withRotation(rotation: ModelRotation) = copy(rotation = rotation) /** * Marks a rotation using a Direction component */ fun withDirection(dir: Direction) = copy(rotation = DIRECTION_TO_ROTATION.getValue(dir)) /** * Indicates that this model must be baked, this allow the model to be used for an item or a blockstate */ fun withBake(bake: Boolean) = copy(bake = bake) /** * Indicates that this model must be analyzed to create animated models */ fun withAnimation(animate: Boolean) = copy(animate = animate) /** * Indicates that this model should be processed to generate a [MutableModel] */ fun withMutable(mutable: Boolean) = copy(mutable = mutable) /** * Marks the generated bakedmodel so Minecraft knows that the item with that model needs to use an ItemRenderer */ fun withItemRenderer(itemRenderer: Boolean) = copy(itemRenderer = itemRenderer) /** * Binds a callback that will receive the model after is gets loaded * * You must return a new model instead of editing the argument, * because models are loaded only once and shared for several ModelConfigs registrations */ fun withPreBake(preBake: ((ModelResourceLocation, IUnbakedModel) -> IUnbakedModel)?) = copy(preBake = preBake) /** * Binds a callback that will receive the model after is gets baked * * You can return the same model with changes or return a different instance, for example, wrapping the model */ fun withPostBake(postBake: ((ModelResourceLocation, IBakedModel) -> IBakedModel)?) = copy(postBake = postBake) /** * Binds a callback that filters which parts to keep in the model */ fun withPartFilter(partFilter: ((String)-> Boolean)?) = copy(partFilter = partFilter) /** * Combines withDirection and withRotation, allowing to use a direction for rotation * and apply an extra rotation over it */ fun withDirection(dir: Direction, rot: ModelRotation): ModelConfig { return withRotation(DIRECTION_TO_ROTATION.getValue(dir) + rot) } companion object { /** * Rotations per direction */ @JvmField val DIRECTION_TO_ROTATION = mapOf( Direction.DOWN to ModelRotation.X0_Y0, Direction.UP to ModelRotation.X180_Y0, Direction.NORTH to ModelRotation.X90_Y0, Direction.SOUTH to ModelRotation.X270_Y0, Direction.WEST to ModelRotation.X270_Y270, Direction.EAST to ModelRotation.X270_Y90 ) /** * Adds 2 rotations together */ operator fun ModelRotation.plus(other: ModelRotation): ModelRotation { val x = this.getX() + other.getX() val y = this.getY() + other.getY() return ModelRotation.getModelRotation(x, y) } /** * Gets the X component of a rotation */ fun ModelRotation.getX() = when (this) { ModelRotation.X0_Y0 -> 0 ModelRotation.X0_Y90 -> 0 ModelRotation.X0_Y180 -> 0 ModelRotation.X0_Y270 -> 0 ModelRotation.X90_Y0 -> 90 ModelRotation.X90_Y90 -> 90 ModelRotation.X90_Y180 -> 90 ModelRotation.X90_Y270 -> 90 ModelRotation.X180_Y0 -> 180 ModelRotation.X180_Y90 -> 180 ModelRotation.X180_Y180 -> 180 ModelRotation.X180_Y270 -> 180 ModelRotation.X270_Y0 -> 270 ModelRotation.X270_Y90 -> 270 ModelRotation.X270_Y180 -> 270 ModelRotation.X270_Y270 -> 270 } /** * Gets the Y component of a rotation */ fun ModelRotation.getY() = when (this) { ModelRotation.X0_Y0 -> 0 ModelRotation.X0_Y90 -> 90 ModelRotation.X0_Y180 -> 180 ModelRotation.X0_Y270 -> 270 ModelRotation.X90_Y0 -> 0 ModelRotation.X90_Y90 -> 90 ModelRotation.X90_Y180 -> 180 ModelRotation.X90_Y270 -> 270 ModelRotation.X180_Y0 -> 0 ModelRotation.X180_Y90 -> 90 ModelRotation.X180_Y180 -> 180 ModelRotation.X180_Y270 -> 270 ModelRotation.X270_Y0 -> 0 ModelRotation.X270_Y90 -> 90 ModelRotation.X270_Y180 -> 180 ModelRotation.X270_Y270 -> 270 } } }
src/main/kotlin/com/cout970/modelloader/api/ModelConfig.kt
1514773412