repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Mindera/skeletoid
base/src/main/java/com/mindera/skeletoid/logs/LoggerManager.kt
1
4033
package com.mindera.skeletoid.logs import android.content.Context import androidx.annotation.VisibleForTesting import com.mindera.skeletoid.generic.AndroidUtils import com.mindera.skeletoid.logs.LOG.PRIORITY import com.mindera.skeletoid.logs.appenders.interfaces.ILogAppender import com.mindera.skeletoid.logs.interfaces.ILoggerManager import com.mindera.skeletoid.logs.utils.LogAppenderUtils import com.mindera.skeletoid.threads.utils.ThreadUtils import java.util.ArrayList import java.util.HashMap import java.util.HashSet /** * LOG main class. It contains all the logic and feeds the appenders */ internal class LoggerManager : ILoggerManager { companion object { private const val LOG_TAG = "LoggerManager" /** * Log format */ const val LOG_FORMAT_4ARGS = "%s %s %s | %s" } /** * Application TAG for logs */ private val packageName: String /** * Define if the method name invoking the log should be printed or not (via exception stack) */ @JvmField @VisibleForTesting var addMethodName = false /** * List of appenders (it can be improved to an ArrayMap if we want to add the support lib as dependency */ private val logAppenders: MutableMap<String, ILogAppender> = HashMap() constructor(context: Context) { packageName = AndroidUtils.getApplicationPackage(context) } constructor(packageName: String) { this.packageName = packageName } /** * Enables or disables logging to console/logcat. */ override fun addAppenders( context: Context, logAppenders: List<ILogAppender> ): Set<String> { val appenderIds: MutableSet<String> = HashSet() for (logAppender in logAppenders) { val loggerId = logAppender.loggerId if (this.logAppenders.containsKey(loggerId)) { log(LOG_TAG, PRIORITY.ERROR, null, "Replacing Log Appender with ID: $loggerId") val oldLogAppender = this.logAppenders.remove(loggerId) oldLogAppender!!.disableAppender() } logAppender.enableAppender(context) appenderIds.add(loggerId) this.logAppenders[loggerId] = logAppender } return appenderIds } /** * Enables or disables logging to console/logcat. */ override fun removeAppenders( context: Context, loggerIds: Set<String> ) { if(logAppenders.isNotEmpty()) { for (logId in loggerIds) { val logAppender = logAppenders.remove(logId) logAppender?.disableAppender() } } } override fun removeAllAppenders() { if(logAppenders.isNotEmpty()) { val appendersKeys: List<String?> = ArrayList(logAppenders.keys) for (logId in appendersKeys) { val analyticsAppender = logAppenders.remove(logId) analyticsAppender?.disableAppender() } } } override fun setUserProperty(key: String, value: String) { for (logAppender in logAppenders.values) { logAppender.setUserProperty(key, value) } } override fun setMethodNameVisible(visibility: Boolean) { addMethodName = visibility } private fun pushLogToAppenders( type: PRIORITY, t: Throwable?, log: String ) { for ((_, value) in logAppenders) { value.log(type, t, log) } } override fun log( tag: String, priority: PRIORITY, t: Throwable?, vararg text: String ) { if(logAppenders.isNotEmpty()) { val log = String.format( LOG_FORMAT_4ARGS, tag, LogAppenderUtils.getObjectHash(tag), ThreadUtils.currentThreadName, LogAppenderUtils.getLogString(*text) ) pushLogToAppenders(priority, t, log) } } }
mit
7d0272d84e17c7c5c9bef6fe1ad64725
28.231884
107
0.61691
4.646313
false
false
false
false
Mogikan/mobileLabs
Services/app/src/main/java/com/astu/vk/services/MathIntentService.kt
1
3186
package com.astu.vk.services import android.app.IntentService import android.content.BroadcastReceiver import android.content.Intent import android.content.Context /** * An [IntentService] subclass for handling asynchronous task requests in * a service on a separate handler thread. * * * TODO: Customize class - update intent actions, extra parameters and static * helper methods. */ class MathIntentService : IntentService("MathIntentService") { protected override fun onHandleIntent(intent: Intent?) { if (intent != null) { val action = intent.action if (ACTION_SUM == action) { val param1 = intent.getIntExtra(EXTRA_OPERAND1,0) val param2 = intent.getIntExtra(EXTRA_OPERAND2,0); handleActionSum(param1, param2) } else if (ACTION_MUL == action) { val param1 = intent.getIntExtra(EXTRA_OPERAND1,0) val param2 = intent.getIntExtra(EXTRA_OPERAND2,0); handleActionMul(param1, param2) } } } private fun handleActionSum(operand1: Int, operand2: Int) { var resultIntent:Intent = Intent(RESULT_NOTIFICATION) resultIntent.putExtra(RESULT_EXTRA,operand1+operand2) sendBroadcast(resultIntent) } private fun handleActionMul(operand1: Int, operand2: Int) { var resultIntent:Intent = Intent(RESULT_NOTIFICATION) resultIntent.putExtra(RESULT_EXTRA,operand1*operand2) sendBroadcast(resultIntent) } companion object { public val RESULT_NOTIFICATION = "mathIntentNotification" public val RESULT_EXTRA = "mathIntentResultExtra" private val ACTION_SUM = "com.astu.vk.services.action.SUM" private val ACTION_MUL = "com.astu.vk.services.action.MUL" private val EXTRA_OPERAND1 = "com.astu.vk.services.extra.OPERAND1" private val EXTRA_OPERAND2 = "com.astu.vk.services.extra.OPERAND2" /** * Starts this service to perform action Foo with the given parameters. If * the service is already performing a task this action will be queued. * @see IntentService */ // TODO: Customize helper method fun startActionSum(context: Context, operand1: Int, operand2: Int) { val intent = Intent(context, MathIntentService::class.java) intent.action = ACTION_SUM intent.putExtra(EXTRA_OPERAND1, operand1) intent.putExtra(EXTRA_OPERAND2, operand2) context.startService(intent) } /** * Starts this service to perform action Baz with the given parameters. If * the service is already performing a task this action will be queued. * @see IntentService */ // TODO: Customize helper method fun startActionMul(context: Context, operand1: Int, operand2: Int) { val intent = Intent(context, MathIntentService::class.java) intent.action = ACTION_MUL intent.putExtra(EXTRA_OPERAND1, operand1) intent.putExtra(EXTRA_OPERAND2, operand2) context.startService(intent) } } }
gpl-3.0
f8a99fc2982f5d697ee44bc3030a9408
36.046512
82
0.648776
4.394483
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/refactoringTesting/CompilationStatusTracker.kt
3
2480
// 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.ide.DataManager import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.Presentation import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.compiler.CompilationStatusListener import com.intellij.openapi.compiler.CompileContext import com.intellij.openapi.compiler.CompilerTopics.COMPILATION_STATUS import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable internal class CompilationStatusTracker(private val project: Project) { private val compilationStatusListener = object : CompilationStatusListener { init { val disposable = KotlinPluginDisposable.getInstance(project) project.messageBus.connect(disposable).subscribe(COMPILATION_STATUS, this) } var hasCompilerError = false private set var compilationFinished = false private set fun reset() { compilationFinished = false hasCompilerError = false } override fun compilationFinished(aborted: Boolean, errors: Int, warnings: Int, compileContext: CompileContext) { hasCompilerError = hasCompilerError || aborted || errors != 0 compilationFinished = true } } private val runBuildAction by lazyPub { val am = ActionManager.getInstance() val action = am.getAction("CompileProject") val event = AnActionEvent( null, DataManager.getInstance().dataContext, ActionPlaces.UNKNOWN, Presentation(), ActionManager.getInstance(), 0 ) return@lazyPub { action.actionPerformed(event) } } fun checkByBuild(cancelledChecker: () -> Boolean): Boolean { compilationStatusListener.reset() ApplicationManager.getApplication().invokeAndWait { runBuildAction() } while (!cancelledChecker() && !compilationStatusListener.compilationFinished) { Thread.yield() } return !compilationStatusListener.hasCompilerError } }
apache-2.0
9ed3482aede2c5a819fa357159351fc5
33.943662
158
0.709677
5.367965
false
false
false
false
RadiationX/ForPDA
app/src/main/java/forpdateam/ru/forpda/entity/remote/others/user/ForumUser.kt
1
413
package forpdateam.ru.forpda.entity.remote.others.user /** * Created by radiationx on 08.07.17. */ class ForumUser : IForumUser { override var id = 0 override var nick: String? = null override var avatar: String? = null constructor() {} constructor(forumUser: IForumUser) { this.id = forumUser.id this.nick = forumUser.nick this.avatar = forumUser.avatar } }
gpl-3.0
9d516ffa009cb56baf05172ec01dc4b7
20.736842
54
0.64891
3.754545
false
false
false
false
radiKal07/pc-notifications
mobile/app/src/main/kotlin/com/radikal/pcnotifications/dagger/DaggerModule.kt
1
4304
package com.radikal.pcnotifications.dagger import android.app.Application import android.content.ContentResolver import android.content.Context import android.content.SharedPreferences import android.net.wifi.WifiManager import android.preference.PreferenceManager import android.telephony.TelephonyManager import com.fasterxml.jackson.databind.ObjectMapper import com.radikal.pcnotifications.contracts.PairingContract import com.radikal.pcnotifications.model.persistence.SmsDao import com.radikal.pcnotifications.model.persistence.impl.SqliteSmsDao import com.radikal.pcnotifications.model.service.* import com.radikal.pcnotifications.model.service.impl.* import com.radikal.pcnotifications.model.validators.Validator import com.radikal.pcnotifications.model.validators.impl.PortValidator import com.radikal.pcnotifications.presenter.PairingPresenter import com.radikal.pcnotifications.listeners.util.SmsIdentifier import com.radikal.pcnotifications.model.persistence.ContactsDao import com.radikal.pcnotifications.model.persistence.impl.ContactsDaoImpl import dagger.Module import dagger.Provides import javax.inject.Named import javax.inject.Singleton /** * Created by tudor on 14.12.2016. */ @Module class DaggerModule(val application: Application) { @Provides @Singleton fun application(): Application { return application } @Provides @Singleton fun sharedPreferences(): SharedPreferences { return PreferenceManager.getDefaultSharedPreferences(application.applicationContext) } @Provides @Singleton fun wifiManager(): WifiManager { return application.getSystemService(Context.WIFI_SERVICE) as WifiManager } @Provides @Singleton @Named("portValidator") fun portValidator(): Validator<String?> { return PortValidator() } @Provides @Singleton fun pairingPresenter(deviceCommunicator: DeviceCommunicator): PairingContract.Presenter { val pairingPresenter = PairingPresenter() pairingPresenter.portValidator = portValidator() pairingPresenter.deviceCommunicator = deviceCommunicator return pairingPresenter } @Provides @Singleton fun deviceCommunicator(wifiManager: WifiManager, serverDetailsDao: ServerDetailsDao, dataSerializer: DataSerializer, smsService: SmsService, contactsDao: ContactsDao): DeviceCommunicator { val socketIOCommunicator = SocketIOCommunicator() socketIOCommunicator.serverDetailsDao = serverDetailsDao socketIOCommunicator.dataSerializer = dataSerializer socketIOCommunicator.smsService = smsService socketIOCommunicator.wifiManager = wifiManager socketIOCommunicator.contactsDao = contactsDao return socketIOCommunicator } @Provides @Singleton fun smsIdentifier(): SmsIdentifier { return SmsIdentifier() } @Provides @Singleton fun serverDetailsDao(sharedPreferences: SharedPreferences): ServerDetailsDao { return SharedPreferencesServerDetailsDao(sharedPreferences) } @Provides @Singleton fun objectMapper(): ObjectMapper { return ObjectMapper() } @Provides @Singleton fun dataSerializer(objectMapper: ObjectMapper): DataSerializer { return JSONDataSerializer(objectMapper) } @Provides @Singleton fun contentResolver(): ContentResolver { return application.contentResolver } @Provides @Singleton fun smsDao(contentResolver: ContentResolver, telephonyManager: TelephonyManager): SmsDao { val sqliteSmsDao = SqliteSmsDao() sqliteSmsDao.contentResolver = contentResolver sqliteSmsDao.telephonyManager = telephonyManager return sqliteSmsDao } @Provides @Singleton fun smsService(smsDao: SmsDao, application: Application): SmsService { val smsService = SmsServiceImpl() smsService.smsDao = smsDao smsService.context = application return smsService } @Provides @Singleton fun telephonyManager(): TelephonyManager { return application.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager } @Provides @Singleton fun contactsDao(): ContactsDao { return ContactsDaoImpl() } }
apache-2.0
e121a0b6444c9bee4f1cb452ac38b1a4
30.195652
192
0.751626
5.287469
false
false
false
false
GunoH/intellij-community
platform/analysis-impl/src/com/intellij/profile/codeInspection/ProjectInspectionProfileManager.kt
1
9787
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.profile.codeInspection import com.intellij.codeInspection.ex.InspectionProfileImpl import com.intellij.codeInspection.ex.InspectionToolRegistrar import com.intellij.configurationStore.* import com.intellij.diagnostic.runActivity import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* import com.intellij.openapi.options.SchemeManagerFactory import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupManager import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.packageDependencies.DependencyValidationManager import com.intellij.profile.ProfileChangeAdapter import com.intellij.project.isDirectoryBased import com.intellij.psi.search.scope.packageSet.NamedScopeManager import com.intellij.psi.search.scope.packageSet.NamedScopesHolder import com.intellij.util.xmlb.annotations.OptionTag import org.jdom.Element import org.jetbrains.annotations.TestOnly import java.util.function.Function private const val VERSION = "1.0" const val PROJECT_DEFAULT_PROFILE_NAME = "Project Default" private val defaultSchemeDigest = JDOMUtil.load("""<component name="InspectionProjectProfileManager"> <profile version="1.0"> <option name="myName" value="Project Default" /> </profile> </component>""").digest() const val PROFILE_DIR: String = "inspectionProfiles" @State(name = "InspectionProjectProfileManager", storages = [(Storage(value = "$PROFILE_DIR/profiles_settings.xml", exclusive = true))]) open class ProjectInspectionProfileManager(val project: Project) : BaseInspectionProfileManager(project.messageBus), PersistentStateComponentWithModificationTracker<Element>, Disposable { companion object { @JvmStatic fun getInstance(project: Project): ProjectInspectionProfileManager { return project.getService(InspectionProjectProfileManager::class.java) as ProjectInspectionProfileManager } } private var state = ProjectInspectionProfileManagerState() protected val schemeManagerIprProvider = if (project.isDirectoryBased) null else SchemeManagerIprProvider("profile") override val schemeManager = SchemeManagerFactory.getInstance(project).create(PROFILE_DIR, object : InspectionProfileProcessor() { override fun createScheme(dataHolder: SchemeDataHolder<InspectionProfileImpl>, name: String, attributeProvider: Function<in String, String?>, isBundled: Boolean): InspectionProfileImpl { val profile = InspectionProfileImpl(name, InspectionToolRegistrar.getInstance(), this@ProjectInspectionProfileManager, dataHolder) profile.isProjectLevel = true return profile } override fun isSchemeFile(name: CharSequence) = !StringUtil.equals(name, "profiles_settings.xml") override fun isSchemeDefault(scheme: InspectionProfileImpl, digest: ByteArray): Boolean { return scheme.name == PROJECT_DEFAULT_PROFILE_NAME && digest.contentEquals(defaultSchemeDigest) } override fun onSchemeDeleted(scheme: InspectionProfileImpl) { schemeRemoved(scheme) } override fun onSchemeAdded(scheme: InspectionProfileImpl) { if (scheme.wasInitialized()) { fireProfileChanged(scheme) } } override fun onCurrentSchemeSwitched(oldScheme: InspectionProfileImpl?, newScheme: InspectionProfileImpl?, processChangeSynchronously: Boolean) { project.messageBus.syncPublisher(ProfileChangeAdapter.TOPIC).profileActivated(oldScheme, newScheme) } }, schemeNameToFileName = OLD_NAME_CONVERTER, streamProvider = schemeManagerIprProvider) override fun initializeComponent() { val app = ApplicationManager.getApplication() if (!project.isDirectoryBased || app.isUnitTestMode) { return } runActivity("project inspection profile loading") { schemeManager.loadSchemes() currentProfile.initInspectionTools(project) } StartupManager.getInstance(project).runAfterOpened { project.messageBus.syncPublisher(ProfileChangeAdapter.TOPIC).profilesInitialized() val projectScopeListener = NamedScopesHolder.ScopeListener { for (profile in schemeManager.allSchemes) { profile.scopesChanged() } } scopesManager.addScopeListener(projectScopeListener, project) NamedScopeManager.getInstance(project).addScopeListener(projectScopeListener, project) } } override fun dispose() { val cleanupInspectionProfilesRunnable = { cleanupSchemes(project) (serviceIfCreated<InspectionProfileManager>() as BaseInspectionProfileManager?)?.cleanupSchemes(project) } val app = ApplicationManager.getApplication() if (app.isUnitTestMode || app.isHeadlessEnvironment) { cleanupInspectionProfilesRunnable.invoke() } else { app.executeOnPooledThread(cleanupInspectionProfilesRunnable) } } override fun getStateModificationCount() = state.modificationCount + severityRegistrar.modificationCount + (schemeManagerIprProvider?.modificationCount ?: 0) @TestOnly fun forceLoadSchemes() { LOG.assertTrue(ApplicationManager.getApplication().isUnitTestMode) schemeManager.loadSchemes() } fun isCurrentProfileInitialized() = currentProfile.wasInitialized() override fun schemeRemoved(scheme: InspectionProfileImpl) { scheme.cleanup(project) } @Synchronized override fun getState(): Element? { val result = Element("settings") schemeManagerIprProvider?.writeState(result) serializeObjectInto(state, result) if (result.children.isNotEmpty()) { result.addContent(Element("version").setAttribute("value", VERSION)) } severityRegistrar.writeExternal(result) return wrapState(result, project) } @Synchronized override fun loadState(state: Element) { val data = unwrapState(state, project, schemeManagerIprProvider, schemeManager) val newState = ProjectInspectionProfileManagerState() data?.let { try { severityRegistrar.readExternal(it) } catch (e: Throwable) { LOG.error(e) } it.deserializeInto(newState) } this.state = newState if (data != null && data.getChild("version")?.getAttributeValue("value") != VERSION) { for (o in data.getChildren("option")) { if (o.getAttributeValue("name") == "USE_PROJECT_LEVEL_SETTINGS") { if (o.getAttributeBooleanValue("value") && newState.projectProfile != null) { currentProfile.convert(data, project) } break } } } } override fun getScopesManager() = DependencyValidationManager.getInstance(project) @Synchronized override fun getProfiles(): Collection<InspectionProfileImpl> { currentProfile return schemeManager.allSchemes } val projectProfile: String? get() = state.projectProfile @Synchronized override fun setRootProfile(name: String?) { state.useProjectProfile = name != null if (name != null) { state.projectProfile = name } schemeManager.setCurrentSchemeName(name, true) } @Synchronized fun useApplicationProfile(name: String) { state.useProjectProfile = false // yes, we reuse the same field - useProjectProfile field will be used to distinguish - is it app or project level // to avoid data format change state.projectProfile = name } @Synchronized @TestOnly fun setCurrentProfile(profile: InspectionProfileImpl?) { schemeManager.setCurrent(profile) state.useProjectProfile = profile != null if (profile != null) { state.projectProfile = profile.name } } @Synchronized override fun getCurrentProfile(): InspectionProfileImpl { if (!state.useProjectProfile) { val applicationProfileManager = InspectionProfileManager.getInstance() return (state.projectProfile?.let { applicationProfileManager.getProfile(it, false) } ?: applicationProfileManager.currentProfile) } var currentScheme = state.projectProfile?.let { schemeManager.findSchemeByName(it) } if (currentScheme == null) { currentScheme = schemeManager.allSchemes.firstOrNull() if (currentScheme == null) { currentScheme = InspectionProfileImpl(PROJECT_DEFAULT_PROFILE_NAME, InspectionToolRegistrar.getInstance(), this) currentScheme.copyFrom(InspectionProfileManager.getInstance().currentProfile) currentScheme.isProjectLevel = true currentScheme.name = PROJECT_DEFAULT_PROFILE_NAME schemeManager.addScheme(currentScheme) } schemeManager.setCurrent(currentScheme, false) } return currentScheme } @Synchronized override fun getProfile(name: String, returnRootProfileIfNamedIsAbsent: Boolean): InspectionProfileImpl? { val profile = schemeManager.findSchemeByName(name) return profile ?: InspectionProfileManager.getInstance().getProfile(name, returnRootProfileIfNamedIsAbsent) } fun fireProfileChanged() { fireProfileChanged(currentProfile) } override fun fireProfileChanged(profile: InspectionProfileImpl) { profile.profileChanged() project.messageBus.syncPublisher(ProfileChangeAdapter.TOPIC).profileChanged(profile) } } private class ProjectInspectionProfileManagerState : BaseState() { @get:OptionTag("PROJECT_PROFILE") var projectProfile by string(PROJECT_DEFAULT_PROFILE_NAME) @get:OptionTag("USE_PROJECT_PROFILE") var useProjectProfile by property(true) }
apache-2.0
52437b1d489482586fb18a136ac4316a
35.518657
187
0.741187
5.36568
false
false
false
false
GunoH/intellij-community
platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/diff/MutableDiffRequestChainProcessor.kt
2
3684
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.collaboration.ui.codereview.diff import com.intellij.diff.chains.AsyncDiffRequestChain import com.intellij.diff.chains.DiffRequestChain import com.intellij.diff.chains.DiffRequestProducer import com.intellij.diff.impl.CacheDiffRequestProcessor import com.intellij.openapi.ListSelection import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.changes.actions.diff.PresentableGoToChangePopupAction import com.intellij.openapi.vcs.changes.ui.ChangeDiffRequestChain import kotlin.properties.Delegates abstract class MutableDiffRequestChainProcessor(project: Project, chain: DiffRequestChain?) : CacheDiffRequestProcessor.Simple(project) { private val asyncChangeListener = AsyncDiffRequestChain.Listener { dropCaches() currentIndex = (this.chain?.index ?: 0) updateRequest(true) } var chain: DiffRequestChain? by Delegates.observable(null) { _, oldValue, newValue -> if (oldValue is AsyncDiffRequestChain) { oldValue.onAssigned(false) oldValue.removeListener(asyncChangeListener) } if (newValue is AsyncDiffRequestChain) { newValue.onAssigned(true) // listener should be added after `onAssigned` call to avoid notification about synchronously loaded requests newValue.addListener(asyncChangeListener, this) } currentIndex = newValue?.index ?: 0 updateRequest() } private var currentIndex: Int = 0 init { this.chain = chain } override fun onDispose() { val chain = chain if (chain is AsyncDiffRequestChain) chain.onAssigned(false) super.onDispose() } override fun getCurrentRequestProvider(): DiffRequestProducer? { val requests = chain?.requests ?: return null return if (currentIndex < 0 || currentIndex >= requests.size) null else requests[currentIndex] } override fun hasNextChange(fromUpdate: Boolean): Boolean { val chain = chain ?: return false return currentIndex < chain.requests.lastIndex } override fun hasPrevChange(fromUpdate: Boolean): Boolean { val chain = chain ?: return false return currentIndex > 0 && chain.requests.size > 1 } override fun goToNextChange(fromDifferences: Boolean) { goToNextChangeImpl(fromDifferences) { currentIndex += 1 selectCurrentChange() } } override fun goToPrevChange(fromDifferences: Boolean) { goToPrevChangeImpl(fromDifferences) { currentIndex -= 1 selectCurrentChange() } } override fun isNavigationEnabled(): Boolean { val chain = chain ?: return false return chain.requests.size > 1 } override fun createGoToChangeAction(): AnAction? { return MyGoToChangePopupAction() } abstract fun selectFilePath(filePath: FilePath) private fun selectCurrentChange() { val producer = currentRequestProvider as? ChangeDiffRequestChain.Producer ?: return selectFilePath(producer.filePath) } private inner class MyGoToChangePopupAction : PresentableGoToChangePopupAction.Default<ChangeDiffRequestChain.Producer>() { override fun getChanges(): ListSelection<out ChangeDiffRequestChain.Producer> { val requests = chain?.requests ?: return ListSelection.empty() val list = ListSelection.createAt(requests, currentIndex) return list.map { it as? ChangeDiffRequestChain.Producer } } override fun onSelected(change: ChangeDiffRequestChain.Producer) { selectFilePath(change.filePath) } } }
apache-2.0
b418fa2e4bd0e573d5c732dc19379abb
33.429907
158
0.752986
4.747423
false
false
false
false
pdvrieze/kotlinsql
sql/src/main/kotlin/io/github/pdvrieze/kotlinsql/ddl/columns/ColumnType.kt
1
14746
/* * Copyright (c) 2021. * * This file is part of kotlinsql. * * This file is licenced to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You should have received a copy of the license with the source distribution. * Alternatively, 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:Suppress("ClassName", "unused") package io.github.pdvrieze.kotlinsql.ddl.columns import io.github.pdvrieze.kotlinsql.ddl.BoundedType import io.github.pdvrieze.kotlinsql.ddl.Column import io.github.pdvrieze.kotlinsql.ddl.IColumnType import java.io.ByteArrayInputStream import java.math.BigDecimal import java.sql.* import kotlin.reflect.KClass @Suppress("ClassName") sealed class ColumnType<T : Any, S : ColumnType<T, S, C>, C : Column<T, S, C>>( override val typeName: String, override val type: KClass<T>, override val javaType: Int, ) : IColumnType<T, S, C> { @Suppress("UNCHECKED_CAST") fun asS() = this as S override fun toString() = "ColumnType: $typeName ($type)" } interface INumericColumnType<T : Any, S : INumericColumnType<T, S, C>, C : INumericColumn<T, S, C>> : IColumnType<T, S, C> sealed class NumericColumnType<T : Any, S : NumericColumnType<T, S>>(typeName: String, type: KClass<T>, javaType: Int) : ColumnType<T, S, NumericColumn<T, S>>(typeName, type, javaType), INumericColumnType<T, S, NumericColumn<T, S>> { object TINYINT_T : NumericColumnType<Byte, TINYINT_T>("TINYINT", Byte::class, Types.TINYINT) { override fun fromResultSet(rs: ResultSet, pos: Int) = rs.getByte(pos).let { if (rs.wasNull()) null else it } override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: Byte?) { statementHelper.setByte(pos, javaType, value) } } object SMALLINT_T : NumericColumnType<Short, SMALLINT_T>("SMALLINT", Short::class, Types.SMALLINT) { override fun fromResultSet(rs: ResultSet, pos: Int) = rs.getShort(pos).let { if (rs.wasNull()) null else it } override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: Short?) { statementHelper.setShort(pos, javaType, value) } } object MEDIUMINT_T : NumericColumnType<Int, MEDIUMINT_T>("MEDIUMINT", Int::class, Types.OTHER) { override fun fromResultSet(rs: ResultSet, pos: Int) = rs.getInt(pos).let { if (rs.wasNull()) null else it } override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: Int?) { statementHelper.setInt(pos, javaType, value) } } object INT_T : NumericColumnType<Int, INT_T>("INT", Int::class, Types.INTEGER) { override fun fromResultSet(rs: ResultSet, pos: Int) = rs.getInt(pos).let { if (rs.wasNull()) null else it } override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: Int?) { statementHelper.setInt(pos, javaType, value) } } object BIGINT_T : NumericColumnType<Long, BIGINT_T>("BIGINT", Long::class, Types.BIGINT) { override fun fromResultSet(rs: ResultSet, pos: Int) = rs.getLong(pos).let { if (rs.wasNull()) null else it } override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: Long?) { statementHelper.setLong(pos, javaType, value) } } object FLOAT_T : NumericColumnType<Float, FLOAT_T>("FLOAT", Float::class, Types.FLOAT) { override fun fromResultSet(rs: ResultSet, pos: Int) = rs.getFloat(pos).let { if (rs.wasNull()) null else it } override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: Float?) { statementHelper.setFloat(pos, javaType, value) } } object DOUBLE_T : NumericColumnType<Double, DOUBLE_T>("DOUBLE", Double::class, Types.DOUBLE) { override fun fromResultSet(rs: ResultSet, pos: Int) = rs.getDouble(pos).let { if (rs.wasNull()) null else it } override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: Double?) { statementHelper.setDouble(pos, javaType, value) } } override fun newConfiguration(refColumn: NumericColumn<T, S>) = NumberColumnConfiguration(asS(), refColumn.name) } sealed class DecimalColumnType<S : DecimalColumnType<S>>(typeName: String, type: KClass<BigDecimal>, javaType: Int) : ColumnType<BigDecimal, S, DecimalColumn<S>>(typeName, type, javaType), INumericColumnType<BigDecimal, S, DecimalColumn<S>> { override fun fromResultSet(rs: ResultSet, pos: Int): BigDecimal? = rs.getBigDecimal(pos) object DECIMAL_T : DecimalColumnType<DECIMAL_T>("DECIMAL", BigDecimal::class, Types.DECIMAL) { override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: BigDecimal?) { statementHelper.setDecimal(pos, javaType, value) } } object NUMERIC_T : DecimalColumnType<NUMERIC_T>("NUMERIC", BigDecimal::class, Types.NUMERIC) { override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: BigDecimal?) { statementHelper.setNumeric(pos, javaType, value) } } override fun newConfiguration(refColumn: DecimalColumn<S>): AbstractColumnConfiguration<BigDecimal, S, DecimalColumn<S>, *> { return DecimalColumnConfiguration(asS(), refColumn.name, refColumn.precision, refColumn.scale) } } sealed class SimpleColumnType<T : Any, S : SimpleColumnType<T, S>>(typeName: String, type: KClass<T>, javaType: Int) : ColumnType<T, S, SimpleColumn<T, S>>(typeName, type, javaType) { object BIT_T : SimpleColumnType<Boolean, BIT_T>("BIT", Boolean::class, Types.BIT), BoundedType { override val maxLen = 64 override fun fromResultSet(rs: ResultSet, pos: Int) = rs.getBoolean(pos).let { if (rs.wasNull()) null else it } override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: Boolean?) { statementHelper.setBoolean(pos, javaType, value) } } object DATE_T : SimpleColumnType<Date, DATE_T>("DATE", Date::class, Types.DATE) { override fun fromResultSet(rs: ResultSet, pos: Int): Date? = rs.getDate(pos) override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: Date?) { statementHelper.setDate(pos, javaType, value) } } object TIME_T : SimpleColumnType<Time, TIME_T>("TIME", Time::class, Types.TIME) { override fun fromResultSet(rs: ResultSet, pos: Int): Time? = rs.getTime(pos) override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: Time?) { statementHelper.setTime(pos, javaType, value) } } object TIMESTAMP_T : SimpleColumnType<Timestamp, TIMESTAMP_T>("TIMESTAMP", Timestamp::class, Types.TIMESTAMP) { override fun fromResultSet(rs: ResultSet, pos: Int): Timestamp? = rs.getTimestamp(pos) override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: Timestamp?) { statementHelper.setTimestamp(pos, javaType, value) } } object DATETIME_T : SimpleColumnType<Timestamp, DATETIME_T>("DATETIME", Timestamp::class, Types.OTHER) { override fun fromResultSet(rs: ResultSet, pos: Int): Timestamp? = rs.getTimestamp(pos) override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: Timestamp?) { statementHelper.setTimestamp(pos, javaType, value) } } object YEAR_T : SimpleColumnType<Date, YEAR_T>("YEAR", Date::class, Types.OTHER) { override fun fromResultSet(rs: ResultSet, pos: Int): Date? = rs.getDate(pos) override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: Date?) { statementHelper.setDate(pos, javaType, value) } } object TINYBLOB_T : SimpleColumnType<ByteArray, TINYBLOB_T>("TINYBLOB", ByteArray::class, Types.OTHER), BoundedType { override val maxLen = 255 override fun fromResultSet(rs: ResultSet, pos: Int): ByteArray? = rs.getBytes(pos) override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: ByteArray?) { statementHelper.setBlob(pos, javaType, if (value == null) null else ByteArrayInputStream(value)) } } object BLOB_T : SimpleColumnType<ByteArray, BLOB_T>("BLOB", ByteArray::class, Types.BLOB), BoundedType { override val maxLen = 0xffff override fun fromResultSet(rs: ResultSet, pos: Int): ByteArray? = rs.getBytes(pos) override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: ByteArray?) { statementHelper.setBlob(pos, javaType, if (value == null) null else ByteArrayInputStream(value)) } } object MEDIUMBLOB_T : SimpleColumnType<ByteArray, MEDIUMBLOB_T>("MEDIUMBLOB", ByteArray::class, Types.OTHER), BoundedType { override val maxLen = 0xffffff override fun fromResultSet(rs: ResultSet, pos: Int): ByteArray? = rs.getBytes(pos) override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: ByteArray?) { statementHelper.setBlob(pos, javaType, if (value == null) null else ByteArrayInputStream(value)) } } object LONGBLOB_T : SimpleColumnType<ByteArray, LONGBLOB_T>("LONGBLOB", ByteArray::class, Types.OTHER), BoundedType { override val maxLen = Int.MAX_VALUE /*Actually it would be more*/ override fun fromResultSet(rs: ResultSet, pos: Int): ByteArray? = rs.getBytes(pos) override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: ByteArray?) { statementHelper.setBlob(pos, javaType, if (value == null) null else ByteArrayInputStream(value)) } } override fun newConfiguration(refColumn: SimpleColumn<T, S>) = NormalColumnConfiguration<T, S>(asS(), refColumn.name) } interface ICharColumnType<S : ICharColumnType<S, C>, C : ICharColumn<S, C>> : IColumnType<String, S, C> sealed class CharColumnType<S : CharColumnType<S>>(typeName: String, type: KClass<String>, javaType: Int) : ColumnType<String, S, CharColumn<S>>(typeName, type, javaType), ICharColumnType<S, CharColumn<S>> { override fun fromResultSet(rs: ResultSet, pos: Int): String? = rs.getString(pos) object TINYTEXT_T : CharColumnType<TINYTEXT_T>("TINYTEXT", String::class, Types.OTHER), BoundedType { override val maxLen: Int get() = 255 } object TEXT_T : CharColumnType<TEXT_T>("TEXT", String::class, Types.OTHER), BoundedType { override val maxLen: Int get() = 0xffff } object MEDIUMTEXT_T : CharColumnType<MEDIUMTEXT_T>("MEDIUMTEXT", String::class, Types.OTHER), BoundedType { override val maxLen: Int get() = 0xffffff } object LONGTEXT_T : CharColumnType<LONGTEXT_T>("LONGTEXT", String::class, Types.OTHER), BoundedType { override val maxLen: Int get() = Int.MAX_VALUE /*Actually it would be more*/ } @Suppress("UNCHECKED_CAST") override fun newConfiguration(refColumn: CharColumn<S>) = CharColumnConfiguration(this as S, refColumn.name) override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: String?) { statementHelper.setString(pos, javaType, value) } } interface ILengthColumnType<T : Any, S : ILengthColumnType<T, S, C>, C : ILengthColumn<T, S, C>> : IColumnType<T, S, C> sealed class LengthColumnType<T : Any, S : LengthColumnType<T, S>>(typeName: String, type: KClass<T>, javaType: Int) : ColumnType<T, S, LengthColumn<T, S>>(typeName, type, javaType), ILengthColumnType<T, S, LengthColumn<T, S>> { object BITFIELD_T : LengthColumnType<BooleanArray, BITFIELD_T>("BIT", BooleanArray::class, Types.OTHER) { @Suppress("UNCHECKED_CAST") override fun fromResultSet(rs: ResultSet, pos: Int) = (rs.getArray(pos).array as Array<Any>).let { array -> BooleanArray(array.size) { i -> array[i] as Boolean } } override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: BooleanArray?) { statementHelper.setArray(pos, javaType, value) } } object BINARY_T : LengthColumnType<ByteArray, BINARY_T>("BINARY", ByteArray::class, Types.BINARY), BoundedType { override val maxLen = 255 override fun fromResultSet(rs: ResultSet, pos: Int): ByteArray? = rs.getBytes(pos) override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: ByteArray?) { statementHelper.setBytes(pos, javaType, value) } } object VARBINARY_T : LengthColumnType<ByteArray, VARBINARY_T>("VARBINARY", ByteArray::class, Types.VARBINARY), BoundedType { override val maxLen = 0xffff override fun fromResultSet(rs: ResultSet, pos: Int): ByteArray? = rs.getBytes(pos) override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: ByteArray?) { statementHelper.setBytes(pos, javaType, value) } } @Suppress("UNCHECKED_CAST") override fun newConfiguration(refColumn: LengthColumn<T, S>) = LengthColumnConfiguration(refColumn.name, this as S, refColumn.length) } sealed class LengthCharColumnType<S : LengthCharColumnType<S>>(typeName: String, type: KClass<String>, javaType: Int) : ColumnType<String, S, LengthCharColumn<S>>(typeName, type, javaType), ILengthColumnType<String, S, LengthCharColumn<S>>, ICharColumnType<S, LengthCharColumn<S>> { object CHAR_T : LengthCharColumnType<CHAR_T>("CHAR", String::class, Types.CHAR), BoundedType { override val maxLen: Int get() = 255 } object VARCHAR_T : LengthCharColumnType<VARCHAR_T>("VARCHAR", String::class, Types.VARCHAR), BoundedType { override val maxLen: Int get() = 0xffff } override fun newConfiguration(refColumn: LengthCharColumn<S>) = LengthCharColumnConfiguration(asS(), refColumn.name, refColumn.length) override fun fromResultSet(rs: ResultSet, pos: Int): String? = rs.getString(pos) override fun setParam(statementHelper: PreparedStatementHelper, pos: Int, value: String?) { statementHelper.setString(pos, javaType, value) } } // @formatter:on
apache-2.0
a8b3f09a3d946e9d4ef911c0a12fac15
47.189542
129
0.685135
4.079115
false
false
false
false
oldergod/android-architecture
app/src/main/java/com/example/android/architecture/blueprints/todoapp/tasks/TasksViewState.kt
1
867
package com.example.android.architecture.blueprints.todoapp.tasks import com.example.android.architecture.blueprints.todoapp.data.Task import com.example.android.architecture.blueprints.todoapp.mvibase.MviViewState import com.example.android.architecture.blueprints.todoapp.tasks.TasksFilterType.ALL_TASKS data class TasksViewState( val isLoading: Boolean, val tasksFilterType: TasksFilterType, val tasks: List<Task>, val error: Throwable?, val uiNotification: UiNotification? ) : MviViewState { enum class UiNotification { TASK_COMPLETE, TASK_ACTIVATED, COMPLETE_TASKS_CLEARED } companion object { fun idle(): TasksViewState { return TasksViewState( isLoading = false, tasksFilterType = ALL_TASKS, tasks = emptyList(), error = null, uiNotification = null ) } } }
apache-2.0
71b6d6ecf2e5ff272c50437781eb2db1
26.967742
90
0.717416
4.378788
false
false
false
false
chkpnt/truststorebuilder-gradle-plugin
src/main/kotlin/de/chkpnt/gradle/plugin/truststorebuilder/CertificateService.kt
1
5290
/* * Copyright 2016 - 2022 Gregor Dschung * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.chkpnt.gradle.plugin.truststorebuilder import java.nio.file.Files import java.nio.file.Path import java.security.KeyStore import java.security.MessageDigest import java.security.cert.CertificateException import java.security.cert.CertificateFactory import java.security.cert.X509Certificate import java.time.Clock import java.time.Duration import java.time.LocalDateTime import java.time.ZoneOffset import javax.naming.ldap.LdapName enum class KeyStoreType { JKS, PKCS12 } interface CertificateService { fun isCertificateValidInFuture(cert: X509Certificate, duration: Duration): Boolean fun addCertificateToKeystore(ks: KeyStore, cert: X509Certificate, alias: String) fun loadCertificates(file: Path): List<X509Certificate> fun deriveAlias(cert: X509Certificate): String fun containsAlias(ks: KeyStore, alias: String): Boolean fun newKeyStore(type: KeyStoreType): KeyStore fun storeKeystore(ks: KeyStore, file: Path, password: String) } internal open class DefaultCertificateService : CertificateService { var clock: Clock = Clock.systemDefaultZone() val cf: CertificateFactory = CertificateFactory.getInstance("X.509") override fun isCertificateValidInFuture(cert: X509Certificate, duration: Duration): Boolean { val notAfterInstant = cert.notAfter.toInstant() val notAfter = LocalDateTime.ofInstant(notAfterInstant, ZoneOffset.UTC) val thresholdDateTime = LocalDateTime.now(clock).plus(duration) return thresholdDateTime.isBefore(notAfter) } override fun addCertificateToKeystore(ks: KeyStore, cert: X509Certificate, alias: String) { val certEntry = KeyStore.TrustedCertificateEntry(cert) ks.setEntry(alias, certEntry, null) } fun getCertificateFromKeystore(ks: KeyStore, alias: String): X509Certificate { if (!ks.containsAlias(alias)) { throw IllegalArgumentException("The keystore does not contain a certificate for alias $alias") } if (!ks.entryInstanceOf(alias, KeyStore.TrustedCertificateEntry::class.java)) { throw UnsupportedOperationException("Certificate extraction is currently only implemented for TrustedCertificateEntry") } val entry = ks.getEntry(alias, null) as KeyStore.TrustedCertificateEntry return entry.trustedCertificate as X509Certificate } override fun loadCertificates(file: Path): List<X509Certificate> { Files.newInputStream(file).use { inputStream -> try { return cf.generateCertificates(inputStream).map { it as X509Certificate } } catch (e: CertificateException) { throw TrustStoreBuilderError(file, "Could not load certificate") } } } override fun deriveAlias(cert: X509Certificate): String { val dn = cert.subjectX500Principal.name val ldapName = LdapName(dn) val cn = ldapName.rdns.firstOrNull { it.type.equals("cn", true) }?.value?.toString() ?: dn val fingerprint = shortFingerprintSha1(cert) return "$cn [$fingerprint]" } private fun shortFingerprintSha1(cert: X509Certificate): String { val sha1 = sha1(cert) return sha1.map { String.format("%02X", (it.toInt() and 0xFF)) } .joinToString(separator = "") .take(8) } fun fingerprintSha1(cert: X509Certificate): String { val sha1 = sha1(cert) return sha1.map { String.format("%02X", (it.toInt() and 0xFF)) } .joinToString(separator = ":") } private fun sha1(cert: X509Certificate): ByteArray { val messageDigest = MessageDigest.getInstance("SHA1") messageDigest.update(cert.encoded) return messageDigest.digest() } override fun containsAlias(ks: KeyStore, alias: String): Boolean { return ks.containsAlias(alias) } override fun newKeyStore(type: KeyStoreType): KeyStore { val keystore = KeyStore.getInstance(type.name) keystore.load(null) return keystore } fun loadKeystore(file: Path, password: String): KeyStore { val type = file.keyStoreType() ?: throw IllegalArgumentException("Can't derive KeyStoreType for $file") val keystore = KeyStore.getInstance(type.name) Files.newInputStream(file).use { inputStream -> keystore.load(inputStream, password.toCharArray()) } return keystore } override fun storeKeystore(ks: KeyStore, file: Path, password: String) { Files.newOutputStream(file).use { outputStream -> ks.store(outputStream, password.toCharArray()) } } }
apache-2.0
54ee38dd32da8033926f8e929a82acbb
36.253521
131
0.697732
4.467905
false
false
false
false
emoji-gen/Emoji-Android
lib-slack/src/main/java/moe/pine/emoji/lib/slack/HtmlParser.kt
1
1302
package moe.pine.emoji.lib.slack import org.jsoup.Connection import org.jsoup.Jsoup import org.jsoup.nodes.FormElement /** * HtmlParser * Created by pine on Apr 17, 2017. */ internal object HtmlParser { fun hasSigninForm(body: String): Boolean { val doc = Jsoup.parse(body) return doc.getElementById("signin_form") is FormElement } fun parseSigninFormData(body: String): List<Connection.KeyVal>? { val doc = Jsoup.parse(body) val form = doc.getElementById("signin_form") as? FormElement return form?.formData() } fun parseRegisterFormData(body: String): List<Connection.KeyVal>? { val doc = Jsoup.parse(body) val form = doc.getElementById("addemoji") as? FormElement return form?.formData() } fun parseAlertMessage(body: String): MessageResult { val doc = Jsoup.parse(body) val elem = doc.select(".alert:first-of-type").first() if (elem.hasClass("alert_success")) { val message = elem.select("strong").first().text().trim() return MessageResult(true, if (message.isBlank()) null else message) } else { val message = elem.text().trim() return MessageResult(false, if (message.isBlank()) null else message) } } }
mit
def553c2c0d86103975670d1459eda20
31.575
81
0.638249
4.06875
false
false
false
false
ClearVolume/scenery
src/main/kotlin/graphics/scenery/primitives/Cylinder.kt
2
2781
package graphics.scenery.primitives import graphics.scenery.BufferUtils import graphics.scenery.Mesh import graphics.scenery.geometry.GeometryType import org.joml.Vector3f import java.util.* import kotlin.math.PI import kotlin.math.cos import kotlin.math.sin import kotlin.math.sqrt /** * Constructs a cylinder with the given [radius] and number of [segments]. * * @author Ulrik Günther <[email protected]> * @param[radius] The radius of the sphere * @param[segments] Number of segments in latitude and longitude. */ class Cylinder(var radius: Float, var height: Float, var segments: Int) : Mesh("cylinder") { init { geometry { geometryType = GeometryType.TRIANGLE_STRIP val vbuffer = ArrayList<Float>(segments * segments * 2 * 3) val nbuffer = ArrayList<Float>(segments * segments * 2 * 3) val tbuffer = ArrayList<Float>(segments * segments * 2 * 2) val delta = 2.0f * PI.toFloat() / segments.toFloat() val c = cos(delta * 1.0).toFloat() val s = sin(delta * 1.0).toFloat() var x2 = radius var z2 = 0.0f for (i: Int in 0..segments) { val texcoord = i / segments.toFloat() val normal = 1.0f / sqrt(x2 * x2 * 1.0 + z2 * z2 * 1.0).toFloat() val xn = x2 * normal val zn = z2 * normal nbuffer.add(xn) nbuffer.add(0.0f) nbuffer.add(zn) tbuffer.add(texcoord) tbuffer.add(0.0f) vbuffer.add(0.0f + x2) vbuffer.add(0.0f) vbuffer.add(0.0f + z2) nbuffer.add(xn) nbuffer.add(0.0f) nbuffer.add(zn) tbuffer.add(texcoord) tbuffer.add(1.0f) vbuffer.add(0.0f + x2) vbuffer.add(0.0f + height) vbuffer.add(0.0f + z2) val x3 = x2 x2 = c * x2 - s * z2 z2 = s * x3 + c * z2 } vertices = BufferUtils.allocateFloatAndPut(vbuffer.toFloatArray()) normals = BufferUtils.allocateFloatAndPut(nbuffer.toFloatArray()) texcoords = BufferUtils.allocateFloatAndPut(tbuffer.toFloatArray()) } boundingBox = generateBoundingBox() } companion object { @JvmStatic fun betweenPoints(p1: Vector3f, p2: Vector3f, radius: Float = 0.02f, height: Float = 1.0f, segments: Int = 16): Cylinder { val cylinder = Cylinder(radius, height, segments) cylinder.spatial { orientBetweenPoints(p1, p2, rescale = true, reposition = true) } return cylinder } } }
lgpl-3.0
562ae384c0a64fa345c276782d27d701
30.590909
141
0.550719
3.904494
false
false
false
false
dahlstrom-g/intellij-community
platform/credential-store/src/kdbx/kdbxApi.kt
9
717
// 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.credentialStore.kdbx internal object KdbxAttributeNames { const val protected = "Protected" } internal object KdbxEntryElementNames { const val title = "Title" const val userName = "UserName" const val password = "Password" const val value = "Value" const val key = "Key" const val string = "String" } class IncorrectMasterPasswordException(val isFileMissed: Boolean = false) : RuntimeException() internal interface KeePassCredentials { val key: ByteArray } internal class KdbxException(message: String) : RuntimeException(message)
apache-2.0
77b527c38960443e80b032f642822e35
27.68
140
0.764296
4.319277
false
false
false
false
ogarcia/ultrasonic
ultrasonic/src/main/kotlin/org/moire/ultrasonic/domain/APIJukeboxCoverter.kt
2
506
// Collection of function to convert subsonic api jukebox responses to app entities @file:JvmName("APIJukeboxConverter") package org.moire.ultrasonic.domain import org.moire.ultrasonic.api.subsonic.models.JukeboxStatus as ApiJukeboxStatus fun ApiJukeboxStatus.toDomainEntity(): JukeboxStatus = JukeboxStatus( positionSeconds = [email protected], currentPlayingIndex = [email protected], isPlaying = [email protected], gain = [email protected] )
gpl-3.0
6a39ce52e2fd7b22d58780affe9309fd
41.166667
83
0.812253
3.862595
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/secondStep/modulesEditor/ModulesEditorComponent.kt
5
4396
// 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.tools.projectWizard.wizard.ui.secondStep.modulesEditor import com.intellij.ui.JBColor import com.intellij.ui.ScrollPaneFactory import com.intellij.util.ui.JBUI import org.jetbrains.kotlin.idea.projectWizard.WizardStatsService.UiEditorUsageStats import org.jetbrains.kotlin.tools.projectWizard.core.Context import org.jetbrains.kotlin.tools.projectWizard.core.entity.ValidationResult import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.ListSettingType import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.reference import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.KotlinPlugin import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ProjectKind import org.jetbrains.kotlin.tools.projectWizard.settings.DisplayableSettingItem import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Module import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.customPanel import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.SettingComponent import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.ValidationIndicator import java.awt.BorderLayout import java.awt.Dimension import javax.swing.BorderFactory import javax.swing.JComponent class ModulesEditorComponent( context: Context, uiEditorUsagesStats: UiEditorUsageStats?, needBorder: Boolean, private val editable: Boolean, oneEntrySelected: (data: DisplayableSettingItem?) -> Unit ) : SettingComponent<List<Module>, ListSettingType<Module>>(KotlinPlugin.modules.reference, context) { private val tree: ModulesEditorTree = ModulesEditorTree( onSelected = { oneEntrySelected(it) }, context = context, isTreeEditable = editable, addModule = { component -> val isMppProject = KotlinPlugin.projectKind.reference.value == ProjectKind.Singleplatform moduleCreator.create( target = null, // The empty tree case allowMultiplatform = isMppProject, allowSinglePlatformJsBrowser = isMppProject, allowSinglePlatformJsNode = isMppProject, allowAndroid = isMppProject, allowIos = isMppProject, allModules = value ?: emptyList(), createModule = model::add )?.showInCenterOf(component) } ).apply { if (editable) { border = JBUI.Borders.emptyRight(10) } } private val model = TargetsModel(tree, ::value, context, uiEditorUsagesStats) override fun onInit() { super.onInit() updateModel() if (editable) { value?.firstOrNull()?.let(tree::selectModule) } } fun updateModel() { model.update() } override fun navigateTo(error: ValidationResult.ValidationError) { val targetModule = error.target as? Module ?: return tree.selectModule(targetModule) } private val moduleCreator = NewModuleCreator() private val toolbarDecorator = if (editable) ModulesEditorToolbarDecorator( tree = tree, moduleCreator = moduleCreator, model = model, getModules = { value ?: emptyList() }, isMultiplatformProject = { KotlinPlugin.projectKind.reference.value != ProjectKind.Singleplatform } ) else null override val component: JComponent by lazy(LazyThreadSafetyMode.NONE) { customPanel { if (needBorder) { border = BorderFactory.createLineBorder(JBColor.border()) } add(createEditorComponent(), BorderLayout.CENTER) } } private fun createEditorComponent() = when { editable -> toolbarDecorator!!.createToolPanel() else -> ScrollPaneFactory.createScrollPane(tree, true).apply { viewport.background = JBColor.PanelBackground } }.apply { preferredSize = Dimension(TREE_WIDTH, preferredSize.height) } override val validationIndicator: ValidationIndicator? = null companion object { private const val TREE_WIDTH = 260 } }
apache-2.0
7e6ece866152e01ff0d7d1a13ad54969
39.703704
158
0.687216
4.961625
false
false
false
false
dahlstrom-g/intellij-community
plugins/git4idea/src/git4idea/ui/branch/dashboard/BranchesInGitLogUiFactoryProvider.kt
9
1443
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.ui.branch.dashboard import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsRoot import com.intellij.openapi.vfs.VirtualFile import com.intellij.vcs.log.VcsLogFilterCollection import com.intellij.vcs.log.VcsLogProvider import com.intellij.vcs.log.impl.CustomVcsLogUiFactoryProvider import com.intellij.vcs.log.impl.VcsLogManager import com.intellij.vcs.log.ui.MainVcsLogUi import git4idea.GitVcs class BranchesInGitLogUiFactoryProvider(private val project: Project) : CustomVcsLogUiFactoryProvider { override fun isActive(providers: Map<VirtualFile, VcsLogProvider>) = hasGitRoots(project, providers.keys) override fun createLogUiFactory(logId: String, vcsLogManager: VcsLogManager, filters: VcsLogFilterCollection?): VcsLogManager.VcsLogUiFactory<out MainVcsLogUi> = BranchesVcsLogUiFactory(vcsLogManager, logId, filters) private fun hasGitRoots(project: Project, roots: Collection<VirtualFile>) = ProjectLevelVcsManager.getInstance(project).allVcsRoots.asSequence() .filter { it.vcs?.keyInstanceMethod == GitVcs.getKey() } .map(VcsRoot::getPath) .toSet() .containsAll(roots) }
apache-2.0
2cb7aa3b147e95d2ed50bd6a135f5f5d
47.133333
158
0.77131
4.610224
false
false
false
false
sreich/ore-infinium
core/src/com/ore/infinium/ErrorDialog.kt
1
5895
package com.ore.infinium /** MIT License Copyright (c) 2016 Shaun Reich <[email protected]> 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. */ import java.awt.BorderLayout import java.awt.Dimension import java.awt.Toolkit import java.awt.Window import java.awt.datatransfer.StringSelection import java.io.PrintWriter import java.io.StringWriter import javax.swing.* import javax.swing.text.DefaultEditorKit class ErrorDialog(private val exception: Throwable, private val thread: Thread) : JDialog() { // JDialog(null as Dialog) //was working before, but kotlin broke this. java just did super((Dialog)null) private var showDetails: Boolean = false private val errorMessageField: JEditorPane private val mainComponent: JComponent private var detailsScrollPane: JScrollPane? = null private lateinit var stackTracePane: JTextPane private var stackTrace: String? = null init { errorMessageField = createErrorMessage(exception) mainComponent = createContent() title = exception.javaClass.name // setModal(true); type = Window.Type.NORMAL defaultCloseOperation = JDialog.DISPOSE_ON_CLOSE contentPane.add(mainComponent) pack() // SwingHelper.position(this, owner); }//show up in taskbar /** * Creates the display with the top-level exception message * followed by a pane (that toggles) for detailed stack traces. */ internal fun createContent(): JComponent { val showDetails = JButton("Show Details >>") stackTracePane = JTextPane() stackTracePane.isEditable = false val errors = StringWriter() exception.printStackTrace(PrintWriter(errors)) stackTrace = errors.toString() println(stackTrace) showDetails.addActionListener { if (this.showDetails) { mainComponent.remove(detailsScrollPane) mainComponent.validate() mainComponent.preferredSize = MESSAGE_SIZE } else { if (detailsScrollPane == null) { detailsScrollPane = createDetailedMessage(exception) stackTracePane.text = stackTrace stackTracePane.background = mainComponent.background stackTracePane.preferredSize = STACKTRACE_SIZE } mainComponent.add(detailsScrollPane, BorderLayout.CENTER) mainComponent.validate() mainComponent.preferredSize = TOTAL_SIZE } this.showDetails = !this.showDetails showDetails.text = if (this.showDetails) "<< Hide Details" else "Show Details >>" [email protected]() } val quit = JButton("Quit") quit.addActionListener { System.exit(1) } val copy = JButton(DefaultEditorKit.copyAction) copy.addActionListener { val select = StringSelection(stackTrace) val clipboard = Toolkit.getDefaultToolkit().systemClipboard clipboard.setContents(select, null) } val buttonPanel = JPanel().apply { add(Box.createHorizontalStrut(20)) add(showDetails) add(Box.createHorizontalStrut(20)) add(copy) add(Box.createHorizontalStrut(20)) add(quit) add(Box.createHorizontalGlue()) } val messagePanel = JPanel().apply { errorMessageField.background = background layout = BorderLayout() border = BorderFactory.createEmptyBorder(20, 20, 20, 20) add(errorMessageField, BorderLayout.CENTER) add(buttonPanel, BorderLayout.SOUTH) preferredSize = MESSAGE_SIZE } val main = JPanel().apply { layout = BorderLayout() add(messagePanel, BorderLayout.NORTH) } return main } /** * Creates a non-editable widget to display the error message. */ internal fun createErrorMessage(t: Throwable): JEditorPane { val message = "${t.message} \n Thread name: ${thread.name}" val messagePane = JEditorPane().apply { contentType = "text/plain" isEditable = false text = message } return messagePane } /** * Creates a non-editable widget to display the detailed stack trace. */ internal fun createDetailedMessage(t: Throwable): JScrollPane { val pane = JScrollPane(stackTracePane, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) return pane } companion object { private val MESSAGE_SIZE = Dimension(600, 200) private val STACKTRACE_SIZE = Dimension(600, 300) private val TOTAL_SIZE = Dimension(600, 500) } }
mit
8e45b24292c0b93027b65a4bfc60f1c2
34.089286
93
0.65598
5.126087
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/table/ClientInfo.kt
1
2663
package jp.juggler.subwaytooter.table import android.content.ContentValues import android.database.sqlite.SQLiteDatabase import android.provider.BaseColumns import jp.juggler.subwaytooter.global.appDatabase import jp.juggler.util.* object ClientInfo : TableCompanion { private val log = LogCategory("ClientInfo") override val table = "client_info2" val columnList: ColumnMeta.List = ColumnMeta.List(table, 19).apply { ColumnMeta(this, 0, BaseColumns._ID, "INTEGER PRIMARY KEY", primary = true) createExtra = { arrayOf( "create unique index if not exists ${table}_host_client_name on $table($COL_HOST,$COL_CLIENT_NAME)" ) } } private val COL_HOST = ColumnMeta(columnList, 0, "h", "text not null") private val COL_CLIENT_NAME = ColumnMeta(columnList, 0, "cn", "text not null") private val COL_RESULT = ColumnMeta(columnList, 0, "r", "text not null") override fun onDBCreate(db: SQLiteDatabase) = columnList.onDBCreate(db) override fun onDBUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) = columnList.onDBUpgrade(db, oldVersion, newVersion) fun load(instance: String, clientName: String): JsonObject? { try { appDatabase.query( table, null, "h=? and cn=?", arrayOf(instance, clientName), null, null, null ) .use { cursor -> if (cursor.moveToFirst()) { return cursor.getString(COL_RESULT).decodeJsonObject() } } } catch (ex: Throwable) { log.e(ex, "load failed.") } return null } fun save(instance: String, clientName: String, json: String) { try { val cv = ContentValues() cv.put(COL_HOST, instance) cv.put(COL_CLIENT_NAME, clientName) cv.put(COL_RESULT, json) appDatabase.replace(table, null, cv) } catch (ex: Throwable) { log.e(ex, "save failed.") } } // 単体テスト用。インスタンス名を指定して削除する fun delete(instance: String, clientName: String) { try { appDatabase.delete( table, "$COL_HOST=? and $COL_CLIENT_NAME=?", arrayOf(instance, clientName) ) } catch (ex: Throwable) { log.e(ex, "delete failed.") } } }
apache-2.0
684fb919043befc70350b970fef7b11a
31.551282
115
0.541078
4.458262
false
false
false
false
spark1991z/spok
project/log/Log.kt
1
952
package project.log import java.text.SimpleDateFormat /** * @author spark1991z */ class Log private constructor() { companion object { private var sdf: SimpleDateFormat = SimpleDateFormat("yyy-MM-dd@HH:mm:ss") private var init_timestamp: Long = System.currentTimeMillis() var DEBUG: Boolean = false private fun log(type: String, service: String, msg: String) { var t: String = ((System.currentTimeMillis() - init_timestamp).toDouble() / 1000).toString() if (t.split(".")[1].length < 3) t += 0 println("[$t][$type][$service] $msg") } fun info(service: String, msg: String) { log("INFO", service, msg) } fun debug(service: String, msg: String) { if (DEBUG) log("DEBUG", service, msg) } fun error(service: String, msg: String) { log("ERROR", service, msg) } } }
gpl-3.0
ca965a5f4faa1625211e1cfb6728ea7a
26.228571
104
0.558824
4.13913
false
false
false
false
miguelfs/desafio-mobile
app/src/main/java/com/partiufast/mercadodoimperador/ui/activities/PaymentActivity.kt
1
6269
package com.partiufast.mercadodoimperador.ui.activities import android.support.v7.app.AppCompatActivity import android.os.Bundle import com.partiufast.mercadodoimperador.R import android.widget.EditText import kotlinx.android.synthetic.main.activity_payment.* import java.util.* import java.text.SimpleDateFormat import android.text.InputType import android.os.Build import android.text.TextUtils import android.view.MenuItem import android.widget.Toast import com.partiufast.mercadodoimperador.api.CartPostRequest import com.partiufast.mercadodoimperador.ui.custom.MonthYearPickerDialog import org.jetbrains.anko.doAsync import org.jetbrains.anko.uiThread import android.app.ProgressDialog import android.content.Intent import com.partiufast.mercadodoimperador.model.BillHistory class PaymentActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_payment) val total_price = intent.getStringExtra(getString(R.string.CART_VALUE_EXTRA)) total_price_text_view.text = "Valor Total: R$$total_price" if (supportActionBar != null) supportActionBar!!.setDisplayHomeAsUpEnabled(true) val myCalendar = Calendar.getInstance() val pickerDialog = MonthYearPickerDialog() pickerDialog.setListener { _, year, month, _ -> myCalendar.set(Calendar.YEAR, year) myCalendar.set(Calendar.MONTH, month) updateLabel(myCalendar, input_date_edittext) } disableSoftInputFromAppearing(input_date_edittext) input_date_edittext.setOnFocusChangeListener { _, hasFocus -> if (hasFocus) { pickerDialog.show(fragmentManager, "MonthYearPickerDialog") input_date_edittext.error = null } } attempt_payment_button.setOnClickListener { attemptPayment(myCalendar, total_price) } //TODO: adicionar valor total na view de forma do pagamento } private fun attemptPayment(calendar: Calendar, total_price: String) { input_layout_fullname.error = null input_layout_number.error = null input_verifier_layout.error = null input_date_layout.error = null val fullname = input_fullname_edittext.text.toString() val cardnumber = input_credit_card_number_edittext.text.toString() val verificationNumber = input_verifiernumber_edittext.text.toString() val date = input_date_edittext.text.toString() var cancel = false //check for a valid name if (TextUtils.isEmpty(date) || calendar.timeInMillis < System.currentTimeMillis()){ input_date_edittext.error = getString(R.string.error_invalid_date) cancel = true } if (TextUtils.isEmpty(fullname) || !isFullnameValid(fullname)) { input_layout_fullname.error = getString(R.string.error_invalid_fullname) cancel = true } if (TextUtils.isEmpty(cardnumber) || !isCreditCardNumberValid(cardnumber)) { input_credit_card_number_edittext.error = getString(R.string.error_invalid_credit_card_number) cancel = true } if (TextUtils.isEmpty(verificationNumber) || !isVerificationNumberValid(verificationNumber)){ input_verifiernumber_edittext.error = getString(R.string.error_invalid_verifier) cancel = true } if (!cancel){ val dialog = ProgressDialog.show(this, "", "Carregando...", true) doAsync { val request = CartPostRequest() val response = request.run(cardnumber, total_price.replace(".", "").toInt(), fullname, verificationNumber.toInt(), date) uiThread { dialog.dismiss() if (response == 200){ val sdf = SimpleDateFormat("dd/MM/yyyy HH:mm") val currentDateandTime = sdf.format(Date()) val bill = BillHistory(currentDateandTime, fullname, cardnumber.substring(12).toInt(), "R$$total_price") val intentBillActivity = Intent(applicationContext, HistoryActivity::class.java) intentBillActivity.putExtra(getString(R.string.BILL_EXTRA), bill) startActivity(intentBillActivity) val intentClearCart = Intent() intentClearCart.putExtra(getString(R.string.CLEAR_CART_EXTRA), true) setResult(RESULT_OK, intentClearCart) finish() } else { Toast.makeText(applicationContext, "Compra não efetuada :(", Toast.LENGTH_SHORT).show() } } } } } private fun isVerificationNumberValid(verificationNumber: String): Boolean { return (verificationNumber.length == 3) } private fun isCreditCardNumberValid(cardnumber: String): Boolean { return ((cardnumber.length == 16)&&(cardnumber.matches(Regex("[0-9]+")))) } private fun isFullnameValid(fullname: String): Boolean { return (fullname.contains(' ') && fullname.length > 8) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { // Respond to the action bar's Up/Home button android.R.id.home -> { finish() return true } } return super.onOptionsItemSelected(item) } private fun updateLabel(calendar: Calendar, editText: EditText) { val myFormat = "MM/yy" //In which you need put here val sdf = SimpleDateFormat(myFormat, Locale.US) editText.setText(sdf.format(calendar.time)) } fun disableSoftInputFromAppearing(editText: EditText) { if (Build.VERSION.SDK_INT >= 11) { editText.setRawInputType(InputType.TYPE_CLASS_TEXT) editText.setTextIsSelectable(true) } else { editText.setRawInputType(InputType.TYPE_NULL) editText.isFocusable = true } } }
mit
84bb136582dd7644a1cd08eaa7899903
36.309524
136
0.633216
4.585223
false
false
false
false
dkhmelenko/draw2fashion
app/src/main/java/org/hackzurich2017/draw2fashion/ListenFragment.kt
1
3551
package org.hackzurich2017.draw2fashion import android.content.Context import android.net.Uri import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import org.hackzurich2017.draw2fashion.draw2fashion.R /** * A simple [Fragment] subclass. * Activities that contain this fragment must implement the * [ListenFragment.OnFragmentInteractionListener] interface * to handle interaction events. * Use the [ListenFragment.newInstance] factory method to * create an instance of this fragment. */ class ListenFragment : Fragment() { // TODO: Rename and change types of parameters private var mParam1: String? = null private var mParam2: String? = null private var mListener: OnFragmentInteractionListener? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (arguments != null) { mParam1 = arguments.getString(ARG_PARAM1) mParam2 = arguments.getString(ARG_PARAM2) } } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment return inflater!!.inflate(R.layout.fragment_listen, container, false) } // TODO: Rename method, update argument and hook method into UI event fun onButtonPressed(uri: Uri) { if (mListener != null) { mListener!!.onFragmentInteraction(uri) } } override fun onAttach(context: Context?) { super.onAttach(context) if (context is OnFragmentInteractionListener) { mListener = context } else { throw RuntimeException(context!!.toString() + " must implement OnFragmentInteractionListener") } } override fun onDetach() { super.onDetach() mListener = null } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * * * See the Android Training lesson [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html) for more information. */ interface OnFragmentInteractionListener { // TODO: Update argument type and name fun onFragmentInteraction(uri: Uri) } companion object { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private val ARG_PARAM1 = "param1" private val ARG_PARAM2 = "param2" /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * @param param1 Parameter 1. * * * @param param2 Parameter 2. * * * @return A new instance of fragment ListenFragment. */ // TODO: Rename and change types and number of parameters fun newInstance(param1: String, param2: String): ListenFragment { val fragment = ListenFragment() val args = Bundle() args.putString(ARG_PARAM1, param1) args.putString(ARG_PARAM2, param2) fragment.arguments = args return fragment } } }// Required empty public constructor
apache-2.0
2e41b6386b574540a43b21f79dd48996
33.144231
172
0.662067
4.857729
false
false
false
false
apollographql/apollo-android
apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/kotlin/file/EnumResponseAdapterBuilder.kt
1
3222
package com.apollographql.apollo3.compiler.codegen.kotlin.file import com.apollographql.apollo3.compiler.codegen.Identifier import com.apollographql.apollo3.compiler.codegen.Identifier.customScalarAdapters import com.apollographql.apollo3.compiler.codegen.Identifier.reader import com.apollographql.apollo3.compiler.codegen.Identifier.safeValueOf import com.apollographql.apollo3.compiler.codegen.Identifier.toJson import com.apollographql.apollo3.compiler.codegen.Identifier.value import com.apollographql.apollo3.compiler.codegen.Identifier.writer import com.apollographql.apollo3.compiler.codegen.kotlin.CgFile import com.apollographql.apollo3.compiler.codegen.kotlin.CgOutputFileBuilder import com.apollographql.apollo3.compiler.codegen.kotlin.KotlinSymbols import com.apollographql.apollo3.compiler.codegen.kotlin.KotlinContext import com.apollographql.apollo3.compiler.ir.IrEnum import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.TypeSpec class EnumResponseAdapterBuilder( val context: KotlinContext, val enum: IrEnum, ) : CgOutputFileBuilder { private val layout = context.layout private val packageName = layout.typeAdapterPackageName() private val simpleName = layout.enumResponseAdapterName(enum.name) override fun prepare() { context.resolver.registerEnumAdapter( enum.name, ClassName(packageName, simpleName) ) } override fun build(): CgFile { return CgFile( packageName = packageName, fileName = simpleName, typeSpecs = listOf(enum.typeSpec()) ) } private fun IrEnum.typeSpec(): TypeSpec { val adaptedTypeName = context.resolver.resolveSchemaType(enum.name) val fromResponseFunSpec = FunSpec.builder(Identifier.fromJson) .addModifiers(KModifier.OVERRIDE) .addParameter(reader, KotlinSymbols.JsonReader) .addParameter(customScalarAdapters, KotlinSymbols.CustomScalarAdapters) .returns(adaptedTypeName) .addCode( CodeBlock.builder() .addStatement("val·rawValue·=·reader.nextString()!!") .addStatement("return·%T.$safeValueOf(rawValue)", adaptedTypeName) .build() ) .addModifiers(KModifier.OVERRIDE) .build() val toResponseFunSpec = toResponseFunSpecBuilder(adaptedTypeName) .addCode("$writer.$value($value.rawValue)") .build() return TypeSpec .objectBuilder(layout.enumResponseAdapterName(name)) .addSuperinterface(KotlinSymbols.Adapter.parameterizedBy(adaptedTypeName)) .addFunction(fromResponseFunSpec) .addFunction(toResponseFunSpec) .build() } } private fun toResponseFunSpecBuilder(typeName: TypeName) = FunSpec.builder(toJson) .addModifiers(KModifier.OVERRIDE) .addParameter(name = writer, type = KotlinSymbols.JsonWriter) .addParameter(name = customScalarAdapters, type = KotlinSymbols.CustomScalarAdapters) .addParameter(value, typeName)
mit
c96583ae5dfc576d60a3a4ed86b9a5ba
40.269231
89
0.766004
4.677326
false
false
false
false
domdomegg/apps-android-commons
app/src/main/java/fr/free/nrw/commons/description/DescriptionEditActivity.kt
2
6831
package fr.free.nrw.commons.description import android.app.ProgressDialog import android.content.Intent import android.os.Bundle import android.os.Parcelable import android.view.View import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import fr.free.nrw.commons.R import fr.free.nrw.commons.databinding.ActivityDescriptionEditBinding import fr.free.nrw.commons.description.EditDescriptionConstants.LIST_OF_DESCRIPTION_AND_CAPTION import fr.free.nrw.commons.description.EditDescriptionConstants.UPDATED_WIKITEXT import fr.free.nrw.commons.description.EditDescriptionConstants.WIKITEXT import fr.free.nrw.commons.recentlanguages.RecentLanguagesDao import fr.free.nrw.commons.settings.Prefs import fr.free.nrw.commons.theme.BaseActivity import fr.free.nrw.commons.upload.UploadMediaDetail import fr.free.nrw.commons.upload.UploadMediaDetailAdapter import fr.free.nrw.commons.utils.DialogUtil.showAlertDialog import javax.inject.Inject /** * Activity for populating and editing existing description and caption */ class DescriptionEditActivity : BaseActivity(), UploadMediaDetailAdapter.EventListener { /** * Adapter for showing UploadMediaDetail in the activity */ private lateinit var uploadMediaDetailAdapter: UploadMediaDetailAdapter /** * Recyclerview for recycling data in views */ @JvmField var rvDescriptions: RecyclerView? = null /** * Current wikitext */ var wikiText: String? = null /** * Saved language */ private lateinit var savedLanguageValue: String /** * For showing progress dialog */ private var progressDialog: ProgressDialog? = null @Inject lateinit var recentLanguagesDao: RecentLanguagesDao private lateinit var binding: ActivityDescriptionEditBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityDescriptionEditBinding.inflate(layoutInflater) setContentView(binding.root) val bundle = intent.extras val descriptionAndCaptions: ArrayList<UploadMediaDetail> = bundle!!.getParcelableArrayList(LIST_OF_DESCRIPTION_AND_CAPTION)!! wikiText = bundle.getString(WIKITEXT) savedLanguageValue = bundle.getString(Prefs.DESCRIPTION_LANGUAGE)!! initRecyclerView(descriptionAndCaptions) binding.btnAddDescription.setOnClickListener(::onButtonAddDescriptionClicked) binding.btnEditSubmit.setOnClickListener(::onSubmitButtonClicked) binding.toolbarBackButton.setOnClickListener(::onBackButtonClicked) } /** * Initializes the RecyclerView * @param descriptionAndCaptions list of description and caption */ private fun initRecyclerView(descriptionAndCaptions: ArrayList<UploadMediaDetail>?) { uploadMediaDetailAdapter = UploadMediaDetailAdapter( savedLanguageValue, descriptionAndCaptions, recentLanguagesDao) uploadMediaDetailAdapter.setCallback { titleStringID: Int, messageStringId: Int -> showInfoAlert( titleStringID, messageStringId ) } uploadMediaDetailAdapter.setEventListener(this) rvDescriptions = binding.rvDescriptionsCaptions rvDescriptions!!.layoutManager = LinearLayoutManager(this) rvDescriptions!!.adapter = uploadMediaDetailAdapter } /** * show dialog with info * @param titleStringID Title ID * @param messageStringId Message ID */ private fun showInfoAlert(titleStringID: Int, messageStringId: Int) { showAlertDialog( this, getString(titleStringID), getString(messageStringId), getString(android.R.string.ok), null, true ) } override fun onPrimaryCaptionTextChange(isNotEmpty: Boolean) {} private fun onBackButtonClicked(view: View) { onBackPressed() } private fun onButtonAddDescriptionClicked(view: View) { val uploadMediaDetail = UploadMediaDetail() uploadMediaDetail.isManuallyAdded = true //This was manually added by the user uploadMediaDetailAdapter.addDescription(uploadMediaDetail) rvDescriptions!!.smoothScrollToPosition(uploadMediaDetailAdapter.itemCount - 1) } private fun onSubmitButtonClicked(view: View) { showLoggingProgressBar() val uploadMediaDetails = uploadMediaDetailAdapter.items updateDescription(uploadMediaDetails) finish() } /** * Updates newly added descriptions in the wikiText and send to calling fragment * @param uploadMediaDetails descriptions and captions */ private fun updateDescription(uploadMediaDetails: List<UploadMediaDetail?>) { var descriptionIndex = wikiText!!.indexOf("description=") if (descriptionIndex == -1) { descriptionIndex = wikiText!!.indexOf("Description=") } val buffer = StringBuilder() if (descriptionIndex != -1) { val descriptionStart = wikiText!!.substring(0, descriptionIndex + 12) val descriptionToEnd = wikiText!!.substring(descriptionIndex + 12) val descriptionEndIndex = descriptionToEnd.indexOf("\n") val descriptionEnd = wikiText!!.substring( descriptionStart.length + descriptionEndIndex ) buffer.append(descriptionStart) for (i in uploadMediaDetails.indices) { val uploadDetails = uploadMediaDetails[i] if (uploadDetails!!.descriptionText != "") { buffer.append("{{") buffer.append(uploadDetails.languageCode) buffer.append("|1=") buffer.append(uploadDetails.descriptionText) buffer.append("}}, ") } } buffer.deleteCharAt(buffer.length - 1) buffer.deleteCharAt(buffer.length - 1) buffer.append(descriptionEnd) } val returningIntent = Intent() returningIntent.putExtra(UPDATED_WIKITEXT, buffer.toString()) returningIntent.putParcelableArrayListExtra( LIST_OF_DESCRIPTION_AND_CAPTION, uploadMediaDetails as ArrayList<out Parcelable?> ) setResult(RESULT_OK, returningIntent) finish() } private fun showLoggingProgressBar() { progressDialog = ProgressDialog(this) progressDialog!!.isIndeterminate = true progressDialog!!.setTitle(getString(R.string.updating_caption_title)) progressDialog!!.setMessage(getString(R.string.updating_caption_message)) progressDialog!!.setCanceledOnTouchOutside(false) progressDialog!!.show() } }
apache-2.0
3c4541b1f083f8353c15584d89bae6c1
37.167598
95
0.694774
5.287152
false
false
false
false
spacecowboy/Feeder
app/src/main/java/com/nononsenseapps/feeder/model/RssNotifications.kt
1
11606
package com.nononsenseapps.feeder.model import android.annotation.TargetApi import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.PendingIntent.FLAG_IMMUTABLE import android.content.Context import android.content.Context.NOTIFICATION_SERVICE import android.content.Intent import android.graphics.BitmapFactory import android.net.Uri import android.os.Build import android.provider.Browser.EXTRA_CREATE_NEW_TAB import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import androidx.core.app.NotificationCompat.GROUP_ALERT_SUMMARY import androidx.core.app.NotificationManagerCompat import androidx.core.net.toUri import androidx.navigation.NavDeepLinkBuilder import com.nononsenseapps.feeder.R import com.nononsenseapps.feeder.db.COL_LINK import com.nononsenseapps.feeder.db.URI_FEEDITEMS import com.nononsenseapps.feeder.db.room.FeedDao import com.nononsenseapps.feeder.db.room.FeedItemDao import com.nononsenseapps.feeder.db.room.FeedItemWithFeed import com.nononsenseapps.feeder.db.room.ID_ALL_FEEDS import com.nononsenseapps.feeder.db.room.ID_UNSET import com.nononsenseapps.feeder.ui.EXTRA_FEEDITEMS_TO_MARK_AS_NOTIFIED import com.nononsenseapps.feeder.ui.MainActivity import com.nononsenseapps.feeder.ui.OpenLinkInDefaultActivity import com.nononsenseapps.feeder.util.DEEP_LINK_BASE_URI import com.nononsenseapps.feeder.util.notificationManager import com.nononsenseapps.feeder.util.urlEncode import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.kodein.di.DI import org.kodein.di.android.closestDI import org.kodein.di.instance const val summaryNotificationId = 2_147_483_646 private const val channelId = "feederNotifications" private const val articleNotificationGroup = "com.nononsenseapps.feeder.ARTICLE" suspend fun notify( appContext: Context, updateSummaryOnly: Boolean = false ) = withContext(Dispatchers.Default) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { createNotificationChannel(appContext) } val di by closestDI(appContext) val nm: NotificationManagerCompat by di.instance() val feedItems = getItemsToNotify(di) if (feedItems.isNotEmpty()) { if (!updateSummaryOnly) { feedItems.map { it.id.toInt() to singleNotification(appContext, it) }.forEach { (id, notification) -> nm.notify(id, notification) } } // Shown on API Level < 24 nm.notify(summaryNotificationId, inboxNotification(appContext, feedItems)) } } suspend fun cancelNotification(context: Context, feedItemId: Long) = cancelNotifications(context, listOf(feedItemId)) suspend fun cancelNotifications(context: Context, feedItemIds: List<Long>) = withContext(Dispatchers.Default) { val nm = context.notificationManager for (feedItemId in feedItemIds) { nm.cancel(feedItemId.toInt()) } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { notify(context) } } /** * This is an update operation if channel already exists so it's safe to call multiple times */ @TargetApi(Build.VERSION_CODES.O) @RequiresApi(Build.VERSION_CODES.O) private fun createNotificationChannel(context: Context) { val name = context.getString(R.string.notification_channel_name) val description = context.getString(R.string.notification_channel_description) val notificationManager: NotificationManager = context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager val channel = NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_LOW) channel.description = description notificationManager.createNotificationChannel(channel) } private fun singleNotification(context: Context, item: FeedItemWithFeed): Notification { val style = NotificationCompat.BigTextStyle() val title = item.plainTitle val text = item.feedDisplayTitle style.bigText(text) style.setBigContentTitle(title) val contentIntent = Intent( Intent.ACTION_VIEW, "$DEEP_LINK_BASE_URI/article/${item.id}".toUri(), context, MainActivity::class.java ) val pendingIntent = PendingIntent.getActivity( context, item.id.toInt(), contentIntent, PendingIntent.FLAG_UPDATE_CURRENT or FLAG_IMMUTABLE ) val builder = notificationBuilder(context) builder.setContentText(text) .setContentTitle(title) .setContentIntent(pendingIntent) .setGroup(articleNotificationGroup) .setGroupAlertBehavior(GROUP_ALERT_SUMMARY) .setDeleteIntent(getPendingDeleteIntent(context, item)) .setNumber(1) // Note that notifications must use PNG resources, because there is no compatibility for vector drawables here item.enclosureLink?.let { enclosureLink -> val intent = Intent(Intent.ACTION_VIEW, Uri.parse(enclosureLink)) intent.putExtra(EXTRA_CREATE_NEW_TAB, true) builder.addAction( R.drawable.notification_play_circle_outline, context.getString(R.string.open_enclosed_media), PendingIntent.getActivity( context, item.id.toInt(), getOpenInDefaultActivityIntent(context, item.id, enclosureLink), PendingIntent.FLAG_UPDATE_CURRENT or FLAG_IMMUTABLE ) ) } item.link?.let { link -> builder.addAction( R.drawable.notification_open_in_browser, context.getString(R.string.open_link_in_browser), PendingIntent.getActivity( context, item.id.toInt(), getOpenInDefaultActivityIntent(context, item.id, link), PendingIntent.FLAG_UPDATE_CURRENT or FLAG_IMMUTABLE ) ) } builder.addAction( R.drawable.notification_check, context.getString(R.string.mark_as_read), PendingIntent.getBroadcast( context, item.id.toInt(), getMarkAsReadIntent(context, item.id), PendingIntent.FLAG_UPDATE_CURRENT or FLAG_IMMUTABLE ) ) style.setBuilder(builder) return style.build() ?: error("Null??") } internal fun getOpenInDefaultActivityIntent( context: Context, feedItemId: Long, link: String? = null ): Intent = Intent( Intent.ACTION_VIEW, // Important to keep the URI different so PendingIntents don't collide URI_FEEDITEMS.buildUpon().appendPath("$feedItemId").also { if (link != null) { it.appendQueryParameter(COL_LINK, link) } }.build(), context, OpenLinkInDefaultActivity::class.java ) internal fun getMarkAsReadIntent( context: Context, feedItemId: Long, ): Intent = Intent( ACTION_MARK_AS_READ, // Important to keep the URI different so PendingIntents don't collide URI_FEEDITEMS.buildUpon().appendPath("$feedItemId").build(), context, RssNotificationBroadcastReceiver::class.java ) /** * Use this on platforms older than 24 to bundle notifications together */ private fun inboxNotification(context: Context, feedItems: List<FeedItemWithFeed>): Notification { val style = NotificationCompat.InboxStyle() val title = context.getString(R.string.updated_feeds) val text = feedItems.map { it.feedDisplayTitle }.toSet().joinToString(separator = ", ") style.setBigContentTitle(title) feedItems.forEach { style.addLine("${it.feedDisplayTitle} \u2014 ${it.plainTitle}") } // We can be a little bit smart - if all items are from the same feed then go to that feed // Otherwise we should go to All feeds val feedTags = feedItems.map { it.tag }.toSet() val deepLinkTag = if (feedTags.size == 1) { feedTags.first() } else { "" } val feedIds = feedItems.map { it.feedId }.toSet() val deepLinkId = if (feedIds.size == 1) { feedIds.first() ?: ID_UNSET } else { if (deepLinkTag.isNotEmpty()) { ID_ALL_FEEDS // Tag will take precedence } else { ID_UNSET // Will default to last open when tag is empty too } } val deepLinkUri = "$DEEP_LINK_BASE_URI/feed?id=$deepLinkId&tag=${deepLinkTag.urlEncode()}" val contentIntent = Intent( Intent.ACTION_VIEW, deepLinkUri.toUri(), context, OpenLinkInDefaultActivity::class.java // Proxy activity to mark as read ).also { it.putExtra( EXTRA_FEEDITEMS_TO_MARK_AS_NOTIFIED, LongArray(feedItems.size) { i -> feedItems[i].id } ) } val pendingIntent = PendingIntent.getActivity( context, summaryNotificationId, contentIntent, PendingIntent.FLAG_UPDATE_CURRENT or FLAG_IMMUTABLE ) val builder = notificationBuilder(context) builder.setContentText(text) .setContentTitle(title) .setContentIntent(pendingIntent) .setGroup(articleNotificationGroup) .setGroupAlertBehavior(GROUP_ALERT_SUMMARY) .setGroupSummary(true) .setDeleteIntent(getDeleteIntent(context, feedItems)) .setNumber(feedItems.size) style.setBuilder(builder) return style.build() ?: error("How null??") } private fun getDeleteIntent(context: Context, feedItems: List<FeedItemWithFeed>): PendingIntent { val intent = Intent(context, RssNotificationBroadcastReceiver::class.java) intent.action = ACTION_MARK_AS_NOTIFIED val ids = LongArray(feedItems.size) { i -> feedItems[i].id } intent.putExtra(EXTRA_FEEDITEM_ID_ARRAY, ids) return PendingIntent.getBroadcast( context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or FLAG_IMMUTABLE ) } internal fun getDeleteIntent(context: Context, feedItem: FeedItemWithFeed): Intent { val intent = Intent(context, RssNotificationBroadcastReceiver::class.java) intent.action = ACTION_MARK_AS_NOTIFIED intent.data = Uri.withAppendedPath(URI_FEEDITEMS, "${feedItem.id}") val ids: LongArray = longArrayOf(feedItem.id) intent.putExtra(EXTRA_FEEDITEM_ID_ARRAY, ids) return intent } private fun getPendingDeleteIntent(context: Context, feedItem: FeedItemWithFeed): PendingIntent = PendingIntent.getBroadcast( context, 0, getDeleteIntent(context, feedItem), PendingIntent.FLAG_UPDATE_CURRENT or FLAG_IMMUTABLE ) private fun notificationBuilder(context: Context): NotificationCompat.Builder { val bm = BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher) return NotificationCompat.Builder(context, channelId) .setSmallIcon(R.drawable.ic_stat_f) .setLargeIcon(bm) .setAutoCancel(true) .setCategory(NotificationCompat.CATEGORY_SOCIAL) .setPriority(NotificationCompat.PRIORITY_LOW) } private suspend fun getItemsToNotify(di: DI): List<FeedItemWithFeed> { val feedDao: FeedDao by di.instance() val feedItemDao: FeedItemDao by di.instance() val feeds = feedDao.loadFeedIdsToNotify() return when (feeds.isEmpty()) { true -> emptyList() false -> feedItemDao.loadItemsToNotify(feeds) } } fun NavDeepLinkBuilder.createPendingIntent(requestCode: Int): PendingIntent? = this.createTaskStackBuilder().getPendingIntent(requestCode, PendingIntent.FLAG_UPDATE_CURRENT)
gpl-3.0
0a680c7a816d8ede9c204b2c33cf22d7
32.935673
114
0.697656
4.465564
false
false
false
false
allotria/intellij-community
plugins/gradle/tooling-proxy/src/org/jetbrains/plugins/gradle/tooling/proxy/TargetIncomingConnector.kt
2
5107
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.tooling.proxy import org.gradle.api.Action import org.gradle.internal.UncheckedException import org.gradle.internal.concurrent.CompositeStoppable import org.gradle.internal.concurrent.DefaultExecutorFactory import org.gradle.internal.id.UUIDGenerator import org.gradle.internal.remote.Address import org.gradle.internal.remote.ConnectionAcceptor import org.gradle.internal.remote.internal.ConnectCompletion import org.gradle.internal.remote.internal.IncomingConnector import org.gradle.internal.remote.internal.KryoBackedMessageSerializer import org.gradle.internal.remote.internal.RemoteConnection import org.gradle.internal.remote.internal.inet.InetAddressFactory import org.gradle.internal.remote.internal.inet.MultiChoiceAddress import org.gradle.internal.remote.internal.inet.SocketConnection import org.gradle.internal.serialize.StatefulSerializer import org.slf4j.LoggerFactory import java.net.InetAddress import java.net.InetSocketAddress import java.nio.channels.ClosedChannelException import java.nio.channels.ServerSocketChannel import java.nio.channels.SocketChannel class TargetIncomingConnector() : IncomingConnector { private val idGenerator = UUIDGenerator() private val addressFactory: InetAddressFactory = InetAddressFactory() private val executorFactory = DefaultExecutorFactory() override fun accept(action: Action<ConnectCompletion>, allowRemote: Boolean): ConnectionAcceptor { val serverSocket: ServerSocketChannel val bindingAddress = getBindingAddress() val localPort: Int try { val bindingPort = getBindingPort() serverSocket = ServerSocketChannel.open() serverSocket.socket().bind(InetSocketAddress(bindingAddress, bindingPort)) localPort = serverSocket.socket().localPort } catch (e: Exception) { throw UncheckedException.throwAsUncheckedException(e) } val id = idGenerator.generateId() val addresses = listOf(bindingAddress) val address: Address = MultiChoiceAddress(id, localPort, addresses) logger.debug("Listening on $address.") val executor = executorFactory.create("Incoming ${if (allowRemote) "remote" else "local"} TCP Connector on port $localPort") executor.execute(Receiver(serverSocket, action, allowRemote)) return object : ConnectionAcceptor { override fun getAddress() = address override fun requestStop() { CompositeStoppable.stoppable(serverSocket).stop() } override fun stop() { requestStop() executor.stop() } } } private fun getBindingPort() = System.getenv("serverBindingPort")?.toIntOrNull() ?: 0 private fun getBindingAddress(): InetAddress { val bindingHost = System.getenv("serverBindingHost") if (bindingHost.isNullOrBlank()) { return addressFactory.localBindingAddress } else { val inetAddresses = InetAddresses() val inetAddress = inetAddresses.remote.find { it.hostName == bindingHost || it.hostAddress == bindingHost } return inetAddress ?: addressFactory.localBindingAddress } } private inner class Receiver(private val serverSocket: ServerSocketChannel, private val action: Action<ConnectCompletion>, private val allowRemote: Boolean) : Runnable { override fun run() { try { while (true) { val socket = serverSocket.accept() val remoteSocketAddress = socket.socket().remoteSocketAddress as InetSocketAddress val remoteInetAddress = remoteSocketAddress.address if (!allowRemote && !addressFactory.isCommunicationAddress(remoteInetAddress)) { logger.error("Cannot accept connection from remote address $remoteInetAddress.") socket.close() } else { logger.debug("Accepted connection from {} to {}.", socket.socket().remoteSocketAddress, socket.socket().localSocketAddress) try { action.execute(SocketConnectCompletion(socket)) } catch (t: Throwable) { socket.close() throw t } } } } catch (ignore: ClosedChannelException) { } catch (t: Throwable) { logger.error("Could not accept remote connection.", t) } finally { CompositeStoppable.stoppable(serverSocket).stop() } } } internal class SocketConnectCompletion(private val socket: SocketChannel) : ConnectCompletion { override fun toString(): String { return socket.socket().localSocketAddress.toString() + " to " + socket.socket().remoteSocketAddress } override fun <T> create(serializer: StatefulSerializer<T>): RemoteConnection<T> { return SocketConnection(socket, KryoBackedMessageSerializer(), serializer) } } companion object { private val logger = LoggerFactory.getLogger(TargetIncomingConnector::class.java) } }
apache-2.0
2f93b074c7e8500a3edbc73918166197
39.220472
140
0.718621
4.887081
false
false
false
false
Homes-MinecraftServerMod/Homes
src/main/kotlin/com/masahirosaito/spigot/homes/datas/strings/ErrorStringData.kt
1
1784
package com.masahirosaito.spigot.homes.datas.strings data class ErrorStringData( val NO_COMMAND: String = "&cCommand <[command-name]> does not exist&r", val NO_CONSOLE_COMMAND: String = "&cConsole command is not find&r", val NO_PERMISSION: String = "&cYou don't have permission <[permission-name]>&r", val NO_ONLINE_PLAYER: String = "&cPlayer <[player-name]> does not exist&r", val NO_OFFLINE_PLAYER: String = "&cPlayer <[player-name]> does not exist&r", val NO_VAULT: String = "&cFee function stopped because Vault can not be found.&r", val NO_ECONOMY: String = "&cFee function stopped because the Economy plugin can not be found.&r", val NO_DEFAULT_HOME: String = "&c[player-name]'s default home does not exist&r", val NO_NAMED_HOME: String = "&c[player-name]'s home named <[home-name]> does not exist&r", val NO_HOME: String = "&c[player-name]'s home is empty&r", val HOME_LIMIT: String = "&cYou can not set more homes (Limit: &r[home-limit-num]&c)&r", val DEFAULT_HOME_IS_PRIVATE: String = "&c[player-name]'s default home is PRIVATE&r", val NAMED_HOME_IS_PRIVATE: String = "&c[player-name]'s home named <[home-name]>} is PRIVATE&r", val NO_RECEIVED_INVITATION: String = "&cYou have not received an invitation&r", val ALREADY_HAS_INVITATION: String = "&c[player-name] already has another invitation&r", val NOT_ALLOW_BY_CONFIG: String = "&cNot allowed by the configuration of this server&r", val ARGUMENT_INCORRECT: String = "&cThe argument is incorrect\n[command-usage]&r", val INVALID_COMMAND_SENDER: String = "&cCommandSender is invalid&r", val ALREADY_EXECUTE_TELEPORT: String = "&cYou are already executing a teleport&r" )
apache-2.0
1208034ff456851419cdc5c8b593c998
76.565217
105
0.668722
3.611336
false
true
false
false
allotria/intellij-community
platform/platform-impl/src/com/intellij/openapi/keymap/impl/DefaultKeymapImpl.kt
3
1708
// 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.keymap.impl import com.intellij.configurationStore.SchemeDataHolder import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.actionSystem.MouseShortcut import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.keymap.Keymap import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.options.SchemeState import com.intellij.openapi.util.SystemInfo import org.jdom.Element import java.awt.event.MouseEvent open class DefaultKeymapImpl(dataHolder: SchemeDataHolder<KeymapImpl>, private val defaultKeymapManager: DefaultKeymap, val plugin: PluginDescriptor) : KeymapImpl(dataHolder) { final override var canModify: Boolean get() = false set(value) { // ignore } override fun getSchemeState(): SchemeState = SchemeState.NON_PERSISTENT override fun getPresentableName(): String = DefaultKeymap.instance.getKeymapPresentableName(this) override fun readExternal(keymapElement: Element) { super.readExternal(keymapElement) if (KeymapManager.DEFAULT_IDEA_KEYMAP == name && !SystemInfo.isXWindow) { addShortcut(IdeActions.ACTION_GOTO_DECLARATION, MouseShortcut(MouseEvent.BUTTON2, 0, 1)) } } // default keymap can have parent only in the defaultKeymapManager // also, it allows us to avoid dependency on KeymapManager (maybe not initialized yet) override fun findParentScheme(parentSchemeName: String): Keymap? = defaultKeymapManager.findScheme(parentSchemeName) }
apache-2.0
4e91d3a4a480bf75b97ef5df531f1d4a
42.794872
140
0.772834
4.936416
false
false
false
false
allotria/intellij-community
uast/uast-tests/src/org/jetbrains/uast/test/common/NestedMaps.kt
3
12488
// 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.uast.test.common import java.nio.CharBuffer import kotlin.math.max /* ------------------------------------------------------------------------------------------- */ //region Map2, Map3 definitions typealias Map2<K1, K2, V> = Map<K1, Map<K2, V>> typealias Map3<K1, K2, K3, V> = Map2<K1, K2, Map<K3, V>> typealias MutableMap2<K1, K2, V> = MutableMap<K1, MutableMap<K2, V>> typealias MutableMap3<K1, K2, K3, V> = MutableMap2<K1, K2, MutableMap<K3, V>> //endregion /* ------------------------------------------------------------------------------------------- */ /* ------------------------------------------------------------------------------------------- */ //region MapK extensions internal inline fun <K, V, R> buildLinkedHashMapOf(pairs: Iterable<Pair<K, V>>, transformValue: (V) -> R) = LinkedHashMap<K, R>().apply { for (pair in pairs) put(pair.first, transformValue(pair.second)) } fun <K1, K2, V> mutableMap2Of(pairs: Iterable<Pair<K1, Map<K2, V>>>): MutableMap2<K1, K2, V> = buildLinkedHashMapOf(pairs) { it.toMutableMap() } fun <K1, K2, V> mutableMap2Of(vararg pairs: Pair<K1, Map<K2, V>>): MutableMap2<K1, K2, V> = buildLinkedHashMapOf(pairs.asIterable()) { it.toMutableMap() } fun <K1, K2, V> Map2<K1, K2, V>.toMutableMap2(): MutableMap2<K1, K2, V> = buildLinkedHashMapOf(toList()) { it.toMutableMap() } fun <K1, K2, K3, V> mutableMap3Of(pairs: Iterable<Pair<K1, Map2<K2, K3, V>>>): MutableMap3<K1, K2, K3, V> = buildLinkedHashMapOf(pairs) { it.toMutableMap2() } fun <K1, K2, K3, V> mutableMap3Of(vararg pairs: Pair<K1, Map2<K2, K3, V>>): MutableMap3<K1, K2, K3, V> = buildLinkedHashMapOf(pairs.asIterable()) { it.toMutableMap2() } fun <K1, K2, K3, V> Map3<K1, K2, K3, V>.toMutableMap3(): MutableMap3<K1, K2, K3, V> = buildLinkedHashMapOf(toList()) { it.toMutableMap2() } fun <KE, K : Iterable<KE>, V> Map<K, V>.foldKeysByLevel( level: Int, keyBuilder: (List<KE>) -> K, keyFolder: (List<KE>) -> Iterable<KE>? ): Map<K, V> { val result = mutableMapOf<K, V>() val folded = mutableMapOf<K, V>() for ((key, value) in entries) { val unfoldedPart = key.take(level) when (val foldedPart = keyFolder(unfoldedPart)) { null -> result[key] = value // do nothing, copy as is else -> folded.merge(keyBuilder(unfoldedPart + foldedPart), value) { old, new -> if (old == new) value else error("Loss of values for key: $key") } } } for (it in folded) { result.merge(it.key, it.value) { _, _ -> error("Folded context should be different from unfolded one: both are ${it.key}") } } return result } inline fun <K, V, KR, T, VR> Map<K, V>.transform( crossinline transformKey: (K) -> KR, crossinline transformValue: (V) -> T, crossinline mergeValues: (VR?, T) -> VR? ): MutableMap<KR, VR> = mutableMapOf<KR, VR>().also { result -> for ((key, value) in entries) { result.compute(transformKey(key)) { _, old -> mergeValues(old, transformValue(value)) } } } inline fun <K1, K2, V, T, K1R, K2R, VR : T> Map2<K1, K2, V>.transformMap2( crossinline transformKey1: (K1) -> K1R, crossinline transformKey2: (K2) -> K2R, crossinline transformValue: (V) -> T, crossinline mergeValues: (VR?, T) -> VR? ): MutableMap2<K1R, K2R, VR> = transform( transformKey1, { it.transform(transformKey2, transformValue, mergeValues) }, { prev: MutableMap<K2R, VR>?, new: MutableMap<K2R, VR> -> (prev ?: mutableMapOf()).apply { mergeMap(new) { a, (_, b) -> mergeValues(a, b) } } } ) inline fun <K1, K2, K3, V, T, K1R, K2R, K3R, VR : T> Map3<K1, K2, K3, V>.transformMap3( crossinline transformKey1: (K1) -> K1R, crossinline transformKey2: (K2) -> K2R, crossinline transformKey3: (K3) -> K3R, crossinline transformValue: (V) -> T, crossinline mergeValues: (VR?, T) -> VR? ): MutableMap3<K1R, K2R, K3R, VR> = transform( transformKey1, { it.transformMap2(transformKey2, transformKey3, transformValue, mergeValues) }, { prev: MutableMap2<K2R, K3R, VR>?, new: MutableMap2<K2R, K3R, VR> -> (prev ?: mutableMapOf()).apply { mergeMap2(new) { a, (_, b) -> mergeValues(a, b) } } } ) inline fun <K1, K2, V> Map2<K1, K2, V>.filterInner( predicate: (K1, K2, V) -> Boolean ): Map2<K1, K2, V> = mapValues { (key1, innerMap) -> innerMap.filter { (key2, value) -> predicate(key1, key2, value) } } inline fun <K, V, VThat> MutableMap<K, V>.mergeMap( that: Map<K, VThat>, crossinline mergeValues: (V?, Map.Entry<K, VThat>) -> V? ) { for (entry in that.entries) { // see KT-41174 //compute(entry.key) { _, prev -> mergeValues(prev, entry) } when (val t = mergeValues(get(entry.key), entry)) { null -> remove(entry.key) else -> put(entry.key, t) } } } inline fun <K1, K2, V, VThat> MutableMap2<K1, K2, V>.mergeMap2( that: Map2<K1, K2, VThat>, crossinline mergeValues: (V?, Map.Entry<K2, VThat>) -> V? ) { mergeMap(that) { prev, (_, innerMap) -> (prev ?: mutableMapOf()).apply { mergeMap(innerMap, mergeValues) } } } inline fun <K1, K2, K3, V, VThat> MutableMap3<K1, K2, K3, V>.mergeMap3( that: Map3<K1, K2, K3, VThat>, crossinline mergeValues: (V?, Map.Entry<K3, VThat>) -> V? ) { mergeMap(that) { prev, (_, innerMap) -> (prev ?: mutableMapOf()).apply { mergeMap2(innerMap, mergeValues) } } } //endregion /* ------------------------------------------------------------------------------------------- */ /* ------------------------------------------------------------------------------------------- */ //region Map pretty printing inline fun <A : Appendable, K, V> A.printMapAsAlignedLists( map: Map<K, V>, keyComparator: Comparator<K>, prefix: String = "[", separator: String = ", ", postfix: String = "]", alignByRight: Boolean = false, keyToList: (K) -> List<String>, valuePrinter: A.(K, V) -> Unit = { _, value -> append(value.toString()) } ): A { val stringifiedKeys = map.mapValues { keyToList(it.key) } val maxContextLength = stringifiedKeys.values.maxBy { it.size }?.size ?: 10 val contextElementWidths = stringifiedKeys.values .fold(MutableList(maxContextLength) { 1 }) { acc, stringifiedContext -> stringifiedContext.forEachIndexed { i, s -> val index = if (alignByRight) maxContextLength - stringifiedContext.size + i else i acc[index] = max(acc[index], s.length) } acc } return printMap(map, keyComparator = keyComparator) { key, value -> val sContext = stringifiedKeys.getValue(key) contextElementWidths .mapIndexed { i, width -> "%-${width}s".format( sContext.getOrNull(if (alignByRight) i + sContext.size - maxContextLength else i) ?: "") } .joinTo(this, prefix = prefix, separator = separator, postfix = postfix) valuePrinter(key, value) } } fun <A : Appendable, K, V> A.printMapAsAlignedTrees( map: Map<K, V>, margin: CharSequence, leafKey: String = ".", keyToList: (K) -> List<String>, keyPrinter: A.(String, Int) -> Unit = { key, _ -> append(key.toString()) }, valuePrinter: A.(K, V) -> Unit = { _, value -> append(value.toString()) } ): A { val stringifiedKeys = map.mapValues { keyToList(it.key) } val tree = map.toList() .map { (key, value) -> Pair(stringifiedKeys.getValue(key), Pair(key, value)) } .toMap() .uncurry(leafKey) // for pretty alignment val valuePadding = max(1, stringifiedKeys.values.asSequence().map { it.lastOrNull()?.length ?: 0 }.max()!!) val treeDepth = stringifiedKeys.values.asSequence().map { it.size }.max()!! prettyPrintTree( tree, margin, keyComparator = Comparator.naturalOrder(), keyPrinter = { key, t -> val children = (t as Node).children when (val child = children.getValue(key)) { is Node -> keyPrinter(key, 1) is Leaf -> { val missedMarginCompensation = margin.length * (treeDepth - (stringifiedKeys[child.value.first]?.size ?: 0)) keyPrinter(key, missedMarginCompensation + valuePadding) } } }, valPrinter = { (context, targets), _ -> valuePrinter(context, targets) }) return this } inline fun <A : Appendable, K, V> A.printMap( map: Map<K, V>, separator: CharSequence = "\n", keyComparator: Comparator<K> = Comparator { _, _ -> 0 }, keyValuePrinter: A.(K, V) -> Unit = { key, value -> append(key.toString()); append(value.toString()) } ): A { map .toList() .sortedWith(Comparator { o1, o2 -> keyComparator.compare(o1.first, o2.first) }) .forEachIndexed { index, (key, value) -> if (index > 0) append(separator) keyValuePrinter(key, value) } return this } private fun <A : Appendable, K, V> A.prettyPrintTree( tree: Tree<K, V>, margin: CharSequence, keyComparator: Comparator<K> = Comparator { _, _ -> 0 }, keyPrinter: Appendable.(K, Tree<K, V>) -> Unit = { key, _ -> append(key.toString()) }, valPrinter: Appendable.(V, Tree<K, V>) -> Unit = { value, _ -> append(value.toString()) } ): Unit { when (tree) { is Node -> printMap(tree.children, keyComparator = keyComparator) t@{ key, value -> keyPrinter(key, tree) when (value) { is Node -> [email protected](margin) m@{ [email protected](value, margin, keyComparator, keyPrinter, valPrinter) } is Leaf -> valPrinter(value.value, tree) } } is Leaf -> valPrinter(tree.value, tree) } } private sealed class Tree<out K, out V> private data class Node<K, V>(val children: Map<K, Tree<K, V>>) : Tree<K, V>() private data class Leaf<V>(val value: V) : Tree<Nothing, V>() /** * Generalized uncurrying: * * Map<(k, k, ..., k), v> <=> (k, k, ..., k) -> v <=> k -> (k -> ... (k -> v)) => Tree<k, v> */ private fun <K, V> Map<List<K>, V>.uncurry(leafKey: K): Tree<K, V> = this.entries .partition { it.key.isEmpty() } .let { (leafCandidate, childrenCandidates) -> val leaf = leafCandidate.singleOrNull()?.value?.let { Leaf(it) } when { childrenCandidates.isEmpty() -> leaf ?: error("Empty or invalid map") else -> { childrenCandidates .groupingBy { it.key.first() } .fold({ _, _ -> mutableMapOf<List<K>, V>() }) { _, innerMap, entry -> innerMap[entry.key.drop(1)] = entry.value innerMap } .mapValuesTo(mutableMapOf()) { it.value.uncurry(leafKey) } .let { children -> when { leafCandidate.isEmpty() -> Node(children) else -> children.put(leafKey, leaf ?: error("Empty or invalid map")) ?.let { error("leaf key must be unique") } ?: Node(children) } } } } } //endregion /* ------------------------------------------------------------------------------------------- */ /* ------------------------------------------------------------------------------------------- */ //region Utils internal fun <A : Appendable> A.appendReplacing(target: CharSequence, old: String, new: String): A { var begin = 0 var end = target.indexOf(old) while (end != -1) { append(target, begin, end) append(new) begin = end + old.length end = target.indexOf(old, begin) } append(target, begin, target.length) return this } internal fun <A : Appendable> A.withMargin(margin: CharSequence, withTrailingNewLine: Boolean = true, targetInit: Appendable.() -> Unit): A { object : Appendable { val newLineMargin = "\n" + margin override fun append(csq: CharSequence?): java.lang.Appendable { [email protected]<A>(csq ?: "null", "\n", newLineMargin) return this } override fun append(csq: CharSequence?, start: Int, end: Int): java.lang.Appendable { return append(csq?.let { CharBuffer.wrap(it).subSequence(start, end) }) } override fun append(c: Char): java.lang.Appendable { [email protected](c) return this } } .apply { if (withTrailingNewLine) appendln() }.targetInit() return this } //endregion /* ------------------------------------------------------------------------------------------- */
apache-2.0
750ebc649af8c09f936a10119a489a32
33.788301
140
0.572229
3.490218
false
false
false
false
F43nd1r/acra-backend
acrarium/src/main/kotlin/com/faendir/acra/model/Version.kt
1
1881
/* * (C) Copyright 2018 Lukas Morawietz (https://github.com/F43nd1r) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.faendir.acra.model import com.faendir.acra.util.equalsBy import org.hibernate.annotations.OnDelete import org.hibernate.annotations.OnDeleteAction import org.hibernate.annotations.Type import java.util.* import javax.persistence.Basic import javax.persistence.CascadeType import javax.persistence.Entity import javax.persistence.FetchType import javax.persistence.GeneratedValue import javax.persistence.GenerationType import javax.persistence.Id import javax.persistence.ManyToOne /** * @author lukas * @since 26.07.18 */ @Entity class Version(@OnDelete(action = OnDeleteAction.CASCADE) @ManyToOne(cascade = [CascadeType.MERGE, CascadeType.REFRESH], optional = false, fetch = FetchType.LAZY) val app: App, val code: Int, var name: String, @Basic(fetch = FetchType.LAZY) @Type(type = "text") var mappings: String? = null) : Comparable<Version> { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private val id = 0 override fun compareTo(other: Version): Int = code.compareTo(other.code) override fun equals(other: Any?) = equalsBy(other, Version::id) override fun hashCode(): Int = Objects.hash(id) }
apache-2.0
1d21d439e0accb444a4f1771f8e5b98a
33.851852
118
0.720362
4.152318
false
false
false
false
zdary/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/columns/ActionsColumn.kt
1
5611
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns import com.intellij.util.ui.ColumnInfo import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.RepositoryModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageOperationType import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperation import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperationFactory import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.PackagesTableItem import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.renderers.PackageActionsTableCellRendererAndEditor import javax.swing.JTable import javax.swing.table.TableCellEditor import javax.swing.table.TableCellRenderer internal class ActionsColumn( private val operationExecutor: (List<PackageSearchOperation<*>>) -> Unit, private val operationFactory: PackageSearchOperationFactory, table: JTable ) : ColumnInfo<PackagesTableItem<*>, Any>(PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.columns.actions")) { var hoverItem: PackagesTableItem<*>? = null private var targetModules: TargetModules = TargetModules.None private var installedKnownRepositories: List<RepositoryModel> = emptyList() private var onlyStable = false private val cellRendererAndEditor = PackageActionsTableCellRendererAndEditor(table) { operationExecutor(it.operations) } override fun getRenderer(item: PackagesTableItem<*>): TableCellRenderer = cellRendererAndEditor override fun getEditor(item: PackagesTableItem<*>): TableCellEditor = cellRendererAndEditor override fun isCellEditable(item: PackagesTableItem<*>) = getOperationTypeFor(item) != null fun updateData(onlyStable: Boolean, targetModules: TargetModules, installedKnownRepositories: List<RepositoryModel>) { this.onlyStable = onlyStable this.targetModules = targetModules this.installedKnownRepositories = installedKnownRepositories } override fun valueOf(item: PackagesTableItem<*>): ActionsViewModel { val operationType = getOperationTypeFor(item) return ActionsViewModel( item.packageModel, createOperationsFor(item, operationType), operationType, generateMessageFor(item), isSearchResult = item is PackagesTableItem.InstallablePackage, isHover = item == hoverItem ) } private fun getOperationTypeFor(item: PackagesTableItem<*>): PackageOperationType? = when (item) { is PackagesTableItem.InstalledPackage -> { val packageModel = item.packageModel val targetVersion = item.selectedPackageModel.selectedVersion if (packageModel.canBeUpgraded(targetVersion, onlyStable)) { PackageOperationType.UPGRADE } else { null } } is PackagesTableItem.InstallablePackage -> PackageOperationType.INSTALL } private fun createOperationsFor(item: PackagesTableItem<*>, operationType: PackageOperationType?): List<PackageSearchOperation<*>> { val targetVersion = item.packageModel.getLatestAvailableVersion(onlyStable) ?: return emptyList() val repoToInstall = item.packageModel.repositoryToAddWhenInstallingOrUpgrading( knownRepositoryModels = installedKnownRepositories, targetModules = targetModules, selectedVersion = targetVersion ) return when (operationType) { PackageOperationType.UPGRADE -> { val packageModel = item.packageModel as PackageModel.Installed operationFactory.createChangePackageVersionOperations(packageModel, targetVersion, targetModules, repoToInstall) } PackageOperationType.INSTALL -> { val packageModel = item.packageModel as PackageModel.SearchResult val selectedScope = item.selectedPackageModel.selectedScope operationFactory.createAddPackageOperations(packageModel, targetVersion, selectedScope, targetModules, repoToInstall) } null -> emptyList() else -> throw IllegalArgumentException("The actions column can only handle INSTALL and UPGRADE operations.") } } private fun generateMessageFor(item: PackagesTableItem<*>): String? { val packageModel = item.packageModel val selectedVersion = item.selectedPackageModel.selectedVersion val repoToInstall = packageModel.repositoryToAddWhenInstallingOrUpgrading(installedKnownRepositories, targetModules, selectedVersion) ?: return null return PackageSearchBundle.message( "packagesearch.repository.willBeAddedOnInstall", repoToInstall.displayName ) } data class ActionsViewModel( val packageModel: PackageModel, val operations: List<PackageSearchOperation<*>>, val operationType: PackageOperationType?, val infoMessage: String?, val isSearchResult: Boolean, val isHover: Boolean ) }
apache-2.0
7357a832946be871878fe00e18f7789b
46.550847
150
0.733203
5.956476
false
false
false
false
leafclick/intellij-community
platform/indexing-impl/src/com/intellij/psi/stubs/PrebuiltStubs.kt
1
5091
// 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.psi.stubs import com.google.common.hash.HashCode import com.google.common.hash.Hashing import com.intellij.index.PrebuiltIndexProvider import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.fileTypes.FileTypeExtension import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.text.StringUtilRt import com.intellij.util.indexing.FileContent import com.intellij.util.io.DataExternalizer import com.intellij.util.io.DataInputOutputUtil import com.intellij.util.io.KeyDescriptor import com.intellij.util.io.PersistentHashMap import org.jetbrains.annotations.TestOnly import java.io.DataInput import java.io.DataOutput import java.io.File import java.io.IOException import java.nio.file.Files const val EP_NAME = "com.intellij.filetype.prebuiltStubsProvider" val prebuiltStubsProvider = FileTypeExtension<PrebuiltStubsProvider>(EP_NAME) interface PrebuiltStubsProvider { fun findStub(fileContent: FileContent): SerializedStubTree? } class FileContentHashing { private val hashing = Hashing.sha256() fun hashString(fileContent: FileContent): HashCode = hashing.hashBytes(fileContent.content)!! } class HashCodeDescriptor : HashCodeExternalizers(), KeyDescriptor<HashCode> { override fun getHashCode(value: HashCode): Int = value.hashCode() override fun isEqual(val1: HashCode, val2: HashCode): Boolean = val1 == val2 companion object { val instance: HashCodeDescriptor = HashCodeDescriptor() } } open class HashCodeExternalizers : DataExternalizer<HashCode> { override fun save(out: DataOutput, value: HashCode) { val bytes = value.asBytes() DataInputOutputUtil.writeINT(out, bytes.size) out.write(bytes, 0, bytes.size) } override fun read(`in`: DataInput): HashCode { val len = DataInputOutputUtil.readINT(`in`) val bytes = ByteArray(len) `in`.readFully(bytes) return HashCode.fromBytes(bytes) } } private val IDE_SERIALIZATION_MANAGER = SerializationManagerEx.getInstanceEx() class FullStubExternalizer : SerializedStubTreeDataExternalizer(true, IDE_SERIALIZATION_MANAGER, StubForwardIndexExternalizer.createFileLocalExternalizer(IDE_SERIALIZATION_MANAGER)) abstract class PrebuiltStubsProviderBase : PrebuiltIndexProvider<SerializedStubTree>(), PrebuiltStubsProvider { private var mySerializationManager: SerializationManagerImpl? = null protected abstract val stubVersion: Int override val indexName: String get() = SDK_STUBS_STORAGE_NAME override val indexExternalizer: FullStubExternalizer get() = FullStubExternalizer() companion object { const val PREBUILT_INDICES_PATH_PROPERTY = "prebuilt_indices_path" const val SDK_STUBS_STORAGE_NAME = "sdk-stubs" private val LOG = logger<PrebuiltStubsProviderBase>() } protected open fun getIndexVersion(): Int = -1 override fun openIndexStorage(indexesRoot: File): PersistentHashMap<HashCode, SerializedStubTree>? { val formatFile = indexesRoot.toPath().resolve("$indexName.version") val versionFileText = Files.readAllLines(formatFile) if (versionFileText.size != 2) { LOG.warn("Invalid version file format: \"$versionFileText\" (file=$formatFile)") return null } val stubSerializationVersion = versionFileText[0] val currentSerializationVersion = StringUtilRt.parseInt(stubSerializationVersion, 0) val expected = getIndexVersion() if (expected != -1 && currentSerializationVersion != expected) { LOG.error("Stub serialization version mismatch: $expected, current version is $currentSerializationVersion") return null } val prebuiltIndexVersion = versionFileText[1] if (StringUtilRt.parseInt(prebuiltIndexVersion, 0) != stubVersion) { LOG.error("Prebuilt stubs version mismatch: $prebuiltIndexVersion, current version is $stubVersion") return null } else { mySerializationManager = SerializationManagerImpl(File(indexesRoot, "$indexName.names").toPath(), true) Disposer.register(ApplicationManager.getApplication(), mySerializationManager!!) return super.openIndexStorage(indexesRoot) } } override fun findStub(fileContent: FileContent): SerializedStubTree? { try { val stubTree = get(fileContent) if (stubTree != null) { val newSerializationManager = IDE_SERIALIZATION_MANAGER val newForwardIndexSerializer = StubForwardIndexExternalizer.getIdeUsedExternalizer(newSerializationManager) val indexedStubsSerializer = StubForwardIndexExternalizer.createFileLocalExternalizer(mySerializationManager!!) return stubTree.reSerialize(mySerializationManager!!, newSerializationManager, indexedStubsSerializer, newForwardIndexSerializer) } } catch (e: IOException) { LOG.error("Can't re-serialize stub tree", e) } return null } } @TestOnly fun PrebuiltStubsProviderBase.reset(): Boolean = this.init()
apache-2.0
a69cb1acbb4b066f1d60d275d2fdaf3c
37.862595
181
0.773915
4.628182
false
false
false
false
leafclick/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowInfoImpl.kt
1
5003
// 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.wm.impl import com.intellij.openapi.components.BaseState import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.wm.* import com.intellij.util.xmlb.Converter import com.intellij.util.xmlb.annotations.Attribute import com.intellij.util.xmlb.annotations.Property import com.intellij.util.xmlb.annotations.Tag import com.intellij.util.xmlb.annotations.Transient import java.awt.Rectangle import kotlin.math.max import kotlin.math.min private val LOG = logger<WindowInfoImpl>() @Suppress("EqualsOrHashCode") @Tag("window_info") @Property(style = Property.Style.ATTRIBUTE) class WindowInfoImpl : Cloneable, WindowInfo, BaseState() { companion object { internal const val TAG = "window_info" const val DEFAULT_WEIGHT = 0.33f } @get:Attribute("active") override var isActiveOnStart by property(false) @get:Attribute(converter = ToolWindowAnchorConverter::class) override var anchor by property(ToolWindowAnchor.LEFT) { it == ToolWindowAnchor.LEFT } @get:Attribute("auto_hide") override var isAutoHide by property(false) /** * Bounds of window in "floating" mode. It equals to `null` if floating bounds are undefined. */ @get:Property(flat = true, style = Property.Style.ATTRIBUTE) override var floatingBounds by property<Rectangle?>(null) { it == null || (it.width == 0 && it.height == 0 && it.x == 0 && it.y == 0) } /** * This attribute persists state 'maximized' for ToolWindowType.WINDOWED where decoration is presented by JFrame */ @get:Attribute("maximized") override var isMaximized by property(false) /** * ID of the tool window */ override var id by string() /** * @return type of the tool window in internal (docked or sliding) mode. Actually the tool * window can be in floating mode, but this method has sense if you want to know what type * tool window had when it was internal one. */ @get:Attribute("internal_type") override var internalType by enum(ToolWindowType.DOCKED) override var type by enum(ToolWindowType.DOCKED) @get:Attribute("visible") override var isVisible by property(false) @get:Attribute("show_stripe_button") override var isShowStripeButton by property(true) /** * Internal weight of tool window. "weight" means how much of internal desktop * area the tool window is occupied. The weight has sense if the tool window is docked or * sliding. */ override var weight by property(DEFAULT_WEIGHT) { max(0f, min(1f, it)) } override var sideWeight by property(0.5f) { max(0f, min(1f, it)) } @get:Attribute("side_tool") override var isSplit by property(false) @get:Attribute("content_ui", converter = ContentUiTypeConverter::class) override var contentUiType: ToolWindowContentUiType by property(ToolWindowContentUiType.TABBED) { it == ToolWindowContentUiType.TABBED } /** * Defines order of tool window button inside the stripe. */ override var order by property(-1) @get:Transient override var isFromPersistentSettings = true internal set fun copy(): WindowInfoImpl { val info = WindowInfoImpl() info.copyFrom(this) info.isFromPersistentSettings = isFromPersistentSettings return info } override val isDocked: Boolean get() = type == ToolWindowType.DOCKED fun normalizeAfterRead() { setTypeAndCheck(type) if (isVisible && id != null && !canActivateOnStart(id!!)) { isVisible = false } } internal fun setType(type: ToolWindowType) { if (ToolWindowType.DOCKED == type || ToolWindowType.SLIDING == type) { internalType = type } setTypeAndCheck(type) } // hardcoded to avoid single-usage-API private fun setTypeAndCheck(value: ToolWindowType) { type = if (ToolWindowId.PREVIEW === id && value == ToolWindowType.DOCKED) ToolWindowType.SLIDING else value } override fun hashCode(): Int { return anchor.hashCode() + id!!.hashCode() + type.hashCode() + order } override fun toString() = "id: $id, ${super.toString()}" } private class ContentUiTypeConverter : Converter<ToolWindowContentUiType>() { override fun fromString(value: String): ToolWindowContentUiType = ToolWindowContentUiType.getInstance(value) override fun toString(value: ToolWindowContentUiType): String = value.name } private class ToolWindowAnchorConverter : Converter<ToolWindowAnchor>() { override fun fromString(value: String): ToolWindowAnchor { try { return ToolWindowAnchor.fromText(value) } catch (e: IllegalArgumentException) { LOG.warn(e) return ToolWindowAnchor.LEFT } } override fun toString(value: ToolWindowAnchor) = value.toString() } private fun canActivateOnStart(id: String): Boolean { for (ep in ToolWindowEP.EP_NAME.extensionList) { if (id == ep.id) { return !ep.isDoNotActivateOnStart } } return true }
apache-2.0
b6e02ed2d0b26829280d91e68acacaa6
31.076923
140
0.724565
4.221941
false
false
false
false
leafclick/intellij-community
platform/platform-impl/src/com/intellij/ide/actions/HideSideWindowsAction.kt
1
1418
// 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.ide.actions import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAware import com.intellij.openapi.wm.ex.ToolWindowManagerEx internal class HideSideWindowsAction : AnAction(), DumbAware { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val toolWindowManager = ToolWindowManagerEx.getInstanceEx(project) val id = toolWindowManager.activeToolWindowId ?: toolWindowManager.lastActiveToolWindowId ?: return if (HideToolWindowAction.shouldBeHiddenByShortCut(toolWindowManager, id)) { toolWindowManager.hideToolWindow(id, true) } } override fun update(event: AnActionEvent) { val presentation = event.presentation val project = event.project if (project == null) { presentation.isEnabled = false return } val toolWindowManager = ToolWindowManagerEx.getInstanceEx(project) var id = toolWindowManager.activeToolWindowId if (id != null) { presentation.isEnabled = true return } id = toolWindowManager.lastActiveToolWindowId presentation.isEnabled = id != null && HideToolWindowAction.shouldBeHiddenByShortCut(toolWindowManager, id) } }
apache-2.0
93b5895382bce9108b1a25d27a7c406b
37.351351
140
0.761636
4.906574
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/jvmField/visibility.kt
2
2272
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT // FULL_JDK import java.lang.reflect.Field import kotlin.reflect.jvm.javaField import kotlin.reflect.KProperty import kotlin.test.assertNotEquals import java.lang.reflect.Modifier @JvmField public val publicField = "OK"; @JvmField internal val internalField = "OK"; fun testVisibilities() { checkVisibility(::publicField.javaField!!, Modifier.PUBLIC) checkVisibility(::internalField.javaField!!, Modifier.PUBLIC) } class A { @JvmField public val publicField = "OK"; @JvmField internal val internalField = "OK"; @JvmField protected val protectedfield = "OK"; fun testVisibilities() { checkVisibility(A::publicField.javaField!!, Modifier.PUBLIC) checkVisibility(A::internalField.javaField!!, Modifier.PUBLIC) checkVisibility(A::protectedfield.javaField!!, Modifier.PROTECTED) } } class AWithCompanion { companion object { @JvmField public val publicField = "OK"; @JvmField internal val internalField = "OK"; @JvmField protected val protectedfield = "OK"; operator fun get(name: String) = AWithCompanion.Companion::class.members.single { it.name == name } as KProperty<*> fun testVisibilities() { checkVisibility(this["publicField"].javaField!!, Modifier.PUBLIC) checkVisibility(this["internalField"].javaField!!, Modifier.PUBLIC) checkVisibility(this["protectedfield"].javaField!!, Modifier.PROTECTED) } } } object Object { @JvmField public val publicField = "OK"; @JvmField internal val internalField = "OK"; operator fun get(name: String) = Object::class.members.single { it.name == name } as KProperty<*> fun testVisibilities() { checkVisibility(this["publicField"].javaField!!, Modifier.PUBLIC) checkVisibility(this["internalField"].javaField!!, Modifier.PUBLIC) } } fun box(): String { A().testVisibilities() AWithCompanion.testVisibilities() Object.testVisibilities() return "OK" } public fun checkVisibility(field: Field, visibility: Int) { assertNotEquals(field.modifiers and visibility, 0, "Field ${field} has wrong visibility") }
apache-2.0
c455fc900a2ef980c1b63764995d356c
31
123
0.700264
4.311195
false
true
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/stdlib/OrderingTest/combineComparators.kt
2
905
import kotlin.test.* import kotlin.comparisons.* data class Item(val name: String, val rating: Int) : Comparable<Item> { public override fun compareTo(other: Item): Int { return compareValuesBy(this, other, { it.rating }, { it.name }) } } val v1 = Item("wine", 9) val v2 = Item("beer", 10) val v3 = Item("apple", 20) fun box() { val byName = compareBy<Item> { it.name } val byRating = compareBy<Item> { it.rating } val v3 = Item(v1.name, v1.rating + 1) val v4 = Item(v2.name + "_", v2.rating) assertTrue((byName then byRating).compare(v1, v2) > 0) assertTrue((byName then byRating).compare(v1, v3) < 0) assertTrue((byName thenDescending byRating).compare(v1, v3) > 0) assertTrue((byRating then byName).compare(v1, v2) < 0) assertTrue((byRating then byName).compare(v4, v2) > 0) assertTrue((byRating thenDescending byName).compare(v4, v2) < 0) }
apache-2.0
e35173654f6ab95892963ac97feb97f3
33.807692
71
0.653039
3.12069
false
false
false
false
psenchanka/comant
comant-site/src/main/kotlin/com/psenchanka/comant/model/User.kt
1
1003
package com.psenchanka.comant.model import org.mindrot.jbcrypt.BCrypt import javax.persistence.* @Entity @Table(name = "code.users") class User { enum class Role { STUDENT, TEACHER, ADMIN } enum class Gender { MALE, FEMALE } @Id lateinit var username: String lateinit var password: String lateinit var firstname: String lateinit var lastname: String @Enumerated(EnumType.STRING) @Column(nullable = false) lateinit var role: Role @Enumerated(EnumType.STRING) @Column(nullable = false) lateinit var gender: Gender @ManyToMany(mappedBy = "instructors") lateinit var coursesInstructed: List<Course> @ManyToMany(mappedBy = "listeners") lateinit var coursesListened: List<Course> fun passwordMatches(plaintext: String) = BCrypt.checkpw(plaintext, password) companion object { fun encryptPassword(password: String) = BCrypt.hashpw(password, BCrypt.gensalt()) } }
mit
82da0b4de3090d4a3778dd06f1f3ef6d
20.361702
89
0.673978
4.196653
false
false
false
false
GlobalTechnology/android-gto-support
gto-support-okta/src/test/kotlin/org/ccci/gto/android/common/okta/oidc/OktaUserProfileProviderTest.kt
2
9068
package org.ccci.gto.android.common.okta.oidc import androidx.test.ext.junit.runners.AndroidJUnit4 import com.okta.oidc.Tokens import com.okta.oidc.clients.sessions.SessionClient import com.okta.oidc.net.response.UserInfo import com.okta.oidc.storage.OktaRepository import com.okta.oidc.storage.OktaStorage import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest import org.ccci.gto.android.common.base.TimeConstants.HOUR_IN_MS import org.ccci.gto.android.common.okta.oidc.clients.sessions.oktaRepo import org.ccci.gto.android.common.okta.oidc.net.response.CLAIM_OKTA_USER_ID import org.ccci.gto.android.common.okta.oidc.net.response.PersistableUserInfo import org.ccci.gto.android.common.okta.oidc.net.response.oktaUserId import org.ccci.gto.android.common.okta.oidc.storage.ChangeAwareOktaStorage import org.ccci.gto.android.common.okta.oidc.storage.makeChangeAware import org.json.JSONObject import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.kotlin.any import org.mockito.kotlin.atLeastOnce import org.mockito.kotlin.clearInvocations import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.reset import org.mockito.kotlin.spy import org.mockito.kotlin.stub import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @RunWith(AndroidJUnit4::class) @OptIn(ExperimentalCoroutinesApi::class) internal class OktaUserProfileProviderTest : BaseOktaOidcTest() { private lateinit var sessionClient: SessionClient override val storage = mock<OktaStorage>().makeChangeAware() as ChangeAwareOktaStorage private lateinit var oktaRepo: OktaRepository private val testScope = TestScope() private lateinit var provider: OktaUserProfileProvider private lateinit var tokens: Tokens private lateinit var userInfo: PersistableUserInfo @Before fun setup() { tokens = mock { on { idToken } doReturn ID_TOKEN } userInfo = mock() sessionClient = spy(webAuthClient.sessionClient) { doReturn(tokens).whenever(it).tokens } oktaRepo = spy(sessionClient.oktaRepo) { doReturn(userInfo).whenever(it).get(PersistableUserInfo.Restore(OKTA_USER_ID)) } provider = OktaUserProfileProvider(sessionClient, oktaRepo, coroutineScope = testScope) } // region userInfoFlow() @Test fun verifyUserInfoFlow() = runTest(UnconfinedTestDispatcher()) { val results = mutableListOf<UserInfo?>() // initial user info val flow = provider.userInfoFlow().onEach { results += it }.launchIn(this) assertEquals(1, provider.activeFlows.get()) verify(oktaRepo).get(PersistableUserInfo.Restore(OKTA_USER_ID)) assertEquals(1, results.size) assertNull(results[0]) // update user info results.clear() userInfo.stub { on { userInfo } doReturn UserInfo(JSONObject(mapOf(CLAIM_OKTA_USER_ID to OKTA_USER_ID))) } storage.notifyChanged() verify(oktaRepo, times(2)).get(PersistableUserInfo.Restore(OKTA_USER_ID)) assertEquals(1, results.size) assertEquals(OKTA_USER_ID, results[0]!!.oktaUserId) // close the flow flow.cancel() assertEquals(0, provider.activeFlows.get()) } @Test fun verifyUserInfoFlowChangeUser() = runTest(UnconfinedTestDispatcher()) { tokens.stub { on { idToken } doReturn null } val results = mutableListOf<UserInfo?>() // initial user info val flow = provider.userInfoFlow().onEach { results += it }.launchIn(this) assertEquals(0, provider.activeFlows.get()) verify(oktaRepo, never()).get<PersistableUserInfo>(any()) assertEquals(1, results.size) assertNull(results[0]) // update user info for different oktaUserId results.clear() userInfo.stub { on { userInfo } doReturn UserInfo(JSONObject(mapOf(CLAIM_OKTA_USER_ID to OKTA_USER_ID))) } storage.notifyChanged() assertEquals(0, provider.activeFlows.get()) verify(oktaRepo, never()).get<PersistableUserInfo>(any()) assertEquals(0, results.size) // update user id tokens.stub { on { idToken } doReturn ID_TOKEN } storage.notifyChanged() assertEquals(1, provider.activeFlows.get()) verify(oktaRepo).get(PersistableUserInfo.Restore(OKTA_USER_ID)) assertEquals(1, results.size) assertEquals(OKTA_USER_ID, results[0]!!.oktaUserId) // close the flow flow.cancel() assertEquals(0, provider.activeFlows.get()) } @Test fun verifyUserInfoFlowNullOnLogout() = runTest(UnconfinedTestDispatcher()) { userInfo.stub { on { userInfo } doReturn UserInfo(JSONObject(mapOf(CLAIM_OKTA_USER_ID to OKTA_USER_ID))) } val results = mutableListOf<UserInfo?>() // initial user info val flow = launch { provider.userInfoFlow().collect { results += it } } assertEquals(1, provider.activeFlows.get()) verify(oktaRepo).get(PersistableUserInfo.Restore(OKTA_USER_ID)) assertEquals(1, results.size) assertEquals(OKTA_USER_ID, results[0]!!.oktaUserId) // user is logged out reset(oktaRepo) results.clear() tokens.stub { on { idToken } doReturn null } storage.notifyChanged() assertEquals(0, provider.activeFlows.get()) verify(oktaRepo, never()).get<PersistableUserInfo>(any()) assertEquals(1, results.size) assertNull(results[0]) // close the flow flow.cancel() assertEquals(0, provider.activeFlows.get()) } // endregion userInfoFlow() // region refreshActor @Test fun verifyRefreshActorWakesUpOnNewFlow() = testScope.runTest { provider.activeFlows.set(0) advanceUntilIdle() verify(oktaRepo, never()).get<PersistableUserInfo>(any()) verify(httpClient, never()).connect(any(), any()) provider.activeFlows.set(1) assertTrue(provider.refreshActor.trySend(Unit).isSuccess) runCurrent() verify(oktaRepo, atLeastOnce()).get(PersistableUserInfo.Restore(OKTA_USER_ID)) verify(httpClient, never()).connect(any(), any()) provider.shutdown() } @Test fun verifyRefreshActorWakesUpOnOktaUserIdChange() = testScope.runTest { tokens.stub { on { idToken } doReturn null } provider.activeFlows.set(1) advanceUntilIdle() verify(oktaRepo, never()).get<PersistableUserInfo>(any()) verify(httpClient, never()).connect(any(), any()) tokens.stub { on { idToken } doReturn ID_TOKEN } storage.notifyChanged() runCurrent() verify(oktaRepo).get(PersistableUserInfo.Restore(OKTA_USER_ID)) verify(httpClient, never()).connect(any(), any()) provider.shutdown() } @Test fun verifyRefreshActorWakesUpWhenRefreshDelayHasExpired() = testScope.runTest { provider.activeFlows.set(1) provider.refreshIfStaleFlows.set(1) userInfo.stub { on { isStale } doReturn false on { nextRefreshDelay } doReturn HOUR_IN_MS } runCurrent() verify(oktaRepo, atLeastOnce()).get(PersistableUserInfo.Restore(OKTA_USER_ID)) verify(httpClient, never()).connect(any(), any()) clearInvocations(oktaRepo) advanceTimeBy(HOUR_IN_MS - 1) runCurrent() verify(oktaRepo, never()).get<PersistableUserInfo>(any()) verify(httpClient, never()).connect(any(), any()) advanceTimeBy(1) runCurrent() verify(oktaRepo).get(PersistableUserInfo.Restore(OKTA_USER_ID)) verify(httpClient, never()).connect(any(), any()) provider.shutdown() } @Test fun verifyRefreshActorDoesntWakesUpForRefreshDelayWhenRefreshIfStaleIsFalse() = testScope.runTest { provider.activeFlows.set(1) provider.refreshIfStaleFlows.set(0) userInfo.stub { on { isStale } doReturn true on { nextRefreshDelay } doReturn -1 } testScope.runCurrent() verify(oktaRepo, atLeastOnce()).get(PersistableUserInfo.Restore(OKTA_USER_ID)) verify(httpClient, never()).connect(any(), any()) clearInvocations(oktaRepo) testScope.advanceUntilIdle() verify(oktaRepo, never()).get<PersistableUserInfo>(any()) verify(httpClient, never()).connect(any(), any()) provider.shutdown() } // endregion refreshActor }
mit
3ee44d5c5632544629d3625846c6c6f1
36.941423
114
0.693317
4.215714
false
true
false
false
jotomo/AndroidAPS
app/src/main/java/info/nightscout/androidaps/activities/SingleFragmentActivity.kt
1
2310
package info.nightscout.androidaps.activities import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.plugins.configBuilder.PluginStore import info.nightscout.androidaps.utils.locale.LocaleHelper import info.nightscout.androidaps.utils.protection.ProtectionCheck import javax.inject.Inject class SingleFragmentActivity : DaggerAppCompatActivityWithResult() { @Inject lateinit var pluginStore: PluginStore @Inject lateinit var protectionCheck: ProtectionCheck private var plugin: PluginBase? = null public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_single_fragment) plugin = pluginStore.plugins[intent.getIntExtra("plugin", -1)] title = plugin?.name supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) if (savedInstanceState == null) { supportFragmentManager.beginTransaction().replace(R.id.frame_layout, supportFragmentManager.fragmentFactory.instantiate(ClassLoader.getSystemClassLoader(), plugin?.pluginDescription?.fragmentClass!!)).commit() } } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { finish() return true } else if (item.itemId == R.id.nav_plugin_preferences) { protectionCheck.queryProtection(this, ProtectionCheck.Protection.PREFERENCES, Runnable { val i = Intent(this, PreferencesActivity::class.java) i.putExtra("id", plugin?.preferencesId) startActivity(i) }, null) return true } return false } override fun onCreateOptionsMenu(menu: Menu): Boolean { if (plugin?.preferencesId != -1) menuInflater.inflate(R.menu.menu_single_fragment, menu) return super.onCreateOptionsMenu(menu) } public override fun attachBaseContext(newBase: Context) { super.attachBaseContext(LocaleHelper.wrap(newBase)) } }
agpl-3.0
0004dd30c2201dd8b14a1db4ead15161
38.844828
156
0.716883
5.099338
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/inventory/shops/ShopsFragment.kt
1
4456
package com.habitrpg.android.habitica.ui.fragments.inventory.shops import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.os.bundleOf import androidx.fragment.app.FragmentPagerAdapter import com.google.firebase.analytics.FirebaseAnalytics import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.InventoryRepository import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.models.shops.Shop import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment import com.habitrpg.android.habitica.ui.views.CurrencyViews import io.reactivex.functions.Consumer import kotlinx.android.synthetic.main.fragment_viewpager.* import javax.inject.Inject open class ShopsFragment : BaseMainFragment() { protected var lockTab: Int? = null @Inject lateinit var inventoryRepository: InventoryRepository private val currencyView: CurrencyViews by lazy { CurrencyViews(context) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { this.usesTabLayout = true this.hidesToolbar = true super.onCreateView(inflater, container, savedInstanceState) return inflater.inflate(R.layout.fragment_viewpager, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewPager.currentItem = 0 setViewPagerAdapter() toolbarAccessoryContainer?.addView(currencyView) if (lockTab == null) { arguments?.let { val args = ShopsFragmentArgs.fromBundle(it) if (args.selectedTab > 0) { viewPager.currentItem = args.selectedTab } } } else { this.usesTabLayout = false tabLayout?.visibility = View.GONE viewPager.currentItem = lockTab ?: 0 viewPager.setOnTouchListener { _, _ -> true } } context?.let { FirebaseAnalytics.getInstance(it).logEvent("open_shop", bundleOf(Pair("shopIndex", lockTab))) } compositeSubscription.add(userRepository.getUser().subscribe(Consumer { updateCurrencyView(it) }, RxErrorHandler.handleEmptyError())) } override fun onDestroyView() { toolbarAccessoryContainer?.removeView(currencyView) super.onDestroyView() } override fun onDestroy() { inventoryRepository.close() super.onDestroy() } override fun injectFragment(component: UserComponent) { component.inject(this) } private fun setViewPagerAdapter() { val fragmentManager = childFragmentManager viewPager?.adapter = object : FragmentPagerAdapter(fragmentManager) { override fun getItem(position: Int): androidx.fragment.app.Fragment { val fragment = ShopFragment() fragment.shopIdentifier = when (position) { 0 -> Shop.MARKET 1 -> Shop.QUEST_SHOP 2 -> Shop.SEASONAL_SHOP 3 -> Shop.TIME_TRAVELERS_SHOP else -> "" } fragment.user = [email protected] return fragment } override fun getCount(): Int = 4 override fun getPageTitle(position: Int): CharSequence? { return when (position) { 0 -> context?.getString(R.string.market) 1 -> context?.getString(R.string.quests) 2 -> context?.getString(R.string.seasonalShop) 3 -> context?.getString(R.string.timeTravelers) else -> "" } } } if (viewPager != null) { tabLayout?.setupWithViewPager(viewPager) } } private fun updateCurrencyView(user: User) { currencyView.gold = user.stats?.gp ?: 0.0 currencyView.gems = user.gemCount.toDouble() currencyView.hourglasses = user.hourglassCount?.toDouble() ?: 0.0 } }
gpl-3.0
6855f6d7820c76c2d80571ddb19ec447
34.227642
141
0.629039
5.046433
false
false
false
false
siosio/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/ReplaceBySourceAsGraph.kt
1
25699
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage.impl import com.google.common.collect.HashBiMap import com.google.common.collect.HashMultimap import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.impl.exceptions.ReplaceBySourceException internal object ReplaceBySourceAsGraph { /** * Here: identificator means [hashCode] or ([PersistentEntityId] in case it exists) * * Plan of [replaceBySource]: * - Traverse all entities of the current builder and save the matched (by [sourceFilter]) to map by identificator. * - In the current builder, remove all references *between* matched entities. If a matched entity has a reference to an unmatched one, * save the unmatched entity to map by identificator. * We'll check if the reference to unmatched reference is still valid after replacing. * - Traverse all matched entities in the [replaceWith] storage. Detect if the particular entity exists in current builder using identificator. * Perform add / replace operation if necessary (remove operation will be later). * - Remove all entities that weren't found in [replaceWith] storage. * - Restore entities between matched and unmatched entities. At this point the full action may fail (e.g. if an entity in [replaceWith] * has a reference to an entity that doesn't exist in current builder. * - Restore references between matched entities. */ internal fun replaceBySourceAsGraph(thisBuilder: WorkspaceEntityStorageBuilderImpl, replaceWith: WorkspaceEntityStorage, sourceFilter: (EntitySource) -> Boolean) { replaceWith as AbstractEntityStorage val initialStore = if (ConsistencyCheckingMode.current != ConsistencyCheckingMode.DISABLED) thisBuilder.toStorage() else null LOG.debug { "Performing replace by source" } // Map of entities in THIS builder with the entitySource that matches the predicate. Key is either hashCode or PersistentId val localMatchedEntities = HashMultimap.create<Any, Pair<WorkspaceEntityData<out WorkspaceEntity>, ThisEntityId>>() // Map of entities in replaceWith store with the entitySource that matches the predicate. Key is either hashCode or PersistentId val replaceWithMatchedEntities = HashMultimap.create<Any, NotThisEntityId>() // Map of entities in THIS builder that have a reference to matched entity. Key is either hashCode or PersistentId val localUnmatchedReferencedNodes = HashMultimap.create<Any, ThisEntityId>() // Association of the EntityId in THIS store to the EntityId in the remote store val replaceMap = HashBiMap.create<ThisEntityId, NotThisEntityId>() LOG.debug { "1) Traverse all entities and store matched only" } thisBuilder.indexes.entitySourceIndex.entries().filter { sourceFilter(it) }.forEach { entitySource -> thisBuilder.indexes.entitySourceIndex.getIdsByEntry(entitySource)?.forEach { val entityData = thisBuilder.entityDataByIdOrDie(it) localMatchedEntities.put(entityData.identificator(thisBuilder), entityData to it.asThis()) } } LOG.debug { "1.1) Cleanup references" } // If the reference leads to the matched entity, we can safely remove this reference. // If the reference leads to the unmatched entity, we should save the entity to try to restore the reference later. for ((_, entityId) in localMatchedEntities.values()) { // Traverse parents of the entity val childEntityId = entityId.id.asChild() for ((connectionId, parentId) in thisBuilder.refs.getParentRefsOfChild(childEntityId)) { val parentEntity = thisBuilder.entityDataByIdOrDie(parentId.id) if (sourceFilter(parentEntity.entitySource)) { // Remove the connection between matched entities thisBuilder.refs.removeParentToChildRef(connectionId, parentId, childEntityId) } else { // Save the entity for restoring reference to it later localUnmatchedReferencedNodes.put(parentEntity.identificator(thisBuilder), parentId.id.asThis()) } } // TODO: 29.04.2020 Do we need iterate over children and parents? Maybe only parents would be enough? // Traverse children of the entity for ((connectionId, childrenIds) in thisBuilder.refs.getChildrenRefsOfParentBy(entityId.id.asParent())) { for (childId in childrenIds) { val childEntity = thisBuilder.entityDataByIdOrDie(childId.id) if (sourceFilter(childEntity.entitySource)) { // Remove the connection between matched entities thisBuilder.refs.removeParentToChildRef(connectionId, entityId.id.asParent(), childId) } else { // Save the entity for restoring reference to it later localUnmatchedReferencedNodes.put(childEntity.identificator(thisBuilder), childId.id.asThis()) } } } } LOG.debug { "2) Traverse entities of replaceWith store" } // 2) Traverse entities of the enemy // and trying to detect whenever the entity already present in the local builder or not. // If the entity already exists we optionally perform replace operation (or nothing), // otherwise we add the entity. // Local entities that don't exist in replaceWith store will be removed later. for (replaceWithEntitySource in replaceWith.indexes.entitySourceIndex.entries().filter { sourceFilter(it) }) { val entityDataList = replaceWith.indexes.entitySourceIndex .getIdsByEntry(replaceWithEntitySource) ?.map { replaceWith.entityDataByIdOrDie(it) to it.notThis() } ?: continue for ((matchedEntityData, matchedEntityId) in entityDataList) { replaceWithMatchedEntities.put(matchedEntityData.identificator(replaceWith), matchedEntityId) // Find if the entity exists in local store val localNodeAndId = localMatchedEntities.find(matchedEntityData, replaceWith) // We should check if the issue still exists in this builder because it can be removed if it's referenced by another entity // that had persistent id clash. val entityStillExists = localNodeAndId?.second?.let { thisBuilder.entityDataById(it.id) != null } ?: false if (entityStillExists && localNodeAndId != null) { val (localNode, localNodeEntityId) = localNodeAndId // This entity already exists. Store the association of EntityIdss replaceMap[localNodeEntityId] = matchedEntityId val dataDiffersByProperties = !localNode.equalsIgnoringEntitySource(matchedEntityData) val dataDiffersByEntitySource = localNode.entitySource != matchedEntityData.entitySource if (localNode.hasPersistentId( thisBuilder) && (dataDiffersByEntitySource || dataDiffersByProperties) && matchedEntityData.entitySource !is DummyParentEntitySource) { // Entity exists in local store, but has changes. Generate replace operation replaceOperation(thisBuilder, matchedEntityData, replaceWith, localNode, matchedEntityId, dataDiffersByProperties, dataDiffersByEntitySource) } // To make a store consistent in such case, we will clean up all refer to this entity if (localNode.entitySource !is DummyParentEntitySource && matchedEntityData.entitySource !is DummyParentEntitySource) { thisBuilder.removeEntitiesByOneToOneRef(sourceFilter, replaceWith, replaceMap, matchedEntityId, localNodeEntityId) .forEach { removedEntityData -> localUnmatchedReferencedNodes.removeAll(removedEntityData.identificator( thisBuilder)) } } if (localNode == matchedEntityData) { thisBuilder.indexes.updateExternalMappingForEntityId(matchedEntityId.id, localNodeEntityId.id, replaceWith.indexes) } // Remove added entity localMatchedEntities.remove(localNode.identificator(thisBuilder), localNodeAndId) } else { // This is a new entity for this store. Perform add operation val persistentId = matchedEntityData.persistentId(thisBuilder) if (persistentId != null) { val existingEntityId = thisBuilder.indexes.persistentIdIndex.getIdsByEntry(persistentId)?.asThis() if (existingEntityId != null) { // Bad news, we have this persistent id already. CPP-22547 // This may happened if local entity has entity source and remote entity has a different entity source // Technically we should throw an exception, but now we just remove local entity // Entity exists in local store, but has changes. Generate replace operation val localNode = thisBuilder.entityDataByIdOrDie(existingEntityId.id) val dataDiffersByProperties = !localNode.equalsIgnoringEntitySource(matchedEntityData) val dataDiffersByEntitySource = localNode.entitySource != matchedEntityData.entitySource replaceOperation(thisBuilder, matchedEntityData, replaceWith, localNode, matchedEntityId, dataDiffersByProperties, dataDiffersByEntitySource) // To make a store consistent in such case, we will clean up all refer to this entity thisBuilder.removeEntitiesByOneToOneRef(sourceFilter, replaceWith, replaceMap, matchedEntityId, existingEntityId) .forEach { removedEntityData -> localUnmatchedReferencedNodes.removeAll(removedEntityData.identificator( thisBuilder)) } replaceMap[existingEntityId] = matchedEntityId continue } } val entityClass = ClassConversion.entityDataToEntity(matchedEntityData.javaClass).toClassId() val newEntity = thisBuilder.entitiesByType.cloneAndAdd(matchedEntityData, entityClass) val newEntityId = matchedEntityId.id.copy(arrayId = newEntity.id).asThis() replaceMap[newEntityId] = matchedEntityId thisBuilder.indexes.virtualFileIndex.updateIndex(matchedEntityId.id, newEntityId.id, replaceWith.indexes.virtualFileIndex) replaceWith.indexes.entitySourceIndex.getEntryById(matchedEntityId.id)?.also { thisBuilder.indexes.entitySourceIndex.index(newEntityId.id, it) } replaceWith.indexes.persistentIdIndex.getEntryById(matchedEntityId.id)?.also { thisBuilder.indexes.persistentIdIndex.index(newEntityId.id, it) } thisBuilder.indexes.updateExternalMappingForEntityId(matchedEntityId.id, newEntityId.id, replaceWith.indexes) if (newEntity is SoftLinkable) thisBuilder.indexes.updateSoftLinksIndex(newEntity) thisBuilder.createAddEvent(newEntity) } } } LOG.debug { "3) Remove old entities" } // After previous operation localMatchedEntities contain only entities that exist in local store, but don't exist in replaceWith store. // Those entities should be just removed. for ((localEntity, entityId) in localMatchedEntities.values()) { val entityClass = ClassConversion.entityDataToEntity(localEntity.javaClass).toClassId() thisBuilder.entitiesByType.remove(localEntity.id, entityClass) thisBuilder.indexes.removeFromIndices(entityId.id) if (localEntity is SoftLinkable) thisBuilder.indexes.removeFromSoftLinksIndex(localEntity) thisBuilder.changeLog.addRemoveEvent(entityId.id) } val lostChildren = HashSet<ThisEntityId>() LOG.debug { "4) Restore references between matched and unmatched entities" } // At this moment the operation may fail because of inconsistency. // E.g. after this operation we can't have non-null references without corresponding entity. // This may happen if we remove the matched entity, but don't have a replacement for it. for (thisUnmatchedId in localUnmatchedReferencedNodes.values()) { val replaceWithUnmatchedEntity = replaceWith.entityDataById(thisUnmatchedId.id) if (replaceWithUnmatchedEntity == null || replaceWithUnmatchedEntity != thisBuilder.entityDataByIdOrDie(thisUnmatchedId.id)) { // Okay, replaceWith storage doesn't have this "unmatched" entity at all. // TODO: 14.04.2020 Don't forget about entities with persistence id for ((connectionId, parentId) in thisBuilder.refs.getParentRefsOfChild(thisUnmatchedId.id.asChild())) { val parent = thisBuilder.entityDataById(parentId.id) // TODO: 29.04.2020 Review and write tests if (parent == null) { if (connectionId.canRemoveParent()) { thisBuilder.refs.removeParentToChildRef(connectionId, parentId, thisUnmatchedId.id.asChild()) } else { thisBuilder.refs.removeParentToChildRef(connectionId, parentId, thisUnmatchedId.id.asChild()) lostChildren += thisUnmatchedId } } } for ((connectionId, childIds) in thisBuilder.refs.getChildrenRefsOfParentBy(thisUnmatchedId.id.asParent())) { for (childId in childIds) { val child = thisBuilder.entityDataById(childId.id) if (child == null) { thisBuilder.refs.removeParentToChildRef(connectionId, thisUnmatchedId.id.asParent(), childId) } } } } else { // ----------------- Update parent references --------------- val removedConnections = HashMap<ConnectionId, EntityId>() // Remove parents in local store for ((connectionId, parentId) in thisBuilder.refs.getParentRefsOfChild(thisUnmatchedId.id.asChild())) { val parentData = thisBuilder.entityDataById(parentId.id) if (parentData != null && !sourceFilter(parentData.entitySource)) continue thisBuilder.refs.removeParentToChildRef(connectionId, parentId, thisUnmatchedId.id.asChild()) removedConnections[connectionId] = parentId.id } // Transfer parents from replaceWith storage for ((connectionId, parentId) in replaceWith.refs.getParentRefsOfChild(thisUnmatchedId.id.asChild())) { if (!sourceFilter(replaceWith.entityDataByIdOrDie(parentId.id).entitySource)) continue val localParentId = replaceMap.inverse().getValue(parentId.id.notThis()) thisBuilder.refs.updateParentOfChild(connectionId, thisUnmatchedId.id.asChild(), localParentId.id.asParent()) removedConnections.remove(connectionId) } // TODO: 05.06.2020 The similar logic should exist for children references // Check not restored connections for ((connectionId, parentId) in removedConnections) { if (!connectionId.canRemoveParent()) thisBuilder.rbsFailedAndReport("Cannot restore connection to $parentId; $connectionId", sourceFilter, initialStore, replaceWith) } // ----------------- Update children references ----------------------- for ((connectionId, childrenId) in thisBuilder.refs.getChildrenRefsOfParentBy(thisUnmatchedId.id.asParent())) { for (childId in childrenId) { val childData = thisBuilder.entityDataById(childId.id) if (childData != null && !sourceFilter(childData.entitySource)) continue thisBuilder.refs.removeParentToChildRef(connectionId, thisUnmatchedId.id.asParent(), childId) } } for ((connectionId, childrenId) in replaceWith.refs.getChildrenRefsOfParentBy(thisUnmatchedId.id.asParent())) { for (childId in childrenId) { if (!sourceFilter(replaceWith.entityDataByIdOrDie(childId.id).entitySource)) continue val localChildId = replaceMap.inverse().getValue(childId.id.notThis()) thisBuilder.refs.updateParentOfChild(connectionId, localChildId.id.asChild(), thisUnmatchedId.id.asParent()) } } } } // Some children left without parents. We should delete these children as well. for (entityId in lostChildren) { thisBuilder.removeEntity(entityId.id) } LOG.debug { "5) Restore references in matching ids" } val parentsWithSortedChildren = mutableSetOf<Pair<NotThisEntityId, ConnectionId>>() for (nodeId in replaceWithMatchedEntities.values()) { for ((connectionId, parentId) in replaceWith.refs.getParentRefsOfChild(nodeId.id.asChild())) { if (!sourceFilter(replaceWith.entityDataByIdOrDie(parentId.id).entitySource)) { // replaceWith storage has a link to unmatched entity. We should check if we can "transfer" this link to the current storage if (!connectionId.isParentNullable) { val localParent = thisBuilder.entityDataById(parentId.id) if (localParent == null) thisBuilder.rbsFailedAndReport( "Cannot link entities. Child entity doesn't have a parent after operation; $connectionId", sourceFilter, initialStore, replaceWith) val localChildId = replaceMap.inverse().getValue(nodeId) if (connectionId.connectionType == ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY) { parentsWithSortedChildren += parentId.id.notThis() to connectionId } thisBuilder.refs.updateParentOfChild(connectionId, localChildId.id.asChild(), parentId) } continue } val localChildId = replaceMap.inverse().getValue(nodeId) val localParentId = replaceMap.inverse().getValue(parentId.id.notThis()) if (connectionId.connectionType == ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY) { parentsWithSortedChildren += parentId.id.notThis() to connectionId } thisBuilder.refs.updateParentOfChild(connectionId, localChildId.id.asChild(), localParentId.id.asParent()) } } // Try to sort children // At the moment we sort only one-to-abstract-many children. This behaviour can be updated or removed at all parentsWithSortedChildren.forEach { (notThisParentId, connectionId) -> if (!replaceMap.containsValue(notThisParentId)) return@forEach val thisParentId = replaceMap.inverse().getValue(notThisParentId) val children = replaceWith.refs.getOneToAbstractManyChildren(connectionId, notThisParentId.id.asParent()) ?.mapNotNull { replaceMap.inverse().getValue(it.id.notThis()) } ?: return@forEach val localChildren = thisBuilder.refs.getOneToAbstractManyChildren(connectionId, thisParentId.id.asParent())?.toMutableSet() ?: return@forEach val savedLocalChildren = thisBuilder.refs.getOneToAbstractManyChildren(connectionId, thisParentId.id.asParent()) ?: return@forEach val newChildren = mutableListOf<ChildEntityId>() for (child in children) { val removed = localChildren.remove(child.id.asChild()) if (removed) { newChildren += child.id.asChild() } } newChildren.addAll(localChildren) if (savedLocalChildren != newChildren) { thisBuilder.refs.updateChildrenOfParent(connectionId, thisParentId.id.asParent(), newChildren) } } // Assert consistency if (!thisBuilder.brokenConsistency && !replaceWith.brokenConsistency) { thisBuilder.assertConsistencyInStrictMode("Check after replaceBySource", sourceFilter, initialStore, replaceWith) } else { thisBuilder.brokenConsistency = true } LOG.debug { "Replace by source finished" } } private fun WorkspaceEntityData<*>.identificator(storage: AbstractEntityStorage): Any { return this.persistentId(storage) ?: this.hashCode() } private fun <T> HashMultimap<Any, Pair<WorkspaceEntityData<out WorkspaceEntity>, T>>.find(entity: WorkspaceEntityData<out WorkspaceEntity>, storage: AbstractEntityStorage): Pair<WorkspaceEntityData<out WorkspaceEntity>, T>? { val possibleValues = this[entity.identificator(storage)] val persistentId = entity.persistentId(storage) return if (persistentId != null) { possibleValues.singleOrNull() } else { possibleValues.find { it.first == entity } } } private fun WorkspaceEntityData<*>.hasPersistentId(thisBuilder: WorkspaceEntityStorageBuilderImpl): Boolean { val entity = this.createEntity(thisBuilder) return entity is WorkspaceEntityWithPersistentId } private fun replaceOperation(thisBuilder: WorkspaceEntityStorageBuilderImpl, matchedEntityData: WorkspaceEntityData<out WorkspaceEntity>, replaceWith: AbstractEntityStorage, localNode: WorkspaceEntityData<out WorkspaceEntity>, matchedEntityId: NotThisEntityId, dataDiffersByProperties: Boolean, dataDiffersByEntitySource: Boolean) { val clonedEntity = matchedEntityData.clone() val persistentIdBefore = matchedEntityData.persistentId(replaceWith) ?: error("PersistentId expected for $matchedEntityData") clonedEntity.id = localNode.id val clonedEntityId = matchedEntityId.id.copy(arrayId = clonedEntity.id) thisBuilder.entitiesByType.replaceById(clonedEntity, clonedEntityId.clazz) thisBuilder.updatePersistentIdIndexes(clonedEntity.createEntity(thisBuilder), persistentIdBefore, clonedEntity) thisBuilder.indexes.virtualFileIndex.updateIndex(matchedEntityId.id, clonedEntityId, replaceWith.indexes.virtualFileIndex) replaceWith.indexes.entitySourceIndex.getEntryById(matchedEntityId.id) ?.also { thisBuilder.indexes.entitySourceIndex.index(clonedEntityId, it) } thisBuilder.indexes.updateExternalMappingForEntityId(matchedEntityId.id, clonedEntityId, replaceWith.indexes) if (dataDiffersByProperties) { thisBuilder.changeLog.addReplaceEvent(clonedEntityId, clonedEntity, emptyList(), emptySet(), emptyMap()) } if (dataDiffersByEntitySource) { thisBuilder.changeLog.addChangeSourceEvent(clonedEntityId, clonedEntity) } } /** * The goal of this method is to help to keep the store in at the consistent state at replaceBySource operation. It's responsible * for handling 1-1 references where entity source of the record is changed and we know the persistent Id of one of the elements * at this relationship.How this method works: we try to find all 1-1 references where current entity is parent or child. * We check that such reference also exist at the replacing store. And if such reference exist at the second store we can safely * delete related by the reference entity because we sure that the reference will be restored and entity from the second store * will be added to the main. * One important notes of the entity remove: we make it only if the second store contains entity which matched by source filter, * we don't remove entity which already was replaced and we don't remove the the object itself. */ private fun WorkspaceEntityStorageBuilderImpl.removeEntitiesByOneToOneRef(sourceFilter: (EntitySource) -> Boolean, replaceWith: AbstractEntityStorage, replaceMap: Map<ThisEntityId, NotThisEntityId>, matchedEntityId: NotThisEntityId, localEntityId: ThisEntityId): Set<WorkspaceEntityData<out WorkspaceEntity>> { val replacingChildrenOneToOneConnections = replaceWith.refs .getChildrenOneToOneRefsOfParentBy(matchedEntityId.id.asParent()) .filter { !it.key.isParentNullable } val result = refs.getChildrenOneToOneRefsOfParentBy(localEntityId.id.asParent()) .asSequence() .filter { !it.key.isParentNullable } .mapNotNull { (connectionId, entityId) -> val suggestedNewChildEntityId = replacingChildrenOneToOneConnections[connectionId] ?: return@mapNotNull null val suggestedNewChildEntityData = replaceWith.entityDataByIdOrDie(suggestedNewChildEntityId.id) if (sourceFilter(suggestedNewChildEntityData.entitySource)) { val childEntityData = entityDataByIdOrDie(entityId.id) removeEntity(entityId.id) { it != localEntityId.id && !replaceMap.containsKey(it.asThis()) } return@mapNotNull childEntityData } return@mapNotNull null }.toMutableSet() return result } private fun WorkspaceEntityStorageBuilderImpl.rbsFailedAndReport(message: String, sourceFilter: (EntitySource) -> Boolean, left: WorkspaceEntityStorage?, right: WorkspaceEntityStorage) { reportConsistencyIssue(message, ReplaceBySourceException(message), sourceFilter, left, right, this) } val LOG = logger<ReplaceBySourceAsGraph>() }
apache-2.0
427f8af83b7c1c246181f3c1544574f6
57.142534
177
0.692284
5.193816
false
false
false
false
siosio/intellij-community
platform/built-in-server/src/org/jetbrains/ide/ToolboxRestService.kt
1
7884
// 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.ide import com.google.gson.JsonElement import com.google.gson.JsonObject import com.google.gson.JsonParser import com.intellij.openapi.Disposable import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.util.Disposer import com.intellij.util.castSafelyTo import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.io.delete import io.netty.buffer.Unpooled import io.netty.channel.ChannelHandlerContext import io.netty.channel.ChannelOption import io.netty.handler.codec.http.* import org.jetbrains.io.addCommonHeaders import java.nio.file.Files import java.nio.file.Path import java.util.* import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit import kotlin.io.path.writeText val toolboxHandlerEP: ExtensionPointName<ToolboxServiceHandler<*>> = ExtensionPointName.create("com.intellij.toolboxServiceHandler") interface ToolboxServiceHandler<T> { /** * Specifies a request, it is actually the last part of the path, * e.g. `http://localhost:port/api/toolbox/update-notification */ val requestName : String /** * This method is executed synchronously for the handler to parser * request parameters, it may throw an exception on malformed inputs, */ fun parseRequest(request: JsonElement) : T /** * This function is executes on a background thread to handle a Toolbox * request. The implementation allows to send a response after a long * while back to Toolbox. * * The [lifetime] should be used to bind all necessary * resources to the underlying Toolbox connection. It can * be disposed during the execution of this method. * * Use the [onResult] to pass a result back to Toolbox and * to close the connection. The [lifetime] is disposed after * the connection is closed too, it must not be used after [onResult] * callback is executed */ fun handleToolboxRequest( lifetime: Disposable, request: T, onResult: (JsonElement) -> Unit, ) } private fun findToolboxHandlerByUri(requestUri: String): ToolboxServiceHandler<*>? = toolboxHandlerEP.findFirstSafe { requestUri.endsWith("/" + it.requestName.trim('/')) } private fun interface ToolboxInnerHandler { fun handleToolboxRequest( lifetime: Disposable, onResult: (JsonElement) -> Unit, ) } private fun <T> wrapHandler(handler: ToolboxServiceHandler<T>, request: JsonElement): ToolboxInnerHandler { val param = handler.parseRequest(request) return object : ToolboxInnerHandler { override fun handleToolboxRequest(lifetime: Disposable, onResult: (JsonElement) -> Unit) { handler.handleToolboxRequest(lifetime, param, onResult) } override fun toString(): String = "ToolboxInnerHandler{$handler, $param}" } } internal class ToolboxRestServiceConfig : Disposable { override fun dispose() = Unit init { val toolboxPortFilePath = System.getProperty("toolbox.notification.portFile") if (toolboxPortFilePath != null) { AppExecutorUtil.getAppExecutorService().submit { val server = BuiltInServerManager.getInstance() val port = server.waitForStart().port val portFile = Path.of(toolboxPortFilePath) runCatching { Files.createDirectories(portFile.parent) } runCatching { portFile.writeText("$port") } Disposer.register(this) { runCatching { portFile.delete() } } } } } } internal class ToolboxRestService : RestService() { internal companion object { @Suppress("SSBasedInspection") private val LOG = logger<ToolboxRestService>() } override fun getServiceName() = "toolbox" override fun isSupported(request: FullHttpRequest): Boolean { val token = System.getProperty("toolbox.notification.token") ?: return false if (request.headers()["Authorization"] != "toolbox $token") return false val requestUri = request.uri().substringBefore('?') if (findToolboxHandlerByUri(requestUri) == null) return false return super.isSupported(request) } override fun isMethodSupported(method: HttpMethod) = method == HttpMethod.POST override fun execute(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): String? { val requestJson = createJsonReader(request).use { JsonParser.parseReader(it) } val channel = context.channel() val toolboxRequest : ToolboxInnerHandler = try { val handler = findToolboxHandlerByUri(urlDecoder.path()) if (handler == null) { sendStatus(HttpResponseStatus.NOT_FOUND, false, channel) return null } wrapHandler(handler, requestJson) } catch (t: Throwable) { LOG.warn("Failed to process parameters of $request. ${t.message}", t) sendStatus(HttpResponseStatus.BAD_REQUEST, false, channel) return null } val response = DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK) response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=utf-8") response.addCommonHeaders() response.headers().remove(HttpHeaderNames.ACCEPT_RANGES) response.headers().set(HttpHeaderNames.CACHE_CONTROL, "private, must-revalidate") //NON-NLS response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED) response.headers().set(HttpHeaderNames.LAST_MODIFIED, Date(Calendar.getInstance().timeInMillis)) channel.writeAndFlush(response).get() val heartbeatDelay = requestJson.castSafelyTo<JsonObject>()?.get("heartbeatMillis")?.asLong ?: System.getProperty("toolbox.heartbeat.millis", "5000").toLong() runCatching { channel.config().setOption(ChannelOption.TCP_NODELAY, true) } runCatching { channel.config().setOption(ChannelOption.SO_KEEPALIVE, true) } runCatching { channel.config().setOption(ChannelOption.SO_TIMEOUT, heartbeatDelay.toInt() * 2) } val lifetime = Disposer.newDisposable("toolbox-service-request") val heartbeat = context.executor().scheduleWithFixedDelay(Runnable { try { channel .writeAndFlush(Unpooled.copiedBuffer(" ", Charsets.UTF_8)) .get() } catch (t: Throwable) { LOG.debug("Failed to write next heartbeat. ${t.message}", t) Disposer.dispose(lifetime) } }, heartbeatDelay, heartbeatDelay, TimeUnit.MILLISECONDS) Disposer.register(lifetime) { heartbeat.cancel(false) } val callback = CompletableFuture<JsonElement?>() AppExecutorUtil.getAppExecutorService().submit { toolboxRequest.handleToolboxRequest(lifetime) { r -> callback.complete(r) } } channel.closeFuture().addListener { Disposer.dispose(lifetime) } callback .exceptionally { e -> LOG.warn("The future completed with exception. ${e.message}", e) JsonObject().apply { addProperty("status", "error") } } .thenAcceptAsync( { json -> //kill the heartbeat, it may close the lifetime too runCatching { heartbeat.cancel(false) heartbeat.await() } //no need to do anything if it's already disposed if (Disposer.isDisposed(lifetime)) { //closing the channel just in case runCatching { channel.close() } return@thenAcceptAsync } runCatching { channel.writeAndFlush(Unpooled.copiedBuffer(gson.toJson(json), Charsets.UTF_8)).get() } runCatching { channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT).get() } Disposer.dispose(lifetime) }, AppExecutorUtil.getAppExecutorService() ) return null } }
apache-2.0
a3101c94101ae34542c811f87277e235
36.542857
158
0.710299
4.557225
false
false
false
false
siosio/intellij-community
plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/scripting/gradle/roots/GradleBuildRootsManager.kt
1
18776
// 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.scripting.gradle.roots import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.progress.util.BackgroundTaskUtil import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiManager import com.intellij.ui.EditorNotifications import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager import org.jetbrains.kotlin.idea.core.script.configuration.CompositeScriptConfigurationManager import org.jetbrains.kotlin.idea.core.script.configuration.DefaultScriptingSupport import org.jetbrains.kotlin.idea.core.script.configuration.ScriptingSupport import org.jetbrains.kotlin.idea.core.script.scriptingDebugLog import org.jetbrains.kotlin.idea.core.script.scriptingErrorLog import org.jetbrains.kotlin.idea.core.script.scriptingInfoLog import org.jetbrains.kotlin.idea.core.script.ucache.ScriptClassRootsBuilder import org.jetbrains.kotlin.idea.core.util.EDT import org.jetbrains.kotlin.idea.scripting.gradle.* import org.jetbrains.kotlin.idea.scripting.gradle.importing.KotlinDslGradleBuildSync import org.jetbrains.kotlin.idea.scripting.gradle.roots.GradleBuildRoot.ImportingStatus.* import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.plugins.gradle.config.GradleSettingsListenerAdapter import org.jetbrains.plugins.gradle.service.GradleInstallationManager import org.jetbrains.plugins.gradle.settings.* import org.jetbrains.plugins.gradle.util.GradleConstants import java.nio.file.FileSystems import java.nio.file.Files import java.nio.file.Paths import java.nio.file.attribute.BasicFileAttributes import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.atomic.AtomicBoolean /** * [GradleBuildRoot] is a linked gradle build (don't confuse with gradle project and included build). * Each [GradleBuildRoot] may have it's own Gradle version, Java home and other settings. * * Typically, IntelliJ project have no more than one [GradleBuildRoot]. * * This manager allows to find related Gradle build by the Gradle Kotlin script file path. * Each imported build have info about all of it's Kotlin Build Scripts. * It is populated by calling [update], stored in FS and will be loaded from FS on next project opening * * [CompositeScriptConfigurationManager] may ask about known scripts by calling [collectConfigurations]. * * It also used to show related notification and floating actions depending on root kind, state and script state itself. * * Roots may be: * - [GradleBuildRoot] - Linked project, that may be itself: * - [Legacy] - Gradle build with old Gradle version (<6.0) * - [New] - not yet imported * - [Imported] - imported */ class GradleBuildRootsManager(val project: Project) : GradleBuildRootsLocator(project), ScriptingSupport { private val manager: CompositeScriptConfigurationManager get() = ScriptConfigurationManager.getInstance(project) as CompositeScriptConfigurationManager private val updater get() = manager.updater var enabled: Boolean = true set(value) { if (value != field) { field = value roots.list.toList().forEach { reloadBuildRoot(it.pathPrefix, null) } } } //////////// /// ScriptingSupport.Provider implementation: override fun isApplicable(file: VirtualFile): Boolean { val scriptUnderRoot = findScriptBuildRoot(file) ?: return false if (scriptUnderRoot.nearest is Legacy) return false if (roots.isStandaloneScript(file.path)) return false return true } override fun isConfigurationLoadingInProgress(file: KtFile): Boolean { return findScriptBuildRoot(file.originalFile.virtualFile)?.nearest?.isImportingInProgress() ?: return false } @Suppress("MemberVisibilityCanBePrivate") // used in GradleImportHelper.kt.201 fun isConfigurationOutOfDate(file: VirtualFile): Boolean { val script = getScriptInfo(file) ?: return false if (script.buildRoot.isImportingInProgress()) return false return !script.model.inputs.isUpToDate(project, file) } override fun collectConfigurations(builder: ScriptClassRootsBuilder) { roots.list.forEach { root -> if (root is Imported) { root.collectConfigurations(builder) } } } override fun afterUpdate() { roots.list.forEach { root -> if (root.importing.compareAndSet(updatingCaches, updated)) { updateNotifications { it.startsWith(root.pathPrefix) } } } } ////////////////// override fun getScriptInfo(localPath: String): GradleScriptInfo? = manager.getLightScriptInfo(localPath) as? GradleScriptInfo override fun getScriptFirstSeenTs(path: String): Long { val nioPath = FileSystems.getDefault().getPath(path) return Files.readAttributes(nioPath, BasicFileAttributes::class.java) ?.creationTime()?.toMillis() ?: Long.MAX_VALUE } fun fileChanged(filePath: String, ts: Long = System.currentTimeMillis()) { findAffectedFileRoot(filePath)?.fileChanged(filePath, ts) scheduleModifiedFilesCheck(filePath) } fun markImportingInProgress(workingDir: String, inProgress: Boolean = true) { actualizeBuildRoot(workingDir, null)?.importing?.set(if (inProgress) importing else updated) updateNotifications { it.startsWith(workingDir) } } fun update(sync: KotlinDslGradleBuildSync) { val oldRoot = actualizeBuildRoot(sync.workingDir, sync.gradleVersion) ?: return try { val newRoot = updateRoot(oldRoot, sync) if (newRoot == null) { markImportingInProgress(sync.workingDir, false) return } add(newRoot) } catch (e: Exception) { markImportingInProgress(sync.workingDir, false) return } } private fun updateRoot(oldRoot: GradleBuildRoot, sync: KotlinDslGradleBuildSync): Imported? { // fast path for linked gradle builds without .gradle.kts support if (sync.models.isEmpty()) { if (oldRoot is Imported && oldRoot.data.models.isEmpty()) return null } if (oldRoot is Legacy) return null scriptingDebugLog { "gradle project info after import: $sync" } // TODO: can gradleHome be null, what to do in this case val gradleHome = sync.gradleHome if (gradleHome == null) { scriptingInfoLog("Cannot find valid gradle home for ${sync.gradleHome} with version = ${sync.gradleVersion}, script models cannot be saved") return null } oldRoot.importing.set(updatingCaches) scriptingDebugLog { "save script models after import: ${sync.models}" } val newData = GradleBuildRootData(sync.ts, sync.projectRoots, gradleHome, sync.javaHome, sync.models) val mergedData = if (sync.failed && oldRoot is Imported) merge(oldRoot.data, newData) else newData val newRoot = tryCreateImportedRoot(sync.workingDir, LastModifiedFiles()) { mergedData } ?: return null val buildRootDir = newRoot.dir ?: return null GradleBuildRootDataSerializer.write(buildRootDir, mergedData) newRoot.saveLastModifiedFiles() return newRoot } private fun merge(old: GradleBuildRootData, new: GradleBuildRootData): GradleBuildRootData { val roots = old.projectRoots.toMutableSet() roots.addAll(new.projectRoots) val models = old.models.associateByTo(mutableMapOf()) { it.file } new.models.associateByTo(models) { it.file } return GradleBuildRootData(new.importTs, roots, new.gradleHome, new.javaHome, models.values) } private val modifiedFilesCheckScheduled = AtomicBoolean() private val modifiedFiles = ConcurrentLinkedQueue<String>() fun scheduleModifiedFilesCheck(filePath: String) { modifiedFiles.add(filePath) if (modifiedFilesCheckScheduled.compareAndSet(false, true)) { val disposable = KotlinPluginDisposable.getInstance(project) BackgroundTaskUtil.executeOnPooledThread(disposable) { if (modifiedFilesCheckScheduled.compareAndSet(true, false)) { checkModifiedFiles() } } } } private fun checkModifiedFiles() { updateNotifications(restartAnalyzer = false) { true } roots.list.forEach { it.saveLastModifiedFiles() } // process modifiedFiles queue while (true) { val file = modifiedFiles.poll() ?: break // detect gradle version change val buildDir = findGradleWrapperPropertiesBuildDir(file) if (buildDir != null) { actualizeBuildRoot(buildDir, null) } } } fun updateStandaloneScripts(update: StandaloneScriptsUpdater.() -> Unit) { val changes = StandaloneScriptsUpdater.collectChanges(delegate = roots, update) updateNotifications { it in changes.new || it in changes.removed } loadStandaloneScriptConfigurations(changes.new) } init { getGradleProjectSettings(project).forEach { // don't call this.add, as we are inside scripting manager initialization roots.add(loadLinkedRoot(it)) } // subscribe to linked gradle project modification val listener = object : GradleSettingsListenerAdapter() { override fun onProjectsLinked(settings: MutableCollection<GradleProjectSettings>) { settings.forEach { add(loadLinkedRoot(it)) } } override fun onProjectsUnlinked(linkedProjectPaths: MutableSet<String>) { linkedProjectPaths.forEach { remove(it) } } override fun onGradleHomeChange(oldPath: String?, newPath: String?, linkedProjectPath: String) { val version = GradleInstallationManager.getGradleVersion(newPath) reloadBuildRoot(linkedProjectPath, version) } override fun onGradleDistributionTypeChange(currentValue: DistributionType?, linkedProjectPath: String) { reloadBuildRoot(linkedProjectPath, null) } } val disposable = KotlinPluginDisposable.getInstance(project) project.messageBus.connect(disposable).subscribe(GradleSettingsListener.TOPIC, listener) } private fun getGradleProjectSettings(workingDir: String): GradleProjectSettings? { return (ExternalSystemApiUtil.getSettings(project, GradleConstants.SYSTEM_ID) as GradleSettings) .getLinkedProjectSettings(workingDir) } /** * Check that root under [workingDir] in sync with it's [GradleProjectSettings]. * Actually this should be true, but we may miss some change events. * For that cases we are rechecking this on each Gradle Project sync (importing/reimporting) */ private fun actualizeBuildRoot(workingDir: String, gradleVersion: String?): GradleBuildRoot? { val actualSettings = getGradleProjectSettings(workingDir) val buildRoot = getBuildRootByWorkingDir(workingDir) val version = gradleVersion ?: actualSettings?.let { getGradleVersion(project, it) } return when { buildRoot != null -> { when { !buildRoot.checkActual(version) -> reloadBuildRoot(workingDir, version) else -> buildRoot } } actualSettings != null && version != null -> { loadLinkedRoot(actualSettings, version) } else -> null } } private fun GradleBuildRoot.checkActual(version: String?): Boolean { if (version == null) return false val knownAsSupported = this !is Legacy val shouldBeSupported = kotlinDslScriptsModelImportSupported(version) return knownAsSupported == shouldBeSupported } private fun reloadBuildRoot(rootPath: String, version: String?): GradleBuildRoot? { val settings = getGradleProjectSettings(rootPath) if (settings == null) { remove(rootPath) return null } else { val gradleVersion = version ?: getGradleVersion(project, settings) val newRoot = loadLinkedRoot(settings, gradleVersion) add(newRoot) return newRoot } } private fun loadLinkedRoot(settings: GradleProjectSettings, version: String = getGradleVersion(project, settings)): GradleBuildRoot { if (!enabled) { return Legacy(settings) } val supported = kotlinDslScriptsModelImportSupported(version) return when { supported -> tryLoadFromFsCache(settings, version) ?: New(settings) else -> Legacy(settings) } } private fun tryLoadFromFsCache(settings: GradleProjectSettings, version: String): Imported? { return tryCreateImportedRoot(settings.externalProjectPath) { GradleBuildRootDataSerializer.read(it)?.let { data -> val gradleHome = data.gradleHome if (gradleHome.isNotBlank() && GradleInstallationManager.getGradleVersion(gradleHome) != version) return@let null addFromSettings(data, settings) } } } private fun addFromSettings( data: GradleBuildRootData, settings: GradleProjectSettings ) = data.copy(projectRoots = data.projectRoots.toSet() + settings.modules) private fun tryCreateImportedRoot( externalProjectPath: String, lastModifiedFiles: LastModifiedFiles = loadLastModifiedFiles(externalProjectPath) ?: LastModifiedFiles(), dataProvider: (buildRoot: VirtualFile) -> GradleBuildRootData? ): Imported? { try { val buildRoot = VfsUtil.findFile(Paths.get(externalProjectPath), true) ?: return null val data = dataProvider(buildRoot) ?: return null return Imported(externalProjectPath, data, lastModifiedFiles) } catch (e: Exception) { scriptingErrorLog("Cannot load script configurations from file attributes for $externalProjectPath", e) return null } } private fun add(newRoot: GradleBuildRoot) { val old = roots.add(newRoot) if (old is Imported && newRoot !is Imported) { removeData(old.pathPrefix) } if (old !is Legacy || newRoot !is Legacy) { updater.invalidateAndCommit() } updateNotifications { it.startsWith(newRoot.pathPrefix) } } private fun remove(rootPath: String) { val removed = roots.remove(rootPath) if (removed is Imported) { removeData(rootPath) updater.invalidateAndCommit() } updateNotifications { it.startsWith(rootPath) } } private fun removeData(rootPath: String) { val buildRoot = LocalFileSystem.getInstance().findFileByPath(rootPath) if (buildRoot != null) { GradleBuildRootDataSerializer.remove(buildRoot) LastModifiedFiles.remove(buildRoot) } } @Suppress("MemberVisibilityCanBePrivate") fun updateNotifications( restartAnalyzer: Boolean = true, shouldUpdatePath: (String) -> Boolean ) { if (!project.isOpen) return // import notification is a balloon, so should be shown only for selected editor FileEditorManager.getInstance(project).selectedEditor?.file?.let { if (shouldUpdatePath(it.path) && maybeAffectedGradleProjectFile(it.path)) { updateFloatingAction(it) } } val openedScripts = FileEditorManager.getInstance(project).selectedEditors .mapNotNull { it.file } .filter { shouldUpdatePath(it.path) && maybeAffectedGradleProjectFile(it.path) } if (openedScripts.isEmpty()) return GlobalScope.launch(EDT(project)) { if (project.isDisposed) return@launch openedScripts.forEach { if (isApplicable(it)) { DefaultScriptingSupport.getInstance(project).ensureNotificationsRemoved(it) } if (restartAnalyzer) { // this required only for "pause" state val ktFile = PsiManager.getInstance(project).findFile(it) if (ktFile != null) DaemonCodeAnalyzer.getInstance(project).restart(ktFile) } EditorNotifications.getInstance(project).updateAllNotifications() } } } private fun updateFloatingAction(file: VirtualFile) { if (isConfigurationOutOfDate(file)) { scriptConfigurationsNeedToBeUpdated(project, file) } else { scriptConfigurationsAreUpToDate(project) } } private fun loadStandaloneScriptConfigurations(files: MutableSet<String>) { runReadAction { files.forEach { val virtualFile = LocalFileSystem.getInstance().findFileByPath(it) if (virtualFile != null) { val ktFile = PsiManager.getInstance(project).findFile(virtualFile) as? KtFile if (ktFile != null) { DefaultScriptingSupport.getInstance(project) .ensureUpToDatedConfigurationSuggested(ktFile, skipNotification = true) } } } } } companion object { fun getInstanceSafe(project: Project): GradleBuildRootsManager = ScriptingSupport.EPN.findExtensionOrFail(GradleBuildRootsManager::class.java, project) fun getInstance(project: Project): GradleBuildRootsManager? = ScriptingSupport.EPN.findExtension(GradleBuildRootsManager::class.java, project) } }
apache-2.0
627dabc159e866d26553d47069b3c7fa
38.951064
158
0.668726
5.15258
false
false
false
false
jwren/intellij-community
platform/execution-impl/src/com/intellij/execution/ui/RunContentManagerImpl.kt
1
29467
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplacePutWithAssignment") package com.intellij.execution.ui import com.intellij.execution.ExecutionBundle import com.intellij.execution.Executor import com.intellij.execution.KillableProcess import com.intellij.execution.RunnerAndConfigurationSettings import com.intellij.execution.configurations.RunConfiguration import com.intellij.execution.dashboard.RunDashboardManager import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.execution.process.ProcessAdapter import com.intellij.execution.process.ProcessEvent import com.intellij.execution.process.ProcessHandler import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.runners.ExecutionUtil import com.intellij.execution.ui.layout.impl.DockableGridContainerFactory import com.intellij.ide.plugins.DynamicPluginListener import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.actionSystem.PlatformCoreDataKeys import com.intellij.openapi.application.AppUIExecutor import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.serviceIfCreated import com.intellij.openapi.options.advanced.AdvancedSettings import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.Key import com.intellij.openapi.util.ScalableIcon import com.intellij.openapi.wm.RegisterToolWindowTask import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.ex.ToolWindowManagerListener import com.intellij.openapi.wm.impl.content.ToolWindowContentUi import com.intellij.ui.AppUIUtil import com.intellij.ui.ExperimentalUI import com.intellij.ui.IconManager import com.intellij.ui.content.* import com.intellij.ui.content.Content.CLOSE_LISTENER_KEY import com.intellij.ui.content.impl.ContentManagerImpl import com.intellij.ui.docking.DockManager import com.intellij.util.ObjectUtils import com.intellij.util.SmartList import com.intellij.util.ui.EmptyIcon import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.ApiStatus import java.awt.KeyboardFocusManager import java.util.concurrent.ConcurrentLinkedDeque import java.util.function.Predicate import javax.swing.Icon private val EXECUTOR_KEY: Key<Executor> = Key.create("Executor") class RunContentManagerImpl(private val project: Project) : RunContentManager { private val toolWindowIdToBaseIcon: MutableMap<String, Icon> = HashMap() private val toolWindowIdZBuffer = ConcurrentLinkedDeque<String>() init { val containerFactory = DockableGridContainerFactory() DockManager.getInstance(project).register(DockableGridContainerFactory.TYPE, containerFactory, project) AppUIExecutor.onUiThread().expireWith(project).submit { init() } } companion object { @JvmField val ALWAYS_USE_DEFAULT_STOPPING_BEHAVIOUR_KEY = Key.create<Boolean>("ALWAYS_USE_DEFAULT_STOPPING_BEHAVIOUR_KEY") @ApiStatus.Internal @JvmField val TEMPORARY_CONFIGURATION_KEY = Key.create<RunnerAndConfigurationSettings>("TemporaryConfiguration") @JvmStatic fun copyContentAndBehavior(descriptor: RunContentDescriptor, contentToReuse: RunContentDescriptor?) { if (contentToReuse != null) { val attachedContent = contentToReuse.attachedContent if (attachedContent != null && attachedContent.isValid) { descriptor.setAttachedContent(attachedContent) } if (contentToReuse.isReuseToolWindowActivation) { descriptor.isActivateToolWindowWhenAdded = contentToReuse.isActivateToolWindowWhenAdded } if (descriptor.processHandler?.getUserData(RunContentDescriptor.CONTENT_TOOL_WINDOW_ID_KEY) == null) { descriptor.contentToolWindowId = contentToReuse.contentToolWindowId } descriptor.isSelectContentWhenAdded = contentToReuse.isSelectContentWhenAdded } } @JvmStatic fun isTerminated(content: Content): Boolean { val processHandler = getRunContentDescriptorByContent(content)?.processHandler ?: return true return processHandler.isProcessTerminated } @JvmStatic fun getRunContentDescriptorByContent(content: Content): RunContentDescriptor? { return content.getUserData(RunContentDescriptor.DESCRIPTOR_KEY) } @JvmStatic fun getExecutorByContent(content: Content): Executor? = content.getUserData(EXECUTOR_KEY) @JvmStatic fun getLiveIndicator(icon: Icon?): Icon = when (ExperimentalUI.isNewUI()) { true -> IconManager.getInstance().withIconBadge(icon ?: EmptyIcon.ICON_13, JBUI.CurrentTheme.IconBadge.SUCCESS) else -> ExecutionUtil.getLiveIndicator(icon) } } // must be called on EDT private fun init() { val messageBusConnection = project.messageBus.connect() messageBusConnection.subscribe(ToolWindowManagerListener.TOPIC, object : ToolWindowManagerListener { override fun stateChanged(toolWindowManager: ToolWindowManager) { toolWindowIdZBuffer.retainAll(toolWindowManager.toolWindowIdSet) val activeToolWindowId = toolWindowManager.activeToolWindowId if (activeToolWindowId != null && toolWindowIdZBuffer.remove(activeToolWindowId)) { toolWindowIdZBuffer.addFirst(activeToolWindowId) } } }) messageBusConnection.subscribe(DynamicPluginListener.TOPIC, object : DynamicPluginListener { override fun beforePluginUnload(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean) { processToolWindowContentManagers { _, contentManager -> val contents = contentManager.contents for (content in contents) { val runContentDescriptor = getRunContentDescriptorByContent(content) ?: continue if (runContentDescriptor.processHandler?.isProcessTerminated == true) { contentManager.removeContent(content, true) } } } } }) } @ApiStatus.Internal fun registerToolWindow(executor: Executor): ContentManager { val toolWindowManager = getToolWindowManager() val toolWindowId = executor.toolWindowId var toolWindow = toolWindowManager.getToolWindow(toolWindowId) if (toolWindow != null) { return toolWindow.contentManager } toolWindow = toolWindowManager.registerToolWindow(RegisterToolWindowTask( id = toolWindowId, icon = executor.toolWindowIcon, stripeTitle = executor::getActionName )) toolWindow.setToHideOnEmptyContent(true) if (DefaultRunExecutor.EXECUTOR_ID == executor.id) { toolWindow.component.putClientProperty(ToolWindowContentUi.ALLOW_DND_FOR_TABS, true) } val contentManager = toolWindow.contentManager contentManager.addDataProvider(object : DataProvider { override fun getData(dataId: String): Any? { if (PlatformCoreDataKeys.HELP_ID.`is`(dataId)) { return executor.helpId } return null } }) initToolWindow(executor, toolWindowId, executor.toolWindowIcon, contentManager) return contentManager } private fun initToolWindow(executor: Executor?, toolWindowId: String, toolWindowIcon: Icon, contentManager: ContentManager) { toolWindowIdToBaseIcon.put(toolWindowId, toolWindowIcon) contentManager.addContentManagerListener(object : ContentManagerListener { override fun selectionChanged(event: ContentManagerEvent) { if (event.operation != ContentManagerEvent.ContentOperation.add) { return } val content = event.content // Content manager contains contents related with different executors. // Try to get executor from content. // Must contain this user data since all content is added by this class. val contentExecutor = executor ?: getExecutorByContent(content)!! syncPublisher.contentSelected(getRunContentDescriptorByContent(content), contentExecutor) content.helpId = contentExecutor.helpId } }) Disposer.register(contentManager, Disposable { contentManager.removeAllContents(true) toolWindowIdZBuffer.remove(toolWindowId) toolWindowIdToBaseIcon.remove(toolWindowId) }) toolWindowIdZBuffer.addLast(toolWindowId) } private val syncPublisher: RunContentWithExecutorListener get() = project.messageBus.syncPublisher(RunContentManager.TOPIC) override fun toFrontRunContent(requestor: Executor, handler: ProcessHandler) { val descriptor = getDescriptorBy(handler, requestor) ?: return toFrontRunContent(requestor, descriptor) } override fun toFrontRunContent(requestor: Executor, descriptor: RunContentDescriptor) { ApplicationManager.getApplication().invokeLater(Runnable { val contentManager = getContentManagerForRunner(requestor, descriptor) val content = getRunContentByDescriptor(contentManager, descriptor) if (content != null) { contentManager.setSelectedContent(content) getToolWindowManager().getToolWindow(getToolWindowIdForRunner(requestor, descriptor))!!.show(null) } }, project.disposed) } override fun hideRunContent(executor: Executor, descriptor: RunContentDescriptor) { ApplicationManager.getApplication().invokeLater(Runnable { val toolWindow = getToolWindowManager().getToolWindow(getToolWindowIdForRunner(executor, descriptor)) toolWindow?.hide(null) }, project.disposed) } override fun getSelectedContent(): RunContentDescriptor? { for (activeWindow in toolWindowIdZBuffer) { val contentManager = getContentManagerByToolWindowId(activeWindow) ?: continue val selectedContent = contentManager.selectedContent ?: if (contentManager.contentCount == 0) { // continue to the next window if the content manager is empty continue } else { // stop iteration over windows because there is some content in the window and the window is the last used one break } // here we have selected content return getRunContentDescriptorByContent(selectedContent) } return null } override fun removeRunContent(executor: Executor, descriptor: RunContentDescriptor): Boolean { val contentManager = getContentManagerForRunner(executor, descriptor) val content = getRunContentByDescriptor(contentManager, descriptor) return content != null && contentManager.removeContent(content, true) } override fun showRunContent(executor: Executor, descriptor: RunContentDescriptor) { showRunContent(executor, descriptor, descriptor.executionId) } private fun showRunContent(executor: Executor, descriptor: RunContentDescriptor, executionId: Long) { if (ApplicationManager.getApplication().isUnitTestMode) { return } val contentManager = getContentManagerForRunner(executor, descriptor) val toolWindowId = getToolWindowIdForRunner(executor, descriptor) val oldDescriptor = chooseReuseContentForDescriptor(contentManager, descriptor, executionId, descriptor.displayName, getReuseCondition(toolWindowId)) val content: Content? if (oldDescriptor == null) { content = createNewContent(descriptor, executor) } else { content = oldDescriptor.attachedContent!! syncPublisher.contentRemoved(oldDescriptor, executor) Disposer.dispose(oldDescriptor) // is of the same category, can be reused } content.executionId = executionId content.component = descriptor.component content.setPreferredFocusedComponent(descriptor.preferredFocusComputable) content.putUserData(RunContentDescriptor.DESCRIPTOR_KEY, descriptor) content.putUserData(EXECUTOR_KEY, executor) content.displayName = descriptor.displayName descriptor.setAttachedContent(content) val toolWindow = getToolWindowManager().getToolWindow(toolWindowId) val processHandler = descriptor.processHandler if (processHandler != null) { val processAdapter = object : ProcessAdapter() { override fun startNotified(event: ProcessEvent) { UIUtil.invokeLaterIfNeeded { content.icon = getLiveIndicator(descriptor.icon) var icon = toolWindowIdToBaseIcon[toolWindowId] if (ExperimentalUI.isNewUI() && icon is ScalableIcon) { icon = IconLoader.loadCustomVersionOrScale(icon, 20f) } toolWindow!!.setIcon(getLiveIndicator(icon)) } } override fun processTerminated(event: ProcessEvent) { AppUIUtil.invokeLaterIfProjectAlive(project) { val manager = getContentManagerByToolWindowId(toolWindowId) ?: return@invokeLaterIfProjectAlive val alive = isAlive(manager) setToolWindowIcon(alive, toolWindow!!) val icon = descriptor.icon content.icon = if (icon == null) executor.disabledIcon else IconLoader.getTransparentIcon(icon) } } } processHandler.addProcessListener(processAdapter) val disposer = content.disposer if (disposer != null) { Disposer.register(disposer, Disposable { processHandler.removeProcessListener(processAdapter) }) } } if (oldDescriptor == null) { contentManager.addContent(content) content.putUserData(CLOSE_LISTENER_KEY, CloseListener(content, executor)) } if (descriptor.isSelectContentWhenAdded /* also update selection when reused content is already selected */ || oldDescriptor != null && content.manager!!.isSelected(content)) { content.manager!!.setSelectedContent(content) } if (!descriptor.isActivateToolWindowWhenAdded) { return } ApplicationManager.getApplication().invokeLater(Runnable { // let's activate tool window, but don't move focus // // window.show() isn't valid here, because it will not // mark the window as "last activated" windows and thus // some action like navigation up/down in stacktrace wont // work correctly var focus = descriptor.isAutoFocusContent if (KeyboardFocusManager.getCurrentKeyboardFocusManager().focusOwner == null) { // This is to cover the case, when the focus was in Run tool window already, // and it was reset due to us replacing tool window content. // We're restoring focus in the tool window in this case. // It shouldn't harm in any case - having no focused component isn't useful at all. focus = true } getToolWindowManager().getToolWindow(toolWindowId)!!.activate(descriptor.activationCallback, focus, focus) }, project.disposed) } private fun getContentManagerByToolWindowId(toolWindowId: String): ContentManager? { project.serviceIfCreated<RunDashboardManager>()?.let { if (it.toolWindowId == toolWindowId) { return if (toolWindowIdToBaseIcon.contains(toolWindowId)) it.dashboardContentManager else null } } return getToolWindowManager().getToolWindow(toolWindowId)?.contentManagerIfCreated } override fun getReuseContent(executionEnvironment: ExecutionEnvironment): RunContentDescriptor? { if (ApplicationManager.getApplication().isUnitTestMode) { return null } val contentToReuse = executionEnvironment.contentToReuse if (contentToReuse != null) { return contentToReuse } val toolWindowId = getContentDescriptorToolWindowId(executionEnvironment) val reuseCondition: Predicate<Content>? val contentManager: ContentManager if (toolWindowId == null) { contentManager = getContentManagerForRunner(executionEnvironment.executor, null) reuseCondition = null } else { contentManager = getOrCreateContentManagerForToolWindow(toolWindowId, executionEnvironment.executor) reuseCondition = getReuseCondition(toolWindowId) } return chooseReuseContentForDescriptor(contentManager, null, executionEnvironment.executionId, executionEnvironment.toString(), reuseCondition) } private fun getReuseCondition(toolWindowId: String): Predicate<Content>? { val runDashboardManager = RunDashboardManager.getInstance(project) return if (runDashboardManager.toolWindowId == toolWindowId) runDashboardManager.reuseCondition else null } override fun findContentDescriptor(requestor: Executor, handler: ProcessHandler): RunContentDescriptor? { return getDescriptorBy(handler, requestor) } override fun showRunContent(info: Executor, descriptor: RunContentDescriptor, contentToReuse: RunContentDescriptor?) { copyContentAndBehavior(descriptor, contentToReuse) showRunContent(info, descriptor, descriptor.executionId) } private fun getContentManagerForRunner(executor: Executor, descriptor: RunContentDescriptor?): ContentManager { return descriptor?.attachedContent?.manager ?: getOrCreateContentManagerForToolWindow(getToolWindowIdForRunner(executor, descriptor), executor) } private fun getOrCreateContentManagerForToolWindow(id: String, executor: Executor): ContentManager { val contentManager = getContentManagerByToolWindowId(id) if (contentManager != null) { updateToolWindowDecoration(id, executor) return contentManager } val dashboardManager = RunDashboardManager.getInstance(project) if (dashboardManager.toolWindowId == id) { initToolWindow(null, dashboardManager.toolWindowId, dashboardManager.toolWindowIcon, dashboardManager.dashboardContentManager) return dashboardManager.dashboardContentManager } else { return registerToolWindow(executor) } } override fun getToolWindowByDescriptor(descriptor: RunContentDescriptor): ToolWindow? { descriptor.contentToolWindowId?.let { return getToolWindowManager().getToolWindow(it) } processToolWindowContentManagers { toolWindow, contentManager -> if (getRunContentByDescriptor(contentManager, descriptor) != null) { return toolWindow } } return null } private fun updateToolWindowDecoration(id: String, executor: Executor) { if (project.serviceIfCreated<RunDashboardManager>()?.toolWindowId == id) { return } getToolWindowManager().getToolWindow(id)?.apply { stripeTitle = executor.actionName setIcon(executor.toolWindowIcon) toolWindowIdToBaseIcon[id] = executor.toolWindowIcon } } private inline fun processToolWindowContentManagers(processor: (ToolWindow, ContentManager) -> Unit) { val toolWindowManager = getToolWindowManager() for (executor in Executor.EXECUTOR_EXTENSION_NAME.extensionList) { val toolWindow = toolWindowManager.getToolWindow(executor.id) ?: continue processor(toolWindow, toolWindow.contentManagerIfCreated ?: continue) } project.serviceIfCreated<RunDashboardManager>()?.let { val toolWindowId = it.toolWindowId if (toolWindowIdToBaseIcon.contains(toolWindowId)) { processor(toolWindowManager.getToolWindow(toolWindowId) ?: return, it.dashboardContentManager) } } } override fun getAllDescriptors(): List<RunContentDescriptor> { val descriptors: MutableList<RunContentDescriptor> = SmartList() processToolWindowContentManagers { _, contentManager -> for (content in contentManager.contents) { getRunContentDescriptorByContent(content)?.let { descriptors.add(it) } } } return descriptors } override fun selectRunContent(descriptor: RunContentDescriptor) { processToolWindowContentManagers { _, contentManager -> val content = getRunContentByDescriptor(contentManager, descriptor) ?: return@processToolWindowContentManagers contentManager.setSelectedContent(content) return } } private fun getToolWindowManager() = ToolWindowManager.getInstance(project) override fun getContentDescriptorToolWindowId(configuration: RunConfiguration?): String? { if (configuration != null) { val runDashboardManager = RunDashboardManager.getInstance(project) if (runDashboardManager.isShowInDashboard(configuration)) { return runDashboardManager.toolWindowId } } return null } override fun getToolWindowIdByEnvironment(executionEnvironment: ExecutionEnvironment): String { // Also there are some places where ToolWindowId.RUN or ToolWindowId.DEBUG are used directly. // For example, HotSwapProgressImpl.NOTIFICATION_GROUP. All notifications for this group is shown in Debug tool window, // however such notifications should be shown in Run Dashboard tool window, if run content is redirected to Run Dashboard tool window. val toolWindowId = getContentDescriptorToolWindowId(executionEnvironment) return toolWindowId ?: executionEnvironment.executor.toolWindowId } private fun getDescriptorBy(handler: ProcessHandler, runnerInfo: Executor): RunContentDescriptor? { fun find(manager: ContentManager?): RunContentDescriptor? { if (manager == null) return null val contents = if (manager is ContentManagerImpl) { manager.contentsRecursively } else { manager.contents.toList() } for (content in contents) { val runContentDescriptor = getRunContentDescriptorByContent(content) if (runContentDescriptor?.processHandler === handler) { return runContentDescriptor } } return null } find(getContentManagerForRunner(runnerInfo, null))?.let { return it } find(getContentManagerByToolWindowId(project.serviceIfCreated<RunDashboardManager>()?.toolWindowId ?: return null) ?: return null)?.let { return it } return null } fun moveContent(executor: Executor, descriptor: RunContentDescriptor) { val content = descriptor.attachedContent ?: return val oldContentManager = content.manager val newContentManager = getOrCreateContentManagerForToolWindow(getToolWindowIdForRunner(executor, descriptor), executor) if (oldContentManager == null || oldContentManager === newContentManager) return val listener = content.getUserData(CLOSE_LISTENER_KEY) if (listener != null) { oldContentManager.removeContentManagerListener(listener) } oldContentManager.removeContent(content, false) if (isAlive(descriptor)) { if (!isAlive(oldContentManager)) { updateToolWindowIcon(oldContentManager, false) } if (!isAlive(newContentManager)) { updateToolWindowIcon(newContentManager, true) } } newContentManager.addContent(content) // Close listener is added to new content manager by propertyChangeListener in BaseContentCloseListener. } private fun updateToolWindowIcon(contentManagerToUpdate: ContentManager, alive: Boolean) { processToolWindowContentManagers { toolWindow, contentManager -> if (contentManagerToUpdate == contentManager) { setToolWindowIcon(alive, toolWindow) return } } } private fun setToolWindowIcon(alive: Boolean, toolWindow: ToolWindow) { val base = toolWindowIdToBaseIcon.get(toolWindow.id) toolWindow.setIcon(if (alive) getLiveIndicator(base) else ObjectUtils.notNull(base, EmptyIcon.ICON_13)) } private inner class CloseListener(content: Content, private val myExecutor: Executor) : BaseContentCloseListener(content, project) { override fun disposeContent(content: Content) { try { val descriptor = getRunContentDescriptorByContent(content) syncPublisher.contentRemoved(descriptor, myExecutor) if (descriptor != null) { Disposer.dispose(descriptor) } } finally { content.release() } } override fun closeQuery(content: Content, projectClosing: Boolean): Boolean { val descriptor = getRunContentDescriptorByContent(content) ?: return true if (Content.TEMPORARY_REMOVED_KEY.get(content, false)) return true val processHandler = descriptor.processHandler if (processHandler == null || processHandler.isProcessTerminated) { return true } val sessionName = descriptor.displayName val killable = processHandler is KillableProcess && (processHandler as KillableProcess).canKillProcess() val task = object : WaitForProcessTask(processHandler, sessionName, projectClosing, project) { override fun onCancel() { if (killable && !processHandler.isProcessTerminated) { (processHandler as KillableProcess).killProcess() } } } if (killable) { val cancelText = ExecutionBundle.message("terminating.process.progress.kill") task.cancelText = cancelText task.cancelTooltipText = cancelText } return askUserAndWait(processHandler, sessionName, task) } } } private fun chooseReuseContentForDescriptor(contentManager: ContentManager, descriptor: RunContentDescriptor?, executionId: Long, preferredName: String?, reuseCondition: Predicate<in Content>?): RunContentDescriptor? { var content: Content? = null if (descriptor != null) { //Stage one: some specific descriptors (like AnalyzeStacktrace) cannot be reused at all if (descriptor.isContentReuseProhibited) { return null } // stage two: try to get content from descriptor itself val attachedContent = descriptor.attachedContent if (attachedContent != null && attachedContent.isValid && (descriptor.displayName == attachedContent.displayName || !attachedContent.isPinned)) { val contents = if (contentManager is ContentManagerImpl) { contentManager.contentsRecursively } else { contentManager.contents.toList() } if (contents.contains(attachedContent)) { content = attachedContent } } } // stage three: choose the content with name we prefer if (content == null) { content = getContentFromManager(contentManager, preferredName, executionId, reuseCondition) } if (content == null || !RunContentManagerImpl.isTerminated(content) || content.executionId == executionId && executionId != 0L) { return null } val oldDescriptor = RunContentManagerImpl.getRunContentDescriptorByContent(content) ?: return null if (oldDescriptor.isContentReuseProhibited) { return null } if (descriptor == null || oldDescriptor.reusePolicy.canBeReusedBy(descriptor)) { return oldDescriptor } return null } private fun getContentFromManager(contentManager: ContentManager, preferredName: String?, executionId: Long, reuseCondition: Predicate<in Content>?): Content? { val contents = if (contentManager is ContentManagerImpl) { contentManager.contentsRecursively } else { contentManager.contents.toMutableList() } val first = contentManager.selectedContent if (first != null && contents.remove(first)) { //selected content should be checked first contents.add(0, first) } if (preferredName != null) { // try to match content with specified preferred name for (c in contents) { if (canReuseContent(c, executionId) && preferredName == c.displayName) { return c } } } // return first "good" content return contents.firstOrNull { canReuseContent(it, executionId) && (reuseCondition == null || reuseCondition.test(it)) } } private fun canReuseContent(c: Content, executionId: Long): Boolean { return !c.isPinned && RunContentManagerImpl.isTerminated(c) && !(c.executionId == executionId && executionId != 0L) } private fun getToolWindowIdForRunner(executor: Executor, descriptor: RunContentDescriptor?): String { return descriptor?.contentToolWindowId ?: executor.toolWindowId } private fun createNewContent(descriptor: RunContentDescriptor, executor: Executor): Content { val content = ContentFactory.SERVICE.getInstance().createContent(descriptor.component, descriptor.displayName, true) content.putUserData(ToolWindow.SHOW_CONTENT_ICON, java.lang.Boolean.TRUE) if (AdvancedSettings.getBoolean("start.run.configurations.pinned")) content.isPinned = true content.icon = descriptor.icon ?: executor.toolWindowIcon return content } private fun getRunContentByDescriptor(contentManager: ContentManager, descriptor: RunContentDescriptor): Content? { return contentManager.contents.firstOrNull { descriptor == RunContentManagerImpl.getRunContentDescriptorByContent(it) } } private fun isAlive(contentManager: ContentManager): Boolean { return contentManager.contents.any { val descriptor = RunContentManagerImpl.getRunContentDescriptorByContent(it) descriptor != null && isAlive(descriptor) } } private fun isAlive(descriptor: RunContentDescriptor): Boolean { val handler = descriptor.processHandler return handler != null && !handler.isProcessTerminated }
apache-2.0
86cfea27ee48328687f091b7cd35a10b
41.217765
153
0.733125
5.311283
false
false
false
false
jwren/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/builder/components/DslLabel.kt
1
6093
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.dsl.builder.components import com.intellij.lang.documentation.DocumentationMarkup.EXTERNAL_LINK_ICON import com.intellij.openapi.ui.panel.ComponentPanelBuilder import com.intellij.openapi.util.text.HtmlBuilder import com.intellij.openapi.util.text.HtmlChunk import com.intellij.ui.ColorUtil import com.intellij.ui.dsl.UiDslException import com.intellij.ui.dsl.builder.HyperlinkEventAction import com.intellij.ui.dsl.builder.MAX_LINE_LENGTH_NO_WRAP import com.intellij.util.ui.HTMLEditorKitBuilder import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import java.awt.Dimension import javax.swing.JEditorPane import javax.swing.event.HyperlinkEvent import javax.swing.text.DefaultCaret /** * Denied content and reasons */ private val DENIED_TAGS = mapOf( Regex("<html>", RegexOption.IGNORE_CASE) to "tag <html> inserted automatically and shouldn't be used", Regex("<body>", RegexOption.IGNORE_CASE) to "tag <body> inserted automatically and shouldn't be used", Regex("""<a\s+href\s*=\s*(""|'')\s*>""", RegexOption.IGNORE_CASE) to "empty href like <a href=''> is denied, use <a> instead", ) private const val LINK_GROUP = "link" private val BROWSER_LINK_REGEX = Regex("""<a\s+href\s*=\s*['"]?(?<href>https?://[^>'"]*)['"]?\s*>(?<link>[^<]*)</a>""", setOf(RegexOption.DOT_MATCHES_ALL, RegexOption.IGNORE_CASE)) @ApiStatus.Internal enum class DslLabelType { LABEL, COMMENT } @ApiStatus.Internal class DslLabel(private val type: DslLabelType) : JEditorPane() { var action: HyperlinkEventAction? = null var maxLineLength: Int = MAX_LINE_LENGTH_NO_WRAP set(value) { field = value updateEditorPaneText() } @Nls private var userText: String? = null init { contentType = UIUtil.HTML_MIME editorKit = HTMLEditorKitBuilder().build() // JEditorPane.setText updates cursor and requests scrolling to cursor position if scrollable is used. Disable it (caret as DefaultCaret).updatePolicy = DefaultCaret.NEVER_UPDATE foreground = when (type) { DslLabelType.COMMENT -> JBUI.CurrentTheme.ContextHelp.FOREGROUND DslLabelType.LABEL -> JBUI.CurrentTheme.Label.foreground() } addHyperlinkListener { e -> when (e?.eventType) { HyperlinkEvent.EventType.ACTIVATED -> action?.hyperlinkActivated(e) HyperlinkEvent.EventType.ENTERED -> action?.hyperlinkEntered(e) HyperlinkEvent.EventType.EXITED -> action?.hyperlinkExited(e) } } patchFont() } override fun updateUI() { super.updateUI() isFocusable = false isEditable = false border = null background = UIUtil.TRANSPARENT_COLOR isOpaque = false patchFont() } override fun getBaseline(width: Int, height: Int): Int { // JEditorPane doesn't support baseline, calculate it manually from font val fontMetrics = getFontMetrics(font) return fontMetrics.ascent } override fun setText(@Nls t: String?) { userText = t updateEditorPaneText() } private fun updateEditorPaneText() { val text = userText if (text == null) { super.setText(null) return } for ((regex, reason) in DENIED_TAGS) { if (regex.find(text, 0) != null) { UiDslException.error("Invalid html: $reason, text: $text") } } @Suppress("HardCodedStringLiteral") var processedText = text.replace("<a>", "<a href=''>", ignoreCase = true) processedText = appendExternalLinkIcons(processedText) var body = HtmlChunk.body() if (maxLineLength > 0 && maxLineLength != MAX_LINE_LENGTH_NO_WRAP && text.length > maxLineLength) { val width = getFontMetrics(font).stringWidth(text.substring(0, maxLineLength)) body = body.attr("width", width) } @NonNls val css = createCss(maxLineLength != MAX_LINE_LENGTH_NO_WRAP) super.setText(HtmlBuilder() .append(HtmlChunk.raw(css)) .append(HtmlChunk.raw(processedText).wrapWith(body)) .wrapWith(HtmlChunk.html()) .toString()) // There is a bug in JDK: if JEditorPane gets height = 0 (text is null) then it never gets correct preferred size afterwards // Below is a simple workaround to fix that, see details in BasicTextUI.getPreferredSize // See also https://stackoverflow.com/questions/49273118/jeditorpane-getpreferredsize-not-always-working-in-java-9 size = Dimension(0, 0) } @Nls private fun appendExternalLinkIcons(@Nls text: String): String { val matchers = BROWSER_LINK_REGEX.findAll(text) if (!matchers.any()) { return text } val result = StringBuilder() val externalLink = EXTERNAL_LINK_ICON.toString() var i = 0 for (matcher in matchers) { val linkEnd = matcher.groups[LINK_GROUP]!!.range.last result.append(text.substring(i..linkEnd)) result.append(externalLink) i = linkEnd + 1 } result.append(text.substring(i)) @Suppress("HardCodedStringLiteral") return result.toString() } private fun patchFont() { if (type == DslLabelType.COMMENT) { font = ComponentPanelBuilder.getCommentFont(font) } } private fun createCss(wordWrap: Boolean): String { val styles = mutableListOf( "a, a:link {color:#${ColorUtil.toHex(JBUI.CurrentTheme.Link.Foreground.ENABLED)};}", "a:visited {color:#${ColorUtil.toHex(JBUI.CurrentTheme.Link.Foreground.VISITED)};}", "a:hover {color:#${ColorUtil.toHex(JBUI.CurrentTheme.Link.Foreground.HOVERED)};}", "a:active {color:#${ColorUtil.toHex(JBUI.CurrentTheme.Link.Foreground.PRESSED)};}" ) if (!wordWrap) { styles.add("body, p {white-space:nowrap;}") } return styles.joinToString(" ", "<head><style type='text/css'>", "</style></head>") } }
apache-2.0
c647bae4e2d01e7b299e6d033b443454
33.230337
158
0.687018
4.067423
false
false
false
false
mickele/DBFlow
dbflow-processor/src/main/java/com/raizlabs/android/dbflow/processor/definition/TypeConverterDefinition.kt
1
1474
package com.raizlabs.android.dbflow.processor.definition import com.raizlabs.android.dbflow.processor.ClassNames import com.raizlabs.android.dbflow.processor.ProcessorManager import com.squareup.javapoet.ClassName import com.squareup.javapoet.TypeName import javax.lang.model.type.DeclaredType import javax.lang.model.type.TypeMirror /** * Description: Holds data about type converters in order to write them. */ class TypeConverterDefinition(val className: ClassName, typeMirror: TypeMirror, manager: ProcessorManager) { var modelTypeName: TypeName? = null private set var dbTypeName: TypeName? = null private set init { val types = manager.typeUtils var typeConverterSuper: DeclaredType? = null val typeConverter = manager.typeUtils.getDeclaredType(manager.elements .getTypeElement(ClassNames.TYPE_CONVERTER.toString())) for (superType in types.directSupertypes(typeMirror)) { val erasure = types.erasure(superType) if (types.isAssignable(erasure, typeConverter) || erasure.toString() == typeConverter.toString()) { typeConverterSuper = superType as DeclaredType } } if (typeConverterSuper != null) { val typeArgs = typeConverterSuper.typeArguments dbTypeName = ClassName.get(typeArgs[0]) modelTypeName = ClassName.get(typeArgs[1]) } } }
mit
6219809a21f0a68ed82df9d6b144e680
32.5
111
0.683853
4.97973
false
false
false
false
DSteve595/Put.io
app/src/main/java/com/stevenschoen/putionew/transfers/add/FromUrlFragment.kt
1
3043
package com.stevenschoen.putionew.transfers.add import android.app.Dialog import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CheckBox import android.widget.EditText import androidx.fragment.app.Fragment import com.jakewharton.rxbinding2.widget.RxTextView import com.stevenschoen.putionew.R import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.subjects.BehaviorSubject class FromUrlFragment : BaseFragment(R.id.addtransfer_link_destination_holder) { var callbacks: Callbacks? = null val link = BehaviorSubject.createDefault("") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState != null) { } else { if (arguments != null && arguments!!.containsKey(EXTRA_PRECHOSEN_LINK)) { link.onNext(arguments!!.getString(EXTRA_PRECHOSEN_LINK)) } } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { val view = inflater.inflate(R.layout.addtransfer_link, container, false) val linkView = view.findViewById<EditText>(R.id.addtransfer_link_url) RxTextView.textChanges(linkView) .subscribe { link.onNext(it.toString()) } if (savedInstanceState == null && arguments!!.containsKey(EXTRA_PRECHOSEN_LINK)) { linkView.setText(arguments!!.getString(EXTRA_PRECHOSEN_LINK)) } val clearLinkView = view.findViewById<View>(R.id.addtransfer_link_clear) clearLinkView.setOnClickListener { linkView.text = null } val extractView = view.findViewById<CheckBox>(R.id.addtransfer_link_extract) val addView = view.findViewById<View>(R.id.addtransfer_link_add) addView.setOnClickListener { callbacks?.onLinkSelected(link.value!!, extractView.isChecked) } val cancelView = view.findViewById<View>(R.id.addtransfer_link_cancel) cancelView.setOnClickListener { dismiss() } link.observeOn(AndroidSchedulers.mainThread()) .subscribe { newLink -> if (!newLink.isBlank()) { clearLinkView.visibility = View.VISIBLE addView.isEnabled = true } else { clearLinkView.visibility = View.GONE addView.isEnabled = false } } return view } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { return super.onCreateDialog(savedInstanceState).apply { setTitle(R.string.add_transfer) } } interface Callbacks { fun onLinkSelected(link: String, extract: Boolean) } companion object { const val EXTRA_PRECHOSEN_LINK = "link" fun newInstance(context: Context, preChosenLink: String?): FromUrlFragment { val args = Bundle() preChosenLink?.let { args.putString(EXTRA_PRECHOSEN_LINK, it) } return Fragment.instantiate(context, FromUrlFragment::class.java.name, args) as FromUrlFragment } } }
mit
08a3105d0cb86b2a75e577f92afecf99
30.05102
113
0.712126
4.267882
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ide/browsers/BrowserLauncherImpl.kt
7
4433
// 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.ide.browsers import com.intellij.CommonBundle import com.intellij.ide.IdeBundle import com.intellij.ide.impl.isTrusted import com.intellij.ide.impl.setTrusted import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.Disposable import com.intellij.openapi.application.AppUIExecutor import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageDialogBuilder import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.showOkNoDialog import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.registry.Registry import com.intellij.util.Urls import org.jetbrains.ide.BuiltInServerManager import java.net.URI open class BrowserLauncherImpl : BrowserLauncherAppless() { override fun getEffectiveBrowser(browser: WebBrowser?): WebBrowser? { var effectiveBrowser = browser if (browser == null) { // https://youtrack.jetbrains.com/issue/WEB-26547 val browserManager = WebBrowserManager.getInstance() if (browserManager.getDefaultBrowserPolicy() == DefaultBrowserPolicy.FIRST) { effectiveBrowser = browserManager.firstActiveBrowser } } return effectiveBrowser } override fun desktopBrowse(project: Project?, uri: URI): Boolean { if (!canBrowse(project, uri)) { return true // don't do anything else } return super.desktopBrowse(project, uri) } private fun canBrowse(project: Project?, uri: URI): Boolean { if (project == null || project.isTrusted()) { return true } val yesLabel = IdeBundle.message("external.link.confirmation.yes.label") val trustLabel = IdeBundle.message("external.link.confirmation.trust.label") val noLabel = CommonBundle.getCancelButtonText() val answer = MessageDialogBuilder .Message( title = IdeBundle.message("external.link.confirmation.title"), message = IdeBundle.message("external.link.confirmation.message.0", uri), ) .asWarning() .buttons(yesLabel, trustLabel, noLabel) .defaultButton(yesLabel) .focusedButton(trustLabel) .show(project) when (answer) { yesLabel -> { return true } trustLabel -> { project.setTrusted(true) return true } else -> { return false } } } override fun signUrl(url: String): String { @Suppress("NAME_SHADOWING") var url = url val serverManager = BuiltInServerManager.getInstance() val parsedUrl = Urls.parse(url, false) if (parsedUrl != null && serverManager.isOnBuiltInWebServer(parsedUrl)) { if (Registry.`is`("ide.built.in.web.server.activatable", false)) { PropertiesComponent.getInstance().setValue("ide.built.in.web.server.active", true) } url = serverManager.addAuthToken(parsedUrl).toExternalForm() } return url } override fun openWithExplicitBrowser(url: String, browserPath: String?, project: Project?) { val browserManager = WebBrowserManager.getInstance() if (browserManager.getDefaultBrowserPolicy() == DefaultBrowserPolicy.FIRST) { browserManager.firstActiveBrowser?.let { browse(url, it, project) return } } else if (SystemInfo.isMac && "open" == browserPath) { browserManager.firstActiveBrowser?.let { browseUsingPath(url, null, it, project) return } } super.openWithExplicitBrowser(url, browserPath, project) } override fun showError(@NlsContexts.DialogMessage error: String?, browser: WebBrowser?, project: Project?, @NlsContexts.DialogTitle title: String?, fix: (() -> Unit)?) { AppUIExecutor.onUiThread().expireWith(project ?: Disposable {}).submit { if (showOkNoDialog(title ?: IdeBundle.message("browser.error"), error ?: IdeBundle.message("unknown.error"), project, okText = IdeBundle.message("button.fix"), noText = Messages.getOkButton())) { val browserSettings = BrowserSettings() if (ShowSettingsUtil.getInstance().editConfigurable(project, browserSettings, browser?.let { Runnable { browserSettings.selectBrowser(it) } })) { fix?.invoke() } } } } }
apache-2.0
4db70279794b59f5f316c388e671568a
36.260504
171
0.699752
4.415339
false
false
false
false
dkrivoruchko/ScreenStream
common/src/main/kotlin/info/dvkr/screenstream/common/settings/AppSettings.kt
1
2017
package info.dvkr.screenstream.common.settings import android.os.Build import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.core.longPreferencesKey import kotlinx.coroutines.flow.Flow interface AppSettings { object Key { val NIGHT_MODE = intPreferencesKey("NIGHT_MODE") val KEEP_AWAKE = booleanPreferencesKey("KEEP_AWAKE") val STOP_ON_SLEEP = booleanPreferencesKey("TOP_ON_SLEEP") val START_ON_BOOT = booleanPreferencesKey("START_ON_BOOT") val AUTO_START_STOP = booleanPreferencesKey("AUTO_START_STOP") val LOGGING_VISIBLE = booleanPreferencesKey("LOGGING_VISIBLE") val LAST_UPDATE_REQUEST_MILLIS = longPreferencesKey("LAST_UPDATE_REQUEST_MILLIS") val ADD_TILE_ASKED = booleanPreferencesKey("ADD_TILE_ASKED") } object Default { var NIGHT_MODE = if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) 3 else -1 const val KEEP_AWAKE = false const val STOP_ON_SLEEP = false const val START_ON_BOOT = false const val AUTO_START_STOP = false const val LOGGING_VISIBLE = false const val LAST_IAU_REQUEST_TIMESTAMP = 0L const val ADD_TILE_ASKED = false } val nightModeFlow: Flow<Int> suspend fun setNightMode(value: Int) val keepAwakeFlow: Flow<Boolean> suspend fun setKeepAwake(value: Boolean) val stopOnSleepFlow: Flow<Boolean> suspend fun setStopOnSleep(value: Boolean) val startOnBootFlow: Flow<Boolean> suspend fun setStartOnBoot(value: Boolean) val autoStartStopFlow: Flow<Boolean> suspend fun setAutoStartStop(value: Boolean) val loggingVisibleFlow: Flow<Boolean> suspend fun setLoggingVisible(value: Boolean) val lastUpdateRequestMillisFlow: Flow<Long> suspend fun setLastUpdateRequestMillis(value: Long) val addTileAsked: Flow<Boolean> suspend fun setAddTileAsked(value: Boolean) }
mit
17296938819b29f4d5d9919d70c543a7
31.548387
89
0.723352
4.237395
false
false
false
false
jwren/intellij-community
plugins/kotlin/copyright/tests/test/org/jetbrains/kotlin/copyright/AbstractUpdateKotlinCopyrightTest.kt
4
1838
// 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.copyright import junit.framework.AssertionFailedError import org.jetbrains.kotlin.idea.copyright.UpdateKotlinCopyright import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils import org.junit.Assert abstract class AbstractUpdateKotlinCopyrightTest : KotlinLightCodeInsightFixtureTestCase() { fun doTest(@Suppress("UNUSED_PARAMETER") path: String) { myFixture.configureByFile(fileName()) val fileText = myFixture.file.text.trim() val expectedNumberOfComments = InTextDirectivesUtils.getPrefixedInt(fileText, "// COMMENTS: ") ?: run { if (fileText.isNotEmpty()) { throw AssertionFailedError("Every test should assert number of comments with `COMMENTS` directive") } else { 0 } } val comments = UpdateKotlinCopyright.getExistentComments(myFixture.file) for (comment in comments) { val commentText = comment.text when { commentText.contains("PRESENT") -> { } commentText.contains("ABSENT") -> { throw AssertionFailedError("Unexpected comment found: `$commentText`") } else -> { throw AssertionFailedError("A comment with bad directive found: `$commentText`") } } } Assert.assertEquals( "Wrong number of comments found:\n${comments.joinToString(separator = "\n") { it.text }}\n", expectedNumberOfComments, comments.size ) } }
apache-2.0
bad292e0ba1d1ae839e172e3c5d95d47
40.795455
158
0.644178
5.390029
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/jvm-debugger/util/src/org/jetbrains/kotlin/idea/debugger/kotlinMethodBytecodeInfo.kt
2
4630
// 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.debugger import com.intellij.debugger.jdi.MethodBytecodeUtil import com.sun.jdi.Method import org.jetbrains.org.objectweb.asm.Label import org.jetbrains.org.objectweb.asm.MethodVisitor import org.jetbrains.org.objectweb.asm.Opcodes fun Method.isSimpleGetter() = isSimpleMemberVariableGetter() || isSimpleStaticVariableGetter() || isJVMStaticVariableGetter() fun Method.isLateinitVariableGetter() = isOldBackendLateinitVariableGetter() || isIRBackendLateinitVariableGetter() fun Method.isOldBackendLateinitVariableGetter() = verifyMethod(14, intArrayOf( Opcodes.ALOAD, Opcodes.GETFIELD, Opcodes.DUP, Opcodes.IFNONNULL, Opcodes.LDC, Opcodes.INVOKESTATIC ) ) fun Method.isIRBackendLateinitVariableGetter() = verifyMethod(18, MethodBytecodeVerifierFromArray( intArrayOf( Opcodes.ALOAD, Opcodes.GETFIELD, Opcodes.ASTORE, Opcodes.ALOAD, Opcodes.IFNULL, Opcodes.ALOAD, Opcodes.ARETURN, Opcodes.LDC, Opcodes.INVOKESTATIC, Opcodes.ACONST_NULL, Opcodes.ATHROW ) ) ) private fun Method.isSimpleStaticVariableGetter() = verifyMethod(4, intArrayOf(Opcodes.GETSTATIC)) private fun Method.isSimpleMemberVariableGetter() = verifyMethod(5, intArrayOf(Opcodes.ALOAD, Opcodes.GETFIELD)) private fun Method.isJVMStaticVariableGetter() = verifyMethod(7, object : MethodBytecodeVerifier(3) { override fun verify(opcode: Int, position: Int) = when(position) { 0 -> opcode == Opcodes.GETSTATIC 1 -> opcode == Opcodes.GETSTATIC || opcode == Opcodes.INVOKEVIRTUAL 2 -> opcode.isReturnOpcode() else -> false } }) private fun Method.verifyMethod( expectedNumOfBytecodes: Int, opcodes: IntArray ) = verifyMethod(expectedNumOfBytecodes, MethodBytecodeVerifierWithReturnOpcode(opcodes)) private fun Method.verifyMethod( expectedNumOfBytecodes: Int, methodBytecodeVerifier: MethodBytecodeVerifier ): Boolean { if (bytecodes().size != expectedNumOfBytecodes) { return false } MethodBytecodeUtil.visit(this, methodBytecodeVerifier, false) return methodBytecodeVerifier.getResult() } private class MethodBytecodeVerifierWithReturnOpcode(val opcodes: IntArray) : MethodBytecodeVerifier(opcodes.size + 1) { override fun verify(opcode: Int, position: Int) = when { position > opcodes.size -> false position == opcodes.size -> opcode.isReturnOpcode() else -> opcode == opcodes[position] } } private class MethodBytecodeVerifierFromArray(val opcodes: IntArray) : MethodBytecodeVerifier(opcodes.size) { override fun verify(opcode: Int, position: Int) = when { position >= opcodes.size -> false else -> opcode == opcodes[position] } } private fun Int.isReturnOpcode() = this in Opcodes.IRETURN..Opcodes.ARETURN private abstract class MethodBytecodeVerifier(val expectedNumOfProcessedOpcodes: Int) : MethodVisitor(Opcodes.API_VERSION) { var processedOpcodes = 0 var opcodesMatched = true protected abstract fun verify(opcode: Int, position: Int): Boolean private fun visitOpcode(opcode: Int) { if (!verify(opcode, processedOpcodes)) { opcodesMatched = false } processedOpcodes += 1 } fun getResult() = opcodesMatched && processedOpcodes == expectedNumOfProcessedOpcodes override fun visitVarInsn(opcode: Int, variable: Int) = visitOpcode(opcode) override fun visitFieldInsn(opcode: Int, owner: String?, name: String?, descriptor: String?) = visitOpcode(opcode) override fun visitInsn(opcode: Int) = visitOpcode(opcode) override fun visitIntInsn(opcode: Int, operand: Int) = visitOpcode(opcode) override fun visitTypeInsn(opcode: Int, type: String?) = visitOpcode(opcode) override fun visitJumpInsn(opcode: Int, label: Label?) = visitOpcode(opcode) override fun visitLdcInsn(value: Any?) = visitOpcode(Opcodes.LDC) override fun visitMethodInsn( opcode: Int, owner: String?, name: String?, descriptor: String?, isInterface: Boolean ) = visitOpcode(opcode) }
apache-2.0
fdbae27adba52242d817624de7880fe9
34.343511
158
0.675594
4.451923
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/actions/ScratchAction.kt
4
1330
// 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.scratch.actions import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformCoreDataKeys import com.intellij.openapi.fileEditor.TextEditor import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.idea.scratch.ScratchFile import org.jetbrains.kotlin.idea.scratch.ui.KtScratchFileEditorWithPreview import org.jetbrains.kotlin.idea.scratch.ui.findScratchFileEditorWithPreview import javax.swing.Icon abstract class ScratchAction(@Nls message: String, icon: Icon) : AnAction(message, message, icon) { override fun update(e: AnActionEvent) { val scratchFile = e.currentScratchFile e.presentation.isVisible = scratchFile != null } protected val AnActionEvent.currentScratchFile: ScratchFile? get() = currentScratchEditor?.scratchFile protected val AnActionEvent.currentScratchEditor: KtScratchFileEditorWithPreview? get() { val textEditor = getData(PlatformCoreDataKeys.FILE_EDITOR) as? TextEditor return textEditor?.findScratchFileEditorWithPreview() } }
apache-2.0
a88f1c2b93b069b40c7fcc7f9333f1c2
43.366667
158
0.786466
4.699647
false
false
false
false
smmribeiro/intellij-community
java/java-impl/src/com/intellij/internal/statistic/libraryUsage/LibraryUsageStatisticsAction.kt
2
2265
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistic.libraryUsage import com.intellij.codeInsight.hint.HintManager import com.intellij.internal.statistic.libraryJar.findJarVersion import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.components.service import com.intellij.openapi.ui.Messages class LibraryUsageStatisticsAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val editor = e.getRequiredData(CommonDataKeys.EDITOR) val caretOffset = e.getRequiredData(CommonDataKeys.CARET).offset val psiFile = e.getRequiredData(CommonDataKeys.PSI_FILE) val fileType = psiFile.fileType fun showErrorHint(message: String): Unit = HintManager.getInstance().showErrorHint(editor, message) val processor = LibraryUsageImportProcessor.EP_NAME.findFirstSafe { it.isApplicable(fileType) } ?: return showErrorHint("LibraryUsageImportProcessor is not found for ${fileType.name} file type") val libraryDescriptorFinder = service<LibraryDescriptorFinderService>().cachedLibraryDescriptorFinder() ?: return showErrorHint("LibraryDescriptorFinder is not cached") val import = processor.imports(psiFile).find { caretOffset in it.textRange } ?: return showErrorHint("import at caret is not found") val qualifier = processor.importQualifier(import) ?: return showErrorHint("qualifier is null") val libraryName = libraryDescriptorFinder.findSuitableLibrary(qualifier) ?: return showErrorHint("suitable library in not found") val resolvedElement = processor.resolve(import) ?: return showErrorHint("failed to resolve") val libraryVersion = resolvedElement.let(::findJarVersion) ?: return showErrorHint("failed to find version") val libraryUsage = LibraryUsage( name = libraryName, version = libraryVersion, fileType = fileType, ) Messages.showInfoMessage(project, libraryUsage.toString(), "Library Info") } }
apache-2.0
8c876be6e6cb22262eb828b383c612d8
55.65
158
0.768212
5.022173
false
false
false
false
Heapy/komodo
komodo-core-concurrent/src/main/kotlin/io/heapy/komodo/core/concurent/KomodoThreadFactory.kt
1
753
package io.heapy.komodo.core.concurent import java.util.concurrent.ThreadFactory import java.util.concurrent.atomic.AtomicInteger /** * Thread factory which uses [AtomicInteger] to generate thread ids. * * @author Ruslan Ibragimov * @since 1.0 */ class KomodoThreadFactory( private val isDaemon: Boolean = false, private val nameProducer: ThreadNameProducer = { "komodo-$it" } ) : ThreadFactory { private val counter = AtomicInteger() override fun newThread(runnable: Runnable): Thread { val id = counter.incrementAndGet() return Thread(runnable).also { it.name = nameProducer(id) it.isDaemon = isDaemon } } } internal typealias ThreadNameProducer = (counter: Int) -> String
lgpl-3.0
27983ebfac3cd12e92e9298c08b93ecc
25.892857
68
0.693227
4.278409
false
false
false
false
mattiasniiranen/lov
lov/src/main/kotlin/net/niiranen/lov/Lov.kt
1
4636
/* * Copyright 2016 Mattias Niiranen * * 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 net.niiranen.lov import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.support.v4.content.ContextCompat import android.util.Log import rx.Observable import rx.subjects.PublishSubject import java.util.* /** * A simple permission requester. */ object Lov { internal val permissionSubjects = HashMap<String, PublishSubject<AndroidPermission>>() internal val rationales = HashMap<String, PermissionRationale>() /** * Add a rationale for [permission]. * * The rationale will be shown if [shouldShowRequestPermissionRationale][android.support.v4.app.ActivityCompat.shouldShowRequestPermissionRationale(String)] * returns true when the permission is about to be requested. */ fun addRationale(permission: String, rationale: PermissionRationale) { rationales[permission] = rationale } /** * Remove the rationale for [permission]. */ fun removeRationale(permission: String) { rationales.remove(permission) } /** * Requests permissions to be granted to [context]. * If a permission is already granted it will not be requested. * * @param context The context to request permission in. * @param permissions The permissions to ask for. * * @sample net.niiranen.lov.LovTest.requestPermission */ fun request(context: Context, vararg permissions: String): Observable<AndroidPermission> { val results = mutableListOf<Observable<AndroidPermission>>() val unset = permissions.partition { ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED }.run { first.forEach { // Add all already granted permissions results.add(Observable.just(AndroidPermission(it, true, false))) } // Return all permissions that need to be requested return@run second } // Filter out ongoing requests val unrequested = unset.filter { permissionSubjects[it] == null } // Create/restart subjects unset.forEach { results.add(permissionSubjects.run { var subject = getOrPut(it, { PublishSubject.create<AndroidPermission>() }) if (subject.hasCompleted()) { subject = PublishSubject.create<AndroidPermission>() put(it, subject) } return@run subject }) } if (unrequested.isNotEmpty()) { val intent = Intent(context, LovActivity::class.java) .putExtra(LovActivity.PERMISSIONS_KEY, unrequested.toTypedArray()) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.applicationContext.startActivity(intent) } return Observable.concat<AndroidPermission>(Observable.from(results)) } /** * Runs [block] if all permissions are granted. */ fun onPermissions(context: Context, vararg permissions: String, block: () -> Unit) { Lov.request(context, *permissions).all { it.granted } .subscribe({ if (it) { block() } }, { Log.e("Lov", "Error requesting permission(s) $it", it) }) } } /** * Requests permissions to be granted to `this`. * If a permission is already granted it will not be requested. * * @param permissions The permissions to ask for. */ fun <T : Context> T.requestPermissions(vararg permissions: String): Observable<AndroidPermission> { return Lov.request(this, *permissions) } /** * Runs [block] if all permissions are granted. */ fun <T : Context> T.onPermissions(vararg permissions: String, block: () -> Unit) { Lov.onPermissions(this, *permissions, block = block) }
apache-2.0
84a3d55548887c99477619463921246e
34.121212
160
0.6305
4.745138
false
false
false
false
Adven27/Exam
example/src/main/kotlin/app/Main.kt
1
8381
@file:JvmName("SutApp") package app import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer import io.ktor.application.ApplicationCall import io.ktor.application.call import io.ktor.application.install import io.ktor.application.log import io.ktor.features.CallLogging import io.ktor.features.ContentNegotiation import io.ktor.http.HttpStatusCode import io.ktor.http.HttpStatusCode.Companion.BadRequest import io.ktor.http.HttpStatusCode.Companion.Created import io.ktor.http.content.resources import io.ktor.http.content.static import io.ktor.jackson.jackson import io.ktor.request.header import io.ktor.request.httpMethod import io.ktor.request.receive import io.ktor.request.receiveOrNull import io.ktor.request.receiveText import io.ktor.request.uri import io.ktor.response.respond import io.ktor.routing.delete import io.ktor.routing.get import io.ktor.routing.post import io.ktor.routing.put import io.ktor.routing.routing import io.ktor.server.engine.embeddedServer import io.ktor.server.netty.Netty import io.ktor.util.pipeline.PipelineContext import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import org.jetbrains.exposed.sql.ResultRow import org.jetbrains.exposed.sql.deleteWhere import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.select import org.jetbrains.exposed.sql.selectAll import org.jetbrains.exposed.sql.update import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.util.TimeZone private val engine = embeddedServer(Netty, port = System.getProperty("server.port").toInt(), host = "") { install(CallLogging) install(ContentNegotiation) { jackson { setTimeZone(TimeZone.getDefault()) registerModule( JavaTimeModule() .addSerializer( LocalDateTime::class.java, LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")) ) ) configure(SerializationFeature.INDENT_OUTPUT, true) configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) } } DatabaseFactory.init() val jobs: MutableList<Int> = ArrayList() val widgetService = WidgetService() val jobService = JobService() routing { post("/jobs") { log.info("trigger job " + call.receiveOrNull<NewWidget>()) val id = jobService.add() jobs.add(id) // do some hard work async GlobalScope.launch { delay(2000L) jobService.update(id, "done") jobs.remove(id) } call.respond("""{ "id" : $id }""") } get("/jobs/{id}") { log.info("is job running?") call.respond("""{ "running" : "${jobs.contains(call.parameters["id"]?.toInt()!!)}" }""") } get("/widgets") { log.info("service.getAll: " + widgetService.getAll().toString()) call.respond(widgetService.getAll()) } get("/widgets/{id}") { val widget = widgetService.getBy(call.parameters["id"]?.toInt()!!) if (widget == null) call.respond(HttpStatusCode.NotFound) else call.respond(widget) } post("/widgets") { val widget = call.receive<NewWidget>() return@post when { widget.name == null -> call.respond(BadRequest, mapOf("error" to "name is required")) widget.quantity == null -> call.respond(BadRequest, mapOf("error" to "quantity is required")) else -> { try { call.respond(Created, widgetService.add(widget)) } catch (expected: Exception) { call.respond(BadRequest, mapOf("error" to expected.message)) } } } } put("/widgets") { val widget = call.receive<NewWidget>() val updated = widgetService.update(widget) if (updated == null) call.respond(HttpStatusCode.NotFound) else call.respond(HttpStatusCode.OK, updated) } delete("/widgets/{id}") { val removed = widgetService.delete(call.parameters["id"]?.toInt()!!) if (removed) call.respond(HttpStatusCode.OK) else call.respond(HttpStatusCode.NotFound) } post("/mirror/body") { call.respond(call.receiveText()) } put("/mirror/body") { call.respond(call.receiveText()) } post("/mirror/request") { mirrorRequestWithBody() } put("/mirror/request") { mirrorRequestWithBody() } delete("/mirror/request") { mirrorRequest() } get("/mirror/request") { mirrorRequest() } get("/mirror/headers") { mirrorHeaders() } delete("/mirror/headers") { mirrorHeaders() } get("/ignoreJson") { call.respond( """ { "param1":"value1", "param2":"value2", "arr": [{"param3":"value3", "param4":"value4"}, {"param3":"value3", "param4":"value4"}] } """.trimIndent() ) } static("/ui") { resources("files") } } } private suspend fun PipelineContext<Unit, ApplicationCall>.mirrorRequestWithBody() { with(call) { respond( mapOf( request.httpMethod.value to request.uri, "body" to receive(Map::class) ) ) } } private suspend fun PipelineContext<Unit, ApplicationCall>.mirrorRequest() { call.respond(mapOf(call.request.httpMethod.value to call.request.uri)) } private suspend fun PipelineContext<Unit, ApplicationCall>.mirrorHeaders() { with(call) { respond( mapOf( request.httpMethod.value to request.uri, "Authorization" to request.header("Authorization"), "Accept-Language" to request.header("Accept-Language"), "cookies" to request.cookies.rawCookies ) ) } } fun main() { start() } fun start() = engine.start() fun stop() = engine.stop(1000L, 2000L) class WidgetService { suspend fun getAll(): List<Widget> = DatabaseFactory.dbQuery { Widgets.selectAll().map { toWidget(it) } } suspend fun getBy(id: Int): Widget? = DatabaseFactory.dbQuery { Widgets.select { (Widgets.id eq id) }.mapNotNull { toWidget(it) }.singleOrNull() } suspend fun update(widget: NewWidget) = widget.id?.let { DatabaseFactory.dbQuery { Widgets.update({ Widgets.id eq it }) { it[name] = widget.name!! it[quantity] = widget.quantity!! it[updatedAt] = LocalDateTime.now() } } getBy(it) } ?: add(widget) suspend fun add(widget: NewWidget): Widget { var key = 0 DatabaseFactory.dbQuery { key = ( Widgets.insert { it[name] = if (widget.name!!.isBlank()) throw BlankNotAllowed() else widget.name it[quantity] = widget.quantity!! it[updatedAt] = LocalDateTime.now() } get Widgets.id ) } return getBy(key)!! } class BlankNotAllowed : RuntimeException("blank value not allowed") suspend fun delete(id: Int): Boolean = DatabaseFactory.dbQuery { Widgets.deleteWhere { Widgets.id eq id } > 0 } private fun toWidget(row: ResultRow) = Widget( id = row[Widgets.id], name = row[Widgets.name], quantity = row[Widgets.quantity], updatedAt = row[Widgets.updatedAt] ) } class JobService { suspend fun add(): Int { var key = 0 DatabaseFactory.dbQuery { key = (JobResult.insert {} get JobResult.id) } return key } suspend fun update(id: Int, jobResult: String) { DatabaseFactory.dbQuery { JobResult.update({ JobResult.id eq id }) { it[result] = jobResult } } } }
mit
9fdb9399df5aa21e4a87008350591daf
32.794355
115
0.594798
4.429704
false
false
false
false
kangsLee/sh8email-kotlin
app/src/main/kotlin/org/triplepy/sh8email/sh8/activities/main/MainActivity.kt
1
1322
package org.triplepy.sh8email.sh8.activities.main import android.content.Context import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.transition.TransitionInflater import kotlinx.android.synthetic.main.activity_main.* import org.triplepy.sh8email.sh8.R import org.triplepy.sh8email.sh8.activities.BaseActivity import org.triplepy.sh8email.sh8.adapter.BaseAdapter class MainActivity : BaseActivity() { private var context: Context? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) context = this setContentView(R.layout.activity_main) setupWindowAnimations() // RecyclerView setting recyclerView.apply { setHasFixedSize(true) val linearLayout = LinearLayoutManager(context) layoutManager = linearLayout clearOnScrollListeners() } // Adapter setting initAdapter() } private fun initAdapter() { if (recyclerView.adapter == null) { recyclerView.adapter = BaseAdapter(this) } } private fun setupWindowAnimations() { val fade = TransitionInflater.from(this).inflateTransition(R.transition.activity_fade) window.exitTransition = fade } }
apache-2.0
2fbf0c0d3260664ae16e0aacfc62789c
25.979592
94
0.696672
4.738351
false
false
false
false
grote/Transportr
app/src/main/java/de/grobox/transportr/trips/detail/StopViewHolder.kt
1
2875
/* * Transportr * * Copyright (c) 2013 - 2021 Torsten Grote * * This program is Free Software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.grobox.transportr.trips.detail import android.view.View import android.view.View.* import android.widget.ImageButton import android.widget.ImageView import android.widget.TextView import de.grobox.transportr.trips.BaseViewHolder import de.grobox.transportr.utils.DateUtils.formatTime import de.grobox.transportr.utils.TransportrUtils.getLocationName import de.schildbach.pte.dto.Stop import kotlinx.android.synthetic.main.list_item_stop.view.* import java.util.Date internal class StopViewHolder(v: View, private val listener : LegClickListener) : BaseViewHolder(v) { private val circle: ImageView = v.circle private val stopLocation: TextView = v.stopLocation private val stopButton: ImageButton = v.stopButton fun bind(stop: Stop, color: Int) { if (stop.arrivalTime != null) { setArrivalTimes(fromTime, fromDelay, stop) fromTime.visibility = VISIBLE } else { fromDelay.visibility = GONE if (stop.departureTime == null) { // insert dummy time field for stops without times set, so that stop circles align fromTime.text = formatTime(context, Date()) fromTime.visibility = INVISIBLE } else { fromTime.visibility = GONE } } if (stop.departureTime != null) { if (stop.departureTime == stop.arrivalTime) { toTime.visibility = GONE toDelay.visibility = GONE } else { setDepartureTimes(toTime, toDelay, stop) toTime.visibility = VISIBLE } } else { toTime.visibility = GONE toDelay.visibility = GONE } circle.setColorFilter(color) stopLocation.text = getLocationName(stop.location) stopLocation.setOnClickListener { listener.onLocationClick(stop.location) } stopLocation.addPlatform(stop.arrivalPosition) // show popup on button click stopButton.setOnClickListener { LegPopupMenu(stopButton.context, stopButton, stop).show() } } }
gpl-3.0
382bb10a8da24ffa7b67e403338c91f8
34.9375
101
0.665739
4.513344
false
false
false
false
cnsgcu/KotlinKoans
src/iii_conventions/MyDate.kt
1
1589
package iii_conventions data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> { override fun compareTo(other: MyDate): Int { if (year != other.year) { return year - other.year } else if (month != other.month) { return month - other.month } else if (dayOfMonth != other.dayOfMonth) { return dayOfMonth - other.dayOfMonth } return 0 } } fun MyDate.rangeTo(end: MyDate): DateRange { return DateRange(this, end) } fun MyDate.plus(timeInterval: TimeInterval): MyDate { return addTimeIntervals(timeInterval, 1) } fun MyDate.plus(timeIntervals: Array<TimeInterval>): MyDate { return timeIntervals.fold(this, {date, timeInterval -> date.addTimeIntervals(timeInterval, 1)}) } fun TimeInterval.times(num: Int): Array<TimeInterval> { return Array(num, {this}) } enum class TimeInterval { DAY, WEEK, YEAR } class DateRange(public override val start: MyDate, public override val end: MyDate) : Iterable<MyDate>, Range<MyDate> { override fun contains(item: MyDate): Boolean { return start <= item && item <= end } override fun iterator(): Iterator<MyDate> { return object : Iterator<MyDate> { private var current = start override fun hasNext(): Boolean { return current <= end } override fun next(): MyDate { val iDate = current current = current.nextDay() return iDate } } } }
mit
a94333f2b4e587db18dcb0e1c2473a98
25.483333
119
0.604783
4.463483
false
false
false
false
gordon0001/vitaorganizer
src/com/soywiz/vitaorganizer/popups/AboutFrame.kt
1
2146
package com.soywiz.vitaorganizer.popups import com.soywiz.vitaorganizer.Texts import com.soywiz.vitaorganizer.VitaOrganizer import com.soywiz.vitaorganizer.VitaOrganizerVersion import com.soywiz.vitaorganizer.ext.onClick import com.soywiz.vitaorganizer.ext.openWebpage import java.awt.* import javax.swing.* class AboutFrame() : JFrame(Texts.format("ABOUT_TITLE")) { fun JLinkLabel(text: String, link: String, extra: String = ""): JLabel { return JLabel("""<html><a href="$link">$text</a>$extra</html>""").apply { cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) }.onClick { openWebpage(link) } } fun Contibutor(text: String, link: String, role: String = ""): JComponent { return JLinkLabel(text, link, if (role.isNotEmpty()) " - $role" else "") } init { isResizable = false add(JPanel(BorderLayout()).apply { add(JLabel("VitaOrganizer ${VitaOrganizerVersion.currentVersion}", SwingConstants.CENTER).apply { font = Font("Arial", Font.BOLD, 24) }, BorderLayout.NORTH) add(object : JPanel() { override fun getInsets(): Insets { return Insets(10, 10, 10, 10) } init { layout = BoxLayout(this, BoxLayout.Y_AXIS) add(JLabel(Texts.format("ABOUT_PROGRAMMING"))) add(Contibutor("soywiz", "http://soywiz.com/")) add(Contibutor("luckylucks", "https://github.com/luckylucks/")) add(JLabel(Texts.format("ABOUT_TRANSLATIONS"))) add(Contibutor("paweloszu", "https://github.com/paweloszu", "Polish")) add(Contibutor("Ridge", "https://www.twitter.com/telepathyclub", "Norwegian")) add(Contibutor("pvc1", "https://github.com/pvc1", "Russian")) add(Contibutor("Mdslino", "https://github.com/Mdslino", "Brazilian")) add(Contibutor("gordon0001", "https://github.com/gordon0001", "German")) add(Contibutor("charlyzard", "https://github.com/charlyzard", "Spanish")) add(Contibutor("anthologist", "https://github.com/anthologist", "Italian")) add(Contibutor("adeldk", "https://github.com/adeldk", "French")) add(Contibutor("kavid", "https://github.com/kavid", "Chinese")) } }) preferredSize = Dimension(500, 400) }) } }
gpl-3.0
40e7655daf12d3433538059eef8b6b0e
37.321429
100
0.684995
3.110145
false
false
false
false
NephyProject/Penicillin
src/main/kotlin/jp/nephy/penicillin/extensions/endpoints/CreatePollTweet.kt
1
3140
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ @file:Suppress("UNUSED", "PublicApiImplicitType") package jp.nephy.penicillin.extensions.endpoints import jp.nephy.jsonkt.stringify import jp.nephy.jsonkt.toJsonObject import jp.nephy.penicillin.core.emulation.EmulationMode import jp.nephy.penicillin.core.request.action.ApiAction import jp.nephy.penicillin.endpoints.Option import jp.nephy.penicillin.endpoints.PrivateEndpoint import jp.nephy.penicillin.endpoints.Statuses import jp.nephy.penicillin.endpoints.cards import jp.nephy.penicillin.endpoints.cards.create import jp.nephy.penicillin.endpoints.statuses.create import jp.nephy.penicillin.extensions.DelegatedAction import jp.nephy.penicillin.extensions.execute import jp.nephy.penicillin.models.Status import kotlinx.serialization.json.JsonConfiguration /** * Creates new poll tweet. * * **Warning: This endpoint is private endpoint. So if you use this endpoint, your account can be banned.** * * @param status Status body. * @param choices A list of choices. Max size is 4. * @param minutes Duration minutes. Default 1440 mins (1 day). * @param options Optional. Custom parameters of this request. * @receiver [Statuses] endpoint instance. * @return [ApiAction] for [Status] model. */ @PrivateEndpoint(EmulationMode.TwitterForiPhone) fun Statuses.createPollTweet( status: String, choices: List<String>, minutes: Int = 1440, vararg options: Option ) = DelegatedAction { val card = client.cards.create( cardData = linkedMapOf<String, Any>().apply { choices.forEachIndexed { i, choice -> put("twitter:string:choice${i + 1}_label", choice) } put("twitter:api:api:endpoint", "1") put("twitter:card", "poll${choices.size}choice_text_only") put("twitter:long:duration_minutes", minutes) }.toJsonObject().stringify(JsonConfiguration.Stable) ).execute() create(status, cardUri = card.result.cardUri, options = *options).execute().result }
mit
2c3299a457bcc1e8fd009b2f556df4c5
40.866667
107
0.742994
4.231806
false
false
false
false
jayrave/falkon
falkon-sql-builder-sqlite/src/test/kotlin/com/jayrave/falkon/sqlBuilders/sqlite/SqliteTypeTranslatorTest.kt
1
2199
package com.jayrave.falkon.sqlBuilders.sqlite import com.jayrave.falkon.engine.Type import org.assertj.core.api.Assertions.assertThat import org.junit.Test class SqliteTypeTranslatorTest { private val typeTranslator = SqliteTypeTranslator() @Test fun testTranslateForShort() { val input = Type.SHORT val expectedOutput = "INTEGER" assertThat(typeTranslator.translate(input)).isEqualTo(expectedOutput) assertThat(typeTranslator.translate(input, 5)).isEqualTo(expectedOutput) } @Test fun testTranslateForInt() { val input = Type.INT val expectedOutput = "INTEGER" assertThat(typeTranslator.translate(input)).isEqualTo(expectedOutput) assertThat(typeTranslator.translate(input, 5)).isEqualTo(expectedOutput) } @Test fun testTranslateForLong() { val input = Type.LONG val expectedOutput = "INTEGER" assertThat(typeTranslator.translate(input)).isEqualTo(expectedOutput) assertThat(typeTranslator.translate(input, 5)).isEqualTo(expectedOutput) } @Test fun testTranslateForFloat() { val input = Type.FLOAT val expectedOutput = "REAL" assertThat(typeTranslator.translate(input)).isEqualTo(expectedOutput) assertThat(typeTranslator.translate(input, 5)).isEqualTo(expectedOutput) } @Test fun testTranslateForDouble() { val input = Type.DOUBLE val expectedOutput = "REAL" assertThat(typeTranslator.translate(input)).isEqualTo(expectedOutput) assertThat(typeTranslator.translate(input, 5)).isEqualTo(expectedOutput) } @Test fun testTranslateForString() { val input = Type.STRING val expectedOutput = "TEXT" assertThat(typeTranslator.translate(input)).isEqualTo(expectedOutput) assertThat(typeTranslator.translate(input, 5)).isEqualTo(expectedOutput) } @Test fun testTranslateForBlob() { val input = Type.BLOB val expectedOutput = "BLOB" assertThat(typeTranslator.translate(input)).isEqualTo(expectedOutput) assertThat(typeTranslator.translate(input, 5)).isEqualTo(expectedOutput) } }
apache-2.0
4282aa982c4d7d3908ed7111a4324b11
29.555556
80
0.69759
4.780435
false
true
false
false
UweTrottmann/SeriesGuide
app/src/main/java/com/battlelancer/seriesguide/shows/search/discover/SearchResultDiffCallback.kt
1
761
package com.battlelancer.seriesguide.shows.search.discover import androidx.recyclerview.widget.DiffUtil /** [DiffUtil.ItemCallback] for [SearchResult] items for use with a RecyclerView adapter. */ class SearchResultDiffCallback : DiffUtil.ItemCallback<SearchResult>() { override fun areItemsTheSame(oldItem: SearchResult, newItem: SearchResult): Boolean = oldItem.tmdbId == newItem.tmdbId && oldItem.title == newItem.title override fun areContentsTheSame(oldItem: SearchResult, newItem: SearchResult): Boolean = oldItem.state == newItem.state && oldItem.language == newItem.language && oldItem.posterPath == newItem.posterPath && oldItem.overview == newItem.overview }
apache-2.0
dc2b4d407f5d399e30f6913f9e029eb9
41.333333
92
0.704336
5.435714
false
false
false
false
tuarua/WebViewANE
native_library/android/WebViewANE/app/src/main/java/com/tuarua/webviewane/KotlinController.kt
1
9561
/* * Copyright 2017 Tua Rua Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Additional Terms * No part, or derivative of this Air Native Extensions's code is permitted * to be sold as the basis of a commercially packaged Air Native Extension which * undertakes the same purpose as this software. That is, a WebView for Windows, * OSX and/or iOS and/or Android. * All Rights Reserved. Tua Rua Ltd. */ package com.tuarua.webviewane import android.content.Intent import android.graphics.Bitmap import android.graphics.RectF import android.os.Build import android.webkit.WebChromeClient.FileChooserParams import android.webkit.WebView import com.adobe.air.FreKotlinActivityResultCallback import com.adobe.fre.FREContext import com.adobe.fre.FREObject import com.tuarua.frekotlin.* import com.tuarua.frekotlin.display.FreBitmapDataKotlin import com.tuarua.frekotlin.geom.RectF import com.tuarua.webviewane.ChromeClient.Companion.REQUEST_FILE @Suppress("unused", "UNUSED_PARAMETER", "UNCHECKED_CAST") class KotlinController : FreKotlinMainController, FreKotlinActivityResultCallback { private var isAdded = false private var scaleFactor = 1.0f private var webViewController: WebViewController? = null private var capturedBitmapData: Bitmap? = null fun isSupported(ctx: FREContext, argv: FREArgv): FREObject? { return true.toFREObject() } fun init(ctx: FREContext, argv: FREArgv): FREObject? { argv.takeIf { argv.size > 4 } ?: return FreArgException() val initialUrl = URLRequest(argv[0]) val viewPort = RectF(argv[1]) val settings = Settings(argv[2]) Float(argv[3])?.let { scaleFactor = it } val backgroundColor = argv[4].toColor() webViewController = WebViewController(ctx, initialUrl, scaleViewPort(viewPort), settings, backgroundColor) return null } fun clearCache(ctx: FREContext, argv: FREArgv): FREObject? { webViewController?.clearCache() return null } fun zoomIn(ctx: FREContext, argv: FREArgv): FREObject? { webViewController?.zoomIn() return null } fun zoomOut(ctx: FREContext, argv: FREArgv): FREObject? { webViewController?.zoomOut() return null } fun setViewPort(ctx: FREContext, argv: FREArgv): FREObject? { argv.takeIf { argv.size > 0 } ?: return FreArgException() val viewPortFre = RectF(argv[0]) webViewController?.viewPort = scaleViewPort(viewPortFre) return null } fun setVisible(ctx: FREContext, argv: FREArgv): FREObject? { argv.takeIf { argv.size > 0 } ?: return FreArgException() val visible = Boolean(argv[0]) == true if (!isAdded) { webViewController?.add() isAdded = true } webViewController?.visible = visible return null } fun loadHTMLString(ctx: FREContext, argv: FREArgv): FREObject? { argv.takeIf { argv.size > 0 } ?: return FreArgException() val data = String(argv[0]) ?: return null webViewController?.loadHTMLString(data) return null } fun load(ctx: FREContext, argv: FREArgv): FREObject? { argv.takeIf { argv.size > 0 } ?: return FreArgException() val request = URLRequest(argv[0]) webViewController?.loadUrl(request) return null } fun loadFileURL(ctx: FREContext, argv: FREArgv): FREObject? { argv.takeIf { argv.size > 0 } ?: return FreArgException() val url = String(argv[0]) ?: return null webViewController?.loadFileUrl(url) return null } fun reload(ctx: FREContext, argv: FREArgv): FREObject? { webViewController?.reload() return null } fun clearRequestHeaders(ctx: FREContext, argv: FREArgv): FREObject? { UrlRequestHeaderManager.remove() return null } fun go(ctx: FREContext, argv: FREArgv): FREObject? { argv.takeIf { argv.size > 0 } ?: return FreArgException() val offset = Int(argv[0]) ?: return null webViewController?.go(offset) return null } fun goBack(ctx: FREContext, argv: FREArgv): FREObject? { webViewController?.goBack() return null } fun goForward(ctx: FREContext, argv: FREArgv): FREObject? { webViewController?.goForward() return null } fun stopLoading(ctx: FREContext, argv: FREArgv): FREObject? { webViewController?.stopLoading() return null } fun reloadFromOrigin(ctx: FREContext, argv: FREArgv): FREObject? { webViewController?.reload() return null } fun allowsMagnification(ctx: FREContext, argv: FREArgv): FREObject? { return true.toFREObject() } fun showDevTools(ctx: FREContext, argv: FREArgv): FREObject? { WebView.setWebContentsDebuggingEnabled(true) return null } fun closeDevTools(ctx: FREContext, argv: FREArgv): FREObject? { WebView.setWebContentsDebuggingEnabled(false) return null } fun callJavascriptFunction(ctx: FREContext, argv: FREArgv): FREObject? { argv.takeIf { argv.size > 1 } ?: return FreArgException() val js = String(argv[0]) ?: return null val callback = String(argv[1]) webViewController?.evaluateJavascript(js, callback) return null } fun evaluateJavaScript(ctx: FREContext, argv: FREArgv): FREObject? { argv.takeIf { argv.size > 1 } ?: return FreArgException() val js = String(argv[0]) ?: return null val callback = String(argv[1]) webViewController?.evaluateJavascript(js, callback) return null } fun getCurrentTab(ctx: FREContext, argv: FREArgv): FREObject? { val ret = 0 return ret.toFREObject() } fun getTabDetails(ctx: FREContext, argv: FREArgv): FREObject? { val vecTabs = FREArray("com.tuarua.webview.TabDetails", 1, true) ?: return null val currentTabFre = FREObject("com.tuarua.webview.TabDetails", 0, webViewController?.url ?: "" , webViewController?.title ?: "" , webViewController?.isLoading ?: false , webViewController?.canGoBack ?: false , webViewController?.canGoForward ?: false , webViewController?.progress ?: 0.0 ) vecTabs[0] = currentTabFre return vecTabs } fun capture(ctx: FREContext, argv: FREArgv): FREObject? { argv.takeIf { argv.size > 0 } ?: return FreArgException() val cropTo = scaleViewPort(RectF(argv[0])) capturedBitmapData = webViewController?.capture(cropTo) dispatchEvent(WebViewEvent.ON_CAPTURE_COMPLETE, "") return null } fun getCapturedBitmapData(ctx: FREContext, argv: FREArgv): FREObject? { val cbmd = capturedBitmapData ?: return null val bmd = FreBitmapDataKotlin(cbmd) return bmd.rawValue } fun backForwardList(ctx: FREContext, argv: FREArgv): FREObject? = null fun setCurrentTab(ctx: FREContext, argv: FREArgv): FREObject? = null fun addTab(ctx: FREContext, argv: FREArgv): FREObject? = null fun closeTab(ctx: FREContext, argv: FREArgv): FREObject? = null fun injectScript(ctx: FREContext, argv: FREArgv): FREObject? = null fun print(ctx: FREContext, argv: FREArgv): FREObject? = null fun printToPdf(ctx: FREContext, argv: FREArgv): FREObject? = null fun focus(ctx: FREContext, argv: FREArgv): FREObject? = null fun onFullScreen(ctx: FREContext, argv: FREArgv): FREObject? = null fun shutDown(ctx: FREContext, argv: FREArgv): FREObject? = null private fun scaleViewPort(rect: RectF): RectF { return RectF( (rect.left * scaleFactor), (rect.top * scaleFactor), (rect.right * scaleFactor), (rect.bottom * scaleFactor)) } fun getOsVersion(ctx: FREContext, argv: FREArgv): FREObject? { return intArrayOf(Build.VERSION.SDK_INT, 0, 0).toFREObject() } fun deleteCookies(ctx: FREContext, argv: FREArgv): FREObject? { webViewController?.deleteCookies() return null } override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) { if (requestCode != REQUEST_FILE) return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return webViewController?.chromeClient?.filePathCallback?.onReceiveValue(FileChooserParams.parseResult(resultCode, intent)) webViewController?.chromeClient?.filePathCallback = null } override fun dispose() { webViewController?.dispose() webViewController = null } @Suppress("PropertyName") override val TAG: String? get() = this::class.java.simpleName private var _context: FREContext? = null override var context: FREContext? get() = _context set(value) { _context = value FreKotlinLogger.context = _context } }
apache-2.0
dbf2f8ceb01d4cb5593ac84252381a42
34.679104
124
0.657881
3.841302
false
false
false
false
FutureioLab/FastPeak
app/src/main/java/com/binlly/fastpeak/base/glide/progress/ProgressResponseBody.kt
1
1359
package com.binlly.fastpeak.base.glide.progress import okhttp3.MediaType import okhttp3.ResponseBody import okio.* import java.io.IOException class ProgressResponseBody(private val imageUrl: String, private val responseBody: ResponseBody?, private val progressListener: OnProgressListener): ResponseBody() { private var bufferedSource: BufferedSource? = null override fun contentType(): MediaType? { return responseBody?.contentType() } override fun contentLength(): Long { return responseBody?.contentLength() ?: 0 } override fun source(): BufferedSource? { responseBody?.let { bufferedSource = Okio.buffer(source(responseBody.source())) } return bufferedSource } private fun source(source: Source): Source { return object: ForwardingSource(source) { internal var totalBytesRead: Long = 0 @Throws(IOException::class) override fun read(sink: Buffer, byteCount: Long): Long { val bytesRead = super.read(sink, byteCount) totalBytesRead += if (bytesRead == -1L) 0 else bytesRead progressListener.onProgress(imageUrl, totalBytesRead, contentLength(), bytesRead == -1L, null) return bytesRead } } } }
mit
595ee7da010d938fd4358acdce8c97b9
32.146341
97
0.635762
5.479839
false
false
false
false
ajalt/clikt
clikt/src/commonMain/kotlin/com/github/ajalt/clikt/core/CliktCommand.kt
1
22114
package com.github.ajalt.clikt.core import com.github.ajalt.clikt.completion.CompletionGenerator import com.github.ajalt.clikt.mpp.exitProcessMpp import com.github.ajalt.clikt.output.CliktConsole import com.github.ajalt.clikt.output.HelpFormatter.ParameterHelp import com.github.ajalt.clikt.output.TermUi import com.github.ajalt.clikt.parameters.arguments.Argument import com.github.ajalt.clikt.parameters.arguments.ProcessedArgument import com.github.ajalt.clikt.parameters.arguments.argument import com.github.ajalt.clikt.parameters.groups.OptionGroup import com.github.ajalt.clikt.parameters.groups.ParameterGroup import com.github.ajalt.clikt.parameters.options.* import com.github.ajalt.clikt.parsers.Parser /** * The [CliktCommand] is the core of command line interfaces in Clikt. * * Command line interfaces created by creating a subclass of [CliktCommand] with properties defined with * [option] and [argument]. You can then parse `argv` by calling [main], which will take care of printing * errors and help to the user. If you want to handle output yourself, you can use [parse] instead. * * Once the command line has been parsed and all of the parameters are populated, [run] is called. * * @param help The help for this command. The first line is used in the usage string, and the entire string is * used in the help output. Paragraphs are automatically re-wrapped to the terminal width. * @param epilog Text to display at the end of the full help output. It is automatically re-wrapped to the * terminal width. * @param name The name of the program to use in the help output. If not given, it is inferred from the class * name. * @param invokeWithoutSubcommand Used when this command has subcommands, and this command is called * without a subcommand. If true, [run] will be called. By default, a [PrintHelpMessage] is thrown instead. * @param printHelpOnEmptyArgs If this command is called with no values on the command line, print a * help message (by throwing [PrintHelpMessage]) if this is true, otherwise run normally. * @param helpTags Extra information about this option to pass to the help formatter. * @param autoCompleteEnvvar The envvar to use to enable shell autocomplete script generation. Set * to null to disable generation. * @param allowMultipleSubcommands If true, allow multiple of this command's subcommands to be * called sequentially. This will disable `allowInterspersedArgs` on the context of this command an * its descendants. This functionality is experimental, and may change in a future release. * @param treatUnknownOptionsAsArgs If true, any options on the command line whose names aren't * valid will be parsed as an argument rather than reporting an error. You'll need to define an * `argument().multiple()` to collect these options, or an error will still be reported. Unknown * short option flags grouped with other flags on the command line will always be reported as * errors. * @param hidden If true, don't display this command in help output when used as a subcommand. */ @Suppress("PropertyName") @ParameterHolderDsl abstract class CliktCommand( help: String = "", epilog: String = "", name: String? = null, val invokeWithoutSubcommand: Boolean = false, val printHelpOnEmptyArgs: Boolean = false, val helpTags: Map<String, String> = emptyMap(), private val autoCompleteEnvvar: String? = "", internal val allowMultipleSubcommands: Boolean = false, internal val treatUnknownOptionsAsArgs: Boolean = false, private val hidden: Boolean = false, ) : ParameterHolder { /** * The name of this command, used in help output. * * You can set this by passing `name` to the [CliktCommand] constructor. */ val commandName: String = name ?: inferCommandName() /** * The help text for this command. * * You can set this by passing `help` to the [CliktCommand] constructor, or by overriding this * property. */ open val commandHelp: String = help /** * Help text to display at the end of the help output, after any parameters. * * You can set this by passing `epilog` to the [CliktCommand] constructor, or by overriding this * property. */ open val commandHelpEpilog: String = epilog internal var _subcommands: List<CliktCommand> = emptyList() internal val _options: MutableList<Option> = mutableListOf() internal val _arguments: MutableList<Argument> = mutableListOf() internal val _groups: MutableList<ParameterGroup> = mutableListOf() internal var _contextConfig: Context.Builder.() -> Unit = {} private var _context: Context? = null private val _messages = mutableListOf<String>() private fun registeredOptionNames() = _options.flatMapTo(mutableSetOf()) { it.names } private fun createContext(argv: List<String>, parent: Context?, ancestors: List<CliktCommand>) { _context = Context.build(this, parent, argv, _contextConfig) if (allowMultipleSubcommands) { require(currentContext.ancestors().drop(1).none { it.command.allowMultipleSubcommands }) { "Commands with allowMultipleSubcommands=true cannot be nested in " + "commands that also have allowMultipleSubcommands=true" } } if (currentContext.helpOptionNames.isNotEmpty()) { val names = currentContext.helpOptionNames - registeredOptionNames() if (names.isNotEmpty()) _options += helpOption(names, currentContext.localization.helpOptionMessage()) } for (command in _subcommands) { val a = (ancestors + parent?.command).filterNotNull() check(command !in a) { "Command ${command.commandName} already registered" } command.createContext(argv, currentContext, a) } } private fun allHelpParams(): List<ParameterHelp> { return _options.mapNotNull { it.parameterHelp(currentContext) } + _arguments.mapNotNull { it.parameterHelp(currentContext) } + _groups.mapNotNull { it.parameterHelp(currentContext) } + _subcommands.mapNotNull { when { it.hidden -> null else -> ParameterHelp.Subcommand(it.commandName, it.shortHelp(), it.helpTags) } } } private fun getCommandNameWithParents(): String { if (_context == null) createContext(emptyList(), null, emptyList()) return currentContext.commandNameWithParents().joinToString(" ") } private fun generateCompletion() { if (autoCompleteEnvvar == null) return val envvar = when { autoCompleteEnvvar.isBlank() -> "_${commandName.replace("-", "_").uppercase()}_COMPLETE" else -> autoCompleteEnvvar } val envval = currentContext.readEnvvar(envvar) ?: return CompletionGenerator.throwCompletionMessage(this, envval) } /** * This command's context. * * @throws NullPointerException if accessed before [parse] or [main] are called. */ val currentContext: Context get() { checkNotNull(_context) { "Context accessed before parse has been called." } return _context!! } /** All messages issued during parsing. */ val messages: List<String> get() = _messages /** Add a message to be printed after parsing */ fun issueMessage(message: String) { _messages += message } /** The help displayed in the commands list when this command is used as a subcommand. */ protected fun shortHelp(): String = Regex("""\s*(?:```)?\s*(.+)""").find(commandHelp)?.groups?.get(1)?.value ?: "" /** The names of all direct children of this command */ fun registeredSubcommandNames(): List<String> = _subcommands.map { it.commandName } /** * Get a read-only list of commands registered as [subcommands] of this command. */ fun registeredSubcommands(): List<CliktCommand> = _subcommands.toList() /** * Get a read-only list of options registered in this command (e.g. via [registerOption] or an [option] delegate) */ fun registeredOptions(): List<Option> = _options.toList() /** * Get a read-only list of arguments registered in this command (e.g. via [registerArgument] or an [argument] delegate) */ fun registeredArguments(): List<Argument> = _arguments.toList() /** * Get a read-only list of groups registered in this command (e.g. via [registerOptionGroup] or an [OptionGroup] delegate) */ fun registeredParameterGroups(): List<ParameterGroup> = _groups.toList() /** * Register an option with this command. * * This is called automatically for the built in options, but you need to call this if you want to add a * custom option. */ fun registerOption(option: Option) { val names = registeredOptionNames() for (name in option.names) { require(name !in names) { "Duplicate option name $name" } } _options += option } override fun registerOption(option: GroupableOption) = registerOption(option as Option) /** * Register an argument with this command. * * This is called automatically for the built in arguments, but you need to call this if you want to add a * custom argument. */ fun registerArgument(argument: Argument) { require(argument.nvalues > 0 || _arguments.none { it.nvalues < 0 }) { "Cannot declare multiple arguments with variable numbers of values" } _arguments += argument } /** * Register a group with this command. * * This is called automatically for built in groups, but you need to call this if you want to * add a custom group. */ fun registerOptionGroup(group: ParameterGroup) { require(group !in _groups) { "Cannot register the same group twice" } require(group.groupName == null || _groups.none { it.groupName == group.groupName }) { "Cannot register the same group name twice" } _groups += group } /** Return the usage string for this command. */ open fun getFormattedUsage(): String { val programName = getCommandNameWithParents() return currentContext.helpFormatter.formatUsage(allHelpParams(), programName = programName) } /** Return the full help string for this command. */ open fun getFormattedHelp(): String { val programName = getCommandNameWithParents() return currentContext.helpFormatter.formatHelp(commandHelp, commandHelpEpilog, allHelpParams(), programName = programName) } /** * A list of command aliases. * * If the user enters a command that matches a key in this map, the command is replaced with the * corresponding value in the map. The aliases aren't recursive, so aliases won't be looked up again while * tokens from an existing alias are being parsed. */ open fun aliases(): Map<String, List<String>> = emptyMap() /** Print the default [line separator][CliktConsole.lineSeparator] to `stdout` */ protected fun echo() { echo("") } @Deprecated( message = "Specify message explicitly with `err` or `lineSeparator`", replaceWith = ReplaceWith("echo(\"\", err=err, lineSeparator=lineSeparator)") ) /** @suppress */ protected fun echo(err: Boolean, lineSeparator: String) { echo("", err = err, lineSeparator = lineSeparator) } /** * Print the [message] to the screen. * * This is similar to [print] or [println], but converts newlines to the system line separator. * * @param message The message to print. * @param trailingNewline If true, behave like [println], otherwise behave like [print] * @param err If true, print to stderr instead of stdout */ protected fun echo( message: Any?, trailingNewline: Boolean = true, err: Boolean = false, lineSeparator: String = currentContext.console.lineSeparator, ) { TermUi.echo(message, trailingNewline, err, currentContext.console, lineSeparator) } /** * Prompt a user for text input. * * If the user sends a terminate signal (e.g. ctrl-c) while the prompt is active, null will be returned. * * @param text The text to display for the prompt. * @param default The default value to use for the input. If the user enters a newline without any other * value, [default] will be returned. * @param hideInput If true, the user's input will not be echoed back to the screen. This is commonly used * for password inputs. * @param requireConfirmation If true, the user will be required to enter the same value twice before it * is accepted. * @param confirmationPrompt The text to show the user when [requireConfirmation] is true. * @param promptSuffix A delimiter printed between the [text] and the user's input. * @param showDefault If true, the [default] value will be shown as part of the prompt. * @return the user's input, or null if the stdin is not interactive and EOF was encountered. */ protected fun prompt( text: String, default: String? = null, hideInput: Boolean = false, requireConfirmation: Boolean = false, confirmationPrompt: String = "Repeat for confirmation: ", promptSuffix: String = ": ", showDefault: Boolean = true, ): String? { return TermUi.prompt( text = text, default = default, hideInput = hideInput, requireConfirmation = requireConfirmation, confirmationPrompt = confirmationPrompt, promptSuffix = promptSuffix, showDefault = showDefault, console = currentContext.console, convert = { it } ) } /** * Prompt a user for text input and convert the result. * * If the user sends a terminate signal (e.g. ctrl-c) while the prompt is active, null will be returned. * * @param text The text to display for the prompt. * @param default The default value to use for the input. If the user enters a newline without any other * value, [default] will be returned. This parameter is a String instead of [T], since it will be * displayed to the user. * @param hideInput If true, the user's input will not be echoed back to the screen. This is commonly used * for password inputs. * @param requireConfirmation If true, the user will be required to enter the same value twice before it * is accepted. * @param confirmationPrompt The text to show the user when [requireConfirmation] is true. * @param promptSuffix A delimiter printed between the [text] and the user's input. * @param showDefault If true, the [default] value will be shown as part of the prompt. * @param convert A callback that will convert the text that the user enters to the return value of the * function. If the callback raises a [UsageError], its message will be printed and the user will be * asked to enter a new value. If [default] is not null and the user does not input a value, the value * of [default] will be passed to this callback. * @return the user's input, or null if the stdin is not interactive and EOF was encountered. */ protected fun <T> prompt( text: String, default: String? = null, hideInput: Boolean = false, requireConfirmation: Boolean = false, confirmationPrompt: String = "Repeat for confirmation: ", promptSuffix: String = ": ", showDefault: Boolean = true, convert: ((String) -> T), ): T? { return TermUi.prompt( text = text, default = default, hideInput = hideInput, requireConfirmation = requireConfirmation, confirmationPrompt = confirmationPrompt, promptSuffix = promptSuffix, showDefault = showDefault, console = currentContext.console, convert = convert ) } /** * Prompt for user confirmation. * * Responses will be read from stdin, even if it's redirected to a file. * * @param text the question to ask * @param default the default, used if stdin is empty * @param abort if `true`, a negative answer aborts the program by raising [Abort] * @param promptSuffix a string added after the question and choices * @param showDefault if false, the choices will not be shown in the prompt. * @return the user's response, or null if stdin is not interactive and EOF was encountered. */ protected fun confirm( text: String, default: Boolean = false, abort: Boolean = false, promptSuffix: String = ": ", showDefault: Boolean = true, ): Boolean? { return TermUi.confirm(text, default, abort, promptSuffix, showDefault, currentContext.console) } /** * Parse the command line and throw an exception if parsing fails. * * You should use [main] instead unless you want to handle output yourself. */ fun parse(argv: List<String>, parentContext: Context? = null) { createContext(argv, parentContext, emptyList()) generateCompletion() Parser.parse(argv, this.currentContext) } fun parse(argv: Array<String>, parentContext: Context? = null) { parse(argv.asList(), parentContext) } /** * Parse the command line and print helpful output if any errors occur. * * This function calls [parse] and catches and [CliktError]s that are thrown. Other errors are allowed to * pass through. */ fun main(argv: List<String>) { try { parse(argv) } catch (e: ProgramResult) { exitProcessMpp(e.statusCode) } catch (e: PrintHelpMessage) { echo(e.command.getFormattedHelp()) exitProcessMpp(if (e.error) 1 else 0) } catch (e: PrintCompletionMessage) { val s = if (e.forceUnixLineEndings) "\n" else currentContext.console.lineSeparator echo(e.message, lineSeparator = s) exitProcessMpp(0) } catch (e: PrintMessage) { echo(e.message) exitProcessMpp(if (e.error) 1 else 0) } catch (e: UsageError) { echo(e.helpMessage(), err = true) exitProcessMpp(e.statusCode) } catch (e: CliktError) { echo(e.message, err = true) exitProcessMpp(1) } catch (e: Abort) { echo(currentContext.localization.aborted(), err = true) exitProcessMpp(if (e.error) 1 else 0) } } fun main(argv: Array<out String>) = main(argv.asList()) /** * Perform actions after parsing is complete and this command is invoked. * * This is called after command line parsing is complete. If this command is a subcommand, this will only * be called if the subcommand is invoked. * * If one of this command's subcommands is invoked, this is called before the subcommand's arguments are * parsed. */ abstract fun run() override fun toString() = buildString { append("<${[email protected]()} name=$commandName") if (_options.isNotEmpty() || _arguments.isNotEmpty() || _subcommands.isNotEmpty()) { append(" ") } if (_options.isNotEmpty()) { append("options=[") for ((i, option) in _options.withIndex()) { if (i > 0) append(" ") append(option.longestName()) if (_context != null && option is OptionDelegate<*>) { try { val value = option.value append("=").append(value) } catch (_: IllegalStateException) { } } } append("]") } if (_arguments.isNotEmpty()) { append(" arguments=[") for ((i, argument) in _arguments.withIndex()) { if (i > 0) append(" ") append(argument.name) if (_context != null && argument is ProcessedArgument<*, *>) { try { val value = argument.value append("=").append(value) } catch (_: IllegalStateException) { } } } append("]") } if (_subcommands.isNotEmpty()) { _subcommands.joinTo(this, " ", prefix = " subcommands=[", postfix = "]") } append(">") } } /** Add the given commands as a subcommand of this command. */ fun <T : CliktCommand> T.subcommands(commands: Iterable<CliktCommand>): T = apply { _subcommands = _subcommands + commands } /** Add the given commands as a subcommand of this command. */ fun <T : CliktCommand> T.subcommands(vararg commands: CliktCommand): T = apply { _subcommands = _subcommands + commands } /** * Configure this command's [Context]. * * Context property values are normally inherited from the parent context, but you can override any of them * here. */ fun <T : CliktCommand> T.context(block: Context.Builder.() -> Unit): T = apply { // save the old config to allow multiple context calls val c = _contextConfig _contextConfig = { c() block() } } private fun Any.classSimpleName(): String = this::class.simpleName.orEmpty().split("$").last() private fun CliktCommand.inferCommandName(): String { val name = classSimpleName() if (name == "Command") return "command" return name.removeSuffix("Command").replace(Regex("([a-z])([A-Z])")) { "${it.groupValues[1]}-${it.groupValues[2]}" }.lowercase() }
apache-2.0
3024376127076e950e1b2565e0ffd454
40.411985
140
0.642896
4.574679
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/DiscordiaCommand.kt
1
1548
package net.perfectdreams.loritta.morenitta.commands.vanilla.images import net.perfectdreams.loritta.morenitta.commands.AbstractCommand import net.perfectdreams.loritta.morenitta.commands.CommandContext import net.perfectdreams.loritta.morenitta.gifs.MentionGIF import net.perfectdreams.loritta.morenitta.utils.Constants import net.perfectdreams.loritta.morenitta.utils.MiscUtils import net.perfectdreams.loritta.morenitta.api.commands.Command import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.common.locale.LocaleKeyData import net.perfectdreams.loritta.morenitta.utils.OutdatedCommandUtils import net.perfectdreams.loritta.morenitta.LorittaBot class DiscordiaCommand(loritta: LorittaBot) : AbstractCommand(loritta, "mentions", listOf("discórdia", "discord", "discordia"), net.perfectdreams.loritta.common.commands.CommandCategory.IMAGES) { override fun getDescriptionKey() = LocaleKeyData("commands.command.discordping.description") override fun getExamplesKey() = Command.SINGLE_IMAGE_EXAMPLES_KEY // TODO: Fix Usage override fun needsToUploadFiles() = true override suspend fun run(context: CommandContext,locale: BaseLocale) { OutdatedCommandUtils.sendOutdatedCommandMessage(context, locale, "discordping") var contextImage = context.getImageAt(0) ?: run { Constants.INVALID_IMAGE_REPLY.invoke(context); return; } var file = MentionGIF.getGIF(contextImage) loritta.gifsicle.optimizeGIF(file) context.sendFile(file, "discordia.gif", context.getAsMention(true)) file.delete() } }
agpl-3.0
5639eb41d755ef476cc110ffed8f9a52
48.935484
195
0.828054
4.215259
false
false
false
false
jitsi/jibri
src/main/kotlin/org/jitsi/jibri/util/LoggingUtils.kt
1
2536
/* * Copyright @ 2018 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jitsi.jibri.util import org.jitsi.utils.logging2.Logger import org.jitsi.utils.logging2.LoggerImpl import java.io.BufferedReader import java.io.InputStream import java.io.InputStreamReader import java.util.concurrent.Callable import java.util.concurrent.Future import java.util.logging.FileHandler class LoggingUtils { companion object { var createPublishingTail: (InputStream, (String) -> Unit) -> PublishingTail = ::PublishingTail /** * The default implementation of the process output logger */ val OutputLogger: (ProcessWrapper, Logger) -> Future<Boolean> = { process, logger -> TaskPools.ioPool.submit( Callable<Boolean> { val reader = BufferedReader(InputStreamReader(process.getOutput())) while (true) { val line = reader.readLine() ?: break logger.info(line) } return@Callable true } ) } /** * A variable pointing to the current impl of the process output logger function. * Overridable so tests can change it. */ var logOutput = OutputLogger /** * A helper function to log a given [ProcessWrapper]'s output to the given [Logger]. * A future is returned which will be completed when the end of the given * stream is reached. */ fun logOutputOfProcess(process: ProcessWrapper, logger: Logger): Future<Boolean> { return logOutput(process, logger) } } } /** * Create a logger with [name] and all of its inherited * handlers cleared, adding only the given handler */ fun getLoggerWithHandler(name: String, handler: FileHandler): Logger { return LoggerImpl(name).apply { setUseParentHandlers(false) addHandler(handler) } }
apache-2.0
b42eff081af3b2bfc94600882fe5b695
32.368421
102
0.644716
4.653211
false
false
false
false
christophpickl/gadsu
src/main/kotlin/at/cpickl/gadsu/service/internetconnection.kt
1
4523
package at.cpickl.gadsu.service import at.cpickl.gadsu.global.AppEvent import at.cpickl.gadsu.global.GADSU_LATEST_VERSION_URL import at.cpickl.gadsu.global.UserEvent import at.cpickl.gadsu.view.AsyncDialogSettings import at.cpickl.gadsu.view.AsyncWorker import at.cpickl.gadsu.view.components.DialogType import at.cpickl.gadsu.view.components.Dialogs import at.cpickl.gadsu.view.currentActiveJFrame import com.google.common.eventbus.EventBus import com.google.common.eventbus.Subscribe import com.google.common.io.Resources import com.google.inject.AbstractModule import java.net.SocketException import java.net.UnknownHostException import javax.inject.Inject class InternetConnectionLostEvent: AppEvent() class InternetConnectionEstablishedEvent: AppEvent() class InternetConnectionStateChangedEvent(val isConnected: Boolean): AppEvent() class ReconnectInternetConnectionEvent : UserEvent() class NoInternetConnectionException(cause: Throwable? = null) : RuntimeException(cause) interface InternetConnectionController { val isConnected: Boolean } @Logged open class InternetConnectionControllerImpl @Inject constructor( private val bus: EventBus, private val asyncWorker: AsyncWorker, private val dialogs: Dialogs ) : InternetConnectionController { companion object { private val HOST_TO_CHECK = "www.google.com" private val TIMEOUT_IN_MS = 4000 } private val log = LOG(javaClass) private var _isConnected = true override val isConnected: Boolean get() = _isConnected @Subscribe open fun onInternetConnectionLostEvent(event: InternetConnectionLostEvent) { dialogs.show( title = "Keine Internetverbindung", message = "Deine Internet Verbindung ist leider unterbrochen.", type = DialogType.ERROR, overrideOwner = currentActiveJFrame() ) _isConnected = false bus.post(InternetConnectionStateChangedEvent(_isConnected)) } @Subscribe open fun onInternetConnectionEstablishedEvent(event: InternetConnectionEstablishedEvent) { _isConnected = true bus.post(InternetConnectionStateChangedEvent(_isConnected)) } private fun checkIsConnected(): Boolean { // try { // log.info("Checking for host: {}", HOST_TO_CHECK) // val connected = InetAddress.getByName(HOST_TO_CHECK).isReachable(TIMEOUT_IN_MS) // if (!connected) log.info("Host was not reachable.") // return connected // } catch(e: UnknownHostException) { // log.debug("Got an UnknownHostException.") // return false // } try { // just test some URL which should be there Resources.toString(GADSU_LATEST_VERSION_URL, Charsets.UTF_8).trim() return true } catch (e: UnknownHostException) { return false } catch (e: SocketException) { return false } } @Subscribe open fun onReconnectInternetConnectionEvent(event: ReconnectInternetConnectionEvent) { if (_isConnected == true) { throw IllegalStateException("Already connected!") } asyncWorker.doInBackground(settings = AsyncDialogSettings( title = "Bitte Warten", message = "Pr\u00fcfe die Internet Verbindung" ), backgroundTask = { checkIsConnected() }, doneTask = { connectedResult -> onIsConnected(connectedResult!!) }, exceptionTask = { e -> throw e }) } private fun onIsConnected(connectedResult: Boolean) { if (connectedResult) { bus.post(InternetConnectionEstablishedEvent()) dialogs.show( title = "Internetverbindung", message = "Die Internet Verbindung wurde wieder hergestellt.", type = DialogType.INFO, overrideOwner = currentActiveJFrame() ) } else { dialogs.show( title = "Internetverbindung", message = "Die Internet Verbindung ist nach wie vor unterbrochen.", type = DialogType.WARN, overrideOwner = currentActiveJFrame() ) } } } class InternetConnectionModule : AbstractModule() { override fun configure() { bind(InternetConnectionController::class.java).to(InternetConnectionControllerImpl::class.java).asEagerSingleton() } }
apache-2.0
ac1e9bc384bd7b7555ec568430912089
35.475806
122
0.663055
4.827108
false
false
false
false
gatheringhallstudios/MHGenDatabase
app/src/main/java/com/ghstudios/android/features/items/detail/ItemDetailViewModel.kt
1
3030
package com.ghstudios.android.features.items.detail import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import com.ghstudios.android.util.MHUtils import com.ghstudios.android.data.classes.Combining import com.ghstudios.android.data.classes.Component import com.ghstudios.android.data.classes.Item import com.ghstudios.android.data.classes.meta.ItemMetadata import com.ghstudios.android.data.DataManager import com.ghstudios.android.data.classes.Gathering import com.ghstudios.android.util.loggedThread import com.ghstudios.android.util.toList data class ItemUsage( val combinations: List<Combining>, val crafting: List<Component> ) class ItemDetailViewModel(app: Application): AndroidViewModel(app) { private val dataManager = DataManager.get() val itemData = MutableLiveData<Item>() val craftData = MutableLiveData<List<Combining>>() val usageData = MutableLiveData<ItemUsage>() // live data used to create cursors. Every call returns a new cursor. Temporary and here to support incremental refactor val monsterRewardsData get() = MHUtils.createLiveData { dataManager.queryHuntingRewardItem(itemId) } // live data used to create cursors. Every call returns a new cursor. Temporary and here to support incremental refactor val questRewardsData get() = MHUtils.createLiveData { dataManager.queryQuestRewardItem(itemId) } /** * Returns a livedata containing a list of item gather data. */ val gatherData = MutableLiveData<List<Gathering>>() var itemId = -1L private set private var metadata: ItemMetadata? = null /** * If the item id is unique, loads item data. */ fun setItem(itemId: Long): ItemMetadata { if (this.itemId == itemId && this.metadata != null) { return metadata!! } this.itemId = itemId this.metadata = dataManager.queryItemMetadata(itemId) loggedThread(name = "Item Loading") { itemData.postValue(dataManager.getItem(itemId)) // query crafting usage val craftUsage = dataManager.queryComponentComponent(itemId).toList { it.component } // query combination usage val combiningResults = dataManager.queryCombiningOnItemID(itemId).toList { it.combining } // Combinations that result in this item are added to the craft list craftData.postValue(combiningResults.filter { it.createdItem.id == itemId }) usageData.postValue(ItemUsage( combinations = combiningResults.filter { it.createdItem.id != itemId }, crafting = craftUsage )) // query and post gathering data val gatherDataItems = dataManager.queryGatheringItem(itemId).toList { it.gathering } gatherData.postValue(gatherDataItems) } return metadata!! } }
mit
e2a2db550e4446c6dbd1c63f143fe52e
34.244186
124
0.686799
4.749216
false
false
false
false
evant/assertk
src/main/kotlin/me/tatarka/assertk/assertions/support/support.kt
1
1574
package me.tatarka.assertk.assertions.support import me.tatarka.assertk.* /** * Shows a value in a failure message. */ fun show(value: Any?): String = "<${display(value)}>" private fun display(value: Any?): String { return when (value) { null -> "null" is String -> "\"$value\"" is Class<*> -> value.name is Array<*> -> value.joinToString(prefix = "[", postfix = "]", transform = ::display) is Regex -> "/$value/" else -> value.toString() } } /** * Fails an assert with the given expected and actual values. */ fun <T> Assert<T>.fail(expected: Any?, actual: Any?) { if (expected == null || actual == null || expected == actual) { expected(":${show(expected)} but was:${show(actual)}") } else { val extractor = DiffExtractor(display(expected), display(actual)) val prefix = extractor.compactPrefix() val suffix = extractor.compactSuffix() expected(":<$prefix${extractor.expectedDiff()}$suffix> but was:<$prefix${extractor.actualDiff()}$suffix>") } } /** * Fails an assert with the given expected message. These should be in the format: * * expected("to be:${show(expected)} but was:${show(actual)}") * * -> "expected to be: <1> but was <2>" */ fun <T> Assert<T>.expected(message: String) { val maybeSpace = if (message.startsWith(":")) "" else " " fail("expected${formatName(name)}$maybeSpace$message") } private fun formatName(name: String?): String { return if (name.isNullOrEmpty()) { "" } else { " [$name]" } }
apache-2.0
fd78da6e1a243569904521d2b1e51e1c
28.698113
114
0.601017
3.839024
false
false
false
false
pixis/TraktTV
app/src/main/java/com/pixis/traktTV/screen_login/LoginActivity.kt
2
2626
package com.pixis.traktTV.screen_login /* import android.app.Activity import android.content.Intent import android.os.Bundle import android.widget.Toast import butterknife.BindString import butterknife.OnClick import com.pixis.traktTV.R import com.pixis.traktTV.base.BaseActivity import com.pixis.traktTV.screen_login.views.AuthDialog import com.pixis.traktTV.screen_login.views.AuthDialogResultListener import com.pixis.traktTV.screen_main_old.MainActivity import com.pixis.trakt_api.utils.Token.TokenDatabase import com.pixis.trakt_api.services_trakt.Authentication import com.pixis.trakt_api.utils.applySchedulers import timber.log.Timber import javax.inject.Inject class LoginActivity : BaseActivity() { override val layoutId = R.layout.activity_login @Inject lateinit var auth: Authentication @Inject lateinit var tokenDatabase: TokenDatabase @BindString(R.string.client_id) lateinit var client_id: String @BindString(R.string.client_secret) lateinit var client_secret: String @BindString(R.string.redirect_url) lateinit var redirect_url: String override fun init(savedInstanceState: Bundle?) { getComponent().inject(this) } @OnClick(R.id.btnLogin) fun login() { AuthDialog.newInstance(object : AuthDialogResultListener { override fun onAuthDialogFinished(resultCode: Int, bundle: Bundle?) { if (resultCode == Activity.RESULT_OK && bundle != null) { authenticate(bundle.getString("CODE")) } else { Toast.makeText(getContext(), "An error has occurred", Toast.LENGTH_SHORT) } } }).show(fragmentManager, null) } private fun authenticate(code: String) { auth.exchangeCodeForAccessToken(code = code, clientId = client_id, clientSecret = client_secret, redirectUri = redirect_url) .applySchedulers() .filter { it != null } .subscribe { tokenDatabase.saveToken(it) Timber.d("ACCESS TOKEN %s", it.toString()) onLoginFinished() } } private fun onLoginFinished() { val intent = Intent(getContext(), MainActivity::class.java) .withBackStackCleared() startActivity(intent) finish() } } //TODO extract this private fun Intent.withBackStackCleared(): Intent { return this.addFlags(android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP or android.content.Intent.FLAG_ACTIVITY_NEW_TASK) } */
apache-2.0
259567ec12998ee06faa59ebbcddf4de
30.650602
121
0.661843
4.376667
false
false
false
false
mua-uniandes/weekly-problems
codeforces/1426/1426B.kt
1
934
import java.io.BufferedReader import java.io.InputStreamReader fun main() { val In = BufferedReader(InputStreamReader(System.`in`)) val cases = In.readLine()!!.toInt() for(t in 1..cases) { val tiles = In.readLine()!!.split(" ").map{it.toInt()} val tileTypes = mutableListOf<List<List<Int>>>() for(n in 0 until tiles[0] ) { val tile1 = In.readLine()!!.split(" ").map { it.toInt() } val tile2 = In.readLine()!!.split(" ").map { it.toInt() } tileTypes.add(n, listOf(tile1, tile2)) } var covered = false if(tiles[1] % 2 == 1) println("NO") else { for (i in 0 until tiles[0]) { if (tileTypes[i][0][1] == tileTypes[i][1][0]) covered = true } if (covered) println("YES") else println("NO") } } }
gpl-3.0
0cb83ca047b18eadb9a5d62e754d8b20
30.166667
69
0.479657
3.90795
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/features/electric_machines/Blocks.kt
2
9325
package com.cout970.magneticraft.features.electric_machines import com.cout970.magneticraft.features.heat_machines.TileElectricHeater import com.cout970.magneticraft.features.heat_machines.TileRfHeater import com.cout970.magneticraft.misc.CreativeTabMg import com.cout970.magneticraft.misc.RegisterBlocks import com.cout970.magneticraft.misc.block.get import com.cout970.magneticraft.misc.resource import com.cout970.magneticraft.misc.tileentity.getModule import com.cout970.magneticraft.misc.tileentity.getTile import com.cout970.magneticraft.systems.blocks.* import com.cout970.magneticraft.systems.blocks.CommonMethods.propertyOf import com.cout970.magneticraft.systems.itemblocks.blockListOf import com.cout970.magneticraft.systems.itemblocks.itemBlockListOf import com.cout970.magneticraft.systems.tilemodules.ModuleWindTurbine import net.minecraft.block.Block import net.minecraft.block.material.Material import net.minecraft.block.properties.IProperty import net.minecraft.block.properties.PropertyEnum import net.minecraft.block.state.BlockFaceShape import net.minecraft.block.state.IBlockState import net.minecraft.item.ItemBlock import net.minecraft.util.BlockRenderLayer import net.minecraft.util.IStringSerializable /** * Created by cout970 on 2017/06/29. */ @RegisterBlocks object Blocks : IBlockMaker { val PROPERTY_DECAY_MODE: PropertyEnum<DecayMode> = propertyOf("decay_mode") val PROPERTY_WORKING_MODE: PropertyEnum<WorkingMode> = propertyOf("working_mode") lateinit var battery: BlockBase private set lateinit var electricFurnace: BlockBase private set lateinit var infiniteEnergy: BlockBase private set lateinit var airLock: BlockBase private set lateinit var airBubble: BlockBase private set lateinit var thermopile: BlockBase private set lateinit var windTurbine: BlockBase private set lateinit var windTurbineGap: BlockBase private set lateinit var electricHeater: BlockBase private set lateinit var rfHeater: BlockBase private set lateinit var rfTransformer: BlockBase private set lateinit var electricEngine: BlockBase private set override fun initBlocks(): List<Pair<Block, ItemBlock?>> { val builder = BlockBuilder().apply { material = Material.IRON creativeTab = CreativeTabMg } battery = builder.withName("battery").copy { states = CommonMethods.Orientation.values().toList() factory = factoryOf(::TileBattery) alwaysDropDefault = true generateDefaultItemBlockModel = false hasCustomModel = true customModels = listOf( "model" to resource("models/block/mcx/battery.mcx"), "inventory" to resource("models/block/mcx/battery.mcx") ) //methods onBlockPlaced = CommonMethods::placeWithOrientation pickBlock = CommonMethods::pickDefaultBlock onActivated = CommonMethods::openGui }.build() electricFurnace = builder.withName("electric_furnace").copy { material = Material.ROCK states = CommonMethods.OrientationActive.values().toList() factory = factoryOf(::TileElectricFurnace) alwaysDropDefault = true //methods onBlockPlaced = CommonMethods::placeInactiveWithOppositeOrientation pickBlock = CommonMethods::pickDefaultBlock onActivated = CommonMethods::openGui }.build() infiniteEnergy = builder.withName("infinite_energy").copy { factory = factoryOf(::TileInfiniteEnergy) }.build() airBubble = builder.withName("air_bubble").copy { states = DecayMode.values().toList() material = Material.GLASS tickRandomly = true blockLayer = BlockRenderLayer.CUTOUT hasCustomModel = true tickRate = 1 onNeighborChanged = { if (it.state[PROPERTY_DECAY_MODE]?.enable == true && it.worldIn.rand.nextBoolean()) { it.worldIn.setBlockToAir(it.pos) } } onUpdateTick = { if (it.state[PROPERTY_DECAY_MODE]?.enable == true) { it.world.setBlockToAir(it.pos) } } onDrop = { emptyList() } collisionBox = { null } shouldSideBeRendered = func@{ val state = it.blockAccess.getBlockState(it.pos.offset(it.side)) if (state.block === it.state.block) false else !state.doesSideBlockRendering(it.blockAccess, it.pos.offset(it.side), it.side.opposite) } }.build() airLock = builder.withName("airlock").copy { factory = factoryOf(::TileAirLock) onActivated = CommonMethods::openGui }.build() thermopile = builder.withName("thermopile").copy { factory = factoryOf(::TileThermopile) //methods onActivated = CommonMethods::openGui }.build() windTurbine = builder.withName("wind_turbine").copy { states = CommonMethods.Orientation.values().toList() factory = factoryOf(::TileWindTurbine) alwaysDropDefault = true generateDefaultItemBlockModel = false hasCustomModel = true customModels = listOf( "model" to resource("models/block/mcx/wind_turbine.mcx") ) //methods onActivated = CommonMethods::openGui onBlockPlaced = CommonMethods::placeWithOrientation pickBlock = CommonMethods::pickDefaultBlock }.build() windTurbineGap = builder.withName("wind_turbine_gap").copy { factory = factoryOf(::TileWindTurbineGap) hasCustomModel = true onDrop = { emptyList() } onBlockBreak = func@{ val thisTile = it.worldIn.getTile<TileWindTurbineGap>(it.pos) ?: return@func val pos = thisTile.centerPos ?: return@func val mod = it.worldIn.getModule<ModuleWindTurbine>(pos) ?: return@func if (mod.hasTurbineHitbox) { mod.removeTurbineHitbox() } it.worldIn.removeTileEntity(it.pos) } blockFaceShape = { BlockFaceShape.UNDEFINED } }.build() electricHeater = builder.withName("electric_heater").copy { states = WorkingMode.values().toList() factory = factoryOf(::TileElectricHeater) alwaysDropDefault = true pickBlock = CommonMethods::pickDefaultBlock onActivated = CommonMethods::openGui }.build() rfHeater = builder.withName("rf_heater").copy { states = WorkingMode.values().toList() factory = factoryOf(::TileRfHeater) alwaysDropDefault = true pickBlock = CommonMethods::pickDefaultBlock onActivated = CommonMethods::openGui }.build() rfTransformer = builder.withName("rf_transformer").copy { factory = factoryOf(::TileRfTransformer) onActivated = CommonMethods::openGui }.build() electricEngine = builder.withName("electric_engine").copy { states = CommonMethods.Facing.values().toList() factory = factoryOf(::TileElectricEngine) alwaysDropDefault = true generateDefaultItemBlockModel = false hasCustomModel = true customModels = listOf( "model" to resource("models/block/gltf/electric_engine.gltf"), "inventory" to resource("models/block/gltf/electric_engine.gltf") ) //methods onActivated = CommonMethods::openGui onBlockPlaced = CommonMethods::placeWithOppositeFacing pickBlock = CommonMethods::pickDefaultBlock }.build() return itemBlockListOf(battery, electricFurnace, infiniteEnergy, airBubble, airLock, thermopile, windTurbine, electricHeater, rfHeater, rfTransformer, electricEngine) + blockListOf(windTurbineGap) } enum class WorkingMode( override val stateName: String, override val isVisible: Boolean, val enable: Boolean ) : IStatesEnum, IStringSerializable { OFF("off", true, false), ON("on", false, true); override fun getName() = name.toLowerCase() override val properties: List<IProperty<*>> get() = listOf(PROPERTY_WORKING_MODE) override fun getBlockState(block: Block): IBlockState { return block.defaultState.withProperty(PROPERTY_WORKING_MODE, this) } } enum class DecayMode( override val stateName: String, override val isVisible: Boolean, val enable: Boolean ) : IStatesEnum, IStringSerializable { OFF("off", true, false), ON("on", false, true); override fun getName() = name.toLowerCase() override val properties: List<IProperty<*>> get() = listOf(PROPERTY_DECAY_MODE) override fun getBlockState(block: Block): IBlockState { return block.defaultState.withProperty(PROPERTY_DECAY_MODE, this) } } }
gpl-2.0
cdc178b95bf3e306262db089be7c4f89
40.0837
111
0.644075
4.740722
false
false
false
false
mallowigi/a-file-icon-idea
common/src/main/java/com/mallowigi/config/associations/ui/columns/NameEditableColumnInfo.kt
1
3761
/* * The MIT License (MIT) * * Copyright (c) 2015-2022 Elior "Mallowigi" Boukhobza * * 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.mallowigi.config.associations.ui.columns import com.intellij.openapi.Disposable import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.ui.cellvalidators.StatefulValidatingCellEditor import com.intellij.openapi.ui.cellvalidators.ValidatingTableCellRendererWrapper import com.intellij.ui.components.fields.ExtendableTextField import com.intellij.util.ui.table.TableModelEditor.EditableColumnInfo import com.mallowigi.config.AtomSettingsBundle.message import com.mallowigi.config.associations.ui.internal.ModifiedInfoCellRenderer import com.mallowigi.icons.associations.Association import javax.swing.table.TableCellEditor import javax.swing.table.TableCellRenderer /** * Editable column info for [Association] name * * @property parent the Parent class * @property editable whether the column should be editable */ @Suppress("UnstableApiUsage") class NameEditableColumnInfo(private val parent: Disposable, private val editable: Boolean) : EditableColumnInfo<Association, String>(message("AssociationsForm.folderIconsTable.columns.name")) { /** * The value of the column is the name * * @param item the [Association] * @return [Association] name */ override fun valueOf(item: Association): String = item.name /** * Set [Association]'s name * * @param item the [Association] * @param value the new name */ override fun setValue(item: Association, value: String) { item.name = value item.touched = true } /** * Creates an editor for the name, with empty value validation * * @param item the [Association] * @return the [TableCellEditor] */ override fun getEditor(item: Association): TableCellEditor { val cellEditor = ExtendableTextField() return StatefulValidatingCellEditor(cellEditor, parent) } /** * Creates a renderer for the name: displays the name with a calidation tooltip if the name is empty * * @param item the [Association] * @return the [TableCellRenderer] */ override fun getRenderer(item: Association): TableCellRenderer? { return ValidatingTableCellRendererWrapper(ModifiedInfoCellRenderer(item)) .withCellValidator { value: Any?, _: Int, _: Int -> if (value == null || value == "") { return@withCellValidator ValidationInfo(message("AtomAssocConfig.NameEditor.empty")) } else { return@withCellValidator null } } } /** * Whether the cell is editable * * @param item * @return */ override fun isCellEditable(item: Association): Boolean = editable }
mit
c94dbabdc16f0e7a28e35943612acceb
36.237624
102
0.738367
4.414319
false
false
false
false
mcmacker4/PBR-Test
src/main/kotlin/net/upgaming/pbrengine/graphics/ShaderProgram.kt
1
2568
package net.upgaming.pbrengine.graphics import org.joml.Vector3f import org.lwjgl.opengl.GL11.* import org.lwjgl.opengl.GL20.* import java.io.File import java.nio.FloatBuffer import java.nio.file.Files class ShaderProgram(private val program: Int) { fun start() { glUseProgram(program) } fun stop() { glUseProgram(program) } fun loadFloat(varname: String, value: Float) { val loc = glGetUniformLocation(program, varname) glUniform1f(loc, value) } fun loadInt(varname: String, value: Int) { val loc = glGetUniformLocation(program, varname) glUniform1i(loc, value) } fun loadVector3f(varname: String, vec: Vector3f) { val loc = glGetUniformLocation(program, varname) glUniform3f(loc, vec.x, vec.y, vec.z) } fun loadMatrix4f(varname: String, buffer: FloatBuffer) { val loc = glGetUniformLocation(program, varname) glUniformMatrix4fv(loc, false, buffer) } fun delete() { glDeleteProgram(program) } companion object { fun load(name: String): ShaderProgram { val vsrc = Files.readAllLines(File("res/shaders/$name.v.glsl").toPath()).joinToString("\n") val fsrc = Files.readAllLines(File("res/shaders/$name.f.glsl").toPath()).joinToString("\n") return load(vsrc, fsrc) } fun load(vsrc: String, fsrc: String): ShaderProgram { val program = glCreateProgram() val vshader = createShader(GL_VERTEX_SHADER, vsrc) val fshader = createShader(GL_FRAGMENT_SHADER, fsrc) glAttachShader(program, vshader) glAttachShader(program, fshader) glLinkProgram(program) if(glGetProgrami(program, GL_LINK_STATUS) != GL_TRUE) throw Exception(glGetProgramInfoLog(program)) glValidateProgram(program) if(glGetProgrami(program, GL_VALIDATE_STATUS) != GL_TRUE) throw Exception(glGetProgramInfoLog(program)) glDeleteShader(vshader) glDeleteShader(fshader) return ShaderProgram(program) } private fun createShader(type: Int, src: String): Int { val shader = glCreateShader(type) glShaderSource(shader, src) glCompileShader(shader) if(glGetShaderi(shader, GL_COMPILE_STATUS) != GL_TRUE) throw Exception(glGetShaderInfoLog(shader)) return shader } } }
apache-2.0
6fec17d0dc630c4ff1b54f779d5df042
31.1125
103
0.61176
4.382253
false
false
false
false
toastkidjp/Jitte
app/src/main/java/jp/toastkid/yobidashi/search/favorite/ModuleViewHolder.kt
1
2583
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.search.favorite import android.view.View import android.view.ViewGroup import androidx.annotation.ColorInt import androidx.annotation.DrawableRes import androidx.core.view.isVisible import androidx.core.view.updateMargins import androidx.recyclerview.widget.RecyclerView import jp.toastkid.lib.view.SwipeViewHolder import jp.toastkid.yobidashi.R import jp.toastkid.yobidashi.databinding.ItemSearchHistoryBinding /** * @author toastkidjp */ internal class ModuleViewHolder(private val binding: ItemSearchHistoryBinding) : RecyclerView.ViewHolder(binding.root), SwipeViewHolder { private val buttonMargin = binding.root.resources .getDimensionPixelSize(R.dimen.button_margin) init { binding.searchHistoryBookmark.visibility = View.GONE binding.time.visibility = View.GONE } fun setText(text: String?) { binding.searchHistoryText.text = text } fun setImageRes(@DrawableRes iconId: Int) { binding.searchHistoryImage.setImageResource(iconId) } fun setOnClickAdd(history: FavoriteSearch, onClickAdd: (FavoriteSearch) -> Unit) { binding.searchHistoryAdd.setOnClickListener { _ -> onClickAdd(history) } } fun setOnClickDelete(onClick: () -> Unit) { binding.delete.setOnClickListener { onClick() } } fun setAddIcon(@DrawableRes addIcon: Int) { binding.searchHistoryAdd.setImageResource(addIcon) } fun setIconColor(@ColorInt color: Int) { binding.searchHistoryAdd.setColorFilter(color) } override fun getFrontView(): View = binding.front override fun isButtonVisible(): Boolean = binding.delete.isVisible override fun showButton() { binding.delete.visibility = View.VISIBLE updateRightMargin(buttonMargin) } override fun hideButton() { binding.delete.visibility = View.INVISIBLE updateRightMargin(0) } private fun updateRightMargin(margin: Int) { val marginLayoutParams = binding.front.layoutParams as? ViewGroup.MarginLayoutParams marginLayoutParams?.rightMargin = margin binding.front.layoutParams = marginLayoutParams marginLayoutParams?.updateMargins() } }
epl-1.0
e8071b20cfaf1e862a577a8dba7b76c2
30.120482
92
0.721642
4.696364
false
false
false
false
SergeyPirogov/kirk
kirk-core/src/main/kotlin/com/automation/remarks/kirk/conditions/Have.kt
1
505
@file:JvmName("Have") package com.automation.remarks.kirk.conditions /** * Created by sergey on 25.06.17. */ fun text(text: String) = Text(text) fun size(size: Int) = CollectionSize(size) fun sizeAtLeast(size: Int) = CollectionMinimumSize(size) fun elementWithText(text: String) = CollectionContainText(text) fun exactText(vararg text: String) = CollectionExactText(text) fun attr(name: String, value: String) = AttributeValue(name, value) fun cssClass(cssClass: String) = CssClassValue(cssClass)
apache-2.0
58757227f1b7e21f39331e85efbaecc0
25.631579
67
0.758416
3.344371
false
false
false
false
chrisbanes/tivi
common/ui/compose/src/main/java/app/tivi/common/compose/ui/UserProfileButton.kt
1
2367
/* * Copyright 2021 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 * * 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 app.tivi.common.compose.ui import androidx.compose.foundation.layout.size import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Person import androidx.compose.material.icons.outlined.Person import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import app.tivi.data.entities.TraktUser import app.tivi.common.ui.resources.R as UiR @Composable fun UserProfileButton( loggedIn: Boolean, user: TraktUser?, onClick: () -> Unit, modifier: Modifier = Modifier ) { IconButton( onClick = onClick, modifier = modifier ) { when { loggedIn && user?.avatarUrl != null -> { AsyncImage( model = user.avatarUrl!!, requestBuilder = { crossfade(true) }, contentDescription = stringResource( UiR.string.cd_profile_pic, user.name ?: user.username ), modifier = Modifier .size(32.dp) .clip(MaterialTheme.shapes.small) ) } else -> { Icon( imageVector = when { loggedIn -> Icons.Default.Person else -> Icons.Outlined.Person }, contentDescription = stringResource(UiR.string.cd_user_profile) ) } } } }
apache-2.0
50ddbec608700abd3c739e6b4867fd1c
32.814286
83
0.617659
4.772177
false
false
false
false
polson/MetroTripper
app/src/main/java/com/philsoft/metrotripper/app/state/transformer/MapTransformer.kt
1
2577
package com.philsoft.metrotripper.app.state.transformer import com.google.android.gms.location.LocationResult import com.google.android.gms.maps.model.LatLng import com.philsoft.metrotripper.app.state.AppState import com.philsoft.metrotripper.app.state.LocationUiEvent.InitialLocationUpdate import com.philsoft.metrotripper.app.state.MapAction import com.philsoft.metrotripper.app.state.MapUiEvent.CameraIdle import com.philsoft.metrotripper.app.state.StopHeadingUiEvent.LocationButtonClicked import com.philsoft.metrotripper.app.state.StopListUiEvent.StopSearched import com.philsoft.metrotripper.app.state.StopListUiEvent.StopSelectedFromDrawer import com.philsoft.metrotripper.model.Stop class MapTransformer : ViewActionTransformer<MapAction>() { companion object { private val MINNEAPOLIS_LATLNG = LatLng(44.9799700, -93.2638400) } override fun handleEvent(state: AppState) = state.appUiEvent.run { when (this) { is InitialLocationUpdate -> handleInitialLocationUpdate(locationResult) is LocationButtonClicked -> handleLocationButtonClicked(state.selectedStop) is StopSearched -> handleStopSearched(state.selectedStop) is StopSelectedFromDrawer -> handleStopSelected(stop) is CameraIdle -> handleCameraIdle(state.visibleStops) } } private fun handleStopSelected(stop: Stop) { send(MapAction.MoveCameraToPosition(stop.latLng)) send(MapAction.SelectStopMarker(stop)) } private fun handleCameraIdle(visibleStops: List<Stop>) { send(MapAction.ShowStopMarkers(visibleStops)) } private fun handleStopSearched(selectedStop: Stop?) { if (selectedStop != null) { send(MapAction.MoveCameraToPosition(selectedStop.latLng)) send(MapAction.SelectStopMarker(selectedStop)) } } private fun handleInitialLocationUpdate(locationResult: LocationResult) { val lastLocation = locationResult.lastLocation if (lastLocation != null) { val latLng = LatLng(lastLocation.latitude, lastLocation.longitude) send(MapAction.MoveCameraToPosition(latLng)) send(MapAction.EnableLocationButton(true)) } else { send(MapAction.MoveCameraToPosition(MINNEAPOLIS_LATLNG)) } } private fun handleLocationButtonClicked(selectedStop: Stop?) { if (selectedStop != null) { send(MapAction.MoveCameraToPosition(selectedStop.latLng)) send(MapAction.SelectStopMarker(selectedStop)) } } }
apache-2.0
379b4dd003fd642c028c5ced8b07b82d
39.904762
87
0.729919
4.473958
false
false
false
false
NordicSemiconductor/Android-nRF-Toolbox
profile_uart/src/main/java/no/nordicsemi/android/uart/data/UARTManager.kt
1
7727
/* * 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.uart.data import android.annotation.SuppressLint import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGattCharacteristic import android.bluetooth.BluetoothGattService import android.content.Context import android.util.Log import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.* import no.nordicsemi.android.ble.BleManager import no.nordicsemi.android.ble.WriteRequest import no.nordicsemi.android.ble.common.callback.battery.BatteryLevelResponse import no.nordicsemi.android.ble.ktx.asFlow import no.nordicsemi.android.ble.ktx.asValidResponseFlow import no.nordicsemi.android.ble.ktx.suspend import no.nordicsemi.android.logger.NordicLogger import no.nordicsemi.android.service.ConnectionObserverAdapter import no.nordicsemi.android.utils.EMPTY import no.nordicsemi.android.utils.launchWithCatch import java.util.* val UART_SERVICE_UUID: UUID = UUID.fromString("6E400001-B5A3-F393-E0A9-E50E24DCCA9E") private val UART_RX_CHARACTERISTIC_UUID = UUID.fromString("6E400002-B5A3-F393-E0A9-E50E24DCCA9E") private val UART_TX_CHARACTERISTIC_UUID = UUID.fromString("6E400003-B5A3-F393-E0A9-E50E24DCCA9E") private val BATTERY_SERVICE_UUID = UUID.fromString("0000180F-0000-1000-8000-00805f9b34fb") private val BATTERY_LEVEL_CHARACTERISTIC_UUID = UUID.fromString("00002A19-0000-1000-8000-00805f9b34fb") internal class UARTManager( context: Context, private val scope: CoroutineScope, private val logger: NordicLogger ) : BleManager(context) { private var batteryLevelCharacteristic: BluetoothGattCharacteristic? = null private var rxCharacteristic: BluetoothGattCharacteristic? = null private var txCharacteristic: BluetoothGattCharacteristic? = null private var useLongWrite = true private val data = MutableStateFlow(UARTData()) val dataHolder = ConnectionObserverAdapter<UARTData>() init { connectionObserver = dataHolder data.onEach { dataHolder.setValue(it) }.launchIn(scope) } override fun log(priority: Int, message: String) { logger.log(priority, message) } override fun getMinLogPriority(): Int { return Log.VERBOSE } private inner class UARTManagerGattCallback : BleManagerGattCallback() { @SuppressLint("WrongConstant") override fun initialize() { setNotificationCallback(txCharacteristic).asFlow() .flowOn(Dispatchers.IO) .map { val text: String = it.getStringValue(0) ?: String.EMPTY log(10, "\"$text\" received") val messages = data.value.messages + UARTRecord(text, UARTRecordType.OUTPUT) messages.takeLast(50) } .onEach { data.value = data.value.copy(messages = it) }.launchIn(scope) requestMtu(517).enqueue() enableNotifications(txCharacteristic).enqueue() setNotificationCallback(batteryLevelCharacteristic).asValidResponseFlow<BatteryLevelResponse>() .onEach { data.value = data.value.copy(batteryLevel = it.batteryLevel) }.launchIn(scope) enableNotifications(batteryLevelCharacteristic).enqueue() } override fun isRequiredServiceSupported(gatt: BluetoothGatt): Boolean { val service: BluetoothGattService? = gatt.getService(UART_SERVICE_UUID) if (service != null) { rxCharacteristic = service.getCharacteristic(UART_RX_CHARACTERISTIC_UUID) txCharacteristic = service.getCharacteristic(UART_TX_CHARACTERISTIC_UUID) } var writeRequest = false var writeCommand = false rxCharacteristic?.let { val rxProperties: Int = it.properties writeRequest = rxProperties and BluetoothGattCharacteristic.PROPERTY_WRITE > 0 writeCommand = rxProperties and BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE > 0 // Set the WRITE REQUEST type when the characteristic supports it. // This will allow to send long write (also if the characteristic support it). // In case there is no WRITE REQUEST property, this manager will divide texts // longer then MTU-3 bytes into up to MTU-3 bytes chunks. if (!writeRequest) { useLongWrite = false } } gatt.getService(BATTERY_SERVICE_UUID)?.run { batteryLevelCharacteristic = getCharacteristic(BATTERY_LEVEL_CHARACTERISTIC_UUID) } return rxCharacteristic != null && txCharacteristic != null && (writeRequest || writeCommand) } override fun onServicesInvalidated() { batteryLevelCharacteristic = null rxCharacteristic = null txCharacteristic = null useLongWrite = true } } @SuppressLint("WrongConstant") fun send(text: String) { if (rxCharacteristic == null) return scope.launchWithCatch { val writeType = if (useLongWrite) { BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT } else { BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE } val request: WriteRequest = writeCharacteristic(rxCharacteristic, text.toByteArray(), writeType) if (!useLongWrite) { request.split() } request.suspend() data.value = data.value.copy( messages = data.value.messages + UARTRecord( text, UARTRecordType.INPUT ) ) log(10, "\"$text\" sent") } } fun clearItems() { data.value = data.value.copy(messages = emptyList()) } override fun getGattCallback(): BleManagerGattCallback { return UARTManagerGattCallback() } }
bsd-3-clause
28831ccaead0c8e3bcfa56570b8b55cd
39.883598
107
0.6762
4.802362
false
false
false
false
Pagejects/pagejects-integration
pagejects-allure/src/main/kotlin/net/pagejects/allure/AllurePagejectsAdaptor.kt
1
1456
package net.pagejects.allure import net.pagejects.core.PageObjectListener import ru.yandex.qatools.allure.Allure import ru.yandex.qatools.allure.annotations.Step import ru.yandex.qatools.allure.events.StepFinishedEvent import ru.yandex.qatools.allure.events.StepStartedEvent import java.lang.reflect.Method import java.text.MessageFormat import java.util.* /** * This class allow to integrate Allure with Pagejects * * @author Andrey Paslavsky * @since 0.1 */ class AllurePagejectsAdaptor(private val allure: Allure = Allure.LIFECYCLE) : PageObjectListener { override fun beforeMethod(method: Method, pageObject: Any, args: Array<out Any?>?) { val step = method.getAnnotation(Step::class.java) if (step != null) { val event = StepStartedEvent(method.nameWithArgs(args)).withTitle(step.title(args)) allure.fire(event) } } private fun Step.title(args: Array<out Any?>?): String? = if (value.isNotBlank()) { if (args != null) MessageFormat.format(value, *args) else MessageFormat.format(value) } else { null } private fun Method.nameWithArgs(args: Array<out Any?>?) = if (args != null) name + Arrays.toString(args) else name override fun afterMethod(method: Method, pageObject: Any, args: Array<out Any?>?, result: Any?) { if (method.isAnnotationPresent(Step::class.java)) { allure.fire(StepFinishedEvent()) } } }
apache-2.0
f9de372dceb140254f82e3bbb7c35442
34.536585
101
0.692308
3.752577
false
false
false
false
PSPDFKit-labs/QuickDemo
app/src/main/kotlin/com/pspdfkit/labs/quickdemo/activity/ConfigurationActivity.kt
1
5690
/* * Copyright (c) 2016-2019 PSPDFKit GmbH. All rights reserved. * * THIS SOURCE CODE AND ANY ACCOMPANYING DOCUMENTATION ARE PROTECTED BY INTERNATIONAL COPYRIGHT LAW * AND MAY NOT BE RESOLD OR REDISTRIBUTED. USAGE IS BOUND TO THE PSPDFKIT LICENSE AGREEMENT. * UNAUTHORIZED REPRODUCTION OR DISTRIBUTION IS SUBJECT TO CIVIL AND CRIMINAL PENALTIES. * This notice may not be removed from this file */ package com.pspdfkit.labs.quickdemo.activity import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.content.SharedPreferences import android.os.Bundle import android.preference.PreferenceFragment import android.preference.SwitchPreference import androidx.annotation.ArrayRes import androidx.appcompat.app.AppCompatActivity import com.pspdfkit.labs.quickdemo.DemoMode import com.pspdfkit.labs.quickdemo.R class ConfigurationActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) supportActionBar?.setIcon(R.drawable.ic_configuration_activity) fragmentManager.beginTransaction().replace(android.R.id.content, DemoModePreferences()).commit() } override fun onStart() { super.onStart() // Whenever this activity comes to the foreground, we check if the required permissions have been granted. // If the permissions are missing, launch the setup guide. val demoMode = DemoMode.get(this) if (!demoMode.requiredPermissionsGranted || !demoMode.demoModeAllowed) { SetupGuideActivity.launch(this) // We have to finish this activity, otherwise users that do not complete the setup guide would end up in a endless loop. finish() } } class DemoModePreferences : PreferenceFragment(), SharedPreferences.OnSharedPreferenceChangeListener { private lateinit var demoMode: DemoMode private var updateFromReceiver: Boolean = false private val demoModeChangeReceiver = object : BroadcastReceiver() { override fun onReceive(p0: Context?, p1: Intent?) { updateFromReceiver = true updateDemoModeSwitch() updateFromReceiver = false } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) demoMode = DemoMode.get(context) addPreferencesFromResource(R.xml.demo_mode_preferences) preferenceManager.sharedPreferences.registerOnSharedPreferenceChangeListener(this) updateSummaries() } fun updateSummaries() { setSummaryFromArrayValue("batteryLevel", R.array.batteryLevelEscaped, R.array.batteryLevelValues, DemoMode.DEFAULT_BATTERY_LEVEL.toString()) setSummaryFromArrayValue("statusBarMode", R.array.statusBarModes, R.array.statusBarModeValues, DemoMode.DEFAULT_STATUS_BAR_MODE) setSummaryFromArrayValue("networkMobileDatatype", R.array.networkMobileDatatypes, R.array.networkMobileDatatypeValues, DemoMode.DEFAULT_MOBILE_DATATYPE) setSummaryFromArrayValue("networkMobileLevel", R.array.networkReceptionLevels, R.array.networkReceptionLevelValues, DemoMode.DEFAULT_MOBILE_LEVEL.toString()) setSummaryFromArrayValue("networkNumberOfSims", R.array.networkNumOfSims, R.array.networkNumOfSims, DemoMode.DEFAULT_NETWORK_NUM_OF_SIMS.toString()) setSummaryFromArrayValue("networkWifiLevel", R.array.networkReceptionLevels, R.array.networkReceptionLevelValues, DemoMode.DEFAULT_WIFI_LEVEL.toString()) setSummaryFromArrayValue("statusVolume", R.array.statusVolume, R.array.statusVolumeValues, DemoMode.DEFAULT_STATUS_HIDDEN) setSummaryFromArrayValue("statusBluetooth", R.array.statusBluetooth, R.array.statusBluetoothValues, DemoMode.DEFAULT_STATUS_HIDDEN) } fun setSummaryFromArrayValue(key: String, @ArrayRes labelArrayRes: Int, @ArrayRes valueArrayRes: Int, default: String) { val preference = findPreference(key) val value = preferenceManager.sharedPreferences.getString(key, default) val i = resources.getStringArray(valueArrayRes).indexOf(value) if (i >= 0) preference.summary = resources.getStringArray(labelArrayRes)[i] } override fun onStart() { super.onStart() context.registerReceiver(demoModeChangeReceiver, IntentFilter("com.android.systemui.demo")) updateDemoModeSwitch() } override fun onStop() { super.onStop() context.unregisterReceiver(demoModeChangeReceiver) } private fun updateDemoModeSwitch() { val enabled = findPreference("enable_demo") as SwitchPreference enabled.isChecked = demoMode.enabled } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { when (key) { "enable_demo" -> { if (!updateFromReceiver) demoMode.enabled = sharedPreferences.getBoolean(key, false) } "batteryLevel", "statusBarMode", "networkMobileDatatype", "networkMobileLevel", "networkNumberOfSims", "networkWifiLevel", "statusVolume", "statusBluetooth" -> { updateSummaries() } } } } companion object { fun launch(context: Context) { val intent = Intent(context, ConfigurationActivity::class.java) context.startActivity(intent) } } }
mit
910f25f3d72b08ab2e3266894304da40
46.416667
169
0.700176
4.978128
false
false
false
false
eprendre/v2rayNG
V2rayNG/app/src/main/kotlin/com/v2ray/ang/receiver/NetWorkStateReceiver.kt
1
3495
package com.v2ray.ang.receiver import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.net.ConnectivityManager import android.widget.Toast import com.v2ray.ang.AppConfig import com.v2ray.ang.util.MessageUtil class NetWorkStateReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { var isConnected = false try { //检测API是不是小于23,因为到了API23之后getNetworkInfo(int networkType)方法被弃用 if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) { val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetwork = cm.activeNetworkInfo if (activeNetwork != null) { // connected to the internet if (activeNetwork.type == ConnectivityManager.TYPE_WIFI) { // connected to wifi isConnected = true //Toast.makeText(context, activeNetwork.typeName, Toast.LENGTH_SHORT).show() } else if (activeNetwork.type == ConnectivityManager.TYPE_MOBILE) { // connected to the mobile provider's data plan isConnected = true //Toast.makeText(context, activeNetwork.typeName, Toast.LENGTH_SHORT).show() } } else { // not connected to the internet } //API大于23时使用下面的方式进行网络监听 } else { //获得ConnectivityManager对象 val connMgr = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager //获取所有网络连接的信息 val networks = connMgr.allNetworks if (networks != null) { //通过循环将网络信息逐个取出来 loop@ for (i in networks.indices) { //获取ConnectivityManager对象对应的NetworkInfo对象 val networkInfo = connMgr.getNetworkInfo(networks[i]) if (networkInfo != null && networkInfo.isConnected) { if (networkInfo.type == ConnectivityManager.TYPE_WIFI) { // connected to wifi isConnected = true //Toast.makeText(context, networkInfo.typeName, Toast.LENGTH_SHORT).show() break@loop } else if (networkInfo.type == ConnectivityManager.TYPE_MOBILE) { // connected to mobile isConnected = true //Toast.makeText(context, networkInfo.typeName, Toast.LENGTH_SHORT).show() break@loop } } } } } } catch (e: Exception) { e.printStackTrace() } if (isConnected) { sendMsg2Service(context) } } private fun sendMsg2Service(context: Context) { //Toast.makeText(context, "Restart v2ray", Toast.LENGTH_SHORT).show() MessageUtil.sendMsg2Service(context, AppConfig.MSG_STATE_RESTART_SOFT, "") } }
mit
9cb7401d94e4982f3d7e8348ef00740a
44.27027
107
0.536578
5.366987
false
false
false
false
alashow/music-android
modules/ui-downloads/src/main/java/tm/alashow/datmusic/ui/downloads/Downloads.kt
1
2659
/* * Copyright (C) 2021, Alashov Berkeli * All rights reserved. */ package tm.alashow.datmusic.ui.downloads import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.Divider import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.hilt.navigation.compose.hiltViewModel import com.google.accompanist.insets.ui.Scaffold import tm.alashow.common.compose.rememberFlowWithLifecycle import tm.alashow.datmusic.domain.entities.AudioDownloadItem import tm.alashow.datmusic.downloader.DownloadItems import tm.alashow.datmusic.ui.downloads.audio.AudioDownload import tm.alashow.domain.models.Success import tm.alashow.domain.models.Uninitialized import tm.alashow.ui.components.AppTopBar import tm.alashow.ui.components.EmptyErrorBox import tm.alashow.ui.components.fullScreenLoading @Composable fun Downloads() { Downloads(viewModel = hiltViewModel()) } @Composable private fun Downloads(viewModel: DownloadsViewModel) { val listState = rememberLazyListState() val asyncDownloads by rememberFlowWithLifecycle(viewModel.downloadRequests).collectAsState(Uninitialized) Scaffold( topBar = { AppTopBar(title = stringResource(R.string.downloads_title)) }, modifier = Modifier.fillMaxSize() ) { padding -> LazyColumn( state = listState, contentPadding = padding, ) { when (val dls = asyncDownloads) { is Success -> downloadsList( downloads = dls(), onAudioPlay = viewModel::playAudioDownload ) else -> fullScreenLoading() } } } } fun LazyListScope.downloadsList( downloads: DownloadItems, onAudioPlay: (AudioDownloadItem) -> Unit, ) { val downloadsEmpty = downloads.audios.isEmpty() if (downloadsEmpty) { item { EmptyErrorBox( message = stringResource(R.string.downloads_empty), retryVisible = false, modifier = Modifier.fillParentMaxHeight() ) } } itemsIndexed(downloads.audios, { _, it -> it.downloadRequest.id }) { index, it -> if (index != 0) Divider() AudioDownload(it, onAudioPlay) } }
apache-2.0
d587a6eda62aea856599a42aa17d4496
32.2375
109
0.705904
4.640489
false
false
false
false
rustamgaifullin/TranslateIt
api/src/test/kotlin/com/rm/translateit/api/models/translation/WordsTest.kt
1
1029
package com.rm.translateit.api.models.translation import com.rm.translateit.api.models.translation.Words.Companion.words import org.junit.Assert import org.junit.Test class WordsTest { @Test fun should_return_string_from_one_item_in_word_list() { //given val sut = words("One word") //when val result = sut.toOneLineString() //then Assert.assertEquals("the string should be equal to one word", "One word", result) } @Test fun should_return_string_from_few_items_in_word_list() { //given val sut = words("First word", "Second word") //when val result = sut.toOneLineString() //then Assert.assertEquals( "the string should be formed from several words", "First word, Second word", result ) } @Test fun should_return_empty_string_when_word_list_is_empty() { //given val sut = words("") //when val result = sut.toOneLineString() //then Assert.assertEquals("the string should be formed from several words", "", result) } }
mit
d5b4c44d6efab8b672f934ededfa6d74
21.888889
91
0.664723
3.675
false
true
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/shop_type/SearchAdapter.kt
2
1858
package de.westnordost.streetcomplete.quests.shop_type import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.Filter import android.widget.Filterable import android.widget.TextView class SearchAdapter<T>( private val context: Context, private val filterQuery: (term: String) -> List<T>, private val convertToString: (T) -> String ) : BaseAdapter(), Filterable { private val filter = SearchFilter() private var items: List<T> = emptyList() set(value) { field = value notifyDataSetChanged() } override fun getCount(): Int = items.size override fun getItem(position: Int): T = items[position] override fun getItemId(position: Int): Long = position.toLong() override fun getFilter() = filter override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val view = convertView ?: LayoutInflater.from(context).inflate(android.R.layout.simple_dropdown_item_1line, parent, false) (view as TextView).text = filter.convertResultToString(getItem(position)) return view } inner class SearchFilter : Filter() { override fun performFiltering(constraint: CharSequence?) = FilterResults().also { val term = constraint?.toString() ?: "" val results = filterQuery(term) it.count = results.size it.values = results } override fun publishResults(constraint: CharSequence?, results: FilterResults) { items = results.values as List<T> } override fun convertResultToString(resultValue: Any?): CharSequence { return (resultValue as? T?)?.let(convertToString) ?: super.convertResultToString(resultValue) } } }
gpl-3.0
ce9a98e1dbb6a13127fa8ad969761f50
34.056604
130
0.685145
4.621891
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/GameColorsFragment.kt
1
10067
package com.boardgamegeek.ui import android.graphics.* import android.os.Bundle import android.view.* import androidx.annotation.ColorInt import androidx.core.content.ContextCompat import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import com.boardgamegeek.R import com.boardgamegeek.databinding.FragmentColorsBinding import com.boardgamegeek.extensions.* import com.boardgamegeek.ui.adapter.GameColorRecyclerViewAdapter import com.boardgamegeek.ui.dialog.AddColorToGameDialogFragment import com.boardgamegeek.ui.viewmodel.GameColorsViewModel import com.google.android.material.snackbar.Snackbar import kotlin.math.max import kotlin.math.min class GameColorsFragment : Fragment() { private var _binding: FragmentColorsBinding? = null private val binding get() = _binding!! @ColorInt private var iconColor = Color.TRANSPARENT private var actionMode: ActionMode? = null private val swipePaint = Paint() private var deleteIcon: Bitmap? = null private val viewModel by activityViewModels<GameColorsViewModel>() private val adapter: GameColorRecyclerViewAdapter by lazy { createAdapter() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } @Suppress("RedundantNullableReturnType") override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = FragmentColorsBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.fab.colorize(iconColor) setUpRecyclerView() arguments?.let { iconColor = it.getInt(KEY_ICON_COLOR, Color.TRANSPARENT) } binding.fab.colorize(iconColor) binding.fab.setOnClickListener { requireActivity().showAndSurvive(AddColorToGameDialogFragment()) } viewModel.colors.observe(viewLifecycleOwner) { it?.let { adapter.colors = it binding.emptyView.fade(it.isEmpty()) binding.recyclerView.fade(it.isNotEmpty(), isResumed) binding.fab.show() binding.progressView.fadeOut() } } } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun setUpRecyclerView() { binding.recyclerView.adapter = adapter swipePaint.color = ContextCompat.getColor(requireContext(), R.color.delete) deleteIcon = requireContext().getBitmap(R.drawable.ic_baseline_delete_24, Color.WHITE) val itemTouchHelper = ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) { override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean { return false } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, swipeDir: Int) { adapter.getColorName(viewHolder.bindingAdapterPosition)?.let { color -> viewModel.removeColor(color) Snackbar.make(binding.containerView, getString(R.string.msg_color_deleted, color), Snackbar.LENGTH_INDEFINITE) .setAction(R.string.undo) { viewModel.addColor(color) } .show() } } override fun getSwipeDirs(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int { return if (actionMode != null) 0 else super.getSwipeDirs(recyclerView, viewHolder) } override fun onChildDraw( c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean ) { val horizontalPadding = requireContext().resources.getDimension(R.dimen.material_margin_horizontal) if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) { val itemView = viewHolder.itemView deleteIcon?.let { val verticalPadding = (itemView.height - it.height) / 2.toFloat() val background: RectF val iconSrc: Rect val iconDst: RectF if (dX > 0) { background = RectF(itemView.left.toFloat(), itemView.top.toFloat(), dX, itemView.bottom.toFloat()) iconSrc = Rect(0, 0, min((dX - itemView.left - horizontalPadding).toInt(), it.width), it.height) iconDst = RectF( itemView.left.toFloat() + horizontalPadding, itemView.top.toFloat() + verticalPadding, min(itemView.left + horizontalPadding + it.width, dX), itemView.bottom.toFloat() - verticalPadding ) } else { background = RectF(itemView.right.toFloat() + dX, itemView.top.toFloat(), itemView.right.toFloat(), itemView.bottom.toFloat()) iconSrc = Rect(max(it.width + horizontalPadding.toInt() + dX.toInt(), 0), 0, it.width, it.height) iconDst = RectF( max(itemView.right.toFloat() + dX, itemView.right.toFloat() - horizontalPadding - it.width), itemView.top.toFloat() + verticalPadding, itemView.right.toFloat() - horizontalPadding, itemView.bottom.toFloat() - verticalPadding ) } c.drawRect(background, swipePaint) c.drawBitmap(it, iconSrc, iconDst, swipePaint) } } super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive) } }) itemTouchHelper.attachToRecyclerView(binding.recyclerView) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.game_colors, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return if (item.itemId == R.id.menu_colors_generate) { viewModel.computeColors() binding.containerView.snackbar(R.string.msg_colors_generated) true } else super.onOptionsItemSelected(item) } private fun createAdapter(): GameColorRecyclerViewAdapter { return GameColorRecyclerViewAdapter(object : GameColorRecyclerViewAdapter.Callback { override fun onItemClick(position: Int) { if (actionMode != null) { toggleSelection(position) } } override fun onItemLongPress(position: Int): Boolean { if (actionMode != null) return false actionMode = requireActivity().startActionMode(object : ActionMode.Callback { override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { mode.menuInflater.inflate(R.menu.colors_context, menu) adapter.clearSelections() binding.fab.hide() return true } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { return false } override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { when (item.itemId) { R.id.menu_delete -> { val colors = adapter.getSelectedColors() val count = colors.size colors.forEach { viewModel.removeColor(it) } binding.containerView.snackbar(resources.getQuantityString(R.plurals.msg_colors_deleted, count, count)) mode.finish() return true } } mode.finish() return false } override fun onDestroyActionMode(mode: ActionMode) { actionMode = null adapter.clearSelections() binding.fab.show() } }) if (actionMode == null) return false toggleSelection(position) return true } private fun toggleSelection(position: Int) { adapter.toggleSelection(position) val count = adapter.selectedItemCount if (count == 0) { actionMode?.finish() } else { actionMode?.title = resources.getQuantityString(R.plurals.msg_colors_selected, count, count) actionMode?.invalidate() } } }) } companion object { private const val KEY_ICON_COLOR = "ICON_COLOR" fun newInstance(@ColorInt iconColor: Int): GameColorsFragment { return GameColorsFragment().apply { arguments = bundleOf(KEY_ICON_COLOR to iconColor) } } } }
gpl-3.0
d046180c5066cded646f780ba08b49a1
42.206009
145
0.569981
5.690786
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
fluxc/src/main/java/org/wordpress/android/fluxc/action/CommentsAction.kt
2
1982
package org.wordpress.android.fluxc.action import org.wordpress.android.fluxc.annotations.Action import org.wordpress.android.fluxc.annotations.ActionEnum import org.wordpress.android.fluxc.annotations.action.IAction import org.wordpress.android.fluxc.model.CommentModel import org.wordpress.android.fluxc.store.CommentStore.FetchCommentsPayload import org.wordpress.android.fluxc.store.CommentStore.FetchCommentsResponsePayload import org.wordpress.android.fluxc.store.CommentStore.RemoteCommentPayload import org.wordpress.android.fluxc.store.CommentStore.RemoteCommentResponsePayload import org.wordpress.android.fluxc.store.CommentStore.RemoteCreateCommentPayload @Deprecated( "This is a temporary code for backward compatibility and will be replaced with " + "Comments Unification project." ) @ActionEnum enum class CommentsAction : IAction { // Remote actions @Action(payloadType = FetchCommentsPayload::class) FETCH_COMMENTS, @Action(payloadType = RemoteCommentPayload::class) FETCH_COMMENT, @Action(payloadType = RemoteCreateCommentPayload::class) CREATE_NEW_COMMENT, @Action(payloadType = RemoteCommentPayload::class) PUSH_COMMENT, @Action(payloadType = RemoteCommentPayload::class) DELETE_COMMENT, @Action(payloadType = RemoteCommentPayload::class) LIKE_COMMENT, // Remote responses @Action(payloadType = FetchCommentsResponsePayload::class) FETCHED_COMMENTS, @Action(payloadType = RemoteCommentResponsePayload::class) FETCHED_COMMENT, @Action(payloadType = RemoteCommentResponsePayload::class) CREATED_NEW_COMMENT, @Action(payloadType = RemoteCommentResponsePayload::class) PUSHED_COMMENT, @Action(payloadType = RemoteCommentResponsePayload::class) DELETED_COMMENT, @Action(payloadType = RemoteCommentResponsePayload::class) LIKED_COMMENT, // Local actions @Action(payloadType = CommentModel::class) UPDATE_COMMENT }
gpl-2.0
694b00299e58845846509c9915559f63
32.033333
90
0.776993
4.327511
false
false
false
false
PKRoma/github-android
app/src/main/java/com/github/pockethub/android/ui/repo/RepositoryViewActivity.kt
5
12753
/* * Copyright (c) 2015 PocketHub * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pockethub.android.ui.repo import android.content.Intent import android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP import android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP import android.net.Uri import android.os.Bundle import android.text.TextUtils import android.view.Menu import android.view.MenuItem import android.view.View import com.afollestad.materialdialogs.MaterialDialog import com.github.pockethub.android.Intents.Builder import com.github.pockethub.android.Intents.EXTRA_REPOSITORY import com.github.pockethub.android.R import com.github.pockethub.android.ResultCodes.RESOURCE_CHANGED import com.github.pockethub.android.core.repo.RepositoryUtils import com.github.pockethub.android.rx.AutoDisposeUtils import com.github.pockethub.android.ui.DialogResultListener import com.github.pockethub.android.ui.base.BaseActivity import com.github.pockethub.android.ui.helpers.PagerHandler import com.github.pockethub.android.ui.user.UriLauncherActivity import com.github.pockethub.android.ui.user.UserViewActivity import com.github.pockethub.android.util.InfoUtils import com.github.pockethub.android.util.ShareUtils import com.github.pockethub.android.util.ToastUtils import com.meisolsson.githubsdk.core.ServiceGenerator import com.meisolsson.githubsdk.model.Repository import com.meisolsson.githubsdk.service.activity.StarringService import com.meisolsson.githubsdk.service.repositories.RepositoryContentService import com.meisolsson.githubsdk.service.repositories.RepositoryForkService import com.meisolsson.githubsdk.service.repositories.RepositoryService import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.pager_with_tabs.* import kotlinx.android.synthetic.main.tabbed_progress_pager.* import retrofit2.Response /** * Activity to view a repository */ class RepositoryViewActivity : BaseActivity(), DialogResultListener { private var repository: Repository? = null private var isStarred: Boolean = false private var starredStatusChecked: Boolean = false private var hasReadme: Boolean = false private var pagerHandler: PagerHandler<RepositoryPagerAdapter>? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.tabbed_progress_pager) repository = intent.getParcelableExtra(EXTRA_REPOSITORY) val owner = repository!!.owner()!! val actionBar = supportActionBar!! actionBar.title = repository!!.name() actionBar.subtitle = owner.login() actionBar.setDisplayHomeAsUpEnabled(true) if (owner.avatarUrl() != null && RepositoryUtils.isComplete(repository!!)) { checkReadme() } else { pb_loading.visibility = View.VISIBLE ServiceGenerator.createService(this, RepositoryService::class.java) .getRepository(repository!!.owner()!!.login(), repository!!.name()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .`as`(AutoDisposeUtils.bindToLifecycle(this)) .subscribe({ response -> if (response.isSuccessful) { repository = response.body() checkReadme() } else { ToastUtils.show(this, R.string.error_repo_load) pb_loading.visibility = View.GONE } }, { e -> ToastUtils.show(this, R.string.error_repo_load) pb_loading.visibility = View.GONE }) } } override fun onCreateOptionsMenu(optionsMenu: Menu): Boolean { menuInflater.inflate(R.menu.activity_repository, optionsMenu) return super.onCreateOptionsMenu(optionsMenu) } override fun onPrepareOptionsMenu(menu: Menu): Boolean { val followItem = menu.findItem(R.id.m_star) followItem.isVisible = starredStatusChecked followItem.setTitle(if (isStarred) R.string.unstar else R.string.star) val parentRepo = menu.findItem(R.id.m_parent_repo) if (repository != null && repository!!.isFork != null) parentRepo.isVisible = repository!!.isFork!! return super.onPrepareOptionsMenu(menu) } override fun onBackPressed() { if (pagerHandler?.adapter == null || vp_pages.currentItem != pagerHandler?.adapter!!.itemCode || !pagerHandler?.adapter!!.onBackPressed()) { super.onBackPressed() } } private fun checkReadme() { pb_loading.visibility = View.VISIBLE ServiceGenerator.createService(this, RepositoryContentService::class.java) .hasReadme(repository!!.owner()!!.login(), repository!!.name()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .`as`(AutoDisposeUtils.bindToLifecycle(this)) .subscribe({ response -> hasReadme = response.code() == 200 configurePager() }, { e -> hasReadme = false configurePager() }) } private fun configurePager() { val adapter = RepositoryPagerAdapter(this, repository!!.hasIssues()!!, hasReadme) pagerHandler = PagerHandler(this, vp_pages, adapter) lifecycle.addObserver(pagerHandler!!) pagerHandler!!.tabs = sliding_tabs_layout pb_loading.visibility = View.GONE pagerHandler!!.setGone(false) checkStarredRepositoryStatus() } override fun onDestroy() { super.onDestroy() lifecycle.removeObserver(pagerHandler!!) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.m_star -> { starRepository() return true } R.id.m_fork -> { forkRepository() return true } R.id.m_contributors -> { startActivity(RepositoryContributorsActivity.createIntent(repository)) return true } R.id.m_share -> { shareRepository() return true } R.id.m_parent_repo -> { if (repository!!.parent() == null) { ServiceGenerator.createService(this, RepositoryService::class.java) .getRepository(repository!!.owner()!!.login(), repository!!.name()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { response -> val parent = response.body()!!.parent() startActivity(RepositoryViewActivity.createIntent(parent!!)) } } else { startActivity(RepositoryViewActivity.createIntent(repository!!.parent()!!)) } return true } R.id.m_delete -> { deleteRepository() return true } R.id.m_refresh -> { checkStarredRepositoryStatus() return super.onOptionsItemSelected(item) } android.R.id.home -> { finish() val intent = UserViewActivity.createIntent(repository!!.owner()!!) intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP or FLAG_ACTIVITY_SINGLE_TOP) startActivity(intent) return true } else -> return super.onOptionsItemSelected(item) } } override fun onDialogResult(requestCode: Int, resultCode: Int, arguments: Bundle) { pagerHandler?.adapter!!.onDialogResult(vp_pages.currentItem, requestCode, resultCode, arguments) } private fun starRepository() { val service = ServiceGenerator.createService(this, StarringService::class.java) val starSingle: Single<Response<Void>> starSingle = if (isStarred) { service.unstarRepository(repository!!.owner()!!.login(), repository!!.name()) } else { service.starRepository(repository!!.owner()!!.login(), repository!!.name()) } starSingle.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .`as`(AutoDisposeUtils.bindToLifecycle(this)) .subscribe({ aVoid -> isStarred = !isStarred setResult(RESOURCE_CHANGED) }, { e -> ToastUtils.show(this, if (isStarred) R.string.error_unstarring_repository else R.string.error_starring_repository) }) } private fun checkStarredRepositoryStatus() { starredStatusChecked = false ServiceGenerator.createService(this, StarringService::class.java) .checkIfRepositoryIsStarred(repository!!.owner()!!.login(), repository!!.name()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .`as`(AutoDisposeUtils.bindToLifecycle(this)) .subscribe { response -> isStarred = response.code() == 204 starredStatusChecked = true invalidateOptionsMenu() } } private fun shareRepository() { var repoUrl = repository!!.htmlUrl() if (TextUtils.isEmpty(repoUrl)) { repoUrl = "https://github.com/" + InfoUtils.createRepoId(repository!!) } val sharingIntent = ShareUtils.create(InfoUtils.createRepoId(repository!!), repoUrl) startActivity(sharingIntent) } private fun forkRepository() { ServiceGenerator.createService(this, RepositoryForkService::class.java) .createFork(repository!!.owner()!!.login(), repository!!.name()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .`as`(AutoDisposeUtils.bindToLifecycle(this)) .subscribe({ response -> val repo = response.body()!! UriLauncherActivity.launchUri(this, Uri.parse(repo.htmlUrl())) }, { e -> ToastUtils.show(this, R.string.error_forking_repository) }) } private fun deleteRepository() { MaterialDialog.Builder(this) .title(R.string.are_you_sure) .content(R.string.unexpected_bad_things) .positiveText(R.string.not_sure) .negativeText(R.string.delete_cap) .callback(object : MaterialDialog.ButtonCallback() { override fun onPositive(dialog: MaterialDialog?) { super.onPositive(dialog) dialog!!.dismiss() } override fun onNegative(dialog: MaterialDialog?) { super.onNegative(dialog) dialog!!.dismiss() ServiceGenerator.createService(dialog.context, RepositoryService::class.java) .deleteRepository(repository!!.owner()!!.login(), repository!!.name()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .`as`(AutoDisposeUtils.bindToLifecycle(lifecycle)) .subscribe({ response -> onBackPressed() ToastUtils.show(this@RepositoryViewActivity, R.string.delete_successful) }, { e -> ToastUtils.show(this@RepositoryViewActivity, R.string.error_deleting_repository) }) } }) .show() } companion object { val TAG = "RepositoryViewActivity" /** * Create intent for this activity * * @param repository * @return intent */ fun createIntent(repository: Repository): Intent { return Builder("repo.VIEW").repo(repository).toIntent() } } }
apache-2.0
1cceeebe5151c16399e1e8adf36e17b9
39.485714
148
0.620325
5.119631
false
false
false
false
sabi0/intellij-community
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/util.kt
1
3598
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.intellij.build.images import com.intellij.openapi.util.io.FileUtil import com.intellij.util.SVGLoader import java.awt.Dimension import java.awt.Image import java.io.File import java.math.BigInteger import java.security.MessageDigest import javax.imageio.ImageIO internal val File.children: List<File> get() = if (isDirectory) listFiles().toList() else emptyList() internal fun isImage(file: File, iconsOnly: Boolean): Boolean { if (!isImage(file)) return false return !iconsOnly || isIcon(file) } internal fun isIcon(file: File): Boolean { if (!isImage(file)) return false val size = imageSize(file) ?: return false return size.height == size.width || size.height <= 100 && size.width <= 100 } internal fun isImage(file: File) = ImageExtension.fromFile(file) != null internal fun imageSize(file: File): Dimension? { val image = loadImage(file) if (image == null) { println("WARNING: can't load ${file.path}") return null } val width = image.getWidth(null) val height = image.getHeight(null) return Dimension(width, height) } internal fun loadImage(file: File): Image? { try { if (file.name.endsWith(".svg")) { return SVGLoader.load(file.toURI().toURL(), 1.0f) } else { return ImageIO.read(file) } } catch (e: Exception) { e.printStackTrace() return null } } internal fun md5(file: File): String { val md5 = MessageDigest.getInstance("MD5") val bytes = file.inputStream().readBytes() val hash = md5.digest(bytes) return BigInteger(hash).abs().toString(16) } internal enum class ImageType(private val suffix: String) { BASIC(""), RETINA("@2x"), DARCULA("_dark"), RETINA_DARCULA("@2x_dark"); companion object { fun getBasicName(file: File, prefix: List<String>): String { return getBasicName(file.name, prefix) } fun getBasicName(suffix: String, prefix: List<String>): String { val name = FileUtil.getNameWithoutExtension(suffix) return stripSuffix((prefix + name).joinToString("/")) } fun fromFile(file: File): ImageType { val name = FileUtil.getNameWithoutExtension(file.name) return fromName(name) } fun fromName(name: String): ImageType { if (name.endsWith(RETINA_DARCULA.suffix)) return RETINA_DARCULA if (name.endsWith(RETINA.suffix)) return RETINA if (name.endsWith(DARCULA.suffix)) return DARCULA return BASIC } fun stripSuffix(name: String): String { val type = fromName(name) return name.removeSuffix(type.suffix) } } } internal enum class ImageExtension(private val suffix: String) { PNG(".png"), SVG(".svg"), GIF(".gif"); companion object { fun fromFile(file: File): ImageExtension? { return fromName(file.name) } fun fromName(name: String): ImageExtension? { if (name.endsWith(PNG.suffix)) return PNG if (name.endsWith(SVG.suffix)) return SVG if (name.endsWith(GIF.suffix)) return GIF return null } } }
apache-2.0
4f78f05d1d59074fbfd271810bca5ad9
28.5
101
0.691217
3.844017
false
false
false
false
zhufucdev/PCtoPE
app/src/main/java/com/zhufucdev/pctope/activities/DetailsActivity.kt
1
23443
package com.zhufucdev.pctope.activities import android.app.Activity import android.app.ProgressDialog import android.content.* import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.os.AsyncTask import android.os.Build import androidx.core.widget.NestedScrollView import androidx.appcompat.app.AlertDialog import android.os.Bundle import android.os.Environment import androidx.appcompat.widget.Toolbar import android.view.* import android.view.animation.AccelerateDecelerateInterpolator import android.view.animation.AnimationUtils import android.widget.* import androidx.cardview.widget.CardView import com.bm.library.PhotoView import com.google.android.material.appbar.CollapsingToolbarLayout import com.google.android.material.bottomsheet.BottomSheetDialog import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.snackbar.Snackbar import com.zhufucdev.pctope.utils.Textures import com.zhufucdev.pctope.R import com.zhufucdev.pctope.utils.* import java.io.File import java.io.FileInputStream import java.io.IOException import java.math.BigDecimal import java.nio.channels.FileChannel import kotlin.math.roundToInt class DetailsActivity : BaseActivity(), ViewTreeObserver.OnPreDrawListener { private var name: String? = null private var description: String? = null private lateinit var version: String private var icon: String? = null private lateinit var path: String private lateinit var textures: Textures private lateinit var textureEditor: Textures.Edit private lateinit var size: BigDecimal private lateinit var cards: NestedScrollView private lateinit var fab: FloatingActionButton private var compressSize = 0 private var compressFinalSize = 0 private var isDataChanged = false /* Some Utils */ fun getFolderTotalSize(path: String): Long { val files = File(path).listFiles() var size: Long = 0 for (f in files!!) if (f.exists()) { if (f.isFile) { var fc: FileChannel? = null var inputStream: FileInputStream? = null try { inputStream = FileInputStream(f) fc = inputStream.channel size += fc!!.size() inputStream.close() } catch (e: IOException) { e.printStackTrace() } } else size += getFolderTotalSize(f.path) } return size } private fun MakeErrorDialog(errorString: String) { //make up a error dialog val error_dialog = AlertDialog.Builder(this@DetailsActivity) error_dialog.setTitle(R.string.error) error_dialog.setMessage([email protected](R.string.error_dialog) + errorString) error_dialog.setIcon(R.drawable.alert_octagram) error_dialog.setCancelable(false) error_dialog.setPositiveButton(R.string.close, null) error_dialog.setNegativeButton(R.string.copy) { dialogInterface, i -> val copy = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager copy.setPrimaryClip(ClipData.newPlainText("PathCopied", path)) }.show() } private var fabListener: View.OnClickListener = View.OnClickListener { val dialogView = LayoutInflater.from(this@DetailsActivity) .inflate(R.layout.details_texture_basic_info_editor, null) val dialog = AlertDialog.Builder(this@DetailsActivity) dialog.setTitle(R.string.project_icon_edit) dialog.setView(dialogView) val editName = dialogView.findViewById<EditText>(R.id.details_edit_name) val editDescription = dialogView.findViewById<EditText>(R.id.details_edit_description) editName.setText(name) editDescription.setText(description) dialog.setPositiveButton(R.string.confirm) { dialogInterface, i -> val setName = editName.text.toString() val setDescription = editDescription.text.toString() if (setName != name || setDescription != description) { mLog.i( "Edit", "Change name and description of $name to $setName and $setDescription" ) textureEditor.changeNameAndDescription(setName, setDescription) isDataChanged = true loadDetailedInfo() } } dialog.setNeutralButton(R.string.icon_edit) { _, _ -> val intent = Intent(this, FileChooserActivity::class.java) startActivityForResult(intent, 0) } dialog.show() } override fun onCreate(bundle: Bundle?) { super.onCreate(bundle) setContentView(R.layout.activity_details) progress = findViewById(R.id.details_loading_progress) fab = findViewById(R.id.details_fab) fab.setOnClickListener(fabListener) val intent = intent icon = intent.getStringExtra("texture_icon")!! version = intent.getStringExtra("texture_version")!! name = intent.getStringExtra("texture_name")!! description = intent.getStringExtra("texture_description")!! path = intent.getStringExtra("texture_path")!! initBasicTitles() initToolbar() loadDetailedInfo() } fun updateInformation() { textures = Textures(File(path)) textureEditor = Textures.Edit(path) //on Crash textureEditor.setOnCrashListener(object : Textures.Edit.OnCrashListener { override fun onCrash(e: String) { MakeErrorDialog(e) } }) version = textures.getVersion() name = textures.name description = textures.description val totalSize = BigDecimal(getFolderTotalSize(path)) val BtoMB = BigDecimal(1024 * 1024) size = totalSize.divide(BtoMB, 5, BigDecimal.ROUND_HALF_UP) } fun loadDetailedInfo() { cards = findViewById(R.id.details_info_layout) class LoadingTask : AsyncTask<Void, Int, Boolean>() { public override fun onPreExecute() { showLoading() fab.isEnabled = false cards.visibility = View.INVISIBLE } public override fun doInBackground(vararg params: Void): Boolean { updateInformation() if (description == null) { description = "" } return true } public override fun onPostExecute(result: Boolean?) { initBasicTitles() loadViews() hideLoading() initOperationalCards() } } LoadingTask().execute() } fun loadViews() { //-----FloatingActionButton----- fab.isEnabled = true //-----CARD------ val size = findViewById<TextView>(R.id.details_texture_size) size.text = "${getString(R.string.details_card_basic_info_size)} : ${this.size} MB" val location = findViewById<TextView>(R.id.details_texture_location) location.text = (getString(R.string.details_card_basic_info_location) + ": " + path).toString() location.setOnClickListener { view -> val clipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val data = ClipData.newPlainText("Path", path) clipboardManager.setPrimaryClip(data) Snackbar.make(view, R.string.copied, Snackbar.LENGTH_SHORT).show() } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val anim = ViewAnimationUtils.createCircularReveal( cards, cards.width / 2, 0, 0f, Math.hypot( cards.width.toDouble(), cards.height.toDouble() ).toFloat() ) cards.visibility = View.VISIBLE anim.duration = 500 anim.interpolator = AccelerateDecelerateInterpolator() anim.start() } else { cards.visibility = View.VISIBLE } } lateinit var iconView: ImageView lateinit var iconFullScreenView: PhotoView lateinit var iconLayout: FrameLayout lateinit var toolbarLayout: CollapsingToolbarLayout var isFullScreenShown = false fun setFullScreen(shown: Boolean) { isFullScreenShown = shown val mInfo = PhotoView.getImageViewInfo(iconView) if (shown) { iconView.visibility = View.INVISIBLE iconLayout.visibility = View.VISIBLE iconLayout.startAnimation(AnimationUtils.loadAnimation(this, R.anim.cards_show)) iconFullScreenView.animaFrom(mInfo) fab.visibility = View.INVISIBLE } else { iconFullScreenView.animaTo(mInfo) { iconLayout.startAnimation(AnimationUtils.loadAnimation(this, R.anim.cards_hide)) iconLayout.visibility = View.GONE iconView.visibility = View.VISIBLE fab.visibility = View.VISIBLE } } } fun initBasicTitles() { iconView = findViewById(R.id.details_icon) iconFullScreenView = findViewById(R.id.photo_view) iconLayout = findViewById(R.id.full_screen_image_view_layout) val packdescription = findViewById<TextView>(R.id.details_description) toolbarLayout = findViewById(R.id.details_toolbar_layout) val vto = iconView.viewTreeObserver vto.addOnPreDrawListener(this) if (icon != null) { val icon = BitmapFactory.decodeFile(icon) iconView.setImageBitmap(icon) iconFullScreenView.setImageBitmap(icon) } else iconView.setImageResource(R.drawable.bug_pack_icon) iconFullScreenView.enable() iconFullScreenView.maxScale = 8f iconView.setOnClickListener { setFullScreen(true) } iconFullScreenView.setOnClickListener { setFullScreen(false) } if (!name.isNullOrEmpty()) toolbarLayout.title = name else toolbarLayout.title = getString(R.string.unable_to_get_name) val smallestWith = resources.configuration.smallestScreenWidthDp mLog.d("Smallest Screen Width", "$smallestWith") if (!description.isNullOrEmpty()) { packdescription.visibility = View.VISIBLE packdescription.text = description toolbarLayout.expandedTitleMarginBottom = (3 / 7.0 * smallestWith).roundToInt() } else { packdescription.visibility = View.INVISIBLE toolbarLayout.expandedTitleMarginBottom = (25 / 79.0 * smallestWith).roundToInt() } } override fun onPreDraw(): Boolean { toolbarLayout.expandedTitleMarginStart = (iconView.measuredWidth * 1.3).roundToInt() mLog.d("Titles", "Margin set.") iconView.viewTreeObserver.removeOnPreDrawListener(this) return true } fun initToolbar() { val toolbar = findViewById<Toolbar>(R.id.details_toolbar) setSupportActionBar(toolbar) val actionBar = supportActionBar actionBar?.setDisplayHomeAsUpEnabled(true) } fun initOperationalCards() { val verStr = textures.getVersion() //Set Compression val baseFrom = if (verStr == (TextureCompat.fullPC) || verStr == (TextureCompat.brokenPC)) "$path/assets/minecraft/textures" else "$path/textures" var image: String = FindFile.withKeywordOnce("grass_side.png", baseFrom)!! //grass >> sword >> never mind if (image.isEmpty()) { image = FindFile.withKeywordOnce("iron_sword.png", baseFrom)!! if (image.isEmpty()) image = FindFile.withKeywordOnce(".png", baseFrom)!! } val imageLocation = image //set listener val compress = findViewById<CardView>(R.id.compression_card) compress.setOnClickListener(View.OnClickListener { val dialog = BottomSheetDialog(this@DetailsActivity) val dialogView = layoutInflater.inflate(R.layout.compression_dialog, null) dialog.setContentView(dialogView) val bitmap = BitmapFactory.decodeFile(imageLocation) val confirm = dialogView.findViewById<Button>(R.id.compression_button_confirm) loadDialogLayout(dialogView, bitmap) val spinner = dialogView.findViewById<Spinner>(R.id.compression_spinner) spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected( adapterView: AdapterView<*>, view: View, i: Int, l: Long ) { val options = resources.getStringArray(R.array.compression_options) compressSize = when (options[i]) { "8x" -> 8 "16x" -> 16 "32x" -> 32 "64x" -> 64 "128x" -> 128 "256x" -> 256 "512x" -> 512 else -> 0 } if (compressSize != 0) { loadDialogLayout( dialogView, CompressImage.getBitmap(bitmap, compressSize, compressSize) ) } else loadDialogLayout(dialogView, bitmap) if (compressSize > bitmap.width || compressSize > bitmap.height) { confirm.isEnabled = false confirm.setTextColor(resources.getColor(R.color.grey_primary)) Toast.makeText( this@DetailsActivity, R.string.compression_alert, Toast.LENGTH_SHORT ).show() } else { confirm.isEnabled = true confirm.setTextColor(resources.getColor(R.color.colorAccent)) } } override fun onNothingSelected(adapterView: AdapterView<*>) { compressSize = 0 } } dialog.setOnCancelListener { compressSize = compressFinalSize } dialog.show() confirm.setOnClickListener(View.OnClickListener { compressFinalSize = compressSize dialog.dismiss() if (compressFinalSize == 0) { return@OnClickListener } val progressDialog = ProgressDialog(this@DetailsActivity) progressDialog.setTitle(R.string.progress_compressing_title) progressDialog.setMessage(getString(R.string.please_wait)) progressDialog.show() textureEditor.setOnCompressionProgressChangeListener(object : Textures.Edit.CompressionProgressChangeListener { override fun progressChangeListener( whatsBeingCompressed: String?, isDone: Boolean ) { if (!isDone) { runOnUiThread { progressDialog.setTitle(R.string.progress_compressing_title) progressDialog.setMessage(whatsBeingCompressed) } } else { runOnUiThread { progressDialog.dismiss() loadDetailedInfo() } } } }) Thread(Runnable { textureEditor.compressImages(compressFinalSize) }).start() }) }) //For mcpack compress card val mcpackCard = findViewById<CardView>(R.id.card_mcpack_compress) val mcpackSubtitle = findViewById<TextView>(R.id.card_mcpack_compress_subtitle) val mcpackChe = findViewById<ImageView>(R.id.card_mcpack_compress_chevron) val mcpackPath = File("${Environment.getExternalStorageDirectory()}/games/com.mojang/mcpacks/${name}.mcpack") val isMcpackExisted = mcpackPath.exists() && mcpackPath.isFile if (!isMcpackExisted) { mcpackSubtitle.text = "${getString(R.string.mcpack_compress_subtitle)} $mcpackPath" mcpackChe.setImageResource(R.drawable.chevron_right_overlay) mcpackChe.setOnClickListener(null) mcpackChe.background = null } else { mcpackSubtitle.text = "${getString(R.string.mcpack_exists)} $mcpackPath" mcpackChe.setImageResource(R.drawable.ic_delete_black_24dp) mcpackChe.setOnClickListener { if (isMcpackExisted) { val alertDialog = AlertDialog.Builder(this@DetailsActivity) .setMessage(R.string.mcpack_delete) .setPositiveButton(R.string.confirm) { _, _ -> mcpackPath.delete() initOperationalCards() } .setNegativeButton(R.string.no, null) .create() alertDialog.show() } } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mcpackChe.background = getDrawable(R.drawable.nomaskripple) } } mcpackCard.setOnClickListener { if (!isMcpackExisted) { class compressingTask : AsyncTask<Void, Void, Int>() { lateinit var progressDialog: ProgressDialog override fun onPreExecute() { progressDialog = ProgressDialog(this@DetailsActivity) progressDialog.setTitle(R.string.compressing_mcpack) progressDialog.setMessage(mcpackPath.path) progressDialog.show() super.onPreExecute() } override fun doInBackground(vararg p0: Void?): Int { textureEditor!!.setMcpack(mcpackPath.path) return 0 } override fun onPostExecute(result: Int?) { progressDialog.hide() initOperationalCards() super.onPostExecute(result) } } compressingTask().execute() } else { val intent = Intent(Intent.ACTION_SEND) val uri = Uri.parse(mcpackPath.path) intent.putExtra(Intent.EXTRA_STREAM, uri) intent.type = "*/*" startActivity(Intent.createChooser(intent, getString(R.string.share))) } } } private fun loadDialogLayout(dialogView: View, bitmap: Bitmap?) { val spinner = dialogView.findViewById<Spinner>(R.id.compression_spinner) if (compressSize != 0) { when (compressSize) { 8 -> spinner.setSelection(1) 16 -> spinner.setSelection(2) 32 -> spinner.setSelection(3) 64 -> spinner.setSelection(4) 128 -> spinner.setSelection(5) 256 -> spinner.setSelection(6) 512 -> spinner.setSelection(7) else -> spinner.setSelection(0) } } else spinner.setSelection(0, true) //set view val preview = dialogView.findViewById<ImageView>(R.id.compression_image) preview.setImageBitmap(bitmap) //set text val width_text = dialogView.findViewById<TextView>(R.id.compression_width_text) val height_text = dialogView.findViewById<TextView>(R.id.compression_height_text) width_text.text = bitmap!!.width.toString() height_text.text = bitmap.height.toString() } private var progress: ProgressBar? = null fun showLoading() { progress!!.visibility = View.VISIBLE } fun hideLoading() { progress!!.visibility = View.GONE } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId when (id) { android.R.id.home -> onBackPressed() } return true } override fun onBackPressed() { if (!isFullScreenShown) { fab.visibility = View.INVISIBLE val intent = Intent() intent.putExtra("isDataChanged", isDataChanged) setResult(Activity.RESULT_OK, intent) super.onBackPressed() } else { setFullScreen(false) } } //Activity Result override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK) if (requestCode == 0) { val iconMap = BitmapFactory.decodeFile(data!!.getStringExtra("path")) if (CompressImage.testBitmap(512, 512, iconMap)) { val builder = AlertDialog.Builder(this@DetailsActivity) builder.setTitle(R.string.icon_edit_high_res_title) builder.setMessage(R.string.icon_edit_high_res_subtitle) builder.setPositiveButton(R.string.confirm) { dialogInterface, i -> try { var scale = 1f val scaleHeight = 512f / iconMap.height val scaleWidth = 512f / iconMap.width scale = if (scaleHeight <= scaleWidth) scaleHeight else scaleWidth textureEditor.iconEdit(CompressImage.getBitmap(iconMap, scale)) } catch (e: IOException) { e.printStackTrace() } loadDetailedInfo() } builder.setNegativeButton(R.string.thanks) { _, _ -> try { textureEditor.iconEdit(iconMap) } catch (e: IOException) { e.printStackTrace() } loadDetailedInfo() } builder.show() } else { try { textureEditor.iconEdit(iconMap) } catch (e: IOException) { e.printStackTrace() } loadDetailedInfo() } isDataChanged = true } } }
gpl-3.0
e76e9592110aca614d5b257188be42e3
35.746082
104
0.565243
5.282334
false
false
false
false
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/ui/RecyclerItemClickListener.kt
1
5252
package com.pr0gramm.app.ui import android.view.GestureDetector import android.view.MotionEvent import android.view.View import androidx.recyclerview.widget.RecyclerView import com.pr0gramm.app.Logger import com.pr0gramm.app.ui.fragments.feed.FeedItemViewHolder import com.pr0gramm.app.util.OnClickListener import com.pr0gramm.app.util.OnViewClickListener import com.pr0gramm.app.util.invoke class RecyclerItemClickListener(private val recyclerView: RecyclerView) { private val logger = Logger("RecyclerItemClickListener") private var touchListener: Listener? = null private val scrollListener = ScrollListener() private var longClickEnabled: Boolean = false private var longPressJustTriggered: Boolean = false private var ignoreLongTap: Boolean = false var itemClicked: OnViewClickListener? = null var itemLongClicked: OnViewClickListener? = null var itemLongClickEnded: OnClickListener? = null init { recyclerView.addOnScrollListener(scrollListener) touchListener = Listener().also { listener -> recyclerView.addOnItemTouchListener(listener) } } fun enableLongClick(enabled: Boolean) { longClickEnabled = enabled longPressJustTriggered = longPressJustTriggered and enabled } private var lastChildView: View? = null private inner class Listener : RecyclerView.SimpleOnItemTouchListener() { private val mGestureDetector = GestureDetector(recyclerView.context, object : GestureDetector.SimpleOnGestureListener() { override fun onSingleTapUp(e: MotionEvent): Boolean { lastChildView?.let { childView -> itemClicked?.invoke(childView) } return true } override fun onLongPress(e: MotionEvent) { if (touchListener !== this@Listener) { return } logger.debug { "LongPress event detected: $e" } if (longClickEnabled) { val childView = recyclerView.findChildViewUnder(e.x, e.y) if (childView != null) { longPressJustTriggered = true itemLongClicked(childView) } } } }) override fun onInterceptTouchEvent(view: RecyclerView, e: MotionEvent): Boolean { if (touchListener !== this) { return false } if (e.action == MotionEvent.ACTION_DOWN) { // if we do not start on an item view, we dont want to do anything, // we do not want to intercept it or direct it to the feed holder val childView = view.findChildViewUnder(e.x, e.y) if (childView?.tag !is FeedItemViewHolder) { return false } lastChildView = childView } if (mGestureDetector.onTouchEvent(e)) { logger.debug { "TouchEvent intercepted: $e" } return true } logger.debug { "Touch event was not intercepted: $e" } // a long press might have been triggered between the last touch event // and the current. we use this info to start tracking the current long touch // if that happened. val intercept = longClickEnabled && longPressJustTriggered && e.action != MotionEvent.ACTION_DOWN longPressJustTriggered = false if (intercept) { // actually this click right now might be the end of the long press, so push it to onTouchEvent too onTouchEvent(view, e) } return intercept } override fun onTouchEvent(view: RecyclerView, motionEvent: MotionEvent) { logger.debug { "onTouchEvent($motionEvent)" } when (motionEvent.action) { MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_HOVER_EXIT, MotionEvent.ACTION_POINTER_UP -> itemLongClickEnded() } } } private inner class ScrollListener : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { when (newState) { RecyclerView.SCROLL_STATE_DRAGGING, RecyclerView.SCROLL_STATE_SETTLING -> { touchListener?.let { listener -> recyclerView.removeOnItemTouchListener(listener) } touchListener = null ignoreLongTap = true } RecyclerView.SCROLL_STATE_IDLE -> { touchListener?.let { listener -> recyclerView.removeOnItemTouchListener(listener) } touchListener = Listener().also { listener -> recyclerView.addOnItemTouchListener(listener) } } } } } }
mit
874a30d7a85b733e74b3b18e3a410763
34.727891
115
0.575019
5.702497
false
false
false
false
jeffgbutler/mybatis-qbe
src/main/kotlin/org/mybatis/dynamic/sql/util/kotlin/mybatis3/ProviderBuilderFunctions.kt
1
5153
/* * Copyright 2016-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("TooManyFunctions") package org.mybatis.dynamic.sql.util.kotlin.mybatis3 import org.mybatis.dynamic.sql.BasicColumn import org.mybatis.dynamic.sql.SqlTable import org.mybatis.dynamic.sql.delete.render.DeleteStatementProvider import org.mybatis.dynamic.sql.insert.BatchInsertDSL import org.mybatis.dynamic.sql.insert.InsertDSL import org.mybatis.dynamic.sql.insert.MultiRowInsertDSL import org.mybatis.dynamic.sql.insert.render.BatchInsert import org.mybatis.dynamic.sql.insert.render.GeneralInsertStatementProvider import org.mybatis.dynamic.sql.insert.render.InsertSelectStatementProvider import org.mybatis.dynamic.sql.insert.render.InsertStatementProvider import org.mybatis.dynamic.sql.insert.render.MultiRowInsertStatementProvider import org.mybatis.dynamic.sql.render.RenderingStrategies import org.mybatis.dynamic.sql.select.render.SelectStatementProvider import org.mybatis.dynamic.sql.update.render.UpdateStatementProvider import org.mybatis.dynamic.sql.util.kotlin.BatchInsertCompleter import org.mybatis.dynamic.sql.util.kotlin.CountCompleter import org.mybatis.dynamic.sql.util.kotlin.DeleteCompleter import org.mybatis.dynamic.sql.util.kotlin.GeneralInsertCompleter import org.mybatis.dynamic.sql.util.kotlin.InsertCompleter import org.mybatis.dynamic.sql.util.kotlin.InsertSelectCompleter import org.mybatis.dynamic.sql.util.kotlin.MultiRowInsertCompleter import org.mybatis.dynamic.sql.util.kotlin.SelectCompleter import org.mybatis.dynamic.sql.util.kotlin.UpdateCompleter import org.mybatis.dynamic.sql.util.kotlin.model.count import org.mybatis.dynamic.sql.util.kotlin.model.countDistinct import org.mybatis.dynamic.sql.util.kotlin.model.countFrom import org.mybatis.dynamic.sql.util.kotlin.model.deleteFrom import org.mybatis.dynamic.sql.util.kotlin.model.insertInto import org.mybatis.dynamic.sql.util.kotlin.model.insertSelect import org.mybatis.dynamic.sql.util.kotlin.model.into import org.mybatis.dynamic.sql.util.kotlin.model.select import org.mybatis.dynamic.sql.util.kotlin.model.selectDistinct import org.mybatis.dynamic.sql.util.kotlin.model.update fun count(column: BasicColumn, completer: CountCompleter): SelectStatementProvider = count(column, completer).render(RenderingStrategies.MYBATIS3) fun countDistinct(column: BasicColumn, completer: CountCompleter): SelectStatementProvider = countDistinct(column, completer).render(RenderingStrategies.MYBATIS3) fun countFrom(table: SqlTable, completer: CountCompleter): SelectStatementProvider = countFrom(table, completer).render(RenderingStrategies.MYBATIS3) fun deleteFrom(table: SqlTable, completer: DeleteCompleter): DeleteStatementProvider = deleteFrom(table, completer).render(RenderingStrategies.MYBATIS3) fun insertInto(table: SqlTable, completer: GeneralInsertCompleter): GeneralInsertStatementProvider = insertInto(table, completer).render(RenderingStrategies.MYBATIS3) fun insertSelect(table: SqlTable, completer: InsertSelectCompleter): InsertSelectStatementProvider = insertSelect(table, completer).render(RenderingStrategies.MYBATIS3) fun <T> BatchInsertDSL.IntoGatherer<T>.into(table: SqlTable, completer: BatchInsertCompleter<T>): BatchInsert<T> = into(table, completer).render(RenderingStrategies.MYBATIS3) fun <T> InsertDSL.IntoGatherer<T>.into(table: SqlTable, completer: InsertCompleter<T>): InsertStatementProvider<T> = into(table, completer).render(RenderingStrategies.MYBATIS3) fun <T> MultiRowInsertDSL.IntoGatherer<T>.into( table: SqlTable, completer: MultiRowInsertCompleter<T> ): MultiRowInsertStatementProvider<T> = into(table, completer).render(RenderingStrategies.MYBATIS3) fun select(vararg columns: BasicColumn, completer: SelectCompleter): SelectStatementProvider = select(columns.asList(), completer).render(RenderingStrategies.MYBATIS3) fun select(columns: List<BasicColumn>, completer: SelectCompleter): SelectStatementProvider = select(columns, completer).render(RenderingStrategies.MYBATIS3) fun selectDistinct(vararg columns: BasicColumn, completer: SelectCompleter): SelectStatementProvider = selectDistinct(columns.asList(), completer).render(RenderingStrategies.MYBATIS3) fun selectDistinct(columns: List<BasicColumn>, completer: SelectCompleter): SelectStatementProvider = selectDistinct(columns, completer).render(RenderingStrategies.MYBATIS3) fun update(table: SqlTable, completer: UpdateCompleter): UpdateStatementProvider = update(table, completer).render(RenderingStrategies.MYBATIS3)
apache-2.0
4179112778f6de0021fe69e286c82ad6
52.677083
116
0.821657
3.933588
false
false
false
false
ykrank/S1-Next
app/src/main/java/me/ykrank/s1next/data/api/model/Pm.kt
1
2430
package me.ykrank.s1next.data.api.model import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import com.google.common.base.Objects import com.github.ykrank.androidtools.ui.adapter.StableIdModel import com.github.ykrank.androidtools.ui.adapter.model.DiffSameItem @JsonIgnoreProperties(ignoreUnknown = true) class Pm : Cloneable, DiffSameItem, StableIdModel { @JsonProperty("plid") var plId: String? = null @JsonProperty("pmid") var pmId: String? = null @JsonProperty("pmtype") var pmType: String? = null @JsonProperty("authorid") var authorId: String? = null var author: String? = null var subject: String? = null var message: String? = null var dateline: Long = 0 @JsonProperty("msgfromid") var msgFromId: String? = null @JsonProperty("msgfrom") var msgFrom: String? = null @JsonProperty("msgtoid") var msgToId: String? = null //no this data in api, should set it manual @JsonIgnore var msgTo: String? = null override val stableId: Long get() = pmId?.toLongOrNull() ?: 0 override fun equals(o: Any?): Boolean { if (this === o) return true if (o == null || javaClass != o.javaClass) return false val pm = o as Pm? return Objects.equal(plId, pm!!.plId) && Objects.equal(pmId, pm.pmId) && Objects.equal(pmType, pm.pmType) && Objects.equal(authorId, pm.authorId) && Objects.equal(author, pm.author) && Objects.equal(subject, pm.subject) && Objects.equal(message, pm.message) && Objects.equal(dateline, pm.dateline) && Objects.equal(msgFromId, pm.msgFromId) && Objects.equal(msgFrom, pm.msgFrom) && Objects.equal(msgToId, pm.msgToId) && Objects.equal(msgTo, pm.msgTo) } override fun hashCode(): Int { return Objects.hashCode(plId, pmId, pmType, authorId, author, subject, message, dateline, msgFromId, msgFrom, msgToId, msgTo) } override fun isSameItem(o: Any?): Boolean { if (this === o) return true if (o == null || javaClass != o.javaClass) return false val pm = o as Pm? return Objects.equal(plId, pm!!.plId) && Objects.equal(pmId, pm.pmId) } }
apache-2.0
49bcc10a87bd3fd01fd092c413c12aa4
36.384615
133
0.632099
3.857143
false
false
false
false
Kushki/kushki-android
kushki/src/main/java/com/kushkipagos/tests/KushkiUnitTest.kt
1
50359
package com.kushkipagos.tests import android.app.Activity import android.content.Context import com.github.tomakehurst.wiremock.client.WireMock.* import com.github.tomakehurst.wiremock.junit.WireMockRule import com.kushkipagos.exceptions.KushkiException import com.kushkipagos.kushki.* import com.kushkipagos.models.* import com.kushkipagos.tests.Helpers.buildBankListResponse import com.kushkipagos.tests.Helpers.buildBinInfoResponse import com.kushkipagos.tests.Helpers.buildResponse import com.kushkipagos.tests.Helpers.buildSecureValidationOTPResponse import com.kushkipagos.tests.Helpers.buildSecureValidationResponse import org.apache.commons.lang3.RandomStringUtils import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.CoreMatchers.notNullValue import org.hamcrest.MatcherAssert.assertThat import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.mockito.Mockito.mock import java.net.HttpURLConnection class KushkiUnitTest { @Rule @JvmField val wireMockRule = WireMockRule(8888) private val totalAmount = 10.0 private val validCard = Card("John Doe", "5321952125169352", "123", "12", "21") private val invalidCard = Card("Invalid John Doe", "4242424242", "123", "12", "21") private val kushki = Kushki("10000002036955013614148494909956", "USD", TestEnvironment.LOCAL) private val kushkiTest = Kushki("ca643d9b2c0a45bf9a5cb82ffe7ddad9", "USD", KushkiEnvironment.QA) private val kushkiCardOTP = Kushki("20000000108588217776", "USD", TestEnvironment.LOCAL_QA) private val kushkiTransfer = Kushki("7871421bff4c4c19a925a50dc6b70af3", "USD", TestEnvironment.LOCAL) private val kushkiTransferSubscription = Kushki("20000000107415376000", "COP", TestEnvironment.LOCAL) private val kushkiSingleIP = Kushki("10000002036955013614148494909956", "USD", TestEnvironment.LOCAL, true) private val kushkiCardAsync = Kushki("10000002667885476032150186346335", "CLP", TestEnvironment.LOCAL) private val kushkiCardAsyncErrorMerchant = Kushki("20000000", "CLP", TestEnvironment.LOCAL) private val kushkiCardAsyncErrorCurrency = Kushki("10000002667885476032150186346335", "CCC", TestEnvironment.LOCAL) private val kushkiCash = Kushki("6000000000154083361249085016881", "USD", TestEnvironment.LOCAL) private val kushkiCashErrorMerchant = Kushki("20000000", "USD", TestEnvironment.LOCAL) private val kushkiCashErrorCurrency = Kushki("10000002667885476032150186346335", "CCC", TestEnvironment.LOCAL) private val kushkiBankList = Kushki("20000000107415376000", "COP", TestEnvironment.LOCAL) private val kushkiBinInfo = Kushki("10000002036955013614148494909956", "USD", TestEnvironment.LOCAL) private val totalAmountCardAsync = 1000.00 private val kushkiSubscriptionTransfer = TransferSubscriptions("892352", "1", "jose", "gonzalez", "123123123", "CC", "01", 12, "[email protected]", "USD") private val kushkiCardSubscriptionAsync = Kushki("e955d8c491674b08869f0fe6f480c63e", "CLP", TestEnvironment.LOCAL_QA) private val kushkiCardSubscriptionAsyncErrorMerchant = Kushki("20000000103303102000", "CLP", TestEnvironment.LOCAL_QA) private lateinit var context:Context private lateinit var activity: Activity private val name = "José" private val lastName = "Fernn" private val identification = "1721834349" private val returnUrl = "https://return.url" private val description = "Description test" private val email = "[email protected]" private val amount = Amount(10.0, 0.0, 1.2) private val callbackUrl = "www.kushkipagos.com" private val callbackUrlAsync = "https://mycallbackurl.com" private val userType = "0" private val documentType = "NIT" private val documentNumber = "892352" private val currency = "CLP" private val paymentDescription = "Test JD" private val cityCode = "1" private val stateCode = "13" private val phone = "00987654321" private val expeditionDate = "15/12/1958" private val answers = JSONArray(""" [ { "id": "1", "answer": "1" }, { "id": "2", "answer": "1" }, { "id": "3", "answer": "1" }, { "id": "4", "answer": "1" } ] """) private val answersInvalid = JSONArray(""" [ { "id": "asdasd", "answer": "asdasd" } ] """) private val cardNumber = "4242424242424242" private val merchantId = "20000000107415376000" @Test @Throws(KushkiException::class) fun shouldReturnTokenWhenCalledWithValidParams() { val token = RandomStringUtils.randomAlphanumeric(32) val expectedRequestBody = buildExpectedRequestBody(validCard, totalAmount) val responseBody = buildResponse("000", "", token) stubTokenApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_OK) val transaction = kushki.requestToken(validCard, totalAmount) System.out.println(transaction.token) System.out.println(token) assertThat(transaction.token.length, equalTo(32)) } @Test @Throws(KushkiException::class) suspend fun shouldTest3DSecureWhen3DSIsNotEnabled() { context =mock(Context::class.java) activity = mock(Activity::class.java) val transaction = kushkiTest.requestToken(validCard, totalAmount, context, activity, true) assertThat(transaction.code, equalTo("000")) } @Test @Throws(KushkiException::class) fun shouldReturnErrorMessageWhenCalledWithInvalidParams() { val errorCode = RandomStringUtils.randomNumeric(3) val errorMessage = "Cuerpo de la petición inválido." val expectedRequestBody = buildExpectedRequestBody(invalidCard, totalAmount) val responseBody = buildResponse(errorCode, errorMessage) stubTokenApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_PAYMENT_REQUIRED) val transaction = kushki.requestToken(invalidCard, totalAmount) assertThat(transaction.token, equalTo("")) assertThat(transaction.code, equalTo("K001")) assertThat(transaction.message, equalTo(errorMessage)) } @Test @Throws(KushkiException::class) fun shouldReturnOKMessageWhenCalledWithSingleIP() { val token = RandomStringUtils.randomAlphanumeric(32) val expectedRequestBody = buildExpectedRequestBody(validCard, totalAmount) val responseBody = buildResponse("000", "", token) stubTokenApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_OK) val transaction = kushkiSingleIP.requestToken(validCard, totalAmount) System.out.println(transaction.token) System.out.println(token) assertThat(transaction.message, equalTo("")) assertThat(transaction.token.length, equalTo(32)) } @Test @Throws(KushkiException::class) fun shouldReturnSubscriptionTokenWhenCalledWithValidParams() { val token = RandomStringUtils.randomAlphanumeric(32) val expectedRequestBody = buildExpectedSubscriptionRequestBody(validCard) val responseBody = buildResponse("000", "", token) stubSubscriptionTokenApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_OK) val transaction = kushki.requestSubscriptionToken(validCard) assertThat(transaction.token.length, equalTo(32)) } @Test @Throws(KushkiException::class) fun shouldReturnErrorMessageWhenCalledWithInvalidSubscriptionParams() { val errorCode = RandomStringUtils.randomNumeric(3) val errorMessage = "Cuerpo de la petición inválido." val expectedRequestBody = buildExpectedSubscriptionRequestBody(invalidCard) val responseBody = buildResponse(errorCode, errorMessage) stubSubscriptionTokenApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_PAYMENT_REQUIRED) val transaction = kushki.requestSubscriptionToken(invalidCard) assertThat(transaction.token, equalTo("")) assertThat(transaction.code, equalTo("K001")) assertThat(transaction.message, equalTo(errorMessage)) } @Test @Throws(KushkiException::class) fun shouldReturnCardAsyncTokenWhenCalledWithValidParams() { val token = RandomStringUtils.randomAlphanumeric(32) val expectedRequestBody = buildExpectedRequestCardAsyncBody(totalAmountCardAsync, returnUrl, description, email) val responseBody = buildResponse("000", "", token) stubCardAsyncTokenApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_OK) val transaction = kushkiCardAsync.requestCardAsyncToken(totalAmountCardAsync, returnUrl, description, email) System.out.println(transaction.token) System.out.println(token) assertThat(transaction.token.length, equalTo(32)) } @Test @Throws(KushkiException::class) fun shouldReturnCardAsyncTokenWhenCalledWithIncompleteParams() { val token = RandomStringUtils.randomAlphanumeric(32) val expectedRequestBody = buildExpectedRequestCardAsyncBodyIncomplete(totalAmountCardAsync, returnUrl) val responseBody = buildResponse("000", "", token) stubCardAsyncTokenApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_OK) val transaction = kushkiCardAsync.requestCardAsyncToken(totalAmountCardAsync, returnUrl) System.out.println(transaction.token) System.out.println(token) assertThat(transaction.token.length, equalTo(32)) } @Test @Throws(KushkiException::class) fun shouldReturnCardAsyncTokenWhenCalledWithIncompleteParamsOnlyEmail() { val token = RandomStringUtils.randomAlphanumeric(32) val expectedRequestBody = buildExpectedRequestCardAsyncBodyOnlyEmail(totalAmountCardAsync, returnUrl, email) val responseBody = buildResponse("000", "", token) stubCardAsyncTokenApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_OK) val transaction = kushkiCardAsync.requestCardAsyncToken(totalAmountCardAsync, returnUrl) System.out.println(transaction.token) System.out.println(token) assertThat(transaction.token.length, equalTo(32)) } @Test @Throws(KushkiException::class) fun shouldReturnCashTokenWhenCalledWithValidParams() { val token = RandomStringUtils.randomAlphanumeric(32) val expectedRequestBody = buildExpectedRequestCashBody(name, lastName, identification, documentType, email, totalAmount, currency, description) val responseBody = buildResponse("000", "", token) stubCashTokenApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_OK) val transaction = kushkiCash.requestCashToken(name, lastName, identification, documentType, email, totalAmount, "USD", description) System.out.println(transaction.token) System.out.println(token) assertThat(transaction.token.length, equalTo(32)) } @Test @Throws(KushkiException::class) fun shouldReturnCashTokenWhenCalledWithIncompleteParams() { val token = RandomStringUtils.randomAlphanumeric(32) val expectedRequestBody = buildExpectedRequestCashBodyIncomplete(name, lastName, identification, documentType, totalAmount, currency) val responseBody = buildResponse("000", "", token) stubCashTokenApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_OK) val transaction = kushkiCash.requestCashToken(name, lastName, identification, documentType, totalAmount, "USD") System.out.println(transaction.token) System.out.println(token) assertThat(transaction.token.length, equalTo(32)) } @Test @Throws(KushkiException::class) fun shouldReturnCashTokenWhenCalledWithIncompleteParamsOnlyEmail() { val token = RandomStringUtils.randomAlphanumeric(32) val expectedRequestBody = buildExpectedRequestCashBodyIncompleteOnlyEmail( name, lastName, identification, documentType, email, totalAmount, currency) val responseBody = buildResponse("000", "", token) stubCashTokenApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_OK) val transaction = kushkiCash.requestCashToken(name, lastName, identification, documentType, email, totalAmount, "USD") System.out.println(transaction.token) System.out.println(token) assertThat(transaction.token.length, equalTo(32)) } @Test @Throws(KushkiException::class) fun shouldReturnTransferSubscriptionTokenWhenCalledWithCompleteParamsOnlyEmail() { val token = RandomStringUtils.randomAlphanumeric(32) val expectedRequestBody = buildRequestTransferSubscriptionMessage(kushkiSubscriptionTransfer) val responseBody = buildResponse("000", "", token) stubTransferSubscriptionTokenApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_OK) val transaction = kushkiTransferSubscription.requestTransferSubscriptionToken(kushkiSubscriptionTransfer) System.out.println(transaction.token) System.out.println(token) assertThat(transaction.token.length, equalTo(32)) } @Test @Throws(KushkiException::class) fun shouldReturnErrorMessageWhenCalledWithInvalidMerchant() { val errorCode = RandomStringUtils.randomNumeric(3) val errorMessage = "ID de comercio o credencial no válido" val expectedRequestBody = buildExpectedRequestCardAsyncBody(totalAmountCardAsync, returnUrl, description, email) val responseBody = buildResponse(errorCode, errorMessage) stubCardAsyncTokenApiErrorMerchant(expectedRequestBody, responseBody, HttpURLConnection.HTTP_PAYMENT_REQUIRED) val transaction = kushkiCardAsyncErrorMerchant.requestCardAsyncToken(totalAmountCardAsync, returnUrl, description, email) assertThat(transaction.token, equalTo("")) assertThat(transaction.code, equalTo("CAS004")) assertThat(transaction.message, equalTo(errorMessage)) } @Test @Throws(KushkiException::class) fun shouldReturnErrorMessageWhenCalledWithInvalidCurrency() { val errorCode = RandomStringUtils.randomNumeric(3) val errorMessage = "Cuerpo de la petición inválido." val expectedRequestBody = buildExpectedRequestCardAsyncBody(totalAmountCardAsync, returnUrl, description, email) val responseBody = buildResponse(errorCode, errorMessage) stubCardAsyncTokenApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_PAYMENT_REQUIRED) val transaction = kushkiCardAsyncErrorCurrency.requestCardAsyncToken(totalAmountCardAsync, returnUrl, description, email) assertThat(transaction.token, equalTo("")) assertThat(transaction.code, equalTo("CAS001")) assertThat(transaction.message, equalTo(errorMessage)) } @Test @Throws(KushkiException::class) fun shouldReturnCashErrorMessageWhenCalledWithInvalidMerchant() { val errorCode = RandomStringUtils.randomNumeric(3) val errorMessage = "ID de comercio o credencial no válido" val expectedRequestBody = buildExpectedRequestCashBody(name, lastName, identification, documentType, email, totalAmount, currency, description) val responseBody = buildResponse(errorCode, errorMessage) stubCashAsyncTokenApiErrorMerchant(expectedRequestBody, responseBody, HttpURLConnection.HTTP_PAYMENT_REQUIRED) val transaction = kushkiCashErrorMerchant.requestCashToken(name, lastName, identification, documentType, email, totalAmount, currency, description) assertThat(transaction.token, equalTo("")) assertThat(transaction.code, equalTo("C004")) assertThat(transaction.message, equalTo(errorMessage)) } @Test @Throws(KushkiException::class) fun shouldReturnCashErrorMessageWhenCalledWithInvalidCurrency() { val errorCode = RandomStringUtils.randomNumeric(3) val errorMessage = "Cuerpo de la petición inválido." val expectedRequestBody = buildExpectedRequestCashBody(name, lastName, identification, documentType, email, totalAmount, "ABC", description) val responseBody = buildResponse(errorCode, errorMessage) stubCashTokenApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_PAYMENT_REQUIRED) val transaction = kushkiCash.requestCashToken(name, lastName, identification, documentType, email, totalAmount, "ABC", description) assertThat(transaction.token, equalTo("")) assertThat(transaction.code, equalTo("C001")) assertThat(transaction.message, equalTo(errorMessage)) } @Test @Throws(KushkiException::class) fun shouldReturnTransferTokenWhenCalledWithValidParams() { val token = RandomStringUtils.randomAlphanumeric(32) val expectedRequestBody = buildExpectedRequestTransferBody() val responseBody = buildResponse("000", "", token) stubTransferTokenApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_OK) val transaction = kushkiTransfer.requestTransferToken(amount, callbackUrl, userType, documentType, documentNumber, email, currency) System.out.println(transaction.token) System.out.println(token) assertThat(transaction.token.length, equalTo(32)) } @Test @Throws(KushkiException::class) fun shouldReturnTransferTokenWhenCalledWithValidCompletedParams() { val token = RandomStringUtils.randomAlphanumeric(32) val expectedRequestBody = buildExpectedRequestTransferBody(paymentDescription) val responseBody = buildResponse("000", "", token) stubTransferTokenApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_OK) val transaction = kushkiTransfer.requestTransferToken(amount, callbackUrl, userType, documentType, documentNumber, email, currency, paymentDescription) System.out.println(transaction.token) System.out.println(token) assertThat(transaction.token.length, equalTo(32)) } @Test @Throws(KushkiException::class) fun shouldReturnTransferTokenWhenCalledWithInvalidParams() { val errorCode = RandomStringUtils.randomNumeric(3) val errorMessage = "Cuerpo de la petición inválido." val expectedRequestBody = buildExpectedRequestTransferBody(paymentDescription, "test") val responseBody = buildResponse(errorCode, errorMessage) stubTransferTokenApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_PAYMENT_REQUIRED) val transaction = kushki.requestTransferToken(amount, callbackUrl, "test", documentType, documentNumber, email, currency) assertThat(transaction.token, equalTo("")) assertThat(transaction.code, equalTo("T001")) assertThat(transaction.message, equalTo(errorMessage)) } @Test @Throws(KushkiException::class) fun shouldReturnBankListWhenCalledWithValidResponse() { val responseBody = buildBankListResponse() stubBankListApi(responseBody, HttpURLConnection.HTTP_OK) val banklist = kushkiBankList.getBankList() System.out.println(banklist.banks) System.out.println(banklist.banks[3]) assertThat(banklist.banks, notNullValue()) } @Test @Throws(KushkiException::class) fun shouldReturnBinInfoWhenCalledWithValidResponse() { val responseBody = buildBinInfoResponse() stubBinInfoApi(responseBody, HttpURLConnection.HTTP_OK) val binInfo = kushkiBinInfo.getBinInfo("465775") System.out.println(binInfo.bank) System.out.println(binInfo.brand) System.out.println(binInfo.cardType) assertThat(binInfo.bank, notNullValue()) } @Ignore @Test @Throws(KushkiException::class) fun shouldReturnAskQuestionnaireWhenCalledWithCompleteParams() { val expectedRequestBody = buildRequestTransferSubscriptionMessage(kushkiSubscriptionTransfer) val responseBody = buildSecureValidationResponse("000", "", "02") stubSecureValidationApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_OK) val transaction = kushkiTransferSubscription.requestTransferSubscriptionToken(kushkiSubscriptionTransfer) val secureInfo = AskQuestionnaire(transaction.secureId, transaction.secureService, cityCode, stateCode, phone, expeditionDate, merchantId) val secureValidation = kushkiTransferSubscription.requestSecureValidation(secureInfo) assertThat(secureValidation.questions.length(), equalTo(3)) System.out.println(secureValidation.questions.getJSONObject(0).getJSONArray("options").getJSONObject(0).get("text")) } @Test @Throws(KushkiException::class) fun shouldReturnOTPExpiradoMessageWhenCalledWithInvalidSucureServiceId() { val errorCode = "CardRule Credential not found" val errorMessage = "El ID de comercio no corresponde a la credencial enviada" val expectedRequestBody = buildRequestTransferSubscriptionMessage(kushkiSubscriptionTransfer) val responseBody = buildSecureValidationResponse(errorCode, errorMessage, "") stubSecureValidationApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_OK) val askQuestionnaire = AskQuestionnaire("InvalidId", "confronta", cityCode, stateCode, phone, expeditionDate, merchantId) val secureValidation = kushkiTransferSubscription.requestSecureValidation(askQuestionnaire) assertThat(secureValidation.questions.length(), equalTo(0)) assertThat(secureValidation.code, equalTo(errorCode)) assertThat(secureValidation.message, equalTo(errorMessage)) } @Test @Throws(KushkiException::class) fun shouldReturnErrorMessageWhenCalledWithInvalidConfrontaBiometrics() { val errorCode = "BIO006" val errorMessage = "Cuerpo de petición inválido" val expectedRequestBody = buildRequestTransferSubscriptionMessage(kushkiSubscriptionTransfer) val responseBody = buildSecureValidationResponse(errorCode, errorMessage, "") stubSecureValidationApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_OK) val transaction = kushkiTransferSubscription.requestTransferSubscriptionToken(kushkiSubscriptionTransfer) val askQuestionnaire = AskQuestionnaire(transaction.secureId, transaction.secureService, "", "", "", "", merchantId) val secureValidation = kushkiTransferSubscription.requestSecureValidation(askQuestionnaire) assertThat(secureValidation.questions.length(), equalTo(0)) assertThat(secureValidation.code, equalTo("BIO006")) assertThat(secureValidation.message, equalTo("Cuerpo de petición inválido")) } @Test @Throws(KushkiException::class) fun shouldReturnOkMessageWhenCalledWithValidAnswers() { val expectedRequestBody = buildRequestTransferSubscriptionMessage(kushkiSubscriptionTransfer) val responseBody = buildSecureValidationResponse("000", "", "02") stubSecureValidationApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_OK) val transaction = kushkiTransferSubscription.requestTransferSubscriptionToken(kushkiSubscriptionTransfer) val askQuestionnaire = AskQuestionnaire(transaction.secureId, transaction.secureService, cityCode, stateCode, phone, expeditionDate, merchantId) var secureValidation = kushkiTransferSubscription.requestSecureValidation(askQuestionnaire) println(transaction.secureId) println(transaction.secureService) val validateAnswers = ValidateAnswers(transaction.secureId, transaction.secureService, "7224", answers) secureValidation = kushkiTransferSubscription.requestSecureValidation(validateAnswers) assertThat(secureValidation.message, equalTo("ok")) assertThat(secureValidation.code, equalTo("BIO000")) } @Ignore @Test @Throws(KushkiException::class) fun shouldReturnOkMessageWhenCalledWithValidCardAnswers() { val expectedRequestBody = buildExpectedRequestBody(validCard, totalAmount) val responseBody = buildSecureValidationOTPResponse("OTP000") stubSecureValidationApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_OK) val transaction = kushkiCardOTP.requestToken(validCard, totalAmount) val validateOTP = OTPValidation(transaction.secureId, "155") val secureValidation = kushkiCardOTP.requestSecureValidation(validateOTP) println(transaction.secureId) println(transaction.secureService) assertThat(secureValidation.message, equalTo("ok")) assertThat(secureValidation.code, equalTo("OTP000")) } @Ignore @Test @Throws(KushkiException::class) fun shouldReturnErrorMessageWhenCalledWithInvalidCardAnswers() { val expectedRequestBody = buildExpectedRequestBody(validCard, totalAmount) val responseBody = buildSecureValidationOTPResponse("OTP100") stubSecureValidationApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_PAYMENT_REQUIRED) val transaction = kushkiCardOTP.requestToken(validCard, totalAmount) val validateOTP = OTPValidation(transaction.secureId, "") val secureValidation = kushkiCardOTP.requestSecureValidation(validateOTP) println(transaction.secureId) println(transaction.secureService) assertThat(secureValidation.message, equalTo("OTP inválido")) assertThat(secureValidation.code, equalTo("OTP100")) assertThat(secureValidation.isSuccessful, equalTo(false)) } @Test @Throws(KushkiException::class) fun shouldReturnInvalidUserMessageWhenCalledWithInvalidAnswers() { val expectedRequestBody = buildRequestTransferSubscriptionMessage(kushkiSubscriptionTransfer) val responseBody = buildSecureValidationResponse("000", "", "02") stubSecureValidationApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_OK) val transaction = kushkiTransferSubscription.requestTransferSubscriptionToken(kushkiSubscriptionTransfer) val askQuestionnaire = AskQuestionnaire(transaction.secureId, transaction.secureService, cityCode, stateCode, phone, expeditionDate, merchantId) var secureValidation = kushkiTransferSubscription.requestSecureValidation(askQuestionnaire) val validateAnswers = ValidateAnswers(transaction.secureId, transaction.secureService, "3123", answersInvalid) secureValidation = kushkiTransferSubscription.requestSecureValidation(validateAnswers) assertThat(secureValidation.code, equalTo("BIO100")) } // @Test // @Throws(KushkiException::class) // fun shouldReturnCardSubscriptionAsyncTokenWhenCalledWithValidParams() { // val token = RandomStringUtils.randomAlphanumeric(32) // val expectedRequestBody = buildExpectedRequestCardSubscriptionAsyncBody(email, currency, callbackUrlAsync, cardNumber) // val responseBody = buildResponse("000", "", token) // stubCardSubscriptionAsyncTokenApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_OK) // val transaction = kushkiCardSubscriptionAsync.requestCardSubscriptionAsyncToken(email, currency, callbackUrlAsync, cardNumber) // System.out.println(transaction.token) // System.out.println(token) // assertThat(transaction.token.length, equalTo(32)) // } // @Test // @Throws(KushkiException::class) // fun shouldReturnCardSubscriptionAsyncTokenCalledWithIncompleteParams() { // val token = RandomStringUtils.randomAlphanumeric(32) // val expectedRequestBody = buildExpectedRequestCardSubscriptionAsyncIncompleteBody(email, currency, callbackUrlAsync) // val responseBody = buildResponse("000", "", token) // stubCardSubscriptionAsyncTokenApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_OK) // val transaction = kushkiCardSubscriptionAsync.requestCardSubscriptionAsyncToken(email, currency, callbackUrlAsync) // System.out.println(transaction.token) // System.out.println(token) // assertThat(transaction.token.length, equalTo(32)) // } @Test @Throws(KushkiException::class) fun shouldReturnCardSubscriptionAsyncErrorMessageWhenCalledWithInvalidMerchant() { val errorCode = RandomStringUtils.randomNumeric(3) val errorMessage = "ID de comercio o credencial no válido" val expectedRequestBody = buildExpectedRequestCardSubscriptionAsyncBody(email, currency, callbackUrlAsync, cardNumber) val responseBody = buildResponse(errorCode, errorMessage) stubSubscriptionCardAsyncTokenApiErrorMerchant(expectedRequestBody, responseBody, HttpURLConnection.HTTP_PAYMENT_REQUIRED) val transaction = kushkiCardSubscriptionAsyncErrorMerchant.requestCardSubscriptionAsyncToken(email, currency, callbackUrlAsync, cardNumber) assertThat(transaction.token, equalTo("")) assertThat(transaction.code, equalTo("K004")) assertThat(transaction.message, equalTo(errorMessage)) } // @Test // @Throws(KushkiException::class) // fun shouldReturnCardSubscriptionAsyncMessageWhenCalledWithInvalidCurrency() { // val errorCode = RandomStringUtils.randomNumeric(3) // val errorMessage = "Cuerpo de la petición inválido." // val expectedRequestBody = buildExpectedRequestCardSubscriptionAsyncBody(email, "USD", callbackUrlAsync, cardNumber) // val responseBody = buildResponse(errorCode, errorMessage) // stubCardSubscriptionAsyncTokenApi(expectedRequestBody, responseBody, HttpURLConnection.HTTP_PAYMENT_REQUIRED) // val transaction = kushkiCardSubscriptionAsync.requestCardSubscriptionAsyncToken(email, "USD", callbackUrlAsync, cardNumber) // assertThat(transaction.token, equalTo("")) // assertThat(transaction.code, equalTo("K004")) // assertThat(transaction.message, equalTo(errorMessage)) // } private fun stubTokenApi(expectedRequestBody: String, responseBody: String, status: Int) { System.out.println("response---body") System.out.println(responseBody) wireMockRule.stubFor(post(urlEqualTo("v1/tokens")) .withRequestBody(equalToJson(expectedRequestBody)) .willReturn(aResponse() .withStatus(status) .withHeader("Content-Type", "application/json") .withHeader("Public-Merchant-Id", "10000001656015280078454110039965") .withBody(responseBody))) } private fun stubSubscriptionTokenApi(expectedRequestBody: String, responseBody: String, status: Int) { wireMockRule.stubFor(post(urlEqualTo("v1/subscription-tokens")) .withRequestBody(equalToJson(expectedRequestBody)) .willReturn(aResponse() .withStatus(status) .withHeader("Content-Type", "application/json") .withHeader("Public-Merchant-Id", "10000001656015280078454110039965") .withBody(responseBody))) } private fun stubTransferTokenApi(expectedRequestBody: String, responseBody: String, status: Int) { wireMockRule.stubFor(post(urlEqualTo("transfer/v1/tokens")) .withRequestBody(equalToJson(expectedRequestBody)) .willReturn(aResponse() .withStatus(status) .withHeader("Content-Type", "application/json") .withHeader("Public-Merchant-Id", "200000001030988") .withBody(responseBody))) } private fun stubCardAsyncTokenApi(expectedRequestBody: String, responseBody: String, status: Int) { System.out.println("response---body") System.out.println(responseBody) wireMockRule.stubFor(post(urlEqualTo("card-async/v1/tokens")) .withRequestBody(equalToJson(expectedRequestBody)) .willReturn(aResponse() .withStatus(status) .withHeader("Content-Type", "application/json") .withHeader("Public-Merchant-Id", "20000000103098876000") .withBody(responseBody))) } private fun stubCashTokenApi(expectedRequestBody: String, responseBody: String, status: Int) { System.out.println("response---body") System.out.println(responseBody) wireMockRule.stubFor(post(urlEqualTo("cash/v1/tokens")) .withRequestBody(equalToJson(expectedRequestBody)) .willReturn(aResponse() .withStatus(status) .withHeader("Content-Type", "application/json") .withHeader("Public-Merchant-Id", "6000000000154083361249085016881") .withBody(responseBody))) } private fun stubTransferSubscriptionTokenApi(expectedRequestBody: String, responseBody: String, status: Int) { System.out.println("response---body") System.out.println(responseBody) wireMockRule.stubFor(post(urlEqualTo("v1/transfer-subscription-tokens")) .withRequestBody(equalToJson(expectedRequestBody)) .willReturn(aResponse() .withStatus(status) .withHeader("Content-Type", "application/json") .withHeader("Public-Merchant-Id", "20000000103098876000") .withBody(responseBody))) } private fun stubCardAsyncTokenApiErrorMerchant(expectedRequestBody: String, responseBody: String, status: Int) { System.out.println("response---body") System.out.println(responseBody) wireMockRule.stubFor(post(urlEqualTo("card-async/v1/tokens")) .withRequestBody(equalToJson(expectedRequestBody)) .willReturn(aResponse() .withStatus(status) .withHeader("Content-Type", "application/json") .withHeader("Public-Merchant-Id", "200000001030988") .withBody(responseBody))) } private fun stubCashAsyncTokenApiErrorMerchant(expectedRequestBody: String, responseBody: String, status: Int) { System.out.println("response---body") System.out.println(responseBody) wireMockRule.stubFor(post(urlEqualTo("card-async/v1/tokens")) .withRequestBody(equalToJson(expectedRequestBody)) .willReturn(aResponse() .withStatus(status) .withHeader("Content-Type", "application/json") .withHeader("Public-Merchant-Id", "200000001030988") .withBody(responseBody))) } private fun stubBankListApi(responseBody: String, status: Int) { System.out.println("response---body") System.out.println(responseBody) wireMockRule.stubFor(get(urlEqualTo("transfer-subscriptions/v1/bankList")) .willReturn(aResponse() .withStatus(status) .withHeader("Content-Type", "application/json") .withHeader("Public-Merchant-Id", "20000000100323955000") .withBody(responseBody))) } private fun stubBinInfoApi(responseBody: String, status: Int) { System.out.println("response---body") System.out.println(responseBody) wireMockRule.stubFor(get(urlEqualTo("card/v1/bin")) .willReturn(aResponse() .withStatus(status) .withHeader("Content-Type", "application/json") .withHeader("Public-Merchant-Id", "20000000100323955000") .withBody(responseBody))) } private fun stubSecureValidationApi(expectedRequestBody: String, responseBody: String, status: Int) { System.out.println("response---body") System.out.println(responseBody) wireMockRule.stubFor(post(urlEqualTo("rules/v1/secureValidation")) .withRequestBody(equalToJson(expectedRequestBody)) .willReturn(aResponse() .withStatus(status) .withHeader("Content-Type", "application/json") .withHeader("Public-Merchant-Id", "20000000107415376000") .withBody(responseBody))) } private fun buildExpectedRequestBody(card: Card, totalAmount: Double): String { val expectedRequestMessage = buildRequestMessage(card, totalAmount) return expectedRequestMessage } private fun buildExpectedSubscriptionRequestBody(card: Card): String { val expectedRequestMessage = buildSubscriptionRequestMessage("10000001436354684173102102", card) return expectedRequestMessage } private fun buildSubscriptionRequestMessage(publicMerchantId: String, card: Card): String { try { val requestTokenParams = JSONObject() requestTokenParams.put("merchant_identifier", publicMerchantId) requestTokenParams.put("card", card.toJsonObject()) return requestTokenParams.toString() } catch (e: JSONException) { throw IllegalArgumentException(e) } } private fun buildRequestMessage(card: Card, totalAmount: Double): String { try { val requestTokenParams = JSONObject() requestTokenParams.put("card", card.toJsonObject()) requestTokenParams.put("totalAmount", totalAmount) return requestTokenParams.toString() } catch (e: JSONException) { throw IllegalArgumentException(e) } } private fun buildExpectedRequestTransferBody():String{ val expectedRequestMessage = buildRequestTransferMessage(amount, callbackUrl, userType, documentType, documentNumber, email, currency ) return expectedRequestMessage } private fun buildExpectedRequestTransferBody(paymentDescription: String, documentTypeAux: String = "CC"):String{ val expectedRequestMessage = buildRequestTransferMessage(amount, callbackUrl, userType, documentTypeAux, documentNumber, email, currency, paymentDescription ) return expectedRequestMessage } private fun buildRequestTransferMessage(amount: Amount, callbackUrl: String, userType: String, documentType: String, documentNumber: String, email: String, currency: String): String { try { val requestTokenParams = JSONObject() requestTokenParams.put("amount", amount.toJsonObject()) requestTokenParams.put("callbackUrl", callbackUrl) requestTokenParams.put("userType", userType) requestTokenParams.put("documentType", documentType) requestTokenParams.put("documentNumber", documentNumber) requestTokenParams.put("email", email) requestTokenParams.put("currency", currency) return requestTokenParams.toString() } catch (e: JSONException) { throw IllegalArgumentException(e) } } private fun buildRequestTransferMessage(amount: Amount, callbackUrl: String, userType: String, documentType: String, documentNumber: String, email: String, currency: String, paymentDescription: String): String { try { val requestTokenParams = JSONObject() requestTokenParams.put("amount", amount.toJsonObject()) requestTokenParams.put("callbackUrl", callbackUrl) requestTokenParams.put("userType", userType) requestTokenParams.put("documentType", documentType) requestTokenParams.put("documentNumber", documentNumber) requestTokenParams.put("email", email) requestTokenParams.put("currency", currency) requestTokenParams.put("paymentDescription", paymentDescription) return requestTokenParams.toString() } catch (e: JSONException) { throw IllegalArgumentException(e) } } private fun buildExpectedRequestCardAsyncBody(totalAmount: Double, returnUrl: String, description: String, email: String): String { val expectedRequestMessage = buildRequestCardAsyncMessage(totalAmount, returnUrl, description, email) return expectedRequestMessage } private fun buildRequestCardAsyncMessage(totalAmount: Double, returnUrl: String, description: String, email: String): String { try { val requestTokenParams = JSONObject() requestTokenParams.put("totalAmount", totalAmount) requestTokenParams.put("returnUrl", returnUrl) requestTokenParams.put("description", description) requestTokenParams.put("email", email) return requestTokenParams.toString() } catch (e: JSONException) { throw IllegalArgumentException(e) } } private fun buildExpectedRequestCashBody(name: String, lastName: String, identification: String, documentType: String, email: String, totalAmount: Double, currency: String, description: String): String { val expectedRequestMessage = buildRequestCashMessage(name, lastName, identification, documentType, email, totalAmount, currency, description) return expectedRequestMessage } private fun buildRequestCashMessage(name: String, lastName: String, identification: String, documentType: String, email: String, totalAmount: Double, currency: String, description: String): String { try { val requestTokenParams = JSONObject() requestTokenParams.put("name", name) requestTokenParams.put("lastName", lastName) requestTokenParams.put("identification", identification) requestTokenParams.put("documentType", documentType) requestTokenParams.put("email", email) requestTokenParams.put("totalAmount", totalAmount) requestTokenParams.put("currency", currency) requestTokenParams.put("description", description) return requestTokenParams.toString() } catch (e: JSONException) { throw IllegalArgumentException(e) } } private fun buildRequestTransferSubscriptionMessage(transferSubscriptions: TransferSubscriptions): String { try { val requestTokenParams = transferSubscriptions.toJsonObject() return requestTokenParams.toString() } catch (e: JSONException) { throw IllegalArgumentException(e) } } private fun buildExpectedRequestCardAsyncBodyIncomplete(totalAmount: Double, returnUrl: String): String { val expectedRequestMessage = buildRequestCardAsyncMessageWithIncompleteParameters(totalAmount, returnUrl) return expectedRequestMessage } private fun buildRequestCardAsyncMessageWithIncompleteParameters(totalAmount: Double, returnUrl: String): String { try { val requestTokenParams = JSONObject() requestTokenParams.put("totalAmount", totalAmount) requestTokenParams.put("returnUrl", returnUrl) return requestTokenParams.toString() } catch (e: JSONException) { throw IllegalArgumentException(e) } } private fun buildExpectedRequestCardAsyncBodyOnlyEmail(totalAmount: Double, returnUrl: String, email: String): String { val expectedRequestMessage = buildRequestCardAsyncMessageWithIncompleteOnlyEmail(totalAmount, returnUrl, email) return expectedRequestMessage } private fun buildRequestCardAsyncMessageWithIncompleteOnlyEmail(totalAmount: Double, returnUrl: String, email: String): String { try { val requestTokenParams = JSONObject() requestTokenParams.put("totalAmount", totalAmount) requestTokenParams.put("returnUrl", returnUrl) requestTokenParams.put("email", email) return requestTokenParams.toString() } catch (e: JSONException) { throw IllegalArgumentException(e) } } private fun buildRequestCashMessageWithIncompleteParameters( name: String, lastName: String, identification: String, documentType: String, totalAmount: Double, currency: String): String { try { val requestTokenParams = JSONObject() requestTokenParams.put("name", name) requestTokenParams.put("lastName", lastName) requestTokenParams.put("identification", identification) requestTokenParams.put("documentType", documentType) requestTokenParams.put("totalAmount", totalAmount) requestTokenParams.put("currency", currency) return requestTokenParams.toString() } catch (e: JSONException) { throw IllegalArgumentException(e) } } private fun buildExpectedRequestCashBodyIncomplete( name: String, lastName: String, identification: String, documentType: String, totalAmount: Double, currency: String): String { val expectedRequestMessage = buildRequestCashMessageWithIncompleteParameters( name, lastName, identification, documentType, totalAmount, currency) return expectedRequestMessage } private fun buildRequestCashMessageWithIncompleteParametersOnlyEmail( name: String, lastName: String, identification: String, documentType: String, email: String, totalAmount: Double, currency: String): String { try { val requestTokenParams = JSONObject() requestTokenParams.put("name", name) requestTokenParams.put("lastName", lastName) requestTokenParams.put("identification", identification) requestTokenParams.put("documentType", documentType) requestTokenParams.put("email", email) requestTokenParams.put("totalAmount", totalAmount) requestTokenParams.put("currency", currency) return requestTokenParams.toString() } catch (e: JSONException) { throw IllegalArgumentException(e) } } private fun buildExpectedRequestCashBodyIncompleteOnlyEmail( name: String, lastName: String, identification: String, documentType: String, email: String, totalAmount: Double, currency: String): String { val expectedRequestMessage = buildRequestCashMessageWithIncompleteParametersOnlyEmail( name, lastName, identification, documentType, email, totalAmount, currency) return expectedRequestMessage } private fun buildExpectedRequestCardSubscriptionAsyncBody(email: String, currency: String, callbackUrl: String, cardNumber: String): String { val expectedRequestMessage = buildRequestCardSubscriptionAsyncMessage(email, currency, callbackUrl, cardNumber) return expectedRequestMessage } private fun buildRequestCardSubscriptionAsyncMessage(email: String, currency: String, callbackUrl: String, cardNumber: String): String { try { val requestTokenParams = JSONObject() requestTokenParams.put("email", email) requestTokenParams.put("currency", currency) requestTokenParams.put("callbackUrl", callbackUrl) requestTokenParams.put("cardNumber", cardNumber) return requestTokenParams.toString() } catch (e: JSONException) { throw IllegalArgumentException(e) } } private fun stubCardSubscriptionAsyncTokenApi(expectedRequestBody: String, responseBody: String, status: Int) { System.out.println("response---body") System.out.println(responseBody) wireMockRule.stubFor(post(urlEqualTo("subscriptions/v1/card-async/tokens")) .withRequestBody(equalToJson(expectedRequestBody)) .willReturn(aResponse() .withStatus(status) .withHeader("Content-Type", "application/json") .withHeader("Public-Merchant-Id", "e955d8c491674b08869f0fe6f480c63e") .withBody(responseBody))) } private fun buildExpectedRequestCardSubscriptionAsyncIncompleteBody(email: String, currency: String, callbackUrl: String): String { val expectedRequestMessage = buildRequestCardSubscriptionAsyncIncompleteMessage(email, currency, callbackUrl) return expectedRequestMessage } private fun buildRequestCardSubscriptionAsyncIncompleteMessage(email: String, currency: String, callbackUrl: String): String { try { val requestTokenParams = JSONObject() requestTokenParams.put("email", email) requestTokenParams.put("currency", currency) requestTokenParams.put("callbackUrl", callbackUrl) return requestTokenParams.toString() } catch (e: JSONException) { throw IllegalArgumentException(e) } } private fun stubSubscriptionCardAsyncTokenApiErrorMerchant(expectedRequestBody: String, responseBody: String, status: Int) { System.out.println("response---body") System.out.println(responseBody) wireMockRule.stubFor(post(urlEqualTo("subscriptions/v1/card-async/tokens")) .withRequestBody(equalToJson(expectedRequestBody)) .willReturn(aResponse() .withStatus(status) .withHeader("Content-Type", "application/json") .withHeader("Public-Merchant-Id", "20000000103303102000") .withBody(responseBody))) } }
mit
78760ec6ed5fb8da0f732771a07f0023
49.846465
152
0.70414
5.057571
false
true
false
false
android/android-studio-poet
aspoet/src/main/kotlin/com/google/androidstudiopoet/models/JavaClassBlueprint.kt
1
2133
/* Copyright 2017 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 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.androidstudiopoet.models class JavaClassBlueprint(packageName: String, classNumber: Int, methodsPerClass: Int, fieldsPerClass: Int, private val where: String, private val methodsToCallWithinClass: List<MethodToCall>, classComplexity: ClassComplexity) : NonTestClassBlueprint(packageName, "Foo" + classNumber, methodsPerClass, fieldsPerClass, classComplexity) { override fun getFieldBlueprints(): List<FieldBlueprint> { return (0 until fieldsPerClass) .map { i -> FieldBlueprint("int$i", "java.lang.Integer", listOf()) } } override fun getMethodBlueprints(): List<MethodBlueprint> { return (0 until methodsPerClass) .map { i -> val statements = ArrayList<String>() // adding lambdas for (j in 0 until lambdaCountInMethod(i)) { statements += getLambda(j) } if (i > 0) { statements += "foo" + (i - 1) + "()" } else if (!methodsToCallWithinClass.isEmpty()) { methodsToCallWithinClass.forEach({ statements += "new ${it.className}().${it.methodName}()" }) } MethodBlueprint("foo$i", statements) } } override fun getClassPath(): String = "$where/$packageName/$className.java" private fun getLambda(lambdaNumber: Int) = "final Runnable anything$lambdaNumber = () -> System.out.println(\"anything\")" }
apache-2.0
4a2c5967aab134be559ccdd25ea0f8d5
41.68
145
0.631974
4.793258
false
false
false
false
jeffgbutler/mybatis-qbe
src/main/kotlin/org/mybatis/dynamic/sql/util/kotlin/CriteriaCollector.kt
1
4302
/* * Copyright 2016-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mybatis.dynamic.sql.util.kotlin import org.mybatis.dynamic.sql.BindableColumn import org.mybatis.dynamic.sql.ColumnAndConditionCriterion import org.mybatis.dynamic.sql.ExistsCriterion import org.mybatis.dynamic.sql.ExistsPredicate import org.mybatis.dynamic.sql.SqlCriterion import org.mybatis.dynamic.sql.VisitableCondition typealias CriteriaReceiver = CriteriaCollector.() -> Unit @MyBatisDslMarker class CriteriaCollector { val criteria = mutableListOf<SqlCriterion>() fun <T> and(column: BindableColumn<T>, condition: VisitableCondition<T>): CriteriaCollector = apply { criteria.add( ColumnAndConditionCriterion.withColumn(column) .withCondition(condition) .withConnector("and") .build() ) } fun <T> and( column: BindableColumn<T>, condition: VisitableCondition<T>, criteriaReceiver: CriteriaReceiver ): CriteriaCollector = apply { criteria.add( ColumnAndConditionCriterion.withColumn(column) .withCondition(condition) .withSubCriteria(CriteriaCollector().apply(criteriaReceiver).criteria) .withConnector("and") .build() ) } fun and(existsPredicate: ExistsPredicate): CriteriaCollector = apply { criteria.add( ExistsCriterion.Builder() .withConnector("and") .withExistsPredicate(existsPredicate) .build() ) } fun and(existsPredicate: ExistsPredicate, criteriaReceiver: CriteriaReceiver): CriteriaCollector = apply { criteria.add( ExistsCriterion.Builder() .withConnector("and") .withExistsPredicate(existsPredicate) .withSubCriteria(CriteriaCollector().apply(criteriaReceiver).criteria) .build() ) } fun <T> or(column: BindableColumn<T>, condition: VisitableCondition<T>): CriteriaCollector = apply { criteria.add( ColumnAndConditionCriterion.withColumn(column) .withCondition(condition) .withConnector("or") .build() ) } fun <T> or( column: BindableColumn<T>, condition: VisitableCondition<T>, criteriaReceiver: CriteriaReceiver ): CriteriaCollector = apply { criteria.add( ColumnAndConditionCriterion.withColumn(column) .withCondition(condition) .withSubCriteria(CriteriaCollector().apply(criteriaReceiver).criteria) .withConnector("or") .build() ) } fun or(existsPredicate: ExistsPredicate): CriteriaCollector = apply { criteria.add( ExistsCriterion.Builder() .withConnector("or") .withExistsPredicate(existsPredicate) .build() ) } fun or(existsPredicate: ExistsPredicate, criteriaReceiver: CriteriaReceiver): CriteriaCollector = apply { criteria.add( ExistsCriterion.Builder() .withConnector("or") .withExistsPredicate(existsPredicate) .withSubCriteria(CriteriaCollector().apply(criteriaReceiver).criteria) .build() ) } }
apache-2.0
4fba463867685beb59809dcc79c6e58e
34.262295
102
0.586007
5.145933
false
false
false
false
grassrootza/grassroot-android-v2
app/src/main/java/za/org/grassroot2/services/account/AccountAuthenticator.kt
1
5109
package za.org.grassroot2.services.account import android.accounts.AbstractAccountAuthenticator import android.accounts.Account import android.accounts.AccountAuthenticatorResponse import android.accounts.AccountManager import android.accounts.NetworkErrorException import android.content.Context import android.content.Intent import android.os.Bundle import android.text.TextUtils import javax.inject.Inject import timber.log.Timber import za.org.grassroot2.GrassrootApplication import za.org.grassroot2.services.UserDetailsService import za.org.grassroot2.services.rest.GrassrootAuthApi import za.org.grassroot2.view.activity.LoginActivity class AccountAuthenticator(private val context: Context) : AbstractAccountAuthenticator(context) { @Inject internal lateinit var authApi: GrassrootAuthApi @Inject internal lateinit var userService: UserDetailsService init { (context.applicationContext as GrassrootApplication).appComponent.inject(this) Timber.e("created the account authenticator") } override fun editProperties(accountAuthenticatorResponse: AccountAuthenticatorResponse, s: String): Bundle? { return null } @Throws(NetworkErrorException::class) override fun addAccount(accountAuthenticatorResponse: AccountAuthenticatorResponse, accountType: String, authTokenType: String, features: Array<String>, options: Bundle): Bundle { Timber.e("adding an account! inside authenticator, of type: %s", accountType) val intent = Intent(context, LoginActivity::class.java) intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType) intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, accountAuthenticatorResponse) intent.putExtra(EXTRA_NEW_ACCOUNT, true) val bundle = Bundle() bundle.putParcelable(AccountManager.KEY_INTENT, intent) return bundle } @Throws(NetworkErrorException::class) override fun confirmCredentials(accountAuthenticatorResponse: AccountAuthenticatorResponse, account: Account, bundle: Bundle): Bundle? { return null } @Throws(NetworkErrorException::class) override fun getAuthToken(accountAuthenticatorResponse: AccountAuthenticatorResponse, account: Account, authTokenType: String, bundle: Bundle): Bundle { val am = AccountManager.get(context) val authToken = am.peekAuthToken(account, authTokenType) val result = Bundle() if (!TextUtils.isEmpty(authToken)) { Timber.d("have a JWT, use it") addTokenToResultBundle(account, authToken, result) } else { Timber.d("no JWT, so go to login") tryTokenRefresh(accountAuthenticatorResponse, account, am, result) } return result } private fun tryTokenRefresh(accountAuthenticatorResponse: AccountAuthenticatorResponse, account: Account, am: AccountManager, result: Bundle) { val oldToken = am.getUserData(account, AuthConstants.USER_DATA_CURRENT_TOKEN) authApi.refreshOtp(oldToken, null).subscribe({ response -> if (response.isSuccessful) { addTokenToResultBundle(account, response.body()!!.data, result) } else { userService.logout(false, false).subscribe({ aBoolean -> }, { Timber.d(it) }) val intent = Intent(context, LoginActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, accountAuthenticatorResponse) intent.putExtra(EXTRA_TOKEN_EXPIRED, true) result.putParcelable(AccountManager.KEY_INTENT, intent) } }, { Timber.e(it) }) } private fun addTokenToResultBundle(account: Account, authToken: String?, result: Bundle) { result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name) result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type) result.putString(AccountManager.KEY_AUTHTOKEN, authToken) } override fun getAuthTokenLabel(authTokenType: String): String? { return if (AuthConstants.AUTH_TOKENTYPE == authTokenType) authTokenType else null } @Throws(NetworkErrorException::class) override fun updateCredentials(accountAuthenticatorResponse: AccountAuthenticatorResponse, account: Account, s: String, bundle: Bundle): Bundle? { return null } @Throws(NetworkErrorException::class) override fun hasFeatures(accountAuthenticatorResponse: AccountAuthenticatorResponse, account: Account, strings: Array<String>): Bundle? { return null } override fun getAccountRemovalAllowed(response: AccountAuthenticatorResponse, account: Account): Bundle { val result = Bundle() result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, true) return result } companion object { private val EXTRA_NEW_ACCOUNT = "extra_new_account" private val EXTRA_TOKEN_EXPIRED = "extra_token_expired" } }
bsd-3-clause
dd7ac90c1d7e6befaa01df406a873ffd
42.29661
156
0.723038
4.999022
false
false
false
false
jingcai-wei/android-news
app/src/main/java/com/sky/android/news/ui/helper/VImageGetter.kt
1
3030
/* * Copyright (c) 2017 The sky Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sky.android.news.ui.helper import android.content.Context import android.graphics.Canvas import android.graphics.Rect import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.text.Html import android.widget.TextView import com.bumptech.glide.Glide import com.bumptech.glide.request.target.SimpleTarget import com.bumptech.glide.request.transition.Transition import com.sky.android.common.util.Alog import java.lang.ref.WeakReference /** * Created by sky on 17-9-24. */ class VImageGetter(val context: Context, private val textView: TextView) : Html.ImageGetter { override fun getDrawable(source: String): Drawable { Alog.d("loadImageSource: $source") val urlDrawable = UrlDrawable() // 加载图片 Glide.with(context.applicationContext) .asDrawable() .load(source) .into(DrawableTarget(urlDrawable, textView)) return urlDrawable } inner class DrawableTarget(urlDrawable: UrlDrawable, container: TextView) : SimpleTarget<Drawable>() { private val drawableReference: WeakReference<UrlDrawable> = WeakReference(urlDrawable) private val containerReference: WeakReference<TextView> = WeakReference(container) override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) { val urlDrawable = drawableReference.get()?: return val textView = containerReference.get()?: return val height = resource.intrinsicHeight val width = resource.intrinsicWidth val scale = getScale(resource) val rect = Rect(0, 0, (width * scale).toInt(), (height * scale).toInt()) resource.bounds = rect urlDrawable.bounds = rect urlDrawable.drawable = resource textView.text = containerReference.get()!!.text textView.invalidate() } private fun getScale(drawable: Drawable): Float { val maxWidth = containerReference.get()!!.width.toFloat() val originalDrawableWidth = drawable.intrinsicWidth.toFloat() return maxWidth / originalDrawableWidth } } inner class UrlDrawable : BitmapDrawable() { var drawable: Drawable? = null override fun draw(canvas: Canvas) { drawable?.draw(canvas) } } }
apache-2.0
10dea6d1ec5785e36d083b3cf861bcaf
31.858696
106
0.685308
4.670788
false
false
false
false
grassrootza/grassroot-android-v2
app/src/main/kotlin/za/org/grassroot2/presenter/MePresenter.kt
1
8558
package za.org.grassroot2.presenter import android.net.Uri import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import okhttp3.MediaType import okhttp3.MultipartBody import okhttp3.RequestBody import timber.log.Timber import za.org.grassroot2.R import za.org.grassroot2.database.DatabaseService import za.org.grassroot2.model.MediaFile import za.org.grassroot2.model.TokenResponse import za.org.grassroot2.model.UserProfile import za.org.grassroot2.presenter.fragment.BaseFragmentPresenter import za.org.grassroot2.services.MediaService import za.org.grassroot2.services.UserDetailsService import za.org.grassroot2.services.rest.GrassrootUserApi import za.org.grassroot2.services.rest.RestResponse import za.org.grassroot2.view.MeView import java.io.File class MePresenter(private val dbService: DatabaseService, private val mediaService: MediaService, private val userDetailsService: UserDetailsService, private val grassrootUserApi: GrassrootUserApi) : BaseFragmentPresenter<MeView>() { private lateinit var currentMediaFileUid: String private lateinit var userProfile: UserProfile override fun onViewCreated() { this.userProfile = dbService.loadUserProfile()!! //this will thrown NPE if user gets to this screen, and it has no user profile data stored view.displayUserData(userProfile) } fun logout() { disposableOnDetach(userDetailsService.logout(true, true) .subscribeOn(io()) .observeOn(main()) .subscribe({ b -> view.returnToWelcomeActivity() }, { it.printStackTrace() })) } fun getLanguages(): Observable<Map<String, String>> { return grassrootUserApi.fetchLanguages() } fun takePhoto() { disposableOnDetach( mediaService .createFileForMedia("image/jpeg", MediaFile.FUNCTION_USER_PROFILE_PHOTO) .subscribeOn(io()) .observeOn(main()) .subscribe({ s -> val mediaFile = dbService.loadObjectByUid(MediaFile::class.java, s)!! currentMediaFileUid = s view.cameraForResult(mediaFile.contentProviderPath, s) }, { throwable -> view.showErrorDialog(R.string.me_error_updating_photo) Timber.e(throwable, "Error creating file") } )) } fun pickFromGallery() { disposableOnDetach(view.ensureWriteExteralStoragePermission().flatMapSingle<String> { aBoolean -> if (aBoolean) { mediaService.createFileForMedia("image/jpeg", MediaFile.FUNCTION_USER_PROFILE_PHOTO) } else throw Exception("Permission not granted") }.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { s -> currentMediaFileUid = s view.pickFromGallery() }, { view.showErrorDialog(R.string.me_error_updating_photo) it.printStackTrace() } ) ) } fun cameraResult() { disposableOnDetach(mediaService.captureMediaFile(currentMediaFileUid, 500, 500) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { val mediaFile = dbService.loadObjectByUid(MediaFile::class.java, currentMediaFileUid) if (mediaFile != null) uploadProfilePhoto(mediaFile) }, { this.handleMediaError(it) } ) ) } fun handlePickResult(data: Uri) { disposableOnDetach(mediaService.storeGalleryFile(currentMediaFileUid, data, 500, 500) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { val mediaFile = dbService.loadObjectByUid(MediaFile::class.java, currentMediaFileUid) if (mediaFile != null) uploadProfilePhoto(mediaFile) }, { this.handleMediaError(it) } ) ) } fun updateProfileData(displayName: String, phoneNumber: String, email: String, languageCode: String) { grassrootUserApi.updateProfileData(displayName, phoneNumber, email, languageCode) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { result -> storeSuccessfulAuthAndProceed(result) }, { view.showErrorDialog(R.string.me_error_updating_data) Timber.e(it) } ) } private fun handleMediaError(throwable: Throwable) { view.showErrorDialog(R.string.me_error_updating_photo) Timber.e(throwable) } private fun uploadProfilePhoto(mediaFile: MediaFile) { mediaFile.initUploading() dbService.storeObject(MediaFile::class.java, mediaFile) val fileMultipart = getFileMultipart(mediaFile, "photo") disposableOnDetach( grassrootUserApi.uploadProfilePhoto(fileMultipart!!) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { result -> if (result.isSuccessful) { view.invalidateProfilePicCache(userProfile.uid) } }, { error -> view.showErrorDialog(R.string.me_error_updating_photo) Timber.e(error) } ) ) } private fun getFileMultipart(mediaFile: MediaFile, paramName: String): MultipartBody.Part? { return try { val file = File(mediaFile.absolutePath) val requestFile = RequestBody.create(MediaType.parse(mediaFile.mimeType), file) MultipartBody.Part.createFormData(paramName, file.name, requestFile) } catch (e: Exception) { Timber.e(e) null } } private fun storeSuccessfulAuthAndProceed(response: RestResponse<TokenResponse>) { val tokenAndUserDetails = response.data tokenAndUserDetails?.let { disposableOnDetach( userDetailsService.storeUserDetails(tokenAndUserDetails.userUid, tokenAndUserDetails.msisdn, tokenAndUserDetails.displayName, tokenAndUserDetails.email, tokenAndUserDetails.languageCode, tokenAndUserDetails.systemRole, tokenAndUserDetails.token) .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) .subscribe( { upd -> this.userProfile = upd view.displayUserData(this.userProfile) }, { view.showErrorDialog(R.string.me_error_updating_data) Timber.e(it) } ) ) } } fun isCurrentLanguage(languageCode: String): Boolean { return userProfile.languageCode == languageCode } fun addDisposableOnDetach(disposable: Disposable) { disposableOnDetach(disposable) } }
bsd-3-clause
4187220929d09d9170c4c3d66856937c
39.563981
147
0.532835
5.798103
false
false
false
false