content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
fun foo(x: Any) { if (x is String) { System.getProperty("abc".substring(<selection>1</selection>)) println() } else { println() } }
plugins/kotlin/idea/tests/testData/resolve/partialBodyResolve/IntConstantTypeBug.kt
1242014650
// !SPECIFY_LOCAL_VARIABLE_TYPE_BY_DEFAULT: true fun foo() { val i = 1 val s = "" }
plugins/kotlin/j2k/new/tests/testData/newJ2k/settings/specifyLocalVariableTypeByDefault.kt
283864375
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diagnostic.report enum class MemoryReportReason { None, UserInvoked, InternalUserInvoked, FrequentLowMemoryNotification, LowMemory, OutOfMemory; fun isUserInvoked(): Boolean { return this == UserInvoked || this == InternalUserInvoked } }
platform/platform-impl/src/com/intellij/diagnostic/report/MemoryReportReason.kt
1457235148
// WITH_STDLIB fun test(s: String) { println(1) kotlin.<caret>checkNotNull(s) println(2) }
plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantRequireNotNullCall/checkNotNull.kt
1215669158
// 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.internal.ui.uiDslShowcase import com.intellij.ide.BrowserUtil import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.project.rootManager import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.ui.DialogWrapper import com.intellij.ui.components.JBTabbedPane import com.intellij.ui.dsl.builder.BottomGap import com.intellij.ui.dsl.builder.panel import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.ui.dsl.gridLayout.VerticalAlign import com.intellij.util.ui.JBEmptyBorder import java.awt.Dimension import javax.swing.JComponent import kotlin.reflect.KFunction import kotlin.reflect.full.findAnnotation import kotlin.reflect.jvm.javaMethod const val BASE_URL = "https://github.com/JetBrains/intellij-community/blob/master/platform/platform-impl/" val DEMOS = arrayOf( ::demoBasics, ::demoRowLayout, ::demoComponentLabels, ::demoComments, ::demoComponents, ::demoGaps, ::demoGroups, ::demoAvailability, ::demoBinding, ::demoTips ) internal class UiDslShowcaseAction : DumbAwareAction() { override fun getActionUpdateThread() = ActionUpdateThread.BGT override fun actionPerformed(e: AnActionEvent) { UiDslShowcaseDialog(e.project, templatePresentation.text).show() } } private class UiDslShowcaseDialog(val project: Project?, dialogTitle: String) : DialogWrapper(project, null, true, IdeModalityType.MODELESS, false) { init { title = dialogTitle init() } override fun createCenterPanel(): JComponent { val result = JBTabbedPane() result.minimumSize = Dimension(400, 300) result.preferredSize = Dimension(800, 600) for (demo in DEMOS) { addDemo(demo, result) } return result } private fun addDemo(demo: KFunction<DialogPanel>, tabbedPane: JBTabbedPane) { val annotation = demo.findAnnotation<Demo>() if (annotation == null) { throw Exception("Demo annotation is missed for ${demo.name}") } val content = panel { row { label("<html>Description: ${annotation.description}") } val simpleName = "src/${demo.javaMethod!!.declaringClass.name}".replace('.', '/') val fileName = (simpleName.substring(0..simpleName.length - 3) + ".kt") row { link("View source") { if (!openInIdeaProject(fileName)) { BrowserUtil.browse(BASE_URL + fileName) } } }.bottomGap(BottomGap.MEDIUM) val args = demo.parameters.associateBy( { it }, { when (it.name) { "parentDisposable" -> myDisposable else -> null } } ) val dialogPanel = demo.callBy(args) if (annotation.scrollbar) { row { dialogPanel.border = JBEmptyBorder(10) scrollCell(dialogPanel) .horizontalAlign(HorizontalAlign.FILL) .verticalAlign(VerticalAlign.FILL) .resizableColumn() }.resizableRow() } else { row { cell(dialogPanel) .horizontalAlign(HorizontalAlign.FILL) .resizableColumn() } } } tabbedPane.add(annotation.title, content) } private fun openInIdeaProject(fileName: String): Boolean { if (project == null) { return false } val moduleManager = ModuleManager.getInstance(project) val module = moduleManager.findModuleByName("intellij.platform.ide.impl") if (module == null) { return false } for (contentRoot in module.rootManager.contentRoots) { val file = contentRoot.findFileByRelativePath(fileName) if (file?.isValid == true) { OpenFileDescriptor(project, file).navigate(true) return true } } return false } }
platform/platform-impl/src/com/intellij/internal/ui/uiDslShowcase/UiDslShowcaseAction.kt
3892060230
package pl.elpassion.elspace.hub.report.list.service import pl.elpassion.elspace.hub.project.Project import io.reactivex.Observable interface ProjectListService { fun getProjects(): Observable<List<Project>> }
el-space-app/src/main/java/pl/elpassion/elspace/hub/report/list/service/ProjectListService.kt
136977955
package org.amshove.kluent.tests.assertions.bigdecimal import org.amshove.kluent.shouldBeNear import java.math.BigDecimal import kotlin.test.Test import kotlin.test.assertFails class BigDecimalShouldBeNearShould { @Test fun passWhenTestingAValueWhichIsWithinTheDelta() { BigDecimal("5.55").shouldBeNear(BigDecimal("5.5"), BigDecimal("0.1")) } @Test fun passWhenTestingAValueWhichIsTheUpperBound() { BigDecimal("5.6").shouldBeNear(BigDecimal("5.5"), BigDecimal("0.1")) } @Test fun passWhenTestingAValueWhichIsTheLowerBound() { BigDecimal("5.5").shouldBeNear(BigDecimal("5.5"), BigDecimal("0.1")) } @Test fun failWhenTestingAValueWhichIsAboveTheBound() { assertFails { BigDecimal("5.7").shouldBeNear(BigDecimal("5.5"), BigDecimal("0.1")) } } @Test fun failWhenTestingAValueWhichIsBelowTheBound() { assertFails { BigDecimal("5.3").shouldBeNear(BigDecimal("5.5"), BigDecimal("0.1")) } } }
jvm/src/test/kotlin/org/amshove/kluent/tests/assertions/bigdecimal/BigDecimalShouldBeNearShould.kt
1333908941
package simyukkuri.gameobject.yukkuri.statistic import messageutil.Condition import simyukkuri.gameobject.yukkuri.event.IndividualEvent import simyukkuri.gameobject.yukkuri.statistic.statistics.* /** ゆっくりのステータスのインターフェース */ interface YukkuriStats : Attribute, Damage, Emotion, Family, Fullness, Growth, Message, MiscStat, Movement, Poo, Pregnancy, Sleep, Sukkiri, Yukabi { val msgList: MessagePicker val messageCondition: Condition var event: IndividualEvent override fun update() }
subprojects/simyukkuri/src/main/kotlin/simyukkuri/gameobject/yukkuri/statistic/YukkuriStats.kt
3375705755
package shitarabatogit import messageutil.* import java.io.InputStream import java.nio.file.Files import java.nio.file.Path /** * したらば版形式のメッセージを読み込み, アクション名 -> (コメント, ゆっくりタイプ) -> セリフリスト) の形式のマップを返す. * * "<"と">"はセットになっていることを前提とする. * * @param strict falseのときタグの閉じ忘れや閉じすぎを無視する. */ fun parseShitarabaMessage(path: Path, strict: Boolean = true): CommentedMessageCollection = Files.newInputStream(path).use { parseShitarabaMessage(it, strict) } /** * したらば版形式のメッセージを読み込み, アクション名 -> (コメント, ゆっくりタイプ -> (コメント, セリフリスト)) の形式のマップを返す. * * @param strict falseのときタグの閉じ忘れや閉じすぎを無視する. */ fun parseShitarabaMessage(input: InputStream, strict: Boolean = true): CommentedMessageCollection { val msgData = mutableCommentedMessageCollection() // 現在の行における状態 var lineNumber = 0 var actionName = "" val comments = mutableListOf<String>() var cond = emptyCondition input.bufferedReader().forEachLine { lineNumber += 1 val line = it.trim { it <= ' ' } if (line.isEmpty()) return@forEachLine val first = line[0] if (first == '#') { comments.add(line.substring(1)) return@forEachLine } // アクション if (first == '[') { // 閉じタグの場合 if (line[1] == '/') { if (actionName.isEmpty()) { if (strict) throw RuntimeException("対応する開始タグがありません at $lineNumber") else { val openPos = 2 val closePos = line.indexOf(']') actionName = line.substring(openPos, closePos) } } msgData.getOrPut(actionName) { MutableCommented(linkedMapOf()) }.commentLines.addAll(comments) comments.clear() actionName = "" if (cond != emptyCondition) if (strict) throw RuntimeException("閉じられていない属性があります at $lineNumber: ${cond.toSimpleString()}") cond = emptyCondition return@forEachLine } // 開始タグの場合 else { if (actionName.isNotEmpty()) throw RuntimeException("閉じられていないアクションがあります at $lineNumber: $actionName") val openPos = 1 val closePos = line.indexOf(']') actionName = line.substring(openPos, closePos) return@forEachLine } } // タイプ else if (first == '<') { // 閉じタグの場合 if (line[1] == '/') { val openPos = 2 val closePos = line.indexOf('>') val attr = line.substring(openPos, closePos) if (!cond.contains(attr)) if (strict) throw Exception("対応する開始タグがありません at $lineNumber: $attr") cond = cond.removed(attr) return@forEachLine } // 開始タグの場合 else { val openPos = 1 val closePos = line.indexOf('>') val attr = line.substring(openPos, closePos) cond = cond.added(attr) return@forEachLine } } // メッセージ本文 else { msgData.getOrPut(actionName) { MutableCommented(linkedMapOf()) } .body.getOrPut(cond) { mutableListOf<String>() } .add(line) } } if (actionName.isNotEmpty()) throw RuntimeException("閉じられていないアクションがあります at $lineNumber: $actionName") return msgData }
subprojects/messageutil/src/main/kotlin/shitarabatogit/ParseMessage.kt
3432306855
package io.looki.redditlive import com.google.gson.Gson import com.google.gson.internal.LinkedTreeMap import com.google.gson.reflect.TypeToken import io.reactivex.ObservableEmitter import io.reactivex.ObservableOnSubscribe import okhttp3.* class LiveMessageObservable(private val gson: Gson, okHttpClient: OkHttpClient, websocketUrl: String) : ObservableOnSubscribe<LiveMessage<LiveMessage.GenericPayload>>, WebSocketListener() { private val emitterList = mutableListOf<ObservableEmitter<LiveMessage<LiveMessage.GenericPayload>>>() private val request = Request.Builder().url(websocketUrl).build() init { okHttpClient.newWebSocket(request, this) } override fun subscribe(observableEmitter: ObservableEmitter<LiveMessage<LiveMessage.GenericPayload>>) { emitterList += observableEmitter } override fun onOpen(webSocket: WebSocket, response: Response) { println("Opened Websocket") } override fun onMessage(webSocket: WebSocket, text: String) { //Get the payload from the sent data to find out what kind of message we received val rawMessage = gson.fromJson<LiveMessage<Any>>(text) //Check if content of Payload is String or Object (String means Delete or Strike Event) val messageContent = when (rawMessage.payload) { //If Object it should be a LinkedTreeMap. In this case find the Event in the LiveEvent.PayloadType enum and parse the JSON to the corresponding POJO schema is LinkedTreeMap<*,*> -> gson.fromJson(gson.toJsonTree(rawMessage.payload), rawMessage.type.payload) is String -> rawMessage.type.payload.getDeclaredConstructor(String::class.java).newInstance(rawMessage.payload) else -> throw Exception("Corrupt Payload") } //Create a new LiveMessage POJO with the correct child type val processedMessage = LiveMessage(rawMessage.type, messageContent) emitterList.forEach { it.onNext(processedMessage) } } override fun onClosing(webSocket: WebSocket, code: Int, reason: String) { emitterList.forEach { it.onComplete() } println("Closing Websocket ($code: $reason)") } override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { emitterList.forEach { it.onError(t) } println("Websocket Error") t.printStackTrace() } private inline fun <reified T> Gson.fromJson(json: String) = this.fromJson<T>(json, object: TypeToken<T>() {}.type) }
src/main/java/io/looki/redditlive/LiveMessageObservable.kt
1294327750
package com.github.nukc.recycleradapter @Suppress("UNCHECKED_CAST") fun <T : Any> getItemType(item: T): Class<T> { if (item is Collection<*>) { for (v in item.iterator()) { if (v != null) { return getItemType(v as T) } } } return item.javaClass }
recycleradapter/src/main/java/com/github/nukc/recycleradapter/Steal.kt
2673264528
import org.junit.Assert import org.junit.Test import koans.util.inEquals class TestExtensionFunctionLiterals { @Test fun testIsOddAndIsEven() { Assert.assertEquals("The functions 'isOdd' and 'isEven' should be implemented correctly".inEquals(), listOf(false, true, true), task()) } }
lesson5/task1/src/tests.kt
3898185132
package xyz.sachil.essence.model.cache.dao import androidx.paging.DataSource import androidx.room.* import xyz.sachil.essence.model.net.bean.TypeData import xyz.sachil.essence.util.Utils @Dao interface TypeDataDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertTypeData(typeDataList: List<TypeData>) @Query("SELECT * FROM type_data_table WHERE category=:category AND type=:type ORDER BY published_date DESC ") fun getTypeData(category: String, type: String): DataSource.Factory<Int, TypeData> @Update(onConflict = OnConflictStrategy.REPLACE) fun updateTypeData(vararg typeData: TypeData) @Query("SELECT COUNT(id) FROM type_data_table WHERE category=:category AND type=:type") fun getCount(category: String, type: String): Int @Delete fun deleteTypeData(vararg typeData: TypeData) @Query("DELETE FROM type_data_table WHERE category=:category AND type=:type") fun deleteTypeData(category: String, type: String) @Query("DELETE FROM type_data_table") fun deleteAllData() }
app/src/main/java/xyz/sachil/essence/model/cache/dao/TypeDataDao.kt
697631117
package backend.Integration import backend.model.misc.Coord import backend.model.user.Participant import backend.services.ConfigurationService import com.fasterxml.jackson.databind.ObjectMapper import org.junit.Before import org.junit.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.MediaType import org.springframework.test.web.servlet.request.MockMvcRequestBuilders import org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status import java.time.LocalDate import java.time.LocalDateTime import kotlin.test.assertEquals import kotlin.test.assertNotNull class TestUserEndpoint : IntegrationTest() { @Autowired lateinit var configurationService: ConfigurationService lateinit var JWT_SECRET: String private fun url(): String = "/user/" private fun url(id: Int): String = "/user/$id/" @Before override fun setUp() { super.setUp() this.JWT_SECRET = configurationService.getRequired("org.breakout.api.jwt_secret") } /** * GET /user/ */ @Test fun getUser() { userService.create("[email protected]", "password", { firstname = "Florian" lastname = "Schmidt" gender = "Male" }) userService.create("[email protected]", "password", { firstname = "Leo" lastname = "Theo" gender = "Male" }) mockMvc.perform(get("/user/")) .andExpect(status().isOk) .andExpect(jsonPath("$").isArray) .andExpect(jsonPath("$[0].id").exists()) .andExpect(jsonPath("$[0].firstname").exists()) .andExpect(jsonPath("$[0].lastname").exists()) .andExpect(jsonPath("$[0].email").doesNotExist()) .andExpect(jsonPath("$[0].gender").exists()) .andExpect(jsonPath("$[0].passwordHash").doesNotExist()) .andExpect(jsonPath("$[1].id").exists()) .andExpect(jsonPath("$[1].firstname").exists()) .andExpect(jsonPath("$[1].lastname").exists()) .andExpect(jsonPath("$[1].email").doesNotExist()) .andExpect(jsonPath("$[1].gender").exists()) .andExpect(jsonPath("$[1].passwordHash").doesNotExist()) } @Test fun getAuthenticatedUser() { val credentials = createUser(this.mockMvc, userService = userService) val request = MockMvcRequestBuilders.get("/me/") .header("Authorization", "Bearer ${credentials.accessToken}") mockMvc.perform(request) .andExpect(status().isOk) .andExpect(jsonPath("$.id").exists()) .andExpect(jsonPath("$.email").exists()) } @Test fun getAuthenticatedUserInvites() { val credentials = createUser(this.mockMvc, userService = userService) val request = MockMvcRequestBuilders.get("/me/invitation/") .header("Authorization", "Bearer ${credentials.accessToken}") val response = mockMvc.perform(request) .andExpect(status().isOk) .andExpect(jsonPath("$").isArray) .andReturn().response.contentAsString println(response) } /** * POST /user/ * Create user with email and password */ @Test fun postUser() { val json = mapOf( "email" to "[email protected]", "password" to "password", "profilePic" to mapOf("type" to "image", "url" to "url") ).toJsonString() val response = mockMvc.perform(post(url(), json)) .andExpect(status().isCreated) .andExpect(jsonPath("$.id").exists()) .andExpect(jsonPath("$.profilePic.type").exists()) .andExpect(jsonPath("$.profilePic.id").exists()) .andExpect(jsonPath("$.profilePic.url").exists()) .andExpect(jsonPath("$.profilePic.type").value("IMAGE")) .andReturn().response.contentAsString print(response) val user = userRepository.findByEmail("[email protected]") assertNotNull(user) assertEquals(user.email, "[email protected]") } /** * POST /user/ * Reject invalid email */ @Test fun postUserRejectInvalidEmail() { val json = mapOf( "email" to "asd.de", "password" to "password" ).toJsonString() mockMvc.perform(post(url(), json)) .andExpect(status().isBadRequest) .andExpect(jsonPath("$.timestamp").exists()) .andExpect(jsonPath("$.message").exists()) } /** * POST /user/ * Reject existing email */ @Test fun postUserRejectExistingEmail() { val json = mapOf( "email" to "[email protected]", "password" to "password" ).toJsonString() mockMvc.perform(post(url(), json)) .andExpect(status().isCreated) .andExpect(jsonPath("$.id").exists()) mockMvc.perform(post(url(), json)) .andExpect(status().isConflict) } /** * PUT /user/:id/ * Modify the data of a user */ @Test fun putUserId() { val credentials = createUser(this.mockMvc, userService = userService) // Update user val json = mapOf( "firstname" to "Florian", "lastname" to "Schmidt", "gender" to "Male", "blocked" to true ).toJsonString() val request = MockMvcRequestBuilders .put("/user/${credentials.id}/") .header("Authorization", "Bearer ${credentials.accessToken}") .contentType(MediaType.APPLICATION_JSON) .content(json) mockMvc.perform(request) .andExpect(status().isOk) .andExpect(jsonPath("$.id").value(credentials.id)) .andExpect(jsonPath("$.email").value("[email protected]")) .andExpect(jsonPath("$.firstname").value("Florian")) .andExpect(jsonPath("$.lastname").value("Schmidt")) .andExpect(jsonPath("$.gender").value("Male")) .andExpect(jsonPath("$.blocked").value(false)) // A user can't block itself .andExpect(jsonPath("$.profilePic.id").exists()) .andExpect(jsonPath("$.profilePic.url").exists()) .andExpect(jsonPath("$.profilePic.type").value("IMAGE")) .andExpect(jsonPath("$.passwordHash").doesNotExist()) // TODO: Can't override existing properties with null! } @Test fun putUserDoesNotOverrideExistingPropertiesWithNull() { val credentials = createUser(this.mockMvc, userService = this.userService) val initJson = mapOf( "firstname" to "Florian", "lastname" to "Schmidt", "gender" to "Male", "blocked" to true ).toJsonString() val initRequest = MockMvcRequestBuilders .put("/user/${credentials.id}/") .header("Authorization", "Bearer ${credentials.accessToken}") .contentType(MediaType.APPLICATION_JSON) .content(initJson) mockMvc.perform(initRequest).andExpect(status().isOk) val json = mapOf( "firstname" to "Florian", "lastname" to "Schmidt", "gender" to "Male", "blocked" to true ).toJsonString() val request = MockMvcRequestBuilders .put("/user/${credentials.id}/") .header("Authorization", "Bearer ${credentials.accessToken}") .contentType(MediaType.APPLICATION_JSON) .content(json) mockMvc.perform(request) .andExpect(status().isOk) .andExpect(jsonPath("$.id").value(credentials.id)) .andExpect(jsonPath("$.email").value("[email protected]")) .andExpect(jsonPath("$.firstname").value("Florian")) .andExpect(jsonPath("$.lastname").value("Schmidt")) .andExpect(jsonPath("$.gender").value("Male")) .andExpect(jsonPath("$.blocked").value(false)) // A user can't block itself .andExpect(jsonPath("$.passwordHash").doesNotExist()) } @Test fun putUserCanOnlyModifyItsOwnData() { val firstUserCredentials = createUser(this.mockMvc, "[email protected]", "pwd", this.userService) val secondUserCredentials = createUser(this.mockMvc, "[email protected]", "pwd", this.userService) val json = mapOf("firstname" to "ChangeMe").toJsonString() val request = MockMvcRequestBuilders .put("/user/${firstUserCredentials.id}/") .header("Authorization", "Bearer ${secondUserCredentials.accessToken}") .contentType(MediaType.APPLICATION_JSON) .content(json) mockMvc.perform(request).andExpect(status().isUnauthorized) } @Test fun putUserUnauthorizedUserCantModifyUserData() { val json = mapOf("firstname" to "ChangeMe").toJsonString() val request = MockMvcRequestBuilders.put("/user/1/") .contentType(MediaType.APPLICATION_JSON) .content(json) mockMvc.perform(request).andExpect(status().isUnauthorized) } @Test fun makeUserParticipant() { val credentials = createUser(this.mockMvc, userService = userService) val date = LocalDate.now().toString() // Update user with role participant val json = mapOf( "firstname" to "Florian", "lastname" to "Schmidt", "gender" to "Male", "blocked" to false, "participant" to mapOf( "tshirtsize" to "XL", "hometown" to "Dresden", "birthdate" to date, "phonenumber" to "01234567890", "emergencynumber" to "0987654321" ) ).toJsonString() val request = MockMvcRequestBuilders .put("/user/${credentials.id}/") .header("Authorization", "Bearer ${credentials.accessToken}") .contentType(MediaType.APPLICATION_JSON) .content(json) mockMvc.perform(request) .andExpect(status().isOk) .andExpect(jsonPath("id").value(credentials.id)) .andExpect(jsonPath("$.id").value(credentials.id)) .andExpect(jsonPath("$.email").value("[email protected]")) .andExpect(jsonPath("$.firstname").value("Florian")) .andExpect(jsonPath("$.lastname").value("Schmidt")) .andExpect(jsonPath("$.gender").value("Male")) .andExpect(jsonPath("$.blocked").value(false)) .andExpect(jsonPath("$.participant").exists()) .andExpect(jsonPath("$.participant.tshirtsize").value("XL")) .andExpect(jsonPath("$.participant.hometown").value("Dresden")) .andExpect(jsonPath("$.participant.birthdate").value(date)) .andExpect(jsonPath("$.participant.phonenumber").value("01234567890")) .andExpect(jsonPath("$.participant.emergencynumber").value("0987654321")) .andReturn().response.contentAsString } @Test fun failToMakeUserParticipantIfUnauthorized() { val date = LocalDate.now().toString() val credentials = createUser(mockMvc, userService = userService) val json = mapOf( "firstname" to "Florian", "lastname" to "Schmidt", "gender" to "Male", "blocked" to false, "participant" to mapOf( "tshirtsize" to "XL", "hometown" to "Dresden", "birthdate" to date, "phonenumber" to "01234567890", "emergencynumber" to "0987654321" ) ).toJsonString() val request = MockMvcRequestBuilders .put("/user/${credentials.id}/") .header("Authorization", "Bearer thisIsAnInvalidAccessToken") .contentType(MediaType.APPLICATION_JSON) .content(json) mockMvc.perform(request) .andExpect(status().isUnauthorized) } @Test fun getUserId() { // Create user val json = mapOf( "email" to "[email protected]", "password" to "password", "firstname" to "Florian", "lastname" to "Schmidt" ).toJsonString() val resultPut = mockMvc.perform(post(url(), json)) .andExpect(status().isCreated) .andExpect(jsonPath("$.id").exists()) .andReturn() val response: Map<String, kotlin.Any> = ObjectMapper() .reader(Map::class.java) .readValue(resultPut.response.contentAsString) val id = response["id"] as Int mockMvc.perform(get(url(id))) .andExpect(status().isOk) .andExpect(jsonPath("$.id").exists()) .andExpect(jsonPath("$.firstname").exists()) .andExpect(jsonPath("$.lastname").exists()) .andExpect(jsonPath("$.email").doesNotExist()) .andExpect(jsonPath("$.passwordHash").doesNotExist()) } @Test fun getUserBySearch() { val creator = userService.create("[email protected]", "password", { firstname = "Florian" lastname = "Schmidt" gender = "Male" addRole(Participant::class) }).getRole(Participant::class)!! val event = eventService.createEvent("title", LocalDateTime.now(), "city", Coord(0.0, 1.1), 36) val team = teamService.create(creator, "team-name1234", "description", event, null) userService.create("[email protected]", "password", { firstname = "Leo" lastname = "Theo" gender = "Male" }) mockMvc.perform(get("/user/search/sch/")) .andExpect(status().isOk) .andExpect(jsonPath("$").isArray) .andExpect(jsonPath("$[0].id").exists()) .andExpect(jsonPath("$[0].firstname").value("Florian")) .andExpect(jsonPath("$[0].lastname").value("Schmidt")) .andExpect(jsonPath("$[0].teamId").value(team.id!!.toInt())) .andExpect(jsonPath("$[0].teamname").value("team-name1234")) .andExpect(jsonPath("$[0].email").doesNotExist()) .andExpect(jsonPath("$[1]").doesNotExist()) mockMvc.perform(get("/user/search/break/")) .andExpect(status().isOk) .andExpect(jsonPath("$").isArray) .andExpect(jsonPath("$[0].id").exists()) .andExpect(jsonPath("$[0].firstname").exists()) .andExpect(jsonPath("$[0].lastname").exists()) .andExpect(jsonPath("$[0].email").doesNotExist()) .andExpect(jsonPath("$[1].id").exists()) .andExpect(jsonPath("$[1].firstname").exists()) .andExpect(jsonPath("$[1].lastname").exists()) .andExpect(jsonPath("$[1].email").doesNotExist()) } @Test fun getUserBySearchTeamname() { val creator = userService.create("[email protected]", "password", { firstname = "Florian" lastname = "Schmidt" gender = "Male" addRole(Participant::class) }).getRole(Participant::class)!! val event = eventService.createEvent("title", LocalDateTime.now(), "city", Coord(0.0, 1.1), 36) val team = teamService.create(creator, "team-name1234", "description", event, null) userService.create("[email protected]", "password", { firstname = "Leo" lastname = "Theo" gender = "Male" }) mockMvc.perform(get("/user/search/name1234/")) .andExpect(status().isOk) .andExpect(jsonPath("$").isArray) .andExpect(jsonPath("$[0].id").exists()) .andExpect(jsonPath("$[0].firstname").value("Florian")) .andExpect(jsonPath("$[0].lastname").value("Schmidt")) .andExpect(jsonPath("$[0].teamId").value(team.id!!.toInt())) .andExpect(jsonPath("$[0].teamname").value("team-name1234")) .andExpect(jsonPath("$[0].email").doesNotExist()) .andExpect(jsonPath("$[1]").doesNotExist()) } @Test fun getUserBySearchEmpty() { userService.create("[email protected]", "password", { firstname = "Florian" lastname = "Schmidt" gender = "Male" }) userService.create("[email protected]", "password", { firstname = "Leo" lastname = "Theo" gender = "Male" }) mockMvc.perform(get("/user/search/br/")) .andExpect(status().isOk) .andExpect(jsonPath("$").isArray) .andExpect(jsonPath("$[0]").doesNotExist()) .andExpect(jsonPath("$[1]").doesNotExist()) } @Test fun requestPasswordReset() { userService.create("[email protected]", "password", { firstname = "Florian" lastname = "Schmidt" gender = "Male" }) val json = mapOf( "email" to "[email protected]" ).toJsonString() val request = MockMvcRequestBuilders .post("/user/requestreset/") .contentType(MediaType.APPLICATION_JSON) .content(json) mockMvc.perform(request) .andExpect(status().isOk) .andExpect(jsonPath("$.status").value("sent reset mail")) .andReturn().response.contentAsString } @Test fun passwordReset() { val user = userService.create("[email protected]", "password", { firstname = "Florian" lastname = "Schmidt" gender = "Male" }) val token = user.createActivationToken() userService.save(user) val json = mapOf( "email" to "[email protected]", "token" to token, "password" to "otherPassword" ).toJsonString() val request = MockMvcRequestBuilders .post("/user/passwordreset/") .contentType(MediaType.APPLICATION_JSON) .content(json) mockMvc.perform(request) .andExpect(status().isOk) .andExpect(jsonPath("$.status").value("reset password")) .andReturn().response.contentAsString } }
src/test/java/backend/Integration/TestUserEndpoint.kt
244828500
package io.georocket.index.generic import io.georocket.index.DatabaseIndex import io.georocket.index.Indexer import io.georocket.index.IndexerFactory import io.georocket.index.geojson.GeoJsonGenericAttributeIndexer import io.georocket.index.xml.XMLGenericAttributeIndexer import io.georocket.query.* import io.georocket.query.QueryCompiler.MatchPriority import io.georocket.query.QueryPart.ComparisonOperator.EQ import io.georocket.util.JsonStreamEvent import io.georocket.util.StreamEvent import io.georocket.util.XMLStreamEvent /** * Base class for factories creating indexers that manage arbitrary generic * string attributes (i.e. key-value pairs) * @author Michel Kraemer */ class GenericAttributeIndexerFactory : IndexerFactory { @Suppress("UNCHECKED_CAST") override fun <T : StreamEvent> createIndexer(eventType: Class<T>): Indexer<T>? { if (eventType.isAssignableFrom(XMLStreamEvent::class.java)) { return XMLGenericAttributeIndexer() as Indexer<T> } else if (eventType.isAssignableFrom(JsonStreamEvent::class.java)) { return GeoJsonGenericAttributeIndexer() as Indexer<T> } return null } override fun getQueryPriority(queryPart: QueryPart): MatchPriority { return when (queryPart) { is StringQueryPart, is LongQueryPart, is DoubleQueryPart -> MatchPriority.SHOULD } } override fun compileQuery(queryPart: QueryPart): IndexQuery { return when (queryPart) { is StringQueryPart, is LongQueryPart, is DoubleQueryPart -> { val key = queryPart.key if (key != null) { ElemMatchCompare( "genAttrs", "key" to key, Compare("value", queryPart.value, queryPart.comparisonOperator ?: EQ) ) } else { ElemMatchExists( "genAttrs", "value" to queryPart.value ) } } } } override fun getDatabaseIndexes(indexedFields: List<String>): List<DatabaseIndex> = listOf( DatabaseIndex.ElemMatchExists("genAttrs", listOf("value", "key"), "gen_attrs_elem_match_exists"), *indexedFields.map { fieldName -> DatabaseIndex.ElemMatchCompare( "genAttrs", "key", "value", fieldName, "gen_attrs_${fieldName}_elem_match_cmp" ) }.toTypedArray(), ) }
src/main/kotlin/io/georocket/index/generic/GenericAttributeIndexerFactory.kt
1681503053
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.insight import com.demonwav.mcdev.facet.MinecraftFacet import com.demonwav.mcdev.util.runWriteAction import com.intellij.openapi.module.ModuleUtilCore import com.intellij.psi.JavaPsiFacade import com.intellij.psi.JavaTokenType import com.intellij.psi.PsiElement import com.intellij.psi.PsiExpressionList import com.intellij.psi.PsiLiteralExpression import com.intellij.psi.PsiReferenceExpression import java.awt.Color fun <T> PsiElement.findColor(function: (Map<String, Color>, Map.Entry<String, Color>) -> T): T? { if (this !is PsiReferenceExpression) { return null } val module = ModuleUtilCore.findModuleForPsiElement(this) ?: return null val facet = MinecraftFacet.getInstance(module) ?: return null val expression = this val type = expression.type ?: return null for (abstractModuleType in facet.types) { val map = abstractModuleType.classToColorMappings for (entry in map.entries) { // This is such a hack // Okay, type will be the fully-qualified class, but it will exclude the actual enum // the expression will be the non-fully-qualified class with the enum // So we combine those checks and get this if (entry.key.startsWith(type.canonicalText) && entry.key.endsWith(expression.canonicalText)) { return function(map, entry) } } } return null } fun PsiElement.setColor(color: String) { this.containingFile.runWriteAction { val split = color.split(".").dropLastWhile(String::isEmpty).toTypedArray() val newColorBase = split.last() val node = this.node val child = node.findChildByType(JavaTokenType.IDENTIFIER) ?: return@runWriteAction val identifier = JavaPsiFacade.getElementFactory(this.project).createIdentifier(newColorBase) child.psi.replace(identifier) } } fun PsiLiteralExpression.setColor(value: Int) { this.containingFile.runWriteAction { val node = this.node val literalExpression = JavaPsiFacade.getElementFactory(this.project) .createExpressionFromText("0x" + Integer.toHexString(value).toUpperCase(), null) as PsiLiteralExpression node.psi.replace(literalExpression) } } fun PsiExpressionList.setColor(red: Int, green: Int, blue: Int) { this.containingFile.runWriteAction { val expressionOne = this.expressions[0] val expressionTwo = this.expressions[1] val expressionThree = this.expressions[2] val nodeOne = expressionOne.node val nodeTwo = expressionTwo.node val nodeThree = expressionThree.node val facade = JavaPsiFacade.getElementFactory(this.project) val literalExpressionOne = facade.createExpressionFromText(red.toString(), null) val literalExpressionTwo = facade.createExpressionFromText(green.toString(), null) val literalExpressionThree = facade.createExpressionFromText(blue.toString(), null) nodeOne.psi.replace(literalExpressionOne) nodeTwo.psi.replace(literalExpressionTwo) nodeThree.psi.replace(literalExpressionThree) } }
src/main/kotlin/com/demonwav/mcdev/insight/ColorUtil.kt
1749464131
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.ui import com.intellij.openapi.project.Project import javax.swing.tree.DefaultTreeModel @Deprecated("Use ChangesGroupingPolicyFactory instead") open class ChangesModuleGroupingPolicy(val myProject: Project, val myModel: DefaultTreeModel) : ChangesGroupingPolicy { override fun getParentNodeFor(nodePath: StaticFilePath, subtreeRoot: ChangesBrowserNode<*>): ChangesBrowserNode<*>? { return null } }
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesModuleGroupingPolicy.kt
4160197080
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.sponge.generation import com.demonwav.mcdev.insight.generation.GenerationData data class SpongeGenerationData(val isIgnoreCanceled: Boolean, val eventOrder: String) : GenerationData
src/main/kotlin/com/demonwav/mcdev/platform/sponge/generation/SpongeGenerationData.kt
695266892
package se.barsk.park.storage import android.provider.BaseColumns object ParkContract { const val SQL_CREATE_ENTRIES = "CREATE TABLE " + CarCollectionTable.TABLE_NAME + " (" + CarCollectionTable.COLUMN_NAME_UUID + " TEXT PRIMARY KEY," + CarCollectionTable.COLUMN_NAME_POSITION + " INTEGER," + CarCollectionTable.COLUMN_NAME_REGNO + " TEXT," + CarCollectionTable.COLUMN_NAME_OWNER + " TEXT," + CarCollectionTable.COLUMN_NAME_NICKNAME + " TEXT)" class CarCollectionTable private constructor() : BaseColumns { companion object { const val TABLE_NAME = "car_collection" const val COLUMN_NAME_UUID = "uuid" const val COLUMN_NAME_POSITION = "position" const val COLUMN_NAME_REGNO = "regno" const val COLUMN_NAME_OWNER = "owner" const val COLUMN_NAME_NICKNAME = "nickname" } } }
app/src/main/java/se/barsk/park/storage/ParkContract.kt
1380141807
package urn.conductor.core import urn.conductor.StandardComplexElementHandler import urn.conductor.stdlib.xml.InvokeMacro class InvokeMacroHandler : StandardComplexElementHandler<InvokeMacro> { override val handles: Class<InvokeMacro> get() = InvokeMacro::class.java override fun process(element: InvokeMacro, engine: urn.conductor.Engine, processChild: (Any) -> Unit) { val macroName = element.ref val macroBody = engine.get(macroName) as Runnable macroBody.run() } }
conductor-engine/src/main/java/urn/conductor/core/InvokeMacroHandler.kt
2969732686
package quickbeer.android.domain.stylelist.network import com.squareup.moshi.Json data class StyleJson( @field:Json(name = "BeerStyleID") val id: Int, @field:Json(name = "BeerStyleName") val name: String, @field:Json(name = "BeerStyleDescription") val description: String?, @field:Json(name = "BeerStyleParent") val parent: Int?, @field:Json(name = "BeerStyleCategory") val category: Int?, )
app/src/main/java/quickbeer/android/domain/stylelist/network/StyleJson.kt
2262437347
package galvin.ff.users import galvin.ff.* import galvin.ff.db.ConnectionManager import org.junit.AfterClass import org.junit.Assert import org.junit.Test class LoginManagerTest{ private enum class LoginTokenManagerType{ inmem, sqlite, psql } companion object { @AfterClass @JvmStatic fun cleanup(){ for (database in databases) { database.cleanup() } } } @Test fun should_login_successfully_by_password() { for( type in LoginTokenManagerType.values() ){ val (auditDB, userDB, loginManager, roles, count) = testObjects(type) val passwords = mutableListOf<String>() for (i in 0..count) { passwords.add(uuid()) } val users = mutableListOf<User>() for (i in 0..count) { users.add(generateUser(roles, uuid(), passwords[i])) userDB.storeUser(users[i]) } for (i in 0..count) { val user = users[i] val password = passwords[i] val credentials = Credentials(username = user.login, password = password) val loginToken = loginManager.authenticate(credentials) Assert.assertEquals("Unexpected user", user.uuid, loginToken.user.uuid) } for (i in 0..count) { val user = users[i] val credentials = Credentials(x509SerialNumber = neverNull(user.serialNumber)) val loginToken = loginManager.authenticate(credentials) Assert.assertEquals("Unexpected user", user.uuid, loginToken.user.uuid) } val auditEvents = auditDB.retrieveAccessInfo() Assert.assertEquals("Unexpected event count", 22, auditEvents.size) for ((i, event) in auditEvents.listIterator().withIndex()) { val index = if (i <= 10) i else i - 11 val user = users[index] Assert.assertEquals("Unexpected user at index $index", user.uuid, event.userUuid) Assert.assertEquals("Unexpected user at index $index", user.uuid, event.resourceUuid) Assert.assertEquals("Unexpected user at index $index", user.login, event.resourceName) Assert.assertTrue("Unexpected access granted $index", event.permissionGranted) } } } @Test fun should_login_successfully_by_serial_number() { for( type in LoginTokenManagerType.values() ){ val (_, userDB, loginManager, roles, count) = testObjects(type) val passwords = mutableListOf<String>() for (i in 0..count) { passwords.add(uuid()) } val users = mutableListOf<User>() for (i in 0..count) { users.add(generateUser(roles, uuid(), passwords[i])) userDB.storeUser(users[i]) } for (i in 0..count) { val user = users[i] val credentials = Credentials(x509SerialNumber = neverNull(user.serialNumber)) val loginToken = loginManager.authenticate(credentials) Assert.assertEquals("Unexpected user", user.uuid, loginToken.user.uuid) } } } @Test fun should_login_successfully_by_login_token() { for( type in LoginTokenManagerType.values() ){ val (_, userDB, loginManager, roles, count) = testObjects(type) val passwords = mutableListOf<String>() for (i in 0..count) { passwords.add(uuid()) } val users = mutableListOf<User>() for (i in 0..count) { users.add(generateUser(roles, uuid(), passwords[i])) userDB.storeUser(users[i]) } val loginTokens = mutableListOf<LoginToken>() for (i in 0..count) { val user = users[i] val password = passwords[i] val credentials = Credentials(username = user.login, password = password) val loginToken = loginManager.authenticate(credentials) loginTokens.add(loginToken) } for (loginToken in loginTokens) { val credentials = Credentials(tokenUuid = loginToken.uuid) val newLoginToken = loginManager.authenticate(credentials) Assert.assertEquals("Unexpected user", loginToken.user.uuid, newLoginToken.user.uuid) } try { val credentials = Credentials(tokenUuid = uuid()) loginManager.authenticate(credentials) throw Exception("Login manager should have thrown") } catch (ex: LoginError) { } } } @Test fun should_log_out() { for( type in LoginTokenManagerType.values() ){ val (_, userDB, loginManager, roles, count) = testObjects(type) val passwords = mutableListOf<String>() for (i in 0..count) { passwords.add(uuid()) } val users = mutableListOf<User>() for (i in 0..count) { users.add(generateUser(roles, uuid(), passwords[i])) userDB.storeUser(users[i]) } val loginTokens = mutableListOf<LoginToken>() for (i in 0..count) { val user = users[i] val password = passwords[i] val credentials = Credentials(username = user.login, password = password) val loginToken = loginManager.authenticate(credentials) loginTokens.add(loginToken) } for (loginToken in loginTokens) { loginManager.logout(loginToken.uuid) } for (loginToken in loginTokens) { try { val credentials = Credentials(tokenUuid = loginToken.uuid) loginManager.authenticate(credentials) throw Exception("Login manager should have thrown") } catch (ex: LoginError) { //no-op } } } } @Test fun should_purge_expired() { for( type in LoginTokenManagerType.values() ){ val (_, userDB, loginManager, roles, count) = testObjects(type = type, tokenLifespan = 1, addressMaxUnhindered = 10_000) val passwords = mutableListOf<String>() for (i in 0..count) { passwords.add(uuid()) } val users = mutableListOf<User>() for (i in 0..count) { users.add(generateUser(roles, uuid(), passwords[i])) userDB.storeUser(users[i]) } val loginTokens = mutableListOf<LoginToken>() for (i in 0..count) { val user = users[i] val password = passwords[i] val credentials = Credentials(username = user.login, password = password) val loginToken = loginManager.authenticate(credentials) loginTokens.add(loginToken) } //let the tokens expire Thread.sleep(100) for (loginToken in loginTokens) { try { val credentials = Credentials(tokenUuid = loginToken.uuid) loginManager.authenticate(credentials) throw Exception("Login manager should have thrown") } catch (ex: LoginError) { //no-op } } // for (loginToken in loginTokens) { // Assert.assertTrue("Token should have expired", loginToken.hasExpired(timeProvider.now())) // } } } @Test fun should_log_out_concurrent_sessions() { for( type in LoginTokenManagerType.values() ){ val (_, userDB, loginManager, roles, count) = testObjects(type = type, allowConcurrentLogins = false, loginMaxFailed = 100) val timeProvider = DefaultTimeProvider() val user = generateUser(roles) userDB.storeUser(user) val badLogins = mutableListOf<LoginToken>() val goodLogins = mutableListOf<LoginToken>() val address1 = "127.0.0.1" for (i in 0..count) { val credentials = Credentials(ipAddress = address1, x509SerialNumber = neverNull(user.serialNumber)) val loginToken = loginManager.authenticate(credentials) badLogins.add(loginToken) } val address2 = "127.0.0.2" for (i in 0..count) { val credentials = Credentials( ipAddress = address2, x509SerialNumber = neverNull(user.serialNumber) ) val loginToken = loginManager.authenticate(credentials) goodLogins.add(loginToken) } for (token in badLogins) { try { loginManager.authenticate( Credentials(ipAddress = token.ipAddress, tokenUuid = token.uuid) ) throw Exception("Token should have been logged out") }catch( loginError: LoginError ){} } for (token in goodLogins) { val loaded = loginManager.authenticate( Credentials(ipAddress = token.ipAddress, tokenUuid = token.uuid) ) Assert.assertFalse("Token should not have been logged out", loaded.hasExpired(timeProvider.now())) } } } @Test fun should_fail_login_by_password() { for( type in LoginTokenManagerType.values() ){ val (auditDB, userDB, loginManager, roles, count) = testObjects(type) val passwords = mutableListOf<String>() for (i in 0..count) { passwords.add(uuid()) } val users = mutableListOf<User>() for (i in 0..count) { users.add(generateUser(roles, uuid(), passwords[i])) userDB.storeUser(users[i]) } for (i in 0..count) { val user = users[i] val credentials = Credentials(username = user.login, password = uuid()) try { loginManager.authenticate(credentials) throw Exception("Should have thrown login exception") } catch (ex: LoginError) { //no-op } } val auditEvents = auditDB.retrieveAccessInfo() Assert.assertEquals("Unexpected event count", 11, auditEvents.size) for ((i, event) in auditEvents.listIterator().withIndex()) { val index = if (i <= 10) i else i - 11 val user = users[index] Assert.assertEquals("Unexpected user at index $index", user.uuid, event.resourceUuid) Assert.assertEquals("Unexpected user at index $index", user.login, event.resourceName) Assert.assertFalse("Unexpected access granted $index", event.permissionGranted) } } } @Test fun should_lock_and_throw_on_max_failures() { for( type in LoginTokenManagerType.values() ){ val (_, userDB, loginManager, roles, _) = testObjects(type) val user = generateUser(roles) userDB.storeUser(user) val attemptCount = MAX_FAILED_LOGIN_ATTEMPTS_PER_USER + 1 for (i in 0..attemptCount) { val credentials = Credentials(username = user.login, password = uuid()) try { loginManager.authenticate(credentials) throw Exception("Should have thrown login exception") } catch (ex: LoginError) { //no-op } } try { val credentials = Credentials(username = user.login, password = uuid()) loginManager.authenticate(credentials) throw Exception("Should have thrown login exception") } catch (ex: LoginError) { Assert.assertEquals("Unexpected error message", LOGIN_EXCEPTION_MAX_ATTEMPTS_EXCEEDED, ex.message) } Assert.assertTrue("User should have been locked", userDB.isLocked(user.uuid)) } } /// /// utilities /// class LoginManagerTestObjects(private val auditDB: AuditDB, private val userDB: UserDB, private val loginManager: LoginManager, private val roles: List<Role>, private val count: Int = 10 ){ operator fun component1(): AuditDB{ return auditDB } operator fun component2(): UserDB{ return userDB } operator fun component3(): LoginManager{ return loginManager } operator fun component4(): List<Role>{ return roles } operator fun component5(): Int{ return count } } private fun testObjects(type: LoginTokenManagerType, allowConcurrentLogins: Boolean = true, tokenLifespan: Long = 1_000_000, loginMaxFailed: Int = 1, addressMaxUnhindered: Int = MAX_UNHINDERED_LOGIN_ATTEMPTS_IP_ADDRESS): LoginManagerTestObjects { val dbConnection = SqliteDbConnection() val auditDB = dbConnection.randomAuditDB() val userDB = dbConnection.randomUserDB() val roles = generateRoles(userdb = userDB) val config = LoginManagerConfig( tokenLifespan = tokenLifespan, sleepBetweenAttempts = false, allowConcurrentLogins = allowConcurrentLogins, loginMaxFailed = loginMaxFailed, addressMaxUnhindered = addressMaxUnhindered) val tokens = when(type){ LoginTokenManagerType.inmem -> InMemLoginTokenManager() LoginTokenManagerType.sqlite -> LoginTokenManager.SQLite( userDB, 1, SqliteDbConnection.randomDbFile() ) LoginTokenManagerType.psql -> LoginTokenManager.PostgreSQL( userDB, 1, "jdbc:postgresql://localhost:5432/" + PsqlDbConnection().createRandom() ) } val loginManager = LoginManager( userDB = userDB, auditDB = auditDB, config = config, loginTokens = tokens ) return LoginManagerTestObjects(auditDB, userDB, loginManager, roles) } }
src/test/kotlin/galvin/ff/users/LoginManagerTest.kt
133014590
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("RangesBuilder") package com.intellij.openapi.vcs.ex import com.intellij.diff.comparison.* import com.intellij.diff.comparison.iterables.DiffIterableUtil import com.intellij.diff.comparison.iterables.DiffIterableUtil.fair import com.intellij.diff.comparison.iterables.FairDiffIterable import com.intellij.diff.tools.util.text.LineOffsets import com.intellij.diff.tools.util.text.LineOffsetsUtil import com.intellij.diff.util.DiffRangeUtil import com.intellij.diff.util.Range import com.intellij.diff.util.Side import com.intellij.openapi.editor.Document import com.intellij.openapi.progress.DumbProgressIndicator import kotlin.math.max fun createRanges(current: List<String>, vcs: List<String>, currentShift: Int, vcsShift: Int, innerWhitespaceChanges: Boolean): List<LstRange> { val iterable = compareLines(vcs, current) return iterable.iterateChanges().map { val inner = if (innerWhitespaceChanges) createInnerRanges(vcs.subList(it.start1, it.end1), current.subList(it.start2, it.end2)) else null LstRange(it.start2 + currentShift, it.end2 + currentShift, it.start1 + vcsShift, it.end1 + vcsShift, inner) } } fun createRanges(current: Document, vcs: Document): List<LstRange> { return createRanges(current.immutableCharSequence, vcs.immutableCharSequence, current.lineOffsets, vcs.lineOffsets) } fun createRanges(current: CharSequence, vcs: CharSequence): List<LstRange> { return createRanges(current, vcs, current.lineOffsets, vcs.lineOffsets) } private fun createRanges(current: CharSequence, vcs: CharSequence, currentLineOffsets: LineOffsets, vcsLineOffsets: LineOffsets): List<LstRange> { val iterable = compareLines(vcs, current, vcsLineOffsets, currentLineOffsets) return iterable.iterateChanges().map { LstRange(it.start2, it.end2, it.start1, it.end1) } } fun compareLines(text1: CharSequence, text2: CharSequence, lineOffsets1: LineOffsets, lineOffsets2: LineOffsets): FairDiffIterable { val range = expand(text1, text2, 0, 0, text1.length, text2.length) if (range.isEmpty) return fair(DiffIterableUtil.create(emptyList(), lineOffsets1.lineCount, lineOffsets2.lineCount)) val contextLines = 5 val start = max(lineOffsets1.getLineNumber(range.start1) - contextLines, 0) val tail = max(lineOffsets1.lineCount - lineOffsets1.getLineNumber(range.end1) - 1 - contextLines, 0) val lineRange = Range(start, lineOffsets1.lineCount - tail, start, lineOffsets2.lineCount - tail) val iterable = compareLines(lineRange, text1, text2, lineOffsets1, lineOffsets2) return fair(DiffIterableUtil.expandedIterable(iterable, start, start, lineOffsets1.lineCount, lineOffsets2.lineCount)) } fun compareLines(lineRange: Range, text1: CharSequence, text2: CharSequence, lineOffsets1: LineOffsets, lineOffsets2: LineOffsets): FairDiffIterable { val lines1 = DiffRangeUtil.getLines(text1, lineOffsets1, lineRange.start1, lineRange.end1) val lines2 = DiffRangeUtil.getLines(text2, lineOffsets2, lineRange.start2, lineRange.end2) return compareLines(lines1, lines2) } fun tryCompareLines(lineRange: Range, text1: CharSequence, text2: CharSequence, lineOffsets1: LineOffsets, lineOffsets2: LineOffsets): FairDiffIterable? { val lines1 = DiffRangeUtil.getLines(text1, lineOffsets1, lineRange.start1, lineRange.end1) val lines2 = DiffRangeUtil.getLines(text2, lineOffsets2, lineRange.start2, lineRange.end2) return tryCompareLines(lines1, lines2) } fun fastCompareLines(lineRange: Range, text1: CharSequence, text2: CharSequence, lineOffsets1: LineOffsets, lineOffsets2: LineOffsets): FairDiffIterable { val lines1 = DiffRangeUtil.getLines(text1, lineOffsets1, lineRange.start1, lineRange.end1) val lines2 = DiffRangeUtil.getLines(text2, lineOffsets2, lineRange.start2, lineRange.end2) return fastCompareLines(lines1, lines2) } fun createInnerRanges(lineRange: Range, text1: CharSequence, text2: CharSequence, lineOffsets1: LineOffsets, lineOffsets2: LineOffsets): List<LstInnerRange> { val lines1 = DiffRangeUtil.getLines(text1, lineOffsets1, lineRange.start1, lineRange.end1) val lines2 = DiffRangeUtil.getLines(text2, lineOffsets2, lineRange.start2, lineRange.end2) return createInnerRanges(lines1, lines2) } private fun compareLines(lines1: List<String>, lines2: List<String>): FairDiffIterable { val iwIterable: FairDiffIterable = safeCompareLines(lines1, lines2, ComparisonPolicy.IGNORE_WHITESPACES) return processLines(lines1, lines2, iwIterable) } private fun tryCompareLines(lines1: List<String>, lines2: List<String>): FairDiffIterable? { val iwIterable: FairDiffIterable = tryCompareLines(lines1, lines2, ComparisonPolicy.IGNORE_WHITESPACES) ?: return null return processLines(lines1, lines2, iwIterable) } private fun fastCompareLines(lines1: List<String>, lines2: List<String>): FairDiffIterable { val iwIterable: FairDiffIterable = fastCompareLines(lines1, lines2, ComparisonPolicy.IGNORE_WHITESPACES) return processLines(lines1, lines2, iwIterable) } /** * Compare lines, preferring non-optimal but less confusing results for whitespace-only changed lines * Ex: "X\n\nY\nZ" vs " X\n Y\n\n Z" should be a single big change, rather than 2 changes separated by "matched" empty line. */ private fun processLines(lines1: List<String>, lines2: List<String>, iwIterable: FairDiffIterable): FairDiffIterable { val builder = DiffIterableUtil.ExpandChangeBuilder(lines1, lines2) for (range in iwIterable.unchanged()) { val count = range.end1 - range.start1 for (i in 0 until count) { val index1 = range.start1 + i val index2 = range.start2 + i if (lines1[index1] == lines2[index2]) { builder.markEqual(index1, index2) } } } return fair(builder.finish()) } private fun createInnerRanges(lines1: List<String>, lines2: List<String>): List<LstInnerRange> { val iwIterable: FairDiffIterable = safeCompareLines(lines1, lines2, ComparisonPolicy.IGNORE_WHITESPACES) val result = ArrayList<LstInnerRange>() for (pair in DiffIterableUtil.iterateAll(iwIterable)) { val range = pair.first val equals = pair.second result.add(LstInnerRange(range.start2, range.end2, getChangeType(range, equals))) } result.trimToSize() return result } private fun getChangeType(range: Range, equals: Boolean): Byte { if (equals) return LstRange.EQUAL val deleted = range.end1 - range.start1 val inserted = range.end2 - range.start2 if (deleted > 0 && inserted > 0) return LstRange.MODIFIED if (deleted > 0) return LstRange.DELETED if (inserted > 0) return LstRange.INSERTED return LstRange.EQUAL } private fun safeCompareLines(lines1: List<String>, lines2: List<String>, comparisonPolicy: ComparisonPolicy): FairDiffIterable { return tryCompareLines(lines1, lines2, comparisonPolicy) ?: fastCompareLines(lines1, lines2, comparisonPolicy) } private fun tryCompareLines(lines1: List<String>, lines2: List<String>, comparisonPolicy: ComparisonPolicy): FairDiffIterable? { try { return ByLine.compare(lines1, lines2, comparisonPolicy, DumbProgressIndicator.INSTANCE) } catch (e: DiffTooBigException) { return null } } private fun fastCompareLines(lines1: List<String>, lines2: List<String>, comparisonPolicy: ComparisonPolicy): FairDiffIterable { val range = expand(lines1, lines2, 0, 0, lines1.size, lines2.size, { line1, line2 -> ComparisonUtil.isEquals(line1, line2, comparisonPolicy) }) val ranges = if (range.isEmpty) emptyList() else listOf(range) return fair(DiffIterableUtil.create(ranges, lines1.size, lines2.size)) } fun isValidRanges(content1: CharSequence, content2: CharSequence, lineOffsets1: LineOffsets, lineOffsets2: LineOffsets, lineRanges: List<Range>): Boolean { val allRangesValid = lineRanges.all { isValidLineRange(lineOffsets1, it.start1, it.end1) && isValidLineRange(lineOffsets2, it.start2, it.end2) } if (!allRangesValid) return false val iterable = DiffIterableUtil.create(lineRanges, lineOffsets1.lineCount, lineOffsets2.lineCount) for (range in iterable.iterateUnchanged()) { val lines1 = DiffRangeUtil.getLines(content1, lineOffsets1, range.start1, range.end1) val lines2 = DiffRangeUtil.getLines(content2, lineOffsets2, range.start2, range.end2) if (lines1 != lines2) { return false } } return true } private fun isValidLineRange(lineOffsets: LineOffsets, start: Int, end: Int): Boolean { return start in 0..end && end <= lineOffsets.lineCount } internal operator fun <T> Side.get(v1: T, v2: T): T = if (isLeft) v1 else v2 internal fun Range.start(side: Side) = side[start1, start2] internal fun Range.end(side: Side) = side[end1, end2] internal val Document.lineOffsets: LineOffsets get() = LineOffsetsUtil.create(this) internal val CharSequence.lineOffsets: LineOffsets get() = LineOffsetsUtil.create(this)
platform/diff-impl/src/com/intellij/openapi/vcs/ex/RangesBuilder.kt
299855119
// 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.j2k.ast import com.intellij.psi.JavaTokenType import com.intellij.psi.PsiElement import com.intellij.psi.tree.IElementType import org.jetbrains.kotlin.j2k.CodeBuilder import org.jetbrains.kotlin.j2k.append import org.jetbrains.kotlin.lexer.KtTokens import java.util.* class ArrayAccessExpression(val expression: Expression, val index: Expression, val lvalue: Boolean) : Expression() { override fun generateCode(builder: CodeBuilder) { builder.appendOperand(this, expression) if (!lvalue && expression.isNullable) builder.append("!!") builder append "[" append index append "]" } } open class AssignmentExpression(val left: Expression, val right: Expression, val op: Operator) : Expression() { fun isMultiAssignment() = right is AssignmentExpression fun appendAssignment(builder: CodeBuilder, left: Expression, right: Expression) { builder.appendOperand(this, left).append(" ").append(op).append(" ").appendOperand(this, right) } override fun generateCode(builder: CodeBuilder) { if (right !is AssignmentExpression) appendAssignment(builder, left, right) else { right.generateCode(builder) builder.append("\n") appendAssignment(builder, left, right.left) } } } class BangBangExpression(val expr: Expression) : Expression() { override fun generateCode(builder: CodeBuilder) { builder.appendOperand(this, expr).append("!!") } companion object { fun surroundIfNullable(expression: Expression): Expression { return if (expression.isNullable) BangBangExpression(expression).assignNoPrototype() else expression } } } class BinaryExpression(val left: Expression, val right: Expression, val op: Operator) : Expression() { override fun generateCode(builder: CodeBuilder) { builder.appendOperand(this, left, false).append(" ").append(op).append(" ").appendOperand(this, right, true) } } class IsOperator(val expression: Expression, val type: Type) : Expression() { override fun generateCode(builder: CodeBuilder) { builder.appendOperand(this, expression).append(" is ").append(type) } } class TypeCastExpression(val type: Type, val expression: Expression) : Expression() { override fun generateCode(builder: CodeBuilder) { builder.appendOperand(this, expression).append(" as ").append(type) } override val isNullable: Boolean get() = type.isNullable } open class LiteralExpression(val literalText: String) : Expression() { override fun generateCode(builder: CodeBuilder) { builder.append(literalText) } object NullLiteral : LiteralExpression("null"){ override val isNullable: Boolean get() = true } } class ArrayLiteralExpression(val expressions: List<Expression>) : Expression() { override fun generateCode(builder: CodeBuilder) { builder.append("[") builder.append(expressions, ", ") builder.append("]") } } class ParenthesizedExpression(val expression: Expression) : Expression() { override fun generateCode(builder: CodeBuilder) { builder append "(" append expression append ")" } } class PrefixExpression(val op: Operator, val expression: Expression) : Expression() { override fun generateCode(builder: CodeBuilder){ builder.append(op).appendOperand(this, expression) } override val isNullable: Boolean get() = expression.isNullable } class PostfixExpression(val op: Operator, val expression: Expression) : Expression() { override fun generateCode(builder: CodeBuilder) { builder.appendOperand(this, expression) append op } } class ThisExpression(val identifier: Identifier) : Expression() { override fun generateCode(builder: CodeBuilder) { builder.append("this").appendWithPrefix(identifier, "@") } } class SuperExpression(val identifier: Identifier) : Expression() { override fun generateCode(builder: CodeBuilder) { builder.append("super").appendWithPrefix(identifier, "@") } } class QualifiedExpression(val qualifier: Expression, val identifier: Expression, dotPrototype: PsiElement?) : Expression() { private val dot = Dot().assignPrototype(dotPrototype, CommentsAndSpacesInheritance.LINE_BREAKS) override val isNullable: Boolean get() = identifier.isNullable override fun generateCode(builder: CodeBuilder) { if (!qualifier.isEmpty) { builder.appendOperand(this, qualifier).append(if (qualifier.isNullable) "!!" else "") builder.append(dot) } builder.append(identifier) } private class Dot : Element() { override fun generateCode(builder: CodeBuilder) { builder.append(".") } } } open class Operator(val operatorType: IElementType): Expression() { override fun generateCode(builder: CodeBuilder) { builder.append(asString(operatorType)) } fun asString() = asString(operatorType) fun acceptLineBreakBefore(): Boolean { return when(operatorType) { JavaTokenType.ANDAND, JavaTokenType.OROR, JavaTokenType.PLUS, JavaTokenType.MINUS -> true else -> false } } val precedence: Int get() = when (this.operatorType) { JavaTokenType.ASTERISK, JavaTokenType.DIV, JavaTokenType.PERC -> 3 JavaTokenType.PLUS, JavaTokenType.MINUS -> 4 KtTokens.ELVIS -> 7 JavaTokenType.GT, JavaTokenType.LT, JavaTokenType.GE, JavaTokenType.LE -> 9 JavaTokenType.EQEQ, JavaTokenType.NE, KtTokens.EQEQEQ, KtTokens.EXCLEQEQEQ -> 10 JavaTokenType.ANDAND -> 11 JavaTokenType.OROR -> 12 JavaTokenType.GTGTGT, JavaTokenType.GTGT, JavaTokenType.LTLT -> 7 else -> 6 /* simple name */ } private fun asString(tokenType: IElementType): String { return when (tokenType) { JavaTokenType.EQ -> "=" JavaTokenType.EQEQ -> "==" JavaTokenType.NE -> "!=" JavaTokenType.ANDAND -> "&&" JavaTokenType.OROR -> "||" JavaTokenType.GT -> ">" JavaTokenType.LT -> "<" JavaTokenType.GE -> ">=" JavaTokenType.LE -> "<=" JavaTokenType.EXCL -> "!" JavaTokenType.PLUS -> "+" JavaTokenType.MINUS -> "-" JavaTokenType.ASTERISK -> "*" JavaTokenType.DIV -> "/" JavaTokenType.PERC -> "%" JavaTokenType.PLUSEQ -> "+=" JavaTokenType.MINUSEQ -> "-=" JavaTokenType.ASTERISKEQ -> "*=" JavaTokenType.DIVEQ -> "/=" JavaTokenType.PERCEQ -> "%=" JavaTokenType.GTGT -> "shr" JavaTokenType.LTLT -> "shl" JavaTokenType.XOR -> "xor" JavaTokenType.AND -> "and" JavaTokenType.OR -> "or" JavaTokenType.GTGTGT -> "ushr" JavaTokenType.GTGTEQ -> "shr" JavaTokenType.LTLTEQ -> "shl" JavaTokenType.XOREQ -> "xor" JavaTokenType.ANDEQ -> "and" JavaTokenType.OREQ -> "or" JavaTokenType.GTGTGTEQ -> "ushr" JavaTokenType.PLUSPLUS -> "++" JavaTokenType.MINUSMINUS -> "--" KtTokens.EQEQEQ -> "===" KtTokens.EXCLEQEQEQ -> "!==" else -> "" //System.out.println("UNSUPPORTED TOKEN TYPE: " + tokenType?.toString()) } } companion object { val EQEQ = Operator(JavaTokenType.EQEQ).assignNoPrototype() val EQ = Operator(JavaTokenType.EQ).assignNoPrototype() } } class LambdaExpression(val parameterList: ParameterList?, val block: Block) : Expression() { init { assignPrototypesFrom(block) } override fun generateCode(builder: CodeBuilder) { builder append block.lBrace append " " if (parameterList != null && !parameterList.parameters.isEmpty()) { builder.append(parameterList) .append("->") .append(if (block.statements.size > 1) "\n" else " ") .append(block.statements, "\n") } else { builder.append(block.statements, "\n") } builder append " " append block.rBrace } } class StarExpression(val operand: Expression) : Expression() { override fun generateCode(builder: CodeBuilder) { builder.append("*").appendOperand(this, operand) } } class RangeExpression(val start: Expression, val end: Expression): Expression() { override fun generateCode(builder: CodeBuilder) { builder.appendOperand(this, start).append("..").appendOperand(this, end) } } class UntilExpression(val start: Expression, val end: Expression): Expression() { override fun generateCode(builder: CodeBuilder) { builder.appendOperand(this, start).append(" until ").appendOperand(this, end) } } class DownToExpression(val start: Expression, val end: Expression): Expression() { override fun generateCode(builder: CodeBuilder) { builder.appendOperand(this, start).append(" downTo ").appendOperand(this, end) } } class ClassLiteralExpression(val type: Type): Expression() { override fun generateCode(builder: CodeBuilder) { builder.append(type).append("::class") } } fun createArrayInitializerExpression(arrayType: ArrayType, initializers: List<Expression>, needExplicitType: Boolean = true) : MethodCallExpression { val elementType = arrayType.elementType val createArrayFunction = when { elementType is PrimitiveType -> (elementType.toNotNullType().canonicalCode() + "ArrayOf").decapitalize(Locale.US) needExplicitType -> "arrayOf<" + arrayType.elementType.canonicalCode() + ">" else -> "arrayOf" } return MethodCallExpression.buildNonNull(null, createArrayFunction, ArgumentList.withNoPrototype(initializers)) }
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/Expressions.kt
2395621168
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.gitlab.mergerequest.ui.list import com.intellij.collaboration.async.nestedDisposable import com.intellij.openapi.progress.util.ProgressWindow import com.intellij.openapi.project.Project import com.intellij.ui.CollectionListModel import com.intellij.ui.ScrollPaneFactory import com.intellij.util.ui.JBUI import com.intellij.util.ui.scroll.BoundedRangeModelThresholdListener import com.intellij.vcs.log.ui.frame.ProgressStripe import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import org.jetbrains.plugins.gitlab.mergerequest.api.dto.GitLabMergeRequestShortDTO import org.jetbrains.plugins.gitlab.mergerequest.ui.GitLabMergeRequestsListViewModel import org.jetbrains.plugins.gitlab.mergerequest.ui.filters.GitLabFiltersPanelFactory import javax.swing.JComponent import javax.swing.ScrollPaneConstants import javax.swing.event.ChangeEvent internal class GitLabMergeRequestsPanelFactory { fun create(project: Project, scope: CoroutineScope, listVm: GitLabMergeRequestsListViewModel): JComponent { val listModel = collectMergeRequests(scope, listVm) val listMergeRequests = GitLabMergeRequestsListComponentFactory.create(listModel, listVm.avatarIconsProvider) val listLoaderPanel = createListLoaderPanel(scope, listVm, listMergeRequests) val progressStripe = ProgressStripe( listLoaderPanel, scope.nestedDisposable(), ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS ).apply { scope.launch { listVm.loadingState.collect { if (it) startLoadingImmediately() else stopLoading() } } } val searchPanel = createSearchPanel(scope, listVm) GitLabMergeRequestsListController(project, scope, listVm, listMergeRequests.emptyText, listLoaderPanel, progressStripe) return JBUI.Panels.simplePanel(progressStripe) .addToTop(searchPanel) .andTransparent() } private fun collectMergeRequests(scope: CoroutineScope, listVm: GitLabMergeRequestsListViewModel): CollectionListModel<GitLabMergeRequestShortDTO> { val listModel = CollectionListModel<GitLabMergeRequestShortDTO>() scope.launch { var firstEvent = true listVm.listDataFlow.collect { when (it) { is GitLabMergeRequestsListViewModel.ListDataUpdate.NewBatch -> { if (firstEvent) listModel.add(it.newList) else listModel.add(it.batch) } GitLabMergeRequestsListViewModel.ListDataUpdate.Clear -> listModel.removeAll() } firstEvent = false } } return listModel } private fun createListLoaderPanel(scope: CoroutineScope, listVm: GitLabMergeRequestsListViewModel, list: JComponent): JComponent { return ScrollPaneFactory.createScrollPane(list, true).apply { isOpaque = false viewport.isOpaque = false horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED val model = verticalScrollBar.model val listener = object : BoundedRangeModelThresholdListener(model, 0.7f) { override fun onThresholdReached() { if (listVm.canLoadMoreState.value) { listVm.requestMore() } } } model.addChangeListener(listener) scope.launch { listVm.listDataFlow.collect { when (it) { is GitLabMergeRequestsListViewModel.ListDataUpdate.NewBatch -> { if (isShowing) { listener.stateChanged(ChangeEvent(listVm)) } } GitLabMergeRequestsListViewModel.ListDataUpdate.Clear -> { if (isShowing) { listVm.requestMore() } } } } } } } private fun createSearchPanel(scope: CoroutineScope, listVm: GitLabMergeRequestsListViewModel): JComponent { return GitLabFiltersPanelFactory(listVm.filterVm).create(scope) } }
plugins/gitlab/src/org/jetbrains/plugins/gitlab/mergerequest/ui/list/GitLabMergeRequestsPanelFactory.kt
2089591302
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.SmartPsiElementPointer import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtAnnotationEntry import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.replaceFileAnnotationList import org.jetbrains.kotlin.renderer.render /** * A quick fix to add file-level annotations, e.g. `@file:OptIn(SomeExperimentalAnnotation::class)`. * * The fix either creates a new annotation or adds the argument to the existing annotation entry. * It does not check whether the annotation class allows duplicating annotations; it is the caller responsibility. * For example, only one `@file:OptIn(...)` annotation is allowed, so if this annotation entry already exists, * the caller should pass the non-null smart pointer to it as the `existingAnnotationEntry` argument. * * @param file the file where the annotation should be added * @param annotationFqName the fully qualified name of the annotation class (e.g., `kotlin.OptIn`) * @param argumentClassFqName the fully qualified name of the argument class (e.g., `SomeExperimentalAnnotation`) (optional) * @param existingAnnotationEntry a smart pointer to the existing annotation entry with the same annotation class (optional) */ open class AddFileAnnotationFix( file: KtFile, private val annotationFqName: FqName, private val argumentClassFqName: FqName? = null, private val existingAnnotationEntry: SmartPsiElementPointer<KtAnnotationEntry>? = null ) : KotlinQuickFixAction<KtFile>(file) { override fun getText(): String { val annotationName = annotationFqName.shortName().asString() val innerText = argumentClassFqName?.shortName()?.asString()?.let { "$it::class" } ?: "" val annotationText = "$annotationName($innerText)" return KotlinBundle.message("fix.add.annotation.text.containing.file", annotationText, element?.name ?: "") } override fun getFamilyName(): String = KotlinBundle.message("fix.add.annotation.family") override fun invoke(project: Project, editor: Editor?, file: KtFile) { val fileToAnnotate = element ?: return val innerText = argumentClassFqName?.render()?.let { "$it::class"} val annotationText = when (innerText) { null -> annotationFqName.render() else -> "${annotationFqName.render()}($innerText)" } val psiFactory = KtPsiFactory(project) if (fileToAnnotate.fileAnnotationList == null) { // If there are no existing file-level annotations, create an annotation list with the new annotation val newAnnotationList = psiFactory.createFileAnnotationListWithAnnotation(annotationText) val createdAnnotationList = replaceFileAnnotationList(fileToAnnotate, newAnnotationList) fileToAnnotate.addAfter(psiFactory.createWhiteSpace("\n"), createdAnnotationList) ShortenReferences.DEFAULT.process(createdAnnotationList) } else { val annotationList = fileToAnnotate.fileAnnotationList ?: return if (existingAnnotationEntry == null) { // There are file-level annotations, but the fix is expected to add a new entry val newAnnotation = psiFactory.createFileAnnotation(annotationText) annotationList.add(psiFactory.createWhiteSpace("\n")) annotationList.add(newAnnotation) ShortenReferences.DEFAULT.process(annotationList) } else if (innerText != null) { // There is an existing annotation and the non-null argument that should be added to it addArgumentToExistingAnnotation(existingAnnotationEntry, innerText) } } } /** * Add an argument to the existing annotation. * * @param annotationEntry a smart pointer to the existing annotation entry * @param argumentText the argument text */ private fun addArgumentToExistingAnnotation(annotationEntry: SmartPsiElementPointer<KtAnnotationEntry>, argumentText: String) { val entry = annotationEntry.element ?: return val existingArgumentList = entry.valueArgumentList val psiFactory = KtPsiFactory(entry.project) val newArgumentList = psiFactory.createCallArguments("($argumentText)") when { existingArgumentList == null -> // use the new argument list entry.addAfter(newArgumentList, entry.lastChild) existingArgumentList.arguments.isEmpty() -> // replace '()' with the new argument list existingArgumentList.replace(newArgumentList) else -> // add the new argument to the existing list existingArgumentList.addArgument(newArgumentList.arguments[0]) } ShortenReferences.DEFAULT.process(entry) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddFileAnnotationFix.kt
891575431
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("BlockingMethodInNonBlockingContext") package org.jetbrains.intellij.build.impl import com.intellij.diagnostic.telemetry.useWithScope2 import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.io.NioFiles import com.intellij.openapi.util.text.StringUtilRt import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.trace.Span import kotlinx.coroutines.* import org.jetbrains.intellij.build.* import org.jetbrains.intellij.build.TraceManager.spanBuilder import org.jetbrains.intellij.build.impl.productInfo.* import org.jetbrains.intellij.build.impl.support.RepairUtilityBuilder import org.jetbrains.intellij.build.io.* import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardCopyOption import java.nio.file.attribute.FileTime import java.util.concurrent.TimeUnit import java.util.function.BiPredicate import kotlin.io.path.setLastModifiedTime internal class WindowsDistributionBuilder( override val context: BuildContext, private val customizer: WindowsDistributionCustomizer, private val ideaProperties: Path?, ) : OsSpecificDistributionBuilder { private val icoFile: Path? init { val icoPath = (if (context.applicationInfo.isEAP) customizer.icoPathForEAP else null) ?: customizer.icoPath icoFile = icoPath?.let { Path.of(icoPath) } } override val targetOs: OsFamily get() = OsFamily.WINDOWS override suspend fun copyFilesForOsDistribution(targetPath: Path, arch: JvmArchitecture) { val distBinDir = targetPath.resolve("bin") withContext(Dispatchers.IO) { Files.createDirectories(distBinDir) val sourceBinDir = context.paths.communityHomeDir.resolve("bin/win") FileSet(sourceBinDir.resolve(arch.dirName)) .includeAll() .copyToDir(distBinDir) if (context.includeBreakGenLibraries()) { // There's near zero chance that on x64 hardware arm64 library will be needed, but it's only 70 KiB. // Contrary on arm64 hardware all three library versions could be used, so we copy them all. @Suppress("SpellCheckingInspection") FileSet(sourceBinDir) .include("breakgen*.dll") .copyToDir(distBinDir) } generateBuildTxt(context, targetPath) copyDistFiles(context = context, newDir = targetPath, os = OsFamily.WINDOWS, arch = arch) Files.writeString(distBinDir.resolve(ideaProperties!!.fileName), StringUtilRt.convertLineSeparators(Files.readString(ideaProperties), "\r\n")) if (icoFile != null) { Files.copy(icoFile, distBinDir.resolve("${context.productProperties.baseFileName}.ico"), StandardCopyOption.REPLACE_EXISTING) } if (customizer.includeBatchLaunchers) { generateScripts(distBinDir, arch) } generateVMOptions(distBinDir) buildWinLauncher(targetPath, arch) customizer.copyAdditionalFiles(context, targetPath.toString(), arch) } context.executeStep(spanBuilder = spanBuilder("sign windows"), stepId = BuildOptions.WIN_SIGN_STEP) { val nativeFiles = ArrayList<Path>() withContext(Dispatchers.IO) { Files.find(distBinDir, Integer.MAX_VALUE, BiPredicate { file, attributes -> if (attributes.isRegularFile) { val path = file.toString() path.endsWith(".exe") || path.endsWith(".dll") } else { false } }).use { stream -> stream.forEach(nativeFiles::add) } } Span.current().setAttribute(AttributeKey.stringArrayKey("files"), nativeFiles.map(Path::toString)) customizer.getBinariesToSign(context).mapTo(nativeFiles) { targetPath.resolve(it) } if (nativeFiles.isNotEmpty()) { withContext(Dispatchers.IO) { context.signFiles(nativeFiles, BuildOptions.WIN_SIGN_OPTIONS) } } } } override suspend fun buildArtifacts(osAndArchSpecificDistPath: Path, arch: JvmArchitecture) { copyFilesForOsDistribution(osAndArchSpecificDistPath, arch) val suffix = if (arch == JvmArchitecture.x64) "" else "-${arch.fileSuffix}" val runtimeDir = context.bundledRuntime.extract(BundledRuntimeImpl.getProductPrefix(context), OsFamily.WINDOWS, arch) @Suppress("SpellCheckingInspection") val vcRtDll = runtimeDir.resolve("jbr/bin/msvcp140.dll") check(Files.exists(vcRtDll)) { "VS C++ Runtime DLL (${vcRtDll.fileName}) not found in ${vcRtDll.parent}.\n" + "If JBR uses a newer version, please correct the path in this code and update Windows Launcher build configuration.\n" + "If DLL was relocated to another place, please correct the path in this code." } copyFileToDir(vcRtDll, osAndArchSpecificDistPath.resolve("bin")) var exePath: Path? = null val zipWithJbrPath = coroutineScope { Files.walk(osAndArchSpecificDistPath).use { tree -> val fileTime = FileTime.from(context.options.buildDateInSeconds, TimeUnit.SECONDS) tree.forEach { it.setLastModifiedTime(fileTime) } } val zipWithJbrPathTask = if (customizer.buildZipArchiveWithBundledJre) { createBuildWinZipTask(runtimeDir = runtimeDir, zipNameSuffix = suffix + customizer.zipArchiveWithBundledJreSuffix, winDistPath = osAndArchSpecificDistPath, arch = arch, customizer = customizer, context = context) } else { null } if (customizer.buildZipArchiveWithoutBundledJre) { createBuildWinZipTask(runtimeDir = null, zipNameSuffix = suffix + customizer.zipArchiveWithoutBundledJreSuffix, winDistPath = osAndArchSpecificDistPath, arch = arch, customizer = customizer, context = context) } context.executeStep(spanBuilder("build Windows installer") .setAttribute("arch", arch.dirName), BuildOptions.WINDOWS_EXE_INSTALLER_STEP) { val productJsonDir = Files.createTempDirectory(context.paths.tempDir, "win-product-info") validateProductJson(jsonText = generateProductJson(targetDir = productJsonDir, arch = arch, isRuntimeIncluded = true, context = context), relativePathToProductJson = "", installationDirectories = listOf(context.paths.distAllDir, osAndArchSpecificDistPath, runtimeDir), installationArchives = emptyList(), context = context) exePath = buildNsisInstaller(winDistPath = osAndArchSpecificDistPath, additionalDirectoryToInclude = productJsonDir, suffix = suffix, customizer = customizer, runtimeDir = runtimeDir, context = context) } zipWithJbrPathTask?.await() } if (zipWithJbrPath != null && exePath != null) { if (context.options.isInDevelopmentMode) { Span.current().addEvent("comparing .zip and .exe skipped in development mode") } else if (!SystemInfoRt.isLinux) { Span.current().addEvent("comparing .zip and .exe is not supported on ${SystemInfoRt.OS_NAME}") } else { checkThatExeInstallerAndZipWithJbrAreTheSame(zipPath = zipWithJbrPath, exePath = exePath!!, arch = arch, tempDir = context.paths.tempDir, context = context) } return } } private fun generateScripts(distBinDir: Path, arch: JvmArchitecture) { val fullName = context.applicationInfo.productName val baseName = context.productProperties.baseFileName val scriptName = "${baseName}.bat" val vmOptionsFileName = "${baseName}64.exe" val classPathJars = context.bootClassPathJarNames var classPath = "SET \"CLASS_PATH=%IDE_HOME%\\lib\\${classPathJars[0]}\"" for (i in 1 until classPathJars.size) { classPath += "\nSET \"CLASS_PATH=%CLASS_PATH%;%IDE_HOME%\\lib\\${classPathJars[i]}\"" } var additionalJvmArguments = context.getAdditionalJvmArguments(OsFamily.WINDOWS, arch, isScript = true) if (!context.xBootClassPathJarNames.isEmpty()) { additionalJvmArguments = additionalJvmArguments.toMutableList() val bootCp = context.xBootClassPathJarNames.joinToString(separator = ";") { "%IDE_HOME%\\lib\\${it}" } additionalJvmArguments.add("\"-Xbootclasspath/a:$bootCp\"") } val winScripts = context.paths.communityHomeDir.resolve("platform/build-scripts/resources/win/scripts") val actualScriptNames = Files.newDirectoryStream(winScripts).use { dirStream -> dirStream.map { it.fileName.toString() }.sorted() } @Suppress("SpellCheckingInspection") val expectedScriptNames = listOf("executable-template.bat", "format.bat", "inspect.bat", "ltedit.bat") check(actualScriptNames == expectedScriptNames) { "Expected script names '${expectedScriptNames.joinToString(separator = " ")}', " + "but got '${actualScriptNames.joinToString(separator = " ")}' " + "in $winScripts. Please review ${WindowsDistributionBuilder::class.java.name} and update accordingly" } substituteTemplatePlaceholders( inputFile = winScripts.resolve("executable-template.bat"), outputFile = distBinDir.resolve(scriptName), placeholder = "@@", values = listOf( Pair("product_full", fullName), Pair("product_uc", context.productProperties.getEnvironmentVariableBaseName(context.applicationInfo)), Pair("product_vendor", context.applicationInfo.shortCompanyName), Pair("vm_options", vmOptionsFileName), Pair("system_selector", context.systemSelector), Pair("ide_jvm_args", additionalJvmArguments.joinToString(separator = " ")), Pair("class_path", classPath), Pair("base_name", baseName), Pair("main_class_name", context.productProperties.mainClassName), ) ) val inspectScript = context.productProperties.inspectCommandName @Suppress("SpellCheckingInspection") for (fileName in listOf("format.bat", "inspect.bat", "ltedit.bat")) { val sourceFile = winScripts.resolve(fileName) val targetFile = distBinDir.resolve(fileName) substituteTemplatePlaceholders( inputFile = sourceFile, outputFile = targetFile, placeholder = "@@", values = listOf( Pair("product_full", fullName), Pair("script_name", scriptName), ) ) } if (inspectScript != "inspect") { val targetPath = distBinDir.resolve("${inspectScript}.bat") Files.move(distBinDir.resolve("inspect.bat"), targetPath) context.patchInspectScript(targetPath) } FileSet(distBinDir) .include("*.bat") .enumerate() .forEach { file -> transformFile(file) { target -> @Suppress("BlockingMethodInNonBlockingContext") Files.writeString(target, toDosLineEndings(Files.readString(file))) } } } private fun generateVMOptions(distBinDir: Path) { val productProperties = context.productProperties val fileName = "${productProperties.baseFileName}64.exe.vmoptions" val vmOptions = VmOptionsGenerator.computeVmOptions(context.applicationInfo.isEAP, productProperties) VmOptionsGenerator.writeVmOptions(distBinDir.resolve(fileName), vmOptions, "\r\n") } private suspend fun buildWinLauncher(winDistPath: Path, arch: JvmArchitecture) { spanBuilder("build Windows executable").useWithScope2 { val executableBaseName = "${context.productProperties.baseFileName}64" val launcherPropertiesPath = context.paths.tempDir.resolve("launcher-${arch.dirName}.properties") @Suppress("SpellCheckingInspection") val vmOptions = context.getAdditionalJvmArguments(OsFamily.WINDOWS, arch) + listOf("-Dide.native.launcher=true") val productName = context.applicationInfo.shortProductName val classPath = context.bootClassPathJarNames.joinToString(separator = ";") { "%IDE_HOME%\\\\lib\\\\${it}" } val bootClassPath = context.xBootClassPathJarNames.joinToString(separator = ";") { "%IDE_HOME%\\\\lib\\\\${it}" } val envVarBaseName = context.productProperties.getEnvironmentVariableBaseName(context.applicationInfo) val icoFilesDirectory = context.paths.tempDir.resolve("win-launcher-ico-${arch.dirName}") val appInfoForLauncher = generateApplicationInfoForLauncher(context.applicationInfo.appInfoXml, icoFilesDirectory) @Suppress("SpellCheckingInspection") Files.writeString(launcherPropertiesPath, """ IDS_JDK_ONLY=${context.productProperties.toolsJarRequired} IDS_JDK_ENV_VAR=${envVarBaseName}_JDK IDS_VM_OPTIONS_PATH=%APPDATA%\\\\${context.applicationInfo.shortCompanyName}\\\\${context.systemSelector} IDS_VM_OPTION_ERRORFILE=-XX:ErrorFile=%USERPROFILE%\\\\java_error_in_${executableBaseName}_%p.log IDS_VM_OPTION_HEAPDUMPPATH=-XX:HeapDumpPath=%USERPROFILE%\\\\java_error_in_${executableBaseName}.hprof IDS_PROPS_ENV_VAR=${envVarBaseName}_PROPERTIES IDS_VM_OPTIONS_ENV_VAR=${envVarBaseName}_VM_OPTIONS IDS_ERROR_LAUNCHING_APP=Error launching $productName IDS_VM_OPTIONS=${vmOptions.joinToString(separator = " ")} IDS_CLASSPATH_LIBS=${classPath} IDS_BOOTCLASSPATH_LIBS=${bootClassPath} IDS_INSTANCE_ACTIVATION=${context.productProperties.fastInstanceActivation} IDS_MAIN_CLASS=${context.productProperties.mainClassName.replace('.', '/')} """.trimIndent().trim()) val communityHome = context.paths.communityHome val inputPath = "${communityHome}/platform/build-scripts/resources/win/launcher/${arch.dirName}/WinLauncher.exe" val outputPath = winDistPath.resolve("bin/${executableBaseName}.exe") val classpath = ArrayList<String>() val generatorClasspath = context.getModuleRuntimeClasspath(module = context.findRequiredModule("intellij.tools.launcherGenerator"), forTests = false) classpath.addAll(generatorClasspath) sequenceOf(context.findApplicationInfoModule(), context.findRequiredModule("intellij.platform.icons")) .flatMap { it.sourceRoots } .forEach { root -> classpath.add(root.file.absolutePath) } for (p in context.productProperties.brandingResourcePaths) { classpath.add(p.toString()) } classpath.add(icoFilesDirectory.toString()) runIdea( context = context, mainClass = "com.pme.launcher.LauncherGeneratorMain", args = listOf( inputPath, appInfoForLauncher.toString(), "$communityHome/native/WinLauncher/resource.h", launcherPropertiesPath.toString(), icoFile?.fileName?.toString() ?: " ", outputPath.toString(), ), jvmArgs = listOf("-Djava.awt.headless=true"), classPath = classpath ) } } /** * Generates ApplicationInfo.xml file for launcher generator which contains link to proper *.ico file. * todo pass path to ico file to LauncherGeneratorMain directly (probably after IDEA-196705 is fixed). */ private fun generateApplicationInfoForLauncher(appInfo: String, icoFilesDirectory: Path): Path { Files.createDirectories(icoFilesDirectory) if (icoFile != null) { Files.copy(icoFile, icoFilesDirectory.resolve(icoFile.fileName), StandardCopyOption.REPLACE_EXISTING) } val patchedFile = icoFilesDirectory.resolve("win-launcher-application-info.xml") Files.writeString(patchedFile, appInfo) return patchedFile } } private suspend fun checkThatExeInstallerAndZipWithJbrAreTheSame(zipPath: Path, exePath: Path, arch: JvmArchitecture, tempDir: Path, context: BuildContext) { Span.current().addEvent("compare ${zipPath.fileName} vs. ${exePath.fileName}") val tempZip = withContext(Dispatchers.IO) { Files.createTempDirectory(tempDir, "zip-${arch.dirName}") } val tempExe = withContext(Dispatchers.IO) { Files.createTempDirectory(tempDir, "exe-${arch.dirName}") } try { withContext(Dispatchers.IO) { runProcess(args = listOf("7z", "x", "-bd", exePath.toString()), workingDir = tempExe) runProcess(args = listOf("unzip", "-q", zipPath.toString()), workingDir = tempZip) @Suppress("SpellCheckingInspection") NioFiles.deleteRecursively(tempExe.resolve("\$PLUGINSDIR")) runProcess(args = listOf("diff", "-q", "-r", tempZip.toString(), tempExe.toString())) } if (!context.options.buildStepsToSkip.contains(BuildOptions.REPAIR_UTILITY_BUNDLE_STEP)) { RepairUtilityBuilder.generateManifest(context, tempExe, OsFamily.WINDOWS, arch) } } finally { withContext(Dispatchers.IO + NonCancellable) { NioFiles.deleteRecursively(tempZip) NioFiles.deleteRecursively(tempExe) } } } private fun CoroutineScope.createBuildWinZipTask(runtimeDir: Path?, zipNameSuffix: String, winDistPath: Path, arch: JvmArchitecture, customizer: WindowsDistributionCustomizer, context: BuildContext): Deferred<Path> { return async(Dispatchers.IO) { val baseName = context.productProperties.getBaseArtifactName(context.applicationInfo, context.buildNumber) val targetFile = context.paths.artifactDir.resolve("${baseName}${zipNameSuffix}.zip") spanBuilder("build Windows ${zipNameSuffix}.zip distribution") .setAttribute("targetFile", targetFile.toString()) .setAttribute("arch", arch.dirName) .useWithScope2 { val productJsonDir = context.paths.tempDir.resolve("win.dist.product-info.json.zip$zipNameSuffix") generateProductJson(targetDir = productJsonDir, arch = arch, isRuntimeIncluded = runtimeDir != null, context = context) val zipPrefix = customizer.getRootDirectoryName(context.applicationInfo, context.buildNumber) val dirs = listOfNotNull(context.paths.distAllDir, winDistPath, productJsonDir, runtimeDir) val dirMap = dirs.associateWithTo(LinkedHashMap(dirs.size)) { zipPrefix } if (context.options.compressZipFiles) { zipWithCompression(targetFile = targetFile, dirs = dirMap) } else { zip(targetFile = targetFile, dirs = dirMap, addDirEntriesMode = AddDirEntriesMode.NONE) } checkInArchive(archiveFile = targetFile, pathInArchive = zipPrefix, context = context) context.notifyArtifactWasBuilt(targetFile) targetFile } } } private fun generateProductJson(targetDir: Path, isRuntimeIncluded: Boolean, arch: JvmArchitecture, context: BuildContext): String { val launcherPath = "bin/${context.productProperties.baseFileName}64.exe" val vmOptionsPath = "bin/${context.productProperties.baseFileName}64.exe.vmoptions" val javaExecutablePath = if (isRuntimeIncluded) "jbr/bin/java.exe" else null val file = targetDir.resolve(PRODUCT_INFO_FILE_NAME) Files.createDirectories(targetDir) val json = generateMultiPlatformProductJson( "bin", context.builtinModule, listOf(ProductInfoLaunchData( os = OsFamily.WINDOWS.osName, arch = arch.dirName, launcherPath = launcherPath, javaExecutablePath = javaExecutablePath, vmOptionsFilePath = vmOptionsPath, startupWmClass = null, bootClassPathJarNames = context.bootClassPathJarNames, additionalJvmArguments = context.getAdditionalJvmArguments(OsFamily.WINDOWS, arch))), context) Files.writeString(file, json) file.setLastModifiedTime(FileTime.from(context.options.buildDateInSeconds, TimeUnit.SECONDS)) return json } private fun toDosLineEndings(x: String): String = x.replace("\r", "").replace("\n", "\r\n")
platform/build-scripts/src/org/jetbrains/intellij/build/impl/WindowsDistributionBuilder.kt
1849104158
package com.nononsenseapps.feeder.ui.compose.text import io.mockk.every import io.mockk.mockk import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue import org.jsoup.nodes.Element import org.junit.Test class HtmlToComposableUnitTest { private val element = mockk<Element>() @Test fun findImageSrcWithNoSrc() { every { element.attr("srcset") } returns null every { element.attr("abs:src") } returns null val result = getImageSource("http://foo", element) assertFalse(result.hasImage) } @Test fun findImageOnlySrc() { every { element.attr("srcset") } returns null every { element.attr("abs:src") } returns "http://foo/image.jpg" val result = getImageSource("http://foo", element) assertTrue(result.hasImage) assertEquals("http://foo/image.jpg", result.getBestImageForMaxSize(1, 1.0f)) } @Test fun findImageOnlySingleSrcSet() { every { element.attr("srcset") } returns "image.jpg" every { element.attr("abs:src") } returns null val result = getImageSource("http://foo", element) assertTrue(result.hasImage) assertEquals("http://foo/image.jpg", result.getBestImageForMaxSize(1, 1.0f)) } @Test fun findImageBestMinSrcSet() { every { element.attr("srcset") } returns "header640.png 640w, header960.png 960w, header2x.png 2x, header3.0x.png 3.0x, header.png" every { element.attr("abs:src") } returns null val result = getImageSource("http://foo", element) assertTrue(result.hasImage) val maxSize = 1 assertEquals("http://foo/header.png", result.getBestImageForMaxSize(maxSize, 1.0f)) } @Test fun findImageBest640SrcSet() { every { element.attr("srcset") } returns "header640.png 640w, header960.png 960w, header2x.png 2x, header3.0x.png 3.0x, header.png" every { element.attr("abs:src") } returns null val result = getImageSource("http://foo", element) assertTrue(result.hasImage) val maxSize = 640 assertEquals("http://foo/header640.png", result.getBestImageForMaxSize(maxSize, 1.0f)) } @Test fun findImageBest960SrcSet() { every { element.attr("srcset") } returns "header640.png 640w, header960.png 960w, header2x.png 2x, header3.0x.png 3.0x, header.png" every { element.attr("abs:src") } returns null val result = getImageSource("http://foo", element) assertTrue(result.hasImage) val maxSize = 900 assertEquals("http://foo/header960.png", result.getBestImageForMaxSize(maxSize, 8.0f)) } @Test fun findImageBest650SrcSet() { every { element.attr("srcset") } returns "header640.png 640w, header960.png 960w, header2x.png 2x, header3.0x.png 3.0x, header.png" every { element.attr("abs:src") } returns null val result = getImageSource("http://foo", element) assertTrue(result.hasImage) val maxSize = 650 assertEquals("http://foo/header640.png", result.getBestImageForMaxSize(maxSize, 7.0f)) } @Test fun findImageBest950SrcSet() { every { element.attr("srcset") } returns "header640.png 640w, header960.png 960w, header2x.png 2x, header3.0x.png 3.0x, header.png" every { element.attr("abs:src") } returns null val result = getImageSource("http://foo", element) assertTrue(result.hasImage) val maxSize = 950 assertEquals("http://foo/header960.png", result.getBestImageForMaxSize(maxSize, 7.0f)) } @Test fun findImageBest1500SrcSet() { every { element.attr("srcset") } returns "header640.png 640w, header960.png 960w, header2x.png 2x, header3.0x.png 3.0x, header.png" every { element.attr("abs:src") } returns null val result = getImageSource("http://foo", element) assertTrue(result.hasImage) val maxSize = 1500 assertEquals("http://foo/header960.png", result.getBestImageForMaxSize(maxSize, 8.0f)) } @Test fun findImageBest3xSrcSet() { every { element.attr("srcset") } returns "header2x.png 2x, header3.0x.png 3.0x, header.png" every { element.attr("abs:src") } returns null val result = getImageSource("http://foo", element) assertTrue(result.hasImage) val maxSize = 1 assertEquals("http://foo/header3.0x.png", result.getBestImageForMaxSize(maxSize, 3.0f)) } @Test fun findImageBest1xSrcSet() { every { element.attr("srcset") } returns "header2x.png 2x, header3.0x.png 3.0x, header.png" every { element.attr("abs:src") } returns null val result = getImageSource("http://foo", element) assertTrue(result.hasImage) val maxSize = 1 assertEquals("http://foo/header.png", result.getBestImageForMaxSize(maxSize, 1.0f)) } @Test fun findImageBestJunkSrcSet() { every { element.attr("srcset") } returns "header2x.png 2Y" every { element.attr("abs:src") } returns "http://foo/header.png" val result = getImageSource("http://foo", element) assertTrue(result.hasImage) val maxSize = 1 assertEquals("http://foo/header.png", result.getBestImageForMaxSize(maxSize, 1.0f)) } @Test fun findImageBestPoliticoSrcSet() { every { element.attr("srcset") } returns "https://www.politico.eu/cdn-cgi/image/width=1024,quality=80,onerror=redirect,format=auto/wp-content/uploads/2022/10/07/thumbnail_Kal-econ-cartoon-10-7-22synd.jpeg 1024w, https://www.politico.eu/cdn-cgi/image/width=300,quality=80,onerror=redirect,format=auto/wp-content/uploads/2022/10/07/thumbnail_Kal-econ-cartoon-10-7-22synd.jpeg 300w, https://www.politico.eu/cdn-cgi/image/width=1280,quality=80,onerror=redirect,format=auto/wp-content/uploads/2022/10/07/thumbnail_Kal-econ-cartoon-10-7-22synd.jpeg 1280w" every { element.attr("abs:src") } returns "https://www.politico.eu/wp-content/uploads/2022/10/07/thumbnail_Kal-econ-cartoon-10-7-22synd-1024x683.jpeg" every { element.attr("width") } returns "1024" every { element.attr("height") } returns "683" val result = getImageSource("https://www.politico.eu/feed/", element) assertTrue(result.hasImage) val maxSize = 1024 assertEquals( "https://www.politico.eu/cdn-cgi/image/width=1024,quality=80,onerror=redirect,format=auto/wp-content/uploads/2022/10/07/thumbnail_Kal-econ-cartoon-10-7-22synd.jpeg", result.getBestImageForMaxSize( maxSize, 8.0f ) ) } }
app/src/test/java/com/nononsenseapps/feeder/ui/compose/text/HtmlToComposableUnitTest.kt
2322610594
package com.nononsenseapps.feeder.ui.compose.text import android.content.res.Resources import android.text.Annotation import android.text.SpannedString import androidx.annotation.StringRes import androidx.compose.runtime.Composable import androidx.compose.runtime.ReadOnlyComposable import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.core.text.getSpans import com.nononsenseapps.feeder.ui.compose.theme.LinkTextStyle @Composable @ReadOnlyComposable fun resources(): Resources { LocalConfiguration.current return LocalContext.current.resources } @Composable fun annotatedStringResource(@StringRes id: Int): AnnotatedString { val resources = resources() val text = resources.getText(id) as SpannedString return buildAnnotatedString { this.append(text.toString()) for (annotation in text.getSpans<Annotation>()) { when (annotation.key) { "style" -> { getSpanStyle(annotation.value)?.let { spanStyle -> addStyle( spanStyle, text.getSpanStart(annotation), text.getSpanEnd(annotation) ) } } } } } } @Composable private fun getSpanStyle(name: String?): SpanStyle? { return when (name) { "link" -> LinkTextStyle().toSpanStyle() else -> null } }
app/src/main/java/com/nononsenseapps/feeder/ui/compose/text/Extensions.kt
2318978134
package com.jetbrains.packagesearch.intellij.plugin.extensions.gradle.configuration import com.intellij.openapi.components.BaseState import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.project.Project import com.intellij.util.xmlb.annotations.OptionTag import com.jetbrains.packagesearch.intellij.plugin.configuration.PackageSearchGeneralConfiguration fun packageSearchGradleConfigurationForProject(project: Project): PackageSearchGradleConfiguration = ServiceManager.getService(project, PackageSearchGradleConfiguration::class.java) @State( name = "PackageSearchGradleConfiguration", storages = [(Storage(PackageSearchGeneralConfiguration.StorageFileName))] ) class PackageSearchGradleConfiguration : BaseState(), PersistentStateComponent<PackageSearchGradleConfiguration> { override fun getState(): PackageSearchGradleConfiguration? = this override fun loadState(state: PackageSearchGradleConfiguration) { this.copyFrom(state) } @get:OptionTag("GRADLE_SCOPES") var gradleScopes by string(PackageSearchGradleConfigurationDefaults.GradleScopes) @get:OptionTag("GRADLE_SCOPES_DEFAULT") var defaultGradleScope by string(PackageSearchGradleConfigurationDefaults.GradleScope) @get:OptionTag("UPDATE_SCOPES_ON_USE") var updateScopesOnUsage by property(true) fun determineDefaultGradleScope(): String = if (!defaultGradleScope.isNullOrEmpty()) { defaultGradleScope!! } else { PackageSearchGradleConfigurationDefaults.GradleScope } fun addGradleScope(scope: String) { val currentScopes = getGradleScopes() if (!currentScopes.contains(scope)) { gradleScopes = currentScopes.joinToString(",") + ",$scope" this.incrementModificationCount() } } fun getGradleScopes(): List<String> { var scopes = gradleScopes.orEmpty().split(",", ";", "\n") .map { it.trim() } .filter { it.isNotEmpty() } if (scopes.isEmpty()) { scopes = PackageSearchGradleConfigurationDefaults.GradleScopes.split(",", ";", "\n") .map { it.trim() } .filter { it.isNotEmpty() } } return scopes } }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensions/gradle/configuration/PackageSearchGradleConfiguration.kt
3819633245
// 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.openapi.projectRoots.impl.jdkDownloader import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.WriteAction import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.projectRoots.JavaSdk import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.SdkType import com.intellij.openapi.roots.ui.configuration.UnknownSdk import com.intellij.testFramework.IdeaTestUtil import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase import com.intellij.util.ThrowableRunnable import com.intellij.util.lang.JavaVersion import org.jetbrains.annotations.NotNull import org.jetbrains.jps.model.java.LanguageLevel import org.junit.Assert import org.junit.Test import java.util.function.Predicate class JdkAutoTest : JavaCodeInsightFixtureTestCase() { private lateinit var indicator: ProgressIndicator private lateinit var jdks : Map<Int, Sdk> override fun setUp() { super.setUp() indicator = EmptyProgressIndicator() val values : Array<LanguageLevel> = LanguageLevel.values() jdks = values.filterNot { it.isPreview }.map { val javaVersion = it.toJavaVersion() val sdk = registerMockJdk(javaVersion) javaVersion.feature to sdk }.toMap() } @Test fun `test '1_8' jdk`() { val resolver = JdkAuto().createResolverImpl(project, indicator) requireNotNull(resolver) val proposal = resolver.proposeLocalFix( SdkRequest(mySdkName = "1.8"), indicator ) requireNotNull(proposal) Assert.assertEquals(jdks.getValue(8).homePath, proposal.existingSdkHome) } @Test fun `test '8' jdk`() { val resolver = JdkAuto().createResolverImpl(project, indicator) requireNotNull(resolver) val proposal = resolver.proposeLocalFix( SdkRequest(mySdkName = "8"), indicator ) requireNotNull(proposal) Assert.assertEquals(jdks.getValue(8).homePath, proposal.existingSdkHome) } @Test fun `test '11' jdk`() { val resolver = JdkAuto().createResolverImpl(project, indicator) requireNotNull(resolver) val proposal = resolver.proposeLocalFix( SdkRequest(mySdkName = "11"), indicator ) requireNotNull(proposal) Assert.assertEquals(jdks.getValue(11).homePath, proposal.existingSdkHome) } @Test fun `test 'IDEA jdk' Must Not Suggest Any SDK`() { val resolver = JdkAuto().createResolverImpl(project, indicator) requireNotNull(resolver) val proposal = resolver.proposeLocalFix( SdkRequest(mySdkName = "IDEA jdk"), indicator ) Assert.assertNull(proposal) } @Test fun `test 'IDEA jdk' Must Not Suggest Any SDK 2`() { val resolver = JdkAuto().createResolverImpl(project, indicator) requireNotNull(resolver) val proposal = resolver.proposeLocalFix( SdkRequest(mySdkName = "IDEA jdk", mySdkHomePredicate = Predicate { true }), indicator ) Assert.assertNull(proposal) } @Test fun `test with filter jdk`() { val resolver = JdkAuto().createResolverImpl(project, indicator) requireNotNull(resolver) val proposal = resolver.proposeLocalFix( SdkRequest(mySdkVersionPredicate = Predicate { true }), indicator ) requireNotNull(proposal) //the most recent JDK should be returned Assert.assertEquals(jdks.getValue(jdks.keys.max()!!).homePath, proposal.existingSdkHome) } @Test fun `test most recent Jdk with same feature version`() { val resolver = JdkAuto().createResolverImpl(project, indicator) requireNotNull(resolver) registerMockJdk(JavaVersion.tryParse("11.0.5")!!) val v7 = registerMockJdk(JavaVersion.tryParse("11.0.7")!!) val proposal = resolver.proposeLocalFix( SdkRequest(mySdkName = "11"), indicator ) requireNotNull(proposal) //the most recent JDK should be returned Assert.assertEquals(JavaVersion.tryParse(v7.versionString)!!, JavaVersion.tryParse(proposal.versionString)!!) } private fun registerMockJdk(javaVersion: @NotNull JavaVersion): Sdk { val sdk = IdeaTestUtil.getMockJdk(javaVersion) val jdkTable = ProjectJdkTable.getInstance() val foundJdk = jdkTable.findJdk(sdk.name) if (foundJdk != null) return sdk val addSdk = ThrowableRunnable<RuntimeException> { jdkTable.addJdk(sdk, myFixture.projectDisposable) } if (ApplicationManager.getApplication().isWriteAccessAllowed) { addSdk.run() } else { WriteAction.run(addSdk) } return sdk } private data class SdkRequest( val mySdkType: SdkType = JavaSdk.getInstance(), val mySdkName: String? = null, val mySdkVersionPredicate :Predicate<String>? = null, val mySdkHomePredicate: Predicate<String>? = null ): UnknownSdk { override fun getSdkType() = mySdkType override fun getSdkName() = mySdkName ?: super.getSdkName() override fun getSdkVersionStringPredicate() = mySdkVersionPredicate ?: super.getSdkVersionStringPredicate() override fun getSdkHomePredicate(): Predicate<String>? = mySdkHomePredicate ?: super.getSdkHomePredicate() } }
java/idea-ui/testSrc/com/intellij/openapi/projectRoots/impl/jdkDownloader/JdkAutoTest.kt
2010635397
package me.nya_n.notificationnotifier.domain.usecase import android.content.Context import android.net.Uri import com.google.gson.Gson import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import me.nya_n.notificationnotifier.data.repository.AppRepository import me.nya_n.notificationnotifier.data.repository.UserSettingRepository import me.nya_n.notificationnotifier.data.repository.source.DB import me.nya_n.notificationnotifier.model.Backup import java.io.BufferedReader import java.io.InputStreamReader /** * 外部ストレージのバックアップからデータを復元 */ class ImportDataUseCase( private val userSettingRepository: UserSettingRepository, private val appRepository: AppRepository, ) { suspend operator fun invoke(context: Context, uri: Uri): Result<Unit> { return runCatching { val sb = StringBuilder() withContext(Dispatchers.IO) { context.contentResolver.openInputStream(uri).use { input -> BufferedReader(InputStreamReader(input)).use { reader -> sb.append(reader.readLine()) } } } val json = sb.toString() val backup = Gson().fromJson(json, Backup::class.java) if (backup.version != DB.version()) { throw RuntimeException("bad version.") } userSettingRepository.saveUserSetting(backup.setting) appRepository.clearAll() backup.targets.forEach { appRepository.addTargetApp(it) } backup.filterCondition.forEach { appRepository.saveFilterCondition(it) } } } }
AndroidApp/domain/src/main/java/me/nya_n/notificationnotifier/domain/usecase/ImportDataUseCase.kt
1650582667
package ch.difty.scipamato.publ.persistence.paper import ch.difty.scipamato.common.persistence.AbstractFilterConditionMapper import ch.difty.scipamato.common.persistence.FilterConditionMapper import ch.difty.scipamato.publ.db.tables.Paper import ch.difty.scipamato.publ.db.tables.records.PaperRecord import ch.difty.scipamato.publ.entity.Code import ch.difty.scipamato.publ.entity.filter.PublicPaperFilter import org.jooq.Condition import org.jooq.TableField import org.jooq.impl.DSL import org.jooq.impl.SQLDataType import java.util.regex.Matcher import java.util.regex.Pattern private const val RE_QUOTE = "\"" private val QUOTED = Pattern.compile("$RE_QUOTE([^$RE_QUOTE]+)$RE_QUOTE") private const val QUOTED_GROUP_INDEX = 1 @FilterConditionMapper class PublicPaperFilterConditionMapper : AbstractFilterConditionMapper<PublicPaperFilter>() { override fun internalMap(filter: PublicPaperFilter): List<Condition> { val conditions = mutableListOf<Condition>() filter.number?.let { conditions.add(Paper.PAPER.NUMBER.eq(it)) } filter.authorMask?.let { conditions.addAll(Paper.PAPER.AUTHORS.tokenize(it)) } filter.titleMask?.let { conditions.addAll(Paper.PAPER.TITLE.tokenize(it)) } filter.methodsMask?.let { conditions.addAll(Paper.PAPER.METHODS.tokenize(it)) } if (filter.publicationYearFrom != null) { if (hasNoOrIdenticalPubYearUntil(filter)) { conditions.add(Paper.PAPER.PUBLICATION_YEAR.eq(filter.publicationYearFrom)) } else { conditions.add( Paper.PAPER.PUBLICATION_YEAR.between(filter.publicationYearFrom, filter.publicationYearUntil)) } } else if (filter.publicationYearUntil != null) { conditions.add(Paper.PAPER.PUBLICATION_YEAR.le(filter.publicationYearUntil)) } filter.populationCodes?.let { codes -> val ids = codes.map { it.id }.toTypedArray() conditions.add(Paper.PAPER.CODES_POPULATION.contains(ids)) } filter.studyDesignCodes?.let { codes -> val ids = codes.map { it.id }.toTypedArray() conditions.add(Paper.PAPER.CODES_STUDY_DESIGN.contains(ids)) } if (filter.codesOfClass1 != null || filter.codesOfClass2 != null || filter.codesOfClass3 != null || filter.codesOfClass4 != null || filter.codesOfClass5 != null || filter.codesOfClass6 != null || filter.codesOfClass7 != null || filter.codesOfClass8 != null) { val allCodes = filter.allCodes() if (allCodes.isNotEmpty()) conditions.add(allCodes.toCondition()) } return conditions } private fun hasNoOrIdenticalPubYearUntil(filter: PublicPaperFilter) = filter.publicationYearUntil == null || filter.publicationYearFrom == filter.publicationYearUntil /* * Currently does not allow to mix quoted and unquoted terms. If this will * become necessary we might have to implement a proper tokenization of the * search term, as was done in core with the SearchTerm hierarchy. */ private fun TableField<PaperRecord, String>.tokenize(mask: String): List<Condition> { val m = QUOTED.matcher(mask) val (conditions, done) = tokenizeQuoted(m) return conditions + if (!done) tokenizeUnquoted(mask) else emptyList() } private fun TableField<PaperRecord, String>.tokenizeQuoted(m: Matcher): Pair<List<Condition>, Boolean> { val conditions = mutableListOf<Condition>() var term: String? = null while (m.find()) { term = m.group(QUOTED_GROUP_INDEX) conditions.add(likeIgnoreCase("%$term%")) } return Pair(conditions, term != null) } private fun TableField<PaperRecord, String>.tokenizeUnquoted(mask: String): List<Condition> { val conditions = mutableListOf<Condition>() if (!mask.contains(" ")) conditions.add(likeIgnoreCase("%$mask%")) else for (t in mask.split(" ").toTypedArray()) { val token = t.trim { it <= ' ' } if (token.isNotEmpty()) conditions.add(likeIgnoreCase("%$token%")) } return conditions } private fun PublicPaperFilter.allCodes() = with(this) { codesOfClass1.codesNullSafe() + codesOfClass2.codesNullSafe() + codesOfClass3.codesNullSafe() + codesOfClass4.codesNullSafe() + codesOfClass5.codesNullSafe() + codesOfClass6.codesNullSafe() + codesOfClass7.codesNullSafe() + codesOfClass8.codesNullSafe() } private fun List<Code>?.codesNullSafe() = this?.mapNotNull { it.code } ?: emptyList() /** * Due to bug https://github.com/jOOQ/jOOQ/issues/4754, the straightforward way * of mapping the codes to the array of type text does not work: * * <pre> * return PAPER.CODES.contains(codeCollection.toArray(new String[0])); * </pre> * * While I originally casted to PostgresDataType.TEXT, I now need to cast to SQLDataType.CLOB * due to https://github.com/jOOQ/jOOQ/issues/7375 */ private fun List<String>.toCondition(): Condition = Paper.PAPER.CODES.contains( DSL.array( mapNotNull { DSL.`val`(it).cast(SQLDataType.CLOB) } ) ) }
public/public-persistence-jooq/src/main/kotlin/ch/difty/scipamato/publ/persistence/paper/PublicPaperFilterConditionMapper.kt
3981072994
// 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.internal.retype import com.intellij.codeInsight.CodeInsightSettings import com.intellij.codeInsight.CodeInsightWorkspaceSettings import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementPresentation import com.intellij.codeInsight.lookup.LookupFocusDegree import com.intellij.codeInsight.lookup.LookupManager import com.intellij.codeInsight.lookup.impl.LookupImpl import com.intellij.codeInsight.template.TemplateManager import com.intellij.codeInsight.template.impl.LiveTemplateLookupElement import com.intellij.diagnostic.ThreadDumper import com.intellij.ide.DataManager import com.intellij.ide.IdeEventQueue import com.intellij.internal.performance.LatencyDistributionRecordKey import com.intellij.internal.performance.TypingLatencyReportDialog import com.intellij.internal.performance.currentLatencyRecordKey import com.intellij.internal.performance.latencyRecorderProperties import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.actionSystem.ex.ActionManagerEx import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.actionSystem.LatencyRecorder import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.fileEditor.impl.text.PsiAwareTextEditorImpl import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.ui.playback.commands.ActionCommand import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.IdeFocusManager import com.intellij.ui.EditorNotificationPanel import com.intellij.ui.EditorNotifications import com.intellij.ui.LightColors import com.intellij.util.Alarm import org.intellij.lang.annotations.Language import java.awt.event.KeyEvent import java.io.File import java.util.* fun String.toReadable() = replace(" ", "<Space>").replace("\n", "<Enter>").replace("\t", "<Tab>") class RetypeLog { val LOG = Logger.getInstance(RetypeLog::class.java) private val log = arrayListOf<String>() private var currentTyping: String? = null private var currentCompletion: String? = null var typedChars = 0 private set var completedChars = 0 private set fun recordTyping(c: Char) { if (currentTyping == null) { flushCompletion() currentTyping = "" } currentTyping += c.toString().toReadable() typedChars++ } fun recordCompletion(c: Char) { if (currentCompletion == null) { flushTyping() currentCompletion = "" } currentCompletion += c.toString().toReadable() completedChars++ } fun recordDesync(message: String) { flush() log.add("Desync: $message") } fun flush() { flushTyping() flushCompletion() } private fun flushTyping() { if (currentTyping != null) { log.add("Type: $currentTyping") currentTyping = null } } private fun flushCompletion() { if (currentCompletion != null) { log.add("Complete: $currentCompletion") currentCompletion = null } } fun printToStdout() { for (s in log) { if (ApplicationManager.getApplication().isUnitTestMode) { LOG.debug(s) } else { println(s) } } } } class RetypeSession( private val project: Project, private val editor: EditorImpl, private val delayMillis: Int, private val scriptBuilder: StringBuilder?, private val threadDumpDelay: Int, private val threadDumps: MutableList<String> = mutableListOf(), private val filesForIndexCount: Int = -1, private val restoreText: Boolean = !ApplicationManager.getApplication().isUnitTestMode ) : Disposable { private val document = editor.document // -- Alarms private val threadDumpAlarm = Alarm(Alarm.ThreadToUse.POOLED_THREAD, this) private val originalText = document.text @Volatile private var pos = 0 private val endPos: Int private val tailLength: Int private val log = RetypeLog() private val oldSelectAutopopup = CodeInsightSettings.getInstance().SELECT_AUTOPOPUP_SUGGESTIONS_BY_CHARS private val oldAddUnambiguous = CodeInsightSettings.getInstance().ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY private val oldOptimize = CodeInsightWorkspaceSettings.getInstance(project).isOptimizeImportsOnTheFly var startNextCallback: (() -> Unit)? = null private val disposeLock = Any() private var typedRightBefore = false private var skipLookupSuggestion = false private var textBeforeLookupSelection: String? = null @Volatile private var waitingForTimerInvokeLater: Boolean = false private var lastTimerTick = -1L private var threadPoolTimerLag = 0L private var totalTimerLag = 0L // This stack will contain autocompletion elements // E.g. "}", "]", "*/", "* @return" private val completionStack = ArrayDeque<String>() private var stopInterfereFileChanger = false var retypePaused: Boolean = false private val timerThread = Thread(::runLoop, "RetypeSession loop") private var stopTimer = false init { if (editor.selectionModel.hasSelection()) { pos = editor.selectionModel.selectionStart endPos = editor.selectionModel.selectionEnd } else { pos = editor.caretModel.offset endPos = document.textLength } tailLength = document.textLength - endPos } fun start() { editor.putUserData(RETYPE_SESSION_KEY, this) val vFile = FileDocumentManager.getInstance().getFile(document) val keyName = "${vFile?.name ?: "Unknown file"} (${document.textLength} chars)" currentLatencyRecordKey = LatencyDistributionRecordKey(keyName) latencyRecorderProperties.putAll(mapOf("Delay" to "$delayMillis ms", "Thread dump delay" to "$threadDumpDelay ms" )) scriptBuilder?.let { if (vFile != null) { val contentRoot = ProjectRootManager.getInstance(project).fileIndex.getContentRootForFile(vFile) ?: return@let it.append("%openFile ${VfsUtil.getRelativePath(vFile, contentRoot)}\n") } it.append(correctText(originalText.substring(0, pos) + originalText.substring(endPos))) val line = editor.document.getLineNumber(pos) it.append("%goto ${line + 1} ${pos - editor.document.getLineStartOffset(line) + 1}\n") } WriteCommandAction.runWriteCommandAction(project) { document.deleteString(pos, endPos) } CodeInsightSettings.getInstance().apply { SELECT_AUTOPOPUP_SUGGESTIONS_BY_CHARS = false ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = false } CodeInsightWorkspaceSettings.getInstance(project).isOptimizeImportsOnTheFly = false EditorNotifications.getInstance(project).updateNotifications(editor.virtualFile) retypePaused = false startLargeIndexing() timerThread.start() checkStop() } private fun correctText(text: String) = "%replaceText ${text.replace('\n', '\u32E1')}\n" fun stop(startNext: Boolean) { stopTimer = true timerThread.join() for (retypeFileAssistant in RetypeFileAssistant.EP_NAME.extensions) { retypeFileAssistant.retypeDone(editor) } if (restoreText) { WriteCommandAction.runWriteCommandAction(project) { document.replaceString(0, document.textLength, originalText) } } synchronized(disposeLock) { Disposer.dispose(this) } editor.putUserData(RETYPE_SESSION_KEY, null) CodeInsightSettings.getInstance().apply { SELECT_AUTOPOPUP_SUGGESTIONS_BY_CHARS = oldSelectAutopopup ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = oldAddUnambiguous } CodeInsightWorkspaceSettings.getInstance(project).isOptimizeImportsOnTheFly = oldOptimize currentLatencyRecordKey?.details = "typed ${log.typedChars} chars, completed ${log.completedChars} chars" log.flush() log.printToStdout() currentLatencyRecordKey = null if (startNext) { startNextCallback?.invoke() } removeLargeIndexing() stopInterfereFileChanger = true EditorNotifications.getInstance(project).updateAllNotifications() } override fun dispose() { } private fun inFocus(): Boolean = editor.contentComponent == IdeFocusManager.findInstance().focusOwner && ApplicationManager.getApplication().isActive || ApplicationManager.getApplication().isUnitTestMode private fun runLoop() { while (pos != endPos && !stopTimer) { Thread.sleep(delayMillis.toLong()) if (stopTimer) break typeNext() } } private fun typeNext() { if (!ApplicationManager.getApplication().isUnitTestMode) { threadDumpAlarm.addRequest({ logThreadDump() }, threadDumpDelay) } val timerTick = System.currentTimeMillis() waitingForTimerInvokeLater = true val expectedTimerTick = if (lastTimerTick != -1L) lastTimerTick + delayMillis else -1L if (lastTimerTick != -1L) { threadPoolTimerLag += (timerTick - expectedTimerTick) } lastTimerTick = timerTick ApplicationManager.getApplication().invokeLater { if (stopTimer) return@invokeLater typeNextInEDT(timerTick, expectedTimerTick) } } private fun typeNextInEDT(timerTick: Long, expectedTimerTick: Long) { if (retypePaused) { if (inFocus()) { // Resume retyping on editor focus retypePaused = false } else { checkStop() return } } if (expectedTimerTick != -1L) { totalTimerLag += (System.currentTimeMillis() - expectedTimerTick) } EditorNotifications.getInstance(project).updateAllNotifications() waitingForTimerInvokeLater = false val processNextEvent = handleIdeaIntelligence() if (processNextEvent) return if (TemplateManager.getInstance(project).getActiveTemplate(editor) != null) { TemplateManager.getInstance(project).finishTemplate(editor) checkStop() return } val lookup = LookupManager.getActiveLookup(editor) as LookupImpl? if (lookup != null && !skipLookupSuggestion) { val currentLookupElement = lookup.currentItem if (currentLookupElement?.shouldAccept(lookup.lookupStart) == true) { lookup.lookupFocusDegree = LookupFocusDegree.FOCUSED scriptBuilder?.append("${ActionCommand.PREFIX} ${IdeActions.ACTION_CHOOSE_LOOKUP_ITEM}\n") typedRightBefore = false textBeforeLookupSelection = document.text executeEditorAction(IdeActions.ACTION_CHOOSE_LOOKUP_ITEM, timerTick) checkStop() return } } // Do not perform typing if editor is not in focus if (!inFocus()) retypePaused = true if (retypePaused) { checkStop() return } // Restore caret position (E.g. user clicks accidentally on another position) if (editor.caretModel.offset != pos) editor.caretModel.moveToOffset(pos) val c = originalText[pos++] log.recordTyping(c) // Reset lookup related variables textBeforeLookupSelection = null if (c == ' ') skipLookupSuggestion = false // We expecting new lookup suggestions if (c == '\n') { scriptBuilder?.append("${ActionCommand.PREFIX} ${IdeActions.ACTION_EDITOR_ENTER}\n") executeEditorAction(IdeActions.ACTION_EDITOR_ENTER, timerTick) typedRightBefore = false } else { scriptBuilder?.let { if (typedRightBefore) { it.deleteCharAt(it.length - 1) it.append("$c\n") } else { it.append("%delayType $delayMillis|$c\n") } } if (ApplicationManager.getApplication().isUnitTestMode) { editor.type(c.toString()) } else { IdeEventQueue.getInstance().postEvent( KeyEvent(editor.component, KeyEvent.KEY_PRESSED, timerTick, 0, KeyEvent.VK_UNDEFINED, c)) IdeEventQueue.getInstance().postEvent( KeyEvent(editor.component, KeyEvent.KEY_TYPED, timerTick, 0, KeyEvent.VK_UNDEFINED, c)) } typedRightBefore = true } checkStop() } /** * @return if next queue event should be processed */ private fun handleIdeaIntelligence(): Boolean { val actualBeforeCaret = document.text.take(pos) val expectedBeforeCaret = originalText.take(pos) if (actualBeforeCaret != expectedBeforeCaret) { // Unexpected changes before current cursor position // (may be unwanted import) if (textBeforeLookupSelection != null) { log.recordDesync("Restoring text before lookup (expected ...${expectedBeforeCaret.takeLast( 5).toReadable()}, actual ...${actualBeforeCaret.takeLast(5).toReadable()} ") // Unexpected changes was made by lookup. // Restore previous text state and set flag to skip further suggestions until whitespace will be typed WriteCommandAction.runWriteCommandAction(project) { document.replaceText(textBeforeLookupSelection ?: return@runWriteCommandAction, document.modificationStamp + 1) } skipLookupSuggestion = true } else { log.recordDesync( "Restoring text before caret (expected ...${expectedBeforeCaret.takeLast(5).toReadable()}, actual ...${actualBeforeCaret.takeLast( 5).toReadable()} | pos: $pos, caretOffset: ${editor.caretModel.offset}") // There changes wasn't made by lookup, so we don't know how to handle them // Restore text before caret as it should be at this point without any intelligence WriteCommandAction.runWriteCommandAction(project) { document.replaceString(0, editor.caretModel.offset, expectedBeforeCaret) } } } if (editor.caretModel.offset > pos) { // Caret movement has been preformed // Move the caret forward until the characters match while (pos < document.textLength - tailLength && originalText[pos] == document.text[pos] && document.text[pos] !in listOf('\n') // Don't count line breakers because we want to enter "enter" explicitly ) { log.recordCompletion(document.text[pos]) pos++ } if (editor.caretModel.offset > pos) { log.recordDesync("Deleting extra characters: ${document.text.substring(pos, editor.caretModel.offset).toReadable()}") WriteCommandAction.runWriteCommandAction(project) { // Delete symbols not from original text and move caret document.deleteString(pos, editor.caretModel.offset) } } editor.caretModel.moveToOffset(pos) } if (document.textLength > pos + tailLength) { updateStack(completionStack) val firstCompletion = completionStack.peekLast() if (firstCompletion != null) { val origIndexOfFirstCompletion = originalText.substring(pos, endPos).trim().indexOf(firstCompletion) if (origIndexOfFirstCompletion == 0) { // Next non-whitespace chars from original tests are from completion stack val origIndexOfFirstComp = originalText.substring(pos, endPos).indexOf(firstCompletion) val docIndexOfFirstComp = document.text.substring(pos).indexOf(firstCompletion) if (originalText.substring(pos).take(origIndexOfFirstComp) != document.text.substring(pos).take(origIndexOfFirstComp)) { // We have some unexpected chars before completion. Remove them WriteCommandAction.runWriteCommandAction(project) { val replacement = originalText.substring(pos, pos + origIndexOfFirstComp) log.recordDesync("Replacing extra characters before completion: ${document.text.substring(pos, pos + docIndexOfFirstComp).toReadable()} -> ${replacement.toReadable()}") document.replaceString(pos, pos + docIndexOfFirstComp, replacement) } } (pos until pos + origIndexOfFirstComp + firstCompletion.length).forEach { log.recordCompletion(document.text[it]) } pos += origIndexOfFirstComp + firstCompletion.length editor.caretModel.moveToOffset(pos) completionStack.removeLast() checkStop() return true } else if (origIndexOfFirstCompletion < 0) { // Completion is wrong and original text doesn't contain it // Remove this completion val docIndexOfFirstComp = document.text.substring(pos).indexOf(firstCompletion) log.recordDesync("Removing wrong completion: ${document.text.substring(pos, pos + docIndexOfFirstComp).toReadable()}") WriteCommandAction.runWriteCommandAction(project) { document.replaceString(pos, pos + docIndexOfFirstComp + firstCompletion.length, "") } completionStack.removeLast() checkStop() return true } } } else if (document.textLength == pos + tailLength && completionStack.isNotEmpty()) { // Text is as expected, but we have some extra completions in stack completionStack.clear() } return false } private fun updateStack(completionStack: Deque<String>) { val unexpectedCharsDoc = document.text.substring(pos, document.textLength - tailLength) var endPosDoc = unexpectedCharsDoc.length val completionIterator = completionStack.iterator() while (completionIterator.hasNext()) { // Validate all existing completions and add new completions if they are val completion = completionIterator.next() val lastIndexOfCompletion = unexpectedCharsDoc.substring(0, endPosDoc).lastIndexOf(completion) if (lastIndexOfCompletion < 0) { completionIterator.remove() continue } endPosDoc = lastIndexOfCompletion } // Add new completion in stack unexpectedCharsDoc.substring(0, endPosDoc).trim().split("\\s+".toRegex()).map { it.trim() }.reversed().forEach { if (it.isNotEmpty()) { completionStack.add(it) } } } private fun checkStop() { if (pos == endPos) { stop(true) if (startNextCallback == null && !ApplicationManager.getApplication().isUnitTestMode) { if (scriptBuilder != null) { scriptBuilder.append(correctText(originalText)) val file = File.createTempFile("perf", ".test") val vFile = VfsUtil.findFileByIoFile(file, false)!! WriteCommandAction.runWriteCommandAction(project) { VfsUtil.saveText(vFile, scriptBuilder.toString()) } OpenFileDescriptor(project, vFile).navigate(true) } latencyRecorderProperties["Thread pool timer lag"] = "$threadPoolTimerLag ms" latencyRecorderProperties["Total timer lag"] = "$totalTimerLag ms" TypingLatencyReportDialog(project, threadDumps).show() } } } private fun LookupElement.shouldAccept(lookupStartOffset: Int): Boolean { for (retypeFileAssistant in RetypeFileAssistant.EP_NAME.extensionList) { if (!retypeFileAssistant.acceptLookupElement(this)) { return false } } if (this is LiveTemplateLookupElement) { return false } val lookupString = try { LookupElementPresentation.renderElement(this).itemText ?: return false } catch (e: Exception) { return false } val textAtLookup = originalText.substring(lookupStartOffset) if (textAtLookup.take(lookupString.length) != lookupString) { return false } return textAtLookup.length == lookupString.length || !Character.isJavaIdentifierPart(textAtLookup[lookupString.length] + 1) } private fun executeEditorAction(actionId: String, timerTick: Long) { val actionManager = ActionManagerEx.getInstanceEx() val action = actionManager.getAction(actionId) val event = AnActionEvent.createFromAnAction(action, null, "", DataManager.getInstance().getDataContext( editor.component)) action.beforeActionPerformedUpdate(event) actionManager.fireBeforeActionPerformed(action, event.dataContext, event) LatencyRecorder.getInstance().recordLatencyAwareAction(editor, actionId, timerTick) action.actionPerformed(event) actionManager.fireAfterActionPerformed(action, event.dataContext, event) } private fun logThreadDump() { if (editor.isProcessingTypedAction || waitingForTimerInvokeLater) { threadDumps.add(ThreadDumper.dumpThreadsToString()) if (threadDumps.size > 200) { threadDumps.subList(0, 100).clear() } synchronized(disposeLock) { if (!threadDumpAlarm.isDisposed) { threadDumpAlarm.addRequest({ logThreadDump() }, threadDumpDelay) } } } } private fun startLargeIndexing() { if (filesForIndexCount <= 0) return val dir = File(editor.virtualFile.parent.path, LARGE_INDEX_DIR_NAME) dir.mkdir() for (i in 0..filesForIndexCount) { val file = File(dir, "MyClass$i.java") file.createNewFile() file.writeText(code.repeat(500)) } } private fun removeLargeIndexing() { if (filesForIndexCount <= 0) return val dir = File(editor.virtualFile.parent.path, LARGE_INDEX_DIR_NAME) dir.deleteRecursively() } @Language("JAVA") val code = """ final class MyClass { public static void main1(String[] args) { int x = 5; } } """.trimIndent() companion object { val LOG = Logger.getInstance(RetypeSession::class.java) const val INTERFERE_FILE_NAME = "IdeaRetypeBackgroundChanges.java" const val LARGE_INDEX_DIR_NAME = "_indexDir_" } } val RETYPE_SESSION_KEY = Key.create<RetypeSession>("com.intellij.internal.retype.RetypeSession") val RETYPE_SESSION_NOTIFICATION_KEY = Key.create<EditorNotificationPanel>("com.intellij.internal.retype.RetypeSessionNotification") class RetypeEditorNotificationProvider : EditorNotifications.Provider<EditorNotificationPanel>() { override fun getKey(): Key<EditorNotificationPanel> = RETYPE_SESSION_NOTIFICATION_KEY override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor, project: Project): EditorNotificationPanel? { if (fileEditor !is PsiAwareTextEditorImpl) return null val retypeSession = fileEditor.editor.getUserData(RETYPE_SESSION_KEY) if (retypeSession == null) return null val panel: EditorNotificationPanel if (retypeSession.retypePaused) { panel = EditorNotificationPanel(fileEditor) panel.setText("Pause retyping. Click on editor to resume") } else { panel = EditorNotificationPanel(LightColors.SLIGHTLY_GREEN) panel.setText("Retyping") } panel.createActionLabel("Stop without report") { retypeSession.stop(false) } return panel } }
platform/lang-impl/src/com/intellij/internal/retype/RetypeSession.kt
1786224227
package ch.difty.scipamato.common.entity import ch.difty.scipamato.common.entity.CodeClassId.CC1 import ch.difty.scipamato.common.entity.CodeClassId.CC2 import ch.difty.scipamato.common.entity.CodeClassId.CC3 import ch.difty.scipamato.common.entity.CodeClassId.CC4 import ch.difty.scipamato.common.entity.CodeClassId.CC5 import ch.difty.scipamato.common.entity.CodeClassId.CC6 import ch.difty.scipamato.common.entity.CodeClassId.CC7 import ch.difty.scipamato.common.entity.CodeClassId.CC8 import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldBeFalse import org.amshove.kluent.shouldBeTrue import org.amshove.kluent.shouldContainSame import org.junit.jupiter.api.Test class CodeClassIdTest { @Test fun values() { CodeClassId.values() shouldContainSame listOf(CC1, CC2, CC3, CC4, CC5, CC6, CC7, CC8) } @Test fun fromId_whenPresent() { CodeClassId.fromId(1).isPresent.shouldBeTrue() CodeClassId.fromId(1).get() shouldBeEqualTo CC1 CodeClassId.fromId(2).get() shouldBeEqualTo CC2 CodeClassId.fromId(3).get() shouldBeEqualTo CC3 CodeClassId.fromId(4).get() shouldBeEqualTo CC4 CodeClassId.fromId(5).get() shouldBeEqualTo CC5 CodeClassId.fromId(6).get() shouldBeEqualTo CC6 CodeClassId.fromId(7).get() shouldBeEqualTo CC7 CodeClassId.fromId(8).get() shouldBeEqualTo CC8 } @Test fun fromId_whenNotPresent() { CodeClassId.fromId(-1).isPresent.shouldBeFalse() } @Test fun getId() { CC1.id shouldBeEqualTo 1 } }
common/common-entity/src/test/kotlin/ch/difty/scipamato/common/entity/CodeClassIdTest.kt
2029047365
package ch.difty.scipamato.core.config import ch.difty.scipamato.common.config.ScipamatoBaseProperties import ch.difty.scipamato.core.logic.exporting.RisExporterStrategy import ch.difty.scipamato.core.logic.parsing.AuthorParserStrategy import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.stereotype.Component @Component @ConfigurationProperties(prefix = "scipamato") data class ScipamatoProperties( /** * Brand name of the application. Appears e.g. in the Navbar. */ override var brand: String = "SciPaMaTo-Core", /** * Page Title of the application. Appears in the browser tab. */ override var pageTitle: String? = null, /** * Default localization. Normally the browser locale is used. */ override var defaultLocalization: String = "en", /** * The base url used to access the Pubmed API. */ override var pubmedBaseUrl: String = "https://www.ncbi.nlm.nih.gov/pubmed/", /** * The author parser used for parsing Author Strings. Currently only * DEFAULT is implemented. */ var authorParser: String = "DEFAULT", /** * The ris export adapter used for exporting studies into RIS format. Currently only * DEFAULT and DISTILLERSR is implemented. */ var risExporter: String = "DEFAULT", /** * Any free number below this threshold will not be reused. */ var paperNumberMinimumToBeRecycled: Int = 0, /** * DB Schema. */ var dbSchema: String = "public", /** * Port from where an unsecured http connection is forwarded to the secured * https port (@literal server.port}. Only has an effect if https is configured. */ override var redirectFromPort: Int? = null, /** * The URL of the CMS page that points to the paper search page */ override var cmsUrlSearchPage: String? = null, /** * @return the author parser strategy used for interpreting the authors string. */ var authorParserStrategy: AuthorParserStrategy = AuthorParserStrategy.fromProperty(authorParser, AUTHOR_PARSER_PROPERTY_KEY), /** * @return the strategy for exporting studies into RIS file format. */ var risExporterStrategy: RisExporterStrategy = RisExporterStrategy.fromProperty(risExporter, RIS_EXPORTER_PROPERTY_KEY), /** * The threshold above which the multi-select box may (if configured) show the * action box providing the select all/select none buttons */ override var multiSelectBoxActionBoxWithMoreEntriesThan: Int = 4, /** * The API Key used for accessing pubmed papers. * * * https://ncbiinsights.ncbi.nlm.nih.gov/2017/11/02/new-api-keys-for-the-e-utilities/ */ var pubmedApiKey: String? = null, ) : ScipamatoBaseProperties { companion object { private const val serialVersionUID = 1L private const val AUTHOR_PARSER_PROPERTY_KEY = "scipamato.author-parser" private const val RIS_EXPORTER_PROPERTY_KEY = "scipamato.ris-exporter" } }
core/core-web/src/main/java/ch/difty/scipamato/core/config/ScipamatoProperties.kt
2000243203
// 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 training.learn.lesson.general.assistance import com.intellij.codeInsight.documentation.DocumentationComponent import com.intellij.codeInsight.documentation.QuickDocUtil import com.intellij.codeInsight.hint.ImplementationViewComponent import training.dsl.LessonContext import training.dsl.LessonSample import training.dsl.LessonUtil.restoreIfModifiedOrMoved import training.dsl.TaskRuntimeContext import training.learn.LessonsBundle import training.learn.course.KLesson class QuickPopupsLesson(private val sample: LessonSample) : KLesson("CodeAssistance.QuickPopups", LessonsBundle.message("quick.popups.lesson.name")) { override val lessonContent: LessonContext.() -> Unit = { prepareSample(sample) task("QuickJavaDoc") { text(LessonsBundle.message("quick.popups.show.documentation", action(it))) triggerByUiComponentAndHighlight(highlightBorder = false, highlightInside = false) { _: DocumentationComponent -> true } restoreIfModifiedOrMoved() test { actions(it) } } task { text(LessonsBundle.message("quick.popups.press.escape", action("EditorEscape"))) stateCheck { checkDocComponentClosed() } restoreIfModifiedOrMoved() test { invokeActionViaShortcut("ESCAPE") } } task("QuickImplementations") { text(LessonsBundle.message("quick.popups.show.implementation", action(it))) triggerByUiComponentAndHighlight(highlightBorder = false, highlightInside = false) { _: ImplementationViewComponent -> true } restoreIfModifiedOrMoved() test { actions(it) } } } private fun TaskRuntimeContext.checkDocComponentClosed(): Boolean { val activeDocComponent = QuickDocUtil.getActiveDocComponent(project) return activeDocComponent == null || !activeDocComponent.isShowing } }
plugins/ide-features-trainer/src/training/learn/lesson/general/assistance/QuickPopupsLesson.kt
3021362715
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines import kotlinx.coroutines.flow.* import kotlinx.coroutines.internal.* import java.io.* import java.util.concurrent.* import kotlin.coroutines.* /** * [CoroutineDispatcher] that has underlying [Executor] for dispatching tasks. * Instances of [ExecutorCoroutineDispatcher] should be closed by the owner of the dispatcher. * * This class is generally used as a bridge between coroutine-based API and * asynchronous API that requires an instance of the [Executor]. */ public abstract class ExecutorCoroutineDispatcher: CoroutineDispatcher(), Closeable { /** @suppress */ @ExperimentalStdlibApi public companion object Key : AbstractCoroutineContextKey<CoroutineDispatcher, ExecutorCoroutineDispatcher>( CoroutineDispatcher, { it as? ExecutorCoroutineDispatcher }) /** * Underlying executor of current [CoroutineDispatcher]. */ public abstract val executor: Executor /** * Closes this coroutine dispatcher and shuts down its executor. * * It may throw an exception if this dispatcher is global and cannot be closed. */ public abstract override fun close() } @ExperimentalCoroutinesApi public actual typealias CloseableCoroutineDispatcher = ExecutorCoroutineDispatcher /** * Converts an instance of [ExecutorService] to an implementation of [ExecutorCoroutineDispatcher]. * * ## Interaction with [delay] and time-based coroutines. * * If the given [ExecutorService] is an instance of [ScheduledExecutorService], then all time-related * coroutine operations such as [delay], [withTimeout] and time-based [Flow] operators will be scheduled * on this executor using [schedule][ScheduledExecutorService.schedule] method. If the corresponding * coroutine is cancelled, [ScheduledFuture.cancel] will be invoked on the corresponding future. * * If the given [ExecutorService] is an instance of [ScheduledThreadPoolExecutor], then prior to any scheduling, * remove on cancel policy will be set via [ScheduledThreadPoolExecutor.setRemoveOnCancelPolicy] in order * to reduce the memory pressure of cancelled coroutines. * * If the executor service is neither of this types, the separate internal thread will be used to * _track_ the delay and time-related executions, but the coroutine itself will still be executed * on top of the given executor. * * ## Rejected execution * If the underlying executor throws [RejectedExecutionException] on * attempt to submit a continuation task (it happens when [closing][ExecutorCoroutineDispatcher.close] the * resulting dispatcher, on underlying executor [shutdown][ExecutorService.shutdown], or when it uses limited queues), * then the [Job] of the affected task is [cancelled][Job.cancel] and the task is submitted to the * [Dispatchers.IO], so that the affected coroutine can cleanup its resources and promptly complete. */ @JvmName("from") // this is for a nice Java API, see issue #255 public fun ExecutorService.asCoroutineDispatcher(): ExecutorCoroutineDispatcher = ExecutorCoroutineDispatcherImpl(this) /** * Converts an instance of [Executor] to an implementation of [CoroutineDispatcher]. * * ## Interaction with [delay] and time-based coroutines. * * If the given [Executor] is an instance of [ScheduledExecutorService], then all time-related * coroutine operations such as [delay], [withTimeout] and time-based [Flow] operators will be scheduled * on this executor using [schedule][ScheduledExecutorService.schedule] method. If the corresponding * coroutine is cancelled, [ScheduledFuture.cancel] will be invoked on the corresponding future. * * If the given [Executor] is an instance of [ScheduledThreadPoolExecutor], then prior to any scheduling, * remove on cancel policy will be set via [ScheduledThreadPoolExecutor.setRemoveOnCancelPolicy] in order * to reduce the memory pressure of cancelled coroutines. * * If the executor is neither of this types, the separate internal thread will be used to * _track_ the delay and time-related executions, but the coroutine itself will still be executed * on top of the given executor. * * ## Rejected execution * * If the underlying executor throws [RejectedExecutionException] on * attempt to submit a continuation task (it happens when [closing][ExecutorCoroutineDispatcher.close] the * resulting dispatcher, on underlying executor [shutdown][ExecutorService.shutdown], or when it uses limited queues), * then the [Job] of the affected task is [cancelled][Job.cancel] and the task is submitted to the * [Dispatchers.IO], so that the affected coroutine can cleanup its resources and promptly complete. */ @JvmName("from") // this is for a nice Java API, see issue #255 public fun Executor.asCoroutineDispatcher(): CoroutineDispatcher = (this as? DispatcherExecutor)?.dispatcher ?: ExecutorCoroutineDispatcherImpl(this) /** * Converts an instance of [CoroutineDispatcher] to an implementation of [Executor]. * * It returns the original executor when used on the result of [Executor.asCoroutineDispatcher] extensions. */ public fun CoroutineDispatcher.asExecutor(): Executor = (this as? ExecutorCoroutineDispatcher)?.executor ?: DispatcherExecutor(this) private class DispatcherExecutor(@JvmField val dispatcher: CoroutineDispatcher) : Executor { override fun execute(block: Runnable) = dispatcher.dispatch(EmptyCoroutineContext, block) override fun toString(): String = dispatcher.toString() } internal class ExecutorCoroutineDispatcherImpl(override val executor: Executor) : ExecutorCoroutineDispatcher(), Delay { /* * Attempts to reflectively (to be Java 6 compatible) invoke * ScheduledThreadPoolExecutor.setRemoveOnCancelPolicy in order to cleanup * internal scheduler queue on cancellation. */ init { removeFutureOnCancel(executor) } override fun dispatch(context: CoroutineContext, block: Runnable) { try { executor.execute(wrapTask(block)) } catch (e: RejectedExecutionException) { unTrackTask() cancelJobOnRejection(context, e) Dispatchers.IO.dispatch(context, block) } } override fun scheduleResumeAfterDelay(timeMillis: Long, continuation: CancellableContinuation<Unit>) { val future = (executor as? ScheduledExecutorService)?.scheduleBlock( ResumeUndispatchedRunnable(this, continuation), continuation.context, timeMillis ) // If everything went fine and the scheduling attempt was not rejected -- use it if (future != null) { continuation.cancelFutureOnCancellation(future) return } // Otherwise fallback to default executor DefaultExecutor.scheduleResumeAfterDelay(timeMillis, continuation) } override fun invokeOnTimeout(timeMillis: Long, block: Runnable, context: CoroutineContext): DisposableHandle { val future = (executor as? ScheduledExecutorService)?.scheduleBlock(block, context, timeMillis) return when { future != null -> DisposableFutureHandle(future) else -> DefaultExecutor.invokeOnTimeout(timeMillis, block, context) } } private fun ScheduledExecutorService.scheduleBlock(block: Runnable, context: CoroutineContext, timeMillis: Long): ScheduledFuture<*>? { return try { schedule(block, timeMillis, TimeUnit.MILLISECONDS) } catch (e: RejectedExecutionException) { cancelJobOnRejection(context, e) null } } private fun cancelJobOnRejection(context: CoroutineContext, exception: RejectedExecutionException) { context.cancel(CancellationException("The task was rejected", exception)) } override fun close() { (executor as? ExecutorService)?.shutdown() } override fun toString(): String = executor.toString() override fun equals(other: Any?): Boolean = other is ExecutorCoroutineDispatcherImpl && other.executor === executor override fun hashCode(): Int = System.identityHashCode(executor) } private class ResumeUndispatchedRunnable( private val dispatcher: CoroutineDispatcher, private val continuation: CancellableContinuation<Unit> ) : Runnable { override fun run() { with(continuation) { dispatcher.resumeUndispatched(Unit) } } } /** * An implementation of [DisposableHandle] that cancels the specified future on dispose. * @suppress **This is unstable API and it is subject to change.** */ private class DisposableFutureHandle(private val future: Future<*>) : DisposableHandle { override fun dispose() { future.cancel(false) } override fun toString(): String = "DisposableFutureHandle[$future]" }
kotlinx-coroutines-core/jvm/src/Executors.kt
1434018067
/* * #%L * fixture * %% * Copyright (C) 2013 Martin Lau * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package io.fixture.repository import io.fixture.domain.PersistentLogin import java.util.UUID import org.springframework.data.jpa.repository.JpaRepository import org.springframework.data.jpa.repository.Modifying import org.springframework.data.jpa.repository.Query import org.springframework.data.repository.query.Param import javax.persistence.QueryHint import org.springframework.data.jpa.repository.QueryHints trait PersistentLoginRepository: JpaRepository<PersistentLogin, UUID> { [Modifying] [Query(value = "DELETE FROM PersistentLogin pl WHERE pl.user = (SELECT u FROM User u WHERE u.username = :username)")] [QueryHints(value = array( QueryHint(name = "org.hibernate.cacheable", value = "true") ))] fun deleteAllForUsername([Param(value = "username")] username: String) [Query(value = "SELECT pl FROM PersistentLogin pl WHERE pl.series = :series")] [QueryHints(value = array( QueryHint(name = "org.hibernate.cacheable", value = "true") ))] fun findOne([Param(value = "series")] series: String): PersistentLogin? }
src/main/kotlin/io/fixture/repository/PersistentLoginRepository.kt
3936148115
// 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.observable.properties import org.jetbrains.annotations.TestOnly import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.atomic.AtomicBoolean class PropertyGraph { private val inPropagation = AtomicBoolean(false) private val propagationListeners = CopyOnWriteArrayList<() -> Unit>() private val properties = ConcurrentHashMap<ObservableClearableProperty<*>, PropertyNode>() private val dependencies = ConcurrentHashMap<PropertyNode, CopyOnWriteArrayList<Dependency<*>>>() fun <T> dependsOn(child: ObservableClearableProperty<T>, parent: ObservableClearableProperty<*>, update: () -> T) { val childNode = properties[child] ?: throw IllegalArgumentException("Unregistered child property") val parentNode = properties[parent] ?: throw IllegalArgumentException("Unregistered parent property") dependencies.putIfAbsent(parentNode, CopyOnWriteArrayList()) val children = dependencies.getValue(parentNode) children.add(Dependency(childNode, child, update)) } fun afterPropagation(listener: () -> Unit) { propagationListeners.add(listener) } fun register(property: ObservableClearableProperty<*>) { val node = PropertyNode() properties[property] = node property.afterChange { if (!inPropagation.get()) { node.isPropagationBlocked = true } } property.afterReset { node.isPropagationBlocked = false } property.afterChange { inPropagation.withLockIfCan { node.inPropagation.withLockIfCan { propagateChange(node) } propagationListeners.forEach { it() } } } } private fun propagateChange(parent: PropertyNode) { val dependencies = dependencies[parent] ?: return for (dependency in dependencies) { val child = dependency.node if (child.isPropagationBlocked) continue child.inPropagation.withLockIfCan { dependency.applyUpdate() propagateChange(child) } } } @TestOnly fun isPropagationBlocked(property: ObservableClearableProperty<*>) = properties.getValue(property).isPropagationBlocked private inner class PropertyNode { @Volatile var isPropagationBlocked = false val inPropagation = AtomicBoolean(false) } private class Dependency<T>(val node: PropertyNode, private val property: ObservableClearableProperty<T>, private val update: () -> T) { fun applyUpdate() { property.set(update()) } } companion object { private inline fun AtomicBoolean.withLockIfCan(action: () -> Unit) { if (!compareAndSet(false, true)) return try { action() } finally { set(false) } } } }
platform/platform-impl/src/com/intellij/openapi/observable/properties/PropertyGraph.kt
3871706749
/* * Copyright 2022 Benoit LETONDOR * * 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.benoitletondor.easybudgetapp.db.impl import androidx.room.* import com.benoitletondor.easybudgetapp.db.impl.entity.ExpenseEntity import com.benoitletondor.easybudgetapp.db.impl.entity.RecurringExpenseEntity import androidx.sqlite.db.SupportSQLiteQuery import androidx.room.RawQuery import java.time.LocalDate @Dao interface ExpenseDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun persistExpense(expenseEntity: ExpenseEntity): Long @Query("SELECT COUNT(*) FROM expense WHERE date = :dayDate LIMIT 1") suspend fun hasExpenseForDay(dayDate: LocalDate): Int @Query("SELECT * FROM expense WHERE date = :dayDate") suspend fun getExpensesForDay(dayDate: LocalDate): List<ExpenseEntity> @Query("SELECT * FROM expense WHERE date >= :monthStartDate AND date <= :monthEndDate") suspend fun getExpensesForMonth(monthStartDate: LocalDate, monthEndDate: LocalDate): List<ExpenseEntity> @Query("SELECT SUM(amount) FROM expense WHERE date <= :dayDate") suspend fun getBalanceForDay(dayDate: LocalDate): Long? @Query("SELECT SUM(amount) FROM expense WHERE date <= :dayDate AND checked") suspend fun getCheckedBalanceForDay(dayDate: LocalDate): Long? @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun persistRecurringExpense(recurringExpenseEntity: RecurringExpenseEntity): Long @Delete suspend fun deleteRecurringExpense(recurringExpenseEntity: RecurringExpenseEntity) @Delete suspend fun deleteExpense(expenseEntity: ExpenseEntity) @Query("DELETE FROM expense WHERE monthly_id = :recurringExpenseId") suspend fun deleteAllExpenseForRecurringExpense(recurringExpenseId: Long) @Query("SELECT * FROM expense WHERE monthly_id = :recurringExpenseId") suspend fun getAllExpenseForRecurringExpense(recurringExpenseId: Long): List<ExpenseEntity> @Query("DELETE FROM expense WHERE monthly_id = :recurringExpenseId AND date > :afterDate") suspend fun deleteAllExpenseForRecurringExpenseAfterDate(recurringExpenseId: Long, afterDate: LocalDate) @Query("SELECT * FROM expense WHERE monthly_id = :recurringExpenseId AND date > :afterDate") suspend fun getAllExpensesForRecurringExpenseAfterDate(recurringExpenseId: Long, afterDate: LocalDate): List<ExpenseEntity> @Query("DELETE FROM expense WHERE monthly_id = :recurringExpenseId AND date < :beforeDate") suspend fun deleteAllExpenseForRecurringExpenseBeforeDate(recurringExpenseId: Long, beforeDate: LocalDate) @Query("SELECT * FROM expense WHERE monthly_id = :recurringExpenseId AND date < :beforeDate") suspend fun getAllExpensesForRecurringExpenseBeforeDate(recurringExpenseId: Long, beforeDate: LocalDate): List<ExpenseEntity> @Query("SELECT count(*) FROM expense WHERE monthly_id = :recurringExpenseId AND date < :beforeDate LIMIT 1") suspend fun hasExpensesForRecurringExpenseBeforeDate(recurringExpenseId: Long, beforeDate: LocalDate): Int @Query("SELECT * FROM monthlyexpense WHERE _expense_id = :recurringExpenseId LIMIT 1") suspend fun findRecurringExpenseForId(recurringExpenseId: Long): RecurringExpenseEntity? @RawQuery suspend fun checkpoint(supportSQLiteQuery: SupportSQLiteQuery): Int @Query("SELECT * FROM expense ORDER BY date LIMIT 1") suspend fun getOldestExpense(): ExpenseEntity? @Query("UPDATE expense SET checked = 1 WHERE date < :beforeDate") suspend fun markAllEntriesAsChecked(beforeDate: LocalDate) }
Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/db/impl/ExpenseDao.kt
2087482821
package com.dbflow5.adapter import com.dbflow5.annotation.QueryModel import com.dbflow5.config.DBFlowDatabase /** * Description: The baseclass for adapters to [QueryModel] that defines how it interacts with the DB. The * where query is not defined here, rather its determined by the cursor used. */ @Deprecated(replaceWith = ReplaceWith("RetrievalAdapter<T>", "com.dbflow5.adapter"), message = "QueryModelAdapter is now redundant. Use Retrieval Adapter") abstract class QueryModelAdapter<T : Any>(databaseDefinition: DBFlowDatabase) : RetrievalAdapter<T>(databaseDefinition)
lib/src/main/kotlin/com/dbflow5/adapter/QueryModelAdapter.kt
2043625926
// 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.testFramework.assertions import com.intellij.testFramework.UsefulTestCase import com.intellij.util.io.delete import com.intellij.util.io.directoryStreamIfExists import com.intellij.util.io.isFile import com.intellij.util.io.isHidden import gnu.trove.THashSet import org.junit.rules.ExternalResource import java.nio.file.Path class CleanupSnapshots(private val dir: Path) : ExternalResource() { private val usedPaths: MutableSet<Path> = THashSet<Path>() private val listener = object : SnapshotFileUsageListener { override fun beforeMatch(file: Path) { if (file.startsWith(dir)) { usedPaths.add(file) } } } override fun before() { if (!UsefulTestCase.IS_UNDER_TEAMCITY) { snapshotFileUsageListeners.add(listener) } } override fun after() { dir.directoryStreamIfExists { for (file in it) { if (!usedPaths.contains(file) && !file.isHidden() && file.isFile()) { file.delete(false) println("Remove outdated snapshot ${dir.relativize(file)}") } } } snapshotFileUsageListeners.remove(listener) } }
platform/testFramework/extensions/src/com/intellij/testFramework/assertions/CleanupSnapshots.kt
3186383688
class A { companion object { private var r: Int = 1; fun test(): Int { r++ ++r return r } var holder: String = "" var r2: Int = 1 get() { holder += "getR2" return field } fun test2() : Int { r2++ ++r2 return r2 } var r3: Int = 1 set(p: Int) { holder += "setR3" field = p } fun test3() : Int { r3++ ++r3 return r3 } var r4: Int = 1 get() { holder += "getR4" return field } set(p: Int) { holder += "setR4" field = p } fun test4() : Int { r4++ holder += ":" ++r4 return r4 } } } fun box() : String { val p = A.test() if (p != 3) return "fail 1: $p" val p2 = A.test2() var holderValue = A.holder if (p2 != 3 || holderValue != "getR2getR2getR2getR2") return "fail 2: $p2 ${holderValue}" A.holder = "" val p3 = A.test3() if (p3 != 3 || A.holder != "setR3setR3") return "fail 3: $p3 ${A.holder}" A.holder = "" val p4 = A.test4() if (p4 != 3 || A.holder != "getR4setR4:getR4setR4getR4getR4") return "fail 4: $p4 ${A.holder}" return "OK" }
backend.native/tests/external/codegen/box/statics/incInClassObject.kt
484656741
package com.byoutline.kickmaterial.model import android.support.annotation.StringRes import com.byoutline.kickmaterial.KickMaterialApp import com.byoutline.kickmaterial.R import java.util.* /** * Created by Sebastian Kacprzak <sebastian.kacprzak at byoutline.com> on 31.03.15. */ enum class SortTypes(@StringRes nameResId: Int) { MAGIC(R.string.sort_magic), POPULARITY(R.string.sort_popularity), NEWEST(R.string.sort_newest), END_DATE(R.string.sort_end_date), MOST_FUNDED(R.string.sort_most_funded); val apiName: String = name.toLowerCase(Locale.ENGLISH) private val displayName: String by lazy { KickMaterialApp.component.app.getString(nameResId) } override fun toString() = displayName }
app/src/main/java/com/byoutline/kickmaterial/model/SortTypes.kt
1433674907
/* * Copyright 2017 Muhammad Rifqi Fatchurrahman Putra Danar * * 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.github.muhrifqii.maos import android.app.Application import butterknife.ButterKnife import com.squareup.leakcanary.LeakCanary import com.squareup.leakcanary.RefWatcher import timber.log.Timber /** * Created on : 21/01/17 * Author : muhrifqii * Name : Muhammad Rifqi Fatchurrahman Putra Danar * Github : https://github.com/muhrifqii * LinkedIn : https://linkedin.com/in/muhrifqii */ class MaosApplication : Application() { lateinit var refwatcher: RefWatcher private set lateinit var component: AppComponent private set override fun onCreate() { super.onCreate() if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) refwatcher = LeakCanary.install(this) ButterKnife.setDebug(true) } component = DaggerAppComponent.builder().appModule(AppModule(this)).build() } }
app/src/main/java/io/github/muhrifqii/maos/MaosApplication.kt
222118508
class ClassC<T> object Test { @JvmStatic fun main(args: Array<String>) { var a: ClassC<*> } }
plugins/kotlin/j2k/new/tests/testData/newJ2k/issues/kt-31818.kt
599330247
package switch_demo object SwitchDemo { @JvmStatic fun main(args: Array<String>) { val month = 8 val monthString: String monthString = when (month) { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 -> "December" else -> "Invalid month" } println(monthString) } }
plugins/kotlin/j2k/new/tests/testData/newJ2k/switch/fallDown.kt
540247438
// 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 org.jetbrains.idea.maven.onlinecompletion import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.service.fus.collectors.FUCounterUsageLogger import org.jetbrains.idea.reposearch.SearchParameters object MavenDependencySearchStatisticsCollector { private const val GROUP_ID = "build.maven.packagesearch" @JvmStatic fun notifyError(endPoint: String, parameters: SearchParameters, timeMillisToResponse: Long, e: Throwable) { FUCounterUsageLogger.getInstance().logEvent(GROUP_ID, "packagesearch.error", FeatureUsageData() .addData("time", timeMillisToResponse) .addData("endpoint", endPoint) .addData("useCache", parameters.useCache()) .addData("exception", e.javaClass.canonicalName)); } @JvmStatic fun notifySuccess(endPoint: String, parameters: SearchParameters, timeMillisToResponse: Long) { FUCounterUsageLogger.getInstance().logEvent(GROUP_ID, "packagesearch.success", FeatureUsageData() .addData("time", timeMillisToResponse) .addData("endpoint", endPoint) .addData("useCache", parameters.useCache())); } }
plugins/maven/src/main/java/org/jetbrains/idea/maven/onlinecompletion/MavenDependencySearchStatisticsCollector.kt
2672567043
import kotlin.error as veryBad fun foo() { v<caret> } // ELEMENT: "veryBad"
plugins/kotlin/completion/tests/testData/handlers/basic/importAliases/TopLevelFun.kt
3434866295
open class A class <caret>B : A() { // INFO: {"checked": "true"} fun barw() { } // INFO: {"checked": "true", "toAbstract": "true"} val foo8: Int = 1 }
plugins/kotlin/idea/tests/testData/refactoring/pullUp/k2k/fromClassToClassMakeAbstractWithCommentAndAnotherIndent.kt
3907340181
package zielu.gittoolbox.util import com.intellij.openapi.Disposable import com.intellij.openapi.util.Disposer internal class DisposeAfterExecutableTask( private val task: ExecutableTask, private val disposable: Disposable ) : ExecutableTask { override fun run() { try { task.run() } finally { Disposer.dispose(disposable) } } override fun getTitle(): String = task.title }
src/main/kotlin/zielu/gittoolbox/util/DisposeAfterExecutableTask.kt
202717603
import kotlinx.datetime.* actual fun <lineMarker descr="Has declaration in common module">f</lineMarker>(): LocalDate { val ld = LocalDate(0, 0, 0) // ld.toNSDateComponents() return ld }
plugins/kotlin/idea/tests/testData/gradle/importAndCheckHighlighting/consumingKotlinXDatetimeInNativeMain/src/jvmMain/kotlin/MyTestRenamed.kt
3249567017
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.jetsnack.ui.home.cart import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.jetsnack.R import com.example.jetsnack.model.OrderLine import com.example.jetsnack.model.SnackRepo import com.example.jetsnack.model.SnackbarManager import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow /** * Holds the contents of the cart and allows changes to it. * * TODO: Move data to Repository so it can be displayed and changed consistently throughout the app. */ class CartViewModel( private val snackbarManager: SnackbarManager, snackRepository: SnackRepo ) : ViewModel() { private val _orderLines: MutableStateFlow<List<OrderLine>> = MutableStateFlow(snackRepository.getCart()) val orderLines: StateFlow<List<OrderLine>> get() = _orderLines // Logic to show errors every few requests private var requestCount = 0 private fun shouldRandomlyFail(): Boolean = ++requestCount % 5 == 0 fun increaseSnackCount(snackId: Long) { if (!shouldRandomlyFail()) { val currentCount = _orderLines.value.first { it.snack.id == snackId }.count updateSnackCount(snackId, currentCount + 1) } else { snackbarManager.showMessage(R.string.cart_increase_error) } } fun decreaseSnackCount(snackId: Long) { if (!shouldRandomlyFail()) { val currentCount = _orderLines.value.first { it.snack.id == snackId }.count if (currentCount == 1) { // remove snack from cart removeSnack(snackId) } else { // update quantity in cart updateSnackCount(snackId, currentCount - 1) } } else { snackbarManager.showMessage(R.string.cart_decrease_error) } } fun removeSnack(snackId: Long) { _orderLines.value = _orderLines.value.filter { it.snack.id != snackId } } private fun updateSnackCount(snackId: Long, count: Int) { _orderLines.value = _orderLines.value.map { if (it.snack.id == snackId) { it.copy(count = count) } else { it } } } /** * Factory for CartViewModel that takes SnackbarManager as a dependency */ companion object { fun provideFactory( snackbarManager: SnackbarManager = SnackbarManager, snackRepository: SnackRepo = SnackRepo ): ViewModelProvider.Factory = object : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { return CartViewModel(snackbarManager, snackRepository) as T } } } }
Jetsnack/app/src/main/java/com/example/jetsnack/ui/home/cart/CartViewModel.kt
2978375308
package com.habitrpg.android.habitica.models.inventory import android.graphics.Color import io.realm.RealmObject import io.realm.annotations.PrimaryKey /** * Created by phillip on 31.01.18. */ open class QuestColors : RealmObject() { @PrimaryKey var key: String? = null var dark: String? = null var medium: String? = null var light: String? = null var extralight: String? = null var darkColor: Int = 0 get() { return Color.parseColor(dark) } var mediumColor: Int = 0 get() { return Color.parseColor(medium) } var lightColor: Int = 0 get() { return Color.parseColor(light) } var extraLightColor: Int = 0 get() { return Color.parseColor(extralight) } }
Habitica/src/main/java/com/habitrpg/android/habitica/models/inventory/QuestColors.kt
2652787733
// "Replace with '@JvmInline value'" "true" // DISABLE-ERRORS <caret>inline class IC(val i: Int)
plugins/kotlin/idea/tests/testData/multiModuleQuickFix/inlineToValue/commonWithJvm/common/ic.kt
1614408978
/* * Copyright (c) 2015 Andrew O'Malley * * 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 com.github.andrewoma.kommon.lang import org.junit.Test import kotlin.test.assertEquals class StringExtensionsTest { @Test fun `truncateRight should return the right hand side of a string`() { assertEquals("", "hello".truncateRight(0)) assertEquals("llo", "hello".truncateRight(3)) assertEquals("hello", "hello".truncateRight(5)) assertEquals("hello", "hello".truncateRight(100)) } @Test fun `truncateRight should prefix on truncation`() { assertEquals("...", "hello".truncateRight(0, "...")) assertEquals("...llo", "hello".truncateRight(3, "...")) } }
src/test/kotlin/com/github/andrewoma/kommon/lang/StringExtensionsTest.kt
345687112
package com.github.jsonj import com.github.jsonj.tools.JsonBuilder import com.github.jsonj.tools.JsonBuilder.array import com.github.jsonj.tools.JsonBuilder.nullValue import com.github.jsonj.tools.JsonBuilder.primitive import org.apache.commons.lang3.StringUtils import java.lang.IllegalStateException import java.math.BigDecimal import java.math.BigInteger import java.util.Locale import kotlin.reflect.KClass import kotlin.reflect.KParameter import kotlin.reflect.KType import kotlin.reflect.full.cast import kotlin.reflect.full.declaredMemberProperties import kotlin.reflect.full.isSubtypeOf import kotlin.reflect.full.primaryConstructor import kotlin.reflect.full.starProjectedType import kotlin.reflect.full.withNullability import kotlin.reflect.jvm.jvmErasure fun obj(init: JsonObject.() -> Unit): JsonObject { val newObject = JsonObject() newObject.init() return newObject } fun arr(init: JsonArray.() -> Unit): JsonArray { val newObject = JsonArray() newObject.init() return newObject } fun JsonObject.field(key: String, vararg values: Any) { when (values.size) { 0 -> put(key, JsonBuilder.nullValue()) 1 -> put(key, values[0]) else -> put(key, JsonBuilder.array(*values)) } } fun JsonObject.arrayField(key: String, vararg values: Any) { put(key, JsonBuilder.array(*values)) } /** * @param property name * @param ignoreCase if true ignore case * @param ignoreUnderscores if true ignore underscores * @return the value of the first field matching the name or null */ fun JsonObject.flexGet(name: String, ignoreCase: Boolean = true, ignoreUnderscores: Boolean = true): JsonElement? { val key = keys.filter { normalize(it, ignoreCase, ignoreUnderscores) == normalize(name, ignoreCase, ignoreUnderscores) } .firstOrNull() return if (key != null) { val value = get(key) if (value?.isNull() == true) { // handle json null as null null } else { value } } else { null } } fun <T : Enum<*>> enumVal(clazz: KClass<T>, value: String): T? { val enumConstants = clazz.java.enumConstants return enumConstants.filter { value == it.name }.first() } /** * @param clazz a kotlin class * @return a new instance of clazz populated with values from the json object matched on the property names (ignoring case and underscores). */ fun <T : Any> JsonObject.construct(clazz: KClass<T>): T { val primaryConstructor = clazz.primaryConstructor val paramz: MutableMap<KParameter, Any?> = mutableMapOf() if (primaryConstructor != null) { primaryConstructor.parameters.forEach { val name = it.name.orEmpty() val nonNullableType = it.type.withNullability(false) if (nonNullableType.isSubtypeOf(Int::class.starProjectedType)) { paramz.put(it, flexGet(name)?.asInt()) } else if (nonNullableType.isSubtypeOf(Long::class.starProjectedType.withNullability(true))) { paramz.put(it, flexGet(name)?.asLong()) } else if (nonNullableType.isSubtypeOf(Float::class.starProjectedType.withNullability(true))) { paramz.put(it, flexGet(name)?.asFloat()) } else if (nonNullableType.isSubtypeOf(Double::class.starProjectedType.withNullability(true))) { paramz.put(it, flexGet(name)?.asDouble()) } else if (nonNullableType.isSubtypeOf(BigInteger::class.starProjectedType.withNullability(true))) { paramz.put(it, flexGet(name)?.asNumber()) } else if (nonNullableType.isSubtypeOf(BigDecimal::class.starProjectedType.withNullability(true))) { paramz.put(it, flexGet(name)?.asNumber()) } else if (nonNullableType.isSubtypeOf(Long::class.starProjectedType.withNullability(true))) { paramz.put(it, flexGet(name)?.asLong()) } else if (nonNullableType.isSubtypeOf(String::class.starProjectedType.withNullability(true))) { paramz.put(it, flexGet(name)?.asString()) } else if (nonNullableType.isSubtypeOf(Boolean::class.starProjectedType.withNullability(true))) { paramz.put(it, flexGet(name)?.asBoolean()) } else if (nonNullableType.isSubtypeOf(Enum::class.starProjectedType.withNullability(true))) { val enumName = flexGet(name)?.asString() if (enumName != null) { @Suppress("UNCHECKED_CAST") // we already checked but too hard for Kotlin to figure out paramz.put(it, enumVal(it.type.jvmErasure as KClass<Enum<*>>, enumName)) } } else if (nonNullableType.isSubtypeOf(JsonElement::class.starProjectedType.withNullability(true))) { paramz.put(it, flexGet(name)) } else { paramz.put(it, flexGet(name)?.asObject()?.construct(it.type.jvmErasure)) } } return primaryConstructor.callBy(paramz) } else { throw IllegalStateException("no primary constructor for ${clazz.qualifiedName}") } } /** * Attempt to populate the json object using the properties of the provided object. Field names are lower cased and underscored. * @param obj an object */ fun <T : Any> JsonObject.fill(obj: T): JsonObject { val clazz = obj::class for (memberProperty in clazz.declaredMemberProperties) { val propertyName = memberProperty.name val jsonName = toUnderscore(propertyName) try { val value = memberProperty.getter.call(obj) if (memberProperty.returnType.isSubtypeOf(Enum::class.starProjectedType)) { val enumValue = value as Enum<*> put(jsonName, enumValue.name) } else { val returnType = memberProperty.returnType val jsonElement: JsonElement = jsonElement(returnType, value) put(jsonName, jsonElement) } } catch (e: UnsupportedOperationException) { // function properties fail, skip those if (!(e.message?.contains("internal synthetic class") ?: false)) { throw e } else { @Suppress("UNCHECKED_CAST") // this seems to work ;-), ugly though val fn = (memberProperty.call(obj) ?: throw e) as Function0<Any> put(jsonName, fn.invoke()) } } } return this } private fun normalize(input: String, lower: Boolean = true, ignoreUnderscores: Boolean = true): String { val normalized = if (ignoreUnderscores) input.replace("_", "") else input return if (lower) normalized.toLowerCase(Locale.ROOT) else normalized } private fun toUnderscore(propertyName: String): String { return StringUtils.splitByCharacterTypeCamelCase(propertyName) .filter { !it.equals("_") } // avoid getting ___ .map { it.toLowerCase(Locale.ROOT) } .joinToString("_") } private fun jsonElement(returnType: KType, value: Any?): JsonElement { val jsonElement: JsonElement if (value == null) { return nullValue() } val nonNullableReturnType = returnType.withNullability(false) if (nonNullableReturnType.isSubtypeOf(JsonElement::class.starProjectedType)) { jsonElement = value as JsonElement } else if (nonNullableReturnType.isSubtypeOf(JsonDataObject::class.starProjectedType)) { jsonElement = (value as JsonDataObject).jsonObject } else if (nonNullableReturnType.isSubtypeOf(Number::class.starProjectedType) || nonNullableReturnType.isSubtypeOf(String::class.starProjectedType) || nonNullableReturnType.isSubtypeOf(Boolean::class.starProjectedType) ) { jsonElement = primitive(value) } else if (nonNullableReturnType.isSubtypeOf(Collection::class.starProjectedType)) { val arr = array() Collection::class.cast(value).forEach { if (it != null) { arr.add(jsonElement(it::class.starProjectedType, it)) } } jsonElement = arr } else if (nonNullableReturnType.isSubtypeOf(Map::class.starProjectedType)) { val newObj = JsonObject() Map::class.cast(value).forEach { if (it.key != null) { if (it.value != null) { newObj.put(toUnderscore(it.key.toString()), jsonElement(it::class.starProjectedType, it.value)) } } } jsonElement = newObj } else { val newObj = JsonObject() newObj.fill(value) jsonElement = newObj } return jsonElement }
src/main/kotlin/com/github/jsonj/JsonJExtensions.kt
1329812680
// 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.openapi.externalSystem.service.project.autoimport import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.externalSystem.ExternalSystemAutoImportAware import com.intellij.openapi.externalSystem.autoimport.* import com.intellij.openapi.externalSystem.importing.ImportSpecBuilder import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType.RESOLVE_PROJECT import com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode import com.intellij.openapi.externalSystem.service.internal.ExternalSystemProcessingManager import com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask import com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager import com.intellij.openapi.externalSystem.util.ExternalSystemUtil import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtil import java.io.File import java.util.concurrent.atomic.AtomicReference class ProjectAware( private val project: Project, override val projectId: ExternalSystemProjectId, private val autoImportAware: ExternalSystemAutoImportAware ) : ExternalSystemProjectAware { private val systemId = projectId.systemId private val projectPath = projectId.externalProjectPath override val settingsFiles: Set<String> get() = externalProjectFiles.map { FileUtil.toCanonicalPath(it.path) }.toSet() private val externalProjectFiles: List<File> get() = autoImportAware.getAffectedExternalProjectFiles(projectPath, project) override fun subscribe(listener: ExternalSystemProjectRefreshListener, parentDisposable: Disposable) { val progressManager = ExternalSystemProgressNotificationManager.getInstance() progressManager.addNotificationListener(TaskNotificationListener(listener), parentDisposable) } override fun reloadProject(context: ExternalSystemProjectReloadContext) { val importSpec = ImportSpecBuilder(project, systemId) if (!context.isExplicitReload) { importSpec.dontReportRefreshErrors() importSpec.dontNavigateToError() } if (!ExternalSystemUtil.isTrusted(project, systemId)) { importSpec.usePreviewMode() } ExternalSystemUtil.refreshProject(projectPath, importSpec) } private inner class TaskNotificationListener( val delegate: ExternalSystemProjectRefreshListener ) : ExternalSystemTaskNotificationListenerAdapter() { var externalSystemTaskId = AtomicReference<ExternalSystemTaskId?>(null) override fun onStart(id: ExternalSystemTaskId, workingDir: String?) { if (id.type != RESOLVE_PROJECT) return if (!FileUtil.pathsEqual(workingDir, projectPath)) return val task = ApplicationManager.getApplication().getService(ExternalSystemProcessingManager::class.java).findTask(id) if (task is ExternalSystemResolveProjectTask) { if (!autoImportAware.isApplicable(task.resolverPolicy)) { return } } externalSystemTaskId.set(id) delegate.beforeProjectRefresh() } private fun afterProjectRefresh(id: ExternalSystemTaskId, status: ExternalSystemRefreshStatus) { if (id.type != RESOLVE_PROJECT) return if (!externalSystemTaskId.compareAndSet(id, null)) return delegate.afterProjectRefresh(status) } override fun onSuccess(id: ExternalSystemTaskId) { afterProjectRefresh(id, ExternalSystemRefreshStatus.SUCCESS) } override fun onFailure(id: ExternalSystemTaskId, e: Exception) { afterProjectRefresh(id, ExternalSystemRefreshStatus.FAILURE) } override fun onCancel(id: ExternalSystemTaskId) { afterProjectRefresh(id, ExternalSystemRefreshStatus.CANCEL) } } }
platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/autoimport/ProjectAware.kt
2097050393
// "Create class 'BookKeeper'" "true" // ERROR: Type mismatch: inferred type is BookKeeper but Unit was expected // WITH_RUNTIME package pack import pack.Currrency.EUR enum class Currrency { EUR } class Item(val p1: Double, p2: Currrency) class Transaction(vararg val p: Item) fun place() { val transactions = listOf(Transaction(Item(10.0, EUR), Item(10.0, EUR))) if (transactions.isNotEmpty()) { return BookKee<caret>per(transactions) } }
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/callExpression/inReturn2.kt
4174275243
// WITH_RUNTIME open class A abstract class <caret>B: A() { // INFO: {"checked": "true", "toAbstract": "true"} val x = 1 // INFO: {"checked": "true", "toAbstract": "true"} val y: Int get() = 2 // INFO: {"checked": "true", "toAbstract": "true"} val z: Int by lazy { 3 } // INFO: {"checked": "true", "toAbstract": "true"} abstract val t: Int // INFO: {"checked": "true", "toAbstract": "true"} fun foo(n: Int): Boolean = n > 0 // INFO: {"checked": "true", "toAbstract": "true"} abstract fun bar(s: String) // INFO: {"checked": "true", "toAbstract": "true"} inner class X { } // INFO: {"checked": "true", "toAbstract": "true"} class Y { } }
plugins/kotlin/idea/tests/testData/refactoring/pullUp/k2k/fromClassToClassMakeAbstract.kt
2790269116
// WITH_RUNTIME import java.io.File fun main(args: Array<String>) { val reader = File("hello-world.txt").bufferedReader() <caret>try { // do stuff with reader } finally { reader.close() } }
plugins/kotlin/idea/tests/testData/intentions/convertTryFinallyToUseCall/example.kt
4210528712
/* * Copyright 2000-2016 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 org.jetbrains.debugger import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.thenAsyncAccept import org.jetbrains.debugger.values.Value import org.jetbrains.io.JsonUtil import java.util.* import java.util.regex.Pattern private val KEY_NOTATION_PROPERTY_NAME_PATTERN = Pattern.compile("[\\p{L}_$]+[\\d\\p{L}_$]*") object ValueModifierUtil { fun setValue(variable: Variable, newValue: String, evaluateContext: EvaluateContext, modifier: ValueModifier) = evaluateContext.evaluate(newValue) .thenAsyncAccept { modifier.setValue(variable, it.value, evaluateContext) } fun evaluateGet(variable: Variable, host: Any, evaluateContext: EvaluateContext, selfName: String): Promise<Value> { val builder = StringBuilder(selfName) appendUnquotedName(builder, variable.name) return evaluateContext.evaluate(builder.toString(), Collections.singletonMap(selfName, host), false) .then { variable.value = it.value it.value } } fun propertyNamesToString(list: List<String>, quotedAware: Boolean): String { val builder = StringBuilder() for (i in list.indices.reversed()) { val name = list[i] doAppendName(builder, name, quotedAware && (name[0] == '"' || name[0] == '\'')) } return builder.toString() } fun appendUnquotedName(builder: StringBuilder, name: String) { doAppendName(builder, name, false) } } private fun doAppendName(builder: StringBuilder, name: String, quoted: Boolean) { val useKeyNotation = !quoted && KEY_NOTATION_PROPERTY_NAME_PATTERN.matcher(name).matches() if (builder.length != 0) { builder.append(if (useKeyNotation) '.' else '[') } if (useKeyNotation) { builder.append(name) } else { if (quoted) { builder.append(name) } else { JsonUtil.escape(name, builder) } builder.append(']') } }
platform/script-debugger/backend/src/ValueModifierUtil.kt
1369824988
import java.util.ArrayList import kotlin.math.sqrt object ZumkellerNumbers { @JvmStatic fun main(args: Array<String>) { var n = 1 println("First 220 Zumkeller numbers:") run { var count = 1 while (count <= 220) { if (isZumkeller(n)) { print("%3d ".format(n)) if (count % 20 == 0) { println() } count++ } n += 1 } } n = 1 println("\nFirst 40 odd Zumkeller numbers:") run { var count = 1 while (count <= 40) { if (isZumkeller(n)) { print("%6d".format(n)) if (count % 10 == 0) { println() } count++ } n += 2 } } n = 1 println("\nFirst 40 odd Zumkeller numbers that do not end in a 5:") var count = 1 while (count <= 40) { if (n % 5 != 0 && isZumkeller(n)) { print("%8d".format(n)) if (count % 10 == 0) { println() } count++ } n += 2 } } private fun isZumkeller(n: Int): Boolean { // numbers congruent to 6 or 12 modulo 18 are Zumkeller numbers if (n % 18 == 6 || n % 18 == 12) { return true } val divisors = getDivisors(n) val divisorSum = divisors.stream().mapToInt { i: Int? -> i!! }.sum() // divisor sum cannot be odd if (divisorSum % 2 == 1) { return false } // numbers where n is odd and the abundance is even are Zumkeller numbers val abundance = divisorSum - 2 * n if (n % 2 == 1 && abundance > 0 && abundance % 2 == 0) { return true } divisors.sort() val j = divisors.size - 1 val sum = divisorSum / 2 // Largest divisor larger than sum - then cannot partition and not Zumkeller number return if (divisors[j] > sum) false else canPartition(j, divisors, sum, IntArray(2)) } private fun canPartition(j: Int, divisors: List<Int>, sum: Int, buckets: IntArray): Boolean { if (j < 0) { return true } for (i in 0..1) { if (buckets[i] + divisors[j] <= sum) { buckets[i] += divisors[j] if (canPartition(j - 1, divisors, sum, buckets)) { return true } buckets[i] -= divisors[j] } if (buckets[i] == 0) { break } } return false } private fun getDivisors(number: Int): MutableList<Int> { val divisors: MutableList<Int> = ArrayList() val sqrt = sqrt(number.toDouble()).toLong() for (i in 1..sqrt) { if (number % i == 0L) { divisors.add(i.toInt()) val div = (number / i).toInt() if (div.toLong() != i) { divisors.add(div) } } } return divisors } }
Zumkeller_numbers/Kotlin/src/ZumkellerNumbers.kt
2757939599
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtClass // OPTIONS: usages, constructorUsages // FIND_BY_REF // WITH_FILE_NAME package usages import library.* class X: A { constructor(n: Int): super(n) } class Y(): A(1) fun test() { val a: <caret>A = A() val aa = A(1) } // FIR_IGNORE
plugins/kotlin/idea/tests/testData/findUsages/libraryUsages/kotlinLibrary/LibraryClassUsages.0.kt
3966437582
/* * Copyright 2012-2016 Dmitri Pisarenko * * WWW: http://altruix.cc * E-Mail: [email protected] * Skype: dp118m (voice calls must be scheduled in advance) * * Physical address: * * 4-i Rostovskii pereulok 2/1/20 * 119121 Moscow * Russian Federation * * This file is part of econsim-tr01. * * econsim-tr01 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. * * econsim-tr01 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 econsim-tr01. If not, see <http://www.gnu.org/licenses/>. * */ package cc.altruix.econsimtr01.flourprod import cc.altruix.econsimtr01.DefaultSimulation import cc.altruix.econsimtr01.IAgent import cc.altruix.econsimtr01.ISensor import cc.altruix.econsimtr01.ResourceFlow import cc.altruix.econsimtr01.ch0202.SimResRow import org.joda.time.DateTime /** * @author Dmitri Pisarenko ([email protected]) * @version $Id$ * @since 1.0 */ class FlourProductionSimulation(val logTarget:StringBuilder, val flows:MutableList<ResourceFlow>, simParametersProvider: FlourProductionSimulationParametersProvider, val resultsStorage:MutableMap<DateTime, SimResRow<FlourProductionSimRowField>>) : DefaultSimulation(simParametersProvider){ override fun continueCondition(time: DateTime): Boolean = time.year <= 3 override fun createAgents(): List<IAgent> = simParametersProvider.agents override fun createSensors(): List<ISensor> = listOf(FlourProductionSimulationAccountant(resultsStorage, (simParametersProvider as FlourProductionSimulationParametersProvider) .data["SimulationName"].toString())) }
src/main/java/cc/altruix/econsimtr01/flourprod/FlourProductionSimulation.kt
3474664245
// WITH_RUNTIME fun foo() { var list = <caret>ArrayList<Int>() }
plugins/kotlin/idea/tests/testData/intentions/convertCollectionConstructorToFunction/replaceArrayListCallWithType.kt
362402721
@file:Suppress("RedundantVisibilityModifier") package co.zsmb.materialdrawerkt.draweritems.badgeable import com.mikepenz.materialdrawer.holder.BadgeStyle import com.mikepenz.materialdrawer.holder.StringHolder interface BadgeableKt { /** * The text of the displayed badge, as a StringHolder. * * Non-readable property. Wraps the [com.mikepenz.materialdrawer.model.interfaces.Badgeable.withBadge] method. * * You should use [co.zsmb.materialdrawerkt.draweritems.badge] instead. */ @Deprecated(level = DeprecationLevel.WARNING, message = "This property is for internal use. Use the badgeRes property or the badge method instead.") var badgeHolder: StringHolder /** * The text of the displayed badge as a String resource. * * Non-readable property. Wraps the [com.mikepenz.materialdrawer.model.interfaces.Badgeable.withBadge] method. */ var badgeRes: Int /** * The style of the displayed badge as a BadgeStyle. * * Non-readable property. Wraps the [com.mikepenz.materialdrawer.model.interfaces.ColorfulBadgeable.withBadgeStyle] * method. */ var badgeStyle: BadgeStyle }
library/src/main/java/co/zsmb/materialdrawerkt/draweritems/badgeable/BadgeableKt.kt
3966226634
// 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.util.indexing.roots import com.intellij.ide.lightEdit.LightEdit import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.* import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.containers.addIfNotNull import com.intellij.util.indexing.AdditionalIndexableFileSet import com.intellij.util.indexing.IndexableSetContributor import com.intellij.util.indexing.roots.builders.IndexableIteratorBuilders import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.WorkspaceEntityStorage import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import java.util.function.Predicate internal class DefaultProjectIndexableFilesContributor : IndexableFilesContributor { override fun getIndexableFiles(project: Project): List<IndexableFilesIterator> { @Suppress("DEPRECATION") if (indexProjectBasedOnIndexableEntityProviders()) { val builders: MutableList<IndexableEntityProvider.IndexableIteratorBuilder> = mutableListOf() val entityStorage = WorkspaceModel.getInstance(project).entityStorage.current for (provider in IndexableEntityProvider.EP_NAME.extensionList) { if (provider is IndexableEntityProvider.Existing) { addIteratorBuildersFromProvider(provider, entityStorage, project, builders) ProgressManager.checkCanceled() } } return IndexableIteratorBuilders.instantiateBuilders(builders, project, entityStorage) } else { val seenLibraries: MutableSet<Library> = HashSet() val seenSdks: MutableSet<Sdk> = HashSet() val modules = ModuleManager.getInstance(project).sortedModules val providers: MutableList<IndexableFilesIterator> = mutableListOf() for (module in modules) { providers.addAll(ModuleIndexableFilesIteratorImpl.getModuleIterators(module)) val orderEntries = ModuleRootManager.getInstance(module).orderEntries for (orderEntry in orderEntries) { when (orderEntry) { is LibraryOrderEntry -> { val library = orderEntry.library if (library != null && seenLibraries.add(library)) { @Suppress("DEPRECATION") providers.addIfNotNull(LibraryIndexableFilesIteratorImpl.createIterator(library)) } } is JdkOrderEntry -> { val sdk = orderEntry.jdk if (sdk != null && seenSdks.add(sdk)) { providers.add(SdkIndexableFilesIteratorImpl(sdk)) } } } } } return providers } } override fun getOwnFilePredicate(project: Project): Predicate<VirtualFile> { val projectFileIndex: ProjectFileIndex = ProjectFileIndex.getInstance(project) return Predicate { if (LightEdit.owns(project)) { return@Predicate false } if (projectFileIndex.isInContent(it) || projectFileIndex.isInLibrary(it)) { !FileTypeManager.getInstance().isFileIgnored(it) } else false } } companion object { private fun <E : WorkspaceEntity> addIteratorBuildersFromProvider(provider: IndexableEntityProvider.Existing<E>, entityStorage: WorkspaceEntityStorage, project: Project, iterators: MutableList<IndexableEntityProvider.IndexableIteratorBuilder>) { val entityClass = provider.entityClass for (entity in entityStorage.entities(entityClass)) { iterators.addAll(provider.getExistingEntityIteratorBuilder(entity, project)) } } /** * Registry property introduced to provide quick workaround for possible performance issues. * Should be removed when the feature becomes stable */ @ApiStatus.ScheduledForRemoval @Deprecated("Registry property introduced to provide quick workaround for possible performance issues. " + "Should be removed when the feature is proved to be stable", ReplaceWith("true")) @JvmStatic fun indexProjectBasedOnIndexableEntityProviders(): Boolean = Registry.`is`("indexing.enable.entity.provider.based.indexing") } } internal class AdditionalFilesContributor : IndexableFilesContributor { override fun getIndexableFiles(project: Project): List<IndexableFilesIterator> { return IndexableSetContributor.EP_NAME.extensionList.flatMap { listOf(IndexableSetContributorFilesIterator(it, true), IndexableSetContributorFilesIterator(it, false)) } } override fun getOwnFilePredicate(project: Project): Predicate<VirtualFile> { val additionalFilesContributor = AdditionalIndexableFileSet(project) return Predicate(additionalFilesContributor::isInSet) } } internal class AdditionalLibraryRootsContributor : IndexableFilesContributor { override fun getIndexableFiles(project: Project): List<IndexableFilesIterator> { return AdditionalLibraryRootsProvider.EP_NAME .extensionList .flatMap { it.getAdditionalProjectLibraries(project) } .map { SyntheticLibraryIndexableFilesIteratorImpl(it) } } override fun getOwnFilePredicate(project: Project): Predicate<VirtualFile> { return Predicate { false } // todo: synthetic library changes are served in DefaultProjectIndexableFilesContributor } companion object { @JvmStatic fun createIndexingIterator(presentableLibraryName: @Nls String?, rootsToIndex: List<VirtualFile>, libraryNameForDebug: String): IndexableFilesIterator = AdditionalLibraryIndexableAddedFilesIterator(presentableLibraryName, rootsToIndex, libraryNameForDebug) } }
platform/lang-impl/src/com/intellij/util/indexing/roots/standardContributors.kt
3932319741
// IS_APPLICABLE: false class A(val x: String) { class C {<caret>} constructor(x: String, y: Int) : this(x) { } }
plugins/kotlin/idea/tests/testData/intentions/removeEmptyClassBody/nestedClassFollowedBySecondaryConstructor.kt
4107946005
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ import kotlin.system.* fun main(args: Array<String>) { exitProcess(42) @Suppress("UNREACHABLE_CODE") throw RuntimeException("Exit function call returned normally") }
backend.native/tests/runtime/basic/exit.kt
2045178286
package xyz.dowenliu.ketcd.kv import com.google.protobuf.ByteString import xyz.dowenliu.ketcd.api.Compare /** * The compare predicate * * create at 2017/4/15 * @author liufl * @since 0.1.0 * * @property key Compare key * @property op CmpOp * @property target Compare target. */ class Cmp(private val key: ByteString, private val op: CmpOp, private val target: CmpTarget<*>) { /** * Predicate a [Compare] using in deeper gRPC APIs. * * @return A [Compare] predicated. */ fun toCompare(): Compare { val builder = Compare.newBuilder().setKey(key) .setResult(op.result) .setTarget(target.target) when (target) { is CmpTarget.VersionCmpTarget -> builder.version = target.targetValue is CmpTarget.ValueCmpTarget -> builder.value = target.targetValue is CmpTarget.ModRevisionCmpTarget -> builder.modRevision = target.targetValue is CmpTarget.CreateRevisionCmpTarget -> builder.createRevision = target.targetValue else -> throw IllegalArgumentException("Unexpected target type ($target)") } return builder.build() } /** * A sub collection of [Compare.CompareResult]. * * In a Txn operation, we only do EQUAL, GREATER and LESS compare. * * @property result The [Compare.CompareResult] wrapping. */ enum class CmpOp(val result: Compare.CompareResult) { /** * A wrapper for [Compare.CompareResult.EQUAL] */ EQUAL(Compare.CompareResult.EQUAL), /** * A wrapper for [Compare.CompareResult.GREATER] */ GREATER(Compare.CompareResult.GREATER), /** * A wrapper for [Compare.CompareResult.LESS] */ LESS(Compare.CompareResult.LESS) } }
ketcd-core/src/main/kotlin/xyz/dowenliu/ketcd/kv/Cmp.kt
726938053
package one.two fun write() { KotlinClass.staticLateinit = KotlinClass() }
plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/fromObject/fromCompanion/named/staticLateinit/Write.kt
1573685069
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.* import com.intellij.openapi.project.Project import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.createExpressionByPattern import org.jetbrains.kotlin.psi.expressionVisitor import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.isDynamic import org.jetbrains.kotlin.types.typeUtil.isNullableAny class UnsafeCastFromDynamicInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor = expressionVisitor(fun(expression) { val context = expression.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL) val expectedType = context[BindingContext.EXPECTED_EXPRESSION_TYPE, expression] ?: return val actualType = expression.getType(context) ?: return if (actualType.isDynamic() && !expectedType.isDynamic() && !expectedType.isNullableAny() && !TypeUtils.noExpectedType(expectedType) ) { holder.registerProblem( expression, KotlinBundle.message("implicit.unsafe.cast.from.dynamic.to.0", expectedType), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, CastExplicitlyFix(expectedType) ) } }) } private class CastExplicitlyFix(private val type: KotlinType) : LocalQuickFix { override fun getName() = KotlinBundle.message("cast.explicitly.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val expression = descriptor.psiElement as? KtExpression ?: return val typeName = type.constructor.declarationDescriptor?.name ?: return val pattern = if (type.isMarkedNullable) "$0 as? $1" else "$0 as $1" val newExpression = KtPsiFactory(expression).createExpressionByPattern(pattern, expression, typeName) expression.replace(newExpression) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnsafeCastFromDynamicInspection.kt
694637956
package soutvoid.com.DsrWeatherApp.ui.util import android.animation.Animator import android.annotation.TargetApi import android.content.Context import android.content.SharedPreferences import android.content.res.Resources import android.graphics.drawable.Drawable import android.support.annotation.StringRes import android.support.v4.app.FragmentManager import android.support.v4.content.ContextCompat import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.ViewAnimationUtils import android.view.ViewGroup import io.realm.* import soutvoid.com.DsrWeatherApp.R import soutvoid.com.DsrWeatherApp.domain.triggers.SavedTrigger import soutvoid.com.DsrWeatherApp.domain.triggers.condition.ConditionExpression import soutvoid.com.DsrWeatherApp.domain.triggers.condition.ConditionName import soutvoid.com.DsrWeatherApp.ui.receivers.RequestCode import soutvoid.com.DsrWeatherApp.ui.screen.main.settings.SettingsFragment import io.realm.RealmObject.deleteFromRealm import io.realm.RealmObject import io.realm.RealmList import soutvoid.com.DsrWeatherApp.domain.location.SavedLocation import java.math.BigInteger import java.security.SecureRandom import java.util.* fun ViewGroup.inflate(resId: Int): View { return LayoutInflater.from(context).inflate(resId, this, false) } /** * позволяет получить цвет из текущей темы * @param [attr] имя аттрибута из темы * @return цвет, полученный из темы */ fun Context.getThemeColor(attr: Int): Int { val typedValue: TypedValue = TypedValue() this.theme.resolveAttribute(attr, typedValue, true) return typedValue.data } fun Context.getThemedDrawable(attr: Int): Drawable { val typedValue = TypedValue() theme.resolveAttribute(attr, typedValue, true) return ContextCompat.getDrawable(this, typedValue.data) } /** * @return общий SharedPreferences для любого контекста */ fun Context.getDefaultPreferences(): SharedPreferences { return this.getSharedPreferences(SettingsFragment.SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE) } /** * чтобы добавить тему, напиши стиль в res-main styles, добавь записи в res-settings strings для экрана настроек, добавь опцию сюда * @return id текущей темы */ fun SharedPreferences.getPreferredThemeId(): Int { var themeNumber = getString(SettingsFragment.SHARED_PREFERENCES_THEME, "0").toInt() val preferDark = isDarkThemePreferred() if (preferDark) themeNumber += 100 //dark themes "zone" is 1xx when(themeNumber) { 0 -> return R.style.AppTheme_Light 1 -> return R.style.AppTheme_PurpleLight 2 -> return R.style.AppTheme_GreenLight 3 -> return R.style.AppTheme_RedLight 4 -> return R.style.AppTheme_BlueLight 5 -> return R.style.AppTheme_PinkLight 6 -> return R.style.AppTheme_DeepPurpleLight 7 -> return R.style.AppTheme_CyanLight 8 -> return R.style.AppTheme_TealLight 9 -> return R.style.AppTheme_YellowLight 10 -> return R.style.AppTheme_OrangeLight 11 -> return R.style.AppTheme_BrownLight 100 -> return R.style.AppTheme_Dark 101 -> return R.style.AppTheme_PurpleDark 102 -> return R.style.AppTheme_GreenDark 103 -> return R.style.AppTheme_RedDark 104 -> return R.style.AppTheme_BlueDark 105 -> return R.style.AppTheme_PinkDark 106 -> return R.style.AppTheme_Deep_purpleDark 107 -> return R.style.AppTheme_CyanDark 108 -> return R.style.AppTheme_TealDark 109 -> return R.style.AppTheme_YellowDark 110 -> return R.style.AppTheme_OrangeDark 111 -> return R.style.AppTheme_BrownDark else -> return R.style.AppTheme_Light } } fun SharedPreferences.isDarkThemePreferred(): Boolean { return getBoolean(SettingsFragment.SHARED_PREFERENCES_DARK_THEME, false) } fun View.dpToPx(dp: Double): Double { val scale = context.resources.displayMetrics.density return dp * scale + 0.5f } fun View.spToPx(sp: Float): Int { val px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, context.resources.displayMetrics).toInt() return px } @TargetApi(21) fun View.createFullScreenCircularReveal(startX: Int, startY: Int): Animator { return ViewAnimationUtils.createCircularReveal( this, startX, startY, 0f, maxOf(this.measuredHeight, this.measuredWidth).toFloat() ) } fun ConditionName.getNiceNameStringId(): Int { when(this) { ConditionName.temp -> return R.string.temperature ConditionName.humidity -> return R.string.humidity ConditionName.clouds -> return R.string.clouds ConditionName.pressure -> return R.string.pressure ConditionName.wind_direction -> return R.string.wind_direction ConditionName.wind_speed -> return R.string.wind_speed } } fun ConditionExpression.getNiceStringId(): Int { when(this) { ConditionExpression.gt -> return R.string.more_than ConditionExpression.lt -> return R.string.less_than else -> return R.string.equals } } /** * возвращает @param [alt], если this == null */ fun <T> T?.ifNotNullOr(alt: T): T { if (this == null) return alt else return this } fun <T> T?.ifNotNullOr(alt: () -> T): T { if (this == null) return alt() else return this } fun <T> List<T>.plusElementFront(element: T) : List<T> { val newList = this.toMutableList() newList.add(0, element) return newList.toList() } fun <T> realmListOf(elements: Iterable<T>): RealmList<T> where T: RealmModel{ val list = RealmList<T>() list.addAll(elements) return list } /** * получить сохраненные в бд триггеры по списку id */ fun getSavedTriggers(triggersIds: IntArray = intArrayOf()): List<SavedTrigger> { val realm = Realm.getDefaultInstance() var realmResults: RealmResults<SavedTrigger>? var list = emptyList<SavedTrigger>() if (triggersIds.isEmpty()) realmResults = realm.where(SavedTrigger::class.java).findAll() else realmResults = realm.where(SavedTrigger::class.java).`in`("id", triggersIds.toTypedArray()).findAll() if (realmResults != null) list = realm.copyFromRealm(realmResults) realm.close() return list } /** * сохранить внесенные изменения в бд */ private fun updateDbTriggers(triggers: List<SavedTrigger>) { val realm = Realm.getDefaultInstance() realm.executeTransaction { it.copyToRealmOrUpdate(triggers) } realm.close() } fun getNewRequestCode(): Int { val realm = Realm.getDefaultInstance() val requestCode = RequestCode() realm.executeTransaction { it.copyToRealm(requestCode) } realm.close() return requestCode.value } fun getAllRequestCodes(): List<Int> { val realm = Realm.getDefaultInstance() val realmResults = realm.where(RequestCode::class.java).findAll() var results = emptyList<Int>() realmResults?.let { results = realm.copyFromRealm(realmResults).map { it.value } } realm.close() return results } fun deleteAllRequestCodes() { val realm = Realm.getDefaultInstance() realm.executeTransaction { realm.where(RequestCode::class.java).findAll().deleteAllFromRealm() } realm.close() } fun getAllSavedLocations(): List<SavedLocation> { val realm = Realm.getDefaultInstance() val realmResults = realm.where(SavedLocation::class.java).findAll() var results: List<SavedLocation> = emptyList() realmResults?.let { results = realm.copyFromRealm(realmResults) } realm.close() return results } fun getRandomString(): String { val secureRandom = SecureRandom() return BigInteger(130, secureRandom).toString(32) } fun FragmentManager.clearBackStack() { kotlin.repeat(backStackEntryCount) {popBackStack()} } fun secondsToHours(seconds: Long): Long = seconds / 60 / 60 fun secondsToDays(seconds: Long): Long = secondsToHours(seconds) / 24 fun getHourOfDay(seconds: Long): Int { val calendar = Calendar.getInstance() calendar.timeInMillis = seconds * 1000 return calendar.get(Calendar.HOUR_OF_DAY) }
app/src/main/java/soutvoid/com/DsrWeatherApp/ui/util/Extensions.kt
608814413
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.idea.util.CommentSaver import org.jetbrains.kotlin.idea.util.textRangeIn import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.parentOrNull import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class ReplaceGuardClauseWithFunctionCallInspection : AbstractApplicabilityBasedInspection<KtIfExpression>( KtIfExpression::class.java ) { companion object { private const val ILLEGAL_STATE_EXCEPTION = "IllegalStateException" private const val ILLEGAL_ARGUMENT_EXCEPTION = "IllegalArgumentException" } private enum class KotlinFunction(val functionName: String) { CHECK("check"), CHECK_NOT_NULL("checkNotNull"), REQUIRE("require"), REQUIRE_NOT_NULL("requireNotNull"); val fqName: String get() = "kotlin.$functionName" } override fun inspectionText(element: KtIfExpression) = KotlinBundle.message("replace.guard.clause.with.kotlin.s.function.call") override val defaultFixText get() = KotlinBundle.message("replace.with.kotlin.s.function.call") override fun fixText(element: KtIfExpression) = element.getKotlinFunction()?.let { KotlinBundle.message("replace.with.0.call", it.functionName) } ?: defaultFixText override fun inspectionHighlightRangeInElement(element: KtIfExpression) = element.ifKeyword.textRangeIn(element) override fun isApplicable(element: KtIfExpression): Boolean { val languageVersionSettings = element.languageVersionSettings if (!languageVersionSettings.supportsFeature(LanguageFeature.UseReturnsEffect)) return false if (element.condition == null) return false val call = element.getCallExpression() ?: return false val calleeText = call.calleeExpression?.text ?: return false val valueArguments = call.valueArguments if (valueArguments.size > 1) return false if (calleeText != ILLEGAL_STATE_EXCEPTION && calleeText != ILLEGAL_ARGUMENT_EXCEPTION) return false val context = call.analyze(BodyResolveMode.PARTIAL_WITH_CFA) val argumentType = valueArguments.firstOrNull()?.getArgumentExpression()?.getType(context) if (argumentType != null && !KotlinBuiltIns.isStringOrNullableString(argumentType)) return false if (element.isUsedAsExpression(context)) return false val fqName = call.getResolvedCall(context)?.resultingDescriptor?.fqNameSafe?.parentOrNull() return fqName == FqName("kotlin.$calleeText") || fqName == FqName("java.lang.$calleeText") } override fun applyTo(element: KtIfExpression, project: Project, editor: Editor?) { val condition = element.condition ?: return val call = element.getCallExpression() ?: return val argument = call.valueArguments.firstOrNull()?.getArgumentExpression() val commentSaver = CommentSaver(element) val psiFactory = KtPsiFactory(element) val replaced = when (val kotlinFunction = element.getKotlinFunction(call)) { KotlinFunction.CHECK, KotlinFunction.REQUIRE -> { val (excl, newCondition) = if (condition is KtPrefixExpression && condition.operationToken == KtTokens.EXCL) { "" to (condition.baseExpression ?: return) } else { "!" to condition } val newExpression = if (argument == null) { psiFactory.createExpressionByPattern("${kotlinFunction.fqName}($excl$0)", newCondition) } else { psiFactory.createExpressionByPattern("${kotlinFunction.fqName}($excl$0) { $1 }", newCondition, argument) } val replaced = element.replaceWith(newExpression, psiFactory) val newCall = (replaced as? KtDotQualifiedExpression)?.callExpression val negatedExpression = newCall?.valueArguments?.firstOrNull()?.getArgumentExpression() as? KtPrefixExpression if (negatedExpression != null) { SimplifyNegatedBinaryExpressionInspection.simplifyNegatedBinaryExpressionIfNeeded(negatedExpression) } replaced } KotlinFunction.CHECK_NOT_NULL, KotlinFunction.REQUIRE_NOT_NULL -> { val nullCheckedExpression = condition.notNullCheckExpression() ?: return val newExpression = if (argument == null) { psiFactory.createExpressionByPattern("${kotlinFunction.fqName}($0)", nullCheckedExpression) } else { psiFactory.createExpressionByPattern("${kotlinFunction.fqName}($0) { $1 }", nullCheckedExpression, argument) } element.replaceWith(newExpression, psiFactory) } else -> return } commentSaver.restore(replaced) editor?.caretModel?.moveToOffset(replaced.startOffset) ShortenReferences.DEFAULT.process(replaced) } private fun KtIfExpression.replaceWith(newExpression: KtExpression, psiFactory: KtPsiFactory): KtExpression { val parent = parent val elseBranch = `else` return if (elseBranch != null) { val added = parent.addBefore(newExpression, this) as KtExpression parent.addBefore(psiFactory.createNewLine(), this) replaceWithBranch(elseBranch, isUsedAsExpression = false, keepBraces = false) added } else { replaced(newExpression) } } private fun KtIfExpression.getCallExpression(): KtCallExpression? { val throwExpression = this.then?.let { it as? KtThrowExpression ?: (it as? KtBlockExpression)?.statements?.singleOrNull() as? KtThrowExpression } ?: return null return throwExpression.thrownExpression?.let { it as? KtCallExpression ?: (it as? KtQualifiedExpression)?.callExpression } } private fun KtIfExpression.getKotlinFunction(call: KtCallExpression? = getCallExpression()): KotlinFunction? { val calleeText = call?.calleeExpression?.text ?: return null val isNotNullCheck = condition.notNullCheckExpression() != null return when (calleeText) { ILLEGAL_STATE_EXCEPTION -> if (isNotNullCheck) KotlinFunction.CHECK_NOT_NULL else KotlinFunction.CHECK ILLEGAL_ARGUMENT_EXCEPTION -> if (isNotNullCheck) KotlinFunction.REQUIRE_NOT_NULL else KotlinFunction.REQUIRE else -> null } } private fun KtExpression?.notNullCheckExpression(): KtExpression? { if (this == null) return null if (this !is KtBinaryExpression) return null if (this.operationToken != KtTokens.EQEQ) return null val left = this.left ?: return null val right = this.right ?: return null return when { right.isNullConstant() -> left left.isNullConstant() -> right else -> null } } private fun KtExpression.isNullConstant(): Boolean { return (this as? KtConstantExpression)?.text == KtTokens.NULL_KEYWORD.value } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceGuardClauseWithFunctionCallInspection.kt
1188236748
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.ui.feed import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.WindowInsetsCompat import androidx.core.view.doOnLayout import androidx.core.view.isVisible import androidx.core.view.updatePadding import androidx.fragment.app.activityViewModels import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.RecyclerView import com.google.common.collect.ImmutableMap import com.google.samples.apps.iosched.databinding.FragmentFeedBinding import com.google.samples.apps.iosched.model.SessionId import com.google.samples.apps.iosched.shared.analytics.AnalyticsHelper import com.google.samples.apps.iosched.ui.MainActivityViewModel import com.google.samples.apps.iosched.ui.MainNavigationFragment import com.google.samples.apps.iosched.ui.feed.FeedNavigationAction.NavigateAction import com.google.samples.apps.iosched.ui.feed.FeedNavigationAction.NavigateToScheduleAction import com.google.samples.apps.iosched.ui.feed.FeedNavigationAction.NavigateToSession import com.google.samples.apps.iosched.ui.feed.FeedNavigationAction.OpenLiveStreamAction import com.google.samples.apps.iosched.ui.feed.FeedNavigationAction.OpenSignInDialogAction import com.google.samples.apps.iosched.ui.messages.SnackbarMessageManager import com.google.samples.apps.iosched.ui.messages.setupSnackbarManager import com.google.samples.apps.iosched.ui.signin.SignInDialogFragment import com.google.samples.apps.iosched.ui.signin.setupProfileMenuItem import com.google.samples.apps.iosched.util.doOnApplyWindowInsets import com.google.samples.apps.iosched.util.launchAndRepeatWithViewLifecycle import com.google.samples.apps.iosched.util.openWebsiteUrl import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collect import javax.inject.Inject @AndroidEntryPoint class FeedFragment : MainNavigationFragment() { companion object { private const val DIALOG_NEED_TO_SIGN_IN = "dialog_need_to_sign_in" private const val BUNDLE_KEY_SESSIONS_LAYOUT_MANAGER_STATE = "sessions_layout_manager" } @Inject lateinit var snackbarMessageManager: SnackbarMessageManager @Inject lateinit var analyticsHelper: AnalyticsHelper private val model: FeedViewModel by viewModels() private val mainActivityViewModel: MainActivityViewModel by activityViewModels() private lateinit var binding: FragmentFeedBinding private var adapter: FeedAdapter? = null private lateinit var sessionsViewBinder: FeedSessionsViewBinder override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentFeedBinding.inflate( inflater, container, false ).apply { lifecycleOwner = viewLifecycleOwner viewModel = model } return binding.root } override fun onSaveInstanceState(outState: Bundle) { if (::sessionsViewBinder.isInitialized) { outState.putParcelable( BUNDLE_KEY_SESSIONS_LAYOUT_MANAGER_STATE, sessionsViewBinder.recyclerViewManagerState ) } super.onSaveInstanceState(outState) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) analyticsHelper.sendScreenView("Home", requireActivity()) binding.toolbar.setupProfileMenuItem(mainActivityViewModel, viewLifecycleOwner) binding.root.doOnApplyWindowInsets { _, insets, _ -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) binding.statusBar.run { layoutParams.height = systemBars.top isVisible = layoutParams.height > 0 requestLayout() } } if (adapter == null) { // Initialising sessionsViewBinder here to handle config change. sessionsViewBinder = FeedSessionsViewBinder( model, savedInstanceState?.getParcelable( BUNDLE_KEY_SESSIONS_LAYOUT_MANAGER_STATE ) ) } binding.recyclerView.doOnApplyWindowInsets { v, insets, padding -> val systemInsets = insets.getInsets( WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.ime() ) v.updatePadding(bottom = padding.bottom + systemInsets.bottom) } binding.snackbar.doOnApplyWindowInsets { v, insets, padding -> val systemInsets = insets.getInsets( WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.ime() ) v.updatePadding(bottom = padding.bottom + systemInsets.bottom) } setupSnackbarManager(snackbarMessageManager, binding.snackbar) // Observe feed launchAndRepeatWithViewLifecycle { model.feed.collect { showFeedItems(binding.recyclerView, it) } } // Observe navigation events launchAndRepeatWithViewLifecycle { model.navigationActions.collect { action -> when (action) { is NavigateAction -> findNavController().navigate(action.directions) NavigateToScheduleAction -> findNavController().navigate(FeedFragmentDirections.toSchedule()) is NavigateToSession -> openSessionDetail(action.sessionId) is OpenLiveStreamAction -> openLiveStreamUrl(action.url) OpenSignInDialogAction -> openSignInDialog() } } } } private fun openSessionDetail(id: SessionId) { // TODO support opening a session detail // findNavController().navigate(toSessionDetail(id)) } private fun showFeedItems(recyclerView: RecyclerView, list: List<Any>?) { if (adapter == null) { val sectionHeaderViewBinder = FeedSectionHeaderViewBinder() val countdownViewBinder = CountdownViewBinder() val momentViewBinder = MomentViewBinder( eventListener = model, userInfo = model.userInfo, theme = model.theme ) val sessionsViewBinder = FeedSessionsViewBinder(model) val feedAnnouncementsHeaderViewBinder = AnnouncementsHeaderViewBinder(this, model) val announcementViewBinder = AnnouncementViewBinder(model.timeZoneId, this) val announcementsEmptyViewBinder = AnnouncementsEmptyViewBinder() val announcementsLoadingViewBinder = AnnouncementsLoadingViewBinder() val feedSustainabilitySectionViewBinder = FeedSustainabilitySectionViewBinder() val feedSocialChannelsSectionViewBinder = FeedSocialChannelsSectionViewBinder() @Suppress("UNCHECKED_CAST") val viewBinders = ImmutableMap.builder<FeedItemClass, FeedItemBinder>() .put( sectionHeaderViewBinder.modelClass, sectionHeaderViewBinder as FeedItemBinder ) .put( countdownViewBinder.modelClass, countdownViewBinder as FeedItemBinder ) .put( momentViewBinder.modelClass, momentViewBinder as FeedItemBinder ) .put( sessionsViewBinder.modelClass, sessionsViewBinder as FeedItemBinder ) .put( feedAnnouncementsHeaderViewBinder.modelClass, feedAnnouncementsHeaderViewBinder as FeedItemBinder ) .put( announcementViewBinder.modelClass, announcementViewBinder as FeedItemBinder ) .put( announcementsEmptyViewBinder.modelClass, announcementsEmptyViewBinder as FeedItemBinder ) .put( announcementsLoadingViewBinder.modelClass, announcementsLoadingViewBinder as FeedItemBinder ) .put( feedSustainabilitySectionViewBinder.modelClass, feedSustainabilitySectionViewBinder as FeedItemBinder ) .put( feedSocialChannelsSectionViewBinder.modelClass, feedSocialChannelsSectionViewBinder as FeedItemBinder ) .build() adapter = FeedAdapter(viewBinders) } if (recyclerView.adapter == null) { recyclerView.adapter = adapter } (recyclerView.adapter as FeedAdapter).submitList(list ?: emptyList()) // After submitting the list to the adapter, the recycler view starts measuring and drawing // so let's wait for the layout to be drawn before reporting fully drawn. binding.recyclerView.doOnLayout { // reportFullyDrawn() prints `I/ActivityTaskManager: Fully drawn {activity} {time}` // to logcat. The framework ensures that the statement is printed only once for the // activity, so there is no need to add dedupping logic to the app. activity?.reportFullyDrawn() } } private fun openSignInDialog() { SignInDialogFragment().show( requireActivity().supportFragmentManager, DIALOG_NEED_TO_SIGN_IN ) } private fun openLiveStreamUrl(url: String) { openWebsiteUrl(requireContext(), url) } }
mobile/src/main/java/com/google/samples/apps/iosched/ui/feed/FeedFragment.kt
3655353836
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.gradle.statistics import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.startup.ProjectPostStartupActivity import kotlinx.coroutines.delay import org.jetbrains.kotlin.statistics.BuildSessionLogger import org.jetbrains.kotlin.statistics.BuildSessionLogger.Companion.STATISTICS_FOLDER_NAME import org.jetbrains.kotlin.statistics.fileloggers.MetricsContainer import java.io.File import java.util.concurrent.atomic.AtomicBoolean import kotlin.io.path.Path import kotlin.io.path.exists import kotlin.time.Duration.Companion.minutes class KotlinGradleFUSLogger : ProjectPostStartupActivity { override suspend fun execute(project: Project) { while (true) { delay(EXECUTION_DELAY_MIN.minutes) reportStatistics() } } companion object { /** * Maximum amount of directories which were reported as gradle user dirs * These directories should be monitored for reported gradle statistics. */ private const val MAXIMUM_USER_DIRS = 10 /** * Delay between sequential checks of gradle statistics */ const val EXECUTION_DELAY_MIN = 60L /** * Property name used for persisting gradle user dirs */ private const val GRADLE_USER_DIRS_PROPERTY_NAME = "kotlin-gradle-user-dirs" private val isRunning = AtomicBoolean(false) fun reportStatistics() { if (isRunning.compareAndSet(false, true)) { try { for (gradleUserHome in gradleUserDirs) { BuildSessionLogger.listProfileFiles(File(gradleUserHome, STATISTICS_FOLDER_NAME))?.forEach { statisticFile -> var fileWasRead = true try { var previousEvent: MetricsContainer? = null fileWasRead = MetricsContainer.readFromFile(statisticFile) { metricContainer -> KotlinGradleFUSCollector.reportMetrics(metricContainer, previousEvent) previousEvent = metricContainer } } catch (e: Exception) { Logger.getInstance(KotlinGradleFUSCollector::class.java) .info("Failed to process file ${statisticFile.absolutePath}: ${e.message}", e) } finally { if (fileWasRead && !statisticFile.delete()) { Logger.getInstance(KotlinGradleFUSCollector::class.java) .warn("[FUS] Failed to delete file ${statisticFile.absolutePath}") } } } } } finally { isRunning.set(false) } } } private var gradleUserDirs: List<String> set(value) = PropertiesComponent.getInstance().setList( GRADLE_USER_DIRS_PROPERTY_NAME, value ) get() = PropertiesComponent.getInstance().getList(GRADLE_USER_DIRS_PROPERTY_NAME) ?: emptyList() fun populateGradleUserDir(path: String) { val currentState = gradleUserDirs if (path in currentState) return val result = ArrayList<String>() result.add(path) result.addAll(currentState) gradleUserDirs = result.filter { filePath -> Path(filePath).exists() }.take(MAXIMUM_USER_DIRS) } } }
plugins/kotlin/gradle/gradle/src/org/jetbrains/kotlin/idea/gradle/statistics/KotlinGradleFUSLogger.kt
1467875084
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.health.services.client.data import androidx.health.services.client.PassiveListenerCallback import androidx.health.services.client.proto.DataProto /** * Defines configuration for a passive monitoring listener request using Health Services. * * @constructor Creates a new [PassiveListenerConfig] which defines a request for passive monitoring * using Health Services * * @property dataTypes set of [DataType]s which should be tracked. Requested data will be returned * by [PassiveListenerCallback.onNewDataPointsReceived]. * @property shouldUserActivityInfoBeRequested whether to request [UserActivityInfo] updates. Data * will be returned by [PassiveListenerCallback.onUserActivityInfoReceived]. If set to true, calling * app must have [android.Manifest.permission.ACTIVITY_RECOGNITION]. * @property dailyGoals set of daily [PassiveGoal]s which should be tracked. Achieved goals will be * returned by [PassiveListenerCallback.onGoalCompleted]. * @property healthEventTypes set of [HealthEvent.Type] which should be tracked. Detected health * events will be returned by [PassiveListenerCallback.onHealthEventReceived]. */ @Suppress("ParcelCreator") public class PassiveListenerConfig( public val dataTypes: Set<DataType<out Any, out DataPoint<out Any>>>, @get:JvmName("shouldUserActivityInfoBeRequested") public val shouldUserActivityInfoBeRequested: Boolean, public val dailyGoals: Set<PassiveGoal>, public val healthEventTypes: Set<HealthEvent.Type> ) { internal constructor( proto: DataProto.PassiveListenerConfig ) : this( proto.dataTypesList.map { DataType.deltaFromProto(it) }.toSet(), proto.includeUserActivityState, proto.passiveGoalsList.map { PassiveGoal(it) }.toSet(), proto.healthEventTypesList .map { HealthEvent.Type.fromProto(it) } .toSet() ) internal fun isValidPassiveGoal(): Boolean { // Check if the registered goals are also tracked for (passiveGoal: PassiveGoal in dailyGoals) { if (!dataTypes.contains(passiveGoal.dataTypeCondition.dataType)) return false } return true } /** Builder for [PassiveListenerConfig] instances. */ public class Builder { private var dataTypes: Set<DataType<*, *>> = emptySet() private var requestUserActivityState: Boolean = false private var dailyGoals: Set<PassiveGoal> = emptySet() private var healthEventTypes: Set<HealthEvent.Type> = emptySet() /** Sets the requested [DataType]s that should be passively tracked. */ public fun setDataTypes(dataTypes: Set<DataType<*, *>>): Builder { this.dataTypes = dataTypes.toSet() return this } /** * Sets whether to request the [UserActivityState] updates. If not set they will not be * included by default and [PassiveListenerCallback.onUserActivityInfoReceived] will not be invoked. * [UserActivityState] requires [android.Manifest.permission.ACTIVITY_RECOGNITION]. * * @param shouldUserActivityInfoBeRequested whether to request user activity state tracking */ @Suppress("MissingGetterMatchingBuilder") fun setShouldUserActivityInfoBeRequested( shouldUserActivityInfoBeRequested: Boolean ): Builder { this.requestUserActivityState = shouldUserActivityInfoBeRequested return this } /** * Sets the requested daily [PassiveGoal]s that should be passively tracked. * * @param dailyGoals the daily [PassiveGoal]s that should be tracked passively */ public fun setDailyGoals(dailyGoals: Set<PassiveGoal>): Builder { this.dailyGoals = dailyGoals.toSet() return this } /** * Sets the requested [HealthEvent.Type]s that should be passively tracked. * * @param healthEventTypes the [HealthEvent.Type]s that should be tracked passively */ public fun setHealthEventTypes(healthEventTypes: Set<HealthEvent.Type>): Builder { this.healthEventTypes = healthEventTypes.toSet() return this } /** Returns the built [PassiveListenerConfig]. */ public fun build(): PassiveListenerConfig { return PassiveListenerConfig( dataTypes, requestUserActivityState, dailyGoals, healthEventTypes ) } } internal val proto: DataProto.PassiveListenerConfig = DataProto.PassiveListenerConfig.newBuilder() .addAllDataTypes(dataTypes.map { it.proto }) .setIncludeUserActivityState(shouldUserActivityInfoBeRequested) .addAllPassiveGoals(dailyGoals.map { it.proto }) .addAllHealthEventTypes(healthEventTypes.map { it.toProto() }) .build() public companion object { @JvmStatic public fun builder(): Builder = Builder() } }
health/health-services-client/src/main/java/androidx/health/services/client/data/PassiveListenerConfig.kt
3561215814
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.q.discovery import com.netflix.appinfo.InstanceInfo.InstanceStatus import com.netflix.appinfo.InstanceInfo.InstanceStatus.OUT_OF_SERVICE import com.netflix.appinfo.InstanceInfo.InstanceStatus.UP import com.netflix.discovery.StatusChangeEvent import com.netflix.spinnaker.kork.eureka.RemoteStatusChangedEvent import com.netflix.spinnaker.spek.and import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it object DiscoveryActivatorTest : Spek({ describe("a discovery-activated poller") { val subject = DiscoveryActivator() describe("by default") { it("is disabled") { assertThat(subject.enabled).isFalse() } } given("the instance is up in discovery") { beforeGroup { subject.triggerEvent(OUT_OF_SERVICE, UP) } it("is enabled") { assertThat(subject.enabled).isTrue() } and("the instance goes out of service") { beforeGroup { subject.triggerEvent(UP, OUT_OF_SERVICE) } it("is disabled again") { assertThat(subject.enabled).isFalse() } } } } }) private fun DiscoveryActivator.triggerEvent(from: InstanceStatus, to: InstanceStatus) = onApplicationEvent(event(from, to)) private fun event(from: InstanceStatus, to: InstanceStatus) = RemoteStatusChangedEvent(StatusChangeEvent(from, to))
keiko-spring/src/test/kotlin/com/netflix/spinnaker/q/discovery/DiscoveryActivatorTest.kt
3037329047
/* * Copyright (c) 2022, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be * used to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package no.nordicsemi.android.dfu.app import android.content.Intent import android.os.Bundle import androidx.activity.compose.setContent import androidx.compose.material3.Surface import dagger.hilt.android.AndroidEntryPoint import no.nordicsemi.android.common.navigation.NavigationView import no.nordicsemi.android.common.theme.NordicActivity import no.nordicsemi.android.common.theme.NordicTheme import no.nordicsemi.android.dfu.analytics.DfuAnalytics import no.nordicsemi.android.dfu.analytics.HandleDeepLinkEvent import no.nordicsemi.android.dfu.profile.DFUDestinations import no.nordicsemi.android.dfu.profile.scanner.ScannerDestinations import no.nordicsemi.android.dfu.storage.DeepLinkHandler import javax.inject.Inject @AndroidEntryPoint class MainActivity : NordicActivity() { @Inject lateinit var linkHandler: DeepLinkHandler @Inject lateinit var analytics: DfuAnalytics override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (linkHandler.handleDeepLink(intent)) { analytics.logEvent(HandleDeepLinkEvent) } setContent { NordicTheme { NavigationView(DFUDestinations + ScannerDestinations) } } } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) if (linkHandler.handleDeepLink(intent)) { analytics.logEvent(HandleDeepLinkEvent) } } }
app/src/main/java/no/nordicsemi/android/dfu/app/MainActivity.kt
3148083694
// 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 git4idea.checkin import com.intellij.dvcs.commit.getCommitAndPushActionName import com.intellij.dvcs.ui.DvcsBundle import com.intellij.openapi.components.Service import com.intellij.openapi.util.Key import com.intellij.openapi.vcs.changes.CommitContext import com.intellij.openapi.vcs.changes.CommitExecutorWithRichDescription import com.intellij.openapi.vcs.changes.CommitSession import com.intellij.vcs.commit.CommitWorkflowHandlerState import com.intellij.vcs.commit.commitProperty import org.jetbrains.annotations.Nls private val IS_PUSH_AFTER_COMMIT_KEY = Key.create<Boolean>("Git.Commit.IsPushAfterCommit") internal var CommitContext.isPushAfterCommit: Boolean by commitProperty(IS_PUSH_AFTER_COMMIT_KEY) @Service(Service.Level.PROJECT) internal class GitCommitAndPushExecutor : CommitExecutorWithRichDescription { @Nls override fun getActionText(): String = DvcsBundle.message("action.commit.and.push.text") override fun getText(state: CommitWorkflowHandlerState): String { return getCommitAndPushActionName(state) } override fun useDefaultAction(): Boolean = false override fun requiresSyncCommitChecks(): Boolean = true override fun getId(): String = ID override fun supportsPartialCommit(): Boolean = true override fun createCommitSession(commitContext: CommitContext): CommitSession { commitContext.isPushAfterCommit = true return CommitSession.VCS_COMMIT } companion object { internal const val ID = "Git.Commit.And.Push.Executor" } }
plugins/git4idea/src/git4idea/checkin/GitCommitAndPushExecutor.kt
259641008
// 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.internal.statistic.eventLog.events import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.internal.statistic.StructuredIdeActivity import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule import com.intellij.internal.statistic.service.fus.collectors.FeatureUsageCollectorExtension import com.intellij.internal.statistic.utils.PluginInfo import com.intellij.internal.statistic.utils.getPluginInfo import com.intellij.internal.statistic.utils.getPluginInfoByDescriptor import com.intellij.lang.Language import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.util.Version import org.jetbrains.annotations.NonNls import java.awt.event.KeyEvent import java.awt.event.MouseEvent import org.intellij.lang.annotations.Language as InjectedLanguage @Suppress("FunctionName") object EventFields { /** * Creates a field that will be validated by global regexp rule * @param name name of the field * @param regexpRef reference to global regexp, e.g "integer" for "{regexp#integer}" */ @JvmStatic fun StringValidatedByRegexp(@NonNls name: String, @NonNls regexpRef: String): StringEventField { return StringEventField.ValidatedByRegexp(name, regexpRef) } /** * Creates a field that will be validated by global enum rule * @param name name of the field * @param enumRef reference to global enum, e.g "os" for "{enum#os}" */ @JvmStatic fun StringValidatedByEnum(@NonNls name: String, @NonNls enumRef: String): StringEventField { return StringEventField.ValidatedByEnum(name, enumRef) } /** * Creates a field that will be validated by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule] * @param name name of the field * @param customRuleId ruleId that is accepted by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule.acceptRuleId], * e.g "class_name" for "{util#class_name}" */ @kotlin.Deprecated("Please use EventFields.StringValidatedByCustomRule(String, Class<out CustomValidationRule>)", ReplaceWith("EventFields.StringValidatedByCustomRule(name, customValidationRule)")) @JvmStatic fun StringValidatedByCustomRule(@NonNls name: String, @NonNls customRuleId: String): StringEventField { return StringEventField.ValidatedByCustomRule(name, customRuleId) } /** * Creates a field that will be validated by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule] * @param name name of the field * @param customValidationRule inheritor of [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule], */ @JvmStatic fun StringValidatedByCustomRule(@NonNls name: String, customValidationRule: Class<out CustomValidationRule>): StringEventField = StringEventField.ValidatedByCustomValidationRule(name, customValidationRule) /** * Creates a field that will be validated by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule]. * @param name name of the field */ inline fun <reified T : CustomValidationRule> StringValidatedByCustomRule(@NonNls name: String): StringEventField = StringValidatedByCustomRule(name, T::class.java) /** * Creates a field that allows only a specific list of values * @param name name of the field * @param allowedValues list of allowed values, e.g [ "bool", "int", "float"] */ @JvmStatic fun String(@NonNls name: String, allowedValues: List<String>): StringEventField = StringEventField.ValidatedByAllowedValues(name, allowedValues) @JvmStatic fun Int(@NonNls name: String): IntEventField = IntEventField(name) /** * Creates an int field that will be validated by regexp rule * @param name name of the field * @param regexp regular expression, e.g "-?[0-9]{1,3}" * Please choose regexp carefully to avoid reporting any sensitive data. */ @JvmStatic fun RegexpInt(@NonNls name: String, @InjectedLanguage("RegExp") @NonNls regexp: String): RegexpIntEventField = RegexpIntEventField(name, regexp) /** * Rounds integer value to the next power of two. * Use it to anonymize sensitive information like the number of files in a project. * @see com.intellij.internal.statistic.utils.StatisticsUtil.roundToPowerOfTwo */ @JvmStatic fun RoundedInt(@NonNls name: String): RoundedIntEventField = RoundedIntEventField(name) @JvmStatic fun Long(@NonNls name: String): LongEventField = LongEventField(name) /** * Rounds long value to the next power of two. * Use it to anonymize sensitive information like the number of files in a project. * @see com.intellij.internal.statistic.utils.StatisticsUtil.roundToPowerOfTwo */ @JvmStatic fun RoundedLong(@NonNls name: String): RoundedLongEventField = RoundedLongEventField(name) @JvmStatic fun Float(@NonNls name: String): FloatEventField = FloatEventField(name) @JvmStatic fun Double(@NonNls name: String): DoubleEventField = DoubleEventField(name) @JvmStatic fun Boolean(@NonNls name: String): BooleanEventField = BooleanEventField(name) @JvmStatic fun Class(@NonNls name: String): ClassEventField = ClassEventField(name) val defaultEnumTransform: (Any) -> String = { it.toString() } @JvmStatic @JvmOverloads fun <T : Enum<*>> Enum(@NonNls name: String, enumClass: Class<T>, transform: (T) -> String = defaultEnumTransform): EnumEventField<T> = EnumEventField(name, enumClass, transform) inline fun <reified T : Enum<*>> Enum(@NonNls name: String, noinline transform: (T) -> String = defaultEnumTransform): EnumEventField<T> = EnumEventField(name, T::class.java, transform) /** * Creates a field for a list, each element of which will be validated by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule] * @param name name of the field * @param customRuleId ruleId that is accepted by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule.acceptRuleId], * e.g "class_name" for "{util#class_name}" */ @kotlin.Deprecated("Please use EventFields.StringListValidatedByCustomRule(String, Class<out CustomValidationRule>)", ReplaceWith("EventFields.StringListValidatedByCustomRule(name, customValidationRule)")) @JvmStatic fun StringListValidatedByCustomRule(@NonNls name: String, @NonNls customRuleId: String): StringListEventField = StringListEventField.ValidatedByCustomRule(name, customRuleId) /** * Creates a field for a list, each element of which will be validated by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule] * @param name name of the field * @param customValidationRule inheritor of [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule] */ @JvmStatic fun StringListValidatedByCustomRule(@NonNls name: String, customValidationRule: Class<out CustomValidationRule>): StringListEventField = StringListEventField.ValidatedByCustomValidationRule(name, customValidationRule) /** * Creates a field for a list, each element of which will be validated by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule] * @param name name of the field */ inline fun <reified T : CustomValidationRule> StringListValidatedByCustomRule(@NonNls name: String): StringListEventField = StringListValidatedByCustomRule(name, T::class.java) /** * Creates a field for a list, each element of which will be validated by global enum rule * @param name name of the field * @param enumRef reference to global enum, e.g "os" for "{enum#os}" */ @JvmStatic fun StringListValidatedByEnum(@NonNls name: String, @NonNls enumRef: String): StringListEventField = StringListEventField.ValidatedByEnum(name, enumRef) /** * Creates a field for a list, each element of which will be validated by global regexp * @param name name of the field * @param regexpRef reference to global regexp, e.g "integer" for "{regexp#integer}" */ @JvmStatic fun StringListValidatedByRegexp(@NonNls name: String, @NonNls regexpRef: String): StringListEventField = StringListEventField.ValidatedByRegexp(name, regexpRef) /** * Creates a field for a list in which only a specific values are allowed * @param name name of the field * @param allowedValues list of allowed values, e.g [ "bool", "int", "float"] */ @JvmStatic fun StringList(@NonNls name: String, allowedValues: List<String>): StringListEventField = StringListEventField.ValidatedByAllowedValues(name, allowedValues) @JvmStatic fun LongList(@NonNls name: String): LongListEventField = LongListEventField(name) @JvmStatic fun IntList(@NonNls name: String): IntListEventField = IntListEventField(name) /** * Please choose regexp carefully to avoid reporting any sensitive data. */ @JvmStatic fun StringValidatedByInlineRegexp(@NonNls name: String, @InjectedLanguage("RegExp") @NonNls regexp: String): StringEventField = StringEventField.ValidatedByInlineRegexp(name, regexp) /** * Please choose regexp carefully to avoid reporting any sensitive data. */ @JvmStatic fun StringListValidatedByInlineRegexp(@NonNls name: String, @InjectedLanguage("RegExp") @NonNls regexp: String): StringListEventField = StringListEventField.ValidatedByInlineRegexp(name, regexp) @JvmField val InputEvent = object : PrimitiveEventField<FusInputEvent?>() { override val name = "input_event" override val validationRule: List<String> get() = listOf("{util#shortcut}") override fun addData(fuData: FeatureUsageData, value: FusInputEvent?) { if (value != null) { fuData.addInputEvent(value.inputEvent, value.place) } } } @JvmField val InputEventByAnAction = object : PrimitiveEventField<AnActionEvent?>() { override val name = "input_event" override val validationRule: List<String> get() = listOf("{util#shortcut}") override fun addData(fuData: FeatureUsageData, value: AnActionEvent?) { if (value != null) { fuData.addInputEvent(value) } } } @JvmField val InputEventByKeyEvent = object : PrimitiveEventField<KeyEvent?>() { override val name = "input_event" override val validationRule: List<String> get() = listOf("{util#shortcut}") override fun addData(fuData: FeatureUsageData, value: KeyEvent?) { if (value != null) { fuData.addInputEvent(value) } } } @JvmField val InputEventByMouseEvent = object : PrimitiveEventField<MouseEvent?>() { override val name = "input_event" override val validationRule: List<String> get() = listOf("{util#shortcut}") override fun addData(fuData: FeatureUsageData, value: MouseEvent?) { if (value != null) { fuData.addInputEvent(value) } } } @JvmField val ActionPlace = object : PrimitiveEventField<String?>() { override val name: String = "place" override val validationRule: List<String> get() = listOf("{util#place}") override fun addData(fuData: FeatureUsageData, value: String?) { fuData.addPlace(value) } } //will be replaced with ObjectEventField in the future @JvmField val PluginInfo = object : PrimitiveEventField<PluginInfo?>() { override val name: String get() = "plugin_type" override val validationRule: List<String> get() = listOf("plugin_info") override fun addData( fuData: FeatureUsageData, value: PluginInfo?, ) { fuData.addPluginInfo(value) } } @JvmField val PluginInfoByDescriptor = object : PrimitiveEventField<IdeaPluginDescriptor>() { private val delegate get() = PluginInfo override val name: String get() = delegate.name override val validationRule: List<String> get() = delegate.validationRule override fun addData( fuData: FeatureUsageData, value: IdeaPluginDescriptor, ) { delegate.addData(fuData, getPluginInfoByDescriptor(value)) } } //will be replaced with ObjectEventField in the future @JvmField val PluginInfoFromInstance = object : PrimitiveEventField<Any>() { private val delegate get() = PluginInfo override val name: String get() = delegate.name override val validationRule: List<String> get() = delegate.validationRule override fun addData( fuData: FeatureUsageData, value: Any, ) { delegate.addData(fuData, getPluginInfo(value::class.java)) } } @JvmField val AnonymizedPath = object : PrimitiveEventField<String?>() { override val validationRule: List<String> get() = listOf("{regexp#hash}") override val name = "file_path" override fun addData(fuData: FeatureUsageData, value: String?) { fuData.addAnonymizedPath(value) } } @JvmField val AnonymizedId = object : PrimitiveEventField<String?>() { override val validationRule: List<String> get() = listOf("{regexp#hash}") override val name = "anonymous_id" override fun addData(fuData: FeatureUsageData, value: String?) { value?.let { fuData.addAnonymizedId(value) } } } @JvmField val CodeWithMeClientId = object : PrimitiveEventField<String?>() { override val validationRule: List<String> get() = listOf("{regexp#hash}") override val name: String = "client_id" override fun addData(fuData: FeatureUsageData, value: String?) { fuData.addClientId(value) } } @JvmField val Language = object : PrimitiveEventField<Language?>() { override val name = "lang" override val validationRule: List<String> get() = listOf("{util#lang}") override fun addData(fuData: FeatureUsageData, value: Language?) { fuData.addLanguage(value) } } @JvmField val LanguageById = object : PrimitiveEventField<String?>() { override val name = "lang" override val validationRule: List<String> get() = listOf("{util#lang}") override fun addData(fuData: FeatureUsageData, value: String?) { fuData.addLanguage(value) } } @JvmField val FileType = object : PrimitiveEventField<FileType?>() { override val name = "file_type" override val validationRule: List<String> get() = listOf("{util#file_type}") override fun addData(fuData: FeatureUsageData, value: FileType?) { value?.let { val type = getPluginInfo(it.javaClass) if (type.isSafeToReport()) { fuData.addData("file_type", it.name) } else { fuData.addData("file_type", "third.party") } } } } @JvmField val CurrentFile = object : PrimitiveEventField<Language?>() { override val name = "current_file" override val validationRule: List<String> get() = listOf("{util#current_file}") override fun addData(fuData: FeatureUsageData, value: Language?) { fuData.addCurrentFile(value) } } @JvmField val Version = object : PrimitiveEventField<String?>() { override val name: String = "version" override val validationRule: List<String> get() = listOf("{regexp#version}") override fun addData(fuData: FeatureUsageData, value: String?) { fuData.addVersionByString(value) } } @JvmField val VersionByObject = object : PrimitiveEventField<Version?>() { override val name: String = "version" override val validationRule: List<String> get() = listOf("{regexp#version}") override fun addData(fuData: FeatureUsageData, value: Version?) { fuData.addVersion(value) } } @JvmField val Count = Int("count") @JvmField val Enabled = Boolean("enabled") @JvmField val DurationMs = LongEventField("duration_ms") @JvmField val Size = Int("size") @JvmField val IdeActivityIdField = object : PrimitiveEventField<StructuredIdeActivity>() { override val name: String = "ide_activity_id" override fun addData(fuData: FeatureUsageData, value: StructuredIdeActivity) { fuData.addData(name, value.id) } override val validationRule: List<String> get() = listOf("{regexp#integer}") } @JvmField val TimeToShowMs = LongEventField("time_to_show") @JvmField val StartTime = LongEventField("start_time") /** * Logger merges successive events with identical group id, event id and event data fields except for fields listed here. * * @see com.intellij.internal.statistic.eventLog.StatisticsEventLoggerProvider.createEventsMergeStrategy */ @JvmField val FieldsIgnoredByMerge: List<EventField<*>> = arrayListOf(StartTime) @JvmStatic fun createAdditionalDataField(groupId: String, eventId: String): ObjectEventField { val additionalFields = mutableListOf<EventField<*>>() for (ext in FeatureUsageCollectorExtension.EP_NAME.extensionsIfPointIsRegistered) { if (ext.groupId == groupId && ext.eventId == eventId) { for (field in ext.extensionFields) { if (field != null) { additionalFields.add(field) } } } } return ObjectEventField("additional", *additionalFields.toTypedArray()) } }
platform/statistics/src/com/intellij/internal/statistic/eventLog/events/EventFields.kt
1930187655
// 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.codeInliner import com.intellij.openapi.util.Key import com.intellij.psi.PsiTreeChangeAdapter import com.intellij.psi.PsiTreeChangeEvent import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.intentions.ConvertToBlockBodyIntention import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.PsiChildRange import org.jetbrains.kotlin.psi.psiUtil.canPlaceAfterSimpleNameEntry import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments internal abstract class ReplacementPerformer<TElement : KtElement>( protected val codeToInline: MutableCodeToInline, protected var elementToBeReplaced: TElement ) { protected val psiFactory = KtPsiFactory(elementToBeReplaced) abstract fun doIt(postProcessing: (PsiChildRange) -> PsiChildRange): TElement? } internal abstract class AbstractSimpleReplacementPerformer<TElement : KtElement>( codeToInline: MutableCodeToInline, elementToBeReplaced: TElement ) : ReplacementPerformer<TElement>(codeToInline, elementToBeReplaced) { protected abstract fun createDummyElement(mainExpression: KtExpression): TElement protected open fun rangeToElement(range: PsiChildRange): TElement { assert(range.first == range.last) @Suppress("UNCHECKED_CAST") return range.first as TElement } final override fun doIt(postProcessing: (PsiChildRange) -> PsiChildRange): TElement { assert(codeToInline.statementsBefore.isEmpty()) val mainExpression = codeToInline.mainExpression ?: error("mainExpression mustn't be null") val dummyElement = createDummyElement(mainExpression) val replaced = elementToBeReplaced.replace(dummyElement) codeToInline.performPostInsertionActions(listOf(replaced)) return rangeToElement(postProcessing(PsiChildRange.singleElement(replaced))) } } internal class AnnotationEntryReplacementPerformer( codeToInline: MutableCodeToInline, elementToBeReplaced: KtAnnotationEntry ) : AbstractSimpleReplacementPerformer<KtAnnotationEntry>(codeToInline, elementToBeReplaced) { private val useSiteTarget = elementToBeReplaced.useSiteTarget?.getAnnotationUseSiteTarget() override fun createDummyElement(mainExpression: KtExpression): KtAnnotationEntry = createByPattern("@Dummy($0)", mainExpression) { psiFactory.createAnnotationEntry(it) } override fun rangeToElement(range: PsiChildRange): KtAnnotationEntry { val useSiteTargetText = useSiteTarget?.renderName?.let { "$it:" } ?: "" val isFileUseSiteTarget = useSiteTarget == AnnotationUseSiteTarget.FILE assert(range.first == range.last) assert(range.first is KtAnnotationEntry) val annotationEntry = range.first as KtAnnotationEntry val text = annotationEntry.valueArguments.single().getArgumentExpression()!!.text val newAnnotationEntry = if (isFileUseSiteTarget) psiFactory.createFileAnnotation(text) else psiFactory.createAnnotationEntry("@$useSiteTargetText$text") return annotationEntry.replaced(newAnnotationEntry) } } internal class SuperTypeCallEntryReplacementPerformer( codeToInline: MutableCodeToInline, elementToBeReplaced: KtSuperTypeCallEntry ) : AbstractSimpleReplacementPerformer<KtSuperTypeCallEntry>(codeToInline, elementToBeReplaced) { override fun createDummyElement(mainExpression: KtExpression): KtSuperTypeCallEntry { val text = if (mainExpression is KtCallElement && mainExpression.lambdaArguments.isNotEmpty()) { callWithoutLambdaArguments(mainExpression) } else { mainExpression.text } return psiFactory.createSuperTypeCallEntry(text) } } private fun callWithoutLambdaArguments(callExpression: KtCallElement): String { val copy = callExpression.copy() as KtCallElement val lambdaArgument = copy.lambdaArguments.first() val argumentExpression = lambdaArgument.getArgumentExpression() ?: return callExpression.text return lambdaArgument.moveInsideParenthesesAndReplaceWith( replacement = argumentExpression, functionLiteralArgumentName = null, withNameCheck = false ).text ?: callExpression.text } internal class ExpressionReplacementPerformer( codeToInline: MutableCodeToInline, expressionToBeReplaced: KtExpression ) : ReplacementPerformer<KtExpression>(codeToInline, expressionToBeReplaced) { private fun KtExpression.replacedWithStringTemplate(templateExpression: KtStringTemplateExpression): KtExpression? { val parent = this.parent return if (parent is KtStringTemplateEntryWithExpression // Do not mix raw and non-raw templates && parent.parent.firstChild.text == templateExpression.firstChild.text ) { val entriesToAdd = templateExpression.entries val grandParentTemplateExpression = parent.parent as KtStringTemplateExpression val result = if (entriesToAdd.isNotEmpty()) { grandParentTemplateExpression.addRangeBefore(entriesToAdd.first(), entriesToAdd.last(), parent) val lastNewEntry = parent.prevSibling val nextElement = parent.nextSibling if (lastNewEntry is KtSimpleNameStringTemplateEntry && lastNewEntry.expression != null && !canPlaceAfterSimpleNameEntry(nextElement) ) { lastNewEntry.replace(KtPsiFactory(this).createBlockStringTemplateEntry(lastNewEntry.expression!!)) } grandParentTemplateExpression } else null parent.delete() result } else { replaced(templateExpression) } } override fun doIt(postProcessing: (PsiChildRange) -> PsiChildRange): KtExpression? { val insertedStatements = ArrayList<KtExpression>() for (statement in codeToInline.statementsBefore) { val statementToUse = statement.copy() val anchor = findOrCreateBlockToInsertStatement() val block = anchor.parent as KtBlockExpression val inserted = block.addBefore(statementToUse, anchor) as KtExpression block.addBefore(psiFactory.createNewLine(), anchor) block.addBefore(psiFactory.createNewLine(), inserted) insertedStatements.add(inserted) } val replaced: KtExpression? = when (val mainExpression = codeToInline.mainExpression?.copied()) { is KtStringTemplateExpression -> elementToBeReplaced.replacedWithStringTemplate(mainExpression) is KtExpression -> elementToBeReplaced.replaced(mainExpression) else -> { // NB: Unit is never used as expression val stub = elementToBeReplaced.replaced(psiFactory.createExpression("0")) val bindingContext = stub.analyze() val canDropElementToBeReplaced = !stub.isUsedAsExpression(bindingContext) if (canDropElementToBeReplaced) { stub.delete() null } else { stub.replaced(psiFactory.createExpression("Unit")) } } } codeToInline.performPostInsertionActions(insertedStatements + listOfNotNull(replaced)) var range = if (replaced != null) { if (insertedStatements.isEmpty()) { PsiChildRange.singleElement(replaced) } else { val statement = insertedStatements.first() PsiChildRange(statement, replaced.parentsWithSelf.first { it.parent == statement.parent }) } } else { if (insertedStatements.isEmpty()) { PsiChildRange.EMPTY } else { PsiChildRange(insertedStatements.first(), insertedStatements.last()) } } val listener = replaced?.let { TrackExpressionListener(it) } listener?.attach() try { range = postProcessing(range) } finally { listener?.detach() } val resultExpression = listener?.result // simplify "${x}" to "$x" val templateEntry = resultExpression?.parent as? KtBlockStringTemplateEntry if (templateEntry?.canDropBraces() == true) { return templateEntry.dropBraces().expression } return resultExpression ?: range.last as? KtExpression } /** * Returns statement in a block to insert statement before it */ private fun findOrCreateBlockToInsertStatement(): KtExpression { for (element in elementToBeReplaced.parentsWithSelf) { val parent = element.parent when (element) { is KtContainerNodeForControlStructureBody -> { // control statement without block return element.expression!!.replaceWithBlock() } is KtExpression -> { if (parent is KtWhenEntry) { // when entry without block return element.replaceWithBlock() } if (parent is KtDeclarationWithBody) { withElementToBeReplacedPreserved { ConvertToBlockBodyIntention.convert(parent) } return (parent.bodyExpression as KtBlockExpression).statements.single() } if (parent is KtBlockExpression) return element if (parent is KtBinaryExpression) { return element.replaceWithRun() } } } } elementToBeReplaced = elementToBeReplaced.replaceWithRunBlockAndGetExpression() return elementToBeReplaced } private fun KtElement.replaceWithRun(): KtExpression = withElementToBeReplacedPreserved { replaceWithRunBlockAndGetExpression() } private fun KtElement.replaceWithRunBlockAndGetExpression(): KtExpression { val runExpression = psiFactory.createExpressionByPattern("run { $0 }", this) as KtCallExpression val runAfterReplacement = this.replaced(runExpression) val ktLambdaArgument = runAfterReplacement.lambdaArguments[0] return ktLambdaArgument.getLambdaExpression()?.bodyExpression?.statements?.singleOrNull() ?: throw KotlinExceptionWithAttachments("cant get body expression for $ktLambdaArgument").withAttachment( "ktLambdaArgument", ktLambdaArgument.text ) } private fun KtExpression.replaceWithBlock(): KtExpression = withElementToBeReplacedPreserved { replaced(KtPsiFactory(this).createSingleStatementBlock(this)) }.statements.single() private fun <TElement : KtElement> withElementToBeReplacedPreserved(action: () -> TElement): TElement { elementToBeReplaced.putCopyableUserData(ELEMENT_TO_BE_REPLACED_KEY, Unit) val result = action() elementToBeReplaced = result.findDescendantOfType { it.getCopyableUserData(ELEMENT_TO_BE_REPLACED_KEY) != null } ?: error("Element `elementToBeReplaced` not found") elementToBeReplaced.putCopyableUserData(ELEMENT_TO_BE_REPLACED_KEY, null) return result } private class TrackExpressionListener(expression: KtExpression) : PsiTreeChangeAdapter() { private var expression: KtExpression? = expression private val manager = expression.manager fun attach() { manager.addPsiTreeChangeListener(this) } fun detach() { manager.removePsiTreeChangeListener(this) } val result: KtExpression? get() = expression?.takeIf { it.isValid } override fun childReplaced(event: PsiTreeChangeEvent) { if (event.oldChild == expression) { expression = event.newChild as? KtExpression } } } } private val ELEMENT_TO_BE_REPLACED_KEY = Key<Unit>("ELEMENT_TO_BE_REPLACED_KEY")
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInliner/ReplacementPerformer.kt
4277355847
package com.github.kerubistan.kerub.data.hub import com.github.kerubistan.kerub.model.Entity import java.util.UUID import kotlin.reflect.KClass interface AnyEntityDao { fun get(clazz: KClass<out Entity<*>>, id: UUID): Entity<UUID>? fun getAll(clazz: KClass<out Entity<*>>, ids: Collection<UUID>): List<Entity<*>> }
src/main/kotlin/com/github/kerubistan/kerub/data/hub/AnyEntityDao.kt
5767459
/* * Copyright (c) 2017 Lizhaotailang * * 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.github.tonnyl.mango.ui.user.following import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v4.app.Fragment import android.support.v4.content.ContextCompat import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import io.github.tonnyl.mango.R import io.github.tonnyl.mango.data.Followee import io.github.tonnyl.mango.databinding.FragmentSimpleListBinding import io.github.tonnyl.mango.ui.user.UserProfileActivity import io.github.tonnyl.mango.ui.user.UserProfilePresenter import kotlinx.android.synthetic.main.fragment_simple_list.* import org.jetbrains.anko.startActivity /** * Created by lizhaotailang on 2017/7/29. * * Main ui for the user's following screen. */ class FollowingFragment : Fragment(), FollowingContract.View { private lateinit var mPresenter: FollowingContract.Presenter private var mAdapter: FollowingAdapter? = null private var mIsLoading = false private var mLayoutManager: LinearLayoutManager? = null private var _binding: FragmentSimpleListBinding? = null private val binding get() =_binding!! companion object { @JvmStatic fun newInstance(): FollowingFragment { return FollowingFragment() } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = FragmentSimpleListBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initViews() setHasOptionsMenu(true) mPresenter.subscribe() binding.refreshLayout.setOnRefreshListener { mIsLoading = true mPresenter.loadFollowing() } binding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) if (dy > 0 && (mLayoutManager?.findLastVisibleItemPosition() == binding.recyclerView.adapter.itemCount - 1) && !mIsLoading) { mIsLoading = true mPresenter.loadMoreFollowing() } } }) } override fun onDestroyView() { super.onDestroyView() mPresenter.unsubscribe() } override fun onDestroy() { super.onDestroy() _binding = null } override fun onOptionsItemSelected(item: MenuItem?): Boolean { if (item?.itemId == android.R.id.home) { activity?.onBackPressed() } return super.onOptionsItemSelected(item) } override fun setPresenter(presenter: FollowingContract.Presenter) { mPresenter = presenter } override fun setLoadingIndicator(loading: Boolean) { binding.refreshLayout.isRefreshing = loading } override fun setEmptyViewVisibility(visible: Boolean) { binding.emptyView.visibility = if (visible && (mAdapter == null)) View.VISIBLE else View.GONE } override fun showNetworkError() { Snackbar.make(binding.recyclerView, R.string.network_error, Snackbar.LENGTH_SHORT).show() } override fun showFollowings(followings: List<Followee>) { if (mAdapter == null) { mAdapter = FollowingAdapter(context ?: return, followings) mAdapter?.setOnItemClickListener { _, position -> context?.startActivity<UserProfileActivity>(UserProfilePresenter.EXTRA_USER to followings[position].followee) } binding.recyclerView.adapter = mAdapter } mIsLoading = false } override fun notifyDataAllRemoved(size: Int) { mAdapter?.notifyItemRangeRemoved(0, size) mIsLoading = false } override fun notifyDataAdded(startPosition: Int, size: Int) { mAdapter?.notifyItemRangeInserted(startPosition, size) mIsLoading = false } private fun initViews() { mLayoutManager = LinearLayoutManager(context) binding.recyclerView.layoutManager = mLayoutManager binding.refreshLayout.setColorSchemeColors(ContextCompat.getColor(context ?: return, R.color.colorAccent)) } }
app/src/main/java/io/github/tonnyl/mango/ui/user/following/FollowingFragment.kt
739513249
// 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 training.dsl.impl import training.dsl.LessonContext import training.dsl.TaskContext import training.learn.course.KLesson internal class LessonContextImpl(private val executor: LessonExecutor) : LessonContext() { override fun task(taskContent: TaskContext.() -> Unit) { executor.task(taskContent) } override fun waitBeforeContinue(delayMillis: Int) { executor.waitBeforeContinue(delayMillis) } override val lesson: KLesson = executor.lesson }
plugins/ide-features-trainer/src/training/dsl/impl/LessonContextImpl.kt
1637394594
// 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.test import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase import com.intellij.util.ThrowableRunnable import org.jetbrains.kotlin.test.KotlinRoot import org.jetbrains.kotlin.test.KotlinTestUtils import org.jetbrains.kotlin.test.TestMetadataUtil import java.io.File abstract class KotlinLightPlatformCodeInsightFixtureTestCase : LightPlatformCodeInsightFixtureTestCase() { protected open fun isFirPlugin(): Boolean = false override fun setUp() { super.setUp() enableKotlinOfficialCodeStyle(project) VfsRootAccess.allowRootAccess(myFixture.testRootDisposable, KotlinRoot.DIR.path) if (!isFirPlugin()) { invalidateLibraryCache(project) } } override fun tearDown() { runAll( ThrowableRunnable { disableKotlinOfficialCodeStyle(project) }, ThrowableRunnable { super.tearDown() }, ) } protected fun testDataFile(fileName: String): File = File(testDataPath, fileName) protected fun testDataFile(): File = testDataFile(fileName()) protected fun testPath(fileName: String = fileName()): String = testDataFile(fileName).toString() protected fun testPath(): String = testPath(fileName()) protected open fun fileName(): String = KotlinTestUtils.getTestDataFileName(this::class.java, this.name) ?: (getTestName(false) + ".kt") override fun getTestDataPath() = TestMetadataUtil.getTestDataPath(this::class.java) }
plugins/kotlin/test-framework/test/org/jetbrains/kotlin/idea/test/KotlinLightPlatformCodeInsightFixtureTestCase.kt
2515523636
// WITH_STDLIB // DISABLE-ERRORS interface T<X> { fun <caret>foo(x: X): X } enum class E : T<Int> { A, B, C; }
plugins/kotlin/idea/tests/testData/intentions/implementAbstractMember/function/enumClassWithSemicolon.kt
3126214078
package smartStepIntoInlinedFunLiteral fun main(args: Array<String>) { val array = arrayOf(1, 2) val myClass = MyClass() //Breakpoint! test() // STEP_OVER: 1 // SMART_STEP_INTO_BY_INDEX: 1 myClass.f1 { test() } .f2 { test() } // RESUME: 1 //Breakpoint! test() // STEP_OVER: 1 // SMART_STEP_INTO_BY_INDEX: 3 myClass.f1 { test() } .f2 { test() } // RESUME: 1 //Breakpoint! test() // STEP_OVER: 1 // SMART_STEP_INTO_BY_INDEX: 1 array.map { it *2 } // RESUME: 1 //Breakpoint! test() // STEP_OVER: 1 // SMART_STEP_INTO_BY_INDEX: 1 array.map { it * 2 } .filter { it > 2 } // RESUME: 1 //Breakpoint! test() // STEP_OVER: 1 // SMART_STEP_INTO_BY_INDEX: 3 array.map { it * 2 } .filter { it > 2 } // RESUME: 1 //Breakpoint! test() // STEP_OVER: 1 // SMART_STEP_INTO_BY_INDEX: 1 myClass.f1 { test() }.f2 { test() } // RESUME: 1 //Breakpoint! test() // STEP_OVER: 1 // SMART_STEP_INTO_BY_INDEX: 3 myClass.f1 { test() }.f2 { test() } } class MyClass { inline fun f1(f1Param: () -> Unit): MyClass { test() f1Param() return this } inline fun f2(f1Param: () -> Unit): MyClass { test() f1Param() return this } } fun test() {}
plugins/kotlin/jvm-debugger/test/testData/stepping/custom/smartStepIntoInlineFun.kt
800108910
// AFTER-WARNING: Parameter 'y' is never used // AFTER-WARNING: The expression is unused fun foo(y: Boolean) { <caret>2 > 1 }
plugins/kotlin/idea/tests/testData/intentions/simplifyBooleanWithConstants/reduceableBinary.kt
1376945712
// WITH_STDLIB // INTENTION_TEXT: "Replace with 'firstOrNull{}'" // IS_APPLICABLE_2: false // AFTER-WARNING: Variable 'result' is never used fun foo(list: List<String>) { var result: String? = null <caret>for (s in list) { // search for first non-empty string in the list if (s.length > 0) { // string should be non-empty result = s // save it into result break } } }
plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/firstOrNull/ifAssign_preserveComments.kt
1006811339
// 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("unused") package org.jetbrains.kotlin.idea.gradleTooling import org.jetbrains.kotlin.idea.gradleTooling.reflect.* import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertNull import kotlin.test.assertTrue // 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. class CallReflectiveTest { class TestLogger : ReflectionLogger { val messages = mutableListOf<String>() val exceptions = mutableListOf<Throwable?>() override fun logIssue(message: String, exception: Throwable?) { messages.add(message) exceptions.add(exception) } } private val logger = TestLogger() @Test fun `call get property`() { class Tested(val myProperty: String) val instance = Tested("abc") assertEquals("abc", instance.callReflectiveGetter("getMyProperty", logger)) } @Test fun `call get missing property`() { class Tested(val myProperty: String) val instance = Tested("abc") assertNull(instance.callReflectiveGetter("getWrongPropertyName", logger)) assertEquals(1, logger.messages.size) } @Test fun `call property with wrong return type`() { class Tested(val myProperty: String) val instance = Tested("abc") assertNull(instance.callReflective("getMyProperty", parameters(), returnType<Int>(), logger)) assertEquals(1, logger.messages.size, "Expected single issue being reported") val message = logger.messages.single() assertTrue("String" in message, "Expected logged message to mention 'String'") assertTrue("Int" in message, "Expected logged message to mention 'Int'") } @Test fun `call function`() { class Tested { fun addTwo(value: Int) = value + 2 fun minus(first: Int, second: Int) = first - second } val instance = Tested() assertEquals(4, instance.callReflective("addTwo", parameters(parameter(2)), returnType<Int>(), logger)) assertEquals(0, logger.messages.size) assertEquals(3, instance.callReflective("minus", parameters(parameter(6), parameter(3)), returnType<Int>(), logger)) assertEquals(0, logger.messages.size) } @Test fun `call function with null value (int) parameter`() { class Tested { fun orZero(value: Int?): Int = value ?: 0 } val instance = Tested() assertEquals(0, instance.callReflective("orZero", parameters(parameter<Int?>(null)), returnType<Int>(), logger)) assertEquals(0, logger.messages.size) } @Test fun `call function with null value (string) parameter`() { class Tested { fun orEmpty(value: String?) = value ?: "" } val instance = Tested() assertEquals("", instance.callReflective("orEmpty", parameters(parameter<String?>(null)), returnType<String>(), logger)) assertEquals(0, logger.messages.size) } }
plugins/kotlin/gradle/gradle-tooling/testSrc/org/jetbrains/kotlin/idea/gradleTooling/CallReflectiveTest.kt
3844594115
package foo actual class ExpectInCommonActualInPlatforms actual class <!LINE_MARKER("descr='Has declaration in common module'")!>ExpectInMiddleActualInPlatforms<!> expect class <!NO_ACTUAL_FOR_EXPECT!>ExpectInJvmWithoutActual<!> expect class <!LINE_MARKER("descr='Has actuals in JVM'")!>ExpectInJvmActualInJvm<!> actual class <!LINE_MARKER!>ExpectInJvmActualInJvm<!>
plugins/kotlin/idea/tests/testData/multiplatform/hierarcicalActualization/jvm/jvm.kt
2724882428
// 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.actions.internal.refactoringTesting import com.intellij.openapi.Disposable import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.* internal class FileSystemChangesTracker : Disposable { private val trackerListener = object : VirtualFileListener, Disposable { val createdFilesMutable = mutableSetOf<VirtualFile>() @Volatile private var disposed = false init { VirtualFileManager.getInstance().addVirtualFileListener(this, this@FileSystemChangesTracker) Disposer.register(this@FileSystemChangesTracker, this) } @Synchronized override fun dispose() { if (!disposed) { disposed = true createdFilesMutable.clear() } } override fun fileCreated(event: VirtualFileEvent) { createdFilesMutable.add(event.file) } override fun fileCopied(event: VirtualFileCopyEvent) { createdFilesMutable.add(event.file) } override fun fileMoved(event: VirtualFileMoveEvent) { createdFilesMutable.add(event.file) } } fun reset() { trackerListener.createdFilesMutable.clear() } val createdFiles: Set<VirtualFile> = trackerListener.createdFilesMutable override fun dispose() { trackerListener.dispose() } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/refactoringTesting/FileSystemChangesTracker.kt
3972383146
package com.agog.mathdisplay.render import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Paint import com.pvporbit.freetype.FreeTypeConstants import android.util.Log import com.agog.mathdisplay.parse.MathDisplayException class MTDrawFreeType(val mathfont: MTFontMathTable) { fun drawGlyph(canvas: Canvas, p: Paint, gid: Int, x: Float, y: Float) { val face = mathfont.checkFontSize() /* load glyph image into the slot and render (erase previous one) */ if (gid != 0 && !face.loadGlyph(gid, FreeTypeConstants.FT_LOAD_RENDER)) { val gslot = face.getGlyphSlot() val plainbitmap = gslot.getBitmap() if (plainbitmap != null) { if (plainbitmap.width == 0 || plainbitmap.rows == 0) { if (gid != 1 && gid != 33) { throw MathDisplayException("missing glyph slot $gid.") } } else { val bitmap = Bitmap.createBitmap(plainbitmap.width, plainbitmap.rows, Bitmap.Config.ALPHA_8) bitmap.copyPixelsFromBuffer(plainbitmap.buffer) val metrics = gslot.metrics val offx = metrics.horiBearingX / 64.0f // 26.6 fixed point integer from freetype val offy = metrics.horiBearingY / 64.0f canvas.drawBitmap(bitmap, x + offx, y - offy, p) } } } } //val enclosing = BoundingBox() /* val numGrays: Short get() = FreeType.FT_Bitmap_Get_num_grays(pointer) val paletteMode: Char get() = FreeType.FT_Bitmap_Get_palette_mode(pointer) val pixelMode: Char get() = FreeType.FT_Bitmap_Get_pixel_mode(pointer) */ }
mathdisplaylib/src/main/java/com/agog/mathdisplay/render/MTDrawFreeType.kt
2229198630
package com.lee.kotlin.lifecycle import android.util.Log import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.OnLifecycleEvent import org.jetbrains.annotations.NotNull class CustomLifecycleObserver : LifecycleObserver { private val TAG: String = "CustomLifecycleObserver" @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) fun onCreate(@NotNull owner: LifecycleOwner?) { Log.d(TAG, "CustomLifecycleObserver.onCreate " + this.javaClass.toString()) } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun onDestroy(@NotNull owner: LifecycleOwner?) { Log.d(TAG, "CustomLifecycleObserver.onDestroy " + this.javaClass.toString()) } @OnLifecycleEvent(Lifecycle.Event.ON_ANY) fun onLifecycleChanged(@NotNull owner: LifecycleOwner?, @NotNull event: Lifecycle.Event?) { Log.d(TAG, "CustomLifecycleObserver.onLifecycleChanged " + this.javaClass.toString()) } }
kotlin/src/main/java/com/lee/kotlin/lifecycle/CustomLifecycleObserver.kt
3091323000
package douzifly.list.ui.home import android.content.Intent import android.graphics.Color import android.os.Build import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.util.TypedValue import android.view.View import android.view.inputmethod.EditorInfo import android.widget.EditText import android.widget.TextView import com.github.clans.fab.FloatingActionButton import com.mikepenz.google_material_typeface_library.GoogleMaterial import com.nineoldandroids.animation.ObjectAnimator import com.wdullaer.materialdatetimepicker.date.DatePickerDialog import com.wdullaer.materialdatetimepicker.time.RadialPickerLayout import com.wdullaer.materialdatetimepicker.time.TimePickerDialog import douzifly.list.R import douzifly.list.model.Thing import douzifly.list.model.ThingGroup import douzifly.list.model.ThingsManager import douzifly.list.settings.Settings import douzifly.list.utils.* import douzifly.list.widget.ColorPicker import douzifly.list.widget.FontSizeBar import java.util.* /** * Created by douzifly on 12/14/15. */ class DetailActivity : AppCompatActivity(), DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener { override fun onDateSet(view: DatePickerDialog?, year: Int, monthOfYear: Int, dayOfMonth: Int) { reminderDate = Date(year - 1900, monthOfYear, dayOfMonth) showTimePicker() } override fun onTimeSet(view: RadialPickerLayout?, hourOfDay: Int, minute: Int, second: Int) { "${hourOfDay} : ${minute}".logd("oooo") reminderDate?.hours = hourOfDay reminderDate?.minutes = minute initDate = reminderDate updateTimeUI(reminderDate) } fun updateTimeUI(date: Date?) { if (date == null) { txtReminder.text = "" delReminder.visibility = View.GONE } else { delReminder.visibility = View.VISIBLE txtReminder.text = formatDateTime(date) formatTextViewcolor(txtReminder, date) } } companion object { val EXTRA_THING_ID = "thing_id" private val TAG = "DetailActivity" val RESULT_DELETE = 2 val RESULT_UPDATE = 3 val REQ_CHANGE_GROUP = 100 } var reminderDate: Date? = null var thing: Thing? = null var initDate: Date? = null val actionDone: FloatingActionButton by lazy { val v = findViewById(R.id.action_done) as FloatingActionButton v.setImageDrawable( GoogleMaterial.Icon.gmd_done.colorResOf(R.color.redPrimary) ) v } val actionDelete: FloatingActionButton by lazy { val v = findViewById(R.id.action_delete) as FloatingActionButton v.setImageDrawable( GoogleMaterial.Icon.gmd_delete.colorOf(Color.WHITE) ) v } val txtTitle: TextView by lazy { findViewById(R.id.txt_title) as TextView } val editTitle: EditText by lazy { findViewById(R.id.edit_title) as EditText } val editContent: EditText by lazy { findViewById(R.id.txt_content) as EditText } val addReminder: FloatingActionButton by lazy { findViewById(R.id.fab_add_reminder) as FloatingActionButton } val txtReminder: TextView by lazy { findViewById(R.id.txt_reminder) as TextView } val colorPicker: ColorPicker by lazy { findViewById(R.id.color_picker) as ColorPicker } val txtGroup : TextView by lazy { findViewById(R.id.txt_group) as TextView } val delReminder: View by lazy { val v = findViewById(R.id.reminder_del) v.setOnClickListener { cancelPickTime() } v } val focusChangeListener = View.OnFocusChangeListener { v, hasFocus -> if (!hasFocus) { when (v) { editTitle -> { setTitleEditMode(false) } } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.detail_activity) initView() parseIntent() val alphaAnim = ObjectAnimator.ofFloat(editContent, "alpha", 0.0f, 1.0f) alphaAnim.setDuration(500) alphaAnim.start() addReminder.setImageDrawable( GoogleMaterial.Icon.gmd_alarm.colorResOf(R.color.greyPrimary) ) addReminder.setOnClickListener { showDatePicker() } txtReminder.typeface = fontRailway loadData() } fun finishCompact() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { finishAfterTransition() } else { finish() } } fun cancelPickTime() { reminderDate = null updateTimeUI(reminderDate) } fun showDatePicker() { val selectedDate = Calendar.getInstance(); if (initDate != null) { selectedDate.time = initDate } val dpd = DatePickerDialog.newInstance( this, selectedDate.get(Calendar.YEAR), selectedDate.get(Calendar.MONTH), selectedDate.get(Calendar.DAY_OF_MONTH) ); if (initDate != null) { } dpd.accentColor = colorPicker.selectedColor ui { editTitle.hideKeyboard() editContent.hideKeyboard() } dpd.show((this as AppCompatActivity).getFragmentManager(), "Datepickerdialog"); } fun showTimePicker() { val selectTime = Calendar.getInstance(); if (initDate != null) { selectTime.time = initDate } val dpd = TimePickerDialog.newInstance( this, selectTime.get(Calendar.HOUR_OF_DAY), selectTime.get(Calendar.MINUTE), true) dpd.accentColor = colorPicker.selectedColor dpd.show((this as AppCompatActivity).getFragmentManager(), "Timepickerdialog"); } fun parseIntent() { val id = intent?.getLongExtra(EXTRA_THING_ID, 0) ?: 0 if (id > 0) { thing = ThingsManager.getThingByIdAtCurrentGroup(id) initDate = if (thing!!.reminderTime > 0) Date(thing!!.reminderTime) else null updateGroupText(thing!!.group!!) } } var selectedGroup: ThingGroup? = null fun updateGroupText(group: ThingGroup) { selectedGroup = group txtGroup.text = selectedGroup?.title ?: "Unknown" } fun loadData() { if (thing == null) return txtTitle.text = thing!!.title editTitle.setText(thing!!.title) editContent.setText(thing!!.content) editContent.setBackgroundColor(0x0000) txtTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, FontSizeBar.fontSizeToDp(Settings.fontSize) + 2) editTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, FontSizeBar.fontSizeToDp(Settings.fontSize) + 2) editContent.setTextSize(TypedValue.COMPLEX_UNIT_PX, FontSizeBar.fontSizeToDp(Settings.fontSize)) txtGroup.setTextSize(TypedValue.COMPLEX_UNIT_PX, FontSizeBar.fontSizeToDp(Settings.fontSize)) ui(200) { colorPicker.setSelected(thing!!.color) } updateTimeUI( if (thing!!.reminderTime > 0) Date(thing!!.reminderTime) else null ) if (thing!!.reminderTime > 0) { reminderDate = Date(thing!!.reminderTime) } } fun saveData() { editTitle.hideKeyboard() editContent.hideKeyboard() var changed = false val newTitle = editTitle.text.toString() val newContent = editContent.text.toString() val newColor = colorPicker.selectedColor val newReminderTime = reminderDate?.time ?: 0 if (thing!!.title != newTitle) { thing!!.title = newTitle changed = true } if (thing!!.content != newContent) { thing!!.content = newContent changed = true } if (thing!!.color != newColor) { thing!!.color = newColor ThingsManager.getGroupByGroupId(Settings.selectedGroupId)?.clearAllDisplayColor() changed = true } if (thing!!.reminderTime != newReminderTime) { thing!!.reminderTime = newReminderTime changed = true } if (selectedGroup != null) { changed = true } if (changed) { bg { setResult(RESULT_UPDATE) ThingsManager.saveThing(thing!!, selectedGroup) } } } fun initView() { txtTitle.typeface = fontSourceSansPro txtGroup.typeface = fontSourceSansPro editContent.typeface = fontSourceSansPro editTitle.typeface = fontSourceSansPro editTitle.visibility = View.GONE actionDelete.setOnClickListener { val intent = Intent() intent.putExtra(EXTRA_THING_ID, thing!!.id) setResult(RESULT_DELETE, intent) finishCompact() } actionDone.setOnClickListener { bg { saveData() ui { finishCompact() } } } txtTitle.setOnClickListener(onClickListener) editTitle.onFocusChangeListener = focusChangeListener editContent.isFocusable = false editContent.isFocusableInTouchMode = false editContent.setOnClickListener { v -> editContentRequestFocus() } editTitle.setOnEditorActionListener { textView, actionId, keyEvent -> if (actionId == EditorInfo.IME_ACTION_NEXT) { editContentRequestFocus() true } false }; txtGroup.setOnClickListener { showGroupChoose() } } fun showGroupChoose() { ui { editTitle.hideKeyboard() editContent.hideKeyboard() } val intent = Intent(this, GroupEditorActivity::class.java) intent.putExtra(GroupEditorActivity.EXTRA_KEY_SHOW_ALL, false) startActivityForResult(intent, REQ_CHANGE_GROUP) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQ_CHANGE_GROUP && resultCode == RESULT_OK) { val id = data!!.getLongExtra("id", -1L) if (id != thing!!.group!!.id) { // groupId changed selectedGroup = ThingsManager.getGroupByGroupId(id) "group changed to : ${selectedGroup?.title ?: "not changed"}".logd(TAG) updateGroupText(selectedGroup!!) } } } private fun editContentRequestFocus() { editContent.isFocusable = true editContent.isFocusableInTouchMode = true editContent.requestFocus() ui(100) { editContent.showKeyboard() } } fun setTitleEditMode(editMode: Boolean) { if (editMode) { // show edittext txtTitle.visibility = View.GONE editTitle.setText(txtTitle.text) editTitle.visibility = View.VISIBLE editTitle.requestFocus() editTitle.showKeyboard() } else { txtTitle.visibility = View.VISIBLE editTitle.visibility = View.GONE txtTitle.setText(editTitle.text) } } val onClickListener: (v: View) -> Unit = { v -> if (v == txtTitle) { setTitleEditMode(true) } } }
app/src/main/java/douzifly/list/ui/home/DetailActivity.kt
404239187
package sk.styk.martin.apkanalyzer.util import kotlin.reflect.full.memberProperties import kotlin.reflect.jvm.isAccessible inline fun <reified T : Any, R> T.getPrivateProperty(name: String): R? = try { T::class.memberProperties .firstOrNull { it.name == name } ?.apply { isAccessible = true } ?.get(this) as? R } catch (e: Exception) { throw ReflectiveOperationException("Error reading $name on $this", e) }
app/src/main/java/sk/styk/martin/apkanalyzer/util/ReflectionUtils.kt
1555399772
package stan.androiddemo.project.petal.Base import android.content.Context import android.os.Build import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.view.WindowManager import android.widget.Toast import rx.Subscription import rx.subscriptions.CompositeSubscription import stan.androiddemo.R import stan.androiddemo.project.petal.Config.Config import stan.androiddemo.project.petal.Config.UserSingleton import stan.androiddemo.tool.Base64Utils import stan.androiddemo.tool.NetUtils import stan.androiddemo.tool.SPUtils /** * Created by stanhu on 10/8/2017. */ public abstract class BasePetalActivity :AppCompatActivity(){ protected val TAG = getTag() abstract fun getTag():String abstract fun getLayoutId():Int var isLogin = false var mAuthorization:String = "" lateinit var mFormatImageUrlBig: String //大图的后缀 lateinit var mFormatImageGeneral: String lateinit var mContext:Context override fun toString(): String { return javaClass.simpleName + " @" + Integer.toHexString(hashCode()); } private var mCompositeSubscription: CompositeSubscription? = null fun getCompositeSubscription(): CompositeSubscription { if (this.mCompositeSubscription == null) { this.mCompositeSubscription = CompositeSubscription() } return this.mCompositeSubscription!! } fun addSubscription(s: Subscription?) { if (s == null) { return } if (this.mCompositeSubscription == null) { this.mCompositeSubscription = CompositeSubscription() } this.mCompositeSubscription!!.add(s) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT){ if (isTranslucentStatusBar()){ val wd = window wd.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) } } mFormatImageGeneral = resources.getString(R.string.url_image_general) mFormatImageUrlBig = resources.getString(R.string.url_image_big) setContentView(getLayoutId()) mContext = this getLoginData() initResAndListener() } open fun isTranslucentStatusBar():Boolean{ return true } fun getLoginData(){ UserSingleton.instance.isLogin(application) isLogin = SPUtils.get(mContext,Config.ISLOGIN,false) as Boolean mAuthorization = getAuthorizations(isLogin) } open fun initResAndListener(){ } protected fun getAuthorizations(isLogin: Boolean): String { val temp = " " if (isLogin) { return (SPUtils.get(mContext, Config.TOKENTYPE, temp) as String) + temp + (SPUtils.get(mContext, Config.TOKENACCESS, temp) as String) } return Base64Utils.mClientInto } override fun onDestroy() { super.onDestroy() if (this.mCompositeSubscription != null){ this.mCompositeSubscription = null } } fun checkException(e:Throwable,mRootView:View){ NetUtils.checkHttpException(mContext,e,mRootView) } fun toast(msg:String){ Toast.makeText(mContext,msg,Toast.LENGTH_SHORT).show() } }
app/src/main/java/stan/androiddemo/project/petal/Base/BasePetalActivity.kt
2480586281