repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
smmribeiro/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/tree/formatting.kt
5
2134
// 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.nj2k.tree import org.jetbrains.kotlin.utils.SmartList class JKComment(val text: String, val indent: String? = null) { val isSingleline get() = text.startsWith("//") } class JKTokenElementImpl(override val text: String) : JKTokenElement { override val trailingComments: MutableList<JKComment> = SmartList() override val leadingComments: MutableList<JKComment> = SmartList() override var hasTrailingLineBreak: Boolean = false override var hasLeadingLineBreak: Boolean = false } interface JKFormattingOwner { val trailingComments: MutableList<JKComment> val leadingComments: MutableList<JKComment> var hasTrailingLineBreak: Boolean var hasLeadingLineBreak: Boolean } fun <T : JKFormattingOwner> T.withFormattingFrom(other: JKFormattingOwner): T = also { trailingComments += other.trailingComments leadingComments += other.leadingComments hasTrailingLineBreak = other.hasTrailingLineBreak hasLeadingLineBreak = other.hasLeadingLineBreak } fun <T, S> T.withPsiAndFormattingFrom( other: S ): T where T : JKFormattingOwner, T : PsiOwner, S : JKFormattingOwner, S : PsiOwner = also { withFormattingFrom(other) this.psi = other.psi } inline fun <reified T : JKFormattingOwner> List<T>.withFormattingFrom(other: JKFormattingOwner): List<T> = also { if (isNotEmpty()) { it.first().trailingComments += other.trailingComments it.first().hasTrailingLineBreak = other.hasTrailingLineBreak it.last().leadingComments += other.leadingComments it.last().hasLeadingLineBreak = other.hasLeadingLineBreak } } fun JKFormattingOwner.clearFormatting() { trailingComments.clear() leadingComments.clear() hasTrailingLineBreak = false hasLeadingLineBreak = false } interface JKTokenElement : JKFormattingOwner { val text: String } fun JKFormattingOwner.containsNewLine(): Boolean = hasTrailingLineBreak || hasLeadingLineBreak
apache-2.0
57775a92c22b76e1c1fa73225a39d6c7
32.888889
158
0.748828
4.905747
false
false
false
false
Helabs/generator-he-kotlin-mvp
app/templates/app_arch_comp/src/main/kotlin/data/UserDataSource.kt
1
1103
package <%= appPackage %>.data import <%= appPackage %>.data.local.PreferencesDataSource import <%= appPackage %>.data.local.db.UserDao import <%= appPackage %>.data.model.User import <%= appPackage %>.data.remote.AppApi import io.reactivex.Completable import io.reactivex.Flowable import io.reactivex.Observable interface UserDataSource { fun getLastQuery(): Flowable<String> fun insertUser(user: User): Completable fun getUser(login: String): Observable<User> } class UserRepository(private val appApi: AppApi, val userDao: UserDao, private val preferencesDataSource: PreferencesDataSource): UserDataSource { override fun getUser(login: String): Observable<User> = appApi.getUser(login).doOnNext { preferencesDataSource.storeUser(it.login) } override fun insertUser(user: User): Completable = Completable.create { userDao.insertUser(user) } override fun getLastQuery(): Flowable<String> { return userDao.getLastQuery() .map { user -> user.login } } }
mit
4e6ef07b3c3a6ecbf27d1501eb3f0d87
32.454545
94
0.677244
4.774892
false
false
false
false
Coding/Coding-Android
push-xiaomi/src/main/java/net/coding/program/push/xiaomi/XiaomiPushReceiver.kt
1
10160
package net.coding.program.push.xiaomi import android.annotation.SuppressLint import android.content.Context import android.net.Uri import android.text.TextUtils import android.util.Log import com.xiaomi.mipush.sdk.* import org.greenrobot.eventbus.EventBus import java.net.URLDecoder import java.text.SimpleDateFormat import java.util.* /** * 1、PushMessageReceiver 是个抽象类,该类继承了 BroadcastReceiver。<br></br> * 2、需要将自定义的 DemoMessageReceiver 注册在 AndroidManifest.xml 文件中: * <pre> * `<receiver * android:name="com.xiaomi.mipushdemo.DemoMessageReceiver" * android:exported="true"> * <intent-filter> * <action android:name="com.xiaomi.mipush.RECEIVE_MESSAGE" /> * </intent-filter> * <intent-filter> * <action android:name="com.xiaomi.mipush.MESSAGE_ARRIVED" /> * </intent-filter> * <intent-filter> * <action android:name="com.xiaomi.mipush.ERROR" /> * </intent-filter> * </receiver> `</pre> * * 3、DemoMessageReceiver 的 onReceivePassThroughMessage 方法用来接收服务器向客户端发送的透传消息。<br></br> * 4、DemoMessageReceiver 的 onNotificationMessageClicked 方法用来接收服务器向客户端发送的通知消息, * 这个回调方法会在用户手动点击通知后触发。<br></br> * 5、DemoMessageReceiver 的 onNotificationMessageArrived 方法用来接收服务器向客户端发送的通知消息, * 这个回调方法是在通知消息到达客户端时触发。另外应用在前台时不弹出通知的通知消息到达客户端也会触发这个回调函数。<br></br> * 6、DemoMessageReceiver 的 onCommandResult 方法用来接收客户端向服务器发送命令后的响应结果。<br></br> * 7、DemoMessageReceiver 的 onReceiveRegisterResult 方法用来接收客户端向服务器发送注册命令后的响应结果。<br></br> * 8、以上这些方法运行在非 UI 线程中。 * * @author mayixiang */ class XiaomiPushReceiver : PushMessageReceiver() { private var mRegId: String? = null private val mTopic: String? = null private val mAlias: String? = null private val mAccount: String? = null private val mStartTime: String? = null private val mEndTime: String? = null private val simpleDate: String @SuppressLint("SimpleDateFormat") get() = SimpleDateFormat("MM-dd hh:mm:ss").format(Date()) override fun onReceivePassThroughMessage(context: Context?, message: MiPushMessage?) { Log.v(PushAction.TAG, "onReceivePassThroughMessage is called. " + message!!.toString()) // String log = context.getString(R.string.recv_passthrough_message, message.getContent()); // MainActivity.logList.add(0, getSimpleDate() + " " + log); // // if (!TextUtils.isEmpty(message.getTopic())) { // mTopic = message.getTopic(); // } else if (!TextUtils.isEmpty(message.getAlias())) { // mAlias = message.getAlias(); // } // // Message msg = Message.obtain(); // msg.obj = log; // DemoApplication.getHandler().sendMessage(msg); } override fun onNotificationMessageClicked(context: Context?, message: MiPushMessage?) { Log.v(PushAction.TAG, "onNotificationMessageClicked is called. " + message!!.toString()) val s = message.content if (TextUtils.isEmpty(s)) { return } val extra = HashMap<String, String>() try { val uri = Uri.parse("https://coding.net?" + s) val keyUrl = "param_url" val paramUrl = uri.getQueryParameter(keyUrl) if (!TextUtils.isEmpty(paramUrl)) { extra[keyUrl] = URLDecoder.decode(paramUrl) } val idKey = "notification_id" val paramId = uri.getQueryParameter(idKey) if (!TextUtils.isEmpty(paramId)) { extra[idKey] = paramId } } catch (e: Exception) { Log.e(PushAction.TAG, e.toString()) } if (!extra.isEmpty()) { XiaomiPush.clickPushAction?.click(context!!, extra) } } override fun onNotificationMessageArrived(context: Context?, message: MiPushMessage?) { Log.v(PushAction.TAG, "onNotificationMessageArrived is called. " + message!!.toString()) // String log = context.getString(R.string.arrive_notification_message, message.getContent()); // MainActivity.logList.add(0, getSimpleDate() + " " + log); // // if (!TextUtils.isEmpty(message.getTopic())) { // mTopic = message.getTopic(); // } else if (!TextUtils.isEmpty(message.getAlias())) { // mAlias = message.getAlias(); // } // // Message msg = Message.obtain(); // msg.obj = log; // DemoApplication.getHandler().sendMessage(msg); } override fun onCommandResult(context: Context?, message: MiPushCommandMessage?) { Log.v(PushAction.TAG, "onCommandResult is called. " + message!!.toString()) // String command = message.getCommand(); // List<String> arguments = message.getCommandArguments(); // String cmdArg1 = ((arguments != null && arguments.size() > 0) ? arguments.get(0) : null); // String cmdArg2 = ((arguments != null && arguments.size() > 1) ? arguments.get(1) : null); // String log; // if (MiPushClient.COMMAND_REGISTER.equals(command)) { // if (message.getResultCode() == ErrorCode.SUCCESS) { // mRegId = cmdArg1; // log = context.getString(R.string.register_success); // } else { // log = context.getString(R.string.register_fail); // } // } else if (MiPushClient.COMMAND_SET_ALIAS.equals(command)) { // if (message.getResultCode() == ErrorCode.SUCCESS) { // mAlias = cmdArg1; // log = context.getString(R.string.set_alias_success, mAlias); // } else { // log = context.getString(R.string.set_alias_fail, message.getReason()); // } // } else if (MiPushClient.COMMAND_UNSET_ALIAS.equals(command)) { // if (message.getResultCode() == ErrorCode.SUCCESS) { // mAlias = cmdArg1; // log = context.getString(R.string.unset_alias_success, mAlias); // } else { // log = context.getString(R.string.unset_alias_fail, message.getReason()); // } // } else if (MiPushClient.COMMAND_SET_ACCOUNT.equals(command)) { // if (message.getResultCode() == ErrorCode.SUCCESS) { // mAccount = cmdArg1; // log = context.getString(R.string.set_account_success, mAccount); // } else { // log = context.getString(R.string.set_account_fail, message.getReason()); // } // } else if (MiPushClient.COMMAND_UNSET_ACCOUNT.equals(command)) { // if (message.getResultCode() == ErrorCode.SUCCESS) { // mAccount = cmdArg1; // log = context.getString(R.string.unset_account_success, mAccount); // } else { // log = context.getString(R.string.unset_account_fail, message.getReason()); // } // } else if (MiPushClient.COMMAND_SUBSCRIBE_TOPIC.equals(command)) { // if (message.getResultCode() == ErrorCode.SUCCESS) { // mTopic = cmdArg1; // log = context.getString(R.string.subscribe_topic_success, mTopic); // } else { // log = context.getString(R.string.subscribe_topic_fail, message.getReason()); // } // } else if (MiPushClient.COMMAND_UNSUBSCRIBE_TOPIC.equals(command)) { // if (message.getResultCode() == ErrorCode.SUCCESS) { // mTopic = cmdArg1; // log = context.getString(R.string.unsubscribe_topic_success, mTopic); // } else { // log = context.getString(R.string.unsubscribe_topic_fail, message.getReason()); // } // } else if (MiPushClient.COMMAND_SET_ACCEPT_TIME.equals(command)) { // if (message.getResultCode() == ErrorCode.SUCCESS) { // mStartTime = cmdArg1; // mEndTime = cmdArg2; // log = context.getString(R.string.set_accept_time_success, mStartTime, mEndTime); // } else { // log = context.getString(R.string.set_accept_time_fail, message.getReason()); // } // } else { // log = message.getReason(); // } // MainActivity.logList.add(0, getSimpleDate() + " " + log); // // Message msg = Message.obtain(); // msg.obj = log; // DemoApplication.getHandler().sendMessage(msg); } override fun onReceiveRegisterResult(context: Context?, message: MiPushCommandMessage?) { Log.v(PushAction.TAG, "onReceiveRegisterResult is called. " + message!!.toString()) if (MiPushClient.COMMAND_REGISTER == message.command && message.resultCode == ErrorCode.SUCCESS.toLong()) { message.commandArguments?.let { if (it.size > 0) mRegId = it[0] else mRegId = null } EventBus.getDefault().postSticky(EventPushToken("xiaomi", MiPushClient.getRegId(context))) } } }
mit
bffd0d4324375f19e1491142753f3689
45.085714
109
0.55528
4.299422
false
false
false
false
kmikusek/light-sensor
app/src/main/java/pl/pw/mgr/lightsensor/regression/Measurements.kt
1
5285
package pl.pw.mgr.lightsensor.regression import pl.pw.mgr.lightsensor.data.model.Point object Measurements { val NOTE_1_NAME = "Note 1" val NOTE_2_NAME = "Note 2" val GALAXY_NAME = "Galaxy S3" val HTC_NAME = "HTC One S" val NOTE_1: List<Point> = listOf( Point(1.00f, 10f), Point(2.00f, 20f), Point(5.00f, 30f), Point(5.89f, 40f), Point(6.14f, 50f), Point(7.00f, 60f), Point(8.00f, 70f), Point(8.00f, 80f), Point(8.89f, 90f), Point(9.17f, 100f), Point(9.89f, 110f), Point(10.31f, 120f), Point(10.75f, 130f), Point(12.60f, 140f), Point(12.97f, 150f), Point(13.96f, 160f), Point(14.52f, 170f), Point(14.57f, 180f), Point(15.05f, 190f), Point(15.59f, 200f), Point(18.06f, 250f), Point(20.16f, 300f), Point(22.43f, 350f), Point(24.07f, 400f), Point(25.67f, 450f), Point(26.83f, 500f), Point(29.38f, 550f), Point(31.34f, 600f), Point(32.23f, 650f), Point(34.04f, 700f), Point(34.88f, 750f), Point(37.13f, 800f), Point(38.10f, 850f), Point(38.69f, 900f), Point(40.09f, 950f), Point(40.87f, 1000f) ) val NOTE_2: List<Point> = listOf( Point(14.00f, 10f), Point(28.83f, 20f), Point(44.06f, 30f), Point(56.08f, 40f), Point(70.09f, 50f), Point(84.15f, 60f), Point(99.07f, 70f), Point(112.55f, 80f), Point(127.20f, 90f), Point(141.26f, 100f), Point(156.00f, 110f), Point(170.78f, 120f), Point(183.48f, 130f), Point(197.59f, 140f), Point(212.13f, 150f), Point(225.74f, 160f), Point(241.20f, 170f), Point(259.50f, 180f), Point(275.66f, 190f), Point(288.10f, 200f), Point(363.43f, 250f), Point(433.55f, 300f), Point(514.18f, 350f), Point(587.27f, 400f), Point(664.96f, 450f), Point(735.36f, 500f), Point(813.92f, 550f), Point(881.51f, 600f), Point(958.91f, 650f), Point(1036.43f, 700f), Point(1110.03f, 750f), Point(1194.42f, 800f), Point(1265.88f, 850f), Point(1342.03f, 900f), Point(1422.43f, 950f), Point(1571.28f, 1000f) ) val GALAXY: List<Point> = listOf( Point(14.77f, 10f), Point(29.00f, 20f), Point(42.85f, 30f), Point(56.24f, 40f), Point(69.72f, 50f), Point(84.17f, 60f), Point(97.85f, 70f), Point(112.04f, 80f), Point(126.31f, 90f), Point(138.92f, 100f), Point(153.35f, 110f), Point(166.12f, 120f), Point(181.00f, 130f), Point(193.87f, 140f), Point(208.62f, 150f), Point(221.11f, 160f), Point(235.22f, 170f), Point(250.09f, 180f), Point(264.12f, 190f), Point(278.38f, 200f), Point(349.76f, 250f), Point(419.54f, 300f), Point(487.17f, 350f), Point(560.23f, 400f), Point(632.24f, 450f), Point(701.05f, 500f), Point(772.42f, 550f), Point(826.52f, 600f), Point(894.02f, 650f), Point(965.97f, 700f), Point(1035.21f, 750f), Point(1106.63f, 800f), Point(1181.49f, 850f), Point(1250.52f, 900f), Point(1324.03f, 950f), Point(1387.16f, 1000f) ) val HTC: List<Point> = listOf( Point(320.00f, 10f), Point(320.00f, 20f), Point(640.00f, 30f), Point(640.00f, 40f), Point(1280.00f, 50f), Point(1280.00f, 60f), Point(1280.00f, 70f), Point(1280.00f, 80f), Point(2600.00f, 90f), Point(2600.00f, 100f), Point(2600.00f, 110f), Point(2600.00f, 120f), Point(2600.00f, 130f), Point(10240.00f, 140f), Point(10240.00f, 150f), Point(10240.00f, 160f), Point(10240.00f, 170f), Point(10240.00f, 180f), Point(10240.00f, 190f), Point(10240.00f, 200f), Point(10240.00f, 250f), Point(10240.00f, 300f), Point(10240.00f, 350f), Point(10240.00f, 400f), Point(10240.00f, 450f), Point(10240.00f, 500f), Point(10240.00f, 550f), Point(10240.00f, 600f), Point(10240.00f, 650f), Point(10240.00f, 700f), Point(10240.00f, 750f), Point(10240.00f, 800f), Point(10240.00f, 850f), Point(10240.00f, 900f), Point(10240.00f, 950f), Point(10240.00f, 1000f) ) }
mit
9d62d40810b3867d8c04cfbb247cb019
30.464286
45
0.452034
3.047866
false
false
false
false
nicolas-raoul/apps-android-commons
app/src/test/kotlin/fr/free/nrw/commons/review/ReviewHelperTest.kt
3
4906
package fr.free.nrw.commons.review import com.nhaarman.mockitokotlin2.whenever import fr.free.nrw.commons.Media import fr.free.nrw.commons.media.MediaClient import io.reactivex.Observable import io.reactivex.Single import junit.framework.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.mockito.ArgumentMatchers import org.mockito.InjectMocks import org.mockito.Mock import org.mockito.Mockito.* import org.mockito.MockitoAnnotations import org.wikipedia.dataclient.mwapi.MwQueryPage import org.wikipedia.dataclient.mwapi.MwQueryResponse import org.wikipedia.dataclient.mwapi.MwQueryResult import org.wikipedia.dataclient.mwapi.RecentChange /** * Test class for ReviewHelper */ class ReviewHelperTest { @Mock internal var reviewInterface: ReviewInterface? = null @Mock internal var mediaClient: MediaClient? = null @InjectMocks var reviewHelper: ReviewHelper? = null /** * Init mocks */ @Before @Throws(Exception::class) fun setUp() { MockitoAnnotations.initMocks(this) val mwQueryPage = mock(MwQueryPage::class.java) val mockRevision = mock(MwQueryPage.Revision::class.java) `when`(mockRevision.user).thenReturn("TestUser") `when`(mwQueryPage.revisions()).thenReturn(listOf(mockRevision)) val recentChange = getMockRecentChange("log", "File:Test1.jpeg", 0) val recentChange1 = getMockRecentChange("log", "File:Test2.png", 0) val recentChange2 = getMockRecentChange("log", "File:Test3.jpg", 0) val mwQueryResult = mock(MwQueryResult::class.java) `when`(mwQueryResult.recentChanges).thenReturn(listOf(recentChange, recentChange1, recentChange2)) `when`(mwQueryResult.firstPage()).thenReturn(mwQueryPage) `when`(mwQueryResult.pages()).thenReturn(listOf(mwQueryPage)) val mockResponse = mock(MwQueryResponse::class.java) `when`(mockResponse.query()).thenReturn(mwQueryResult) `when`(reviewInterface?.getRecentChanges(ArgumentMatchers.anyString())) .thenReturn(Observable.just(mockResponse)) `when`(reviewInterface?.getFirstRevisionOfFile(ArgumentMatchers.anyString())) .thenReturn(Observable.just(mockResponse)) val media = mock(Media::class.java) whenever(media.filename).thenReturn("Test file.jpg") `when`(mediaClient?.getMedia(ArgumentMatchers.anyString())) .thenReturn(Single.just(media)) } /** * Test for getting random media */ @Test fun getRandomMedia() { `when`(mediaClient?.checkPageExistsUsingTitle(ArgumentMatchers.anyString())) .thenReturn(Single.just(false)) `when`(mediaClient?.checkPageExistsUsingTitle(ArgumentMatchers.anyString())) .thenReturn(Single.just(false)) reviewHelper?.randomMedia verify(reviewInterface, times(1))!!.getRecentChanges(ArgumentMatchers.anyString()) } /** * Test scenario when all media is already nominated for deletion */ @Test(expected = RuntimeException::class) fun getRandomMediaWithWithAllMediaNominatedForDeletion() { `when`(mediaClient?.checkPageExistsUsingTitle(ArgumentMatchers.anyString())) .thenReturn(Single.just(true)) val media = reviewHelper?.randomMedia?.blockingGet() assertNull(media) verify(reviewInterface, times(1))!!.getRecentChanges(ArgumentMatchers.anyString()) } /** * Test scenario when first media is already nominated for deletion */ @Test fun getRandomMediaWithWithOneMediaNominatedForDeletion() { `when`(mediaClient?.checkPageExistsUsingTitle("Commons:Deletion_requests/File:Test1.jpeg")) .thenReturn(Single.just(true)) `when`(mediaClient?.checkPageExistsUsingTitle("Commons:Deletion_requests/File:Test2.png")) .thenReturn(Single.just(false)) `when`(mediaClient?.checkPageExistsUsingTitle("Commons:Deletion_requests/File:Test3.jpg")) .thenReturn(Single.just(true)) reviewHelper?.randomMedia verify(reviewInterface, times(1))!!.getRecentChanges(ArgumentMatchers.anyString()) } private fun getMockRecentChange(type: String, title: String, oldRevisionId: Long): RecentChange { val recentChange = mock(RecentChange::class.java) `when`(recentChange!!.type).thenReturn(type) `when`(recentChange.title).thenReturn(title) `when`(recentChange.oldRevisionId).thenReturn(oldRevisionId) return recentChange } /** * Test for getting first revision of file */ @Test fun getFirstRevisionOfFile() { val firstRevisionOfFile = reviewHelper?.getFirstRevisionOfFile("Test.jpg")?.blockingFirst() assertTrue(firstRevisionOfFile is MwQueryPage.Revision) } }
apache-2.0
04beca406466ad3c1faee7ee699175d5
37.031008
106
0.703628
4.795699
false
true
false
false
breadwallet/breadwallet-android
app/src/main/java/com/platform/interfaces/MetaDataManager.kt
1
17245
/** * BreadWallet * * Created by Ahsan Butt <[email protected]> on 9/17/19. * Copyright (c) 2019 breadwallet LLC * * 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.platform.interfaces import com.breadwallet.BuildConfig import com.breadwallet.app.BreadApp import com.breadwallet.breadbox.hashString import com.breadwallet.breadbox.isErc20 import com.breadwallet.crypto.Transfer import com.breadwallet.crypto.WalletManagerMode import com.breadwallet.logger.logDebug import com.breadwallet.logger.logError import com.breadwallet.logger.logInfo import com.breadwallet.platform.entities.TxMetaData import com.breadwallet.platform.entities.TxMetaDataEmpty import com.breadwallet.platform.entities.TxMetaDataValue import com.breadwallet.platform.entities.WalletInfoData import com.breadwallet.platform.interfaces.AccountMetaDataProvider import com.breadwallet.protocols.messageexchange.entities.PairingMetaData import com.breadwallet.tools.crypto.CryptoHelper import com.breadwallet.tools.util.TokenUtil import com.breadwallet.tools.util.Utils import com.platform.entities.TokenListMetaData import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.mapLatest import kotlinx.coroutines.flow.onStart import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.util.Date import java.util.Locale @Suppress("TooManyFunctions") class MetaDataManager( private val storeProvider: KVStoreProvider ) : WalletProvider, AccountMetaDataProvider { companion object { private const val KEY_WALLET_INFO = "wallet-info" private const val KEY_TOKEN_LIST_META_DATA = "token-list-metadata" private const val KEY_MSG_INBOX = "encrypted-message-inbox-metadata" private const val KEY_ASSET_INDEX = "asset-index" private const val CURSOR = "cursor" private const val ENABLED_ASSET_IDS = "enabledAssetIds" private const val CLASS_VERSION = "classVersion" private const val CLASS_VERSION_ASSET_IDS = 2 private const val CLASS_VERSION_MSG_INBOX = 1 private const val TX_META_DATA_KEY_PREFIX = "txn2-" private const val TK_META_DATA_KEY_PREFIX = "tkxf-" private const val PAIRING_META_DATA_KEY_PREFIX = "pwd-" private val ORDERED_KEYS = listOf(KEY_WALLET_INFO, KEY_ASSET_INDEX, KEY_TOKEN_LIST_META_DATA) } override fun create(accountCreationDate: Date) { val walletInfoJson = WalletInfoData( creationDate = accountCreationDate.time, connectionModes = BreadApp.getDefaultWalletModes() ).toJSON() storeProvider.put(KEY_WALLET_INFO, walletInfoJson) putEnabledWallets(BreadApp.getDefaultEnabledWallets()) logInfo("MetaDataManager created successfully") } override suspend fun recoverAll(migrate: Boolean): Boolean { // Sync essential metadata first, migrate enabled wallets ASAP storeProvider.sync(KEY_WALLET_INFO) storeProvider.sync(KEY_ASSET_INDEX) if (migrate) { storeProvider.sync(KEY_TOKEN_LIST_META_DATA) migrateTokenList() } // Not redundant to prioritize the above in ordered keys // if above was successful, will be a no-op, and if failed, it's a retry val syncResult = storeProvider.syncAll(ORDERED_KEYS) if (storeProvider.get(KEY_ASSET_INDEX) == null) { // Something went wrong, put default wallets storeProvider.put( KEY_ASSET_INDEX, enabledWalletsToJSON(BreadApp.getDefaultEnabledWallets()) ) } return syncResult } override fun walletInfo(): Flow<WalletInfoData> = storeProvider.keyFlow(KEY_WALLET_INFO) .mapLatest { WalletInfoData.fromJsonObject(it) } .onStart { emit( getOrSync( KEY_WALLET_INFO ) { WalletInfoData().toJSON() } !!.run { WalletInfoData.fromJsonObject(this) } ) } .distinctUntilChanged() override fun getWalletInfoUnsafe(): WalletInfoData? = try { storeProvider.get(KEY_WALLET_INFO) ?.run { WalletInfoData.fromJsonObject(this) } } catch (ex: JSONException) { logError("$ex") null } override fun enabledWallets(): Flow<List<String>> = storeProvider.keyFlow(KEY_ASSET_INDEX) .mapLatest { jsonToEnabledWallets(it) } .onStart { getOrSync(KEY_ASSET_INDEX)?.run { emit(jsonToEnabledWallets(this)) } } .distinctUntilChanged() override fun enableWallet(currencyId: String) { val enabledWallets = getEnabledWalletsUnsafe()?.toMutableList() ?: mutableListOf() if (!enabledWallets.contains(currencyId)) { putEnabledWallets( enabledWallets.apply { add(currencyId) } ) } } override fun enableWallets(currencyIds: List<String>) { val enabledWallets = getEnabledWalletsUnsafe().orEmpty() putEnabledWallets(enabledWallets.union(currencyIds).toList()) } override fun disableWallet(currencyId: String) { getEnabledWalletsUnsafe() ?.toMutableList() ?.filter { !it.equals(currencyId, true) } ?.run(::putEnabledWallets) } override fun reorderWallets(currencyIds: List<String>) { putEnabledWallets(currencyIds) } override fun walletModes(): Flow<Map<String, WalletManagerMode>> = walletInfo() .mapLatest { it.connectionModes } .distinctUntilChanged() override suspend fun putWalletMode(currencyId: String, mode: WalletManagerMode) { var walletInfo = walletInfo().first() if (walletInfo.connectionModes[currencyId] == mode) return val connectionModes = walletInfo.connectionModes.toMutableMap().apply { put(currencyId, mode) } walletInfo = walletInfo.copy(connectionModes = connectionModes) storeProvider.put( KEY_WALLET_INFO, walletInfo.toJSON() ) } override fun getPairingMetadata(pubKey: ByteArray): PairingMetaData? = try { val key = pairingKey(pubKey) storeProvider.get(key)?.run(::PairingMetaData) } catch (ex: JSONException) { logError("Error getting pairing metadata", ex) null } override fun putPairingMetadata(pairingData: PairingMetaData): Boolean = when (pairingData.publicKeyHex) { null -> { logError("pairingData.getPublicKeyHex() is null!") false } else -> { val rawPubKey = CryptoHelper.hexDecode(pairingData.publicKeyHex) ?: pairingData.publicKeyHex.toByteArray(Charsets.UTF_8) storeProvider.put(pairingKey(rawPubKey), pairingData.toJSON()) } } override fun getLastCursor(): String? = try { storeProvider.get(KEY_MSG_INBOX)?.getString(CURSOR) } catch (ex: JSONException) { logError("Error getting last cursor", ex) null } override fun putLastCursor(lastCursor: String): Boolean = storeProvider.put( KEY_MSG_INBOX, JSONObject( mapOf( CLASS_VERSION to CLASS_VERSION_MSG_INBOX, CURSOR to lastCursor ) ) ) override fun txMetaData(onlyGifts: Boolean): Map<String, TxMetaData> { return storeProvider.getKeys() .filter { it.startsWith(TX_META_DATA_KEY_PREFIX) } .mapNotNull { key -> storeProvider.get(key)?.run { key to this } } .toMap() .run { if (onlyGifts) filterValues { TxMetaDataValue.hasGift(it) } else this } .mapValues { (_, v) -> TxMetaDataValue.fromJsonObject(v) } } override fun txMetaData(key: String, isErc20: Boolean): Flow<TxMetaData> { return storeProvider.keyFlow(key) .mapLatest { TxMetaDataValue.fromJsonObject(it) } .onStart { val metaData = storeProvider.get(key) if (metaData != null) emit(TxMetaDataValue.fromJsonObject(metaData)) else emit(TxMetaDataEmpty) } .distinctUntilChanged() } override fun txMetaData(transaction: Transfer): Flow<TxMetaData> { val key = getTxMetaDataKey(transaction) return txMetaData(key, isErc20 = transaction.wallet.currency.isErc20()) } override suspend fun putTxMetaData( transaction: Transfer, newTxMetaData: TxMetaDataValue ) { val key = getTxMetaDataKey(transaction) putTxMetaData(key, transaction.wallet.currency.isErc20(), newTxMetaData) } override suspend fun putTxMetaData(key: String, isErc20: Boolean, newTxMetaData: TxMetaDataValue) { var txMetaData = txMetaData(key, isErc20 = isErc20).first() var needsUpdate = false when (txMetaData) { is TxMetaDataEmpty -> { needsUpdate = !newTxMetaData.comment.isNullOrBlank() || newTxMetaData.exchangeRate != 0.0 || !newTxMetaData.gift?.keyData.isNullOrBlank() txMetaData = newTxMetaData } is TxMetaDataValue -> { val newGift = newTxMetaData.gift val oldGift = txMetaData.gift if (newGift != oldGift && newGift != null) { // Don't overwrite gift unless keyData is provided if (oldGift?.keyData == null && newGift.keyData != null) { txMetaData = txMetaData.copy( gift = newTxMetaData.gift ) needsUpdate = true } else if ( oldGift?.keyData != null && (oldGift.claimed != newGift.claimed || oldGift.reclaimed != newGift.reclaimed) ) { txMetaData = txMetaData.copy( gift = oldGift.copy( claimed = newGift.claimed, reclaimed = newGift.reclaimed ) ) needsUpdate = true } } if (newTxMetaData.comment != txMetaData.comment) { txMetaData = txMetaData.copy( comment = newTxMetaData.comment ) needsUpdate = true } if (txMetaData.exchangeRate == 0.0 && newTxMetaData.exchangeRate != 0.0) { txMetaData = txMetaData.copy( exchangeRate = newTxMetaData.exchangeRate ) needsUpdate = true } } } if (needsUpdate) { storeProvider.put(key, txMetaData.toJSON()) } } override fun getEnabledWalletsUnsafe(): List<String>? = try { storeProvider.get(KEY_ASSET_INDEX) ?.getJSONArray(ENABLED_ASSET_IDS) ?.run { List(length()) { getString(it) } } } catch (ex: JSONException) { logError("$ex") null } override fun resetDefaultWallets() { putEnabledWallets(BreadApp.getDefaultEnabledWallets()) } private fun putEnabledWallets(enabledWallets: List<String>) = enabledWalletsToJSON(enabledWallets) .also { storeProvider.put(KEY_ASSET_INDEX, it) } private fun migrateTokenList() { if (storeProvider.get(KEY_ASSET_INDEX) != null) { logDebug("Metadata for $KEY_ASSET_INDEX found, no migration needed.") return } logDebug("Migrating $KEY_TOKEN_LIST_META_DATA to $KEY_ASSET_INDEX.") try { val tokenListMetaData = storeProvider.get(KEY_TOKEN_LIST_META_DATA) ?.run(::TokenListMetaData) if (tokenListMetaData == null) { logDebug("No value for $KEY_TOKEN_LIST_META_DATA found.") return } TokenUtil.initialize(BreadApp.getBreadContext(), true, !BuildConfig.BITCOIN_TESTNET) val currencyCodeToToken = TokenUtil.getTokenItems() .associateBy { it.symbol.toLowerCase(Locale.ROOT) } tokenListMetaData.enabledCurrencies .filter { enabledToken -> // Need to also ensure not in hidden currencies list tokenListMetaData.hiddenCurrencies.find { it.symbol.equals(enabledToken.symbol, true) } == null } .mapNotNull { currencyCodeToToken[it.symbol.toLowerCase(Locale.ROOT)]?.currencyId } .apply { if (isNotEmpty()) { putEnabledWallets(this) logDebug("Migration to $KEY_ASSET_INDEX completed.") } } } catch (ex: JSONException) { logError("$ex") } } private suspend fun getOrSync( key: String, defaultProducer: (() -> JSONObject)? = null ): JSONObject? { val value = storeProvider.get(key) ?: storeProvider.sync(key) return when (value) { null -> { defaultProducer ?.invoke() ?.also { logDebug("Sync returned null. Putting default value: $key -> $it") storeProvider.put(key, it) } } else -> value } } private fun enabledWalletsToJSON(wallets: List<String>) = JSONObject( mapOf( CLASS_VERSION to CLASS_VERSION_ASSET_IDS, ENABLED_ASSET_IDS to wallets.toJSON() ) ) private fun jsonToEnabledWallets(walletsJSON: JSONObject) = walletsJSON .getJSONArray(ENABLED_ASSET_IDS) .run { List(length(), this::getString) } private fun List<String>.toJSON(): JSONArray { val json = JSONArray() forEach { json.put(it) } return json } private fun getTxMetaDataKey(transaction: Transfer, legacy: Boolean = false): String { return getTxMetaDataKey( transferHash = transaction.hashString(), isErc20 = transaction.wallet.currency.isErc20(), legacy = legacy ) } private fun getTxMetaDataKey( transferHash: String, isErc20: Boolean, legacy: Boolean = false ): String = if (legacy) { TX_META_DATA_KEY_PREFIX + Utils.bytesToHex( CryptoHelper.sha256(transferHash.toByteArray())!! ) } else { val hashString = transferHash.removePrefix("0x") val sha256hash = (CryptoHelper.hexDecode(hashString) ?: hashString.toByteArray(Charsets.UTF_8)) .apply { reverse() } .run(CryptoHelper::sha256) ?.run(CryptoHelper::hexEncode) ?: "" if (isErc20) TK_META_DATA_KEY_PREFIX + sha256hash else TX_META_DATA_KEY_PREFIX + sha256hash } private fun pairingKey(pubKey: ByteArray): String = PAIRING_META_DATA_KEY_PREFIX + CryptoHelper.hexEncode(CryptoHelper.sha256(pubKey)!!) }
mit
ea9975b2b1399a3a107d71e109d8c771
36.652838
136
0.584923
5.124814
false
false
false
false
Adven27/Exam
exam-db/src/main/java/io/github/adven27/concordion/extensions/exam/db/commands/check/CheckParsers.kt
1
4383
package io.github.adven27.concordion.extensions.exam.db.commands.check import io.github.adven27.concordion.extensions.exam.core.commands.SuitableCommandParser import io.github.adven27.concordion.extensions.exam.core.commands.awaitConfig import io.github.adven27.concordion.extensions.exam.core.html.DbRowParser import io.github.adven27.concordion.extensions.exam.core.html.Html import io.github.adven27.concordion.extensions.exam.core.html.attr import io.github.adven27.concordion.extensions.exam.core.html.html import io.github.adven27.concordion.extensions.exam.db.DbTester.Companion.DEFAULT_DATASOURCE import io.github.adven27.concordion.extensions.exam.db.MarkedHasNoDefaultValue import io.github.adven27.concordion.extensions.exam.db.TableData import io.github.adven27.concordion.extensions.exam.db.builder.DataSetBuilder import io.github.adven27.concordion.extensions.exam.db.builder.ExamTable import io.github.adven27.concordion.extensions.exam.db.commands.ColParser import io.github.adven27.concordion.extensions.exam.db.commands.check.CheckCommand.Expected import org.concordion.api.CommandCall import org.concordion.api.Element import org.concordion.api.Evaluator import org.dbunit.dataset.Column import org.dbunit.dataset.DefaultTable import org.dbunit.dataset.ITable import org.dbunit.dataset.datatype.DataType abstract class CheckParser : SuitableCommandParser<Expected> { abstract fun table(command: CommandCall, evaluator: Evaluator): ITable abstract fun caption(command: CommandCall): String? override fun parse(command: CommandCall, evaluator: Evaluator) = Expected( ds = command.attr("ds", DEFAULT_DATASOURCE), caption = caption(command), table = table(command, evaluator), orderBy = command.html().takeAwayAttr("orderBy", evaluator)?.split(",")?.map { it.trim() } ?: listOf(), where = command.html().takeAwayAttr("where", evaluator) ?: "", await = command.awaitConfig() ) } class MdCheckParser : CheckParser() { override fun isSuitFor(element: Element): Boolean = element.localName != "div" override fun caption(command: CommandCall) = command.element.text.ifBlank { null } private fun root(command: CommandCall) = command.element.parentElement.parentElement override fun table(command: CommandCall, evaluator: Evaluator): ITable { val builder = DataSetBuilder() val tableName = command.expression return root(command) .let { cols(it) to values(it) } .let { (cols, rows) -> rows.forEach { row -> builder.newRowTo(tableName).withFields(cols.zip(row).toMap()).add() } builder.build().let { ExamTable( if (it.tableNames.isEmpty()) DefaultTable(tableName, toColumns(cols)) else it.getTable(tableName), evaluator ) } } } private fun toColumns(cols: List<String>) = cols.map { Column(it, DataType.UNKNOWN) }.toTypedArray() private fun cols(it: Element) = it.getFirstChildElement("thead").getFirstChildElement("tr").childElements.map { it.text.trim() } private fun values(it: Element) = it.getFirstChildElement("tbody").childElements.map { tr -> tr.childElements.map { it.text.trim() } } } open class HtmlCheckParser : CheckParser() { private val remarks = HashMap<String, Int>() private val colParser = ColParser() override fun isSuitFor(element: Element): Boolean = element.localName == "div" override fun caption(command: CommandCall) = command.html().attr("caption") override fun table(command: CommandCall, evaluator: Evaluator): ITable = command.html().let { TableData.filled( it.takeAwayAttr("table", evaluator)!!, DbRowParser(it, "row", null, null).parse(), parseCols(it), evaluator ) } protected fun parseCols(el: Html): Map<String, Any?> { val attr = el.takeAwayAttr("cols") return if (attr == null) emptyMap() else { val remarkAndVal = colParser.parse(attr) remarks += remarkAndVal.map { it.key to it.value.first }.filter { it.second > 0 } remarkAndVal.mapValues { if (it.value.second == null) MarkedHasNoDefaultValue() else it.value.second } } } }
mit
130b1b7c659ab37d21967b393222cac6
45.62766
114
0.693361
4.127119
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/search/gene/sql/SqlMultidimensionalArrayGene.kt
1
16596
package org.evomaster.core.search.gene.sql import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType import org.evomaster.core.logging.LoggingUtil import org.evomaster.core.output.OutputFormat import org.evomaster.core.search.gene.* import org.evomaster.core.search.gene.collection.ArrayGene import org.evomaster.core.search.gene.root.CompositeGene import org.evomaster.core.search.gene.utils.GeneUtils import org.evomaster.core.search.impact.impactinfocollection.ImpactUtils import org.evomaster.core.search.service.Randomness import org.evomaster.core.search.service.mutator.MutationWeightControl import org.evomaster.core.search.service.mutator.genemutation.AdditionalGeneMutationInfo import org.evomaster.core.search.service.mutator.genemutation.SubsetGeneMutationSelectionStrategy import org.slf4j.Logger import org.slf4j.LoggerFactory /** * https://www.postgresql.org/docs/14/arrays.html * A multidimensional array representation. * When created, all dimensions have length 0 */ class SqlMultidimensionalArrayGene<T>( /** * The name of this gene */ name: String, /** * The database type of the column where the gene is inserted. * By default, the database type is POSTGRES */ val databaseType: DatabaseType = DatabaseType.POSTGRES, /** * The type for this array. Every time we create a new element to add, it has to be based * on this template */ val template: T, /** * Fixed number of dimensions for this multidimensional array. * Once created, the number of dimensions do not change. */ val numberOfDimensions: Int, /** * How many elements each dimension can have. */ private val maxDimensionSize: Int = ArrayGene.MAX_SIZE ) : CompositeGene(name, mutableListOf()) where T : Gene { /** * Stores what is the size of each dimension. * It is used to check that the multidimensional array * is valid. */ private var dimensionSizes: List<Int> = listOf() init { if (numberOfDimensions < 1) throw IllegalArgumentException("Invalid number of dimensions $numberOfDimensions") } /* FIXME only one direct child override children modifications to rather work on internal array genes. but, before that, need to refactor/look-into CollectionGene */ companion object { val log: Logger = LoggerFactory.getLogger(SqlMultidimensionalArrayGene::class.java) /** * Checks if the given index is within range. * Otherwise an IndexOutOfBounds exception is thrown. */ private fun checkIndexWithinRange(index: Int, indices: IntRange) { if (index !in indices) { throw IndexOutOfBoundsException("Cannot access index $index in a dimension of size $indices") } } /** * Recursively creates the internal representation * of the multidimensional array. The argument is * a list of the size for each dimension. */ private fun <T : Gene> buildNewElements( dimensionSizes: List<Int>, elementTemplate: T ): ArrayGene<*> { val s = dimensionSizes[0] return if (dimensionSizes.size == 1) { // leaf ArrayGene case ArrayGene("[$s]", elementTemplate.copy(), maxSize = s, minSize = s) } else { // nested/inner ArrayGene case val currentDimensionSize = dimensionSizes.first() val nextDimensionSizes = dimensionSizes.drop(1) val arrayTemplate = buildNewElements(nextDimensionSizes, elementTemplate) ArrayGene("[$currentDimensionSize]${arrayTemplate.name}", arrayTemplate, maxSize = currentDimensionSize, minSize = currentDimensionSize) } } } override fun isMutable(): Boolean { return !initialized || this.children[0].isMutable() } /** * Returns the element by using a list of indices for * each dimension. The number of indices must be equal * to the number of dimensions of the multidimensional array. * Additionally, each index must be within range. * * For example, given the following multidimensional array. * { {g1,g2,g3} , {g4, g5, g6} } * getElement({0,0}) returns g1. * getElement({2,2}) returns g6 */ fun getElement(dimensionIndexes: List<Int>): T { if (!initialized) { throw IllegalStateException("Cannot get element from an unitialized multidimensional array") } if (dimensionIndexes.size != numberOfDimensions) { throw IllegalArgumentException("Incorrect number of indices to get an element of an array of $numberOfDimensions dimensions") } var current = getArray() ((0..(dimensionIndexes.size - 2))).forEach { checkIndexWithinRange(dimensionIndexes[it], current.getViewOfElements().indices) current = current.getViewOfElements()[dimensionIndexes[it]] as ArrayGene<*> } checkIndexWithinRange(dimensionIndexes.last(), current.getViewOfElements().indices) return current.getViewOfElements()[dimensionIndexes.last()] as T } private fun isValid(currentArrayGene: ArrayGene<*>, currentDimensionIndex: Int): Boolean { return if (!currentArrayGene.isLocallyValid()) false else if (currentArrayGene.getViewOfChildren().size != this.dimensionSizes[currentDimensionIndex]) { false } else if (currentDimensionIndex == numberOfDimensions - 1) { // case of leaf ArrayGene currentArrayGene.getViewOfChildren().all { it::class.java.isAssignableFrom(template::class.java) } } else { // case of inner, nested ArrayGene currentArrayGene.getViewOfChildren().all { isValid(it as ArrayGene<*>, currentDimensionIndex + 1) } } } /** * Check that the nested arraygenes equal the number of dimensions, check that each * dimension length is preserved. */ override fun isLocallyValid(): Boolean { return if (this.children.size != 1) { false } else { isValid(this.children[0] as ArrayGene<*>, 0) } } /** * Requires the multidimensional array to be initialized */ private fun getArray(): ArrayGene<*> { assert(initialized) return children[0] as ArrayGene<*> } /** * Returns the dimension size for the required dimension * For example, given the following multidimensional array. * { {g1,g2,g3} , {g4, g5, g6} } * getDimensionSize(0) returns 2. * getDimensionSize(1) returns 3 */ fun getDimensionSize(dimensionIndex: Int): Int { if (!initialized) { throw IllegalStateException("Cannot get element from an unitialized multidimensional array") } if (dimensionIndex >= this.numberOfDimensions) { throw IndexOutOfBoundsException("Cannot get dimension size of dimension ${dimensionIndex} for an array of ${numberOfDimensions} dimensions") } var current = getArray() if (current.getViewOfElements().isEmpty()) { checkIndexWithinRange(dimensionIndex, IntRange(0, numberOfDimensions - 1)) return 0 } repeat(dimensionIndex) { current = current.getViewOfElements()[0] as ArrayGene<*> } return current.getViewOfElements().size } /** * Randomizes the whole multidimensional array by removing all dimensions, and then * creating new sizes for each dimension, and new gene elements from the template. */ override fun randomize(randomness: Randomness, tryToForceNewValue: Boolean) { val newDimensionSizes: List<Int> = buildNewDimensionSizes(randomness) val newChild = buildNewElements(newDimensionSizes, template.copy()) killAllChildren() this.dimensionSizes = newDimensionSizes if(initialized){ newChild.doInitialize(randomness) } else { newChild.randomize(randomness, tryToForceNewValue) } addChild(newChild) } /** * Creates a new list of randomized dimension sizes. * The total number of dimensions is equal to numberOfDimensions, and * no dimension is greater than maxDimensionSize. * If the array is unidimensional, the dimensionSize could be 0, otherwise * is always greater than 0. */ private fun buildNewDimensionSizes(randomness: Randomness): List<Int> { if (numberOfDimensions == 1) { val dimensionSize = randomness.nextInt(0, maxDimensionSize) return mutableListOf(dimensionSize) } else { val dimensionSizes: MutableList<Int> = mutableListOf() repeat(numberOfDimensions) { val dimensionSize = randomness.nextInt(1, maxDimensionSize) dimensionSizes.add(dimensionSize) } return dimensionSizes.toList() } } /** * Returns true if the other gene is another multidimensional array, * with the same number of dimensions, size of each dimension, * and containsSameValueAs the other genes. */ override fun containsSameValueAs(other: Gene): Boolean { if (!initialized) { throw IllegalStateException("Cannot call to containsSameValueAs using an unitialized multidimensional array") } if (other !is SqlMultidimensionalArrayGene<*>) { throw IllegalArgumentException("Invalid gene type ${other.javaClass}") } if (this.numberOfDimensions != other.numberOfDimensions) { return false } if (this.dimensionSizes != other.dimensionSizes) { return false } return this.getViewOfChildren()[0].containsSameValueAs(other.getViewOfChildren()[0]) } /** * A multidimensional array gene can only bind to other multidimensional array genes * with the same template and number of dimensions. */ override fun bindValueBasedOn(gene: Gene): Boolean { if (gene !is SqlMultidimensionalArrayGene<*>) { LoggingUtil.uniqueWarn(ArrayGene.log, "cannot bind SqlMultidimensionalArrayGene to ${gene::class.java.simpleName}") return false } if (gene.template::class.java.simpleName != template::class.java.simpleName) { LoggingUtil.uniqueWarn(ArrayGene.log, "cannot bind SqlMultidimensionalArrayGene with the template (${template::class.java.simpleName}) with ${gene::class.java.simpleName}") return false } if (numberOfDimensions != gene.numberOfDimensions) { LoggingUtil.uniqueWarn(ArrayGene.log, "cannot bind SqlMultidimensionalArrayGene of ${numberOfDimensions} dimensions to another multidimensional array gene of ${gene.numberOfDimensions}") return false } killAllChildren() val elements = gene.getViewOfChildren().mapNotNull { it.copy() as? T }.toMutableList() addChildren(elements) this.dimensionSizes = gene.dimensionSizes return true } override fun getValueAsPrintableString( previousGenes: List<Gene>, mode: GeneUtils.EscapeMode?, targetFormat: OutputFormat?, extraCheck: Boolean ): String { if (!initialized) { throw IllegalStateException("Cannot call to getValueAsPrintableString() using an unitialized multidimensional array") } val printableString = getValueAsPrintableString(this.children[0], previousGenes, mode,targetFormat , extraCheck) return when (databaseType) { DatabaseType.H2 -> printableString DatabaseType.POSTGRES -> "\"$printableString\"" else -> throw IllegalStateException("Unsupported getValueAsPrintableString for database type $databaseType") } } /** * Helper funcgtion for printing the inner arrays and elements */ private fun getValueAsPrintableString(gene: Gene, previousGenes: List<Gene>, mode: GeneUtils.EscapeMode?, targetFormat: OutputFormat?, extraCheck: Boolean ): String { return if (gene is ArrayGene<*>) { val str = gene.getViewOfElements().joinToString(", ") { g -> getValueAsPrintableString(g, previousGenes, mode, targetFormat, extraCheck)} when (databaseType) { DatabaseType.POSTGRES -> "{$str}" DatabaseType.H2 -> "ARRAY[$str]" else -> throw IllegalStateException("Unsupported getValueAsPrintableString for database type $databaseType") } } else { val str = gene.getValueAsPrintableString(previousGenes, mode, targetFormat, extraCheck) when (databaseType) { DatabaseType.POSTGRES -> str DatabaseType.H2 -> GeneUtils.replaceEnclosedQuotationMarksWithSingleApostrophePlaceHolder(str) else -> throw IllegalStateException("Unsupported getValueAsPrintableString for database type $databaseType") } } } override fun copyValueFrom(other: Gene) { if (other !is SqlMultidimensionalArrayGene<*>) { throw IllegalArgumentException("Invalid gene type ${other.javaClass}") } if (numberOfDimensions != other.numberOfDimensions) { throw IllegalArgumentException("Cannot copy value to array of $numberOfDimensions dimensions from array of ${other.numberOfDimensions} dimensions") } getViewOfChildren()[0].copyValueFrom(other.getViewOfChildren()[0]) this.dimensionSizes = other.dimensionSizes } /** * 1 is for 'remove' or 'add' element. * The mutationWeight is computed on all elements in the same way * as ArrayGene.mutationWeight() */ override fun mutationWeight(): Double { return 1.0 //TODO //return 1.0 + getAllGenes(this.nestedListOfElements).sumOf { it.mutationWeight() } } /** * The function adaptiveSelectSubset() behaves as ArrayGene.adaptiveSelectSubset() */ override fun adaptiveSelectSubsetToMutate(randomness: Randomness, internalGenes: List<Gene>, mwc: MutationWeightControl, additionalGeneMutationInfo: AdditionalGeneMutationInfo ): List<Pair<Gene, AdditionalGeneMutationInfo?>> { /* element is dynamically modified, then we do not collect impacts for it now. thus for the internal genes, adaptive gene selection for mutation is not applicable */ val s = randomness.choose(internalGenes) /* TODO impact for an element in ArrayGene */ val geneImpact = ImpactUtils.createGeneImpact(s, s.name) return listOf(s to additionalGeneMutationInfo.copyFoInnerGene(geneImpact, s)) } override fun copyContent(): Gene { /* TODO Not sure about this. Even if we want to put this constraint, then should be in Gene */ // if (!initialized) { // throw IllegalStateException("Cannot call to copyContent() from an uninitialized multidimensional array") // } val copy = SqlMultidimensionalArrayGene( name = name, databaseType = this.databaseType, template = template.copy(), numberOfDimensions = numberOfDimensions, maxDimensionSize = maxDimensionSize ) if (children.isNotEmpty()) { copy.addChild(this.children[0].copy()) } copy.dimensionSizes = this.dimensionSizes return copy } override fun isPrintable(): Boolean { return getViewOfChildren().all { it.isPrintable() } } override fun customShouldApplyShallowMutation( randomness: Randomness, selectionStrategy: SubsetGeneMutationSelectionStrategy, enableAdaptiveGeneMutation: Boolean, additionalGeneMutationInfo: AdditionalGeneMutationInfo? ): Boolean { return false } }
lgpl-3.0
261f13dae3fdc9fa11ab6a8a959d6376
38.610979
198
0.63925
5.497184
false
false
false
false
ibinti/intellij-community
platform/platform-tests/testSrc/com/intellij/openapi/vfs/local/FileWatcherTest.kt
6
21796
/* * 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 com.intellij.openapi.vfs.local import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.IoTestUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.* import com.intellij.openapi.vfs.impl.local.FileWatcher import com.intellij.openapi.vfs.impl.local.LocalFileSystemImpl import com.intellij.openapi.vfs.impl.local.NativeFileWatcherImpl import com.intellij.openapi.vfs.newvfs.NewVirtualFile import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.VfsTestUtil import com.intellij.testFramework.fixtures.BareTestFixtureTestCase import com.intellij.testFramework.rules.TempDirectory import com.intellij.testFramework.runInEdtAndWait import com.intellij.util.Alarm import com.intellij.util.TimeoutUtil import com.intellij.util.concurrency.Semaphore import org.assertj.core.api.Assertions.assertThat import org.junit.After import org.junit.Assume.assumeFalse import org.junit.Assume.assumeTrue import org.junit.Before import org.junit.Rule import org.junit.Test import java.io.File import java.util.* import java.util.concurrent.atomic.AtomicBoolean import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue class FileWatcherTest : BareTestFixtureTestCase() { //<editor-fold desc="Set up / tear down"> private val LOG: Logger by lazy { Logger.getInstance(NativeFileWatcherImpl::class.java) } private val START_STOP_DELAY = 10000L // time to wait for the watcher spin up/down private val INTER_RESPONSE_DELAY = 500L // time to wait for a next event in a sequence private val NATIVE_PROCESS_DELAY = 60000L // time to wait for a native watcher response private val SHORT_PROCESS_DELAY = 5000L // time to wait when no native watcher response is expected private val UNICODE_NAME_1 = "Úñíçødê" private val UNICODE_NAME_2 = "Юникоде" @Rule @JvmField val tempDir = TempDirectory() private lateinit var fs: LocalFileSystem private lateinit var root: VirtualFile private lateinit var watcher: FileWatcher private lateinit var alarm: Alarm private val watchedPaths = mutableListOf<String>() private val watcherEvents = Semaphore() private val resetHappened = AtomicBoolean() @Before fun setUp() { LOG.debug("================== setting up " + getTestName(false) + " ==================") fs = LocalFileSystem.getInstance() root = refresh(tempDir.root) runInEdtAndWait { VirtualFileManager.getInstance().syncRefresh() } alarm = Alarm(Alarm.ThreadToUse.POOLED_THREAD, testRootDisposable) watcher = (fs as LocalFileSystemImpl).fileWatcher assertFalse(watcher.isOperational) watchedPaths += tempDir.root.path watcher.startup { path -> if (path == FileWatcher.RESET || path != FileWatcher.OTHER && watchedPaths.any { path.startsWith(it) }) { alarm.cancelAllRequests() alarm.addRequest({ watcherEvents.up() }, INTER_RESPONSE_DELAY) if (path == FileWatcher.RESET) resetHappened.set(true) } } wait { !watcher.isOperational } LOG.debug("================== setting up " + getTestName(false) + " ==================") } @After fun tearDown() { LOG.debug("================== tearing down " + getTestName(false) + " ==================") watcher.shutdown() wait { watcher.isOperational } runInEdtAndWait { runWriteAction { root.delete(this) } (fs as LocalFileSystemImpl).cleanupForNextTest() } LOG.debug("================== tearing down " + getTestName(false) + " ==================") } //</editor-fold> @Test fun testWatchRequestConvention() { val dir = tempDir.newFolder("dir") val r1 = watch(dir) val r2 = watch(dir) assertFalse(r1 == r2) } @Test fun testFileRoot() { val files = arrayOf(tempDir.newFile("test1.txt"), tempDir.newFile("test2.txt")) files.forEach { refresh(it) } files.forEach { watch(it, false) } assertEvents({ files.forEach { it.writeText("new content") } }, files.map { it to 'U' }.toMap()) assertEvents({ files.forEach { it.delete() } }, files.map { it to 'D' }.toMap()) assertEvents({ files.forEach { it.writeText("re-creation") } }, files.map { it to 'C' }.toMap()) } @Test fun testFileRootRecursive() { val files = arrayOf(tempDir.newFile("test1.txt"), tempDir.newFile("test2.txt")) files.forEach { refresh(it) } files.forEach { watch(it, true) } assertEvents({ files.forEach { it.writeText("new content") } }, files.map { it to 'U' }.toMap()) assertEvents({ files.forEach { it.delete() } }, files.map { it to 'D' }.toMap()) assertEvents({ files.forEach { it.writeText("re-creation") } }, files.map { it to 'C' }.toMap()) } @Test fun testNonCanonicallyNamedFileRoot() { assumeTrue(!SystemInfo.isFileSystemCaseSensitive) val file = tempDir.newFile("test.txt") refresh(file) watch(File(file.path.toUpperCase(Locale.US))) assertEvents({ file.writeText("new content") }, mapOf(file to 'U')) assertEvents({ file.delete() }, mapOf(file to 'D')) assertEvents({ file.writeText("re-creation") }, mapOf(file to 'C')) } @Test fun testDirectoryRecursive() { val top = tempDir.newFolder("top") val sub = File(top, "sub") val file = File(sub, "test.txt") refresh(top) watch(top) assertEvents({ sub.mkdir() }, mapOf(sub to 'C')) refresh(sub) assertEvents({ file.createNewFile() }, mapOf(file to 'C')) assertEvents({ file.writeText("new content") }, mapOf(file to 'U')) assertEvents({ file.delete() }, mapOf(file to 'D')) assertEvents({ file.writeText("re-creation") }, mapOf(file to 'C')) } @Test fun testDirectoryFlat() { val top = tempDir.newFolder("top") val watchedFile = tempDir.newFile("top/test.txt") val unwatchedFile = tempDir.newFile("top/sub/test.txt") refresh(top) watch(top, false) assertEvents({ watchedFile.writeText("new content") }, mapOf(watchedFile to 'U')) assertEvents({ unwatchedFile.writeText("new content") }, mapOf(), SHORT_PROCESS_DELAY) } @Test fun testDirectoryMixed() { val top = tempDir.newFolder("top") val sub = tempDir.newFolder("top/sub2") val unwatchedFile = tempDir.newFile("top/sub1/test.txt") val watchedFile1 = tempDir.newFile("top/test.txt") val watchedFile2 = tempDir.newFile("top/sub2/sub/test.txt") refresh(top) watch(top, false) watch(sub, true) assertEvents( { arrayOf(watchedFile1, watchedFile2, unwatchedFile).forEach { it.writeText("new content") } }, mapOf(watchedFile1 to 'U', watchedFile2 to 'U')) } @Test fun testIncorrectPath() { val root = tempDir.newFolder("root") val file = tempDir.newFile("root/file.zip") val pseudoDir = File(file, "sub/zip") refresh(root) watch(pseudoDir, false) assertEvents({ file.writeText("new content") }, mapOf(), SHORT_PROCESS_DELAY) } @Test fun testDirectoryOverlapping() { val top = tempDir.newFolder("top") val topFile = tempDir.newFile("top/file1.txt") val sub = tempDir.newFolder("top/sub") val subFile = tempDir.newFile("top/sub/file2.txt") val side = tempDir.newFolder("side") val sideFile = tempDir.newFile("side/file3.txt") refresh(top) refresh(side) watch(sub) watch(side) assertEvents( { arrayOf(subFile, sideFile).forEach { it.writeText("first content") } }, mapOf(subFile to 'U', sideFile to 'U')) assertEvents( { arrayOf(topFile, subFile, sideFile).forEach { it.writeText("new content") } }, mapOf(subFile to 'U', sideFile to 'U')) val requestForTopDir = watch(top) assertEvents( { arrayOf(topFile, subFile, sideFile).forEach { it.writeText("newer content") } }, mapOf(topFile to 'U', subFile to 'U', sideFile to 'U')) unwatch(requestForTopDir) assertEvents( { arrayOf(topFile, subFile, sideFile).forEach { it.writeText("newest content") } }, mapOf(subFile to 'U', sideFile to 'U')) assertEvents( { arrayOf(topFile, subFile, sideFile).forEach { it.delete() } }, mapOf(topFile to 'D', subFile to 'D', sideFile to 'D')) } // ensure that flat roots set via symbolic paths behave correctly and do not report dirty files returned from other recursive roots @Test fun testSymbolicLinkIntoFlatRoot() { val root = tempDir.newFolder("root") val cDir = tempDir.newFolder("root/A/B/C") val aLink = IoTestUtil.createSymLink("${root.path}/A", "${root.path}/aLink") val flatWatchedFile = tempDir.newFile("root/aLink/test.txt") val fileOutsideFlatWatchRoot = tempDir.newFile("root/A/B/C/test.txt") refresh(root) watch(aLink, false) watch(cDir, false) assertEvents({ flatWatchedFile.writeText("new content") }, mapOf(flatWatchedFile to 'U')) assertEvents({ fileOutsideFlatWatchRoot.writeText("new content") }, mapOf(fileOutsideFlatWatchRoot to 'U')) } @Test fun testMultipleSymbolicLinkPathsToFile() { val root = tempDir.newFolder("root") val file = tempDir.newFile("root/A/B/C/test.txt") val bLink = IoTestUtil.createSymLink("${root.path}/A/B", "${root.path}/bLink") val cLink = IoTestUtil.createSymLink("${root.path}/A/B/C", "${root.path}/cLink") refresh(root) val bFilePath = File(bLink.path, "C/${file.name}") val cFilePath = File(cLink.path, file.name) watch(bLink) watch(cLink) assertEvents({ file.writeText("new content") }, mapOf(bFilePath to 'U', cFilePath to 'U')) assertEvents({ file.delete() }, mapOf(bFilePath to 'D', cFilePath to 'D')) assertEvents({ file.writeText("re-creation") }, mapOf(bFilePath to 'C', cFilePath to 'C')) } @Test fun testSymbolicLinkAboveWatchRoot() { val top = tempDir.newFolder("top") val file = tempDir.newFile("top/dir1/dir2/dir3/test.txt") val link = IoTestUtil.createSymLink("${top.path}/dir1/dir2", "${top.path}/link") val fileLink = File(top, "link/dir3/test.txt") refresh(top) watch(link) assertEvents({ file.writeText("new content") }, mapOf(fileLink to 'U')) assertEvents({ file.delete() }, mapOf(fileLink to 'D')) assertEvents({ file.writeText("re-creation") }, mapOf(fileLink to 'C')) } /* public void testSymlinkBelowWatchRoot() throws Exception { final File targetDir = FileUtil.createTempDirectory("top.", null); final File file = FileUtil.createTempFile(targetDir, "test.", ".txt"); final File linkDir = FileUtil.createTempDirectory("link.", null); final File link = new File(linkDir, "link"); IoTestUtil.createTempLink(targetDir.getPath(), link.getPath()); final File fileLink = new File(link, file.getName()); refresh(targetDir); refresh(linkDir); final LocalFileSystem.WatchRequest request = watch(linkDir); try { myAccept = true; FileUtil.writeToFile(file, "new content"); assertEvent(VFileContentChangeEvent.class, fileLink.getPath()); myAccept = true; FileUtil.delete(file); assertEvent(VFileDeleteEvent.class, fileLink.getPath()); myAccept = true; FileUtil.writeToFile(file, "re-creation"); assertEvent(VFileCreateEvent.class, fileLink.getPath()); } finally { myFileSystem.removeWatchedRoot(request); delete(linkDir); delete(targetDir); } } */ @Test fun testSubst() { assumeTrue(SystemInfo.isWindows) val target = tempDir.newFolder("top") val file = tempDir.newFile("top/sub/test.txt") val substRoot = IoTestUtil.createSubst(target.path) VfsRootAccess.allowRootAccess(testRootDisposable, substRoot.path) val vfsRoot = fs.findFileByIoFile(substRoot)!! watchedPaths += substRoot.path val substFile = File(substRoot, "sub/test.txt") refresh(target) refresh(substRoot) try { watch(substRoot) assertEvents({ file.writeText("new content") }, mapOf(substFile to 'U')) val request = watch(target) assertEvents({ file.writeText("updated content") }, mapOf(file to 'U', substFile to 'U')) assertEvents({ file.delete() }, mapOf(file to 'D', substFile to 'D')) unwatch(request) assertEvents({ file.writeText("re-creation") }, mapOf(substFile to 'C')) } finally { IoTestUtil.deleteSubst(substRoot.path) (vfsRoot as NewVirtualFile).markDirty() fs.refresh(false) } } @Test fun testDirectoryRecreation() { val root = tempDir.newFolder("root") val dir = tempDir.newFolder("root/dir") val file1 = tempDir.newFile("root/dir/file1.txt") val file2 = tempDir.newFile("root/dir/file2.txt") refresh(root) watch(root) assertEvents( { dir.deleteRecursively(); dir.mkdir(); arrayOf(file1, file2).forEach { it.writeText("text") } }, mapOf(file1 to 'U', file2 to 'U')) } @Test fun testWatchRootRecreation() { val root = tempDir.newFolder("root") val file1 = tempDir.newFile("root/file1.txt") val file2 = tempDir.newFile("root/file2.txt") refresh(root) watch(root) assertEvents( { root.deleteRecursively(); root.mkdir() if (SystemInfo.isLinux) TimeoutUtil.sleep(1500) // implementation specific arrayOf(file1, file2).forEach { it.writeText("text") } }, mapOf(file1 to 'U', file2 to 'U')) } @Test fun testWatchNonExistingRoot() { val top = File(tempDir.root, "top") val root = File(tempDir.root, "top/d1/d2/d3/root") refresh(tempDir.root) watch(root) assertEvents({ root.mkdirs() }, mapOf(top to 'C')) } @Test fun testWatchRootRenameRemove() { val top = tempDir.newFolder("top") val root = tempDir.newFolder("top/d1/d2/d3/root") val root2 = File(top, "_root") refresh(top) watch(root) assertEvents({ root.renameTo(root2) }, mapOf(root to 'D', root2 to 'C')) assertEvents({ root2.renameTo(root) }, mapOf(root to 'C', root2 to 'D')) assertEvents({ root.deleteRecursively() }, mapOf(root to 'D')) assertEvents({ root.mkdirs() }, mapOf(root to 'C')) assertEvents({ top.deleteRecursively() }, mapOf(top to 'D')) assertEvents({ root.mkdirs() }, mapOf(top to 'C')) } @Test fun testSwitchingToFsRoot() { val top = tempDir.newFolder("top") val root = tempDir.newFolder("top/root") val file1 = tempDir.newFile("top/1.txt") val file2 = tempDir.newFile("top/root/2.txt") refresh(top) val fsRoot = File(if (SystemInfo.isUnix) "/" else top.path.substring(0, 3)) assertTrue(fsRoot.exists(), "can't guess root of " + top) val request = watch(root) assertEvents({ arrayOf(file1, file2).forEach { it.writeText("new content") } }, mapOf(file2 to 'U')) val rootRequest = watch(fsRoot) assertEvents({ arrayOf(file1, file2).forEach { it.writeText("12345") } }, mapOf(file1 to 'U', file2 to 'U'), SHORT_PROCESS_DELAY) unwatch(rootRequest) assertEvents({ arrayOf(file1, file2).forEach { it.writeText("") } }, mapOf(file2 to 'U')) unwatch(request) assertEvents({ arrayOf(file1, file2).forEach { it.writeText("xyz") } }, mapOf(), SHORT_PROCESS_DELAY) } @Test fun testLineBreaksInName() { assumeTrue(SystemInfo.isUnix) val root = tempDir.newFolder("root") val file = tempDir.newFile("root/weird\ndir\nname/weird\nfile\nname") refresh(root) watch(root) assertEvents({ file.writeText("abc") }, mapOf(file to 'U')) } @Test fun testHiddenFiles() { assumeTrue(SystemInfo.isWindows) val root = tempDir.newFolder("root") val file = tempDir.newFile("root/dir/file") refresh(root) watch(root) assertEvents({ IoTestUtil.setHidden(file.path, true) }, mapOf(file to 'P')) } @Test fun testFileCaseChange() { assumeTrue(!SystemInfo.isFileSystemCaseSensitive) val root = tempDir.newFolder("root") val file = tempDir.newFile("root/file.txt") val newFile = File(file.parent, StringUtil.capitalize(file.name)) refresh(root) watch(root) assertEvents({ file.renameTo(newFile) }, mapOf(newFile to 'P')) } // tests the same scenarios with an active file watcher (prevents explicit marking of refreshed paths) @Test fun testPartialRefresh() = LocalFileSystemTest.doTestPartialRefresh(tempDir.newFolder("top")) @Test fun testInterruptedRefresh() = LocalFileSystemTest.doTestInterruptedRefresh(tempDir.newFolder("top")) @Test fun testRefreshAndFindFile() = LocalFileSystemTest.doTestRefreshAndFindFile(tempDir.newFolder("top")) @Test fun testRefreshEquality() = LocalFileSystemTest.doTestRefreshEquality(tempDir.newFolder("top")) @Test fun testUnicodePaths() { val root = tempDir.newFolder(UNICODE_NAME_1) val file = tempDir.newFile("${UNICODE_NAME_1}/${UNICODE_NAME_2}.txt") refresh(root) watch(root) assertEvents({ file.writeText("abc") }, mapOf(file to 'U')) } @Test fun testDisplacementByIsomorphicTree() { assumeTrue(!SystemInfo.isMac) val top = tempDir.newFolder("top") val root = tempDir.newFolder("top/root") val file = tempDir.newFile("top/root/middle/file.txt") file.writeText("original content") val root_copy = File(top, "root_copy") root.copyRecursively(root_copy) file.writeText("new content") val root_bak = File(top, "root.bak") val vFile = fs.refreshAndFindFileByIoFile(file)!! assertEquals("new content", VfsUtilCore.loadText(vFile)) watch(root) assertEvents({ root.renameTo(root_bak); root_copy.renameTo(root) }, mapOf(file to 'U')) assertTrue(vFile.isValid) assertEquals("original content", VfsUtilCore.loadText(vFile)) } @Test fun testWatchRootReplacement() { val root1 = tempDir.newFolder("top/root1") val root2 = tempDir.newFolder("top/root2") val file1 = tempDir.newFile("top/root1/file.txt") val file2 = tempDir.newFile("top/root2/file.txt") refresh(file1) refresh(file2) val request = watch(root1) assertEvents({ arrayOf(file1, file2).forEach { it.writeText("data") } }, mapOf(file1 to 'U')) fs.replaceWatchedRoot(request, root2.path, true) wait { watcher.isSettingRoots } assertEvents({ arrayOf(file1, file2).forEach { it.writeText("more data") } }, mapOf(file2 to 'U')) } @Test fun testPermissionUpdate() { val file = tempDir.newFile("test.txt") val vFile = refresh(file) assertTrue(vFile.isWritable) val ro = if (SystemInfo.isWindows) arrayOf("attrib", "+R", file.path) else arrayOf("chmod", "500", file.path) val rw = if (SystemInfo.isWindows) arrayOf("attrib", "-R", file.path) else arrayOf("chmod", "700", file.path) watch(file) assertEvents({ PlatformTestUtil.assertSuccessful(GeneralCommandLine(*ro)) }, mapOf(file to 'P')) assertFalse(vFile.isWritable) assertEvents({ PlatformTestUtil.assertSuccessful(GeneralCommandLine(*rw)) }, mapOf(file to 'P')) assertTrue(vFile.isWritable) } @Test fun testSyncRefreshNonWatchedFile() { val file = tempDir.newFile("test.txt") val vFile = refresh(file) file.writeText("new content") assertThat(VfsTestUtil.print(VfsTestUtil.getEvents { vFile.refresh(false, false) })).containsOnly("U : ${vFile.path}") } //<editor-fold desc="Helpers"> private fun wait(timeout: Long = START_STOP_DELAY, condition: () -> Boolean) { val stopAt = System.currentTimeMillis() + timeout while (condition()) { assertTrue(System.currentTimeMillis() < stopAt, "operation timed out") TimeoutUtil.sleep(10) } } private fun watch(file: File, recursive: Boolean = true): LocalFileSystem.WatchRequest { val request = fs.addRootToWatch(file.path, recursive)!! wait { watcher.isSettingRoots } return request } private fun unwatch(request: LocalFileSystem.WatchRequest) { fs.removeWatchedRoot(request) wait { watcher.isSettingRoots } fs.refresh(false) } private fun refresh(file: File): VirtualFile { val vFile = fs.refreshAndFindFileByIoFile(file)!! VfsUtilCore.visitChildrenRecursively(vFile, object : VirtualFileVisitor<Any>() { override fun visitFile(file: VirtualFile): Boolean { file.children; return true } }) vFile.refresh(false, true) return vFile } private fun assertEvents(action: () -> Unit, expectedOps: Map<File, Char>, timeout: Long = NATIVE_PROCESS_DELAY) { LOG.debug("** waiting for ${expectedOps}") watcherEvents.down() alarm.cancelAllRequests() resetHappened.set(false) if (SystemInfo.isWindows || SystemInfo.isMac) TimeoutUtil.sleep(250) action() LOG.debug("** action performed") watcherEvents.waitFor(timeout) watcherEvents.up() assumeFalse("reset happened", resetHappened.get()) LOG.debug("** done waiting") val events = VfsTestUtil.getEvents { fs.refresh(false) } val expected = expectedOps.entries.map { "${it.value} : ${FileUtil.toSystemIndependentName(it.key.path)}" }.sorted() val actual = VfsTestUtil.print(events).sorted() assertEquals(expected, actual) } //</editor-fold> }
apache-2.0
c94c1a00fc39e3f65756f9686577380b
36.047619
133
0.682321
3.93053
false
true
false
false
RP-Kit/RPKit
bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/command/profile/ProfileSetNameCommand.kt
1
3085
/* * Copyright 2021 Ren Binden * 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.rpkit.players.bukkit.command.profile import com.rpkit.core.command.RPKCommandExecutor import com.rpkit.core.command.result.* import com.rpkit.core.command.sender.RPKCommandSender import com.rpkit.core.service.Services import com.rpkit.players.bukkit.RPKPlayersBukkit import com.rpkit.players.bukkit.command.result.NoProfileSelfFailure import com.rpkit.players.bukkit.command.result.NotAPlayerFailure import com.rpkit.players.bukkit.profile.RPKProfile import com.rpkit.players.bukkit.profile.RPKProfileName import com.rpkit.players.bukkit.profile.RPKProfileService import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfile import java.util.concurrent.CompletableFuture class ProfileSetNameCommand(private val plugin: RPKPlayersBukkit) : RPKCommandExecutor { class InvalidNameFailure : CommandFailure() override fun onCommand(sender: RPKCommandSender, args: Array<out String>): CompletableFuture<CommandResult> { if (args.isEmpty()) { sender.sendMessage(plugin.messages.profileSetNameUsage) return CompletableFuture.completedFuture(IncorrectUsageFailure()) } if (sender !is RPKMinecraftProfile) { sender.sendMessage(plugin.messages.notFromConsole) return CompletableFuture.completedFuture(NotAPlayerFailure()) } val profile = sender.profile if (profile !is RPKProfile) { sender.sendMessage(plugin.messages.noProfileSelf) return CompletableFuture.completedFuture(NoProfileSelfFailure()) } val name = RPKProfileName(args[0]) if (!name.value.matches(Regex("[A-z0-9_]{3,16}"))) { sender.sendMessage(plugin.messages.profileSetNameInvalidName) return CompletableFuture.completedFuture(InvalidNameFailure()) } val profileService = Services[RPKProfileService::class.java] if (profileService == null) { sender.sendMessage(plugin.messages.noProfileService) return CompletableFuture.completedFuture(MissingServiceFailure(RPKProfileService::class.java)) } profile.name = name profileService.generateDiscriminatorFor(name).thenAccept { discriminator -> profile.discriminator = discriminator profileService.updateProfile(profile) sender.sendMessage(plugin.messages.profileSetNameValid.withParameters(name = name)) } return CompletableFuture.completedFuture(CommandSuccess) } }
apache-2.0
c4175882f0d421e55c553d5546953200
44.382353
113
0.739708
4.896825
false
false
false
false
mvarnagiris/mvp
mvp-test/src/main/kotlin/com/mvcoding/mvp/data/MemoryDataCacheTestFunctions.kt
1
2784
package com.mvcoding.mvp.data import com.mvcoding.mvp.DataSource import com.mvcoding.mvp.DataWriter import io.reactivex.observers.TestObserver fun <DATA, CACHE> testMemoryDataCache(data: DATA, createDataCache: (DATA?) -> CACHE) where CACHE : DataSource<DATA>, CACHE : DataWriter<DATA> { testDoesNotEmitAnythingInitiallyIfInitialDataWasNotProvided(createDataCache) testEmitsInitialValueIfItWasProvided(data, createDataCache) testEmitsLastValueThatWasWrittenBeforeSubscriptions(data, createDataCache) testEmitsLastValueThatWasWrittenAfterSubscriptions(null, data, createDataCache) } fun <DATA, CACHE> testMemoryDataCacheWithDefaultValue(initialValue: DATA, data: DATA, createDataCache: (DATA?) -> CACHE) where CACHE : DataSource<DATA>, CACHE : DataWriter<DATA> { testEmitsInitialValueIfItWasProvided(initialValue, createDataCache) testEmitsLastValueThatWasWrittenBeforeSubscriptions(data, createDataCache) testEmitsLastValueThatWasWrittenAfterSubscriptions(initialValue, data, createDataCache) } internal fun <DATA, CACHE> testDoesNotEmitAnythingInitiallyIfInitialDataWasNotProvided(createDataCache: (DATA?) -> CACHE) where CACHE : DataSource<DATA>, CACHE : DataWriter<DATA> { val observer = TestObserver.create<DATA>() val dataCache = createDataCache(null) dataCache.data().subscribe(observer) observer.assertNoValues() } internal fun <DATA, CACHE> testEmitsInitialValueIfItWasProvided(initialData: DATA, createDataCache: (DATA?) -> CACHE) where CACHE : DataSource<DATA>, CACHE : DataWriter<DATA> { val observer = TestObserver.create<DATA>() val dataCache = createDataCache(initialData) dataCache.data().subscribe(observer) observer.assertValue(initialData) } internal fun <DATA, CACHE> testEmitsLastValueThatWasWrittenBeforeSubscriptions(data: DATA, createDataCache: (DATA?) -> CACHE) where CACHE : DataSource<DATA>, CACHE : DataWriter<DATA> { val observer = TestObserver.create<DATA>() val dataCache = createDataCache(null) dataCache.write(data) dataCache.data().subscribe(observer) observer.assertValue(data) } internal fun <DATA, CACHE> testEmitsLastValueThatWasWrittenAfterSubscriptions(initialData: DATA?, data: DATA, createDataCache: (DATA?) -> CACHE) where CACHE : DataSource<DATA>, CACHE : DataWriter<DATA> { val observer1 = TestObserver.create<DATA>() val observer2 = TestObserver.create<DATA>() val dataCache = createDataCache(null) dataCache.data().subscribe(observer1) dataCache.data().subscribe(observer2) dataCache.write(data) if (initialData != null) { observer1.assertValues(initialData, data) observer2.assertValues(initialData, data) } else { observer1.assertValue(data) observer2.assertValue(data) } }
apache-2.0
06527ba615bc6e615bf7d76e236f019f
41.846154
203
0.770474
4.74276
false
true
false
false
PaleoCrafter/BitReplicator
src/main/kotlin/de/mineformers/bitreplicator/network/ReplicatorMode.kt
1
1517
package de.mineformers.bitreplicator.network import de.mineformers.bitreplicator.block.Replicator import io.netty.buffer.ByteBuf import net.minecraft.util.math.BlockPos import net.minecraftforge.fml.common.network.simpleimpl.IMessage import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler import net.minecraftforge.fml.common.network.simpleimpl.MessageContext /** * Message and handler for notifying the server about a mode change in a replicator. */ object ReplicatorMode { /** * The message simply holds the repliactors's position and the mode to be set. */ data class Message(var pos: BlockPos = BlockPos.ORIGIN, var mode: Int = 0) : IMessage { override fun toBytes(buf: ByteBuf) { buf.writeLong(pos.toLong()) buf.writeInt(mode) } override fun fromBytes(buf: ByteBuf) { pos = BlockPos.fromLong(buf.readLong()) mode = buf.readInt() } } object Handler : IMessageHandler<Message, IMessage> { override fun onMessage(msg: Message, ctx: MessageContext): IMessage? { val player = ctx.serverHandler.playerEntity // We interact with the world, hence schedule our action player.serverWorld.addScheduledTask { val tile = player.world.getTileEntity(msg.pos) if (tile is Replicator) { tile.mode = msg.mode } } return null } } }
mit
b31c266dbeba709fe4262d5ce9e4681a
34.302326
84
0.640738
4.625
false
false
false
false
yatatsu/conference-app-2017
app/src/test/java/io/github/droidkaigi/confsched2017/repository/sessions/SessionsRepositoryTest.kt
1
9443
package io.github.droidkaigi.confsched2017.repository.sessions import com.sys1yagi.kmockito.invoked import com.sys1yagi.kmockito.mock import com.sys1yagi.kmockito.verify import io.github.droidkaigi.confsched2017.api.DroidKaigiClient import io.github.droidkaigi.confsched2017.model.OrmaDatabase import io.github.droidkaigi.confsched2017.model.Session import io.github.droidkaigi.confsched2017.util.LocaleUtil import io.reactivex.Completable import io.reactivex.Single import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito.* import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import java.util.Date @RunWith(RobolectricTestRunner::class) class SessionsRepositoryTest { @Test fun hasCacheSessions() { // false. cache is null. run { val repository = SessionsRepository( SessionsLocalDataSource(mock()), SessionsRemoteDataSource(mock()) ) assertThat(repository.hasCacheSessions()).isFalse() } // false. repository has any cached session, but repository is dirty. run { val repository = SessionsRepository( SessionsLocalDataSource(mock()), SessionsRemoteDataSource(mock()) ) repository.cachedSessions = mapOf(0 to Session()) repository.setIdDirty(true) assertThat(repository.hasCacheSessions()).isFalse() } // true. run { val repository = SessionsRepository( SessionsLocalDataSource(mock()), SessionsRemoteDataSource(mock()) ) repository.cachedSessions = mapOf(0 to Session()) repository.setIdDirty(false) assertThat(repository.hasCacheSessions()).isTrue() } } @Test fun findAllRemoteRequestAndLocalCache() { val sessions = listOf(Session()) val client = mockDroidKaigiClient(sessions) val ormaDatabase = mock<OrmaDatabase>().apply { transactionAsCompletable(any()).invoked.thenReturn(Completable.complete()) } val cachedSessions: Map<Int, Session> = spy(mutableMapOf()) val repository = SessionsRepository( SessionsLocalDataSource(ormaDatabase), SessionsRemoteDataSource(client) ).apply { this.cachedSessions = cachedSessions } // TODO I want to use enum for language id. repository.findAll(LocaleUtil.LANG_JA) .test() .run { assertNoErrors() assertResult(sessions) assertComplete() client.verify().getSessions(eq(LocaleUtil.LANG_JA)) ormaDatabase.verify().transactionAsCompletable(any()) cachedSessions.verify(never()).values } repository.findAll(LocaleUtil.LANG_JA) .test() .run { assertNoErrors() assertThat(values().first().size).isEqualTo(1) assertComplete() cachedSessions.verify().values } } @Test fun findAllLocalCache() { val sessions = listOf(Session()) val client = mockDroidKaigiClient(sessions) val ormaDatabase = OrmaDatabase .builder(RuntimeEnvironment.application) .name(null) .build() val cachedSessions: Map<Int, Session> = mock() val repository = SessionsRepository( SessionsLocalDataSource(ormaDatabase), SessionsRemoteDataSource(client) ).apply { this.cachedSessions = cachedSessions } repository.findAll(LocaleUtil.LANG_JA) .test() .run { assertNoErrors() assertResult(sessions) assertComplete() client.verify().getSessions(eq(LocaleUtil.LANG_JA)) cachedSessions.verify(never()).values } repository.setIdDirty(true) repository.findAll(LocaleUtil.LANG_JA) .test() .run { assertNoErrors() assertThat(values().first().size).isEqualTo(1) assertComplete() cachedSessions.verify(never()).values } } @Test fun hasCacheSession() { // false cachedSessions is null run { val repository = SessionsRepository( SessionsLocalDataSource(mock()), SessionsRemoteDataSource(mock()) ) assertThat(repository.hasCacheSession(0)).isFalse() } // false sessionId not found run { val repository = SessionsRepository( SessionsLocalDataSource(mock()), SessionsRemoteDataSource(mock()) ) repository.cachedSessions = mapOf(1 to Session()) repository.setIdDirty(false) assertThat(repository.hasCacheSession(0)).isFalse() } // false dirty run { val repository = SessionsRepository( SessionsLocalDataSource(mock()), SessionsRemoteDataSource(mock()) ) repository.cachedSessions = mapOf(1 to Session()) repository.setIdDirty(true) assertThat(repository.hasCacheSession(1)).isFalse() } // true run { val repository = SessionsRepository( SessionsLocalDataSource(mock()), SessionsRemoteDataSource(mock()) ) repository.cachedSessions = mapOf(1 to Session()) repository.setIdDirty(false) assertThat(repository.hasCacheSession(1)).isTrue() } } @Test fun findRemoteRequestSuccess() { val sessions = listOf(createSession(2), createSession(3)) val client = mockDroidKaigiClient(sessions) val repository = SessionsRepository( SessionsLocalDataSource(mock()), SessionsRemoteDataSource(client) ) repository.find(3, LocaleUtil.LANG_JA) .test() .run { assertNoErrors() assertThat(values().first().id).isEqualTo(3) assertComplete() } } @Test fun findRemoteRequestNotFound() { val sessions = listOf(createSession(1), createSession(2)) val client = mockDroidKaigiClient(sessions) val repository = SessionsRepository( SessionsLocalDataSource(mock()), SessionsRemoteDataSource(client) ) repository.find(3, LocaleUtil.LANG_JA) .test() .run { assertNoErrors() assertNoValues() assertComplete() } } @Test fun findHasSessions() { val cachedSessions: Map<Int, Session> = spy(mutableMapOf(1 to createSession(1))) val repository = SessionsRepository( SessionsLocalDataSource(mock()), SessionsRemoteDataSource(mock()) ).apply { this.cachedSessions = cachedSessions } repository.setIdDirty(false) repository.find(1, LocaleUtil.LANG_JA) .test() .run { assertNoErrors() assertThat(values().first().id).isEqualTo(1) assertComplete() cachedSessions.verify().get(eq(1)) } } @Test fun findLocalStorage() { val ormaDatabase = OrmaDatabase .builder(RuntimeEnvironment.application) .name(null) .build() ormaDatabase .insertIntoSession(createSession(12).apply { title = "awesome session" stime = Date() etime = Date() durationMin = 30 type = "android" }) val cachedSessions: Map<Int, Session> = mock() val client: DroidKaigiClient = mock() val repository = SessionsRepository( SessionsLocalDataSource(ormaDatabase), SessionsRemoteDataSource(client) ) repository.cachedSessions = cachedSessions repository.setIdDirty(false) repository.find(12, LocaleUtil.LANG_JA) .test() .run { assertNoErrors() assertThat(values().first().id).isEqualTo(12) assertComplete() cachedSessions.verify(never()).get(eq(12)) client.verify(never()).getSessions(anyString()) } } fun createSession(sessionId: Int) = Session().apply { id = sessionId } fun mockDroidKaigiClient(sessions: List<Session>) = mock<DroidKaigiClient>().apply { getSessions(anyString()).invoked.thenReturn( Single.just(sessions) ) } }
apache-2.0
c50326454a4f197a9a95e9ca4c4cf786
31.228669
88
0.550567
6.006997
false
true
false
false
JustinMullin/drifter-kotlin
src/main/kotlin/xyz/jmullin/drifter/memory/Memory.kt
1
1587
package xyz.jmullin.drifter.memory import com.badlogic.gdx.Gdx import xyz.jmullin.drifter.extensions.drifter import xyz.jmullin.drifter.memory.Memory.prefs object Memory { val prefs by lazy { Gdx.app.getPreferences(drifter().name)!! } } fun getString(key: String, default: String? = null): String { return if(default == null) prefs.getString(key) else prefs.getString(key, default) } fun getInt(key: String, default: Int? = null): Int { return if(default == null) prefs.getInteger(key) else prefs.getInteger(key, default) } fun getFloat(key: String, default: Float? = null): Float { return if(default == null) prefs.getFloat(key) else prefs.getFloat(key, default) } fun getLong(key: String, default: Long? = null): Long { return if(default == null) prefs.getLong(key) else prefs.getLong(key, default) } fun getBoolean(key: String, default: Boolean? = null): Boolean { return if(default == null) prefs.getBoolean(key) else prefs.getBoolean(key, default) } fun forget(key: String) { prefs.remove(key) prefs.flush() } fun clearMemory() { prefs.clear() prefs.flush() } fun putString(key: String, value: String) { prefs.putString(key, value) prefs.flush() } fun putInt(key: String, value: Int) { prefs.putInteger(key, value) prefs.flush() } fun putFloat(key: String, value: Float) { prefs.putFloat(key, value) prefs.flush() } fun putLong(key: String, value: Long) { prefs.putLong(key, value) prefs.flush() } fun putBoolean(key: String, value: Boolean) { prefs.putBoolean(key, value) prefs.flush() }
mit
44b12a65c4fa9d8a290044b32fa61149
23.8125
88
0.691871
3.348101
false
false
false
false
signed/intellij-community
java/java-tests/testSrc/com/intellij/codeInsight/navigation/JavaReflectionClassNavigationTest.kt
1
3803
/* * 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 com.intellij.codeInsight.navigation import com.intellij.psi.PsiClass import com.intellij.testFramework.LightProjectDescriptor import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase /** * @author Pavel.Dolgov */ class JavaReflectionClassNavigationTest : LightCodeInsightFixtureTestCase() { override fun getProjectDescriptor(): LightProjectDescriptor = if (getTestName(false).contains("Java9")) JAVA_9 else super.getProjectDescriptor() fun testPublicClass() { myFixture.addClass("package foo.bar; public class PublicClass {}") doTest("foo.bar.PublicClass") } fun testPublicInnerClass() { myFixture.addClass("package foo.bar; public class PublicClass { public class PublicInnerClass {} }") doTest("foo.bar.PublicClass.PublicInnerClass") } fun testPublicInnerClass2() { myFixture.addClass("package foo.bar; public class PublicClass { public class PublicInnerClass {} }") doTest("foo.bar.<caret>PublicClass.PublicInnerClass") } fun testPackageLocalClass() { myFixture.addClass("package foo.bar; class PackageLocalClass {}") doTest("foo.bar.PackageLocalClass") } fun testPrivateInnerClass() { myFixture.addClass("package foo.bar; public class PublicClass { private class PrivateInnerClass {} }") doTest("foo.bar.PublicClass.PrivateInnerClass") } fun testPrivateInnerClass2() { myFixture.addClass("package foo.bar; public class PublicClass { private class PrivateInnerClass {} }") doTest("foo.bar.<caret>PublicClass.PrivateInnerClass") } fun testWithClassLoader() { myFixture.addClass("package foo.bar; public class PublicClass {}") doTest("foo.bar.<caret>PublicClass.PrivateInnerClass", { "Thread.currentThread().getContextClassLoader().loadClass(\"$it\")" }) } fun testJava9MethodHandlesLookup() { myFixture.addClass("package foo.bar; public class PublicClass {}") doTest("foo.bar.PublicClass", { "java.lang.invoke.MethodHandles.lookup().findClass(\"$it\")" }) } private fun doTest(className: String, usageFormatter: (String) -> String = { "Class.forName(\"$it\")" }) { val caretPos = className.indexOf("<caret>") val atCaret: String var expectedName = className if (caretPos >= 0) { atCaret = className val dotPos = className.indexOf(".", caretPos + 1) if (dotPos >= 0) expectedName = className.substring(0, dotPos).replace("<caret>", "") } else { atCaret = className + "<caret>" } myFixture.configureByText("Main.java", """import foo.bar.*; class Main { void foo() throws ReflectiveOperationException { ${usageFormatter(atCaret)}; } }""") val reference = myFixture.file.findReferenceAt(myFixture.caretOffset) assertNotNull("No reference at the caret", reference) val resolved = reference!!.resolve() assertTrue("Class not resolved: " + reference.canonicalText, resolved is PsiClass) val psiClass = resolved as? PsiClass assertEquals("Class name", expectedName, psiClass?.qualifiedName) } }
apache-2.0
c97a564cae4688751c9dce7c29553a44
39.031579
131
0.68893
4.863171
false
true
false
false
gatheringhallstudios/MHGenDatabase
app/src/main/java/com/ghstudios/android/features/armor/detail/ArmorSetDetailPagerActivity.kt
1
1855
package com.ghstudios.android.features.armor.detail import androidx.lifecycle.ViewModelProvider import com.ghstudios.android.AssetLoader import com.ghstudios.android.BasePagerActivity import com.ghstudios.android.MenuSection import com.ghstudios.android.mhgendatabase.R class ArmorSetDetailPagerActivity : BasePagerActivity() { companion object { const val EXTRA_ARMOR_ID = "com.daviancorp.android.android.ui.detail.armor_id" const val EXTRA_FAMILY_ID = "com.daviancorp.android.android.ui.detail.family_id" } private val viewModel by lazy { ViewModelProvider(this).get(ArmorSetDetailViewModel::class.java) } override fun getSelectedSection() = MenuSection.ARMOR override fun onAddTabs(tabs: TabAdder) { this.hideTabsIfSingular() this.setTabBehavior(BasePagerActivity.TabBehavior.FIXED) val armorId = intent.getLongExtra(EXTRA_ARMOR_ID, -1) val familyId = intent.getLongExtra(EXTRA_FAMILY_ID, -1) val metadata = when (familyId > -1) { true -> viewModel.initByFamily(familyId) false -> viewModel.initByArmor(armorId) } title = metadata.first().familyName val hasSummaryTab = metadata.size > 1 if (hasSummaryTab) { tabs.addTab(R.string.armor_title_set) { ArmorSetSummaryFragment() } } for ((idx, armorData) in metadata.withIndex()) { val icon = AssetLoader.loadIconFor(armorData) tabs.addTab("", icon) { ArmorDetailFragment.newInstance(armorData.id) } // If this is the armor we came here for, set it as the default tab if (armorData.id == armorId) { val preTabCount = if (hasSummaryTab) 1 else 0 tabs.setDefaultItem(idx + preTabCount) } } } }
mit
5fc144acb4b3ec5bee751c2fd79e1365
34.018868
88
0.657682
4.215909
false
false
false
false
r-artworks/game-seed
core/src/com/rartworks/engine/apis/LeaderboardServices.kt
1
352
package com.rartworks.engine.apis interface LeaderboardServices { fun getScore(leaderboardId: String? = null, callback: (Int) -> (Unit)) fun getScores(leaderboardId: String? = null, limit: Int = 5, callback: (List<PlayerScore>) -> (Unit)) fun showScores(leaderboardId: String? = null) fun submitScore(score: Long, leaderboardId: String? = null) }
mit
531a17cbb3f4326148858750a49c7e53
43
102
0.735795
3.384615
false
false
false
false
collinx/susi_android
app/src/main/java/org/fossasia/susi/ai/login/LoginActivity.kt
2
6101
package org.fossasia.susi.ai.login import android.app.ProgressDialog import android.content.Intent import android.graphics.Color import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.view.inputmethod.EditorInfo import android.widget.ArrayAdapter import android.widget.Toast import kotlinx.android.synthetic.main.activity_login.* import org.fossasia.susi.ai.R import org.fossasia.susi.ai.signup.SignUpActivity import org.fossasia.susi.ai.chat.ChatActivity import org.fossasia.susi.ai.forgotpassword.ForgotPasswordActivity import org.fossasia.susi.ai.helper.AlertboxHelper import org.fossasia.susi.ai.helper.Constant import org.fossasia.susi.ai.login.contract.ILoginPresenter import org.fossasia.susi.ai.login.contract.ILoginView /** * <h1>The Login activity.</h1> * <h2>This activity is used to login into the app.</h2> * * Created by chiragw15 on 4/7/17. */ class LoginActivity : AppCompatActivity(), ILoginView { lateinit var loginPresenter: ILoginPresenter lateinit var progressDialog: ProgressDialog override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) if (savedInstanceState != null) { email.editText?.setText(savedInstanceState.getCharSequenceArray(Constant.SAVED_STATES)[0].toString()) password.editText?.setText(savedInstanceState.getCharSequenceArray(Constant.SAVED_STATES)[1].toString()) if (savedInstanceState.getBoolean(Constant.SERVER)) { input_url.visibility = View.VISIBLE } else { input_url.visibility = View.GONE } } progressDialog = ProgressDialog(this) progressDialog.setCancelable(false) progressDialog.setMessage(getString(R.string.login)) addListeners() loginPresenter = LoginPresenter(this) loginPresenter.onAttach(this) } override fun onLoginSuccess(message: String?) { Toast.makeText(this@LoginActivity, message, Toast.LENGTH_SHORT).show() val intent = Intent(this@LoginActivity, ChatActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK intent.putExtra(Constant.FIRST_TIME, true) startActivity(intent) finish() } override fun skipLogin() { val intent = Intent(this@LoginActivity, ChatActivity::class.java) intent.putExtra(Constant.FIRST_TIME, false) startActivity(intent) finish() } override fun invalidCredentials(isEmpty: Boolean, what: String) { if(isEmpty) { when(what) { Constant.EMAIL -> email.error = getString(R.string.email_cannot_be_empty) Constant.PASSWORD -> password.error = getString(R.string.password_cannot_be_empty) Constant.INPUT_URL -> input_url.error = getString(R.string.url_cannot_be_empty) } } else { when(what) { Constant.EMAIL -> email.error = getString(R.string.email_invalid_title) Constant.INPUT_URL -> input_url.error = getString(R.string.invalid_url) } } log_in.isEnabled = true } override fun showProgress(boolean: Boolean) { if (boolean) progressDialog.show() else progressDialog.dismiss() } override fun onLoginError(title: String?, message: String?) { val notSuccessAlertboxHelper = AlertboxHelper(this@LoginActivity, title, message, null, null, getString(R.string.ok), null, Color.BLUE) notSuccessAlertboxHelper.showAlertBox() log_in.isEnabled = true } override fun attachEmails(savedEmails: MutableSet<String>?) { if (savedEmails != null) email_input.setAdapter(ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ArrayList<String>(savedEmails))) } fun addListeners() { showURL() signUp() forgotPassword() skip() logIn() cancelLogin() onEditorAction() } fun showURL() { customer_server.setOnClickListener { input_url.visibility = if(customer_server.isChecked) View.VISIBLE else View.GONE} } fun signUp() { sign_up.setOnClickListener { startActivity(Intent(this@LoginActivity, SignUpActivity::class.java)) } } fun forgotPassword() { forgot_password.setOnClickListener { startActivity(Intent(this@LoginActivity, ForgotPasswordActivity::class.java)) } } fun skip() { skip.setOnClickListener { loginPresenter.skipLogin() } } fun logIn() { log_in.setOnClickListener { startLogin() } } fun startLogin() { val stringEmail = email.editText?.text.toString() val stringPassword = password.editText?.text.toString() val stringURL = input_url.editText?.text.toString() log_in.isEnabled = false email.error = null password.error = null input_url.error = null loginPresenter.login(stringEmail, stringPassword, !customer_server.isChecked, stringURL) } fun cancelLogin() { progressDialog.setOnCancelListener({ loginPresenter.cancelLogin() log_in.isEnabled = true }) } fun onEditorAction(){ password_input.setOnEditorActionListener { _, actionId, _ -> var handled = false if (actionId == EditorInfo.IME_ACTION_GO) { startLogin() handled = true } handled } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) val values = arrayOf<CharSequence>(email.editText?.text.toString(), password.editText?.text.toString()) outState.putCharSequenceArray(Constant.SAVED_STATES, values) outState.putBoolean(Constant.SERVER, customer_server.isChecked) } override fun onDestroy() { loginPresenter.onDetach() super.onDestroy() } }
apache-2.0
8f7fa6bbc1886edc94373278f50c1cb2
33.468927
143
0.663662
4.512574
false
false
false
false
Ph1b/MaterialAudiobookPlayer
data/src/main/kotlin/de/ph1b/audiobook/data/repo/BookmarkRepo.kt
1
1948
package de.ph1b.audiobook.data.repo import de.ph1b.audiobook.data.Book2 import de.ph1b.audiobook.data.BookContent2 import de.ph1b.audiobook.data.Bookmark2 import de.ph1b.audiobook.data.repo.internals.AppDb import de.ph1b.audiobook.data.repo.internals.dao.BookmarkDao2 import de.ph1b.audiobook.data.repo.internals.transaction import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import timber.log.Timber import java.time.Instant import java.time.temporal.ChronoUnit import javax.inject.Inject import javax.inject.Singleton /** * Provides access to bookmarks. */ @Singleton class BookmarkRepo @Inject constructor( private val dao: BookmarkDao2, private val appDb: AppDb ) { suspend fun deleteBookmark(id: Bookmark2.Id) { dao.deleteBookmark(id) } suspend fun addBookmark(bookmark: Bookmark2) { dao.addBookmark(bookmark) } suspend fun addBookmarkAtBookPosition(book: Book2, title: String?, setBySleepTimer: Boolean): Bookmark2 { return withContext(Dispatchers.IO) { val bookMark = Bookmark2( title = title, time = book.content.positionInChapter, id = Bookmark2.Id.random(), addedAt = Instant.now().minus(2, ChronoUnit.DAYS), setBySleepTimer = setBySleepTimer, chapterId = book.content.currentChapter, bookId = book.id ) addBookmark(bookMark) Timber.v("Added bookmark=$bookMark") bookMark } } suspend fun bookmarks(book: BookContent2): List<Bookmark2> { val chapters = book.chapters // we can only query SQLITE_MAX_VARIABLE_NUMBER at once (999 bugs on some devices so we use a number a little smaller.) // if it's larger than the limit, we query in chunks. val limit = 990 return if (chapters.size > limit) { appDb.transaction { chapters.chunked(limit).flatMap { dao.allForFiles(it) } } } else { dao.allForFiles(chapters) } } }
lgpl-3.0
997598a8b9b167d84d0f39de805c3b86
28.074627
123
0.709446
3.789883
false
false
false
false
7hens/KDroid
core/src/main/java/cn/thens/kdroid/core/app/res/Resources.kt
1
1484
@file:Suppress("unused") package cn.thens.kdroid.core.app.res import android.content.Context import android.content.res.ColorStateList import android.graphics.drawable.Drawable import androidx.annotation.* import androidx.core.content.ContextCompat import android.util.DisplayMetrics import android.view.View fun Context.colorOf(@ColorRes resId: Int): Int = ContextCompat.getColor(this, resId) fun Context.colorStateListOf(@ColorRes resId: Int): ColorStateList? = ContextCompat.getColorStateList(this, resId) fun Context.drawableOf(@DrawableRes resId: Int): Drawable? = ContextCompat.getDrawable(this, resId) fun Context.stringOf(@StringRes resId: Int): String = getString(resId) fun Context.dimenOf(@DimenRes resId: Int): Int = resources.getDimensionPixelSize(resId) fun Context.integerOf(@IntegerRes resId: Int): Int = resources.getInteger(resId) inline val Context.displayMetrics: DisplayMetrics get() = resources.displayMetrics fun View.colorOf(@ColorRes resId: Int): Int = context.colorOf(resId) fun View.colorStateListOf(@ColorRes resId: Int): ColorStateList? = context.colorStateListOf(resId) fun View.drawableOf(@DrawableRes resId: Int): Drawable? = context.drawableOf(resId) fun View.stringOf(@StringRes resId: Int): String = context.stringOf(resId) fun View.dimenOf(@DimenRes resId: Int): Int = context.dimenOf(resId) fun View.integerOf(@IntegerRes resId: Int): Int = context.integerOf(resId) inline val View.displayMetrics: DisplayMetrics get() = context.displayMetrics
apache-2.0
09cf3668b4b4e2e36262d989fff6dc0c
54
114
0.80593
4.156863
false
false
false
false
siosio/DomaSupport
src/main/java/siosio/doma/inspection/dao/DaoInspectionTool.kt
1
2529
package siosio.doma.inspection.dao import com.intellij.codeHighlighting.* import com.intellij.codeInspection.* import com.intellij.psi.* import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtVisitorVoid import org.jetbrains.kotlin.psi.psiUtil.containingClass import siosio.doma.* import siosio.doma.psi.* /** * DomaのDAOのチェックを行うクラス。 */ class DaoInspectionTool : AbstractBaseJavaLocalInspectionTool() { override fun getDisplayName(): String = DomaBundle.message("inspection.dao-inspection") override fun isEnabledByDefault(): Boolean = true override fun getDefaultLevel(): HighlightDisplayLevel = HighlightDisplayLevel.ERROR override fun getGroupDisplayName(): String = "Doma" override fun getShortName(): String = "DaoInspection" override fun buildVisitor(problemsHolder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return object : JavaElementVisitor() { override fun visitMethod(method: PsiMethod) { super.visitMethod(method) val daoType = DaoType.valueOf(method) daoType?.let { val psiDaoMethod = PsiDaoMethod(method, it) val rule = psiDaoMethod.daoType.rule rule.inspect(problemsHolder, psiDaoMethod) } } } } } class KotlinDaoInspectionTool: AbstractKotlinInspection() { override fun getDisplayName(): String = DomaBundle.message("inspection.kotlin-dao-inspection") override fun isEnabledByDefault(): Boolean = true override fun getDefaultLevel(): HighlightDisplayLevel = HighlightDisplayLevel.ERROR override fun getGroupDisplayName(): String = "Doma" override fun getShortName(): String = "KotlinDaoInspection" override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { return object: KtVisitorVoid() { override fun visitNamedFunction(function: KtNamedFunction) { super.visitNamedFunction(function) if (function.containingClass() == null) { return } DaoType.valueOf(function)?.let { it.kotlinRule.inspect(holder, PsiDaoFunction(function, it)) } } } } }
mit
34ba35ae6f6c79e187d578d694af1cf4
32.824324
103
0.662405
5.489035
false
false
false
false
wordpress-mobile/WordPress-FluxC-Android
example/src/main/java/org/wordpress/android/fluxc/example/MainExampleActivity.kt
2
2048
package org.wordpress.android.fluxc.example import android.os.Bundle import android.text.method.ScrollingMovementMethod import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.FragmentManager.OnBackStackChangedListener import dagger.android.AndroidInjection import dagger.android.AndroidInjector import dagger.android.DispatchingAndroidInjector import dagger.android.HasAndroidInjector import kotlinx.android.synthetic.main.activity_example.* import javax.inject.Inject class MainExampleActivity : AppCompatActivity(), OnBackStackChangedListener, HasAndroidInjector { @Inject lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Any> override fun onCreate(savedInstanceState: Bundle?) { AndroidInjection.inject(this) super.onCreate(savedInstanceState) setContentView(R.layout.activity_example) setSupportActionBar(toolbar) supportFragmentManager.addOnBackStackChangedListener(this) if (savedInstanceState == null) { val mf = MainFragment() supportFragmentManager.beginTransaction().add(R.id.fragment_container, mf).commit() } log.movementMethod = ScrollingMovementMethod() prependToLog("I'll log stuff here.") updateBackArrow() } fun prependToLog(s: String) { val output = s + "\n" + log.text log.text = output } override fun androidInjector(): AndroidInjector<Any> = dispatchingAndroidInjector override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { onBackPressed() true } else -> super.onOptionsItemSelected(item) } } override fun onBackStackChanged() { updateBackArrow() } private fun updateBackArrow() { val showBackArrow = supportFragmentManager.backStackEntryCount > 0 supportActionBar?.setDisplayHomeAsUpEnabled(showBackArrow) } }
gpl-2.0
afc57a8edb10a66f197144e15a929664
32.032258
97
0.716309
5.535135
false
false
false
false
emufog/emufog
src/test/kotlin/emufog/fog/FogResultTest.kt
1
2933
/* * MIT License * * Copyright (c) 2019 emufog contributors * * 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 emufog.fog import io.mockk.mockk import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test internal class FogResultTest { @Test fun `initialize a new instance`() { val result = FogResult() assertFalse(result.status) assertEquals(0, result.placements.size) } @Test fun `set the status to true`() { val result = FogResult() assertFalse(result.status) result.setSuccess() assertTrue(result.status) } @Test fun `set the status to false`() { val result = FogResult() assertFalse(result.status) result.setFailure() assertFalse(result.status) result.setSuccess() assertTrue(result.status) result.setFailure() assertFalse(result.status) } @Test fun `addPlacement should increase list by one`() { val result = FogResult() assertEquals(0, result.placements.size) val placement: FogNodePlacement = mockk() result.addPlacement(placement) assertEquals(1, result.placements.size) assertEquals(placement, result.placements[0]) } @Test fun `addPlacements should increase list by all elements of the collection`() { val result = FogResult() assertEquals(0, result.placements.size) val placement1: FogNodePlacement = mockk() val placement2: FogNodePlacement = mockk() result.addPlacements(listOf(placement1, placement2)) assertEquals(2, result.placements.size) assertTrue(result.placements.contains(placement1)) assertTrue(result.placements.contains(placement2)) } }
mit
3873fddf2357ed431ede5788ad0a55d8
33.116279
82
0.700989
4.554348
false
true
false
false
vase4kin/TeamCityApp
app/src/androidTest/java/com/github/vase4kin/teamcityapp/buildlog/view/BuildLogFragmentTest.kt
1
5267
/* * Copyright 2019 Andrey Tolpeev * * 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.vase4kin.teamcityapp.buildlog.view import android.content.Intent import android.os.Bundle import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.scrollTo import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.espresso.web.assertion.WebViewAssertions.webMatches import androidx.test.espresso.web.sugar.Web.onWebView import androidx.test.espresso.web.webdriver.DriverAtoms.findElement import androidx.test.espresso.web.webdriver.DriverAtoms.getText import androidx.test.espresso.web.webdriver.Locator import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import com.github.vase4kin.teamcityapp.TeamCityApplication import com.github.vase4kin.teamcityapp.api.TeamCityService import com.github.vase4kin.teamcityapp.base.extractor.BundleExtractorValues import com.github.vase4kin.teamcityapp.build_details.view.BuildDetailsActivity import com.github.vase4kin.teamcityapp.dagger.components.AppComponent import com.github.vase4kin.teamcityapp.dagger.components.RestApiComponent import com.github.vase4kin.teamcityapp.dagger.modules.AppModule import com.github.vase4kin.teamcityapp.dagger.modules.FakeTeamCityServiceImpl import com.github.vase4kin.teamcityapp.dagger.modules.Mocks import com.github.vase4kin.teamcityapp.dagger.modules.RestApiModule import com.github.vase4kin.teamcityapp.helper.CustomIntentsTestRule import com.github.vase4kin.teamcityapp.helper.TestUtils import io.reactivex.Single import it.cosenonjaviste.daggermock.DaggerMockRule import org.hamcrest.Matchers.containsString import org.junit.BeforeClass import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.Matchers.anyString import org.mockito.Mockito.`when` import org.mockito.Spy /** * Tests for [BuildLogFragment] */ @RunWith(AndroidJUnit4::class) class BuildLogFragmentTest { @JvmField @Rule val restComponentDaggerRule: DaggerMockRule<RestApiComponent> = DaggerMockRule(RestApiComponent::class.java, RestApiModule(Mocks.URL)) .addComponentDependency( AppComponent::class.java, AppModule(InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as TeamCityApplication) ) .set { restApiComponent -> val app = InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as TeamCityApplication app.setRestApiInjector(restApiComponent) } @JvmField @Rule val activityRule: CustomIntentsTestRule<BuildDetailsActivity> = CustomIntentsTestRule(BuildDetailsActivity::class.java) @Spy private val teamCityService: TeamCityService = FakeTeamCityServiceImpl() @Spy private val build = Mocks.successBuild() companion object { @JvmStatic @BeforeClass fun disableOnboarding() { TestUtils.disableOnboarding() val storage = (InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as TeamCityApplication).appInjector.sharedUserStorage() storage.clearAll() storage.saveGuestUserAccountAndSetItAsActive(Mocks.URL, false) } } @Test fun testUserCanSeeBuildLog() { // Prepare mocks `when`(teamCityService.build(anyString())).thenReturn(Single.just(build)) // Prepare intent // <! ---------------------------------------------------------------------- !> // Passing build object to activity, had to create it for real, Can't pass mock object as serializable in bundle :( // <! ---------------------------------------------------------------------- !> val intent = Intent() val b = Bundle() b.putSerializable(BundleExtractorValues.BUILD, Mocks.successBuild()) b.putString(BundleExtractorValues.NAME, "name") intent.putExtras(b) // Start activity activityRule.launchActivity(intent) // Checking build log tab title onView(withText("Build Log")) .perform(scrollTo()) .check(matches(isDisplayed())) .perform(click()) // Check web view content onWebView() .withElement(findElement(Locator.ID, "build_log")) .check(webMatches(getText(), containsString("Hello, this is fake build log!"))) } }
apache-2.0
518030b1605640344af4c3509778de21
39.829457
150
0.724131
4.881372
false
true
false
false
wuan/rest-demo-jersey-kotlin
src/main/java/com/tngtech/demo/weather/domain/measurement/AtmosphericData.kt
1
835
package com.tngtech.demo.weather.domain.measurement data class AtmosphericData( /** * temperature in degrees celsius */ val temperature: DataPoint? = null, /** * wind speed in km/h */ val wind: DataPoint? = null, /** * humidity in percent */ val humidity: DataPoint? = null, /** * precipitation in cm */ val precipitation: DataPoint? = null, /** * pressure in mmHg */ val pressure: DataPoint? = null, /** * cloud cover percent from 0 - 100 (integer) */ val cloudCover: DataPoint? = null, /** * the last time this data was updated, in milliseconds since UTC epoch */ val lastUpdateTime: Long = 0)
apache-2.0
d49bc253ef10aa82b3deeea33a3421cc
25.935484
79
0.500599
4.911765
false
false
false
false
komu/siilinkari
src/main/kotlin/siilinkari/vm/Evaluator.kt
1
7855
package siilinkari.vm import siilinkari.ast.FunctionDefinition import siilinkari.env.GlobalStaticEnvironment import siilinkari.lexer.LookaheadLexer import siilinkari.lexer.Token.Keyword import siilinkari.objects.Value import siilinkari.optimizer.optimize import siilinkari.parser.parseExpression import siilinkari.parser.parseFunctionDefinition import siilinkari.parser.parseFunctionDefinitions import siilinkari.translator.FunctionTranslator import siilinkari.translator.translateToCode import siilinkari.translator.translateToIR import siilinkari.types.Type import siilinkari.types.TypedExpression import siilinkari.types.typeCheck import siilinkari.vm.OpCode.* import siilinkari.vm.OpCode.Binary.* /** * Evaluator for opcodes. * * @see OpCode */ class Evaluator { private val globalData = DataSegment() private val globalTypeEnvironment = GlobalStaticEnvironment() private var globalCode = CodeSegment() private val functionTranslator = FunctionTranslator(globalTypeEnvironment) var trace = false var optimize = true /** * Binds a global name to given value. */ fun bind(name: String, value: Value, mutable: Boolean = true) { val binding = globalTypeEnvironment.bind(name, value.type, mutable) globalData[binding.index] = value } /** * Evaluates code which can either be a definition, statement or expression. * If the code represented an expression, returns its value. Otherwise [Value.Unit] is returned. */ fun evaluate(code: String): EvaluationResult { if (LookaheadLexer(code).nextTokenIs(Keyword.Fun)) { val definition = parseFunctionDefinition(code) bindFunction(definition) return EvaluationResult(Value.Unit, Type.Unit) } else { val (segment, type) = translate(code) return EvaluationResult(evaluateSegment(segment), type) } } /** * Loads contents of given file. */ fun loadResource(file: String) { val source = javaClass.classLoader.getResource(file).openStream().use { it.reader().readText() } val defs = parseFunctionDefinitions(source, file) for (def in defs) bindFunction(def) } /** * Returns the names of all global bindings. */ fun bindingsNames(): Set<String> = globalTypeEnvironment.bindingNames() /** * Translates given code to opcodes and returns string representation of the opcodes. */ fun dump(code: String): String { val exp = parseAndTypeCheck(code) if (exp is TypedExpression.Ref && exp.type is Type.Function) { val value = globalData[exp.binding.index] as Value.Function return when (value) { is Value.Function.Compound -> globalCode.getRegion(value.address, value.codeSize).toString() is Value.Function.Native -> "native function $value" } } else { return translate(exp).toString() } } /** * Compiles and binds a global function. */ private fun bindFunction(func: FunctionDefinition) { // We have to create the binding into global environment before calling createFunction // because the function might want to call itself recursively. But if createFunction fails // (most probably to type-checking), we need to unbind the binding. var binding = func.returnType?.let { returnType -> globalTypeEnvironment.bind(func.name, Type.Function(func.args.map { it.second }, returnType), mutable = false) } try { val (signature, code) = functionTranslator.translateFunction(func, optimize) val (newGlobalCode, address) = globalCode.mergeWithRelocatedSegment(code) globalCode = newGlobalCode if (binding == null) binding = globalTypeEnvironment.bind(func.name, signature, mutable = false) globalData[binding.index] = Value.Function.Compound(func.name, signature, address, code.size) } catch (e: Exception) { if (binding != null) globalTypeEnvironment.unbind(func.name) throw e } } /** * Translates code to opcodes. */ private fun translate(code: String): Pair<CodeSegment, Type> { val exp = parseAndTypeCheck(code) return Pair(translate(exp), exp.type) } private fun translate(exp: TypedExpression): CodeSegment { val optExp = if (optimize) exp.optimize() else exp val blocks = optExp.translateToIR() if (optimize) blocks.optimize() return blocks.translateToCode(0) } private fun parseAndTypeCheck(code: String) = parseExpression(code).typeCheck(globalTypeEnvironment) /** * Evaluates given code segment. */ private fun evaluateSegment(segment: CodeSegment): Value { val (code, startAddress) = globalCode.mergeWithRelocatedSegment(segment) val quitPointer = Value.Pointer.Code(-1) val state = ThreadState() state.pc = startAddress state.fp = 0 state[0] = quitPointer evalLoop@while (true) { val op = code[state.pc] if (trace) println("${state.pc.toString().padStart(4)}: ${op.toString().padEnd(40)} [fp=${state.fp}]") state.pc++ when (op) { is Not -> state[op.target] = !(state[op.source] as Value.Bool) is Add -> state.evalBinary(op) { l, r -> l + r } is Subtract -> state.evalBinary(op) { l, r -> l - r } is Multiply -> state.evalBinary(op) { l, r -> l * r } is Divide -> state.evalBinary(op) { l, r -> l / r } is Equal -> state.evalBinaryBool(op) { l, r -> l == r } is LessThan -> state.evalBinaryBool(op) { l, r -> l.lessThan(r) } is LessThanOrEqual -> state.evalBinaryBool(op) { l, r -> l == r || l.lessThan(r) } is ConcatString -> state.evalBinary(op) { l, r-> l + r } is LoadConstant -> state[op.target] = op.value is Copy -> state[op.target] = state[op.source] is LoadGlobal -> state[op.target] = globalData[op.sourceGlobal] is StoreGlobal -> globalData[op.targetGlobal] = state[op.source] is Jump -> state.pc = op.address is JumpIfFalse -> if (!(state[op.sp] as Value.Bool).value) state.pc = op.address is Call -> evalCall(op, state) is RestoreFrame -> state.fp -= op.sp is Ret -> { val returnAddress = state[op.returnAddressPointer] state[0] = state[op.valuePointer] if (returnAddress == quitPointer) break@evalLoop state.pc = (returnAddress as Value.Pointer.Code).value } Nop -> {} else -> error("unknown opcode: $op") } } return state[0] } private fun evalCall(op: Call, state: ThreadState) { val func = state[op.offset] as Value.Function state.fp += op.offset - op.argumentCount when (func) { is Value.Function.Compound -> { state[op.argumentCount] = Value.Pointer.Code(state.pc) state.pc = func.address } is Value.Function.Native -> { val args = state.getArgs(func.argumentCount) state[0] = func(args) } } } }
mit
227f64527d429a3d770b5382a9b45d6f
36.764423
122
0.589943
4.561556
false
false
false
false
Sefford/kor
modules/kor-usecases/src/main/kotlin/com/sefford/kor/usecases/UseCase.kt
1
5089
/* * Copyright (C) 2018 Saúl Díaz * * 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.sefford.kor.usecases import arrow.core.* import com.sefford.kor.usecases.components.* /** * Use case implementation. * * As stated in the documentation, it passes through three stages * <ul> * <li>Execution</li> * <li>Postprocessing</li> * <li>Persistance</li> * </ul> * * By default the postprocessing and persistance stages are optional and * are defaulted to an identity lambda. * * @author Saul Diaz <[email protected]> */ class UseCase<E : Error, R : Response> /** * Creates a new use case. * @param logic Lambda that outputs a {@link Response Response} * @param postProcessor Lambda that processes the response from the logic phase and returns it. * * Note that it can be passed back or create a new one. By default it is an identity lambda. * @param cachePersistance Lambda that caches the response from the postprocessing phase and returns it. * * Note that it can be passed back or create a new one. This is the final result that will be returned by the use case. * * By default it is an identity lambda. */ private constructor(internal val logic: () -> R, internal val postProcessor: (response: R) -> R = ::identity, internal val cachePersistance: (response: R) -> R = ::identity, internal val errorHandler: (ex: Throwable) -> E, internal val performance: PerformanceModule = NoModule) { /** * Execute the use case inmediately in the current thread. */ fun execute(): Either<E, R> { performance.start() return Try { cachePersistance(postProcessor(logic())) } .also { performance.end() } .map { response -> response.right() } .getOrElse { errorHandler(it).left() } } /** * Use case builder * * @author Saul Diaz <[email protected]> */ class Execute<E : Error, R : Response> /** * Initializes a new use case with the required logic. * * If no further piece is returned, postprocessor and persistance phases are an identity function and the * error handling is a default one to produce a basic error. * * @param logic Logic of the use case. */ (internal val logic: () -> R) { internal var postProcessor: (R) -> R = ::identity internal var cachePersistance: (R) -> R = ::identity internal var errorHandler: (Throwable) -> E = emptyErrorHandler() internal var performanceModule: PerformanceModule = NoModule /** * Sets up the logic for the post processing phase. * * The response returned by this piece of logic will be fed to the persistence phase, and does not matter * if the input is returned or a new response is created. * * @param postProcessor Logic that will be applied to the post processor phase */ fun process(postProcessor: (R) -> R): Execute<E, R> { this.postProcessor = postProcessor return this } /** * Sets up the logic for the persistence phase. * * The response returned by this piece of logic will be returned, and does not matter if the input is returned * or a new response is created. * * @param cachePersistance Logic that will be applied to the persistance phase. */ fun persist(cachePersistance: (R) -> R): Execute<E, R> { this.cachePersistance = cachePersistance return this } /** * Sets up a customized error handling. * * This will be returned in the case of any failure in any of execution, postprocessing or persistance stages. * * @param errorHandler Custom error handler. */ fun onError(errorHandler: (Throwable) -> E): Execute<E, R> { this.errorHandler = errorHandler return this; } /** * Sets up a performance module. * * @param module Performance module which will output the metric */ fun withIntrospection(module: PerformanceModule): Execute<E, R> { this.performanceModule = module return this; } /** * Builds a new use case as specified */ fun build(): UseCase<E, R> { return UseCase(logic, postProcessor, cachePersistance, errorHandler, performanceModule) } } }
apache-2.0
ada93466f38d80b0d6779c8834106cca
35.078014
119
0.62414
4.566427
false
false
false
false
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/main/java/com/garpr/android/data/models/PollFrequency.kt
1
1518
package com.garpr.android.data.models import android.os.Parcel import android.os.Parcelable import androidx.annotation.StringRes import com.garpr.android.R import com.garpr.android.extensions.createParcel import com.squareup.moshi.Json import java.util.concurrent.TimeUnit enum class PollFrequency constructor( @StringRes val textResId: Int, timeInMillis: Long ) : Parcelable { @Json(name = "every_8_hours") EVERY_8_HOURS(R.string.every_8_hours, TimeUnit.HOURS.toMillis(8)), @Json(name = "daily") DAILY(R.string.daily, TimeUnit.DAYS.toMillis(1)), @Json(name = "every_2_days") EVERY_2_DAYS(R.string.every_2_days, TimeUnit.DAYS.toMillis(2)), @Json(name = "every_3_days") EVERY_3_DAYS(R.string.every_3_days, TimeUnit.DAYS.toMillis(3)), @Json(name = "every_5_days") EVERY_5_DAYS(R.string.every_5_days, TimeUnit.DAYS.toMillis(5)), @Json(name = "weekly") WEEKLY(R.string.weekly, TimeUnit.DAYS.toMillis(7)), @Json(name = "every_10_days") EVERY_10_DAYS(R.string.every_10_days, TimeUnit.DAYS.toMillis(10)), @Json(name = "every_2_weeks") EVERY_2_WEEKS(R.string.every_2_weeks, TimeUnit.DAYS.toMillis(14)); val timeInSeconds: Long = TimeUnit.MILLISECONDS.toSeconds(timeInMillis) override fun describeContents(): Int = 0 override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeInt(ordinal) } companion object { @JvmField val CREATOR = createParcel { values()[it.readInt()] } } }
unlicense
76143db475a6f25a8622474a007d0b57
27.641509
75
0.687088
3.380846
false
false
false
false
travisobregon/kotlin-koans
src/v_builders/n36ExtensionFunctionLiterals.kt
6
549
package v_builders import util.TODO import util.doc36 fun todoTask36(): Nothing = TODO( """ Task 36. Read about extension function literals. You can declare `isEven` and `isOdd` as values, that can be called as extension functions. Complete the declarations below. """, documentation = doc36() ) fun task36(): List<Boolean> { val isEven: Int.() -> Boolean = { this % 2 == 0 } val isOdd: Int.() -> Boolean = { this % 2 != 0 } return listOf(42.isOdd(), 239.isOdd(), 294823098.isEven()) }
mit
b0c808459f0e43053f95cc3886758585
21.875
98
0.612022
3.921429
false
false
false
false
http4k/http4k
http4k-incubator/src/main/kotlin/org/http4k/routing/experimental/Resource.kt
1
3018
package org.http4k.routing.experimental import org.http4k.core.Body import org.http4k.core.ContentType import org.http4k.core.ContentType.Companion.OCTET_STREAM import org.http4k.core.Headers import org.http4k.core.HttpHandler import org.http4k.core.MemoryResponse import org.http4k.core.Request import org.http4k.core.Status.Companion.NOT_MODIFIED import org.http4k.core.Status.Companion.OK import org.http4k.core.etag.ETag import org.http4k.core.etag.ETagValidationRequestParser import org.http4k.core.etag.FieldValue import java.io.InputStream import java.time.Instant import java.time.ZoneOffset import java.time.format.DateTimeFormatter import java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME interface Resource : HttpHandler { fun openStream(): InputStream val length: Long? get() = null val lastModified: Instant? get() = null val contentType: ContentType get() = OCTET_STREAM val etag: ETag? get() = null fun isModifiedSince(instant: Instant): Boolean = lastModified?.isAfter(instant) ?: true val headers: Headers get() = listOf( "Content-Type" to contentType.value, "Content-Length" to length?.toString(), "Last-Modified" to lastModified?.formattedWith(dateTimeFormatter), "ETag" to etag?.toHeaderString() ) override fun invoke(request: Request) = if (notModifiedSince(request) || etagMatch(request)) MemoryResponse(NOT_MODIFIED, headers) else MemoryResponse(OK, headers, Body(openStream(), length)) // Pipeline is responsible for closing stream private fun notModifiedSince(request: Request): Boolean { val ifModifiedSince = request.header("If-Modified-Since")?.parsedWith(dateTimeFormatter) return ifModifiedSince != null && !isModifiedSince(ifModifiedSince) } private fun etagMatch(request: Request): Boolean { val fieldValue = request.header("If-None-Match")?.parsedForEtags() return fieldValue != null && etagMatch(fieldValue) } private fun etagMatch(fieldValue: FieldValue): Boolean { val localEtag = etag return when { localEtag == null -> false fieldValue === FieldValue.Wildcard -> true fieldValue is FieldValue.ETags -> fieldValue.hasAnEtagWithValue(localEtag.value) else -> false } } } private val dateTimeFormatter = RFC_1123_DATE_TIME.withZone(ZoneOffset.UTC) private fun Instant.formattedWith(formatter: DateTimeFormatter) = formatter.format(this) private fun String.parsedWith(formatter: DateTimeFormatter): Instant? = try { Instant.from(formatter.parse(this)) } catch (x: Exception) { null // "if the passed If-Modified-Since date is invalid, the response is exactly the same as for a normal GET" } private fun String.parsedForEtags(): FieldValue = ETagValidationRequestParser.parse(this) private fun FieldValue.ETags.hasAnEtagWithValue(value: String) = this.value.map(ETag::value).contains(value)
apache-2.0
601a72a6d5968c5e17ced780ac18d437
35.804878
119
0.72167
4.122951
false
false
false
false
RyotaMurohoshi/KotLinq
src/test/kotlin/com/muhron/kotlinq/GroupByTest.kt
1
3120
package com.muhron.kotlinq import org.junit.Assert import org.junit.Test class GroupByTest { @Test fun testA() { val result = sequenceOf(1, 2, 3, 4, 5, 1, 2, 3, 1).groupBy { it }.toList() Assert.assertEquals(result.size, 5); Assert.assertEquals(result.elementAt(0).key, 1); Assert.assertEquals(result.elementAt(0).asSequence().toList(), listOf(1, 1, 1)); Assert.assertEquals(result.elementAt(1).key, 2); Assert.assertEquals(result.elementAt(1).asSequence().toList(), listOf(2, 2)); Assert.assertEquals(result.elementAt(2).key, 3); Assert.assertEquals(result.elementAt(2).asSequence().toList(), listOf(3, 3)); Assert.assertEquals(result.elementAt(3).key, 4); Assert.assertEquals(result.elementAt(3).asSequence().toList(), listOf(4)); Assert.assertEquals(result.elementAt(4).key, 5); Assert.assertEquals(result.elementAt(4).asSequence().toList(), listOf(5)); } @Test fun testB() { val result = sequenceOf(1, 2, 3, 4, 5, 1, 2, 3, 1) .groupBy(keySelector = { it }, elementSelector = { it.toString() }) .toList() Assert.assertEquals(result.size, 5); Assert.assertEquals(result.elementAt(0).key, 1); Assert.assertEquals(result.elementAt(0).asSequence().toList(), listOf("1", "1", "1")); Assert.assertEquals(result.elementAt(1).key, 2); Assert.assertEquals(result.elementAt(1).asSequence().toList(), listOf("2", "2")); Assert.assertEquals(result.elementAt(2).key, 3); Assert.assertEquals(result.elementAt(2).asSequence().toList(), listOf("3", "3")); Assert.assertEquals(result.elementAt(3).key, 4); Assert.assertEquals(result.elementAt(3).asSequence().toList(), listOf("4")); Assert.assertEquals(result.elementAt(4).key, 5); Assert.assertEquals(result.elementAt(4).asSequence().toList(), listOf("5")); } @Test fun testC() { val result = sequenceOf(1, 2, 3, 4, 5, 1, 2, 3, 1) .groupBy(keySelector = { it }, resultSelector = { key, sequences -> sequences.sum() }) .toList() Assert.assertEquals(result.size, 5); Assert.assertEquals(result, listOf(3, 4, 6, 4, 5)) } @Test fun testD() { val result = sequenceOf(1, 2, 3, 4, 5, 1, 2, 3, 1) .groupBy(keySelector = { it }, elementSelector = { it.toString() }, resultSelector = { key, sequences -> sequences.joinToString() }) .toList() Assert.assertEquals(result.size, 5); Assert.assertEquals(result, listOf("1, 1, 1", "2, 2", "3, 3", "4", "5")) } @Test fun testNoThrownException1() { exceptionSequence<Int>().groupBy(keySelector = { it }) exceptionSequence<Int>().groupBy(keySelector = { it }, resultSelector = { key, sequences -> key }) exceptionSequence<Int>().groupBy(keySelector = { it }, elementSelector = { it }) exceptionSequence<Int>().groupBy(keySelector = { it }, elementSelector = { it }, resultSelector = { key, sequences -> key }) } }
mit
61a6c418273c0ced2085de988493713e
43.571429
148
0.607051
3.861386
false
true
false
false
cemrich/zapp
app/src/main/java/de/christinecoenen/code/zapp/app/mediathek/controller/downloads/DownloadController.kt
1
8844
package de.christinecoenen.code.zapp.app.mediathek.controller.downloads import android.content.Context import android.net.ConnectivityManager import com.tonyodev.fetch2.* import com.tonyodev.fetch2.Fetch.Impl.getInstance import com.tonyodev.fetch2.database.DownloadInfo import com.tonyodev.fetch2core.DownloadBlock import com.tonyodev.fetch2core.Downloader.FileDownloaderType import com.tonyodev.fetch2okhttp.OkHttpDownloader import de.christinecoenen.code.zapp.app.mediathek.controller.downloads.exceptions.DownloadException import de.christinecoenen.code.zapp.app.mediathek.controller.downloads.exceptions.NoNetworkException import de.christinecoenen.code.zapp.app.mediathek.controller.downloads.exceptions.WrongNetworkConditionException import de.christinecoenen.code.zapp.app.settings.repository.SettingsRepository import de.christinecoenen.code.zapp.models.shows.DownloadStatus import de.christinecoenen.code.zapp.models.shows.PersistedMediathekShow import de.christinecoenen.code.zapp.models.shows.Quality import de.christinecoenen.code.zapp.repositories.MediathekRepository import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch import okhttp3.JavaNetCookieJar import okhttp3.OkHttpClient import org.joda.time.DateTime import java.net.CookieManager import java.net.CookiePolicy import java.util.concurrent.TimeUnit import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine class DownloadController( applicationContext: Context, private val mediathekRepository: MediathekRepository ) : FetchListener, IDownloadController { private lateinit var fetch: Fetch private val connectivityManager: ConnectivityManager = applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager private val settingsRepository: SettingsRepository = SettingsRepository(applicationContext) private val downloadFileInfoManager: DownloadFileInfoManager = DownloadFileInfoManager(applicationContext, settingsRepository) init { val cookieManager = CookieManager() cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL) val client: OkHttpClient = OkHttpClient.Builder() .readTimeout(40, TimeUnit.SECONDS) // fetch default: 20 seconds .connectTimeout(30, TimeUnit.SECONDS) // fetch default: 15 seconds .cache(null) .followRedirects(true) .followSslRedirects(true) .retryOnConnectionFailure(false) .cookieJar(JavaNetCookieJar(cookieManager)) .build() val fetchConfiguration: FetchConfiguration = FetchConfiguration.Builder(applicationContext) .setNotificationManager(object : ZappNotificationManager(applicationContext, mediathekRepository) { override fun getFetchInstanceForNamespace(namespace: String): Fetch { return fetch } }) .enableRetryOnNetworkGain(false) .setAutoRetryMaxAttempts(0) .setDownloadConcurrentLimit(1) .preAllocateFileOnCreation(false) // true causes downloads to sd card to hang .setHttpDownloader(OkHttpDownloader(client, FileDownloaderType.SEQUENTIAL)) .enableLogging(true) .build() fetch = getInstance(fetchConfiguration) fetch.addListener(this) } override suspend fun startDownload(show: PersistedMediathekShow, quality: Quality) { val downloadUrl = show.mediathekShow.getVideoUrl(quality) ?: throw DownloadException("$quality is no valid download quality.") val download = getDownload(show.downloadId) if (download.id != 0 && download.url == downloadUrl) { // same quality as existing download // save new settings to request applySettingsToRequest(download.request) fetch.updateRequest(download.id, download.request, false, null, null) // update show properties show.downloadedAt = DateTime.now() show.downloadProgress = 0 mediathekRepository.updateShow(show) // retry fetch.retry(show.downloadId) } else { // delete old file with wrong quality fetch.delete(show.downloadId) val filePath = downloadFileInfoManager.getDownloadFilePath(show.mediathekShow, quality) val request: Request try { request = Request(downloadUrl, filePath) request.identifier = show.id.toLong() } catch (e: Exception) { throw DownloadException("Constructing download request failed.", e) } // update show properties show.downloadId = request.id show.downloadedAt = DateTime.now() show.downloadProgress = 0 mediathekRepository.updateShow(show) enqueueDownload(request) } } override fun stopDownload(persistedShowId: Int) { fetch.getDownloadsByRequestIdentifier(persistedShowId.toLong()) { downloadList -> for (download in downloadList) { fetch.cancel(download.id) } } } override fun deleteDownload(persistedShowId: Int) { fetch.getDownloadsByRequestIdentifier(persistedShowId.toLong()) { downloadList -> for (download in downloadList) { fetch.delete(download.id) } } } override fun getDownloadStatus(persistedShowId: Int): Flow<DownloadStatus> { return mediathekRepository.getDownloadStatus(persistedShowId) } override fun getDownloadProgress(persistedShowId: Int): Flow<Int> { return mediathekRepository.getDownloadProgress(persistedShowId) } override fun deleteDownloadsWithDeletedFiles() { fetch.getDownloadsWithStatus(Status.COMPLETED) { downloads -> for (download in downloads) { if (downloadFileInfoManager.shouldDeleteDownload(download)) { fetch.remove(download.id) } } } } /** * @return download with the given id or empty download with id of 0 */ private suspend fun getDownload(downloadId: Int): Download = suspendCoroutine { continuation -> fetch.getDownload(downloadId) { download -> if (download == null) { continuation.resume(DownloadInfo()) } else { continuation.resume(download) } } } private fun enqueueDownload(request: Request) { applySettingsToRequest(request) fetch.enqueue(request, null, null) } private fun applySettingsToRequest(request: Request) { request.networkType = if (settingsRepository.downloadOverUnmeteredNetworkOnly) { NetworkType.UNMETERED } else { NetworkType.ALL } if (connectivityManager.activeNetwork == null) { throw NoNetworkException("No active network available.") } if (settingsRepository.downloadOverUnmeteredNetworkOnly && connectivityManager.isActiveNetworkMetered) { throw WrongNetworkConditionException("Download over metered networks prohibited.") } } private suspend fun updateDownloadStatus(download: Download) { val downloadStatus = DownloadStatus.values()[download.status.value] mediathekRepository.updateDownloadStatus(download.id, downloadStatus) } private suspend fun updateDownloadProgress(download: Download, progress: Int) { mediathekRepository.updateDownloadProgress(download.id, progress) } override fun onAdded(download: Download) { GlobalScope.launch { updateDownloadStatus(download) } } override fun onCancelled(download: Download) { GlobalScope.launch { fetch.delete(download.id) updateDownloadStatus(download) updateDownloadProgress(download, 0) } } override fun onCompleted(download: Download) { GlobalScope.launch { updateDownloadStatus(download) mediathekRepository.updateDownloadedVideoPath(download.id, download.file) downloadFileInfoManager.updateDownloadFileInMediaCollection(download) } } override fun onDeleted(download: Download) { GlobalScope.launch { updateDownloadStatus(download) updateDownloadProgress(download, 0) downloadFileInfoManager.updateDownloadFileInMediaCollection(download) } } override fun onDownloadBlockUpdated( download: Download, downloadBlock: DownloadBlock, totalBlocks: Int ) { } override fun onError(download: Download, error: Error, throwable: Throwable?) { GlobalScope.launch { downloadFileInfoManager.deleteDownloadFile(download) updateDownloadStatus(download) } } override fun onPaused(download: Download) { GlobalScope.launch { updateDownloadStatus(download) } } override fun onProgress( download: Download, etaInMilliSeconds: Long, downloadedBytesPerSecond: Long ) { GlobalScope.launch { updateDownloadProgress(download, download.progress) } } override fun onQueued(download: Download, waitingOnNetwork: Boolean) { GlobalScope.launch { updateDownloadStatus(download) } } override fun onRemoved(download: Download) { GlobalScope.launch { updateDownloadStatus(download) } } override fun onResumed(download: Download) { GlobalScope.launch { updateDownloadStatus(download) } } override fun onStarted( download: Download, downloadBlocks: List<DownloadBlock>, totalBlocks: Int ) { GlobalScope.launch { updateDownloadStatus(download) } } override fun onWaitingNetwork(download: Download) { GlobalScope.launch { updateDownloadStatus(download) } } }
mit
4fad576edd665777ffd04d9b190add99
29.391753
112
0.781999
4.215443
false
false
false
false
brettwooldridge/buck
tools/datascience/src/com/facebook/buck/datascience/traces/CollectDeviceSerials.kt
4
2574
/* * Copyright 2018-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.datascience.traces class CollectDeviceSerials : TraceAnalysisVisitor<Map<String, Long>> { companion object { val PATTERN_EMULATOR = Regex("^emulator-\\d+$") val PATTERN_GENYMOTION = Regex("^[\\d.:\\[\\]]+:5\\d\\d\\d$") } /** * Map of serial number to number of installations. * It seems unlikely that we'd ever have more than one for a single trace, but be safe. * Multiple keys can be present with "buck install -x". */ private val serialCounts = mutableMapOf<String, Long>() override fun traceComplete() = serialCounts override fun finishAnalysis(args: List<String>, intermediates: List<Map<String, Long>>) { // Add up the maps from each trace. val totals = mutableMapOf<String, Long>() intermediates.forEach { it.forEach { k, v -> totals[k] = v + totals.getOrDefault(k, 0) } } totals.toSortedMap().forEach { serial, count -> System.out.println("%24s %d".format(serial, count)) } System.out.println() // Group and count by device type. val kinds = mutableMapOf<String, Long>() totals.forEach { k, v -> val kind = when { k.matches(PATTERN_EMULATOR) -> "emulator" k.matches(PATTERN_GENYMOTION) -> "genymotion" else -> "device" } kinds[kind] = v + kinds.getOrDefault(kind, 0) } kinds.toSortedMap().forEach { kind, count -> System.out.println("%12s %d".format(kind, count)) } } override fun eventBegin(event: TraceEvent, state: TraceState) { if (event.name == "adb_call install exopackage apk") { val serial = event.args["device_serial"].textValue() if (serial != null) { serialCounts[serial] = 1 + serialCounts.getOrDefault(serial, 0) } } } }
apache-2.0
48aa8ac197ff07f4755123a8ec89e34f
35.253521
93
0.607615
4.199021
false
false
false
false
randombyte-developer/holograms
src/main/kotlin/de/randombyte/holograms/Holograms.kt
1
4665
package de.randombyte.holograms import com.google.inject.Inject import de.randombyte.holograms.api.HologramsService import de.randombyte.holograms.commands.ListNearbyHologramsCommand import de.randombyte.holograms.commands.SetNearestHologramText import de.randombyte.holograms.commands.SpawnMultiLineTextHologramCommand import de.randombyte.holograms.commands.SpawnTextHologramCommand import de.randombyte.holograms.data.HologramData import de.randombyte.holograms.data.HologramKeys import de.randombyte.kosp.extensions.toText import org.bstats.sponge.Metrics2 import org.slf4j.Logger import org.spongepowered.api.Sponge import org.spongepowered.api.command.args.GenericArguments.* import org.spongepowered.api.command.spec.CommandSpec import org.spongepowered.api.config.ConfigDir import org.spongepowered.api.data.DataRegistration import org.spongepowered.api.event.Listener import org.spongepowered.api.event.game.GameReloadEvent import org.spongepowered.api.event.game.state.GameInitializationEvent import org.spongepowered.api.event.game.state.GamePreInitializationEvent import org.spongepowered.api.plugin.Plugin import org.spongepowered.api.plugin.PluginContainer import java.nio.file.Files import java.nio.file.Path @Plugin(id = Holograms.ID, name = Holograms.NAME, version = Holograms.VERSION, authors = arrayOf(Holograms.AUTHOR)) class Holograms @Inject constructor( private val logger: Logger, @ConfigDir(sharedRoot = false) private val configPath: Path, private val pluginContainer: PluginContainer, val bStats: Metrics2 ) { companion object { const val NAME = "Holograms" const val ID = "holograms" const val VERSION = "3.2.0" const val AUTHOR = "RandomByte" } val inputFile: Path = configPath.resolve("input.txt") @Listener fun onPreInit(event: GamePreInitializationEvent) { Sponge.getServiceManager().setProvider(this, HologramsService::class.java, HologramsServiceImpl()) HologramKeys.buildKeys() Sponge.getDataManager().registerLegacyManipulatorIds("de.randombyte.holograms.data.HologramData", DataRegistration.builder() .dataClass(HologramData::class.java) .immutableClass(HologramData.Immutable::class.java) .builder(HologramData.Builder()) .manipulatorId("holograms-data") .dataName("Holograms Data") .buildAndRegister(pluginContainer)) } @Listener fun onInit(event: GameInitializationEvent) { inputFile.safelyCreateFile() Sponge.getCommandManager().register(this, CommandSpec.builder() .permission("holograms.list") .executor(ListNearbyHologramsCommand(this)) .arguments(optional(integer("maxDistance".toText()))) .child(CommandSpec.builder() .permission("holograms.create") .arguments(remainingJoinedStrings("text".toText())) .executor(SpawnTextHologramCommand()) .build(), "create") .child(CommandSpec.builder() .permission("holograms.createMultiLine") .arguments(seq( doubleNum("verticalSpace".toText()), firstParsing( integer("numberOfLines".toText()), remainingJoinedStrings("texts".toText()) ) )) .executor(SpawnMultiLineTextHologramCommand()) .build(), "createMultiLine", "cml") .child(CommandSpec.builder() .permission("holograms.list") .arguments(optional(integer("maxDistance".toText()))) .executor(ListNearbyHologramsCommand(this)) .build(), "list") .child(CommandSpec.builder() .permission("holograms.setText") .arguments(remainingJoinedStrings("text".toText())) .executor(SetNearestHologramText()) .build(), "setText") .build(), "holograms") logger.info("$NAME loaded: $VERSION") } @Listener fun onReload(event: GameReloadEvent) { inputFile.safelyCreateFile() } private fun Path.safelyCreateFile() { if (!Files.exists(this)) { Files.createDirectories(this.parent) Files.createFile(this) } } }
gpl-2.0
3c36090c0b898962edaa02daf2c94aa3
40.651786
132
0.633869
5.098361
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
fluxc/src/main/java/org/wordpress/android/fluxc/model/encryptedlogging/LogEncrypter.kt
2
4434
package org.wordpress.android.fluxc.model.encryptedlogging import android.util.Base64 import com.goterl.lazysodium.interfaces.SecretStream import com.goterl.lazysodium.interfaces.SecretStream.State import com.goterl.lazysodium.utils.Key import dagger.Reusable import javax.inject.Inject private const val ENCODED_ENCRYPTED_KEY_LENGTH = 108 private const val ENCODED_HEADER_LENGTH = 32 data class EncryptedLoggingKey(val publicKey: Key) /** * [LogEncrypter] encrypts the logs for the given text. ** * @param encryptedLoggingKey The public key used to encrypt the log * */ @Reusable class LogEncrypter @Inject constructor(private val encryptedLoggingKey: EncryptedLoggingKey) { /** * Encrypts the given [text]. It also adds the given [uuid] to its headers. * * @param text Text contents to be encrypted * @param uuid Uuid for the encrypted log */ fun encrypt(text: String, uuid: String): String = buildString { val state = State.ByReference() append(buildHeader(uuid, state)) val lines = text.lines() lines.asSequence().mapIndexed { index, line -> if (index + 1 >= lines.size) { // If it's the last element line } else { "$line\n" } }.forEach { line -> append(buildMessage(line, state)) } append(buildFooter(state)) } /** * Encrypt and write the provided string to the encrypted log file. * @param string: The string to be written to the file. */ private fun buildMessage(string: String, state: State): String { val encryptedString = encryptMessage(string, SecretStream.TAG_MESSAGE, state) return "\t\t\"$encryptedString\",\n" } /** * An internal convenience function to extract the header building process. */ private fun buildHeader(uuid: String, state: State): String { val header = ByteArray(SecretStream.HEADERBYTES) val key = SecretStreamKey.generate().let { check(EncryptionUtils.sodium.cryptoSecretStreamInitPush(state, header, it.bytes)) it.encrypt(encryptedLoggingKey.publicKey) } require(SecretStream.Checker.headerCheck(header.size)) { "The secret stream header must be the correct length" } val encodedEncryptedKey = base64Encode(key.bytes) check(encodedEncryptedKey.length == ENCODED_ENCRYPTED_KEY_LENGTH) { "The encoded, encrypted key must always be $ENCODED_ENCRYPTED_KEY_LENGTH bytes long" } val encodedHeader = base64Encode(header) check(encodedHeader.length == ENCODED_HEADER_LENGTH) { "The encoded header must always be $ENCODED_HEADER_LENGTH bytes long" } return buildString { append("{") append("\t\"keyedWith\": \"v1\",\n") append("\t\"encryptedKey\": \"$encodedEncryptedKey\",\n") append("\t\"header\": \"$encodedHeader\",\n") append("\t\"uuid\": \"$uuid\",\n") append("\t\"messages\": [\n") } } /** * Add the closing file tag */ private fun buildFooter(state: State): String { val encryptedClosingTag = encryptMessage("", SecretStream.TAG_FINAL, state) return buildString { append("\t\t\"$encryptedClosingTag\"\n") append("\t]\n") append("}") } } /** * An internal convenience function to push more data into the sodium secret stream. */ private fun encryptMessage(string: String, tag: Byte, state: State): String { val plainBytes = string.toByteArray() val encryptedBytes = ByteArray(SecretStream.ABYTES + plainBytes.size) // Stores the encrypted bytes check( EncryptionUtils.sodium.cryptoSecretStreamPush( state, encryptedBytes, plainBytes, plainBytes.size.toLong(), tag ) ) { "Unable to encrypt message: $string" } return base64Encode(encryptedBytes) } } // On Android base64 has lots of options, so define a helper to make it easier to // avoid encoding issues. private fun base64Encode(byteArray: ByteArray): String { return Base64.encodeToString(byteArray, Base64.NO_WRAP) }
gpl-2.0
1a2c458696ffb150caac04c1f26d2b59
33.640625
107
0.616373
4.547692
false
false
false
false
Kotlin/kotlinx.serialization
formats/cbor/commonTest/src/kotlinx/serialization/cbor/SampleClasses.kt
1
3580
/* * Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.cbor import kotlinx.serialization.* import kotlinx.serialization.builtins.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* @Serializable data class Simple(val a: String) @Serializable data class TypesUmbrella( val str: String, val i: Int, val nullable: Double?, val list: List<String>, val map: Map<Int, Boolean>, val inner: Simple, val innersList: List<Simple>, @ByteString val byteString: ByteArray, val byteArray: ByteArray ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || this::class != other::class) return false other as TypesUmbrella if (str != other.str) return false if (i != other.i) return false if (nullable != other.nullable) return false if (list != other.list) return false if (map != other.map) return false if (inner != other.inner) return false if (innersList != other.innersList) return false if (!byteString.contentEquals(other.byteString)) return false if (!byteArray.contentEquals(other.byteArray)) return false return true } override fun hashCode(): Int { var result = str.hashCode() result = 31 * result + i result = 31 * result + (nullable?.hashCode() ?: 0) result = 31 * result + list.hashCode() result = 31 * result + map.hashCode() result = 31 * result + inner.hashCode() result = 31 * result + innersList.hashCode() result = 31 * result + byteString.contentHashCode() result = 31 * result + byteArray.contentHashCode() return result } } @Serializable data class NumberTypesUmbrella( val int: Int, val long: Long, val float: Float, val double: Double, val boolean: Boolean, val char: Char ) @Serializable data class NullableByteString( @ByteString val byteString: ByteArray? ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || this::class != other::class) return false other as NullableByteString if (byteString != null) { if (other.byteString == null) return false if (!byteString.contentEquals(other.byteString)) return false } else if (other.byteString != null) return false return true } override fun hashCode(): Int { return byteString?.contentHashCode() ?: 0 } } @Serializable(with = CustomByteStringSerializer::class) data class CustomByteString(val a: Byte, val b: Byte, val c: Byte) class CustomByteStringSerializer : KSerializer<CustomByteString> { override val descriptor = SerialDescriptor("CustomByteString", ByteArraySerializer().descriptor) override fun serialize(encoder: Encoder, value: CustomByteString) { encoder.encodeSerializableValue(ByteArraySerializer(), byteArrayOf(value.a, value.b, value.c)) } override fun deserialize(decoder: Decoder): CustomByteString { val array = decoder.decodeSerializableValue(ByteArraySerializer()) return CustomByteString(array[0], array[1], array[2]) } } @Serializable data class TypeWithCustomByteString(@ByteString val x: CustomByteString) @Serializable data class TypeWithNullableCustomByteString(@ByteString val x: CustomByteString?)
apache-2.0
07acf9e6ce646e2d987740f8e13cfc06
30.690265
102
0.658939
4.589744
false
true
false
false
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/kingdom/service/internal/testing/Population.kt
1
13742
// Copyright 2021 The Cross-Media Measurement 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.wfanet.measurement.kingdom.service.internal.testing import com.google.gson.JsonParser import com.google.protobuf.kotlin.toByteStringUtf8 import com.google.rpc.ErrorInfo import io.grpc.StatusRuntimeException import io.grpc.protobuf.ProtoUtils import java.time.Clock import java.time.Instant import java.time.temporal.ChronoUnit import kotlin.random.Random import org.wfanet.measurement.common.base64UrlDecode import org.wfanet.measurement.common.crypto.hashSha256 import org.wfanet.measurement.common.crypto.tink.PublicJwkHandle import org.wfanet.measurement.common.crypto.tink.SelfIssuedIdTokens import org.wfanet.measurement.common.crypto.tink.SelfIssuedIdTokens.generateIdToken import org.wfanet.measurement.common.identity.IdGenerator import org.wfanet.measurement.common.openid.createRequestUri import org.wfanet.measurement.common.toProtoTime import org.wfanet.measurement.internal.kingdom.Account import org.wfanet.measurement.internal.kingdom.AccountKt.openIdConnectIdentity import org.wfanet.measurement.internal.kingdom.AccountsGrpcKt.AccountsCoroutineImplBase import org.wfanet.measurement.internal.kingdom.Certificate import org.wfanet.measurement.internal.kingdom.CertificateKt import org.wfanet.measurement.internal.kingdom.CertificatesGrpcKt.CertificatesCoroutineImplBase import org.wfanet.measurement.internal.kingdom.DataProvider import org.wfanet.measurement.internal.kingdom.DataProviderKt import org.wfanet.measurement.internal.kingdom.DataProvidersGrpcKt.DataProvidersCoroutineImplBase import org.wfanet.measurement.internal.kingdom.DuchyProtocolConfigKt import org.wfanet.measurement.internal.kingdom.Measurement import org.wfanet.measurement.internal.kingdom.MeasurementConsumer import org.wfanet.measurement.internal.kingdom.MeasurementConsumerKt import org.wfanet.measurement.internal.kingdom.MeasurementConsumersGrpcKt.MeasurementConsumersCoroutineImplBase import org.wfanet.measurement.internal.kingdom.MeasurementKt import org.wfanet.measurement.internal.kingdom.MeasurementKt.dataProviderValue import org.wfanet.measurement.internal.kingdom.MeasurementsGrpcKt.MeasurementsCoroutineImplBase import org.wfanet.measurement.internal.kingdom.ModelProvider import org.wfanet.measurement.internal.kingdom.ModelProvidersGrpcKt.ModelProvidersCoroutineImplBase import org.wfanet.measurement.internal.kingdom.ProtocolConfigKt import org.wfanet.measurement.internal.kingdom.account import org.wfanet.measurement.internal.kingdom.activateAccountRequest import org.wfanet.measurement.internal.kingdom.certificate import org.wfanet.measurement.internal.kingdom.createMeasurementConsumerCreationTokenRequest import org.wfanet.measurement.internal.kingdom.createMeasurementConsumerRequest import org.wfanet.measurement.internal.kingdom.dataProvider import org.wfanet.measurement.internal.kingdom.duchyProtocolConfig import org.wfanet.measurement.internal.kingdom.generateOpenIdRequestParamsRequest import org.wfanet.measurement.internal.kingdom.measurement import org.wfanet.measurement.internal.kingdom.measurementConsumer import org.wfanet.measurement.internal.kingdom.modelProvider import org.wfanet.measurement.internal.kingdom.protocolConfig private const val API_VERSION = "v2alpha" class Population(val clock: Clock, val idGenerator: IdGenerator) { private fun buildRequestCertificate( derUtf8: String, skidUtf8: String, notValidBefore: Instant, notValidAfter: Instant ) = certificate { fillRequestCertificate(derUtf8, skidUtf8, notValidBefore, notValidAfter) } private fun CertificateKt.Dsl.fillRequestCertificate( derUtf8: String, skidUtf8: String, notValidBefore: Instant, notValidAfter: Instant ) { this.notValidBefore = notValidBefore.toProtoTime() this.notValidAfter = notValidAfter.toProtoTime() subjectKeyIdentifier = skidUtf8.toByteStringUtf8() details = CertificateKt.details { x509Der = derUtf8.toByteStringUtf8() } } suspend fun createMeasurementConsumer( measurementConsumersService: MeasurementConsumersCoroutineImplBase, accountsService: AccountsCoroutineImplBase, notValidBefore: Instant = clock.instant(), notValidAfter: Instant = notValidBefore.plus(365L, ChronoUnit.DAYS) ): MeasurementConsumer { val account = createAccount(accountsService) activateAccount(accountsService, account) val measurementConsumerCreationTokenHash = hashSha256(createMeasurementConsumerCreationToken(accountsService)) return measurementConsumersService.createMeasurementConsumer( createMeasurementConsumerRequest { measurementConsumer = measurementConsumer { certificate = buildRequestCertificate( "MC cert", "MC SKID " + idGenerator.generateExternalId().value, notValidBefore, notValidAfter ) details = MeasurementConsumerKt.details { apiVersion = API_VERSION publicKey = "MC public key".toByteStringUtf8() publicKeySignature = "MC public key signature".toByteStringUtf8() } } externalAccountId = account.externalAccountId this.measurementConsumerCreationTokenHash = measurementConsumerCreationTokenHash } ) } suspend fun createDataProvider( dataProvidersService: DataProvidersCoroutineImplBase, notValidBefore: Instant = clock.instant(), notValidAfter: Instant = notValidBefore.plus(365L, ChronoUnit.DAYS) ): DataProvider { return dataProvidersService.createDataProvider( dataProvider { certificate = buildRequestCertificate( "EDP cert", "EDP SKID " + idGenerator.generateExternalId().value, notValidBefore, notValidAfter ) details = DataProviderKt.details { apiVersion = API_VERSION publicKey = "EDP public key".toByteStringUtf8() publicKeySignature = "EDP public key signature".toByteStringUtf8() } } ) } suspend fun createModelProvider( modelProvidersService: ModelProvidersCoroutineImplBase ): ModelProvider { return modelProvidersService.createModelProvider(modelProvider {}) } private suspend fun createMeasurement( measurementsService: MeasurementsCoroutineImplBase, measurementConsumer: MeasurementConsumer, providedMeasurementId: String, dataProviders: Map<Long, Measurement.DataProviderValue> = mapOf(), details: Measurement.Details ): Measurement { return measurementsService.createMeasurement( measurement { externalMeasurementConsumerId = measurementConsumer.externalMeasurementConsumerId this.providedMeasurementId = providedMeasurementId externalMeasurementConsumerCertificateId = measurementConsumer.certificate.externalCertificateId this.details = details this.dataProviders.putAll(dataProviders) } ) } suspend fun createComputedMeasurement( measurementsService: MeasurementsCoroutineImplBase, measurementConsumer: MeasurementConsumer, providedMeasurementId: String, dataProviders: Map<Long, Measurement.DataProviderValue> = mapOf() ): Measurement { val details = MeasurementKt.details { apiVersion = API_VERSION measurementSpec = "MeasurementSpec".toByteStringUtf8() measurementSpecSignature = "MeasurementSpec signature".toByteStringUtf8() duchyProtocolConfig = duchyProtocolConfig { liquidLegionsV2 = DuchyProtocolConfigKt.liquidLegionsV2 {} } protocolConfig = protocolConfig { liquidLegionsV2 = ProtocolConfigKt.liquidLegionsV2 {} } } return createMeasurement( measurementsService, measurementConsumer, providedMeasurementId, dataProviders, details ) } suspend fun createComputedMeasurement( measurementsService: MeasurementsCoroutineImplBase, measurementConsumer: MeasurementConsumer, providedMeasurementId: String, vararg dataProviders: DataProvider ): Measurement { return createComputedMeasurement( measurementsService, measurementConsumer, providedMeasurementId, dataProviders.associate { it.externalDataProviderId to it.toDataProviderValue() } ) } suspend fun createDirectMeasurement( measurementsService: MeasurementsCoroutineImplBase, measurementConsumer: MeasurementConsumer, providedMeasurementId: String, dataProviders: Map<Long, Measurement.DataProviderValue> = mapOf() ): Measurement { val details = MeasurementKt.details { apiVersion = API_VERSION measurementSpec = "MeasurementSpec".toByteStringUtf8() measurementSpecSignature = "MeasurementSpec signature".toByteStringUtf8() } return createMeasurement( measurementsService, measurementConsumer, providedMeasurementId, dataProviders, details ) } suspend fun createDirectMeasurement( measurementsService: MeasurementsCoroutineImplBase, measurementConsumer: MeasurementConsumer, providedMeasurementId: String, vararg dataProviders: DataProvider ): Measurement { return createDirectMeasurement( measurementsService, measurementConsumer, providedMeasurementId, dataProviders.associate { it.externalDataProviderId to it.toDataProviderValue() } ) } suspend fun createDuchyCertificate( certificatesService: CertificatesCoroutineImplBase, externalDuchyId: String, notValidBefore: Instant = clock.instant(), notValidAfter: Instant = notValidBefore.plus(365L, ChronoUnit.DAYS) ): Certificate { return certificatesService.createCertificate( certificate { this.externalDuchyId = externalDuchyId fillRequestCertificate( "Duchy cert", "Duchy $externalDuchyId SKID", notValidBefore, notValidAfter ) } ) } /** Creates an [Account] and returns it. */ suspend fun createAccount( accountsService: AccountsCoroutineImplBase, externalCreatorAccountId: Long = 0L, externalOwnedMeasurementConsumerId: Long = 0L ): Account { return accountsService.createAccount( account { this.externalCreatorAccountId = externalCreatorAccountId this.externalOwnedMeasurementConsumerId = externalOwnedMeasurementConsumerId } ) } /** * Generates a self-issued ID token and uses it to activate the [Account]. * * @return generated self-issued ID token used for activation */ suspend fun activateAccount( accountsService: AccountsCoroutineImplBase, account: Account, ): String { val openIdRequestParams = accountsService.generateOpenIdRequestParams(generateOpenIdRequestParamsRequest {}) val idToken = generateIdToken( createRequestUri( state = openIdRequestParams.state, nonce = openIdRequestParams.nonce, redirectUri = "", isSelfIssued = true ), clock ) val openIdConnectIdentity = parseIdToken(idToken) accountsService.activateAccount( activateAccountRequest { externalAccountId = account.externalAccountId activationToken = account.activationToken identity = openIdConnectIdentity } ) return idToken } fun parseIdToken(idToken: String, redirectUri: String = ""): Account.OpenIdConnectIdentity { val tokenParts = idToken.split(".") val claims = JsonParser.parseString(tokenParts[1].base64UrlDecode().toString(Charsets.UTF_8)).asJsonObject val subJwk = claims.get("sub_jwk") val jwk = subJwk.asJsonObject val publicJwkHandle = PublicJwkHandle.fromJwk(jwk) val verifiedJwt = SelfIssuedIdTokens.validateJwt( redirectUri = redirectUri, idToken = idToken, publicJwkHandle = publicJwkHandle ) return openIdConnectIdentity { issuer = verifiedJwt.issuer!! subject = verifiedJwt.subject!! } } suspend fun createMeasurementConsumerCreationToken( accountsService: AccountsCoroutineImplBase ): Long { val createMeasurementConsumerCreationTokenResponse = accountsService.createMeasurementConsumerCreationToken( createMeasurementConsumerCreationTokenRequest {} ) return createMeasurementConsumerCreationTokenResponse.measurementConsumerCreationToken } } fun DataProvider.toDataProviderValue(nonce: Long = Random.Default.nextLong()) = dataProviderValue { externalDataProviderCertificateId = certificate.externalCertificateId dataProviderPublicKey = details.publicKey dataProviderPublicKeySignature = details.publicKeySignature encryptedRequisitionSpec = "Encrypted RequisitionSpec $nonce".toByteStringUtf8() nonceHash = hashSha256(nonce) } /** * [ErrorInfo] from [trailers][StatusRuntimeException.getTrailers]. * * TODO(@SanjayVas): Move this to common.grpc. */ val StatusRuntimeException.errorInfo: ErrorInfo? get() { val key = ProtoUtils.keyForProto(ErrorInfo.getDefaultInstance()) return trailers?.get(key) }
apache-2.0
bb2ea10db03a5774f5f52bafd4cfc5a8
36.856749
111
0.758914
5.477083
false
false
false
false
googleapis/gapic-generator-kotlin
generator/src/main/kotlin/com/google/api/kotlin/config/ProtobufTypeMapper.kt
1
5934
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.kotlin.config import com.google.common.base.CaseFormat import com.google.protobuf.DescriptorProtos import com.squareup.kotlinpoet.ClassName /** Maps proto names to kotlin names */ internal class ProtobufTypeMapper private constructor() { private val typeMap = mutableMapOf<String, String>() private val serviceMap = mutableMapOf<String, String>() private val knownProtoTypes = mutableMapOf<String, DescriptorProtos.DescriptorProto>() private val knownProtoEnums = mutableMapOf<String, DescriptorProtos.EnumDescriptorProto>() /** Lookup the Kotlin type given the proto type. */ fun getKotlinType(protoType: String) = ClassName.bestGuess( typeMap[protoType] ?: throw IllegalArgumentException("proto type: $protoType is not recognized") ) /** Get all Kotlin types (excluding enums and map types) */ fun getAllKotlinTypes() = knownProtoTypes.keys .asSequence() .filter { !(knownProtoTypes[it]?.options?.mapEntry ?: false) } .map { typeMap[it] ?: throw IllegalStateException("unknown type: $it") } .toList() fun getAllTypes() = knownProtoTypes.keys.map { TypeNamePair(it, typeMap[it]!!) } /** Checks if the message type is in this mapper */ fun hasProtoTypeDescriptor(type: String) = knownProtoTypes.containsKey(type) /** Lookup up a known proto message type by name */ fun getProtoTypeDescriptor(type: String) = knownProtoTypes[type] ?: throw IllegalArgumentException("unknown type: $type") /** Checks if the enum type is in this mapper */ fun hasProtoEnumDescriptor(type: String) = knownProtoEnums.containsKey(type) /** Lookup a known proto enum type by name */ fun getProtoEnumDescriptor(type: String) = knownProtoEnums[type] ?: throw IllegalArgumentException("unknown enum: $type") override fun toString(): String { val ret = StringBuilder("Types:") typeMap.forEach { k, v -> ret.append("\n $k -> $v") } return ret.toString() } companion object { /** Create a map from a set of proto descriptors */ fun fromProtos(descriptors: Collection<DescriptorProtos.FileDescriptorProto>): ProtobufTypeMapper { val map = ProtobufTypeMapper() descriptors.map { proto -> val protoPackage = if (proto.hasPackage()) "." + proto.`package` else "" val javaPackage = if (proto.options.hasJavaPackage()) proto.options.javaPackage else proto.`package` val enclosingClassName = if (proto.options?.javaMultipleFiles != false) null else getOuterClassname(proto) fun addMsg(p: DescriptorProtos.DescriptorProto, parent: String) { val key = "$protoPackage$parent.${p.name}" map.typeMap[key] = listOfNotNull("$javaPackage$parent", enclosingClassName, p.name) .joinToString(".") map.knownProtoTypes[key] = p } fun addEnum(p: DescriptorProtos.EnumDescriptorProto, parent: String) { val key = "$protoPackage$parent.${p.name}" map.typeMap[key] = listOfNotNull("$javaPackage$parent", enclosingClassName, p.name) .joinToString(".") map.knownProtoEnums[key] = p } fun addService(p: DescriptorProtos.ServiceDescriptorProto, parent: String) { map.serviceMap["$protoPackage$parent.${p.name}"] = listOfNotNull("$javaPackage$parent", enclosingClassName, p.name) .joinToString(".") } fun addNested(p: DescriptorProtos.DescriptorProto, parent: String) { addMsg(p, parent) p.enumTypeList.forEach { addEnum(it, "$parent.${p.name}") } p.nestedTypeList.forEach { addNested(it, "$parent.${p.name}") } } // process top level types and services proto.messageTypeList.forEach { addNested(it, "") } proto.serviceList.forEach { addService(it, "") } proto.enumTypeList.forEach { addEnum(it, "") } } return map } private fun getOuterClassname(proto: DescriptorProtos.FileDescriptorProto): String { if (proto.options.hasJavaOuterClassname()) { return proto.options.javaOuterClassname } var fileName = proto.name.substring(0, proto.name.length - ".proto".length) if (fileName.contains("/")) { fileName = fileName.substring(fileName.lastIndexOf('/') + 1) } fileName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, fileName) if (proto.enumTypeList.any { it.name == fileName } || proto.messageTypeList.any { it.name == fileName } || proto.serviceList.any { it.name == fileName }) { fileName += "OuterClass" } return fileName } } } internal data class TypeNamePair(val protoName: String, val kotlinName: String)
apache-2.0
bae65ee899e41194eadcf469a2e698e7
40.788732
107
0.610381
4.961538
false
false
false
false
cempo/SimpleTodoList
app/src/main/java/com/makeevapps/simpletodolist/ui/view/ScrollAwareFABBehavior.kt
1
3111
package com.makeevapps.simpletodolist.ui.view import android.content.Context import android.support.design.widget.CoordinatorLayout import android.support.design.widget.FloatingActionButton import android.support.v4.view.ViewCompat import android.util.AttributeSet import android.view.View import com.makeevapps.simpletodolist.R class ScrollAwareFABBehavior(context: Context, attrs: AttributeSet) : FloatingActionButton.Behavior() { override fun onStartNestedScroll(coordinatorLayout: CoordinatorLayout, child: FloatingActionButton, directTargetChild: View, target: View, nestedScrollAxes: Int): Boolean { // Ensure we react to vertical scrolling val o = child.getTag(R.id.can_be_visible) val canBeVisible = o == null || o as Boolean return canBeVisible && (nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL || super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes)) } override fun onNestedScroll(coordinatorLayout: CoordinatorLayout, child: FloatingActionButton, target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int) { super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed) if (dyConsumed > 0 && child.visibility == View.VISIBLE) { child.hide(object : FloatingActionButton.OnVisibilityChangedListener() { override fun onHidden(fab: FloatingActionButton?) { super.onHidden(fab) child.visibility = View.INVISIBLE } }) } else if (dyConsumed < 0 && child.visibility != View.VISIBLE) { child.show() } } /*override fun onStartNestedScroll(coordinatorLayout: CoordinatorLayout, child: FloatingActionButton, directTargetChild: View, target: View, axes: Int, type: Int): Boolean { // Ensure we react to vertical scrolling val o = child.getTag(R.id.can_be_visible) val canBeVisible = o == null || o as Boolean return canBeVisible && (type == ViewCompat.SCROLL_AXIS_VERTICAL || super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, axes, type)) } override fun onNestedScroll(coordinatorLayout: CoordinatorLayout, child: FloatingActionButton, target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int, type: Int) { super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type) if (dyConsumed > 0 && child.visibility == View.VISIBLE) { child.hide(object : FloatingActionButton.OnVisibilityChangedListener() { override fun onHidden(fab: FloatingActionButton?) { super.onHidden(fab) child.visibility = View.INVISIBLE } }) } else if (dyConsumed < 0 && child.visibility != View.VISIBLE) { child.show() } }*/ }
mit
bf64e4f69c105f58e2dd84404b7f2ec2
50.016393
197
0.67181
5.219799
false
false
false
false
RizkiMufrizal/Starter-Project
Starter-BackEnd/src/main/kotlin/org/rizki/mufrizal/starter/backend/domain/oauth2/OAuth2RefreshToken.kt
1
824
package org.rizki.mufrizal.starter.backend.domain.oauth2 import javax.persistence.Column import javax.persistence.Entity import javax.persistence.Id import javax.persistence.Table /** * * @Author Rizki Mufrizal <[email protected]> * @Web <https://RizkiMufrizal.github.io> * @Since 20 August 2017 * @Time 6:06 PM * @Project Starter-BackEnd * @Package org.rizki.mufrizal.starter.backend.domain.oauth2 * @File OAuth2RefreshToken * */ @Entity @Table(name = "oauth_refresh_token") data class OAuth2RefreshToken( @Id @Column(name = "token_id") val tokenId: String? = null, @Column(name = "token", columnDefinition = "BLOB") val token: ByteArray? = null, @Column(name = "authentication", columnDefinition = "BLOB") val authentication: ByteArray? = null )
apache-2.0
9d15f2c8af92a976f7131bf83d8a6909
24.78125
67
0.692961
3.646018
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/gui/browser/BaseBrowserFragment.kt
1
26719
/** * ************************************************************************** * BaseBrowserFragment.kt * **************************************************************************** * Copyright © 2018 VLC authors and VideoLAN * Author: Geoffrey Métais * * 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 2 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. * *************************************************************************** */ package org.videolan.vlc.gui.browser import android.content.Intent import android.net.Uri import android.os.Bundle import android.os.Message import android.text.TextUtils import android.util.Log import android.view.* import androidx.appcompat.view.ActionMode import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.lifecycle.Observer import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.google.android.material.snackbar.Snackbar import kotlinx.coroutines.* import org.videolan.medialibrary.MLServiceLocator import org.videolan.medialibrary.interfaces.media.MediaWrapper import org.videolan.medialibrary.media.MediaLibraryItem import org.videolan.resources.* import org.videolan.tools.* import org.videolan.vlc.BuildConfig import org.videolan.vlc.R import org.videolan.vlc.databinding.DirectoryBrowserBinding import org.videolan.vlc.gui.AudioPlayerContainerActivity import org.videolan.vlc.gui.dialogs.CtxActionReceiver import org.videolan.vlc.gui.dialogs.SavePlaylistDialog import org.videolan.vlc.gui.dialogs.showContext import org.videolan.vlc.gui.helpers.MedialibraryUtils import org.videolan.vlc.gui.helpers.UiTools import org.videolan.vlc.gui.helpers.UiTools.addToPlaylist import org.videolan.vlc.gui.helpers.UiTools.addToPlaylistAsync import org.videolan.vlc.gui.helpers.UiTools.showMediaInfo import org.videolan.vlc.gui.helpers.hf.OTG_SCHEME import org.videolan.vlc.gui.view.EmptyLoadingState import org.videolan.vlc.gui.view.VLCDividerItemDecoration import org.videolan.vlc.interfaces.IEventsHandler import org.videolan.vlc.interfaces.IRefreshable import org.videolan.vlc.media.MediaUtils import org.videolan.vlc.media.PlaylistManager import org.videolan.vlc.repository.BrowserFavRepository import org.videolan.vlc.util.Permissions import org.videolan.vlc.util.isSchemeSupported import org.videolan.vlc.viewmodels.browser.BrowserModel import java.util.* private const val TAG = "VLC/BaseBrowserFragment" internal const val KEY_MEDIA = "key_media" private const val KEY_POSITION = "key_list" private const val MSG_SHOW_LOADING = 0 internal const val MSG_HIDE_LOADING = 1 private const val MSG_REFRESH = 3 @ObsoleteCoroutinesApi @ExperimentalCoroutinesApi abstract class BaseBrowserFragment : MediaBrowserFragment<BrowserModel>(), IRefreshable, SwipeRefreshLayout.OnRefreshListener, View.OnClickListener, IEventsHandler<MediaLibraryItem>, CtxActionReceiver, PathAdapterListener, BrowserContainer<MediaLibraryItem> { private lateinit var addPlaylistFolderOnly: MenuItem protected val handler = BrowserFragmentHandler(this) private lateinit var layoutManager: LinearLayoutManager override var mrl: String? = null protected var currentMedia: MediaWrapper? = null private var savedPosition = -1 override var isRootDirectory: Boolean = false override val scannedDirectory = false override val inCards = false protected var showHiddenFiles: Boolean = false protected lateinit var adapter: BaseBrowserAdapter protected abstract val categoryTitle: String protected lateinit var binding: DirectoryBrowserBinding protected lateinit var browserFavRepository: BrowserFavRepository protected abstract fun createFragment(): Fragment protected abstract fun browseRoot() override fun onCreate(bundle: Bundle?) { @Suppress("NAME_SHADOWING") var bundle = bundle super.onCreate(bundle) if (bundle == null) bundle = arguments if (bundle != null) { currentMedia = bundle.getParcelable(KEY_MEDIA) mrl = currentMedia?.location ?: bundle.getString(KEY_MRL) savedPosition = bundle.getInt(KEY_POSITION) } else if (requireActivity().intent != null) { mrl = requireActivity().intent.dataString requireActivity().intent = null } showHiddenFiles = Settings.getInstance(requireContext()).getBoolean("browser_show_hidden_files", false) isRootDirectory = defineIsRoot() browserFavRepository = BrowserFavRepository.getInstance(requireContext()) } override fun onPrepareOptionsMenu(menu: Menu) { super.onPrepareOptionsMenu(menu) menu.findItem(R.id.ml_menu_filter)?.isVisible = enableSearchOption() menu.findItem(R.id.ml_menu_sortby)?.isVisible = !isRootDirectory menu.findItem(R.id.ml_menu_add_playlist)?.isVisible = !isRootDirectory addPlaylistFolderOnly = menu.findItem(R.id.folder_add_playlist) addPlaylistFolderOnly.isVisible = adapter.mediaCount > 0 val browserShowAllFiles = menu.findItem(R.id.browser_show_all_files) browserShowAllFiles.isVisible = true browserShowAllFiles.isChecked = Settings.getInstance(requireActivity()).getBoolean("browser_show_all_files", true) val browserShowHiddenFiles = menu.findItem(R.id.browser_show_hidden_files) browserShowHiddenFiles.isVisible = true browserShowHiddenFiles.isChecked = Settings.getInstance(requireActivity()).getBoolean("browser_show_hidden_files", true) } protected open fun defineIsRoot() = mrl == null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = DirectoryBrowserBinding.inflate(inflater, container, false) return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) if (!this::adapter.isInitialized) adapter = BaseBrowserAdapter(this) layoutManager = LinearLayoutManager(activity) binding.networkList.layoutManager = layoutManager binding.networkList.adapter = adapter registerSwiperRefreshlayout() viewModel.dataset.observe(viewLifecycleOwner, Observer<MutableList<MediaLibraryItem>> { mediaLibraryItems -> adapter.update(mediaLibraryItems!!) if (::addPlaylistFolderOnly.isInitialized) addPlaylistFolderOnly.isVisible = adapter.mediaCount > 0 }) viewModel.getDescriptionUpdate().observe(viewLifecycleOwner, Observer { pair -> if (pair != null) adapter.notifyItemChanged(pair.first, pair.second) }) viewModel.loading.observe(viewLifecycleOwner, Observer { loading -> swipeRefreshLayout.isRefreshing = loading updateEmptyView() }) } open fun registerSwiperRefreshlayout() = swipeRefreshLayout.setOnRefreshListener(this) override fun setBreadcrumb() { val ariane = requireActivity().findViewById<RecyclerView>(R.id.ariane) ?: return val media = currentMedia if (media != null && isSchemeSupported(media.uri?.scheme)) { ariane.visibility = View.VISIBLE ariane.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false) ariane.adapter = PathAdapter(this, media) if (ariane.itemDecorationCount == 0) { ariane.addItemDecoration(VLCDividerItemDecoration(requireContext(), DividerItemDecoration.HORIZONTAL, ContextCompat.getDrawable(requireContext(), R.drawable.ic_divider)!!)) } ariane.scrollToPosition(ariane.adapter!!.itemCount - 1) } else ariane.visibility = View.GONE } override fun backTo(tag: String) { val supportFragmentManager = requireActivity().supportFragmentManager var poped = false for (i in 0 until supportFragmentManager.backStackEntryCount) { if (tag == supportFragmentManager.getBackStackEntryAt(i).name) { supportFragmentManager.popBackStack(tag, FragmentManager.POP_BACK_STACK_INCLUSIVE) poped = true break } } if (!poped) { viewModel.setDestination(MLServiceLocator.getAbstractMediaWrapper(Uri.parse(tag))) supportFragmentManager.popBackStackImmediate() } } override fun currentContext() = requireContext() override fun showRoot() = true override fun getPathOperationDelegate() = viewModel override fun onStart() { super.onStart() fabPlay?.run { setImageResource(R.drawable.ic_fab_play) updateFab() } (activity as? AudioPlayerContainerActivity)?.expandAppBar() } override fun onResume() { super.onResume() viewModel.getAndRemoveDestination()?.let { browse(it, true) } } override fun onStop() { super.onStop() viewModel.stop() } override fun onDestroy() { if (::adapter.isInitialized) adapter.cancel() super.onDestroy() } override fun onSaveInstanceState(outState: Bundle) { outState.putString(KEY_MRL, mrl) outState.putParcelable(KEY_MEDIA, currentMedia) outState.putInt(KEY_POSITION, if (::layoutManager.isInitialized) layoutManager.findFirstCompletelyVisibleItemPosition() else 0) super.onSaveInstanceState(outState) } override fun getTitle(): String = when { isRootDirectory -> categoryTitle currentMedia != null -> currentMedia!!.title else -> mrl ?: "" } override fun getMultiHelper(): MultiSelectHelper<BrowserModel>? = if (::adapter.isInitialized) adapter.multiSelectHelper as? MultiSelectHelper<BrowserModel> else null override val subTitle: String? = if (isRootDirectory) null else { var mrl = mrl?.removeFileProtocole() ?: "" if (!TextUtils.isEmpty(mrl)) { if (this is FileBrowserFragment && mrl.startsWith(AndroidDevices.EXTERNAL_PUBLIC_DIRECTORY)) mrl = getString(R.string.internal_memory) + mrl.substring(AndroidDevices.EXTERNAL_PUBLIC_DIRECTORY.length) mrl = Uri.decode(mrl).replace("://".toRegex(), " ").replace("/".toRegex(), " > ") } if (currentMedia != null) mrl else null } fun goBack(): Boolean { val activity = activity if (activity?.isStarted() != true) return false if (!isRootDirectory && !activity.isFinishing && !activity.isDestroyed) activity.supportFragmentManager.popBackStack() return !isRootDirectory } fun browse(media: MediaWrapper, save: Boolean) { val ctx = activity if (ctx == null || !isResumed || isRemoving) return val ft = ctx.supportFragmentManager.beginTransaction() val next = createFragment() val args = Bundle() viewModel.saveList(media) args.putParcelable(KEY_MEDIA, media) next.arguments = args if (save) ft.addToBackStack(if (isRootDirectory) "root" else if (currentMedia != null) currentMedia?.uri.toString() else mrl!!) if (BuildConfig.DEBUG) for (i in 0 until ctx.supportFragmentManager.backStackEntryCount) { Log.d(this::class.java.simpleName, "Adding to back stack from PathAdapter: ${ctx.supportFragmentManager.getBackStackEntryAt(i).name}") } ft.replace(R.id.fragment_placeholder, next, media.title) ft.commit() } override fun onRefresh() { savedPosition = layoutManager.findFirstCompletelyVisibleItemPosition() viewModel.refresh() } /** * Update views visibility and emptiness info */ protected open fun updateEmptyView() { swipeRefreshLayout.let { when { it.isRefreshing -> { binding.emptyLoading.state = EmptyLoadingState.LOADING binding.networkList.visibility = View.GONE } viewModel.isEmpty() -> { binding.emptyLoading.state = EmptyLoadingState.EMPTY binding.networkList.visibility = View.GONE } else -> { binding.emptyLoading.state = EmptyLoadingState.NONE binding.networkList.visibility = View.VISIBLE } } } } override fun refresh() = viewModel.refresh() override fun onClick(v: View) { when (v.id) { R.id.fab -> playAll(null) } } class BrowserFragmentHandler(owner: BaseBrowserFragment) : WeakHandler<BaseBrowserFragment>(owner) { override fun handleMessage(msg: Message) { val fragment = owner ?: return when (msg.what) { MSG_SHOW_LOADING -> fragment.swipeRefreshLayout.isRefreshing = true MSG_HIDE_LOADING -> { removeMessages(MSG_SHOW_LOADING) fragment.swipeRefreshLayout.isRefreshing = false } MSG_REFRESH -> { removeMessages(MSG_REFRESH) if (!fragment.isDetached) fragment.refresh() } } } } override fun clear() = adapter.clear() override fun removeItem(item: MediaLibraryItem): Boolean { val view = view ?: return false val mw = item as? MediaWrapper ?: return false val cancel = Runnable { viewModel.refresh() } val deleteAction = Runnable { lifecycleScope.launch { MediaUtils.deleteMedia(mw, cancel) viewModel.remove(mw) } } val resId = if (mw.type == MediaWrapper.TYPE_DIR) R.string.confirm_delete_folder else R.string.confirm_delete UiTools.snackerConfirm(view, getString(resId, mw.title), Runnable { if (Permissions.checkWritePermission(requireActivity(), mw, deleteAction)) deleteAction.run() }) return true } private fun playAll(mw: MediaWrapper?) { var positionInPlaylist = 0 val mediaLocations = LinkedList<MediaWrapper>() for (file in viewModel.dataset.getList()) if (file is MediaWrapper) { if (file.type == MediaWrapper.TYPE_VIDEO || file.type == MediaWrapper.TYPE_AUDIO) { mediaLocations.add(file) if (mw != null && file.equals(mw)) positionInPlaylist = mediaLocations.size - 1 } } activity?.let { MediaUtils.openList(it, mediaLocations, positionInPlaylist) } } override fun enableSearchOption() = !isRootDirectory override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { mode.menuInflater.inflate(R.menu.action_mode_browser_file, menu) return true } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { val count = adapter.multiSelectHelper.getSelectionCount() if (count == 0) { stopActionMode() return false } val fileBrowser = this is FileBrowserFragment val single = fileBrowser && count == 1 val selection = if (single) adapter.multiSelectHelper.getSelection() else null val type = if (!selection.isNullOrEmpty()) (selection[0] as MediaWrapper).type else -1 menu.findItem(R.id.action_mode_file_info).isVisible = single && (type == MediaWrapper.TYPE_AUDIO || type == MediaWrapper.TYPE_VIDEO) menu.findItem(R.id.action_mode_file_append).isVisible = PlaylistManager.hasMedia() menu.findItem(R.id.action_mode_file_delete).isVisible = fileBrowser return true } override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { if (!isStarted()) return false val list = adapter.multiSelectHelper.getSelection() as? List<MediaWrapper> ?: return false if (list.isNotEmpty()) { when (item.itemId) { R.id.action_mode_file_play -> MediaUtils.openList(activity, list, 0) R.id.action_mode_file_append -> MediaUtils.appendMedia(activity, list) R.id.action_mode_file_add_playlist -> requireActivity().addToPlaylist(list) R.id.action_mode_file_info -> requireActivity().showMediaInfo(list[0]) R.id.action_mode_file_delete -> removeItems(list) else -> { stopActionMode() return false } } } stopActionMode() return true } override fun onDestroyActionMode(mode: ActionMode?) { actionMode = null adapter.multiSelectHelper.clearSelection() } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.ml_menu_save -> { toggleFavorite() menu?.let { onPrepareOptionsMenu(it) } true } R.id.browser_show_all_files -> { item.isChecked = !Settings.getInstance(requireActivity()).getBoolean("browser_show_all_files", true) Settings.getInstance(requireActivity()).putSingle("browser_show_all_files", item.isChecked) viewModel.updateShowAllFiles(item.isChecked) true } R.id.browser_show_hidden_files -> { item.isChecked = !Settings.getInstance(requireActivity()).getBoolean("browser_show_hidden_files", true) Settings.getInstance(requireActivity()).putSingle("browser_show_hidden_files", item.isChecked) viewModel.updateShowHiddenFiles(item.isChecked) true } R.id.ml_menu_scan -> { currentMedia?.let { media -> addToScannedFolders(media) item.isVisible = false } true } R.id.folder_add_playlist -> { currentMedia?.let { requireActivity().addToPlaylistAsync(it.uri.toString()) } true } R.id.subfolders_add_playlist -> { currentMedia?.let { requireActivity().addToPlaylistAsync(it.uri.toString(), true) } true } else -> super.onOptionsItemSelected(item) } } private fun addToScannedFolders(mw: MediaWrapper) { MedialibraryUtils.addDir(mw.uri.toString(), requireActivity().applicationContext) Snackbar.make(binding.root, getString(R.string.scanned_directory_added, Uri.parse(mw.uri.toString()).lastPathSegment), Snackbar.LENGTH_LONG).show() } private fun toggleFavorite() = lifecycleScope.launch { val mw = currentMedia ?: return@launch when { browserFavRepository.browserFavExists(mw.uri) -> browserFavRepository.deleteBrowserFav(mw.uri) mw.uri.scheme == "file" -> browserFavRepository.addLocalFavItem(mw.uri, mw.title, mw.artworkURL) else -> browserFavRepository.addNetworkFavItem(mw.uri, mw.title, mw.artworkURL) } activity?.invalidateOptionsMenu() } override fun onClick(v: View, position: Int, item: MediaLibraryItem) { val mediaWrapper = item as MediaWrapper if (actionMode != null) { if (mediaWrapper.type == MediaWrapper.TYPE_AUDIO || mediaWrapper.type == MediaWrapper.TYPE_VIDEO || mediaWrapper.type == MediaWrapper.TYPE_DIR) { adapter.multiSelectHelper.toggleSelection(position) invalidateActionMode() } } else { mediaWrapper.removeFlags(MediaWrapper.MEDIA_FORCE_AUDIO) if (mediaWrapper.type == MediaWrapper.TYPE_DIR) browse(mediaWrapper, true) else MediaUtils.openMedia(v.context, mediaWrapper) } } override fun onLongClick(v: View, position: Int, item: MediaLibraryItem): Boolean { if (item.itemType != MediaLibraryItem.TYPE_MEDIA) return false val mediaWrapper = item as MediaWrapper if (mediaWrapper.type == MediaWrapper.TYPE_AUDIO || mediaWrapper.type == MediaWrapper.TYPE_VIDEO || mediaWrapper.type == MediaWrapper.TYPE_DIR) { adapter.multiSelectHelper.toggleSelection(position) if (actionMode == null) startActionMode() } else onCtxClick(v, position, item) return true } override fun onCtxClick(v: View, position: Int, item: MediaLibraryItem) { if (actionMode == null && item.itemType == MediaLibraryItem.TYPE_MEDIA) lifecycleScope.launch { val mw = item as MediaWrapper if (mw.uri.scheme == "content" || mw.uri.scheme == OTG_SCHEME) return@launch var flags = if (!isRootDirectory && this@BaseBrowserFragment is FileBrowserFragment) CTX_DELETE else 0 if (!isRootDirectory && this is FileBrowserFragment) flags = flags or CTX_DELETE if (mw.type == MediaWrapper.TYPE_DIR) { val isEmpty = viewModel.isFolderEmpty(mw) if (!isEmpty) flags = flags or CTX_PLAY val isFileBrowser = this@BaseBrowserFragment is FileBrowserFragment && item.uri.scheme == "file" val isNetworkBrowser = this@BaseBrowserFragment is NetworkBrowserFragment if (isFileBrowser || isNetworkBrowser) { val favExists = browserFavRepository.browserFavExists(mw.uri) flags = if (favExists) { if (isNetworkBrowser) flags or CTX_FAV_EDIT or CTX_FAV_REMOVE else flags or CTX_FAV_REMOVE } else flags or CTX_FAV_ADD } if (isFileBrowser && !isRootDirectory && !MedialibraryUtils.isScanned(item.uri.toString())) { flags = flags or CTX_ADD_SCANNED } if (isFileBrowser) { if (viewModel.provider.hasMedias(mw)) flags = flags or CTX_ADD_FOLDER_PLAYLIST if (viewModel.provider.hasSubfolders(mw)) flags = flags or CTX_ADD_FOLDER_AND_SUB_PLAYLIST } } else { val isVideo = mw.type == MediaWrapper.TYPE_VIDEO val isAudio = mw.type == MediaWrapper.TYPE_AUDIO val isMedia = isVideo || isAudio if (isMedia) flags = flags or CTX_PLAY_ALL or CTX_APPEND or CTX_INFORMATION or CTX_ADD_TO_PLAYLIST if (!isAudio) flags = flags or CTX_PLAY_AS_AUDIO if (isVideo) flags = flags or CTX_DOWNLOAD_SUBTITLES } if (flags != 0L) showContext(requireActivity(), this@BaseBrowserFragment, position, item.getTitle(), flags) } } override fun onCtxAction(position: Int, option: Long) { val mw = adapter.getItem(position) as? MediaWrapper ?: return when (option) { CTX_PLAY -> MediaUtils.openMedia(activity, mw) CTX_PLAY_ALL -> { mw.removeFlags(MediaWrapper.MEDIA_FORCE_AUDIO) playAll(mw) } CTX_APPEND -> MediaUtils.appendMedia(activity, mw) CTX_DELETE -> removeItem(mw) CTX_INFORMATION -> requireActivity().showMediaInfo(mw) CTX_PLAY_AS_AUDIO -> { mw.addFlags(MediaWrapper.MEDIA_FORCE_AUDIO) MediaUtils.openMedia(activity, mw) } CTX_ADD_TO_PLAYLIST -> requireActivity().addToPlaylist(mw.tracks, SavePlaylistDialog.KEY_NEW_TRACKS) CTX_DOWNLOAD_SUBTITLES -> MediaUtils.getSubs(requireActivity(), mw) CTX_FAV_REMOVE -> lifecycleScope.launch(Dispatchers.IO) { browserFavRepository.deleteBrowserFav(mw.uri) } CTX_ADD_SCANNED -> addToScannedFolders(mw) CTX_FIND_METADATA -> { val intent = Intent().apply { setClassName(requireContext().applicationContext, MOVIEPEDIA_ACTIVITY) putExtra(MOVIEPEDIA_MEDIA, mw) } startActivity(intent) } CTX_ADD_FOLDER_PLAYLIST -> { requireActivity().addToPlaylistAsync(mw.uri.toString(), false) } CTX_ADD_FOLDER_AND_SUB_PLAYLIST -> { requireActivity().addToPlaylistAsync(mw.uri.toString(), true) } } } override fun onImageClick(v: View, position: Int, item: MediaLibraryItem) { if (actionMode != null) { onClick(v, position, item) return } onLongClick(v, position, item) } override fun onMainActionClick(v: View, position: Int, item: MediaLibraryItem) {} override fun onUpdateFinished(adapter: RecyclerView.Adapter<*>) { if (!isStarted()) return restoreMultiSelectHelper() swipeRefreshLayout.isRefreshing = false handler.sendEmptyMessage(MSG_HIDE_LOADING) updateEmptyView() if (!viewModel.isEmpty()) { if (savedPosition > 0) { layoutManager.scrollToPositionWithOffset(savedPosition, 0) savedPosition = 0 } } if (!isRootDirectory) { updateFab() UiTools.updateSortTitles(this) } } override fun onItemFocused(v: View, item: MediaLibraryItem) { } private fun updateFab() { fabPlay?.let { if (adapter.mediaCount > 0) { it.show() it.setOnClickListener(this) } else { it.hide() it.setOnClickListener(null) } } } }
gpl-2.0
cded21334a4e4561a0bc84abd269cde1
42.870279
259
0.638844
5.019162
false
false
false
false
QuickBlox/quickblox-android-sdk
sample-conference-kotlin/app/src/main/java/com/quickblox/sample/conference/kotlin/domain/chat/ChatManagerImpl.kt
1
33436
package com.quickblox.sample.conference.kotlin.domain.chat import android.os.Bundle import android.text.TextUtils import androidx.collection.ArraySet import com.quickblox.chat.QBChatService import com.quickblox.chat.exception.QBChatException import com.quickblox.chat.listeners.QBChatDialogMessageListener import com.quickblox.chat.listeners.QBSystemMessageListener import com.quickblox.chat.model.QBAttachment import com.quickblox.chat.model.QBChatDialog import com.quickblox.chat.model.QBChatMessage import com.quickblox.chat.model.QBDialogType import com.quickblox.chat.request.QBDialogRequestBuilder import com.quickblox.chat.request.QBMessageGetBuilder import com.quickblox.content.model.QBFile import com.quickblox.core.request.QBRequestGetBuilder import com.quickblox.sample.conference.kotlin.R import com.quickblox.sample.conference.kotlin.data.DataCallBack import com.quickblox.sample.conference.kotlin.domain.DomainCallback import com.quickblox.sample.conference.kotlin.domain.repositories.chat.ChatRepository import com.quickblox.sample.conference.kotlin.domain.repositories.db.DBRepository import com.quickblox.sample.conference.kotlin.domain.repositories.dialog.DialogRepository import com.quickblox.sample.conference.kotlin.domain.repositories.settings.SettingsRepository import com.quickblox.sample.conference.kotlin.domain.user.USER_DEFAULT_PASSWORD import com.quickblox.sample.conference.kotlin.executor.Executor import com.quickblox.sample.conference.kotlin.executor.ExecutorTask import com.quickblox.sample.conference.kotlin.executor.TaskExistException import com.quickblox.sample.conference.kotlin.presentation.resources.ResourcesManager import com.quickblox.sample.conference.kotlin.presentation.screens.chat.adapters.attachment.AttachmentModel import com.quickblox.sample.conference.kotlin.presentation.screens.main.DIALOGS_LIMIT import com.quickblox.sample.conference.kotlin.presentation.screens.main.EXTRA_SKIP import com.quickblox.sample.conference.kotlin.presentation.screens.main.EXTRA_TOTAL_ENTRIES import com.quickblox.users.model.QBUser import org.jivesoftware.smack.ConnectionListener import org.jivesoftware.smack.SmackException import org.jivesoftware.smack.XMPPConnection import org.jivesoftware.smackx.muc.DiscussionHistory private const val PROPERTY_OCCUPANTS_IDS = "current_occupant_ids" private const val PROPERTY_DIALOG_TYPE = "type" private const val PROPERTY_DIALOG_NAME = "room_name" private const val PROPERTY_NOTIFICATION_TYPE = "notification_type" private const val PROPERTY_NEW_OCCUPANTS_IDS = "new_occupants_ids" const val PROPERTY_CONVERSATION_ID = "conference_id" private const val CREATING_DIALOG = "1" private const val OCCUPANTS_ADDED = "2" private const val OCCUPANT_LEFT = "3" private const val START_CONFERENCE = "4" private const val START_STREAM = "5" private const val LOAD_DIALOGS = "load_dialogs" const val CHAT_HISTORY_ITEMS_PER_PAGE = 50 private const val CHAT_HISTORY_ITEMS_SORT_FIELD = "date_sent" /* * Created by Injoit in 2021-09-30. * Copyright © 2021 Quickblox. All rights reserved. */ class ChatManagerImpl(private val dbRepository: DBRepository, private val dialogRepository: DialogRepository, private val chatRepository: ChatRepository, private val resourcesManager: ResourcesManager, private val executor: Executor, private val settingsRepository: SettingsRepository) : ChatManager { private var chatListeners = hashSetOf<ChatListener>() private var dialogListeners = hashSetOf<DialogListener>() private var systemMessagesListener = SystemMessagesListener() private var dialogsMessageListener = DialogsMessageListener() private var chatMessageListener = ChatMessageListener() private var connectionListener: ChatConnectionListener? = null private var chatService: QBChatService? = QBChatService.getInstance() private val dialogs = arrayListOf<QBChatDialog>() private var totalCount = 0 private var skip = 0 private var connectionChatListeners = hashSetOf<ConnectionChatListener>() override fun subscribeConnectionChatListener(connectionChatListener: ConnectionChatListener) { connectionChatListeners.add(connectionChatListener) } override fun unSubscribeConnectionChatListener(connectionChatListener: ConnectionChatListener) { connectionChatListeners.remove(connectionChatListener) } override fun subscribeDialogListener(dialogListener: DialogListener) { chatService?.systemMessagesManager?.addSystemMessageListener(systemMessagesListener) chatService?.incomingMessagesManager?.addDialogMessageListener(dialogsMessageListener) dialogListeners.add(dialogListener) } override fun unsubscribeDialogListener(dialogListener: DialogListener) { chatService?.systemMessagesManager?.removeSystemMessageListener(systemMessagesListener) chatService?.incomingMessagesManager?.removeDialogMessageListrener(dialogsMessageListener) dialogListeners.remove(dialogListener) } override fun subscribeChatListener(chatListener: ChatListener) { chatService?.incomingMessagesManager?.addDialogMessageListener(chatMessageListener) chatListeners.add(chatListener) } override fun unsubscribeChatListener(chatListener: ChatListener) { chatService?.incomingMessagesManager?.removeDialogMessageListrener(chatMessageListener) chatListeners.remove(chatListener) } private fun addConnectionListener() { if (connectionListener == null) { connectionListener = ChatConnectionListener() chatService?.addConnectionListener(connectionListener) } } private fun removeConnectionListener() { chatService?.removeConnectionListener(connectionListener) connectionListener = null } override fun loadDialogById(dialogId: String, callback: DomainCallback<QBChatDialog, Exception>) { executor.addTask(object : ExecutorTask<QBChatDialog> { override fun backgroundWork(): QBChatDialog { return dialogRepository.getByIdSync(dialogId) } override fun foregroundResult(result: QBChatDialog) { callback.onSuccess(result, null) } override fun onError(exception: Exception) { callback.onError(exception) } }) } override fun createDialog(users: List<QBUser>, chatName: String, callback: DomainCallback<QBChatDialog, Exception>) { val dialog = buildDialog(users, chatName) executor.addTask(object : ExecutorTask<QBChatDialog> { override fun backgroundWork(): QBChatDialog { val createdDialog = dialogRepository.createSync(dialog) val chatMessage = buildMessageCreatedGroupDialog(createdDialog) val systemMessage = buildMessageCreatedGroupDialog(createdDialog) createdDialog.initForChat(chatService) dialogRepository.joinSync(createdDialog) sendSystemMessage(chatMessage, createdDialog.occupants) sendChatMessage(createdDialog, systemMessage) return createdDialog } override fun foregroundResult(result: QBChatDialog) { dialogs.add(result) callback.onSuccess(result, null) } override fun onError(exception: Exception) { callback.onError(exception) } }) } override fun loadMessages(dialog: QBChatDialog, skipPagination: Int, callback: DomainCallback<ArrayList<QBChatMessage>, Exception>) { val messageGetBuilder = QBMessageGetBuilder() messageGetBuilder.skip = skipPagination messageGetBuilder.limit = CHAT_HISTORY_ITEMS_PER_PAGE messageGetBuilder.sortDesc(CHAT_HISTORY_ITEMS_SORT_FIELD) messageGetBuilder.markAsRead(false) executor.addTask(object : ExecutorTask<ArrayList<QBChatMessage>> { override fun backgroundWork(): ArrayList<QBChatMessage> { val result = chatRepository.loadHistorySync(dialog, messageGetBuilder) return result.first } override fun foregroundResult(result: ArrayList<QBChatMessage>) { callback.onSuccess(result, null) } override fun onError(exception: Exception) { callback.onError(exception) } }) } private fun buildDialog(users: List<QBUser>, chatName: String?): QBChatDialog { val userIds: MutableList<Int> = ArrayList() for (user in users) { userIds.add(user.id) } val dialog = QBChatDialog() dialog.name = chatName dialog.type = QBDialogType.GROUP dialog.setOccupantsIds(userIds) return dialog } override fun loginToChat(user: QBUser?, callback: DomainCallback<Unit, Exception>) { if (isLoggedInChat()) { callback.onSuccess(Unit, null) } else { settingsRepository.applyChatSettings() //Need to set password, because the server will not register to chat without password user?.password = USER_DEFAULT_PASSWORD user?.let { executor.addTask(object : ExecutorTask<Unit> { override fun backgroundWork() { QBChatService.getInstance().login(it) } override fun foregroundResult(result: Unit) { chatService = QBChatService.getInstance() addConnectionListener() joinDialogs(dialogs) callback.onSuccess(result, null) } override fun onError(exception: Exception) { callback.onError(exception) } }) } } } override fun loadDialogs(refresh: Boolean, reJoin: Boolean, callback: DomainCallback<ArrayList<QBChatDialog>, Exception>) { if (refresh) { skip = 0 executor.removeTask(LOAD_DIALOGS) } val requestBuilder = QBRequestGetBuilder() requestBuilder.limit = DIALOGS_LIMIT requestBuilder.skip = skip if (skip != 0 && totalCount.minus(skip) == 0) { return } executor.addTaskWithKey(object : ExecutorTask<Pair<ArrayList<QBChatDialog>, Bundle?>> { override fun backgroundWork(): Pair<ArrayList<QBChatDialog>, Bundle?> { return dialogRepository.loadSync(requestBuilder) } override fun foregroundResult(result: Pair<ArrayList<QBChatDialog>, Bundle?>) { totalCount = result.second?.getInt(EXTRA_TOTAL_ENTRIES) ?: 0 skip = result.second?.getInt(EXTRA_SKIP) ?: 0 skip += if (totalCount.minus(skip) < DIALOGS_LIMIT) { totalCount.minus(skip) } else { DIALOGS_LIMIT } if (refresh) { dialogs.clear() } dialogs.addAll(result.first) callback.onSuccess(result.first, null) if (dialogs.isEmpty()) { return } if (isLoggedInChat() && reJoin) { joinDialogs(dialogs) } if (dialogs.size < totalCount) { loadDialogs(false, reJoin, callback) } } override fun onError(exception: Exception) { if (exception is TaskExistException) { // empty } else { callback.onError(exception) } } }, LOAD_DIALOGS) } override fun addUsersToDialog(dialog: QBChatDialog, users: ArraySet<QBUser>, callback: DomainCallback<QBChatDialog?, Exception>) { executor.addTask(object : ExecutorTask<Pair<QBChatDialog?, Bundle>> { override fun backgroundWork(): Pair<QBChatDialog?, Bundle> { val usersIds = arrayListOf<Int>() users.forEach { user -> usersIds.add(user.id) } val message = buildMessageAddedUsers(dialog, occupantsIdsToString(usersIds), dbRepository.getCurrentUser()?.fullName ?: "", getOccupantsNames(users) ?: "" ) val qbRequestBuilder = QBDialogRequestBuilder() qbRequestBuilder.addUsers(*users.toTypedArray()) sendChatMessage(dialog, message) sendSystemMessage(message, usersIds) return dialogRepository.updateSync(dialog, qbRequestBuilder) } override fun foregroundResult(result: Pair<QBChatDialog?, Bundle>) { callback.onSuccess(result.first, result.second) } override fun onError(exception: Exception) { callback.onError(exception) } }) } private fun getOccupantsNames(qbUsers: Collection<QBUser>): String? { val userNameList = arrayListOf<String>() for (user in qbUsers) { if (TextUtils.isEmpty(user.fullName)) { userNameList.add(user.login) } else { userNameList.add(user.fullName) } } return TextUtils.join(", ", userNameList) } private fun occupantsIdsToString(occupantIdsList: Collection<Int>): String { return TextUtils.join(",", occupantIdsList) } private fun sendChatMessage(dialog: QBChatDialog, qbChatMessage: QBChatMessage) { if (dialog.isJoined) { dialog.sendMessage(qbChatMessage) } else { dialogRepository.joinSync(dialog) dialog.sendMessage(qbChatMessage) } } private fun sendSystemMessage(message: QBChatMessage, occupants: List<Int>) { message.setSaveToHistory(false) message.isMarkable = false for (opponentId in occupants) { if (opponentId != dbRepository.getCurrentUser()?.id) { message.recipientId = opponentId chatService?.systemMessagesManager?.sendSystemMessage(message) } } } override fun deleteDialogs(dialogsDelete: ArrayList<QBChatDialog>, qbUser: QBUser, callback: DomainCallback<List<QBChatDialog>, Exception>) { val qbRequestBuilder = QBDialogRequestBuilder() qbRequestBuilder.removeUsers(qbUser) val size = dialogsDelete.size var responseCounter = 0 for (dialog in dialogsDelete) { executor.addTask(object : ExecutorTask<Pair<QBChatDialog?, Bundle>> { override fun backgroundWork(): Pair<QBChatDialog?, Bundle> { val message = buildMessageLeftUser(dialog) sendChatMessage(dialog, message) return dialogRepository.updateSync(dialog, qbRequestBuilder) } override fun foregroundResult(result: Pair<QBChatDialog?, Bundle>) { dialogsDelete.remove(result.first) dialogs.remove(result.first) if (++responseCounter == size) { callback.onSuccess(ArrayList<QBChatDialog>(dialogsDelete), result.second) } } override fun onError(exception: Exception) { if (++responseCounter == size) { callback.onSuccess(ArrayList<QBChatDialog>(dialogsDelete), null) } } }) } } // TODO: 6/9/21 Need to add only 1 logic for leave from dialog override fun leaveDialog(dialog: QBChatDialog, qbUser: QBUser, callback: DomainCallback<QBChatDialog, Exception>) { val qbRequestBuilder = QBDialogRequestBuilder() qbRequestBuilder.removeUsers(qbUser) executor.addTask(object : ExecutorTask<Pair<QBChatDialog?, Bundle>> { override fun backgroundWork(): Pair<QBChatDialog?, Bundle> { val chatMessage = buildMessageLeftUser(dialog) val systemMessage = buildMessageLeftUser(dialog) dialog.leave() sendChatMessage(dialog, chatMessage) sendSystemMessage(systemMessage, dialog.occupants) return dialogRepository.updateSync(dialog, qbRequestBuilder) } override fun foregroundResult(result: Pair<QBChatDialog?, Bundle>) { result.first?.let { callback.onSuccess(it, result.second) } } override fun onError(exception: Exception) { callback.onError(exception) } }) } override fun readMessage(qbChatMessage: QBChatMessage, qbDialog: QBChatDialog, callback: DomainCallback<Unit, Exception>) { executor.addTask(object : ExecutorTask<Unit> { override fun backgroundWork() { return qbDialog.readMessage(qbChatMessage) } override fun foregroundResult(result: Unit) { callback.onSuccess(result, null) } override fun onError(exception: Exception) { callback.onError(exception) } }) } override fun sendCreateConference(dialog: QBChatDialog, callback: DomainCallback<Unit, Exception>) { val message = buildMessageConferenceStarted(dialog) executor.addTask(object : ExecutorTask<Unit> { override fun backgroundWork() { return sendChatMessage(dialog, message) } override fun foregroundResult(result: Unit) { // empty } override fun onError(exception: Exception) { // empty } }) } override fun sendCreateStream(dialog: QBChatDialog, streamId: String, callback: DomainCallback<Unit, Exception>) { val message = buildMessageStreamStarted(dialog, streamId) executor.addTask(object : ExecutorTask<Unit> { override fun backgroundWork() { return sendChatMessage(dialog, message) } override fun foregroundResult(result: Unit) { // empty } override fun onError(exception: Exception) { // empty } }) } override fun sendMessage(currentUser: QBUser, qbDialog: QBChatDialog, text: String, attachmentModels: ArrayList<AttachmentModel>, callback: DomainCallback<Unit, Exception>) { if (isLoggedInChat()) { send(text, qbDialog, attachmentModels, callback) } else { loginToChat(currentUser, object : DomainCallback<Unit, Exception> { override fun onSuccess(result: Unit, bundle: Bundle?) { send(text, qbDialog, attachmentModels, callback) } override fun onError(error: Exception) { callback.onError(error) } }) } } override fun getDialogs(): ArrayList<QBChatDialog> { return dialogs } override fun clearDialogs() { totalCount = 0 skip = 0 dialogs.clear() } private fun send(text: String, qbDialog: QBChatDialog?, attachmentModels: ArrayList<AttachmentModel>, callback: DomainCallback<Unit, Exception>) { qbDialog?.let { dialog -> chatService?.let { qbDialog.initForChat(it) } executor.addTask(object : ExecutorTask<Unit> { override fun backgroundWork() { if (attachmentModels.isNotEmpty()) { for (attachmentModel in attachmentModels) { try { dialog.join(DiscussionHistory()) attachmentModel.qbFile?.let { dialog.sendMessage(buildAttachmentMessage(it)) } attachmentModels.remove(attachmentModel) } catch (exception: Exception) { callback.onError(exception) } } } if (text.isNotEmpty()) { try { dialog.join(DiscussionHistory()) dialog.sendMessage(buildTextMessage(text)) } catch (exception: SmackException.NotConnectedException) { callback.onError(exception) } } return } override fun foregroundResult(result: Unit) { callback.onSuccess(result, null) } override fun onError(exception: Exception) { callback.onError(exception) } }) } } private fun buildMessageAddedUsers(dialog: QBChatDialog?, userIds: String, currentUserName: String, usersNames: String?): QBChatMessage { val qbChatMessage = QBChatMessage() qbChatMessage.dialogId = dialog?.dialogId qbChatMessage.setProperty(PROPERTY_NOTIFICATION_TYPE, OCCUPANTS_ADDED) qbChatMessage.setProperty(PROPERTY_NEW_OCCUPANTS_IDS, userIds) qbChatMessage.body = resourcesManager.get().getString(R.string.occupant_added, currentUserName, usersNames) qbChatMessage.setSaveToHistory(true) qbChatMessage.isMarkable = true return qbChatMessage } private fun buildMessageLeftUser(dialog: QBChatDialog): QBChatMessage { val qbChatMessage = QBChatMessage() qbChatMessage.dialogId = dialog.dialogId qbChatMessage.senderId = dbRepository.getCurrentUser()?.id qbChatMessage.setProperty(PROPERTY_NOTIFICATION_TYPE, OCCUPANT_LEFT) qbChatMessage.body = resourcesManager.get().getString(R.string.occupant_left, dbRepository.getCurrentUser()?.fullName) qbChatMessage.setSaveToHistory(true) qbChatMessage.isMarkable = true return qbChatMessage } private fun buildMessageCreatedGroupDialog(dialog: QBChatDialog): QBChatMessage { val qbChatMessage = QBChatMessage() qbChatMessage.dialogId = dialog.dialogId qbChatMessage.setProperty(PROPERTY_OCCUPANTS_IDS, occupantsIdsToString(dialog.occupants)) qbChatMessage.setProperty(PROPERTY_DIALOG_TYPE, dialog.type.code.toString()) qbChatMessage.setProperty(PROPERTY_DIALOG_NAME, dialog.name.toString()) qbChatMessage.setProperty(PROPERTY_NOTIFICATION_TYPE, CREATING_DIALOG) qbChatMessage.dateSent = System.currentTimeMillis() / 1000 qbChatMessage.body = resourcesManager.get().getString( R.string.new_chat_created, dbRepository.getCurrentUser()?.fullName ?: dbRepository.getCurrentUser()?.login, dialog.name ) qbChatMessage.setSaveToHistory(true) qbChatMessage.isMarkable = true return qbChatMessage } private fun buildAttachmentMessage(qbFile: QBFile): QBChatMessage { val chatMessage = QBChatMessage() chatMessage.addAttachment(buildAttachment(qbFile)) chatMessage.setSaveToHistory(true) chatMessage.dateSent = System.currentTimeMillis() / 1000 chatMessage.isMarkable = true return chatMessage } private fun buildTextMessage(text: String): QBChatMessage { val chatMessage = QBChatMessage() chatMessage.body = text chatMessage.setSaveToHistory(true) chatMessage.dateSent = System.currentTimeMillis() / 1000 chatMessage.isMarkable = true return chatMessage } private fun buildAttachment(qbFile: QBFile): QBAttachment { val type = QBAttachment.IMAGE_TYPE val attachment = QBAttachment(type) attachment.id = qbFile.uid attachment.size = qbFile.size.toDouble() attachment.name = qbFile.name attachment.contentType = qbFile.contentType return attachment } private fun buildMessageConferenceStarted(dialog: QBChatDialog): QBChatMessage { val qbChatMessage = QBChatMessage() qbChatMessage.dialogId = dialog.dialogId qbChatMessage.setProperty(PROPERTY_NOTIFICATION_TYPE, START_CONFERENCE) qbChatMessage.setProperty(PROPERTY_CONVERSATION_ID, dialog.dialogId) qbChatMessage.body = resourcesManager.get().getString(R.string.chat_conversation_started, resourcesManager.get().getString(R.string.conference)) qbChatMessage.setSaveToHistory(true) qbChatMessage.isMarkable = true return qbChatMessage } private fun buildMessageStreamStarted(dialog: QBChatDialog, streamId: String): QBChatMessage { val qbChatMessage = QBChatMessage() qbChatMessage.dialogId = dialog.dialogId qbChatMessage.setProperty(PROPERTY_NOTIFICATION_TYPE, START_STREAM) qbChatMessage.setProperty(PROPERTY_CONVERSATION_ID, streamId) qbChatMessage.body = resourcesManager.get().getString(R.string.started_stream) qbChatMessage.setSaveToHistory(true) qbChatMessage.isMarkable = true return qbChatMessage } override fun destroyChat() { removeConnectionListener() chatService?.destroy() chatService = null } override fun isLoggedInChat(): Boolean { chatService?.let { return it.isLoggedIn } return false } override fun joinDialogs(dialogs: List<QBChatDialog>) { executor.addTask(object : ExecutorTask<Unit> { override fun backgroundWork() { for (dialog in dialogs) { dialogRepository.joinSync(dialog) } } override fun foregroundResult(result: Unit) { // empty } override fun onError(exception: Exception) { // empty } }) } override fun joinDialog(dialog: QBChatDialog, callback: DataCallBack<Unit?, Exception>) { dialog.initForChat(chatService) if (dialog.isJoined) { callback.onSuccess(Unit, null) return } executor.addTask(object : ExecutorTask<Unit> { override fun backgroundWork() { return dialogRepository.joinSync(dialog) } override fun foregroundResult(result: Unit) { callback.onSuccess(result, null) } override fun onError(exception: Exception) { callback.onError(exception) } }) } inner class ChatConnectionListener : ConnectionListener { override fun connected(p0: XMPPConnection?) { //empty } override fun authenticated(p0: XMPPConnection?, p1: Boolean) { //empty } override fun connectionClosed() { chatService = null } override fun connectionClosedOnError(exception: Exception) { connectionChatListeners.forEach { listener -> listener.onError(exception) } } override fun reconnectionSuccessful() { chatService = QBChatService.getInstance() for (dialog in dialogs) { dialog.initForChat(chatService) } joinDialogs(dialogs) connectionChatListeners.forEach { listener -> listener.onConnectedChat() } } override fun reconnectingIn(p0: Int) { //empty } override fun reconnectionFailed(exception: Exception) { connectionChatListeners.forEach { listener -> listener.reconnectionFailed(exception) } chatService = null } } private inner class SystemMessagesListener : QBSystemMessageListener { override fun processMessage(qbChatMessage: QBChatMessage) { executor.addTask(object : ExecutorTask<QBChatDialog> { override fun backgroundWork(): QBChatDialog { // TODO: 5/17/21 Delay for show message try { Thread.sleep(1000) } catch (e: InterruptedException) { e.printStackTrace() } val dialog = dialogRepository.getByIdSync(qbChatMessage.dialogId) if (qbChatMessage.getProperty(PROPERTY_NOTIFICATION_TYPE) == CREATING_DIALOG) { dialogRepository.joinSync(dialog) } return dialog } override fun foregroundResult(result: QBChatDialog) { dialogListeners.forEach { listener -> listener.onUpdatedDialog(result) } } override fun onError(exception: Exception) { dialogListeners.forEach { listener -> listener.onError(exception) } } }) } override fun processError(exception: QBChatException, qbChatMessage: QBChatMessage) { dialogListeners.forEach { listener -> listener.onError(exception) } } } private inner class ChatMessageListener : QBChatDialogMessageListener { override fun processMessage(dialogId: String, chatMessage: QBChatMessage, senderId: Int) { when (chatMessage.getProperty(PROPERTY_NOTIFICATION_TYPE)) { OCCUPANT_LEFT -> { if (dbRepository.getCurrentUser()?.id != senderId) { loadDialogWithJoin(dialogId, chatMessage) } } OCCUPANTS_ADDED -> { loadDialogWithJoin(dialogId, chatMessage) } else -> { chatListeners.forEach { listener -> listener.onReceivedMessage(dialogId, chatMessage, false) } } } } override fun processError(dialogId: String?, exception: QBChatException?, qbChatMessage: QBChatMessage?, userId: Int?) { exception?.message?.let { chatListeners.forEach { listener -> listener.onError(exception) } } } private fun loadDialogWithJoin(dialogId: String, chatMessage: QBChatMessage) { executor.addTask(object : ExecutorTask<Unit> { override fun backgroundWork() { for ((index, dialog) in dialogs.withIndex()) { if (dialog.dialogId == dialogId) { val updatedDialog = dialogRepository.getByIdSync(dialogId) dialogs[index] = updatedDialog dialogRepository.joinSync(updatedDialog) break } } } override fun foregroundResult(result: Unit) { chatListeners.forEach { listener -> listener.onReceivedMessage(dialogId, chatMessage, true) } } override fun onError(exception: Exception) { chatListeners.forEach { listener -> listener.onError(exception) } } }) } } private inner class DialogsMessageListener : QBChatDialogMessageListener { override fun processMessage(dialogId: String, qbChatMessage: QBChatMessage, senderId: Int) { if (qbChatMessage.getProperty(PROPERTY_NOTIFICATION_TYPE) == OCCUPANT_LEFT && senderId == dbRepository.getCurrentUser()?.id) { return } executor.addTask(object : ExecutorTask<QBChatDialog> { override fun backgroundWork(): QBChatDialog { val dialog = dialogRepository.getByIdSync(qbChatMessage.dialogId) dialogRepository.joinSync(dialog) return dialog } override fun foregroundResult(result: QBChatDialog) { dialogListeners.forEach { listener -> listener.onUpdatedDialog(result) } } override fun onError(exception: Exception) { dialogListeners.forEach { listener -> listener.onError(exception) } } }) } override fun processError(dialogId: String?, exception: QBChatException?, qbChatMessage: QBChatMessage?, userId: Int?) { exception?.message?.let { dialogListeners.forEach { listener -> listener.onError(exception) } } } } }
bsd-3-clause
d7185e73d57c9b6ed039a5236bcdf714
39.091127
178
0.612801
5.747808
false
false
false
false
natanieljr/droidmate
project/pcComponents/core/src/test/kotlin/org/droidmate/device/datatypes/UiautomatorWindowDumpTestHelper.kt
1
6987
// DroidMate, an automated execution generator for Android apps. // Copyright (C) 2012-2018. Saarland University // // 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/>. // // Current Maintainers: // Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland> // Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland> // // Former Maintainers: // Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de> // // web: www.droidmate.org package org.droidmate.device.datatypes class UiautomatorWindowDumpTestHelper { // TODO Fix tests /*companion object { private val deviceModel = DeviceModel.buildDefault() //region Fixture dumps @JvmStatic fun newEmptyWindowDump(): UiautomatorWindowDump = UiautomatorWindowDump("", deviceModel.getDeviceDisplayDimensionsForTesting(), deviceModel.getAndroidLauncherPackageName()) @JvmStatic fun newEmptyActivityWindowDump(): UiautomatorWindowDump = UiautomatorWindowDump(windowDump_tsa_emptyAct, deviceModel.getDeviceDisplayDimensionsForTesting(), deviceModel.getAndroidLauncherPackageName()) @JvmStatic fun newAppHasStoppedDialogWindowDump(): UiautomatorWindowDump = UiautomatorWindowDump(windowDump_app_stopped_dialogbox, deviceModel.getDeviceDisplayDimensionsForTesting(), deviceModel.getAndroidLauncherPackageName()) @JvmStatic fun newAppHasStoppedDialogOKDisabledWindowDump(): UiautomatorWindowDump = UiautomatorWindowDump(windowDump_app_stopped_OK_disabled, deviceModel.getDeviceDisplayDimensionsForTesting(), deviceModel.getAndroidLauncherPackageName()) @JvmStatic fun newSelectAHomeAppWindowDump(): UiautomatorWindowDump = UiautomatorWindowDump(windowDump_selectAHomeApp, deviceModel.getDeviceDisplayDimensionsForTesting(), deviceModel.getAndroidLauncherPackageName()) @JvmStatic fun newCompleteActionUsingWindowDump(): UiautomatorWindowDump = UiautomatorWindowDump(windowDump_complActUsing_dialogbox, deviceModel.getDeviceDisplayDimensionsForTesting(), deviceModel.getAndroidLauncherPackageName()) @JvmStatic fun newHomeScreenWindowDump(id: String = ""): UiautomatorWindowDump = UiautomatorWindowDump(windowDump_nexus7_home_screen, deviceModel.getDeviceDisplayDimensionsForTesting(), deviceModel.getAndroidLauncherPackageName(), id) @JvmStatic fun newAppOutOfScopeWindowDump(id: String = ""): UiautomatorWindowDump = UiautomatorWindowDump(windowDump_chrome_offline, deviceModel.getDeviceDisplayDimensionsForTesting(), deviceModel.getAndroidLauncherPackageName(), id) //endregion Fixture dumps @JvmStatic fun newWindowDump(windowHierarchyDump: String): UiautomatorWindowDump = UiautomatorWindowDump(windowHierarchyDump, deviceModel.getDeviceDisplayDimensionsForTesting(), deviceModel.getAndroidLauncherPackageName()) @Suppress("unused") @JvmStatic fun newEmptyActivityWithPackageWindowDump(appPackageName: String): UiautomatorWindowDump { val payload = "" return skeletonWithPayload(topNode(appPackageName, payload)) } @Suppress("unused") @JvmStatic fun new1ButtonWithPackageWindowDump(appPackageName: String): UiautomatorWindowDump = skeletonWithPayload(defaultButtonDump(appPackageName)) @JvmStatic private fun skeletonWithPayload(payload: String, id: String = ""): UiautomatorWindowDump = UiautomatorWindowDump(createDumpSkeleton(payload), deviceModel.getDeviceDisplayDimensionsForTesting(), deviceModel.getAndroidLauncherPackageName(), id) @JvmStatic internal fun createDumpSkeleton(payload: String): String = """<?xml version = '1.0' encoding = 'UTF-8' standalone = 'yes' ?><hierarchy rotation = "0">$payload</hierarchy>""" @JvmStatic private fun topNode(appPackageName: String = apkFixture_simple_packageName, payload: String): String { return """<node index="0" text="" resource-uid="" class="android.widget.FrameLayout" package="$appPackageName" content-contentDesc="" check="false" check="false" clickable="false" enabled="true" focusable="false" focus="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[0,0][800,1205]">$payload</node>""" } @JvmStatic private fun defaultButtonDump(packageName: String = apkFixture_simple_packageName): String { val buttonBounds = createConstantButtonBounds() return createButtonDump(0, "dummyText", buttonBounds, packageName) } @JvmStatic private fun createConstantButtonBounds(): String { val x = 10 val y = 20 val width = 100 val height = 200 return "[$x,$y][${x + width},${y + height}]" } @JvmStatic fun dump(w: Widget): String { val idString = if (w.id.isNotEmpty()) "uid=\"${w.id}\"" else "" return """<node index="${w.index}" text="${w.text}" resource-uid="${w.resourceId}" class="${w.className}" package="${w.packageName}" content-contentDesc="${w.contentDesc}" check="${w.checkable}" check="${w.checked}" clickable="${w.clickable}" enabled="${w.enabled}" focusable="${w.focusable}" focus="${w.focused}" scrollable="${w.scrollable}" long-clickable="${w.longClickable}" password="${w.password}" selected="${w.selected}" bounds="${rectShortString(w.bounds)}" $idString />""" } // WISH deprecated as well as calling methods. Instead, use org.droidmate.test.device.datatypes.UiautomatorWindowDumpTestHelper.dump @JvmStatic private fun createButtonDump(index: Int, text: String, bounds: String, packageName: String = apkFixture_simple_packageName): String = """<node index="$index" text="$text" resource-uid="dummy.package.ExampleApp:uid/button_$text" class="android.widget.Button" package="$packageName" content-contentDesc="" check="false" check="false" clickable="true" enabled="true" focusable="true" focus="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="$bounds"/>""" /** * Returns the same value as {@code android.graphics.Rect.toShortString (java.lang.StringBuilder)} */ @JvmStatic private fun rectShortString(r: Rectangle): String { with(r) { return "[${minX.toInt()},${minY.toInt()}][${maxX.toInt()},${maxY.toInt()}]" } } @JvmStatic fun fromGuiState(guiStatus: IGuiStatus): IDeviceGuiSnapshot { return skeletonWithPayload( guiStatus.widgets.joinToString(System.lineSeparator()) { dump(it) }, guiStatus.id) } }*/ }
gpl-3.0
e13ddc2404a5b0c9c9b3c9bd0fdb8131
39.865497
161
0.7461
4.630219
false
true
false
false
danielgimenes/NasaPicContentFetcher
src/main/java/br/com/dgimenes/nasapiccontentfetcher/DownloadLatestPics.kt
1
12888
package br.com.dgimenes.nasapiccontentfetcher import br.com.dgimenes.nasapiccontentfetcher.service.api.NasaAPODWebservice import br.com.dgimenes.nasapiccontentfetcher.service.api.RetrofitFactory import br.com.dgimenes.nasapicserver.model.SpacePic import br.com.dgimenes.nasapicserver.model.SpacePicSource import br.com.dgimenes.nasapicserver.model.SpacePicStatus import com.cloudinary.Cloudinary import com.cloudinary.Transformation import com.cloudinary.utils.ObjectUtils import org.joda.time.DateTime import org.joda.time.format.DateTimeFormat import java.text.SimpleDateFormat import java.util.* import javax.persistence.Persistence fun main(args: Array<String>) { val program = DownloadLatestPics() try { if (args.size > 0 && args[0] == "test-data") program.insertTestData() else if (args.size > 1 && args[0] == "check-interval") program.downloadLatest(args[1].toInt()) else if (args.size > 1 && args[0] == "set-best") program.downloadAndSetBest(args[1].toString()) else { program.downloadLatest() } program.close() } catch(e: Exception) { e.printStackTrace() program.close() } finally { Thread.sleep(2000) } } class DownloadLatestPics { var em = Persistence.createEntityManagerFactory("primary_pu_dev").createEntityManager() val DATE_FORMAT = "yyyy-MM-dd" val APOD_BASE_URL = "https://api.nasa.gov" val CONFIG_FILE_NAME = "nasapiccontentfetcher.config" var APOD_API_KEY: String? = null var CLOUDINARY_CLOUD_NAME: String? = null var CLOUDINARY_API_KEY: String? = null var CLOUDINARY_API_SECRET: String? = null var cloudinary: Cloudinary? = null fun downloadLatest(checkInterval: Int? = null) { loadConfigurations() println("Fetching pictures metadata...") val spacePics = if (checkInterval != null) downloadLatestAPODsMetadata(checkInterval) else downloadLatestAPODsMetadata() println("SpacePics to persist = ${spacePics.size}") spacePics.forEach { persistNewSpacePic(it) } println("Persisted!") println("Checking SpacePics not published yet...") val spacePicsToPublish = getSpacePicsToPublish() println("Pics to publish = ${spacePicsToPublish.size}") if (spacePicsToPublish.size > 0) { setupCloudinary() println("Preparing and publishing SpacePics...") spacePicsToPublish.map { prepareSpacePicForPublishing(it) } .filterNotNull() .forEach { persistNewSpacePic(it) } } println("All done! Bye") } fun downloadAndSetBest(dateStr: String) { loadConfigurations() println("Fetching picture metadata...") SimpleDateFormat(DATE_FORMAT).parse(dateStr).toString() // just validating val spacePic = downloadAPODMetadata(dateStr) ?: throw RuntimeException("APOD could not be downloaded") spacePic.best = true println("Preparing and publishing SpacePic...") prepareSpacePicForPublishing(spacePic) persistNewSpacePic(spacePic) println("All done! Bye") } private fun loadConfigurations() { val inputStream = this.javaClass.classLoader.getResourceAsStream(CONFIG_FILE_NAME) inputStream ?: throw RuntimeException("Configurations file $CONFIG_FILE_NAME not found!") val properties = Properties() properties.load(inputStream) APOD_API_KEY = properties.get("apod-api-key") as String? CLOUDINARY_CLOUD_NAME = properties.get("cloudinary-cloud-name") as String? CLOUDINARY_API_KEY = properties.get("cloudinary-api-key") as String? CLOUDINARY_API_SECRET = properties.get("cloudinary-api-secret") as String? if (APOD_API_KEY == null || CLOUDINARY_CLOUD_NAME == null || CLOUDINARY_API_KEY == null || CLOUDINARY_API_SECRET == null) { throw RuntimeException("Invalid configurations!") } } private fun setupCloudinary() { val config = HashMap<String, String>() config.put("cloud_name", CLOUDINARY_CLOUD_NAME!!) config.put("api_key", CLOUDINARY_API_KEY!!) config.put("api_secret", CLOUDINARY_API_SECRET!!) cloudinary = Cloudinary(config); } private fun prepareSpacePicForPublishing(spacePic: SpacePic): SpacePic? { println("preparing SpacePic ${DateTime(spacePic.originallyPublishedAt).toString(DATE_FORMAT)}...") spacePic.status = SpacePicStatus.PUBLISHED spacePic.publishedAt = DateTime().toDate() try { val uploadResult = cloudinary?.uploader()?.upload( spacePic.originalApiImageUrl, ObjectUtils.emptyMap()) ?: return null spacePic.hdImageUrl = uploadResult.get("url") as String val resizedUrl = cloudinary?.url()?.transformation( Transformation().width(320).height(320).crop("fill") )?.generate(uploadResult.get("public_id") as String) ?: return null spacePic.previewImageUrl = resizedUrl return spacePic } catch (e: Exception) { e.printStackTrace() return null } } private fun getSpacePicsToPublish(): List<SpacePic> { val toPublishQuery = em.createQuery( "FROM SpacePic WHERE status = :status ORDER BY createdAt DESC") toPublishQuery.setParameter("status", SpacePicStatus.CREATED) return toPublishQuery.resultList as List<SpacePic> } // TODO refator all APOD-related logic to a different // class as soon as there are other SpacePic sources private fun downloadLatestAPODsMetadata(checkInterval: Int = 3): List<SpacePic> { println("=== APOD ===") println("checkInterval = $checkInterval") println("Checking for already downloaded APOD pictures...") val daysToFetch = getDaysThatNeedToFetchAPOD(checkInterval) val spacePics = daysToFetch.map { downloadAPODMetadata(it) }.filterNotNull() return spacePics } private fun downloadAPODMetadata(dayString: String): SpacePic? { println("Downloading APOD metadata of $dayString") val apodWebService = RetrofitFactory.get(APOD_BASE_URL) .create(NasaAPODWebservice::class.java) val response = apodWebService.getAPOD(APOD_API_KEY!!, false, dayString).execute() if (!response.isSuccess) { println("url ${response.raw().request().urlString()}") println(response.errorBody().string()) return null } val apod = response.body() val spacePic = SpacePic( originalApiUrl = response.raw().request().urlString(), originalApiImageUrl = apod.hdUrl ?: apod.url, originallyPublishedAt = DateTimeFormat.forPattern(DATE_FORMAT) .parseDateTime(dayString).toDate(), title = apod.title, createdAt = DateTime().toDate(), status = SpacePicStatus.CREATED, source = SpacePicSource.NASA_APOD, description = apod.explanation, hdImageUrl = "", previewImageUrl = "", publishedAt = null, deletedAt = null, updatedAt = null ) if (apod.mediaType != "image") { spacePic.status = SpacePicStatus.DELETED spacePic.deletedAt = DateTime().toDate() } return spacePic } private fun getDaysThatNeedToFetchAPOD(checkInterval: Int): Set<String> { val startDate = DateTime().minusDays(checkInterval - 1) .withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0) val latestQuery = em.createQuery( """ FROM SpacePic WHERE source = :source AND originallyPublishedAt >= :originallyPublishedAt ORDER BY originallyPublishedAt DESC """) latestQuery.setParameter("source", SpacePicSource.NASA_APOD) latestQuery.setParameter("originallyPublishedAt", startDate.toDate()) val latestPersistedAPODs = latestQuery.resultList as List<SpacePic> val daysAlreadyFetchedAsDateStrings = latestPersistedAPODs.map { DateTime(it.originallyPublishedAt).toString(DATE_FORMAT) }.toSet() println("daysAlreadyFetched = $daysAlreadyFetchedAsDateStrings") val daysThatShouldBeFetchedAsDateStrings = intervalToListOfDateStrings(startDate, DateTime()) println("daysThatShouldBeFetched = $daysThatShouldBeFetchedAsDateStrings") val daysToFetch = daysThatShouldBeFetchedAsDateStrings.minus(daysAlreadyFetchedAsDateStrings) println("daysToFetch = $daysToFetch") return daysToFetch } // TODO refactor private fun intervalToListOfDateStrings(startDate: DateTime, endDate: DateTime): Set<String> { var dateStrings = linkedSetOf<String>() var currDate = startDate while (currDate <= endDate) { dateStrings.add(currDate.toString(DATE_FORMAT)) currDate = currDate.plusDays(1) } return dateStrings } private fun persistNewSpacePic(spacePic: SpacePic) { em.transaction.begin() em.persist(spacePic) em.transaction.commit() } fun insertTestData() { val spacePics = getTestSpacePics() spacePics.forEach { persistNewSpacePic(it) } } private fun getTestSpacePics(): List<SpacePic> { val unpublishedSpacePic = SpacePic( originalApiUrl = "https://api.nasa.gov/planetary/apod?concept_tags=True&api_key=DEMO_KEY", originalApiImageUrl = "http://apod.nasa.gov/apod/image/1512/Refsdal_Hubble_1080.jpg", originallyPublishedAt = DateTime().toDate(), title = "SN Refsdal: The First Predicted Supernova Image", createdAt = DateTime().toDate(), status = SpacePicStatus.CREATED, source = SpacePicSource.NASA_APOD ) val spacePic = SpacePic( originalApiUrl = "https://api.nasa.gov/planetary/apod?concept_tags=True&api_key=DEMO_KEY", originalApiImageUrl = "http://apod.nasa.gov/apod/image/1512/Refsdal_Hubble_1080.jpg", originallyPublishedAt = DateTime().toDate(), title = "SN Refsdal: The First Predicted Supernova Image", createdAt = DateTime().toDate(), status = SpacePicStatus.PUBLISHED, source = SpacePicSource.NASA_APOD, description = "It's back. Never before has an observed supernova been predicted. " + "The unique astronomical event occurred in the field of galaxy cluster MACS J1149.5+2223. " + "Most bright spots in the featured image are galaxies in this cluster. The actual " + "supernova, dubbed Supernova Refsdal, occurred just once far across the universe and well " + "behind this massive galaxy cluster. Gravity caused the cluster to act as a massive " + "gravitational lens, splitting the image of Supernova Refsdal into multiple bright images. " + "One of these images arrived at Earth about ten years ago, likely in the upper red circle, " + "and was missed. Four more bright images peaked in April in the lowest red circle, spread " + "around a massive galaxy in the cluster as the first Einstein Cross supernova. But there " + "was more. Analyses revealed that a sixth bright supernova image was likely still on its " + "way to Earth and likely to arrive within the next year. Earlier this month -- right on " + "schedule -- this sixth bright image was recovered, in the middle red circle, as predicted. " + " Studying image sequences like this help humanity to understand how matter is distributed " + "in galaxies and clusters, how fast the universe expands, and how massive stars explode. " + " Follow APOD on: Facebook, Google Plus, or Twitter", hdImageUrl = "", previewImageUrl = "", publishedAt = DateTime().toDate(), deletedAt = null, updatedAt = DateTime().toDate() ) return listOf(spacePic, unpublishedSpacePic) } fun close() { if (em.isOpen) { em.entityManagerFactory.close() } } }
mit
a52ead1ae0ae59117b4661dcfe457262
44.540636
119
0.628181
4.924723
false
true
false
false
nickthecoder/paratask
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/project/HalfTab_Impl.kt
1
9761
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.project import javafx.css.Styleable import javafx.geometry.Side import javafx.scene.Node import javafx.scene.control.Button import javafx.scene.control.ContextMenu import javafx.scene.control.TextField import javafx.scene.control.ToolBar import javafx.scene.input.KeyEvent import javafx.scene.input.MouseEvent import javafx.scene.layout.BorderPane import javafx.scene.layout.StackPane import uk.co.nickthecoder.paratask.ParaTaskApp import uk.co.nickthecoder.paratask.SidePanel import uk.co.nickthecoder.paratask.Tool import uk.co.nickthecoder.paratask.gui.CompoundButtons import uk.co.nickthecoder.paratask.gui.MySplitPane import uk.co.nickthecoder.paratask.gui.ShortcutHelper import uk.co.nickthecoder.paratask.util.RequestFocus import uk.co.nickthecoder.paratask.util.Stoppable class HalfTab_Impl(override var toolPane: ToolPane) : MySplitPane(), HalfTab { val mainArea = BorderPane() override val toolBars = BorderPane() private val toolBar = ToolBar() private val shortcuts = ShortcutHelper("HalfTab", this) override val optionsField = TextField() override lateinit var projectTab: ProjectTab val stopButton: Button val runButton: Button override val history = History(this) val optionsContextMenu = ContextMenu() var sidePanel: SidePanel? = null set(v) { if (right != null && left is Styleable) { (left as Styleable).styleClass.remove("sidebar") } if (v == null) { right = null left = mainArea } else { left = v.node right = mainArea if (v is Styleable) { v.styleClass.add("sidebar") } } field = v } val sidePanelToggleButton = ParataskActions.SIDE_PANEL_TOGGLE.createButton(shortcuts) { toggleSidePanel() } init { this.dividerRatio = 0.3 toolBars.center = toolBar toolBar.styleClass.add("bottom") left = mainArea with(mainArea) { center = toolPane as Node bottom = toolBars } with(optionsField) { prefColumnCount = 6 addEventHandler(KeyEvent.KEY_PRESSED, { optionsFieldKeyPressed(it) }) addEventHandler(MouseEvent.MOUSE_PRESSED, { optionFieldMouse(it) }) addEventHandler(MouseEvent.MOUSE_RELEASED, { optionFieldMouse(it) }) contextMenu = optionsContextMenu } val historyGroup = CompoundButtons() val backButton = ParataskActions.HISTORY_BACK.createButton(shortcuts) { history.undo() } val forwardButton = ParataskActions.HISTORY_FORWARD.createButton(shortcuts) { history.redo() } backButton.disableProperty().bind(history.canUndoProperty.not()) forwardButton.disableProperty().bind(history.canRedoProperty.not()) historyGroup.children.addAll(backButton, forwardButton) val runStopStack = StackPane() stopButton = ParataskActions.TOOL_STOP.createButton(shortcuts) { onStop() } runButton = ParataskActions.TOOL_RUN.createButton(shortcuts) { onRun() } runStopStack.children.addAll(stopButton, runButton) sidePanelToggleButton.isDisable = !toolPane.tool.hasSidePanel toolBar.items.addAll( optionsField, runStopStack, ParataskActions.TOOL_SELECT.createToolButton(shortcuts) { tool -> onSelectTool(tool) }, historyGroup, sidePanelToggleButton, ParataskActions.TAB_SPLIT_TOGGLE.createButton(shortcuts) { projectTab.splitToggle() }, ParataskActions.TAB_MERGE_TOGGLE.createButton(shortcuts) { projectTab.mergeToggle() }, ParataskActions.TOOL_CLOSE.createButton(shortcuts) { close() }) bindButtons() shortcuts.add(ParataskActions.PARAMETERS_SHOW) { onShowParameters() } shortcuts.add(ParataskActions.RESULTS_SHOW) { onShowResults() } shortcuts.add(ParataskActions.RESULTS_TAB_CLOSE) { onCloseResults() } } override fun attached(projectTab: ProjectTab) { this.projectTab = projectTab ParaTaskApp.logAttach("HalfTab.attaching ToolPane") toolPane.attached(this) ParaTaskApp.logAttach("HalfTab.attached ToolPane") } override fun detaching() { ParaTaskApp.logAttach("HalfTab.detaching ToolPane") toolPane.detaching() mainArea.center = null mainArea.bottom = null left = null right = null toolBars.children.clear() toolBar.items.clear() shortcuts.clear() optionsContextMenu.items.clear() ParaTaskApp.logAttach("HalfTab.detached ToolPane") } override fun isLeft() = projectTab.left === this override fun otherHalf(): HalfTab? { if (isLeft()) { return projectTab.right } else { return projectTab.left } } fun bindButtons() { runButton.disableProperty().bind(toolPane.tool.taskRunner.disableRunProperty) runButton.visibleProperty().bind(toolPane.tool.taskRunner.showRunProperty) stopButton.visibleProperty().bind(toolPane.tool.taskRunner.showStopProperty) } override fun changeTool(tool: Tool, prompt: Boolean) { val showSidePanel = right != null sidePanel = null toolPane.detaching() children.remove(toolPane as Node) toolPane = ToolPane_Impl(tool) mainArea.center = toolPane as Node toolPane.attached(this) projectTab.changed() bindButtons() history.push(tool) if (!prompt) { try { tool.check() } catch(e: Exception) { return } toolPane.parametersPane.run() } sidePanelToggleButton.isDisable = !tool.hasSidePanel if (tool.hasSidePanel && showSidePanel) { toggleSidePanel() } } override fun onStop() { val tool = toolPane.tool if (tool is Stoppable) { tool.stop() } } override fun onRun() { toolPane.parametersPane.run() } fun onSelectTool(tool: Tool) { val newTool = tool.copy() newTool.resolveParameters(projectTab.projectTabs.projectWindow.project.resolver) changeTool(newTool) } override fun close() { projectTab.remove(toolPane) } override fun pushHistory() { history.push(toolPane.tool) } override fun pushHistory(tool: Tool) { history.push(tool) } fun optionsFieldKeyPressed(event: KeyEvent) { var done = false val tool = toolPane.resultsTool() val runner = tool.optionsRunner if (ParataskActions.OPTION_RUN.match(event)) { done = runner.runNonRow(optionsField.text, prompt = false, newTab = false) } else if (ParataskActions.OPTION_RUN_NEW_TAB.match(event)) { done = runner.runNonRow(optionsField.text, prompt = false, newTab = true) } else if (ParataskActions.OPTION_PROMPT.match(event)) { done = runner.runNonRow(optionsField.text, prompt = true, newTab = false) } else if (ParataskActions.OPTION_PROMPT_NEW_TAB.match(event)) { done = runner.runNonRow(optionsField.text, prompt = true, newTab = true) } else if (ParataskActions.CONTEXT_MENU.match(event)) { onOptionsContextMenu() event.consume() } if (done) { optionsField.text = "" } } fun optionFieldMouse(event: MouseEvent) { if (event.isPopupTrigger) { onOptionsContextMenu() event.consume() } } private fun onOptionsContextMenu() { val tool = toolPane.resultsTool() tool.optionsRunner.createNonRowOptionsMenu(optionsContextMenu) optionsContextMenu.show(optionsField, Side.BOTTOM, 0.0, 0.0) } fun onShowParameters() { toolPane.parametersTab.isSelected = true } fun onShowResults() { toolPane.tabPane.selectionModel.select(0) } fun onCloseResults() { val minorTab = toolPane.tabPane.selectedTab if (minorTab != null && minorTab.canClose && minorTab is ResultsTab) { minorTab.close() if ( toolPane.tabPane.tabs.filterIsInstance<ResultsTab>().isEmpty() ) { close() } } } override fun focusOption() { ParaTaskApp.logFocus("HalfTab_Impl focusOption. RequestFocus.requestFocus(optionsField)") RequestFocus.requestFocus(optionsField) } override fun focusOtherHalf() { val other = if (projectTab.left === this) projectTab.right else projectTab.left other?.toolPane?.focusResults() } fun toggleSidePanel() { if (sidePanel == null) { sidePanel = toolPane.tool.getSidePanel() } else { sidePanel = null } } }
gpl-3.0
2278974e6b905583f64a45f71db87729
30.487097
111
0.642352
4.710907
false
false
false
false
soniccat/android-taskmanager
taskmanager/src/main/java/com/example/alexeyglushkov/taskmanager/SimpleTaskManager.kt
1
21814
package com.example.alexeyglushkov.taskmanager import android.os.Handler import android.os.HandlerThread import android.os.Looper import android.util.Log import androidx.annotation.WorkerThread import com.example.alexeyglushkov.streamlib.progress.ProgressListener import com.example.alexeyglushkov.taskmanager.coordinators.TaskManagerCoordinator import com.example.alexeyglushkov.taskmanager.pool.ListTaskPool import com.example.alexeyglushkov.taskmanager.pool.TaskPool import com.example.alexeyglushkov.taskmanager.providers.PriorityTaskProvider import com.example.alexeyglushkov.taskmanager.providers.TaskProvider import com.example.alexeyglushkov.taskmanager.providers.TaskProviders import com.example.alexeyglushkov.taskmanager.runners.InstantThreadRunner import com.example.alexeyglushkov.taskmanager.runners.ScopeThreadRunner import com.example.alexeyglushkov.taskmanager.runners.ThreadRunner import com.example.alexeyglushkov.taskmanager.task.* import com.example.alexeyglushkov.taskmanager.tools.* import com.example.alexeyglushkov.tools.CancelError import com.example.alexeyglushkov.tools.HandlerTools import org.junit.Assert import java.lang.ref.WeakReference import java.util.ArrayList import java.util.Comparator import java.util.Date import kotlinx.coroutines.* import kotlinx.coroutines.android.asCoroutineDispatcher /** * Created by alexeyglushkov on 20.09.14. */ open class SimpleTaskManager : TaskManager, TaskPool.Listener { companion object { internal val TAG = "SimpleTaskManager" const val WaitingTaskProviderId = "WaitingTaskProviderId" } var _threadRunner: ThreadRunner = InstantThreadRunner() // TODO: try to use channel instead of a single thread override var threadRunner: ThreadRunner get() = _threadRunner set(value) { _threadRunner = value loadingTasks.threadRunner = value for (provider in _taskProviders) { provider.threadRunner = value } } private lateinit var callbackHandler: Handler override var userData: Any? = null private var listeners = WeakRefList<TaskManager.Listener>() private var _taskScope: CoroutineScope? = null private var taskScope: CoroutineScope get() = _taskScope!! set(value) { _taskScope = value } private lateinit var loadingTasks: TaskPool private lateinit var waitingTasks: TaskProvider private var taskToJobMap = HashMap<Task, Job>() // TODO: check out how we can avoid using SafeList or another solution // TODO: think about weakref private lateinit var _taskProviders: SafeList<TaskProvider> override val taskProviders: List<TaskProvider> get() { return if (threadRunner.isOnThread()) _taskProviders.originalList else _taskProviders.safeList } private lateinit var _coordinator: TaskManagerCoordinator override var taskManagerCoordinator: TaskManagerCoordinator set(value) { // it's experimental // TODO: need to handle it properly setupCoordinator(value) } get() = _coordinator override fun getLoadingTaskCount(): Int { return loadingTasks.getTaskCount() } @WorkerThread override fun getTaskCount(): Int { return threadRunner.run { var taskCount = loadingTasks.getTaskCount() for (provider in _taskProviders) { taskCount += provider.getTaskCount() } return@run taskCount } } @WorkerThread override fun getTasks(): List<Task> { val tasks = ArrayList<Task>() tasks.addAll(loadingTasks.getTasks()) for (provider in _taskProviders) { tasks.addAll(provider.getTasks()) } return tasks } constructor(inCoordinator: TaskManagerCoordinator) { init(inCoordinator, null, null) } constructor(inCoordinator: TaskManagerCoordinator, scope: CoroutineScope, taskScope: CoroutineScope) { init(inCoordinator, scope, taskScope) } private fun init(inCoordinator: TaskManagerCoordinator, inScope: CoroutineScope?, inTaskScope: CoroutineScope?) { initScope(inScope) initTaskSope(inTaskScope) setupCoordinator(inCoordinator) callbackHandler = Handler(Looper.myLooper()) loadingTasks = ListTaskPool(threadRunner) loadingTasks.addListener(this) _taskProviders = createTaskProviders() createWaitingTaskProvider() } private fun initScope(inScope: CoroutineScope?) { val scope = if (inScope != null) { inScope } else { val localHandlerThread = HandlerThread("SimpleTaskManager Thread") localHandlerThread.start() val handler = Handler(localHandlerThread.looper) val dispatcher = handler.asCoroutineDispatcher("SimpleTaskManager handler dispatcher") CoroutineScope(dispatcher + SupervisorJob()) } _threadRunner = ScopeThreadRunner(scope, "SimpleTaskManagerScopeTheadId") scope.launch { threadRunner.setup() } } private fun setupCoordinator(aCooridinator: TaskManagerCoordinator) { _coordinator = aCooridinator _coordinator.threadRunner = threadRunner } private fun initTaskSope(inScope: CoroutineScope?) { taskScope = inScope ?: CoroutineScope(Dispatchers.IO + SupervisorJob()) } private fun createTaskProviders(): SafeList<TaskProvider> { val sortedList = SortedList(Comparator<TaskProvider> { lhs, rhs -> if (lhs.priority == rhs.priority) { return@Comparator 0 } if (lhs.priority > rhs.priority) { -1 } else 1 }) return SafeList(sortedList, callbackHandler) } private fun createWaitingTaskProvider() { waitingTasks = PriorityTaskProvider(threadRunner, WaitingTaskProviderId) waitingTasks.addListener(this) _taskProviders.add(waitingTasks) } override fun addTask(task: Task) { if (task !is TaskBase) { assert(false); return } if (TaskProviders.addTaskCheck(task, TAG)) { threadRunner.launch { // task will be launched in onTaskAdded method waitingTasks.addTask(task) } } } override fun startImmediately(task: Task) { threadRunner.launchSuspend { if (handleTaskLoadPolicy(task, null)) { startTaskOnThread(task) } } } override fun cancel(task: Task, info: Any?) { threadRunner.launch { cancelTaskOnThread(task, info) } } override fun addTaskProvider(provider: TaskProvider) { Assert.assertEquals(provider.threadRunner, threadRunner) Assert.assertNotNull(provider.taskProviderId) threadRunner.launch { addTaskProviderOnThread(provider) } } @WorkerThread private fun addTaskProviderOnThread(provider: TaskProvider) { threadRunner.checkThread() val oldTaskProvider = getTaskProvider(provider.taskProviderId) if (oldTaskProvider != null) { removeTaskProviderOnThread(oldTaskProvider) } provider.addListener(this) _taskProviders.add(provider) provider.taskFilter = taskManagerCoordinator.taskFilter } override fun setTaskProviderPriority(provider: TaskProvider, priority: Int) { threadRunner.launch { setTaskProviderPriorityOnThread(provider, priority) } } @WorkerThread private fun setTaskProviderPriorityOnThread(provider: TaskProvider, priority: Int) { threadRunner.checkThread() provider.priority = priority (_taskProviders.originalList as SortedList<*>).updateSortedOrder() } override fun getTaskProvider(id: String): TaskProvider? { return findProvider(taskProviders, id) } private fun findProvider(providers: List<TaskProvider>, id: String): TaskProvider? { for (taskProvider in providers) { if (taskProvider.taskProviderId == id) { return taskProvider } } return null } // == TaskPool.TaskPoolListener @WorkerThread override fun onTaskConflict(pool: TaskPool, newTask: Task, oldTask: Task): Task { threadRunner.checkThread() Assert.assertTrue(pool != loadingTasks) return threadRunner.run { resolveTaskConflict(newTask, oldTask) } } @WorkerThread override fun onTaskAdded(pool: TaskPool, task: Task) { threadRunner.launch { val isLoadingPool = pool === loadingTasks if (isLoadingPool) { taskManagerCoordinator.onTaskStartedLoading(pool, task) } logTask(task, "onTaskAdded $isLoadingPool") triggerOnTaskAddedOnThread(task, isLoadingPool) if (!isLoadingPool) { if (handleTaskLoadPolicy(task, pool)) { checkTasksToRunOnThread() } } } } @WorkerThread override fun onTaskRemoved(pool: TaskPool, task: Task) { threadRunner.launch { val isLoadingPool = pool === loadingTasks if (isLoadingPool) { taskManagerCoordinator.onTaskFinishedLoading(pool, task) } logTask(task, "onTaskRemoved $isLoadingPool") triggerOnTaskRemovedOnThread(task, isLoadingPool) } } @WorkerThread override fun onTaskCancelled(pool: TaskPool, task: Task, info: Any?) { threadRunner.launch { cancelTaskOnThread(task, info) } } // == TaskPool interface override fun cancelTask(task: Task, info: Any?) { cancel(task, info) } override fun removeTask(task: Task) { cancel(task, null) } @WorkerThread override fun getTask(taskId: String): Task? { threadRunner.checkThread() return threadRunner.run { var task: Task? = loadingTasks.getTask(taskId) if (task == null) { for (provider in _taskProviders) { task = provider.getTask(taskId) if (task != null) { break } } } return@run task } } override fun removeListener(listener: TaskManager.Listener) { listeners.removeValue(listener) } override fun addListener(listener: TaskManager.Listener) { listeners.add(WeakReference(listener)) } override fun addListener(listener: TaskPool.Listener) { //unnecessary } override fun removeListener(listener: TaskPool.Listener) { //unnecessary } override fun onTaskStatusChanged(task: Task, oldStatus: Task.Status, newStatus: Task.Status) { //unnecessary } @WorkerThread private fun triggerOnTaskAddedOnThread(task: Task, isLoadingQueue: Boolean) { threadRunner.checkThread() for (listener in listeners) { listener.get()?.onTaskAdded(this, task, isLoadingQueue) } } @WorkerThread private fun triggerOnTaskRemovedOnThread(task: Task, isLoadingQueue: Boolean) { threadRunner.checkThread() for (listener in listeners) { listener.get()?.onTaskRemoved(this, task, isLoadingQueue) } } @WorkerThread private fun triggerOnTaskStatusChangedOnThread(task: Task, oldStatus: Task.Status) { threadRunner.checkThread() for (listener in listeners) { listener.get()?.onTaskStatusChanged(task, oldStatus) } } // == override fun removeTaskProvider(provider: TaskProvider) { threadRunner.launch { removeTaskProviderOnThread(provider) } } @WorkerThread private fun removeTaskProviderOnThread(provider: TaskProvider) { threadRunner.checkThread() // cancel all tasks for (task in ArrayList(provider.getTasks())) { cancelTaskOnThread(task, null) } _taskProviders.remove(provider) provider.taskFilter = null } fun setWaitingTaskProvider(provider: TaskProvider) { Assert.assertEquals(provider.threadRunner, threadRunner) provider.taskProviderId = WaitingTaskProviderId addTaskProvider(provider) } // Private // returns true when load policy checks pass @WorkerThread private fun handleTaskLoadPolicy(newTask: Task, taskPool: TaskPool?): Boolean { threadRunner.checkThread() if (newTask.isBlocked()) { return false } val taskId = newTask.taskId if (taskId != null) { val pools = ArrayList<TaskPool>(taskProviders) + loadingTasks for (pool in pools) { if (pool != taskPool) { val oldTask = pool.getTask(taskId) if (oldTask != null) { assert(oldTask != newTask) val resultTask = resolveTaskConflict(newTask, oldTask) if (resultTask == oldTask) { return false // quit when task fails } } } if (newTask.isBlocked()) { return false } } } return true } // returns newTask if we allow adding it in a provider @WorkerThread private fun resolveTaskConflict(newTask: Task, currentTask: Task): Task { threadRunner.checkThread() return when (newTask.loadPolicy) { Task.LoadPolicy.AddDependencyIfAlreadyAdded -> { logTask(newTask, "Conflict: wait until the current task finishes") logTask(currentTask, "Conflict: the current task") // TODO: we need to call addTaskDependency for all other tasks with this id or probably create a list to store all such dependant tasks newTask.addTaskDependency(currentTask) newTask } Task.LoadPolicy.CompleteWhenAlreadyAddedCompletes -> { logTask(newTask, "Conflict: this task will complete with the current task") logTask(currentTask, "Conflict: the current task") connectTaskCompletions(newTask, currentTask) newTask } Task.LoadPolicy.CancelPreviouslyAdded -> { logTask(currentTask, "Conflict: this current task is cancelled") logTask(newTask, "Conflict: the new task") cancelTaskOnThread(currentTask, null) newTask } Task.LoadPolicy.SkipIfAlreadyAdded -> { logTask(newTask, "Conflict: this task was skipped as there is another task already") logTask(currentTask, "Conflict: another task") cancelTaskOnThread(newTask, null) currentTask } } } // completes aTask when toTask completes with setting taskResult // syncs progress state too @WorkerThread private fun connectTaskCompletions(newTask: Task, currentTask: Task) { addTaskBlockedDependency(newTask, currentTask) currentTask.addTaskProgressListener(ProgressListener { _, progressInfo -> progressInfo?.let { newTask as TaskBase newTask.private.triggerProgressListeners(progressInfo) } }) currentTask.addTaskStatusListener(object : Task.StatusListener { override fun onTaskStatusChanged(task: Task, oldStatus: Task.Status, newStatus: Task.Status) { if (task.isFinished()) { currentTask.removeTaskStatusListener(this) if (task.taskStatus != Task.Status.Cancelled) { newTask as TaskBase newTask.private.taskResult = currentTask.taskResult handleTaskFinishOnThread(newTask, false) } else { setTaskStatus(newTask, Task.Status.Waiting) } } } }) } @WorkerThread private fun addTaskBlockedDependency(newTask: Task, currentTask: Task) { setTaskStatus(newTask, Task.Status.Blocked) newTask.addTaskDependency(currentTask) } private fun setTaskStatus(task: Task, status: Task.Status) { val oldStatus = task.taskStatus task as TaskBase task.private.taskStatus = status threadRunner.launch { triggerOnTaskStatusChangedOnThread(task, oldStatus) } } @WorkerThread private fun checkTasksToRunOnThread() { threadRunner.checkThread() threadRunner.launchSuspend { if (taskManagerCoordinator.canAddMoreTasks()) { val task = takeTaskToRunOnThread() if (task != null) { logTask(task, "Have taken task") startTaskOnThread(task) } } } } @WorkerThread private fun takeTaskToRunOnThread(): Task? { threadRunner.checkThread() var topTaskProvider: TaskProvider? = null var topPriorityTask: Task? = null var topPriority = -1 for (provider in _taskProviders) { val t = provider.getTopTask() if (t != null && t.taskPriority > topPriority) { topPriorityTask = t topPriority = t.taskPriority topTaskProvider = provider } } return if (topTaskProvider != null && topPriorityTask != null) { topTaskProvider.takeTopTask() } else { null } } @WorkerThread private suspend fun startTaskOnThread(task: Task) { if (task !is TaskBase) { assert(false); return } threadRunner.checkThread() Assert.assertTrue(task.isReadyToStart()) logTask(task, "Task started") setTaskStatus(task, Task.Status.Started) task.private.setTaskStartDate(Date()) addLoadingTaskOnThread(task) val job = SupervisorJob() taskToJobMap[task] = job var isCancelled = false withContext(taskScope.coroutineContext + job) { try { task.startTask() } catch (e: Throwable) { isCancelled = job.isCancelled } } logTask(task, "Task onCompleted" + if (isCancelled) " (Cancelled)" else "") taskToJobMap.remove(task) if (!isCancelled) { handleTaskFinishOnThread(task, false) } } @WorkerThread private fun addLoadingTaskOnThread(task: Task) { threadRunner.checkThread() loadingTasks.addTask(task) Log.d(TAG, "loading task count " + loadingTasks.getTaskCount()) } @WorkerThread private fun handleTaskFinishOnThread(task: Task, isCancelled: Boolean) { if (task !is TaskBase) { assert(false); return } threadRunner.checkThread() val status = if (isCancelled) Task.Status.Cancelled else Task.Status.Completed if (isCancelled) { task.private.taskError = CancelError() } // the task will be removed from the provider automatically logTask(task, "finished") setTaskStatus(task, status) task.private.clearAllListeners() // TODO: use callback scope task.finishCallback?.let { finishCallback -> HandlerTools.runOnHandlerThread(callbackHandler) { finishCallback.onCompleted(isCancelled) } } //TODO: for another status like cancelled new task won't be started //but we cant't just call checkTasksToRunOnThread because of Task.LoadPolicy.CancelAdded //because we want to have new task already in waiting queue but now it isn't if (task.taskStatus == Task.Status.Completed) { checkTasksToRunOnThread() } } @WorkerThread private fun cancelTaskOnThread(task: Task, info: Any?) { if (task !is TaskBase) { assert(false); return } threadRunner.checkThread() if (!task.private.needCancelTask && !task.isFinished()) { val st = task.taskStatus task.private.cancelTask(info) val canBeCancelledImmediately = task.private.canBeCancelledImmediately() if (task.isReadyToStart()) { handleTaskFinishOnThread(task, true) logTask(task, "Cancelled") } else if (canBeCancelledImmediately) { if (st == Task.Status.Started) { if (canBeCancelledImmediately) { handleTaskFinishOnThread(task, true) logTask(task, "Immediately Cancelled") taskToJobMap[task]?.cancel() } // else wait until the task handles needCancelTask } // else ignore, the callback is already called } // TODO: support taskToJobMap[task]?.cancel() call in else block here // TODO: as we support coroutines now we can do that // TODO: but it seems we need to call job.join to wait until a task coroutine catches cancellation } } /// Helpers private fun logTask(task: Task, prefix: String) { task.log(TAG, prefix) } }
mit
b5cf29a781b25a7224c199501e103856
31.413076
151
0.616897
5.329587
false
false
false
false
rickshory/VegNab
app/src/main/java/com/rickshory/vegnab/ui/FragmentVisitsList.kt
1
5838
package com.rickshory.vegnab.ui import android.content.Context import androidx.fragment.app.Fragment import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.rickshory.vegnab.R import com.rickshory.vegnab.VisitsListOpts import com.rickshory.vegnab.adapters.VisitsListAdapter import com.rickshory.vegnab.viewmodels.VNRoomViewModel import kotlinx.android.synthetic.main.fragment_visits.* import org.koin.dsl.module.applicationContext /** * A simple [Fragment] subclass. * Activities that contain this fragment must implement the * [FragmentVisitsList.VisitsListInterface] interface * to handle interaction events. * Use the [FragmentVisitsList.newInstance] factory method to * create an instance of this fragment. */ // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_VIS_LIST_OPTS = "visListOpts" private lateinit var vnRoomViewModel: VNRoomViewModel private lateinit var vlRecycView: RecyclerView private lateinit var viewManager: RecyclerView.LayoutManager class FragmentVisitsList : Fragment() { private lateinit var vlAdapter: RecyclerView.Adapter<*> private val TAG = this::class.java.simpleName private var visitsListOpts: VisitsListOpts? = null // private var param2: String? = null private var listener: VisitsListInterface? = null override fun onCreate(savedInstanceState: Bundle?) { Log.d(TAG, "onCreate: starts") super.onCreate(savedInstanceState) visitsListOpts = arguments?.getParcelable(ARG_VIS_LIST_OPTS) // arguments?.let { // visit = it.getString(ARG_VISIT) // param2 = it.getString(ARG_PARAM2) // } vnRoomViewModel = activity?.let { ViewModelProviders.of(this).get(VNRoomViewModel::class.java) } ?: throw Exception("Invalid Activity") vnRoomViewModel.allVis.observe(this, Observer {visits_list -> // update the cached copy of visits in the adapter visits_list?.let{{vlAdapter.setVisits(it)}} }) //left?.let { node -> queue.add(node) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { Log.d(TAG, "onCreateView: starts") // Inflate the layout for this fragment val fragView = inflater.inflate(R.layout.fragment_visits, container, false) vlRecycView = fragView.findViewById<RecyclerView>(R.id.visits_list) return fragView } // // TODO: Rename method, update argument and hook method into UI event // fun onButtonPressed(uri: Uri) { // listener?.onGoClicked(uri) // } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { Log.d(TAG, "onAttach: starts") super.onViewCreated(view, savedInstanceState) vlRecycView.adapter = vlAdapter vlRecycView.layoutManager = LinearLayoutManager(context) } override fun onAttach(context: Context) { Log.d(TAG, "onAttach: starts") super.onAttach(context) vlAdapter = VisitsListAdapter() if (context is VisitsListInterface) { listener = context } else { throw RuntimeException(context.toString() + " must implement VisitsListInterface") } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) // back button is up arrow if (listener is AppCompatActivity) { val actionbar = (listener as AppCompatActivity?)?.supportActionBar actionbar?.setDisplayHomeAsUpEnabled(true) } fab_new_visit.setOnClickListener { view -> // Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) // .setAction("Action", null).show() Log.d(TAG, "fab_new_visit action: start") listener?.visitsListOnGoClicked() Log.d(TAG, "fab_new_visit action: exit") } vlAdapter = VisitsListAdapter() // vlAdapter.setVisits() vlRecycView.adapter = vlAdapter } override fun onDetach() { Log.d(TAG, "onDetach: starts") super.onDetach() listener = 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 VisitsListInterface { // TODO: Update argument type and name // fun onGoClicked(uri: Uri) fun visitsListOnGoClicked() } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param visit The visit to edit, or null to add a new visit * @return A new instance of fragment FragmentVisitAddEdit. */ @JvmStatic fun newInstance(visitsListOpts: VisitsListOpts?) = FragmentVisitsList().apply { arguments = Bundle().apply { putParcelable(ARG_VIS_LIST_OPTS, visitsListOpts) // putString(ARG_PARAM2, param2) } } } }
gpl-3.0
48b551ed6b5b486711b3c9749c94379d
33.964072
99
0.671977
4.692926
false
false
false
false
nemerosa/ontrack
ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/schema/GQLTypeBuild.kt
1
20246
package net.nemerosa.ontrack.graphql.schema import graphql.Scalars.* import graphql.schema.* import graphql.schema.GraphQLArgument.newArgument import graphql.schema.GraphQLFieldDefinition.newFieldDefinition import graphql.schema.GraphQLObjectType.newObject import net.nemerosa.ontrack.common.getOrNull import net.nemerosa.ontrack.graphql.schema.actions.UIActionsGraphQLService import net.nemerosa.ontrack.graphql.schema.actions.actions import net.nemerosa.ontrack.graphql.support.listType import net.nemerosa.ontrack.graphql.support.pagination.GQLPaginatedListFactory import net.nemerosa.ontrack.model.pagination.PageRequest import net.nemerosa.ontrack.model.structure.* import net.nemerosa.ontrack.model.support.FreeTextAnnotatorContributor import org.springframework.stereotype.Component @Component class GQLTypeBuild( private val uiActionsGraphQLService: UIActionsGraphQLService, private val structureService: StructureService, private val projectEntityInterface: GQLProjectEntityInterface, private val validation: GQLTypeValidation, private val validationRun: GQLTypeValidationRun, private val runInfo: GQLTypeRunInfo, private val gqlEnumValidationRunSortingMode: GQLEnumValidationRunSortingMode, private val runInfoService: RunInfoService, private val paginatedListFactory: GQLPaginatedListFactory, creation: GQLTypeCreation, projectEntityFieldContributors: List<GQLProjectEntityFieldContributor>, freeTextAnnotatorContributors: List<FreeTextAnnotatorContributor> ) : AbstractGQLProjectEntity<Build>(Build::class.java, ProjectEntityType.BUILD, projectEntityFieldContributors, creation, freeTextAnnotatorContributors) { override fun getTypeName() = BUILD override fun createType(cache: GQLTypeCache): GraphQLObjectType { return newObject() .name(BUILD) .withInterface(projectEntityInterface.typeRef) .fields(projectEntityInterfaceFields()) // Actions .actions(uiActionsGraphQLService, Build::class) // Ref to branch .field( newFieldDefinition() .name("branch") .description("Reference to branch") .type(GraphQLTypeReference(GQLTypeBranch.BRANCH)) .build() ) // Promotion runs .field( newFieldDefinition() .name("promotionRuns") .description("Promotions for this build") .argument( newArgument() .name(ARG_PROMOTION) .description("Name of the promotion level") .type(GraphQLString) .build() ) .argument( newArgument() .name(ARG_LAST_PER_LEVEL) .description("Returns the last promotion run per promotion level") .type(GraphQLBoolean) .build() ) .type(listType(GraphQLTypeReference(GQLTypePromotionRun.PROMOTION_RUN))) .dataFetcher(buildPromotionRunsFetcher()) .build() ) // Validation runs .field( newFieldDefinition() .name("validationRuns") .description("Validations for this build") .argument( newArgument() .name(ARG_VALIDATION_STAMP) .description("Name of the validation stamp, can be a regular expression.") .type(GraphQLString) .build() ) .argument( newArgument() .name(ARG_COUNT) .description("Maximum number of validation runs") .type(GraphQLInt) .defaultValue(50) .build() ) .type(listType(GraphQLTypeReference(GQLTypeValidationRun.VALIDATION_RUN))) .dataFetcher(buildValidationRunsFetcher()) .build() ) // Paginated list of validation runs .field( paginatedListFactory.createPaginatedField<Build, ValidationRun>( cache = cache, fieldName = "validationRunsPaginated", fieldDescription = "Paginated list of validation runs", itemType = validationRun, arguments = listOf( newArgument() .name(ARG_SORTING_MODE) .description("Describes how the validation runs must be sorted.") .type(gqlEnumValidationRunSortingMode.getTypeRef()) .build(), ), itemListCounter = { _, build -> structureService.getValidationRunsCountForBuild( build.id ) }, itemListProvider = { env, build, offset, size -> val sortingMode = env.getArgument<String?>(ARG_SORTING_MODE) ?.let { ValidationRunSortingMode.valueOf(it) } ?: ValidationRunSortingMode.ID structureService.getValidationRunsForBuild( buildId = build.id, offset = offset, count = size, sortingMode = sortingMode ) } ) ) // Validation runs per validation stamp .field { f -> f.name("validations") .description("Validations per validation stamp") .argument( newArgument() .name(ARG_VALIDATION_STAMP) .description("Name of the validation stamp") .type(GraphQLString) .build() ) .argument { it.name(GQLPaginatedListFactory.ARG_OFFSET) .description("Offset for the page") .type(GraphQLInt) .defaultValue(0) } .argument { it.name(GQLPaginatedListFactory.ARG_SIZE) .description("Size of the page") .type(GraphQLInt) .defaultValue(PageRequest.DEFAULT_PAGE_SIZE) } .type(listType(validation.typeRef)) .dataFetcher(buildValidationsFetcher()) } // Build links - "using" direction, with pagination .field( paginatedListFactory.createPaginatedField<Build, Build>( cache = cache, fieldName = "using", fieldDescription = "List of builds being used by this one.", itemType = this, arguments = listOf( newArgument() .name("project") .description("Keeps only links targeted from this project") .type(GraphQLString) .build(), newArgument() .name("branch") .description("Keeps only links targeted from this branch. `project` argument is also required.") .type(GraphQLString) .build() ), itemPaginatedListProvider = { environment, build, offset, size -> val filter: (Build) -> Boolean = getFilter(environment) structureService.getBuildsUsedBy( build, offset, size, filter ) } ) ) // Build links - "usedBy" direction, with pagination .field( paginatedListFactory.createPaginatedField<Build, Build>( cache = cache, fieldName = "usedBy", fieldDescription = "List of builds using this one.", itemType = this, arguments = listOf( newArgument() .name("project") .description("Keeps only links targeted from this project") .type(GraphQLString) .build(), newArgument() .name("branch") .description("Keeps only links targeted from this branch. `project` argument is also required.") .type(GraphQLString) .build() ), itemPaginatedListProvider = { environment, build, offset, size -> val filter = getFilter(environment) structureService.getBuildsUsing( build, offset, size, filter ) } ) ) // Run info .field { it.name("runInfo") .description("Run info associated with this build") .type(runInfo.typeRef) .runInfoFetcher<Build> { entity -> runInfoService.getRunInfo(entity) } } // OK .build() } private fun getFilter(environment: DataFetchingEnvironment): (Build) -> Boolean { val projectName: String? = environment.getArgument("project") val branchName: String? = environment.getArgument("branch") val filter: (Build) -> Boolean = if (branchName != null) { if (projectName == null) { throw IllegalArgumentException("`project` is required") } else { { it.branch.project.name == projectName && it.branch.name == branchName } } } else if (projectName != null) { { it.branch.project.name == projectName } } else { { true } } return filter } private fun buildValidationsFetcher(): DataFetcher<List<GQLTypeValidation.GQLTypeValidationData>> = DataFetcher { environment -> val build: Build = environment.getSource() // Filter on validation stamp val validationStampName: String? = environment.getArgument(ARG_VALIDATION_STAMP) val offset = environment.getArgument<Int>(GQLPaginatedListFactory.ARG_OFFSET) ?: 0 val size = environment.getArgument<Int>(GQLPaginatedListFactory.ARG_SIZE) ?: 10 if (validationStampName != null) { val validationStamp: ValidationStamp? = structureService.findValidationStampByName( build.project.name, build.branch.name, validationStampName ).orElse(null) if (validationStamp != null) { listOf( buildValidation( validationStamp, build, offset, size ) ) } else { emptyList() } } else { // Gets the validation runs for the build structureService.getValidationStampListForBranch(build.branch.id) .map { validationStamp -> buildValidation(validationStamp, build, offset, size) } } } private fun buildValidation( validationStamp: ValidationStamp, build: Build, offset: Int, size: Int ): GQLTypeValidation.GQLTypeValidationData { return GQLTypeValidation.GQLTypeValidationData( validationStamp, structureService.getValidationRunsForBuildAndValidationStamp( build.id, validationStamp.id, offset, size ) ) } private fun buildValidationRunsFetcher() = DataFetcher { environment -> val build: Build = environment.getSource() // Filter val count: Int = environment.getArgument(ARG_COUNT) ?: 50 val validation: String? = environment.getArgument(ARG_VALIDATION_STAMP) if (validation != null) { // Gets one validation stamp by name val validationStamp = structureService.findValidationStampByName( build.project.name, build.branch.name, validation ).getOrNull() // If there is one, we return the list of runs for this very stamp if (validationStamp != null) { // Gets validations runs for this validation level return@DataFetcher structureService.getValidationRunsForBuildAndValidationStamp( build.id, validationStamp.id, 0, count ) } // If not, we collect the list of matching validation stamp, assuming // the argument is a regular expression else { val vsNameRegex = validation.toRegex() return@DataFetcher structureService.getValidationStampListForBranch(build.branch.id) .filter { vs -> vsNameRegex.matches(vs.name) } .flatMap { vs -> structureService.getValidationRunsForBuildAndValidationStamp( build.id, vs.id, 0, count ) } } } else { // Gets all the validation runs (limited by count) return@DataFetcher structureService.getValidationRunsForBuild(build.id, 0, count) .take(count) } } private fun buildPromotionRunsFetcher() = DataFetcher<List<PromotionRun>> { environment -> val build: Build = environment.getSource() // Last per promotion filter? val lastPerLevel: Boolean = environment.getArgument(ARG_LAST_PER_LEVEL) ?: false // Promotion filter val promotion: String? = environment.getArgument(ARG_PROMOTION) val promotionLevel: PromotionLevel? = if (promotion != null) { // Gets the promotion level structureService.findPromotionLevelByName( build.project.name, build.branch.name, promotion ).orElse(null) } else { null } if (promotionLevel != null) { // Gets promotion runs for this promotion level if (lastPerLevel) { return@DataFetcher structureService.getLastPromotionRunForBuildAndPromotionLevel(build, promotionLevel) .map { listOf(it) } .orElse(listOf()) } else { return@DataFetcher structureService.getPromotionRunsForBuildAndPromotionLevel(build, promotionLevel) } } else { // Gets all the promotion runs if (lastPerLevel) { return@DataFetcher structureService.getLastPromotionRunsForBuild(build.id) } else { return@DataFetcher structureService.getPromotionRunsForBuild(build.id) } } } override fun getSignature(entity: Build): Signature? { return entity.signature } companion object { /** * Name of the type */ const val BUILD = "Build" /** * Filter on the validation runs */ const val ARG_VALIDATION_STAMP = "validationStamp" /** * Count argument */ const val ARG_COUNT = "count" /** * Promotion level argument */ const val ARG_PROMOTION = "promotion" /** * Last per level argument */ const val ARG_LAST_PER_LEVEL = "lastPerLevel" /** * Sorting mode for the validation runs */ const val ARG_SORTING_MODE = "sortingMode" } }
mit
5d30197361457383b1225281e6930ccf
48.866995
154
0.427344
7.504077
false
false
false
false
nemerosa/ontrack
ontrack-service/src/main/java/net/nemerosa/ontrack/service/support/ConnectorStatusMetrics.kt
1
2090
package net.nemerosa.ontrack.service.support import io.micrometer.core.instrument.MeterRegistry import io.micrometer.core.instrument.Tag import net.nemerosa.ontrack.model.support.CollectedConnectorStatus import net.nemerosa.ontrack.model.support.ConnectorStatusIndicator import net.nemerosa.ontrack.model.support.ConnectorStatusType import org.springframework.stereotype.Component import org.springframework.transaction.annotation.Transactional import javax.annotation.PostConstruct @Component @Transactional(readOnly = true) class ConnectorStatusMetrics( private val connectorStatusIndicator: List<ConnectorStatusIndicator>, private val connectorStatusJob: ConnectorStatusJob, private val registry: MeterRegistry ) { private fun MeterRegistry.register( name: String, gauge: (ConnectorStatusJob) -> List<CollectedConnectorStatus>?, tags: List<Tag>, extractor: (List<CollectedConnectorStatus>) -> Double ) { gauge( name, tags, connectorStatusJob ) { job -> val statuses = gauge(job) if (statuses != null) { extractor(statuses) } else { 0.0 } } } @PostConstruct fun bindTo() { connectorStatusIndicator.forEach { indicator -> val gauge = { job: ConnectorStatusJob -> job.statuses[indicator.type] } val tags = listOf( Tag.of("type", indicator.type) ) registry.register("ontrack_connector_count", gauge, tags) { statuses -> statuses.size.toDouble() } registry.register("ontrack_connector_up", gauge, tags) { statuses -> statuses.count { it.status.type == ConnectorStatusType.UP }.toDouble() } registry.register("ontrack_connector_down", gauge, tags) { statuses -> statuses.count { it.status.type == ConnectorStatusType.DOWN }.toDouble() } } } }
mit
e01c1a4ad2ed44206e5778969c51a319
31.169231
88
0.623445
5.085158
false
false
false
false
whoww/SneakPeek
app/src/main/java/de/sneakpeek/ui/detail/DetailActivity.kt
1
4911
package de.sneakpeek.ui.detail import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Paint.ANTI_ALIAS_FLAG import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import android.text.TextUtils import android.util.Log import com.squareup.picasso.Picasso import de.sneakpeek.R import de.sneakpeek.adapter.ActorsAdapter import de.sneakpeek.data.MovieInfo import de.sneakpeek.service.TheMovieDBService import de.sneakpeek.util.Util import kotlinx.android.synthetic.main.activity_detail.* import kotlinx.android.synthetic.main.activity_detail_movie_information.* import java.text.NumberFormat import java.text.SimpleDateFormat import java.util.* class DetailActivity : AppCompatActivity() { public override fun onCreate(savedInstanceState: Bundle?) { setTheme(if (Util.GetUseLightTheme(application)) R.style.SneakPeekLightTransparentStatusBar else R.style.SneakPeekDarkTransparentStatusBar) super.onCreate(savedInstanceState) setContentView(R.layout.activity_detail) activity_detail_toolbar.title = "" setSupportActionBar(activity_detail_toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) if (!intent.extras.containsKey(MOVIE_KEY)) { Log.e(TAG, "This Activity has to be started via StartMovieActivity") return } val movie = intent.extras.getParcelable<MovieInfo>(MOVIE_KEY) Picasso.with(this@DetailActivity) .load("${TheMovieDBService.IMAGE_URL}${movie?.poster_path}") .placeholder(R.drawable.movie_poster_placeholder) .into(activity_detail_poster) val vote_average_fab = if (movie.vote_average.compareTo(0) == 0) { getString(R.string.activity_detail_vote_average_na) } else { "${movie.vote_average}" } activity_movie_fab.setImageBitmap(textAsBitmap(vote_average_fab, 40f, Color.WHITE)) activity_detail_original_title.text = if (TextUtils.isEmpty(movie.original_title)) { "" } else { " - ${movie.original_title}" } activity_detail_director.text = movie.director activity_detail_original_language.text = Locale(movie.original_language).displayLanguage activity_detail_genre.text = movie?.genres?.map { it.name ?: "" }?.reduce { acc, s -> "$acc | $s" } activity_detail_vote_average.text = "${movie.vote_average} / 10" val numberFormatter = NumberFormat.getCurrencyInstance() numberFormatter.minimumFractionDigits = 0 activity_detail_budget.text = if (movie.budget == 0) { getText(R.string.activity_detail_budget_na) } else { numberFormatter.format(movie.budget) } activity_detail_plot.text = movie.overview val format = SimpleDateFormat("yyyy-MM-dd", Locale.GERMANY).parse(movie.release_date) activity_detail_released.text = SimpleDateFormat.getDateInstance().format(format) activity_detail_runtime.text = "${movie.runtime} min" activity_detail_writer.text = movie.writer activity_detail_recycler_view_actors.setHasFixedSize(true) activity_detail_recycler_view_actors.adapter = ActorsAdapter(movie.credits?.cast ?: emptyList()) activity_detail_recycler_view_actors.itemAnimator = DefaultItemAnimator() activity_detail_recycler_view_actors.layoutManager = LinearLayoutManager(baseContext) activity_detail_recycler_view_actors.isNestedScrollingEnabled = false } override fun onSupportNavigateUp(): Boolean { onBackPressed() return true } companion object { private val TAG = DetailActivity::class.java.simpleName private val MOVIE_KEY = "MOVIE_KEY" fun StartMovieActivity(context: Context, movie: MovieInfo): Intent { val intent = Intent(context, DetailActivity::class.java) intent.putExtra(MOVIE_KEY, movie) return intent } } fun textAsBitmap(text: String, textSize: Float, textColor: Int): Bitmap { val paint = Paint(ANTI_ALIAS_FLAG) paint.textSize = textSize paint.color = textColor paint.textAlign = Paint.Align.LEFT val baseline = -paint.ascent() // ascent() is negative val image = Bitmap.createBitmap(paint.measureText(text).toInt(), baseline.toInt() + paint.descent().toInt(), Bitmap.Config.ARGB_8888) val canvas = Canvas(image) canvas.drawText(text, 0f, baseline, paint) return image } }
mit
d46be937cc19b97922be48868391b383
36.204545
147
0.691509
4.416367
false
false
false
false
thatJavaNerd/JRAW
meta/src/main/kotlin/net/dean/jraw/meta/MarkdownOverviewCreator.kt
1
3887
package net.dean.jraw.meta import net.steppschuh.markdowngenerator.link.Link import net.steppschuh.markdowngenerator.table.Table import net.steppschuh.markdowngenerator.text.code.Code import net.steppschuh.markdowngenerator.text.heading.Heading import java.io.File import java.text.SimpleDateFormat import java.util.* object MarkdownOverviewCreator { fun create(endpoints: EndpointOverview, f: File) = f.writeText(create(endpoints)) private val dateFormat = SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z") /** In which order to display endpoints. Statuses that come first will appear first. */ private val implementationOrder = listOf( ImplementationStatus.IMPLEMENTED, ImplementationStatus.PLANNED, ImplementationStatus.NOT_PLANNED ) private fun create(overview: EndpointOverview): String { return with (StringBuilder()) { // Comment to those curious enough to open the file block("<!--- Generated ${dateFormat.format(Date())}. Use `./gradlew :meta:update` to update. DO NOT " + "MODIFY DIRECTLY -->") // Main header heading("Endpoints") // Purpose of this file block( "This file contains a list of all the endpoints (regardless of if they have been implemented) that " + "can be found at the [official reddit API docs](https://www.reddit.com/dev/api/oauth). " + "To update this file, run `./gradlew :meta:update`" ) // Summary block("So far, API completion is at **${overview.completionPercentage(decimals = 2)}%**. " + "${overview.implemented} out of ${overview.effectiveTotal} endpoints (ignoring ${overview.notPlanned} " + "endpoints not planned) have been implemented ") val oauthScopes = overview.scopes() for (scope in oauthScopes) { val section = overview.byOAuthScope(scope) heading(if (scope == "any") "(any scope)" else scope, 2) block("${section.completionPercentage(2)}% completion (${section.implemented} implemented, ${section.planned} planned, and " + "${section.notPlanned} not planned)") val table = Table.Builder() .withAlignments(Table.ALIGN_CENTER, Table.ALIGN_LEFT, Table.ALIGN_LEFT) .addRow("Method", "Endpoint", "Implementation") val sorted = section.endpoints.sortedWith(compareBy( // Show sorted endpoints first, then planned, then not planned { implementationOrder.indexOf(it.status) }, // Then sort ascending alphabetically by path { it.path }, // Then sort ascending alphabetically by HTTP method { it.method } )) for (e in sorted) { table.addRow( Code(e.method), Link(Code(e.displayPath), e.redditDocLink), implString(e)) } block(table.build()) } toString() } } private fun StringBuilder.heading(text: String, level: Int = 1) = block(Heading(text, level)) private fun StringBuilder.block(obj: Any) { append(obj) append("\n\n") } private fun implString(e: EndpointMeta): String { return when (e.status) { ImplementationStatus.IMPLEMENTED -> { val method = e.implementation!! Link(Code("${method.declaringClass.simpleName}.${method.name}()"), e.sourceUrl).toString() } ImplementationStatus.NOT_PLANNED -> "Not planned" ImplementationStatus.PLANNED -> "None" } } }
mit
88b4aab08b4705b97fa125eb4a94d932
39.072165
142
0.58194
4.889308
false
false
false
false
ffc-nectec/FFC
ffc/src/main/kotlin/ffc/app/setting/AboutActivity.kt
1
2048
package ffc.app.setting import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.v7.preference.PreferenceFragmentCompat import com.google.android.gms.oss.licenses.OssLicensesMenuActivity import ffc.api.FfcCentral import ffc.app.BuildConfig import ffc.app.FamilyFolderActivity import ffc.app.R import ffc.app.auth.legal.LegalAgreementApi import ffc.app.auth.legal.LegalType import ffc.app.auth.legal.LegalType.privacy import ffc.app.auth.legal.LegalType.terms import org.jetbrains.anko.support.v4.intentFor import org.jetbrains.anko.support.v4.startActivity class AboutActivity : FamilyFolderActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_preference) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportFragmentManager .beginTransaction() .replace(R.id.contentContainer, AboutPreferenceFragment()) .commit() } class AboutPreferenceFragment : PreferenceFragmentCompat() { override fun onCreatePreferences(bundle: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.pref_about, rootKey) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) findPreference("version").summary = BuildConfig.VERSION_NAME findPreference("license").setOnPreferenceClickListener { startActivity<OssLicensesMenuActivity>() true } findPreference("terms").intent = intentOfLegal(terms) findPreference("privacy").intent = intentOfLegal(privacy) } private fun intentOfLegal(type: LegalType): Intent { val term = FfcCentral().service<LegalAgreementApi>().latest(type) return intentFor<LegalViewActivity>().apply { data = Uri.parse(term.request().url().toString()) } } } }
apache-2.0
3981a01f42cc32c345e1fb5d24434cd0
36.236364
77
0.704102
5.019608
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/util/ReleaseUtil.kt
1
1828
package org.wikipedia.util import android.content.Context import android.content.pm.PackageManager import org.wikipedia.BuildConfig import org.wikipedia.settings.Prefs object ReleaseUtil { private const val RELEASE_PROD = 0 private const val RELEASE_BETA = 1 private const val RELEASE_ALPHA = 2 private const val RELEASE_DEV = 3 val isProdRelease: Boolean get() = calculateReleaseType() == RELEASE_PROD val isPreProdRelease: Boolean get() = calculateReleaseType() != RELEASE_PROD val isAlphaRelease: Boolean get() = calculateReleaseType() == RELEASE_ALPHA val isPreBetaRelease: Boolean get() = when (calculateReleaseType()) { RELEASE_PROD, RELEASE_BETA -> false else -> true } val isDevRelease: Boolean get() = calculateReleaseType() == RELEASE_DEV fun getChannel(ctx: Context): String { var channel = Prefs.appChannel if (channel == null) { channel = getChannelFromManifest(ctx) Prefs.appChannel = channel } return channel } private fun calculateReleaseType(): Int { return when { BuildConfig.APPLICATION_ID.contains("beta") -> RELEASE_BETA BuildConfig.APPLICATION_ID.contains("alpha") -> RELEASE_ALPHA BuildConfig.APPLICATION_ID.contains("dev") -> RELEASE_DEV else -> RELEASE_PROD } } private fun getChannelFromManifest(ctx: Context): String { return try { val info = ctx.packageManager .getApplicationInfo(BuildConfig.APPLICATION_ID, PackageManager.GET_META_DATA) val channel = info.metaData.getString(Prefs.appChannelKey) channel ?: "" } catch (t: Throwable) { "" } } }
apache-2.0
be782e184a947bba2cbbdc4189ef9572
29.466667
97
0.624726
4.900804
false
true
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/loader/users/IncomingFriendshipsLoader.kt
1
3193
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.loader.users import android.content.Context import de.vanita5.microblog.library.MicroBlog import de.vanita5.microblog.library.MicroBlogException import de.vanita5.microblog.library.mastodon.Mastodon import de.vanita5.microblog.library.twitter.model.Paging import de.vanita5.twittnuker.annotation.AccountType import de.vanita5.twittnuker.extension.api.lookupUsersMapPaginated import de.vanita5.twittnuker.extension.model.api.mastodon.mapToPaginated import de.vanita5.twittnuker.extension.model.api.mastodon.toParcelable import de.vanita5.twittnuker.extension.model.api.microblog.mapToPaginated import de.vanita5.twittnuker.extension.model.api.toParcelable import de.vanita5.twittnuker.extension.model.newMicroBlogInstance import de.vanita5.twittnuker.model.AccountDetails import de.vanita5.twittnuker.model.ParcelableUser import de.vanita5.twittnuker.model.UserKey import de.vanita5.twittnuker.model.pagination.PaginatedList class IncomingFriendshipsLoader( context: Context, accountKey: UserKey?, data: List<ParcelableUser>?, fromUser: Boolean ) : AbsRequestUsersLoader(context, accountKey, data, fromUser) { @Throws(MicroBlogException::class) override fun getUsers(details: AccountDetails, paging: Paging): PaginatedList<ParcelableUser> { when (details.type) { AccountType.MASTODON -> { val mastodon = details.newMicroBlogInstance(context, Mastodon::class.java) return mastodon.getFollowRequests(paging).mapToPaginated { it.toParcelable(details) } } AccountType.FANFOU -> { val microBlog = details.newMicroBlogInstance(context, MicroBlog::class.java) return microBlog.getFriendshipsRequests(paging).mapToPaginated(pagination) { it.toParcelable(details, profileImageSize = profileImageSize) } } else -> { val microBlog = details.newMicroBlogInstance(context, MicroBlog::class.java) return microBlog.lookupUsersMapPaginated(microBlog.getIncomingFriendships(paging)) { it.toParcelable(details, profileImageSize = profileImageSize) } } } } }
gpl-3.0
21d345bf29593159e6c8ca49a109e05a
42.162162
100
0.723771
4.627536
false
false
false
false
mayank408/susi_android
app/src/main/java/org/fossasia/susi/ai/login/LoginPresenter.kt
1
4147
package org.fossasia.susi.ai.login import org.fossasia.susi.ai.R import org.fossasia.susi.ai.data.contract.ILoginModel import org.fossasia.susi.ai.data.LoginModel import org.fossasia.susi.ai.data.UtilModel import org.fossasia.susi.ai.helper.Constant import org.fossasia.susi.ai.helper.CredentialHelper import org.fossasia.susi.ai.login.contract.ILoginPresenter import org.fossasia.susi.ai.login.contract.ILoginView import org.fossasia.susi.ai.rest.responses.susi.LoginResponse import retrofit2.Response import java.net.UnknownHostException /** * Presenter for Login * The P in MVP * * Created by chiragw15 on 4/7/17. */ class LoginPresenter(loginActivity: LoginActivity): ILoginPresenter, ILoginModel.OnLoginFinishedListener { var loginModel: LoginModel = LoginModel() var utilModel: UtilModel = UtilModel(loginActivity) var loginView: ILoginView?= null lateinit var email: String override fun onAttach(loginView: ILoginView) { this.loginView = loginView if (utilModel.getAnonymity()) { loginView.skipLogin() return } if(utilModel.isLoggedIn()) { loginView.skipLogin() return } loginView.attachEmails(utilModel.getSavedEmails()) } override fun skipLogin() { utilModel.clearToken() utilModel.saveAnonymity(true) loginView?.skipLogin() } override fun login(email: String, password: String, isSusiServerSelected: Boolean, url: String) { if (email.isEmpty()) { loginView?.invalidCredentials(true, Constant.EMAIL) return } if(password.isEmpty()) { loginView?.invalidCredentials(true, Constant.PASSWORD) return } if (!CredentialHelper.isEmailValid(email)) { loginView?.invalidCredentials(false, Constant.EMAIL) return } if (!isSusiServerSelected) { if (url.isEmpty()){ loginView?.invalidCredentials(true, Constant.INPUT_URL) return } if( CredentialHelper.isURLValid(url)) { if (CredentialHelper.getValidURL(url) != null) { utilModel.setServer(false) utilModel.setCustomURL(url) } else { loginView?.invalidCredentials(false, Constant.INPUT_URL) return } } else { loginView?.invalidCredentials(false, Constant.INPUT_URL) return } } else { utilModel.setServer(true) } this.email = email loginView?.showProgress(true) loginModel.login(email.trim({ it <= ' ' }).toLowerCase(), password, this) } override fun cancelLogin() { loginModel.cancelLogin() } override fun onError(throwable: Throwable) { loginView?.showProgress(false) if (throwable is UnknownHostException) { loginView?.onLoginError(utilModel.getString(R.string.unknown_host_exception), throwable.message.toString()) } else { loginView?.onLoginError(utilModel.getString(R.string.error_internet_connectivity), utilModel.getString(R.string.no_internet_connection)) } } override fun onSuccess(response: Response<LoginResponse>) { loginView?.showProgress(false) if (response.isSuccessful && response.body() != null) { utilModel.saveToken(response) utilModel.deleteAllMessages() utilModel.saveEmail(email) utilModel.saveAnonymity(false) loginView?.onLoginSuccess(response.body().message) } else if (response.code() == 422) { loginView?.onLoginError(utilModel.getString(R.string.password_invalid_title), utilModel.getString(R.string.password_invalid)) } else { loginView?.onLoginError("${response.code()} " + utilModel.getString(R.string.error), response.message()) } } override fun onDetach() { loginView = null } }
apache-2.0
1c41830eeb872cce5ac9e5ccf5f221d3
30.656489
119
0.622378
4.734018
false
false
false
false
congwiny/KotlinBasic
src/main/kotlin/operator/overloading/DelegatedProperties01.kt
1
1581
package operator.overloading import java.beans.PropertyChangeListener import java.beans.PropertyChangeSupport /** * 以下示例看得出在Kotlin中,委托属性是如何工作的。 * * 你创建了一个保存属性值的类,并在修改属性时自动触发更改通知。 * 但是需要相当多的样板代码来为每个属性创建ObservableProperty实例。 * * Kotlin的委托属性功能可以让你摆脱这些样板代码。 */ fun main(args: Array<String>) { val p01 = People01("congwiny", 28, 2000) p01.addPropertyChangeListener(PropertyChangeListener { event -> println("Property ${event.propertyName} changed " + "from ${event.oldValue} to ${event.newValue}") }) p01.age = 29 p01.salary = 3000 } class People01( val name: String, age: Int, salary: Int ) : PropertyChangeAware() { val _age = ObservableProperty01("age", age, changeSupport) var age: Int get() = _age.getValue() set(value) { _age.setValue(value) } val _salary = ObservableProperty01("salary", salary, changeSupport) var salary: Int get() = _salary.getValue() set(value) { _salary.setValue(value) } } class ObservableProperty01( val propName: String, var propValue: Int, val changeSupport: PropertyChangeSupport ) { fun getValue(): Int = propValue fun setValue(newValue: Int) { val oldValue = propValue propValue = newValue changeSupport.firePropertyChange(propName, oldValue, newValue) } }
apache-2.0
6c6e4beec54d19981c82c5d44ed7c37d
24.345455
71
0.651113
3.724599
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/cargo/runconfig/buildtool/CargoBuildTaskProvider.kt
2
2341
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.runconfig.buildtool import com.intellij.execution.configurations.RunConfiguration import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.util.Key import com.intellij.openapi.util.text.StringUtil.unquoteString import com.intellij.util.execution.ParametersListUtil import org.rust.cargo.runconfig.buildtool.CargoBuildManager.getBuildConfiguration import org.rust.cargo.runconfig.command.CargoCommandConfiguration import org.rust.cargo.toolchain.tools.Rustup.Companion.checkNeedInstallTarget class CargoBuildTaskProvider : RsBuildTaskProvider<CargoBuildTaskProvider.BuildTask>() { override fun getId(): Key<BuildTask> = ID override fun createTask(runConfiguration: RunConfiguration): BuildTask? = if (runConfiguration is CargoCommandConfiguration) BuildTask() else null override fun executeTask( context: DataContext, configuration: RunConfiguration, environment: ExecutionEnvironment, task: BuildTask ): Boolean { if (configuration !is CargoCommandConfiguration) return false val buildConfiguration = getBuildConfiguration(configuration) ?: return true val projectDirectory = buildConfiguration.workingDirectory ?: return false val configArgs = ParametersListUtil.parse(buildConfiguration.command) val targetFlagIdx = configArgs.indexOfFirst { it.startsWith("--target") } val targetFlag = if (targetFlagIdx != -1) configArgs[targetFlagIdx] else null val targetTriple = when { targetFlag == "--target" -> configArgs.getOrNull(targetFlagIdx + 1) targetFlag?.startsWith("--target=") == true -> unquoteString(targetFlag.substringAfter("=")) else -> null } if (targetTriple != null && checkNeedInstallTarget(configuration.project, projectDirectory, targetTriple)) { return false } return doExecuteTask(buildConfiguration, environment) } class BuildTask : RsBuildTaskProvider.BuildTask<BuildTask>(ID) companion object { @JvmField val ID: Key<BuildTask> = Key.create("CARGO.BUILD_TASK_PROVIDER") } }
mit
cc28d0a1e7564d26cdd4b6c46d9898f1
40.070175
116
0.737719
5.122538
false
true
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/cargo/runconfig/ui/RsCommandConfigurationEditor.kt
3
2266
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.runconfig.ui import com.intellij.execution.ExecutionBundle import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.options.SettingsEditor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.LabeledComponent import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.util.text.nullize import org.rust.cargo.project.workspace.CargoWorkspace import org.rust.cargo.runconfig.RsCommandConfiguration import org.rust.cargo.runconfig.command.CargoCommandConfiguration import org.rust.cargo.util.RsCommandLineEditor import java.nio.file.Path import java.nio.file.Paths abstract class RsCommandConfigurationEditor<T : RsCommandConfiguration>( protected val project: Project ) : SettingsEditor<T>() { abstract val command: RsCommandLineEditor protected fun currentWorkspace(): CargoWorkspace? = CargoCommandConfiguration.findCargoProject(project, command.text, currentWorkingDirectory)?.workspace protected val currentWorkingDirectory: Path? get() = workingDirectory.component.text.nullize()?.let { Paths.get(it) } protected val workingDirectory: LabeledComponent<TextFieldWithBrowseButton> = WorkingDirectoryComponent() override fun resetEditorFrom(configuration: T) { command.text = configuration.command workingDirectory.component.text = configuration.workingDirectory?.toString().orEmpty() } override fun applyEditorTo(configuration: T) { configuration.command = command.text configuration.workingDirectory = currentWorkingDirectory } } private class WorkingDirectoryComponent : LabeledComponent<TextFieldWithBrowseButton>() { init { component = TextFieldWithBrowseButton().apply { val fileChooser = FileChooserDescriptorFactory.createSingleFolderDescriptor().apply { title = ExecutionBundle.message("select.working.directory.message") } addBrowseFolderListener(null, null, null, fileChooser) } text = ExecutionBundle.message("run.configuration.working.directory.label") } }
mit
cda67829817237b26e3e0c4ef13c1534
38.068966
109
0.768756
5.24537
false
true
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/icons/RsIconProvider.kt
2
1184
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.icons import com.intellij.ide.IconProvider import com.intellij.psi.PsiElement import org.rust.cargo.icons.CargoIcons import org.rust.cargo.project.workspace.CargoWorkspace import org.rust.lang.RsConstants import org.rust.lang.core.psi.RsFile import javax.swing.Icon class RsIconProvider : IconProvider() { override fun getIcon(element: PsiElement, flags: Int): Icon? = when (element) { is RsFile -> getFileIcon(element) else -> null } private fun getFileIcon(file: RsFile): Icon? = when { file.name == RsConstants.MOD_RS_FILE -> RsIcons.MOD_RS isMainFile(file) -> RsIcons.MAIN_RS isBuildRs(file) -> CargoIcons.BUILD_RS_ICON else -> null } private fun isMainFile(element: RsFile) = (element.name == RsConstants.MAIN_RS_FILE || element.name == RsConstants.LIB_RS_FILE) && element.isCrateRoot private fun isBuildRs(element: RsFile): Boolean = // TODO containingTarget element.isCrateRoot && element.crate.kind == CargoWorkspace.TargetKind.CustomBuild }
mit
b60d68962315ab8f7b34198b0cd3592c
32.828571
93
0.701014
3.907591
false
false
false
false
androidx/androidx
buildSrc/private/src/main/kotlin/androidx/build/metalava/CheckApiEquivalenceTask.kt
3
4259
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.build.metalava import androidx.build.checkapi.ApiLocation import org.apache.commons.io.FileUtils import org.gradle.api.DefaultTask import org.gradle.api.GradleException import org.gradle.api.provider.ListProperty import org.gradle.api.provider.Property import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFiles import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskAction import org.gradle.work.DisableCachingByDefault import java.io.File import java.util.concurrent.TimeUnit /** Compares two API txt files against each other. */ @DisableCachingByDefault(because = "Doesn't benefit from caching") abstract class CheckApiEquivalenceTask : DefaultTask() { /** * Api file (in the build dir) to check */ @get:Input abstract val builtApi: Property<ApiLocation> /** * Api file (in source control) to compare against */ @get:Input abstract val checkedInApis: ListProperty<ApiLocation> @InputFiles @PathSensitive(PathSensitivity.RELATIVE) fun getTaskInputs(): List<File> { val checkedInApiLocations = checkedInApis.get() val checkedInApiFiles = checkedInApiLocations.flatMap { checkedInApiLocation -> listOf( checkedInApiLocation.publicApiFile, checkedInApiLocation.removedApiFile, checkedInApiLocation.experimentalApiFile, checkedInApiLocation.restrictedApiFile ) } val builtApiLocation = builtApi.get() val builtApiFiles = listOf( builtApiLocation.publicApiFile, builtApiLocation.removedApiFile, builtApiLocation.experimentalApiFile, builtApiLocation.restrictedApiFile ) return checkedInApiFiles + builtApiFiles } @TaskAction fun exec() { val builtApiLocation = builtApi.get() for (checkedInApi in checkedInApis.get()) { checkEqual(checkedInApi.publicApiFile, builtApiLocation.publicApiFile) checkEqual(checkedInApi.removedApiFile, builtApiLocation.removedApiFile) checkEqual(checkedInApi.experimentalApiFile, builtApiLocation.experimentalApiFile) checkEqual(checkedInApi.restrictedApiFile, builtApiLocation.restrictedApiFile) } } } private fun summarizeDiff(a: File, b: File): String { if (!a.exists()) { return "$a does not exist" } if (!b.exists()) { return "$b does not exist" } val process = ProcessBuilder(listOf("diff", a.toString(), b.toString())) .redirectOutput(ProcessBuilder.Redirect.PIPE) .start() process.waitFor(5, TimeUnit.SECONDS) var diffLines = process.inputStream.bufferedReader().readLines().toMutableList() val maxSummaryLines = 50 if (diffLines.size > maxSummaryLines) { diffLines = diffLines.subList(0, maxSummaryLines) diffLines.plusAssign("[long diff was truncated]") } return diffLines.joinToString("\n") } fun checkEqual(expected: File, actual: File) { if (!FileUtils.contentEquals(expected, actual)) { val diff = summarizeDiff(expected, actual) val message = """API definition has changed Declared definition is $expected True definition is $actual Please run `./gradlew updateApi` to confirm these changes are intentional by updating the API definition. Difference between these files: $diff""" throw GradleException(message) } }
apache-2.0
435108a456e6d3c9cc9feea206938806
34.789916
94
0.688425
4.918014
false
false
false
false
mocovenwitch/heykotlin
app/src/main/java/com/mocoven/heykotlin/playground/DepthFirstTraverse.kt
1
746
package com.mocoven.heykotlin.playground /** * Created by Mocoven on 16/08/2018. */ data class Node(val name: String, val left: Node?, val right: Node?) val d = Node("d", null, null) val b = Node("b", null, d) val c = Node("c", d, null) val a = Node("a", b, c) val graph = listOf(a, b, c, d) var visited: MutableList<Node> = mutableListOf() fun depthFirst() { graph.forEach { if (!visited.contains(it)) { visitWho(it) } } } fun visitWho(who: Node) { if (!visited.contains(who)) { visited.add(who) println("visiting ${who.name}") if (who.left != null) { visitWho(who.left) } else if (who.right != null) { visitWho(who.right) } } }
mit
ff827f080d2494f14196d7344b7dbaac
19.75
68
0.552279
3.069959
false
false
false
false
noemus/kotlin-eclipse
kotlin-eclipse-core/src/org/jetbrains/kotlin/core/resolve/lang/java/structure/EclipseJavaField.kt
1
1581
/******************************************************************************* * Copyright 2000-2014 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.kotlin.core.resolve.lang.java.structure import org.eclipse.jdt.core.dom.IVariableBinding import org.jetbrains.kotlin.load.java.structure.JavaClass import org.jetbrains.kotlin.load.java.structure.JavaField import org.jetbrains.kotlin.load.java.structure.JavaType public class EclipseJavaField(private val javaField: IVariableBinding) : EclipseJavaMember<IVariableBinding>(javaField), JavaField { override val hasConstantNotNullInitializer: Boolean get() = false override val initializerValue: Any? get() = null override val isEnumEntry: Boolean = binding.isEnumConstant() override val type: JavaType get() = EclipseJavaType.create(binding.getType()) override val containingClass: JavaClass get() = EclipseJavaClass(binding.getDeclaringClass()) }
apache-2.0
09048ecb214024ab5e951c33b2401bd3
40.631579
132
0.685009
4.790909
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/platform/mixin/handlers/injectionPoint/AtResolver.kt
1
9061
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.handlers.injectionPoint import com.demonwav.mcdev.platform.mixin.reference.isMiscDynamicSelector import com.demonwav.mcdev.platform.mixin.reference.parseMixinSelector import com.demonwav.mcdev.platform.mixin.reference.target.TargetReference import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.SLICE import com.demonwav.mcdev.platform.mixin.util.findSourceElement import com.demonwav.mcdev.util.computeStringArray import com.demonwav.mcdev.util.constantStringValue import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiClass import com.intellij.psi.PsiClassType import com.intellij.psi.PsiElement import com.intellij.psi.PsiExpression import com.intellij.psi.PsiQualifiedReference import com.intellij.psi.PsiReference import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.parentOfType import org.objectweb.asm.tree.ClassNode import org.objectweb.asm.tree.MethodNode /** * Resolves targets of @At. * * Resolution of this reference depends on @At.value(), each of which have their own [InjectionPoint]. This injection * point is in charge of parsing, validating and resolving this reference. * * This reference can be resolved in four different ways. * - [isUnresolved] only checks the bytecode of the target class, to check whether this reference is valid. * - [TargetReference.resolveReference] resolves to the actual member being targeted, rather than the location it's * referenced in the target method. This serves as a backup in case nothing else is found to navigate to, and so that * find usages can take you back to this reference. * - [collectTargetVariants] is used for auto-completion. It does not take into account what is actually in the target * string, and instead matches everything the handler *could* match. The references resolve similarly to * `resolveReference`, although new elements may be created if not found. * - [resolveNavigationTargets] is used when the user attempts to navigate on this reference. This attempts to take you * to the actual location in the source code of the target class which is being targeted. Potentially slow as it may * decompile the target class. * * To support the above, injection points must be able to resolve the target element, and support a collect visitor and * a navigation visitor. The collect visitor finds target instructions in the bytecode of the target method, and the * navigation visitor makes a best-effort attempt at matching source code elements. */ class AtResolver( private val at: PsiAnnotation, private val targetClass: ClassNode, private val targetMethod: MethodNode ) { companion object { private fun getInjectionPoint(at: PsiAnnotation): InjectionPoint<*>? { var atCode = at.findDeclaredAttributeValue("value")?.constantStringValue ?: return null // remove slice selector val isInSlice = at.parentOfType<PsiAnnotation>()?.hasQualifiedName(SLICE) ?: false if (isInSlice) { if (SliceSelector.values().any { atCode.endsWith(":${it.name}") }) { atCode = atCode.substringBeforeLast(':') } } return InjectionPoint.byAtCode(atCode) } fun usesMemberReference(at: PsiAnnotation): Boolean { val handler = getInjectionPoint(at) ?: return false return handler.usesMemberReference() } fun getArgs(at: PsiAnnotation): Map<String, String> { val args = at.findAttributeValue("args")?.computeStringArray() ?: return emptyMap() return args.asSequence() .map { val parts = it.split('=', limit = 2) if (parts.size == 1) { parts[0] to "" } else { parts[0] to parts[1] } } .toMap() } } fun isUnresolved(): InsnResolutionInfo.Failure? { val injectionPoint = getInjectionPoint(at) ?: return null // we don't know what to do with custom handlers, assume ok val targetAttr = at.findAttributeValue("target") val target = targetAttr?.let { parseMixinSelector(it) } val collectVisitor = injectionPoint.createCollectVisitor( at, target, targetClass, CollectVisitor.Mode.MATCH_FIRST ) if (collectVisitor == null) { // syntax error in target val stringValue = targetAttr?.constantStringValue ?: return InsnResolutionInfo.Failure() return if (isMiscDynamicSelector(at.project, stringValue)) { null } else { InsnResolutionInfo.Failure() } } collectVisitor.visit(targetMethod) return if (collectVisitor.result.isEmpty()) { InsnResolutionInfo.Failure(collectVisitor.filterToBlame) } else { null } } fun resolveInstructions(mode: CollectVisitor.Mode = CollectVisitor.Mode.MATCH_ALL): List<CollectVisitor.Result<*>> { return (getInstructionResolutionInfo(mode) as? InsnResolutionInfo.Success)?.results ?: emptyList() } fun getInstructionResolutionInfo(mode: CollectVisitor.Mode = CollectVisitor.Mode.MATCH_ALL): InsnResolutionInfo { val injectionPoint = getInjectionPoint(at) ?: return InsnResolutionInfo.Failure() val targetAttr = at.findAttributeValue("target") val target = targetAttr?.let { parseMixinSelector(it) } val collectVisitor = injectionPoint.createCollectVisitor(at, target, targetClass, mode) ?: return InsnResolutionInfo.Failure() collectVisitor.visit(targetMethod) val result = collectVisitor.result return if (result.isEmpty()) { InsnResolutionInfo.Failure(collectVisitor.filterToBlame) } else { InsnResolutionInfo.Success(result) } } fun resolveNavigationTargets(): List<PsiElement> { // First resolve the actual target in the bytecode using the collect visitor val injectionPoint = getInjectionPoint(at) ?: return emptyList() val targetAttr = at.findAttributeValue("target") val target = targetAttr?.let { parseMixinSelector(it) } val bytecodeResults = resolveInstructions() // Then attempt to find the corresponding source elements using the navigation visitor val targetElement = targetMethod.findSourceElement( targetClass, at.project, GlobalSearchScope.allScope(at.project), canDecompile = true ) ?: return emptyList() val targetPsiClass = targetElement.parentOfType<PsiClass>() ?: return emptyList() val navigationVisitor = injectionPoint.createNavigationVisitor(at, target, targetPsiClass) ?: return emptyList() targetElement.accept(navigationVisitor) return bytecodeResults.mapNotNull { bytecodeResult -> navigationVisitor.result.getOrNull(bytecodeResult.index) } } fun collectTargetVariants(completionHandler: (LookupElementBuilder) -> LookupElementBuilder): List<Any> { val injectionPoint = getInjectionPoint(at) ?: return emptyList() val targetAttr = at.findAttributeValue("target") val target = targetAttr?.let { parseMixinSelector(it) } // Collect all possible targets fun <T : PsiElement> doCollectVariants(injectionPoint: InjectionPoint<T>): List<Any> { val visitor = injectionPoint.createCollectVisitor(at, target, targetClass, CollectVisitor.Mode.COMPLETION) ?: return emptyList() visitor.visit(targetMethod) return visitor.result .mapNotNull { result -> injectionPoint.createLookup(targetClass, result)?.let { completionHandler(it) } } } return doCollectVariants(injectionPoint) } } sealed class InsnResolutionInfo { class Success(val results: List<CollectVisitor.Result<*>>) : InsnResolutionInfo() class Failure(val filterToBlame: String? = null) : InsnResolutionInfo() { infix fun combine(other: Failure): Failure { return if (filterToBlame != null) { this } else { other } } } } enum class SliceSelector { FIRST, LAST, ONE } object QualifiedMember { fun resolveQualifier(reference: PsiQualifiedReference): PsiClass? { val qualifier = reference.qualifier ?: return null ((qualifier as? PsiReference)?.resolve() as? PsiClass)?.let { return it } ((qualifier as? PsiExpression)?.type as? PsiClassType)?.resolve()?.let { return it } return null } }
mit
44c51e1f842985879a74f3a452b10c3e
41.943128
120
0.674319
5.139535
false
false
false
false
getsenic/nuimo-android
nuimo/src/main/kotlin/com/senic/nuimo/NuimoBuiltInLedMatrix.kt
1
909
/* * Copyright (c) 2016 Senic GmbH. All rights reserved. * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package com.senic.nuimo class NuimoBuiltInLedMatrix : NuimoLedMatrix { companion object { @JvmField val BUSY = NuimoBuiltInLedMatrix(1) } private constructor(byte: Byte) : super(byte.toMatrixBits()) override fun equals(other: Any?): Boolean { if (other is NuimoBuiltInLedMatrix) { return super.equals(other) } return super.equals(other) } override fun hashCode(): Int = super.hashCode() * 31 } private fun Byte.toMatrixBits() : Array<Boolean> { val bits = Array(NuimoLedMatrix.LED_COUNT, { false }) var n = toInt() var i = 0 while (n > 0) { bits[i] = n % 2 > 0 n /= 2 i += 1 } return bits }
mit
c94701d446a91d61e586dde3c3b90b64
22.921053
64
0.611661
3.740741
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/utils/ContactsHelper.kt
1
10745
package de.tum.`in`.tumcampusapp.utils import android.content.ContentProviderOperation import android.content.Context import android.content.OperationApplicationException import android.graphics.Bitmap import android.os.RemoteException import android.provider.ContactsContract import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.component.tumui.person.model.Contact import de.tum.`in`.tumcampusapp.component.tumui.person.model.Employee import java.io.ByteArrayOutputStream import java.io.IOException import java.util.* class ContactsHelper { companion object { @JvmStatic fun saveToContacts(context: Context, employee: Employee) { val ops = ArrayList<ContentProviderOperation>() val rawContactID = ops.size // Adding insert operation to operations list // to insert a new raw contact in the table ContactsContract.RawContacts ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI) .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null) .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null) .build()) // Add full name ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.StructuredName.PREFIX, employee.title) .withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, employee.name) .withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, employee.surname) .build()) // Add e-mail address ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.Email.DATA, employee.email) .withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK) .build()) val substations = employee.telSubstations if (substations != null) { for ((number) in substations) { ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, number) .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_WORK) .build()) } } // Add work: telephone, mobile, fax, website addContact(ops, rawContactID, employee.businessContact, true) // Add home: telephone, mobile, fax, website addContact(ops, rawContactID, employee.privateContact, false) // Add organisations employee.groups?.let { groups -> groups.forEach { group -> ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, group.org) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.Organization.TITLE, group.title) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK) .build()) } } // Add office hours val notes = StringBuilder() notes.append(context.getString(R.string.office_hours)) .append(": ") .append(employee.consultationHours) // saveToContacts all rooms val rooms = employee.rooms if (rooms != null && !rooms.isEmpty()) { if (!notes.toString() .isEmpty()) { notes.append('\n') } notes.append(context.getString(R.string.room)) .append(": ") .append(rooms[0] .location) .append(" (") .append(rooms[0] .number) .append(')') } // Finally saveToContacts notes if (!notes.toString() .isEmpty()) { ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.Note.NOTE, notes.toString()) .build()) } // Add image val bitmap = employee.image if (bitmap != null) { // If an image is selected successfully val stream = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.PNG, 75, stream) // Adding insert operation to operations list // to insert Photo in the table ContactsContract.Data ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID) .withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, stream.toByteArray()) .build()) try { stream.flush() } catch (e: IOException) { Utils.log(e) } } // Executing all the insert operations as a single database transaction try { context.contentResolver.applyBatch(ContactsContract.AUTHORITY, ops) Utils.showToast(context, R.string.contact_added) } catch (e: RemoteException) { Utils.log(e) } catch (e: OperationApplicationException) { Utils.log(e) } } private fun addContact(ops: MutableCollection<ContentProviderOperation>, rawContactID: Int, contact: Contact?, work: Boolean) { if (contact != null) { // Add work telephone number ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, contact.telefon) .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, if (work) ContactsContract.CommonDataKinds.Phone.TYPE_WORK else ContactsContract.CommonDataKinds.Phone.TYPE_HOME) .build()) // Add work mobile number ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, contact.mobilephone) .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, if (work) ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE else ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE) .build()) // Add work fax number ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, contact.fax) .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, if (work) ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK else ContactsContract.CommonDataKinds.Phone.TYPE_FAX_HOME) .build()) // Add website ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.Website.URL, contact.homepage) .withValue(ContactsContract.CommonDataKinds.Website.TYPE, if (work) ContactsContract.CommonDataKinds.Website.TYPE_WORK else ContactsContract.CommonDataKinds.Website.TYPE_HOME) .build()) } } } }
gpl-3.0
70bddea912dededc0cd9dba1a408ffc6
56.774194
154
0.610423
5.823848
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/viewHolders/GroupMemberViewHolder.kt
1
4476
package com.habitrpg.android.habitica.ui.viewHolders import android.annotation.SuppressLint import android.view.MenuItem import android.view.View import androidx.appcompat.widget.PopupMenu import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.databinding.PartyMemberBinding import com.habitrpg.android.habitica.models.members.Member import com.habitrpg.android.habitica.models.user.Stats import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper class GroupMemberViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView), PopupMenu.OnMenuItemClickListener { private val binding = PartyMemberBinding.bind(itemView) private var currentUserID: String? = null private var leaderID: String? = null var onClickEvent: (() -> Unit)? = null var sendMessageEvent: (() -> Unit)? = null var removeMemberEvent: (() -> Unit)? = null var transferOwnershipEvent: (() -> Unit)? = null init { binding.buffIconView.setImageBitmap(HabiticaIconsHelper.imageOfBuffIcon()) itemView.setOnClickListener { onClickEvent?.invoke() } binding.moreButton.setOnClickListener { showOptionsPopup() } } private fun showOptionsPopup() { val popup = PopupMenu(itemView.context, binding.moreButton) popup.setOnMenuItemClickListener(this) val inflater = popup.menuInflater inflater.inflate(R.menu.party_member_menu, popup.menu) popup.menu.findItem(R.id.transfer_ownership).isVisible = currentUserID == leaderID popup.menu.findItem(R.id.remove).isVisible = currentUserID == leaderID popup.show() } override fun onMenuItemClick(item: MenuItem?): Boolean { when (item?.itemId) { R.id.send_message -> { sendMessageEvent?.invoke() } R.id.transfer_ownership -> { transferOwnershipEvent?.invoke() } R.id.remove -> { removeMemberEvent?.invoke() } } return true } @SuppressLint("SetTextI18n") fun bind(user: Member, leaderID: String?, userID: String?) { binding.avatarView.setAvatar(user) this.leaderID = leaderID this.currentUserID = userID if (user.id == userID) { binding.youPill.visibility = View.VISIBLE binding.moreButton.visibility = View.GONE } else { binding.youPill.visibility = View.GONE binding.moreButton.visibility = View.VISIBLE } user.stats?.let { binding.healthBar.set(it.hp ?: 0.0, it.maxHealth?.toDouble() ?: 50.0) binding.healthTextview.text = "${it.hp?.toInt()} / ${it.maxHealth}" binding.experienceBar.set(it.exp ?: 0.0, it.toNextLevel?.toDouble() ?: 0.0) binding.experienceTextview.text = "${it.exp?.toInt()} / ${it.toNextLevel}" binding.manaBar.set(it.mp ?: 0.0, it.maxMP?.toDouble() ?: 0.0) binding.manaTextview.text = "${it.mp?.toInt()} / ${it.maxMP}" } binding.displayNameTextview.username = user.profile?.name binding.displayNameTextview.tier = user.contributor?.level ?: 0 if (user.hasClass) { binding.sublineTextview.text = itemView.context.getString(R.string.user_level_with_class, user.stats?.lvl, user.stats?.getTranslatedClassName(itemView.context.resources)) } else { binding.sublineTextview.text = itemView.context.getString(R.string.user_level, user.stats?.lvl) } if (user.stats?.isBuffed == true) { binding.buffIconView.visibility = View.VISIBLE } else { binding.buffIconView.visibility = View.GONE } binding.classIconView.visibility = View.VISIBLE when (user.stats?.habitClass) { Stats.HEALER -> { binding.classIconView.setImageBitmap(HabiticaIconsHelper.imageOfHealerLightBg()) } Stats.WARRIOR -> { binding.classIconView.setImageBitmap(HabiticaIconsHelper.imageOfWarriorLightBg()) } Stats.ROGUE -> { binding.classIconView.setImageBitmap(HabiticaIconsHelper.imageOfRogueLightBg()) } Stats.MAGE -> { binding.classIconView.setImageBitmap(HabiticaIconsHelper.imageOfMageLightBg()) } else -> { binding.classIconView.visibility = View.INVISIBLE } } itemView.isClickable = true } }
gpl-3.0
74350612e2b7e65e1001167ec5910017
41.226415
182
0.651921
4.493976
false
false
false
false
mtransitapps/commons-android
src/main/java/org/mtransit/android/commons/AppUpdateUtils.kt
1
9914
package org.mtransit.android.commons import android.content.Context import com.google.android.play.core.appupdate.AppUpdateManagerFactory import com.google.android.play.core.install.model.UpdateAvailability import org.json.JSONObject import org.mtransit.android.commons.provider.GTFSProvider import org.mtransit.android.commons.receiver.DataChange import org.mtransit.commons.StringUtils import java.util.concurrent.TimeUnit object AppUpdateUtils : MTLog.Loggable { val LOG_TAG: String = AppUpdateUtils::class.java.simpleName private const val FORCE_CHECK_IN_DEBUG = false // private const val FORCE_CHECK_IN_DEBUG = true // DEBUG private const val FORCE_UPDATE_AVAILABLE = false // private const val FORCE_UPDATE_AVAILABLE = true // DEBUG override fun getLogTag(): String = LOG_TAG private const val PREF_KEY_AVAILABLE_VERSION_CODE = "pAvailableVersionCode" private const val PREF_KEY_AVAILABLE_VERSION_CODE_LAST_CHECK_IN_MS = "pAvailableVersionCodeLastCheckInMs" @JvmStatic @JvmOverloads fun getAvailableVersionCode( context: Context, filterS: String? = null, ): Int { return getLastAvailableVersionCode(context, -1).also { lastAvailableVersionCode -> triggerRefreshIfNecessary(context, lastAvailableVersionCode, AppUpdateFilter.fromJSONString(filterS)) } } @Suppress("unused") private fun hasLastAvailableVersionCode( context: Context ): Boolean { return PreferenceUtils.hasPrefLcl(context, PREF_KEY_AVAILABLE_VERSION_CODE) } @Suppress("SameParameterValue") private fun getLastAvailableVersionCode( context: Context, defaultValue: Int = PackageManagerUtils.getAppVersionCode(context) ): Int { return PreferenceUtils.getPrefLcl(context, PREF_KEY_AVAILABLE_VERSION_CODE, defaultValue) } private fun setAvailableVersionCode( context: Context, lastVersionCode: Int = -1, newVersionCode: Int = PackageManagerUtils.getAppVersionCode(context), sync: Boolean = false ) { MTLog.v(this, "setAvailableVersionCode($newVersionCode)") // DEBUG if (lastVersionCode == newVersionCode) { MTLog.d(this, "setAvailableVersionCode() > SKIP (same version code)") return } PreferenceUtils.savePrefLcl(context, PREF_KEY_AVAILABLE_VERSION_CODE, newVersionCode, sync) } private fun getLastCheckInMs( context: Context, defaultValue: Long = -1L ): Long { return PreferenceUtils.getPrefLcl(context, PREF_KEY_AVAILABLE_VERSION_CODE_LAST_CHECK_IN_MS, defaultValue) } private fun setLastCheckInMs( context: Context, lastCheckInMs: Long = TimeUtils.currentTimeMillis(), sync: Boolean = false ) { MTLog.v(this, "setLastCheckInMs($lastCheckInMs)") // DEBUG PreferenceUtils.savePrefLcl(context, PREF_KEY_AVAILABLE_VERSION_CODE_LAST_CHECK_IN_MS, lastCheckInMs, sync) } private fun setAvailableVersionCodeAndLastCheckInMs( context: Context, lastVersionCode: Int = -1, newVersionCode: Int = PackageManagerUtils.getAppVersionCode(context), lastCheckInMs: Long = TimeUtils.currentTimeMillis(), sync: Boolean = false ) { MTLog.v(this, "setAvailableVersionCodeAndLastCheckInMs($lastVersionCode, $newVersionCode, $lastCheckInMs)") // DEBUG setAvailableVersionCode(context, lastVersionCode, newVersionCode, sync) setLastCheckInMs(context, lastCheckInMs, sync) } private fun triggerRefreshIfNecessary( context: Context, lastAvailableVersionCode: Int, filter: AppUpdateFilter? = null ) { if (!FORCE_CHECK_IN_DEBUG && BuildConfig.DEBUG) { MTLog.d(this, "triggerRefreshIfNecessary() > SKIP (DEBUG build)") return // NO WORKING FOR DEBUG BUILDS } val currentVersionCode = PackageManagerUtils.getAppVersionCode(context) if (currentVersionCode in 1 until lastAvailableVersionCode) { // IF current valid & current < last DO MTLog.d(this, "triggerRefreshIfNecessary() > SKIP (new version code already available ($lastAvailableVersionCode > $currentVersionCode))") return // UPDATE ALREADY AVAILABLE } val lastCheckInMs = getLastCheckInMs(context) MTLog.d(this, "lastCheckInMs: $lastCheckInMs") // DEBUG val shortTimeAgo = TimeUtils.currentTimeMillis() - TimeUnit.HOURS.toMillis(if (filter?.inFocus == true) 6L else 24L) MTLog.d(this, "shortTimeAgo: $shortTimeAgo") // DEBUG if (filter?.forceRefresh != true // not force refresh && lastAvailableVersionCode > 0 // last = valid && shortTimeAgo < lastCheckInMs // too recent ) { val timeLapsedInHours = TimeUnit.MILLISECONDS.toHours(TimeUtils.currentTimeMillis() - lastCheckInMs) MTLog.d(this, "triggerRefreshIfNecessary() > SKIP (last successful refresh too recent ($timeLapsedInHours hours)") return // LAST REFRESH TOO RECENT } if (FORCE_UPDATE_AVAILABLE) { val newAvailableVersionCode = 1 + if (lastAvailableVersionCode > 0) lastAvailableVersionCode else currentVersionCode MTLog.d(this, "triggerRefreshIfNecessary() > FORCE_UPDATE_AVAILABLE to $newAvailableVersionCode.") setAvailableVersionCodeAndLastCheckInMs(context, lastAvailableVersionCode, newAvailableVersionCode, TimeUtils.currentTimeMillis()) broadcastUpdateAvailable(lastAvailableVersionCode, currentVersionCode, newAvailableVersionCode, context) return // USE DEBUG FORCE UPDATE++ } val appUpdateManager = AppUpdateManagerFactory.create(context) val appUpdateInfoTask = appUpdateManager.appUpdateInfo appUpdateInfoTask.addOnCompleteListener { task -> // ASYNC if (!task.isSuccessful) { if (BuildConfig.DEBUG) { MTLog.d(this, task.exception, "App update info did NOT complete successfully!") } else { MTLog.w(this, task.exception, "App update info did NOT complete successfully!") } return@addOnCompleteListener } val appUpdateInfo = task.result ?: return@addOnCompleteListener when (appUpdateInfo.updateAvailability()) { UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS -> { MTLog.d(this, "Update in progress already triggered by developer") } UpdateAvailability.UNKNOWN -> { MTLog.d(this, "Update status unknown") } UpdateAvailability.UPDATE_NOT_AVAILABLE -> { MTLog.d(this, "Update NOT available") if (currentVersionCode > 0) { setAvailableVersionCodeAndLastCheckInMs(context, lastAvailableVersionCode, currentVersionCode, TimeUtils.currentTimeMillis()) } } UpdateAvailability.UPDATE_AVAILABLE -> { MTLog.d(this, "Update available") val newAvailableVersionCode = appUpdateInfo.availableVersionCode() if (newAvailableVersionCode > 0) { setAvailableVersionCodeAndLastCheckInMs(context, lastAvailableVersionCode, newAvailableVersionCode, TimeUtils.currentTimeMillis()) broadcastUpdateAvailable(lastAvailableVersionCode, currentVersionCode, newAvailableVersionCode, context) } } } } } private fun broadcastUpdateAvailable( lastAvailableVersionCode: Int, currentVersionCode: Int, newAvailableVersionCode: Int, context: Context ) { if ((lastAvailableVersionCode == -1 || lastAvailableVersionCode == currentVersionCode) // last was unknown OR same as current && newAvailableVersionCode > lastAvailableVersionCode // AND new is newer than last => available update just discovered ) { DataChange.broadcastDataChange(context, GTFSProvider.getAUTHORITY(context), context.packageName, true) // trigger update in MT } } data class AppUpdateFilter( val forceRefresh: Boolean = false, val inFocus: Boolean = false ) { companion object { private const val JSON_FORCE_REFRESH = "force_refresh" private const val JSON_IN_FOCUS = "in_focus" @JvmStatic fun fromJSONString(filterS: String?): AppUpdateFilter { try { if (!filterS.isNullOrBlank()) { val json = JSONObject(filterS) return AppUpdateFilter( forceRefresh = json.optBoolean(JSON_FORCE_REFRESH, false), inFocus = json.optBoolean(JSON_IN_FOCUS, false) ) } } catch (e: Exception) { MTLog.w(LOG_TAG, e, "Error while parsing app update filter '$filterS'!") } return AppUpdateFilter() // DEFAULT VALUES } @JvmStatic fun toJSONString(filter: AppUpdateFilter?): String { return try { JSONObject().apply { put(JSON_FORCE_REFRESH, filter?.forceRefresh) put(JSON_IN_FOCUS, filter?.inFocus) }.toString() } catch (e: Exception) { MTLog.w(LOG_TAG, e, "Error while serializing app update filter '$filter'!") StringUtils.EMPTY } } } @Suppress("unused") fun toJSONString() = toJSONString(this) } }
apache-2.0
299d572dc13a63148d59e8ecebe8edd8
44.068182
154
0.636978
5.474324
false
false
false
false
divinespear/jpa-schema-gradle-plugin
src/test/kotlin/io/github/divinespear/plugin/FormatTest.kt
1
3099
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.github.divinespear.plugin import io.kotest.core.spec.style.WordSpec import io.kotest.matchers.shouldBe class FormatTest : WordSpec() { companion object { val LINE_SEPARATOR = System.getProperty("line.separator") ?: "\n"; } init { "create table" should { "format well" { val source = "CREATE TABLE SYSTEM_CURRENCY_RATE_HISTORY (CREATED_DATE DATETIME NULL,LAST_MODIFIED_DATE DATETIME NULL,RATE NUMERIC(28) NULL,VERSION NUMERIC(19) NOT NULL,REFERENCE_ID VARCHAR(255) NOT NULL,CREATED_BY VARCHAR(36) NULL,LAST_MODIFIED_BY VARCHAR(36) NULL,PRIMARY KEY (VERSION,REFERENCE_ID));"; val expected = """CREATE TABLE SYSTEM_CURRENCY_RATE_HISTORY ( CREATED_DATE DATETIME NULL, LAST_MODIFIED_DATE DATETIME NULL, RATE NUMERIC(28) NULL, VERSION NUMERIC(19) NOT NULL, REFERENCE_ID VARCHAR(255) NOT NULL, CREATED_BY VARCHAR(36) NULL, LAST_MODIFIED_BY VARCHAR(36) NULL, PRIMARY KEY (VERSION, REFERENCE_ID) );""".trimIndent() val actual = format(source, LINE_SEPARATOR) actual shouldBe expected } "format well with options" { val source = "CREATE TEMPORARY TABLE SYSTEM_CURRENCY_RATE_HISTORY (CREATED_DATE DATETIME NULL,LAST_MODIFIED_DATE DATETIME NULL,RATE NUMERIC(28) NULL,VERSION NUMERIC(19) NOT NULL,REFERENCE_ID VARCHAR(255) NOT NULL,CREATED_BY VARCHAR(36) NULL,LAST_MODIFIED_BY VARCHAR(36) NULL,PRIMARY KEY (VERSION,REFERENCE_ID));" val expected = """CREATE TEMPORARY TABLE SYSTEM_CURRENCY_RATE_HISTORY ( CREATED_DATE DATETIME NULL, LAST_MODIFIED_DATE DATETIME NULL, RATE NUMERIC(28) NULL, VERSION NUMERIC(19) NOT NULL, REFERENCE_ID VARCHAR(255) NOT NULL, CREATED_BY VARCHAR(36) NULL, LAST_MODIFIED_BY VARCHAR(36) NULL, PRIMARY KEY (VERSION, REFERENCE_ID) );""".trimIndent() val actual = format(source, LINE_SEPARATOR) actual shouldBe expected } } "issue #9" should { "be fixed illegal syntax" { val source = "CREATE INDEX INDEX_SYSTEM_CURRENCY_RATE_VERSION DESC ON SYSTEM_CURRENCY_RATE (VERSION DESC);" val expected = "CREATE INDEX INDEX_SYSTEM_CURRENCY_RATE_VERSION ON SYSTEM_CURRENCY_RATE (VERSION DESC);" val actual = formatLine(source) actual shouldBe expected } } } }
apache-2.0
673055895e23a2d153f8da36a8217d77
38.730769
309
0.711843
4.040417
false
false
false
false
walleth/walleth
app/src/main/java/org/walleth/request/RequestActivity.kt
1
5637
package org.walleth.request import android.content.Intent import android.os.Bundle import android.text.method.LinkMovementMethod import android.view.Menu import android.view.MenuItem import androidx.lifecycle.lifecycleScope import kotlinx.android.synthetic.main.activity_request.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.kethereum.erc681.ERC681 import org.kethereum.erc681.generateURL import org.kethereum.model.ChainId import org.koin.android.ext.android.inject import org.ligi.compat.HtmlCompat import org.ligi.kaxt.setVisibility import org.walleth.R import org.walleth.base_activities.BaseSubActivity import org.walleth.chains.ChainInfoProvider import org.walleth.chains.getFaucetURL import org.walleth.data.addresses.CurrentAddressProvider import org.walleth.data.exchangerate.ExchangeRateProvider import org.walleth.data.tokens.CurrentTokenProvider import org.walleth.data.tokens.isRootToken import org.walleth.qr.show.getQRCodeIntent import org.walleth.util.copyToClipboard import org.walleth.util.setQRCode import org.walleth.valueview.ValueViewController class RequestActivity : BaseSubActivity() { private lateinit var currentERC67String: String private val currentAddressProvider: CurrentAddressProvider by inject() private val currentTokenProvider: CurrentTokenProvider by inject() private val chainInfoProvider: ChainInfoProvider by inject() private val exchangeRateProvider: ExchangeRateProvider by inject() private var valueInputController: ValueViewController? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_request) supportActionBar?.subtitle = getString(R.string.request_transaction_subtitle) valueInputController = object : ValueViewController(value_input, exchangeRateProvider, settings) { override fun refreshNonValues() { super.refreshNonValues() refreshQR() } } lifecycleScope.launch(Dispatchers.Main) { val initText = if (chainInfoProvider.getCurrent().faucets.isNotEmpty()) { val faucetURL = chainInfoProvider.getCurrent().getFaucetURL(currentAddressProvider.getCurrentNeverNull()) getString(R.string.request_faucet_message, chainInfoProvider.getCurrent()!!.name, faucetURL) } else { getString(R.string.no_faucet) } request_hint.text = HtmlCompat.fromHtml(initText) request_hint.movementMethod = LinkMovementMethod() } add_value_checkbox.setOnCheckedChangeListener { _, isChecked -> value_input.setVisibility(isChecked) refreshQR() } receive_qrcode.setOnClickListener { startActivity(getQRCodeIntent(currentERC67String, showAlternateText = true)) } } override fun onResume() { super.onResume() refreshQR() lifecycleScope.launch(Dispatchers.Main) { valueInputController?.setValue(valueInputController?.getValueOrZero(), currentTokenProvider.getCurrent()) } } private fun refreshQR() { lifecycleScope.launch(Dispatchers.Main) { val currentToken = currentTokenProvider.getCurrent() if (!add_value_checkbox.isChecked || currentToken.isRootToken()) { val relevantAddress = currentAddressProvider.getCurrent() currentERC67String = ERC681(address = relevantAddress!!.hex).generateURL() if (add_value_checkbox.isChecked) { try { currentERC67String = ERC681( address = relevantAddress.hex, value = valueInputController?.getValueOrZero(), chainId = chainInfoProvider.getCurrent()?.let { ChainId(it.chainId) } ).generateURL() } catch (e: NumberFormatException) { } } } else { val relevantAddress = currentToken.address.hex val userAddress = currentAddressProvider.getCurrentNeverNull().hex val functionParams = mutableListOf("address" to userAddress) if (add_value_checkbox.isChecked) { try { functionParams.add("uint256" to valueInputController?.getValueOrZero().toString()) } catch (e: NumberFormatException) { } } currentERC67String = ERC681(address = relevantAddress, function = "transfer", functionParams = functionParams).generateURL() } receive_qrcode.setQRCode(currentERC67String) } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_request, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.menu_share -> true.also { val sendIntent = Intent().apply { action = Intent.ACTION_SEND putExtra(Intent.EXTRA_TEXT, currentERC67String) type = "text/plain" } startActivity(sendIntent) } R.id.menu_copy -> true.also { copyToClipboard(currentERC67String, receive_qrcode) } else -> super.onOptionsItemSelected(item) } }
gpl-3.0
5365e8ac3dc698e07892573f0045e92f
37.609589
121
0.65141
5.287992
false
false
false
false
MarkNKamau/JustJava-Android
app/src/androidTest/java/com/marknkamau/justjava/testUtils/SampleData.kt
1
1708
package com.marknkamau.justjava.testUtils import com.marknjunge.core.data.model.* import com.marknkamau.justjava.data.models.CartItem import com.marknkamau.justjava.data.models.CartOptionEntity import com.marknkamau.justjava.data.models.CartProductEntity object SampleData { val address = Address(0, "Street", "instructions", "-1,1") val user = User(1, "fName", "lName", 0L, "254712345678", "[email protected]", "token", "PASSWORD", listOf(address)) val productChoiceOption = ProductChoiceOption(0, 0.0, "Single", "A single shot of coffee") val productChoice = ProductChoice(0, "Single, double or triple", 0, 1, 0, listOf(productChoiceOption)) val product = Product( 1, "Americano", "americano", "https://res.cloudinary.com/marknjunge/justjava/products/americano.jpg", 1574605132, 120.0, "Italian espresso gets the American treatment; hot water fills the cup for a rich alternative to drip coffee.", "coffee", listOf(productChoice), "enabled" ) val cartOptionEntity = CartOptionEntity(0, 0, "Single, double or triple", 0, "Single", 20.0, 0) val cartItem = CartItem(CartProductEntity(0L, 0L, "Americano", 120.0, 120.0, 1), listOf(cartOptionEntity)) val cartItems = listOf(cartItem) val verifyOrderResponse = VerifyOrderResponse(0, "error", ErrorType.MISSING, ErrorModel.CHOICE, 0, 200.0) val orderItem = OrderItem(1, 1, 120.0, 120.0, "Americano", listOf(OrderItemOption(1, "Single, double or triple", 3, 0.0, 44, "Single"))) val order = Order(null, 1579505466, 120.0, PaymentMethod.MPESA, "AGV7OBST", 1, listOf(orderItem), PaymentStatus.PAID, OrderStatus.PENDING, 0) }
apache-2.0
fe3e0db62d1133a0f82d78f2f3dce62b
46.472222
140
0.69555
3.565762
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/presentation/library/components/LibraryCoverOnlyGrid.kt
1
2857
package eu.kanade.presentation.library.components import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.lazy.grid.items import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.util.fastAny import eu.kanade.domain.library.model.LibraryManga import eu.kanade.tachiyomi.ui.library.LibraryItem @Composable fun LibraryCoverOnlyGrid( items: List<LibraryItem>, showDownloadBadges: Boolean, showUnreadBadges: Boolean, showLocalBadges: Boolean, showLanguageBadges: Boolean, columns: Int, contentPadding: PaddingValues, selection: List<LibraryManga>, onClick: (LibraryManga) -> Unit, onLongClick: (LibraryManga) -> Unit, searchQuery: String?, onGlobalSearchClicked: () -> Unit, ) { LazyLibraryGrid( modifier = Modifier.fillMaxSize(), columns = columns, contentPadding = contentPadding, ) { globalSearchItem(searchQuery, onGlobalSearchClicked) items( items = items, contentType = { "library_only_cover_grid_item" }, ) { libraryItem -> LibraryCoverOnlyGridItem( item = libraryItem, showDownloadBadge = showDownloadBadges, showUnreadBadge = showUnreadBadges, showLocalBadge = showLocalBadges, showLanguageBadge = showLanguageBadges, isSelected = selection.fastAny { it.id == libraryItem.libraryManga.id }, onClick = onClick, onLongClick = onLongClick, ) } } } @Composable fun LibraryCoverOnlyGridItem( item: LibraryItem, showDownloadBadge: Boolean, showUnreadBadge: Boolean, showLocalBadge: Boolean, showLanguageBadge: Boolean, isSelected: Boolean, onClick: (LibraryManga) -> Unit, onLongClick: (LibraryManga) -> Unit, ) { val libraryManga = item.libraryManga val manga = libraryManga.manga LibraryGridCover( modifier = Modifier .selectedOutline(isSelected) .combinedClickable( onClick = { onClick(libraryManga) }, onLongClick = { onLongClick(libraryManga) }, ), mangaCover = eu.kanade.domain.manga.model.MangaCover( manga.id, manga.source, manga.favorite, manga.thumbnailUrl, manga.coverLastModified, ), item = item, showDownloadBadge = showDownloadBadge, showUnreadBadge = showUnreadBadge, showLocalBadge = showLocalBadge, showLanguageBadge = showLanguageBadge, ) }
apache-2.0
1e6994d92041f6858731ecfbf9ec7a87
30.744444
88
0.639482
5.204007
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/presentation/components/LazyList.kt
1
4508
package eu.kanade.presentation.components import androidx.compose.foundation.gestures.FlingBehavior import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.calculateEndPadding import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.unit.dp import eu.kanade.presentation.util.drawVerticalScrollbar import eu.kanade.presentation.util.flingBehaviorIgnoringMotionScale /** * LazyColumn with fling animation fix * * @see flingBehaviorIgnoringMotionScale */ @Composable fun LazyColumn( modifier: Modifier = Modifier, state: LazyListState = rememberLazyListState(), contentPadding: PaddingValues = PaddingValues(0.dp), reverseLayout: Boolean = false, verticalArrangement: Arrangement.Vertical = if (!reverseLayout) Arrangement.Top else Arrangement.Bottom, horizontalAlignment: Alignment.Horizontal = Alignment.Start, flingBehavior: FlingBehavior = flingBehaviorIgnoringMotionScale(), userScrollEnabled: Boolean = true, content: LazyListScope.() -> Unit, ) { androidx.compose.foundation.lazy.LazyColumn( modifier = modifier, state = state, contentPadding = contentPadding, reverseLayout = reverseLayout, verticalArrangement = verticalArrangement, horizontalAlignment = horizontalAlignment, flingBehavior = flingBehavior, userScrollEnabled = userScrollEnabled, content = content, ) } /** * LazyColumn with scrollbar. */ @Composable fun ScrollbarLazyColumn( modifier: Modifier = Modifier, state: LazyListState = rememberLazyListState(), contentPadding: PaddingValues = PaddingValues(0.dp), reverseLayout: Boolean = false, verticalArrangement: Arrangement.Vertical = if (!reverseLayout) Arrangement.Top else Arrangement.Bottom, horizontalAlignment: Alignment.Horizontal = Alignment.Start, flingBehavior: FlingBehavior = flingBehaviorIgnoringMotionScale(), userScrollEnabled: Boolean = true, content: LazyListScope.() -> Unit, ) { val direction = LocalLayoutDirection.current val density = LocalDensity.current val positionOffset = remember(contentPadding) { with(density) { contentPadding.calculateEndPadding(direction).toPx() } } LazyColumn( modifier = modifier .drawVerticalScrollbar( state = state, reverseScrolling = reverseLayout, positionOffsetPx = positionOffset, ), state = state, contentPadding = contentPadding, reverseLayout = reverseLayout, verticalArrangement = verticalArrangement, horizontalAlignment = horizontalAlignment, flingBehavior = flingBehavior, userScrollEnabled = userScrollEnabled, content = content, ) } /** * LazyColumn with fast scroller. */ @Composable fun FastScrollLazyColumn( modifier: Modifier = Modifier, state: LazyListState = rememberLazyListState(), contentPadding: PaddingValues = PaddingValues(0.dp), reverseLayout: Boolean = false, verticalArrangement: Arrangement.Vertical = if (!reverseLayout) Arrangement.Top else Arrangement.Bottom, horizontalAlignment: Alignment.Horizontal = Alignment.Start, flingBehavior: FlingBehavior = flingBehaviorIgnoringMotionScale(), userScrollEnabled: Boolean = true, content: LazyListScope.() -> Unit, ) { VerticalFastScroller( listState = state, modifier = modifier, topContentPadding = contentPadding.calculateTopPadding(), endContentPadding = contentPadding.calculateEndPadding(LocalLayoutDirection.current), ) { LazyColumn( state = state, contentPadding = contentPadding, reverseLayout = reverseLayout, verticalArrangement = verticalArrangement, horizontalAlignment = horizontalAlignment, flingBehavior = flingBehavior, userScrollEnabled = userScrollEnabled, content = content, ) } }
apache-2.0
3443633b61dd2e8929a5ad812b339e01
35.650407
93
0.727152
5.735369
false
false
false
false
Heiner1/AndroidAPS
database/src/main/java/info/nightscout/androidaps/database/transactions/SyncPumpCancelExtendedBolusIfAnyTransaction.kt
1
1458
package info.nightscout.androidaps.database.transactions import info.nightscout.androidaps.database.embedments.InterfaceIDs import info.nightscout.androidaps.database.entities.ExtendedBolus import info.nightscout.androidaps.database.interfaces.end class SyncPumpCancelExtendedBolusIfAnyTransaction( private val timestamp: Long, private val endPumpId: Long, private val pumpType: InterfaceIDs.PumpType, private val pumpSerial: String ) : Transaction<SyncPumpCancelExtendedBolusIfAnyTransaction.TransactionResult>() { override fun run(): TransactionResult { val result = TransactionResult() val existing = database.extendedBolusDao.findByPumpEndIds(endPumpId, pumpType, pumpSerial) if (existing != null) // assume EB has been cut already return result val running = database.extendedBolusDao.getExtendedBolusActiveAt(timestamp).blockingGet() if (running != null && running.interfaceIDs.endId == null) { // do not allow overwrite if cut by end event val pctRun = (timestamp - running.timestamp) / running.duration.toDouble() running.amount *= pctRun running.end = timestamp running.interfaceIDs.endId = endPumpId database.extendedBolusDao.updateExistingEntry(running) result.updated.add(running) } return result } class TransactionResult { val updated = mutableListOf<ExtendedBolus>() } }
agpl-3.0
601b2b12533c8031c43774cc2365e13d
44.59375
137
0.727023
5.301818
false
false
false
false
square/wire
wire-library/wire-tests/src/commonTest/kotlin/com/squareup/wire/ParseTest.kt
1
3624
/* * Copyright 2014 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire import com.squareup.wire.internal.ProtocolException import com.squareup.wire.protos.kotlin.edgecases.OneBytesField import com.squareup.wire.protos.kotlin.edgecases.OneField import com.squareup.wire.protos.kotlin.edgecases.Recursive import okio.ByteString import okio.ByteString.Companion.decodeHex import okio.EOFException import okio.IOException import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotEquals import kotlin.test.fail class ParseTest { @Test fun unknownTagIgnored() { // tag 1 / type 0: 456 // tag 2 / type 0: 789 val data = "08c803109506".decodeHex() val oneField = OneField.ADAPTER.decode(data.toByteArray()) val expected = OneField(opt_int32 = 456) assertNotEquals(expected, oneField) assertEquals(expected, oneField.copy(unknownFields = ByteString.EMPTY)) } @Test fun unknownTypeThrowsIOException() { // tag 1 / type 0: 456 // tag 2 / type 7: 789 val data = "08c803179506".decodeHex() try { OneField.ADAPTER.decode(data.toByteArray()) fail() } catch (expected: ProtocolException) { assertEquals("Unexpected field encoding: 7", expected.message) } } @Test fun truncatedMessageThrowsEOFException() { // tag 1 / 4-byte length delimited string: 0x000000 (3 bytes) val data = "0a04000000".decodeHex() try { OneBytesField.ADAPTER.decode(data.toByteArray()) fail() } catch (expected: EOFException) { } } @Test fun lastValueWinsForRepeatedValueOfNonrepeatedField() { // tag 1 / type 0: 456 // tag 1 / type 0: 789 val data = "08c803089506".decodeHex() val oneField = OneField.ADAPTER.decode(data.toByteArray()) assertEquals(oneField, OneField(opt_int32 = 789)) } @Test fun upToRecursionLimit() { // tag 2: nested message (64 times) // tag 1: signed varint32 456 val data = ( "127e127c127a12781276127412721270126e126c126a12681266126" + "412621260125e125c125a12581256125412521250124e124c124a12481246124412421240123e123c123a123" + "81236123412321230122e122c122a12281226122412221220121e121c121a12181216121412121210120e120" + "c120a1208120612041202120008c803" ).decodeHex() val recursive = Recursive.ADAPTER.decode(data.toByteArray()) assertEquals(456, recursive.value_!!.toInt()) } @Test fun overRecursionLimitThrowsIOException() { // tag 2: nested message (65 times) // tag 1: signed varint32 456 val data = ( "128001127e127c127a12781276127412721270126e126c126a12681" + "266126412621260125e125c125a12581256125412521250124e124c124a12481246124412421240123e123c1" + "23a12381236123412321230122e122c122a12281226122412221220121e121c121a121812161214121212101" + "20e120c120a1208120612041202120008c803" ).decodeHex() try { Recursive.ADAPTER.decode(data.toByteArray()) fail() } catch (expected: IOException) { assertEquals("Wire recursion limit exceeded", expected.message) } } }
apache-2.0
a248a73562b1f5b5d2fbde6ace427d9b
32.869159
100
0.725717
3.602386
false
true
false
false
PolymerLabs/arcs
java/arcs/core/analysis/EntityTypeOperations.kt
1
3244
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.analysis import arcs.core.data.EntityType import arcs.core.data.FieldName import arcs.core.data.FieldType import arcs.core.data.Schema import arcs.core.data.SchemaFields /** Returns the union of two [EntityType] instances. */ infix fun EntityType.union(other: EntityType) = EntityType(entitySchema union other.entitySchema) /** Returns the intersection of two [EntityType] instances. */ infix fun EntityType.intersect(other: EntityType): EntityType { return EntityType(entitySchema intersect other.entitySchema) } /** * Computes the union of the two [Schema] instances. Returns [Outcome.Failure] if the union * is not possible as the inputs are incompatible. */ infix fun Schema.union(other: Schema): Schema { // TODO(b/154235149): hash, refinement, query return Schema( names = names union other.names, fields = fields union other.fields, hash = "" ) } /** Computes the intersection of the two [Schema] instances. */ infix fun Schema.intersect(other: Schema): Schema { // TODO(b/154235149): hash, refinement, query return Schema( names = names intersect other.names, fields = fields intersect other.fields, hash = "" ) } /** * Computes the union of [SchemaFields] instances. Returns [Outcome.Failure] if the union * results in any incompatibility. e.g., incompatible [FieldType] with the same name. */ private infix fun SchemaFields.union(other: SchemaFields): SchemaFields { return SchemaFields( singletons = singletons union other.singletons, collections = collections union other.collections ) } /** Computes the intersection of [SchemaFields] instances. */ private infix fun SchemaFields.intersect(other: SchemaFields): SchemaFields { return SchemaFields( singletons = singletons intersect other.singletons, collections = collections intersect other.collections ) } /** * Returns the result of combining two different field maps. * * If the maps have common [FieldName] entries, the union succeeds if and only if the corresponding * [FieldType] values are the same. */ private infix fun Map<FieldName, FieldType>.union( other: Map<FieldName, FieldType> ): Map<FieldName, FieldType> { val result = mutableMapOf<FieldName, FieldType>() result.putAll(this) other.forEach { (name, type) -> val existing = this[name] if (existing != null && type != existing) { throw TypeCheckException( "Incompatible types for field '$name': $type vs. $existing." ) } result[name] = type } return result } /** Returns the intersection of two field maps. */ private infix fun Map<FieldName, FieldType>.intersect( other: Map<FieldName, FieldType> ): Map<FieldName, FieldType> { // TODO(b/156983624): Reference fields should not be compared with equality. Instead we should // descend into the nested schema and recursively intersect those too. return filter { (name, type) -> other[name] == type } }
bsd-3-clause
15f1b18cf62acf3f25cd3ceb562e2ad6
31.44
99
0.726264
4.175032
false
false
false
false
JStege1206/AdventOfCode
aoc-2015/src/main/kotlin/nl/jstege/adventofcode/aoc2015/days/Day20.kt
1
2102
package nl.jstege.adventofcode.aoc2015.days import nl.jstege.adventofcode.aoccommon.days.Day import nl.jstege.adventofcode.aoccommon.utils.extensions.head /** * * @author Jelle Stege */ class Day20 : Day(title = "Infinite Elves and Infinite Houses") { private companion object Configuration { private const val FIRST_PRESENTS_PER_HOUSE = 10 private const val SECOND_PRESENTS_PER_HOUSE = 11 private const val MAX_HOUSES_VISITED = 50 } override fun first(input: Sequence<String>): Any { val wantedPresents = input.head.toInt() val elves = mutableMapOf<Int, MutableList<Int>>() var elf = 1 var presents = 0 while (elf <= wantedPresents / 10 && presents <= wantedPresents) { val elfList = elves.getOrPut(elf) { mutableListOf() } elfList += elf presents = elfList.sum() * FIRST_PRESENTS_PER_HOUSE if (presents >= wantedPresents) { break } elfList .filter { elf + it <= wantedPresents / 10 } .forEach { elves.getOrPut(elf + it) { mutableListOf() } += it } elf++ } return elf } override fun second(input: Sequence<String>): Any { val wantedPresents = input.head.toInt() val elves = mutableMapOf<Int, MutableList<Int>>() var elf = 1 var presents = 0 while (elf <= (wantedPresents / 10) && presents <= wantedPresents) { if (elf !in elves) { elves[elf] = mutableListOf() } val elfList = elves.remove(elf)!! elfList += elf presents = elfList.sum() * SECOND_PRESENTS_PER_HOUSE if (presents >= wantedPresents) { break } elfList .filter { (elf + it < wantedPresents / 10) && (elf + it <= it * MAX_HOUSES_VISITED) } .forEach { elves.getOrPut(elf + it) { mutableListOf() } += it } elf++ } return elf } }
mit
1c33b606401e86e8911489ee6eec02c8
29.911765
93
0.539486
4.58952
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/component/impl/textedit/EditableTextBuffer.kt
1
1752
package org.hexworks.zircon.internal.component.impl.textedit import org.hexworks.zircon.api.data.Position import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.internal.component.impl.textedit.cursor.Cursor import org.hexworks.zircon.platform.util.SystemUtils interface EditableTextBuffer { var cursor: Cursor val textBuffer: MutableList<MutableList<Char>> fun applyTransformation(transformation: TextBufferTransformation): EditableTextBuffer fun getLastRowIdx(): Int = textBuffer.size - 1 fun getLastColumnIdxForRow(rowIdx: Int): Int = textBuffer[rowIdx].size - 1 fun getColumnCount(rowIdx: Int): Int = textBuffer[rowIdx].size fun getRow(rowIdx: Int): MutableList<Char> = textBuffer[rowIdx] fun deleteRow(rowIdx: Int): MutableList<Char> = textBuffer.removeAt(rowIdx) fun getBoundingBoxSize(): Size = Size.create( width = textBuffer.asSequence() .map { it.size } .maxOrNull() ?: 0, height = textBuffer.size) fun getText(): String = textBuffer.joinToString(SystemUtils.getLineSeparator()) { it.joinToString("") } fun getSize() = textBuffer.size fun getCharAtOrNull(position: Position): Char? = if (position.y >= textBuffer.size || textBuffer[position.y].size <= position.x) { null } else { textBuffer[position.y][position.x] } fun getCharAtOrElse( position: Position, other: (Position) -> Char ): Char = getCharAtOrNull(position) ?: other(position) fun rowCount(): Int = textBuffer.size companion object { fun create(text: String = "", cursor: Cursor = Cursor()): EditableTextBuffer = DefaultEditableTextBuffer(text, cursor) } }
apache-2.0
c13b24d04ce305eea7a1191f4c2f35af
30.854545
107
0.685502
4.503856
false
false
false
false
RadiationX/ForPDA
app/src/main/java/forpdateam/ru/forpda/ui/fragments/news/details/NewsDetailsFragment.kt
1
11029
package forpdateam.ru.forpda.ui.fragments.news.details import android.graphics.Bitmap import android.graphics.Color import android.graphics.PorterDuff import android.os.Bundle import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.viewpager.widget.ViewPager import android.util.Log import android.view.LayoutInflater import android.view.Menu import android.view.View import android.view.ViewGroup import android.view.ViewStub import android.widget.ImageView import android.widget.ProgressBar import android.widget.TextView import moxy.presenter.InjectPresenter import moxy.presenter.ProvidePresenter import com.nostra13.universalimageloader.core.ImageLoader import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener import java.util.ArrayList import forpdateam.ru.forpda.App import forpdateam.ru.forpda.R import forpdateam.ru.forpda.entity.remote.news.DetailsPage import forpdateam.ru.forpda.model.interactors.news.ArticleInteractor import forpdateam.ru.forpda.presentation.articles.detail.ArticleDetailPresenter import forpdateam.ru.forpda.presentation.articles.detail.ArticleDetailView import forpdateam.ru.forpda.ui.activities.MainActivity import forpdateam.ru.forpda.ui.fragments.TabFragment import forpdateam.ru.forpda.ui.fragments.TabTopScroller import forpdateam.ru.forpda.ui.fragments.notes.NotesAddPopup import forpdateam.ru.forpda.ui.views.ExtendedWebView import forpdateam.ru.forpda.ui.views.ScrimHelper /** * Created by isanechek on 8/19/17. */ class NewsDetailsFragment : TabFragment(), ArticleDetailView, TabTopScroller { lateinit var fragmentsPager: androidx.viewpager.widget.ViewPager private set private lateinit var progressBar: ProgressBar private lateinit var imageProgressBar: ProgressBar private lateinit var detailsImage: ImageView private lateinit var detailsTitle: TextView private lateinit var detailsNick: TextView private lateinit var detailsCount: TextView private lateinit var detailsDate: TextView private var isResume = false private var isScrim = false private val interactor = ArticleInteractor( ArticleInteractor.InitData(), App.get().Di().newsRepository, App.get().Di().articleTemplate ) @InjectPresenter lateinit var presenter: ArticleDetailPresenter fun provideChildInteractor(): ArticleInteractor { return interactor } fun getAppBar() = appBarLayout public override fun attachWebView(webView: ExtendedWebView) { super.attachWebView(webView) } @ProvidePresenter fun providePresenter(): ArticleDetailPresenter = ArticleDetailPresenter( interactor, App.get().Di().router, App.get().Di().linkHandler, App.get().Di().errorHandler ) init { configuration.defaultTitle = App.get().getString(R.string.fragment_title_news) configuration.isFitSystemWindow = true } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.e("lalala", "onCreate " + this + " : " + arguments) arguments?.apply { interactor.initData.newsUrl = getString(ARG_NEWS_URL) interactor.initData.newsId = getInt(ARG_NEWS_ID, 0) interactor.initData.commentId = getInt(ARG_NEWS_COMMENT_ID, 0) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) baseInflateFragment(inflater, R.layout.fragment_article) val viewStub = findViewById(R.id.toolbar_content) as ViewStub viewStub.layoutResource = R.layout.toolbar_news_details viewStub.inflate() fragmentsPager = findViewById(R.id.view_pager) as androidx.viewpager.widget.ViewPager progressBar = findViewById(R.id.progress_bar) as ProgressBar detailsImage = findViewById(R.id.article_image) as ImageView detailsTitle = findViewById(R.id.article_title) as TextView detailsNick = findViewById(R.id.article_nick) as TextView detailsCount = findViewById(R.id.article_comments_count) as TextView detailsDate = findViewById(R.id.article_date) as TextView imageProgressBar = findViewById(R.id.article_progress_bar) as ProgressBar detailsImage.maxHeight = App.px24 * 10 setScrollFlagsExitUntilCollapsed() return viewFragment } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val scrimHelper = ScrimHelper(appBarLayout, toolbarLayout) scrimHelper.setScrimListener { scrim1 -> isScrim = scrim1 if (scrim1) { toolbar.navigationIcon?.clearColorFilter() toolbar.overflowIcon?.clearColorFilter() toolbarTitleView.visibility = View.VISIBLE } else { toolbar.navigationIcon?.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP) toolbar.overflowIcon?.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP) toolbarTitleView.visibility = View.GONE } updateStatusBar() } arguments?.apply { val newsTitle = getString(ARG_NEWS_TITLE) val newsNick = getString(ARG_NEWS_AUTHOR_NICK) val newsDate = getString(ARG_NEWS_DATE) val newsImageUrl = getString(ARG_NEWS_IMAGE) val newsCount = getInt(ARG_NEWS_COMMENTS_COUNT, -1) if (newsTitle != null) { setTitle(newsTitle) setTabTitle(String.format(getString(R.string.fragment_tab_title_article), newsTitle)) detailsTitle.text = newsTitle } if (newsNick != null) { detailsNick.text = newsNick } if (newsCount != -1) { detailsCount.text = newsCount.toString() } if (newsDate != null) { detailsDate.text = newsDate } if (newsImageUrl != null) { showArticleImage(newsImageUrl) } } toolbarTitleView.visibility = View.GONE toolbar.navigationIcon?.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP) toolbar.overflowIcon?.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP) detailsNick.setOnClickListener { presenter.openAuthorProfile() } } override fun toggleScrollTop() { ((fragmentsPager.adapter as FragmentPagerAdapter).getItem(fragmentsPager.currentItem) as? TabTopScroller)?.toggleScrollTop() } override fun addBaseToolbarMenu(menu: Menu) { super.addBaseToolbarMenu(menu) menu.add(R.string.copy_link) .setOnMenuItemClickListener { presenter.copyLink() false } menu.add(R.string.share) .setOnMenuItemClickListener { presenter.shareLink() false } menu.add(R.string.create_note) .setOnMenuItemClickListener { presenter.createNote() false } } override fun onBackPressed(): Boolean { if (fragmentsPager.currentItem == 1) { fragmentsPager.currentItem = 0 return true } return super.onBackPressed() } override fun onResumeOrShow() { super.onResumeOrShow() isResume = true updateStatusBar() } override fun onPauseOrHide() { super.onPauseOrHide() isResume = false updateStatusBar() } private fun updateStatusBar() { val defaultSb = MainActivity.getDefaultLightStatusBar(activity!!) if (isResume) { MainActivity.setLightStatusBar(activity!!, isScrim && defaultSb) } else { MainActivity.setLightStatusBar(activity!!, defaultSb) } } override fun setRefreshing(isRefreshing: Boolean) { progressBar.visibility = if (isRefreshing) View.VISIBLE else View.GONE } override fun showArticle(data: DetailsPage) { setTitle(data.title) setTabTitle(String.format(getString(R.string.fragment_tab_title_article), data.title)) detailsTitle.text = data.title detailsNick.text = data.author detailsDate.text = data.date detailsCount.text = data.commentsCount.toString() data.imgUrl?.also { showArticleImage(it) } val pagerAdapter = FragmentPagerAdapter(childFragmentManager) fragmentsPager.adapter = pagerAdapter if (data.commentId > 0) { appBarLayout.setExpanded(false, true) fragmentsPager.setCurrentItem(1, true) } } override fun showCreateNote(title: String, url: String) { NotesAddPopup.showAddNoteDialog(context, title, url) } override fun showArticleImage(imageUrl: String) { ImageLoader.getInstance().displayImage(imageUrl, detailsImage, object : SimpleImageLoadingListener() { override fun onLoadingStarted(imageUri: String?, view: View?) { imageProgressBar.visibility = View.VISIBLE } override fun onLoadingComplete(imageUri: String?, view: View?, loadedImage: Bitmap?) { imageProgressBar.visibility = View.GONE } }) } private inner class FragmentPagerAdapter( fm: androidx.fragment.app.FragmentManager ) : androidx.fragment.app.FragmentPagerAdapter(fm) { private val fragments = ArrayList<androidx.fragment.app.Fragment>() private val titles = ArrayList<String>() init { fragments.add(ArticleContentFragment()) titles.add(App.get().getString(R.string.news_page_content)) fragments.add(ArticleCommentsFragment()) titles.add(App.get().getString(R.string.news_page_comments)) } override fun getItem(position: Int): androidx.fragment.app.Fragment { return fragments[position] } override fun getCount(): Int { return fragments.size } override fun getPageTitle(position: Int): CharSequence? { return titles[position] } } companion object { const val ARG_NEWS_URL = "ARG_NEWS_URL" const val ARG_NEWS_ID = "ARG_NEWS_ID" const val ARG_NEWS_COMMENT_ID = "ARG_NEWS_COMMENT_ID" const val ARG_NEWS_TITLE = "ARG_NEWS_TITLE" const val ARG_NEWS_AUTHOR_NICK = "ARG_NEWS_AUTHOR_NICK" //const val ARG_NEWS_AUTHOR_ID = "ARG_NEWS_AUTHOR_ID" const val ARG_NEWS_COMMENTS_COUNT = "ARG_NEWS_COMMENTS_COUNT" const val ARG_NEWS_DATE = "ARG_NEWS_DATE" const val ARG_NEWS_IMAGE = "ARG_NEWS_IMAGE" } }
gpl-3.0
cda097971b114d92025d1173ec03cbb6
35.042484
132
0.661619
4.780668
false
false
false
false
fengzhizi715/SAF-Kotlin-Utils
saf-kotlin-ext/src/main/java/com/safframework/ext/Context+Extension.kt
1
4449
package com.safframework.ext import android.annotation.SuppressLint import android.content.Context import android.content.pm.PackageInfo import android.content.pm.PackageManager import android.graphics.drawable.Drawable import android.net.ConnectivityManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.ColorRes import androidx.annotation.DimenRes import androidx.annotation.LayoutRes import androidx.annotation.StringRes import java.io.File /** * Created by Tony Shen on 2017/6/30. */ /** * screen width in pixels */ inline val Context.screenWidth get() = resources.displayMetrics.widthPixels /** * screen height in pixels */ inline val Context.screenHeight get() = resources.displayMetrics.heightPixels inline val Context.isNetworkAvailable: Boolean @SuppressLint("MissingPermission") get() { val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetworkInfo = connectivityManager.activeNetworkInfo return activeNetworkInfo?.isConnectedOrConnecting ?: false } /** * returns dip(dp) dimension value in pixels * @param value dp */ fun Context.dp2px(value: Int): Int = (value * resources.displayMetrics.density).toInt() fun Context.dp2px(value: Float): Int = (value * resources.displayMetrics.density).toInt() /** * return sp dimension value in pixels * @param value sp */ fun Context.sp2px(value: Int): Int = (value * resources.displayMetrics.scaledDensity).toInt() fun Context.sp2px(value: Float): Int = (value * resources.displayMetrics.scaledDensity).toInt() /** * converts [px] value into dip or sp * @param px */ fun Context.px2dp(px: Int): Float = px.toFloat() / resources.displayMetrics.density fun Context.px2sp(px: Int): Float = px.toFloat() / resources.displayMetrics.scaledDensity /** * return dimen resource value in pixels * @param resource dimen resource */ fun Context.dimen2px(@DimenRes resource: Int): Int = resources.getDimensionPixelSize(resource) fun Context.string(@StringRes id: Int): String = getString(id) fun Context.color(@ColorRes id: Int): Int = resources.getColor(id) fun Context.inflateLayout(@LayoutRes layoutId: Int, parent: ViewGroup? = null, attachToRoot: Boolean = false): View = LayoutInflater.from(this).inflate(layoutId, parent, attachToRoot) /** * 获取当前app的版本号 */ fun Context.getAppVersion(): String { val appContext = applicationContext val manager = appContext.getPackageManager() try { val info = manager.getPackageInfo(appContext.getPackageName(), 0) if (info != null) return info.versionName } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() } return "" } fun Context.getAppVersionCode(): Int { val appContext = applicationContext val manager = appContext.getPackageManager() try { val info = manager.getPackageInfo(appContext.getPackageName(), 0) if (info != null) return info.versionCode } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() } return 0 } /** * 获取应用的包名 * * @param context context * @return package name */ fun Context.getPackageName(): String = packageName data class AppInfo( val apkPath: String, val packageName: String, val versionName: String, val versionCode: Long, val appName: String, val icon: Drawable ) fun Context.getAppInfo(apkPath: String): AppInfo { val packageInfo = packageManager.getPackageArchiveInfo(apkPath, PackageManager.GET_META_DATA) as PackageInfo packageInfo.applicationInfo.sourceDir = apkPath packageInfo.applicationInfo.publicSourceDir = apkPath val packageName = packageInfo.packageName val appName = packageManager.getApplicationLabel(packageInfo.applicationInfo).toString() val versionName = packageInfo.versionName val versionCode = packageInfo.versionCode val icon = packageManager.getApplicationIcon(packageInfo.applicationInfo) return AppInfo(apkPath, packageName, versionName, versionCode.toLong(), appName, icon) } fun Context.getAppInfos(apkFolderPath: String): List<AppInfo> { val appInfoList = ArrayList<AppInfo>() for (file in File(apkFolderPath).listFiles()) appInfoList.add(getAppInfo(file.path)) return appInfoList }
apache-2.0
edfac4e4f4b68457dfbd61d37470fb40
28.078947
115
0.734555
4.477204
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignature.kt
1
13025
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.changeSignature import com.intellij.lang.java.JavaLanguage import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.NlsContexts import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementFactory import com.intellij.psi.PsiMethod import com.intellij.psi.PsiType import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.changeSignature.* import com.intellij.refactoring.ui.RefactoringDialog import com.intellij.refactoring.util.CanonicalTypes import com.intellij.util.VisibilityUtil import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.asJava.getRepresentativeLightMethod import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.refactoring.CallableRefactoring import org.jetbrains.kotlin.idea.refactoring.broadcastRefactoringExit import org.jetbrains.kotlin.idea.refactoring.changeSignature.ui.KotlinChangePropertySignatureDialog import org.jetbrains.kotlin.idea.refactoring.changeSignature.ui.KotlinChangeSignatureDialog import org.jetbrains.kotlin.idea.refactoring.createJavaMethod import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.application.withPsiAttachment import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments interface KotlinChangeSignatureConfiguration { fun configure(originalDescriptor: KotlinMethodDescriptor): KotlinMethodDescriptor = originalDescriptor fun performSilently(affectedFunctions: Collection<PsiElement>): Boolean = false fun forcePerformForSelectedFunctionOnly(): Boolean = false object Empty : KotlinChangeSignatureConfiguration } fun KotlinMethodDescriptor.modify(action: (KotlinMutableMethodDescriptor) -> Unit): KotlinMethodDescriptor { val newDescriptor = KotlinMutableMethodDescriptor(this) action(newDescriptor) return newDescriptor } fun runChangeSignature( project: Project, editor: Editor?, callableDescriptor: CallableDescriptor, configuration: KotlinChangeSignatureConfiguration, defaultValueContext: PsiElement, @NlsContexts.Command commandName: String? = null ): Boolean { val result = KotlinChangeSignature(project, editor, callableDescriptor, configuration, defaultValueContext, commandName).run() if (!result) { broadcastRefactoringExit(project, "refactoring.changeSignature") } return result } class KotlinChangeSignature( project: Project, editor: Editor?, callableDescriptor: CallableDescriptor, val configuration: KotlinChangeSignatureConfiguration, val defaultValueContext: PsiElement, @NlsContexts.Command commandName: String? ) : CallableRefactoring<CallableDescriptor>( project, editor, callableDescriptor, commandName ?: RefactoringBundle.message("changeSignature.refactoring.name") ) { override fun forcePerformForSelectedFunctionOnly() = configuration.forcePerformForSelectedFunctionOnly() /** * @param propertyProcessor: * - top level * - member level * - primary constructor * * @param functionProcessor: * - top level * - member level * - local level * - constructors * * @param javaProcessor: * - member level */ private fun <T> selectRefactoringProcessor( descriptor: KotlinMethodDescriptor, propertyProcessor: (KotlinMethodDescriptor) -> T?, functionProcessor: (KotlinMethodDescriptor) -> T?, javaProcessor: (KotlinMethodDescriptor, PsiMethod) -> T?, ): T? { return when (val baseDeclaration = descriptor.baseDeclaration) { is KtProperty, is KtParameter -> propertyProcessor(descriptor) /** * functions: * - top level * - member level * - constructors * * class: * - primary constructor */ is KtFunction, is KtClass -> functionProcessor(descriptor) is PsiMethod -> { if (baseDeclaration.language != JavaLanguage.INSTANCE) { Messages.showErrorDialog( KotlinBundle.message("error.text.can.t.change.signature.of.method", baseDeclaration.language.displayName), commandName ) return null } javaProcessor(descriptor, baseDeclaration) } else -> throw KotlinExceptionWithAttachments("Unexpected declaration: ${baseDeclaration::class}") .withPsiAttachment("element.kt", baseDeclaration) .withPsiAttachment("file.kt", baseDeclaration.containingFile) } } @TestOnly fun createSilentRefactoringProcessor(methodDescriptor: KotlinMethodDescriptor): BaseRefactoringProcessor? = selectRefactoringProcessor( methodDescriptor, propertyProcessor = { KotlinChangePropertySignatureDialog.createProcessorForSilentRefactoring(project, commandName, it) }, functionProcessor = { KotlinChangeSignatureDialog.createRefactoringProcessorForSilentChangeSignature( project, commandName, it, defaultValueContext ) }, javaProcessor = { descriptor, _ -> ChangeSignatureProcessor(project, getPreviewInfoForJavaMethod(descriptor).second) } ) private fun runSilentRefactoring(methodDescriptor: KotlinMethodDescriptor) { createSilentRefactoringProcessor(methodDescriptor)?.run() } private fun runInteractiveRefactoring(methodDescriptor: KotlinMethodDescriptor) { val dialog = selectRefactoringProcessor( methodDescriptor, propertyProcessor = { KotlinChangePropertySignatureDialog(project, it, commandName) }, functionProcessor = { KotlinChangeSignatureDialog(project, editor, it, defaultValueContext, commandName) }, javaProcessor = fun(descriptor: KotlinMethodDescriptor, method: PsiMethod): RefactoringDialog? { if (descriptor is KotlinChangeSignatureData) { ChangeSignatureUtil.invokeChangeSignatureOn(method, project) return null } val (preview, javaChangeInfo) = getPreviewInfoForJavaMethod(descriptor) val javaDescriptor = object : JavaMethodDescriptor(preview) { @Suppress("UNCHECKED_CAST") override fun getParameters() = javaChangeInfo.newParameters.toMutableList() as MutableList<ParameterInfoImpl> } return object : JavaChangeSignatureDialog(project, javaDescriptor, false, null) { override fun createRefactoringProcessor(): BaseRefactoringProcessor { val parameters = parameters LOG.assertTrue(myMethod.method.isValid) val newJavaChangeInfo = JavaChangeInfoImpl( visibility ?: VisibilityUtil.getVisibilityModifier(myMethod.method.modifierList), javaChangeInfo.method, methodName, returnType ?: CanonicalTypes.createTypeWrapper(PsiType.VOID), parameters.toTypedArray(), exceptions, isGenerateDelegate, myMethodsToPropagateParameters ?: HashSet(), myMethodsToPropagateExceptions ?: HashSet() ).also { it.setCheckUnusedParameter() } return ChangeSignatureProcessor(myProject, newJavaChangeInfo) } } }, ) ?: return if (isUnitTestMode()) { try { dialog.performOKAction() } finally { dialog.close(DialogWrapper.OK_EXIT_CODE) } } else { dialog.show() } } private fun getPreviewInfoForJavaMethod(descriptor: KotlinMethodDescriptor): Pair<PsiMethod, JavaChangeInfo> { val originalMethod = descriptor.baseDeclaration as PsiMethod val contextFile = defaultValueContext.containingFile as KtFile // Generate new Java method signature from the Kotlin point of view val ktChangeInfo = KotlinChangeInfo(methodDescriptor = descriptor, context = defaultValueContext) val ktSignature = ktChangeInfo.getNewSignature(descriptor.originalPrimaryCallable) val previewClassName = if (originalMethod.isConstructor) originalMethod.name else "Dummy" val dummyFileText = with(StringBuilder()) { contextFile.packageDirective?.let { append(it.text).append("\n") } append("class $previewClassName {\n").append(ktSignature).append("{}\n}") toString() } val dummyFile = KtPsiFactory(project).createFileWithLightClassSupport("dummy.kt", dummyFileText, originalMethod) val dummyDeclaration = (dummyFile.declarations.first() as KtClass).body!!.declarations.first() // Convert to PsiMethod which can be used in Change Signature dialog val containingClass = PsiElementFactory.getInstance(project).createClass(previewClassName) val preview = createJavaMethod(dummyDeclaration.getRepresentativeLightMethod()!!, containingClass) // Create JavaChangeInfo based on new signature // TODO: Support visibility change val visibility = VisibilityUtil.getVisibilityModifier(originalMethod.modifierList) val returnType = CanonicalTypes.createTypeWrapper(preview.returnType ?: PsiType.VOID) val params = (preview.parameterList.parameters.zip(ktChangeInfo.newParameters)).map { val (param, paramInfo) = it // Keep original default value for proper update of Kotlin usages KotlinAwareJavaParameterInfoImpl(paramInfo.oldIndex, param.name, param.type, paramInfo.defaultValueForCall) }.toTypedArray() return preview to JavaChangeInfoImpl( visibility, originalMethod, preview.name, returnType, params, arrayOf<ThrownExceptionInfo>(), false, emptySet<PsiMethod>(), emptySet<PsiMethod>() ) } override fun performRefactoring(descriptorsForChange: Collection<CallableDescriptor>) { val adjustedDescriptor = adjustDescriptor(descriptorsForChange) ?: return val affectedFunctions = adjustedDescriptor.affectedCallables.mapNotNull { it.element } if (affectedFunctions.any { !checkModifiable(it) }) return if (configuration.performSilently(affectedFunctions)) { runSilentRefactoring(adjustedDescriptor) } else { runInteractiveRefactoring(adjustedDescriptor) } } fun adjustDescriptor(descriptorsForSignatureChange: Collection<CallableDescriptor>): KotlinMethodDescriptor? { val baseDescriptor = preferContainedInClass(descriptorsForSignatureChange) val functionDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, baseDescriptor) if (functionDeclaration == null) { LOG.error("Could not find declaration for $baseDescriptor") return null } if (!checkModifiable(functionDeclaration)) { return null } val originalDescriptor = KotlinChangeSignatureData(baseDescriptor, functionDeclaration, descriptorsForSignatureChange) return configuration.configure(originalDescriptor) } private fun preferContainedInClass(descriptorsForSignatureChange: Collection<CallableDescriptor>): CallableDescriptor { for (descriptor in descriptorsForSignatureChange) { val containingDeclaration = descriptor.containingDeclaration if (containingDeclaration is ClassDescriptor && containingDeclaration.kind != ClassKind.INTERFACE) { return descriptor } } //choose at random return descriptorsForSignatureChange.first() } companion object { private val LOG = logger<KotlinChangeSignature>() } }
apache-2.0
b50f9d383283de0598ee6542f09cb062
43.606164
158
0.687985
6.280135
false
false
false
false
sat2707/aicups
clients/kotlin_client/client/src/main/kotlin/core/API/Elevator.kt
1
1208
package core.API import org.json.simple.JSONArray import org.json.simple.JSONObject class Elevator(elevator: JSONObject) : MessagesInterface { val id: Int = elevator["id"]?.toString()?.toInt() ?: 0 val y: Double = elevator["y"]?.toString()?.toDouble() ?: 0.0 val passengers = ArrayList<Passenger>() val state: Int = elevator["state"]?.toString()?.toInt() ?: 0 val speed: Double = elevator["speed"]?.toString()?.toDouble() ?: 0.0 val timeOnFloor: Int = elevator["time_on_floor"]?.toString()?.toInt() ?: 0 val floor: Int = elevator["floor"]?.toString()?.toInt() ?: 0 val type: String = elevator["type"]?.toString() ?: "" var nextFloor: Int = elevator["next_floor"]?.toString()?.toInt() ?: 0 private set val messages = ArrayList<JSONObject>() init { (elevator["passengers"] as JSONArray).mapTo(passengers) { Passenger(it as JSONObject) } } override fun getMessages(): List<JSONObject> = messages fun goToFloor(floor: Int?) { this.nextFloor = floor ?: 0 val jo = JSONObject() jo.put("command", "go_to_floor") val args = JSONObject() args.put("elevator_id", this.id) args.put("floor", floor) jo.put("args", args) this.messages.add(jo) } }
apache-2.0
f7deccc519e17b8c917839d67bdc6a2c
33.542857
91
0.650662
3.739938
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/settings/view/DaysPickerDialogController.kt
1
3019
package io.ipoli.android.settings.view import android.content.DialogInterface import android.os.Bundle import android.support.v7.app.AlertDialog import android.view.LayoutInflater import android.view.View import io.ipoli.android.R import io.ipoli.android.common.view.ReduxDialogController import io.ipoli.android.pet.AndroidPetAvatar import io.ipoli.android.pet.LoadPetDialogAction import io.ipoli.android.pet.PetDialogReducer import io.ipoli.android.pet.PetDialogViewState import kotlinx.android.synthetic.main.view_dialog_header.view.* import org.threeten.bp.DayOfWeek import org.threeten.bp.format.TextStyle import java.util.* /** * Created by Polina Zhelyazkova <[email protected]> * on 5/16/18. */ class DaysPickerDialogController(args: Bundle? = null) : ReduxDialogController<LoadPetDialogAction, PetDialogViewState, PetDialogReducer>(args) { override val reducer = PetDialogReducer private val days: List<DayOfWeek> = DayOfWeek.values().toList() private var listener: (Set<DayOfWeek>) -> Unit = {} private lateinit var selectedDays: MutableSet<DayOfWeek> constructor( selectedDays: Set<DayOfWeek>, listener: (Set<DayOfWeek>) -> Unit ) : this() { this.listener = listener this.selectedDays = selectedDays.toMutableSet() } override fun onCreateContentView(inflater: LayoutInflater, savedViewState: Bundle?): View = inflater.inflate(R.layout.dialog_days_picker, null) override fun onHeaderViewCreated(headerView: View) { headerView.dialogHeaderTitle.setText(R.string.choose_days_of_week) } override fun onCreateDialog( dialogBuilder: AlertDialog.Builder, contentView: View, savedViewState: Bundle? ): AlertDialog { val daysOfWeekNames = days.map { it.getDisplayName(TextStyle.FULL, Locale.getDefault()) } val checked = days.map { selectedDays.contains(it) } return dialogBuilder .setMultiChoiceItems( daysOfWeekNames.toTypedArray(), checked.toBooleanArray() ) { _, which, isChecked -> if (isChecked) { selectedDays.add(days[which]) } else { selectedDays.remove(days[which]) } } .setPositiveButton(R.string.dialog_ok, null) .setNegativeButton(R.string.cancel, null) .create() } override fun onDialogCreated(dialog: AlertDialog, contentView: View) { dialog.setOnShowListener { dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener { listener(selectedDays) dismiss() } } } override fun onCreateLoadAction() = LoadPetDialogAction override fun render(state: PetDialogViewState, view: View) { if (state.type == PetDialogViewState.Type.PET_LOADED) { changeIcon(AndroidPetAvatar.valueOf(state.petAvatar!!.name).headImage) } } }
gpl-3.0
6214f1df773e718d536d9fb282081b7f
32.932584
97
0.675058
4.717188
false
false
false
false
GunoH/intellij-community
plugins/kotlin/gradle/gradle-tooling/impl/src/org/jetbrains/kotlin/idea/gradleTooling/getAdditionalVisibleSourceSets.kt
2
1158
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.gradleTooling import org.gradle.api.Named import org.gradle.api.NamedDomainObjectCollection import org.gradle.api.Project import org.jetbrains.kotlin.idea.gradleTooling.reflect.KotlinSourceSetReflection internal fun getAdditionalVisibleSourceSets(project: Project, sourceSetName: String): Set<String> { val kotlinExtension = project.extensions.findByName("kotlin") ?: return emptySet() val kotlinExtensionClass = kotlinExtension.javaClass val getSourceSets = kotlinExtensionClass.getMethodOrNull("getSourceSets") ?: return emptySet() val sourceSets = getSourceSets.invoke(kotlinExtension) as NamedDomainObjectCollection<*> val sourceSet = sourceSets.findByName(sourceSetName) as? Named ?: return emptySet() return getAdditionalVisibleSourceSets(sourceSet) } internal fun getAdditionalVisibleSourceSets(sourceSet: Named): Set<String> { return KotlinSourceSetReflection(sourceSet).additionalVisibleSourceSets.map { it.name }.toSet() }
apache-2.0
1eed53210aeb0ac9470333f586254ede
54.142857
158
0.80829
5.012987
false
false
false
false
onnerby/musikcube
src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/tracks/activity/TrackListActivity.kt
2
1876
package io.casey.musikcube.remote.ui.tracks.activity import android.content.Context import android.content.Intent import android.view.Menu import android.view.MenuItem import io.casey.musikcube.remote.R import io.casey.musikcube.remote.service.playback.impl.remote.Metadata import io.casey.musikcube.remote.ui.shared.activity.FragmentActivityWithTransport import io.casey.musikcube.remote.ui.shared.fragment.BaseFragment import io.casey.musikcube.remote.ui.tracks.constant.Track import io.casey.musikcube.remote.ui.tracks.fragment.TrackListFragment class TrackListActivity: FragmentActivityWithTransport() { private val tracks get() = content as TrackListFragment override fun onCreateOptionsMenu(menu: Menu): Boolean = tracks.createOptionsMenu(menu) override fun onOptionsItemSelected(item: MenuItem): Boolean = when (tracks.optionsItemSelected(item)) { true -> true false -> super.onOptionsItemSelected(item) } override fun createContentFragment(): BaseFragment = TrackListFragment.create(intent) override val contentFragmentTag: String = TrackListFragment.TAG companion object { fun getOfflineStartIntent(context: Context): Intent = getStartIntent(context, Metadata.Category.OFFLINE, 0).apply { putExtra(Track.Extra.TITLE_ID, R.string.offline_tracks_title) } fun getStartIntent(context: Context, categoryType: String = "", categoryId: Long = 0, categoryValue: String = ""): Intent = Intent(context, TrackListActivity::class.java).apply { putExtra( Track.Extra.FRAGMENT_ARGUMENTS, TrackListFragment.arguments(context, categoryType, categoryId, categoryValue)) } } }
bsd-3-clause
94bcae51f440eadda816cb89db65f9ca
39.782609
98
0.688166
4.962963
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryCompactGridHolder.kt
1
2751
package eu.kanade.tachiyomi.ui.library import androidx.core.view.isVisible import coil.clear import eu.davidea.flexibleadapter.FlexibleAdapter import eu.kanade.tachiyomi.databinding.SourceCompactGridItemBinding import eu.kanade.tachiyomi.util.view.loadAnyAutoPause /** * Class used to hold the displayed data of a manga in the library, like the cover or the title. * All the elements from the layout file "source_compact_grid_item" are available in this class. * * @param binding the inflated view for this holder. * @param adapter the adapter handling this holder. * @param coverOnly true if title should be hidden a.k.a cover only mode. * @constructor creates a new library holder. */ class LibraryCompactGridHolder( override val binding: SourceCompactGridItemBinding, adapter: FlexibleAdapter<*>, private val coverOnly: Boolean ) : LibraryHolder<SourceCompactGridItemBinding>(binding.root, adapter) { /** * Method called from [LibraryCategoryAdapter.onBindViewHolder]. It updates the data for this * holder with the given manga. * * @param item the manga item to bind. */ override fun onSetValues(item: LibraryItem) { // Update the title of the manga. binding.title.text = item.manga.title // For rounded corners binding.badges.leftBadges.clipToOutline = true binding.badges.rightBadges.clipToOutline = true // Update the unread count and its visibility. with(binding.badges.unreadText) { isVisible = item.unreadCount > 0 text = item.unreadCount.toString() } // Update the download count and its visibility. with(binding.badges.downloadText) { isVisible = item.downloadCount > 0 text = item.downloadCount.toString() } // Update the source language and its visibility with(binding.badges.languageText) { isVisible = item.sourceLanguage.isNotEmpty() text = item.sourceLanguage } // set local visibility if its local manga binding.badges.localText.isVisible = item.isLocal // Update the cover. binding.thumbnail.clear() if (coverOnly) { // Cover only mode: Hides title text unless thumbnail is unavailable if (!item.manga.thumbnail_url.isNullOrEmpty()) { binding.thumbnail.loadAnyAutoPause(item.manga) binding.title.isVisible = false } else { binding.title.text = item.manga.title binding.title.isVisible = true } binding.thumbnail.foreground = null } else { binding.thumbnail.loadAnyAutoPause(item.manga) } } }
apache-2.0
de4eb6595739a81e2cda276550c5a5cd
37.208333
97
0.664122
4.718696
false
false
false
false
armcha/Ribble
app/src/main/kotlin/io/armcha/ribble/presentation/adapter/ShotPagerAdapter.kt
1
998
package io.armcha.ribble.presentation.adapter import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentPagerAdapter import io.armcha.ribble.di.scope.PerActivity import io.armcha.ribble.presentation.screen.shot.ShotFragment import io.armcha.ribble.presentation.screen.shot.TYPE_POPULAR import io.armcha.ribble.presentation.screen.shot.TYPE_RECENT import javax.inject.Inject /** * Created by Chatikyan on 06.08.2017. */ @PerActivity class ShotPagerAdapter @Inject constructor(fragmentManager: FragmentManager) : FragmentPagerAdapter(fragmentManager) { private val titles = listOf("Popular", "Recent") override fun getItem(position: Int): Fragment { return if (position == 0) ShotFragment.newInstance(TYPE_POPULAR) else ShotFragment.newInstance(TYPE_RECENT) } override fun getCount(): Int = titles.count() override fun getPageTitle(position: Int) = titles[position] }
apache-2.0
74d5600f7b1b06d0b007417537d54743
32.3
118
0.762525
4.21097
false
false
false
false
MichaelRocks/grip
library/src/main/java/io/michaelrocks/grip/mirrors/signature/ClassSignatureMirror.kt
1
3480
/* * Copyright 2021 Michael Rozumyanskiy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.michaelrocks.grip.mirrors.signature import io.michaelrocks.grip.commons.LazyList import io.michaelrocks.grip.mirrors.GenericTypeListWrapper import io.michaelrocks.grip.mirrors.Type import org.objectweb.asm.signature.SignatureReader import java.util.Collections interface ClassSignatureMirror { val typeVariables: List<GenericType.TypeVariable> val superType: GenericType val interfaces: List<GenericType> fun toJvmSignature(): String class Builder { private val typeVariables = LazyList<GenericType.TypeVariable>() private var superType: GenericType = OBJECT_RAW_TYPE private val interfaces = LazyList<GenericType>() fun addTypeVariable(builder: GenericType.TypeVariable) = apply { typeVariables += builder } fun superType(superType: GenericType) = apply { this.superType = superType } fun addInterface(interfaceType: GenericType) = apply { interfaces += interfaceType } fun build(): ClassSignatureMirror = ClassSignatureMirrorImpl(this) private class ClassSignatureMirrorImpl(builder: Builder) : ClassSignatureMirror { override val typeVariables: List<GenericType.TypeVariable> = builder.typeVariables.detachImmutableCopy() override val superType: GenericType = builder.superType override val interfaces: List<GenericType> = builder.interfaces.detachImmutableCopy() override fun toJvmSignature() = throw UnsupportedOperationException() } } } internal class LazyClassSignatureMirror( asmApi: Int, enclosingGenericDeclaration: GenericDeclaration, private val signature: String, ) : ClassSignatureMirror { private val delegate by lazy(LazyThreadSafetyMode.PUBLICATION) { ClassSignatureReader(asmApi, enclosingGenericDeclaration).run { SignatureReader(signature).accept(this) toClassSignature() } } override val typeVariables: List<GenericType.TypeVariable> get() = delegate.typeVariables override val superType: GenericType get() = delegate.superType override val interfaces: List<GenericType> get() = delegate.interfaces override fun toJvmSignature() = signature } internal class EmptyClassSignatureMirror(superType: Type?, interfaces: List<Type>) : ClassSignatureMirror { override val typeVariables: List<GenericType.TypeVariable> get() = Collections.emptyList() override val superType = superType?.let { GenericType.Raw(it) } ?: OBJECT_RAW_TYPE override val interfaces: List<GenericType> = if (interfaces.isEmpty()) emptyList() else GenericTypeListWrapper(interfaces) override fun toJvmSignature() = "" } internal fun ClassSignatureMirror.asGenericDeclaration(): GenericDeclaration { return GenericDeclaration(typeVariables) } internal fun ClassSignatureMirror.asLazyGenericDeclaration(): GenericDeclaration { return LazyGenericDeclaration { asGenericDeclaration() } }
apache-2.0
0329998a7f13c2f78f9cff4a4d1d6584
33.455446
110
0.76523
4.978541
false
false
false
false
jguerinet/MyMartlet-Android
app/src/main/java/ui/ScheduleActivity.kt
1
24341
/* * Copyright 2014-2019 Julien Guerinet * * 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.guerinet.mymartlet.ui import android.content.res.Configuration import android.os.Bundle import android.view.Gravity import android.view.LayoutInflater import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.ScrollView import android.widget.TextView import androidx.annotation.StringRes import androidx.appcompat.app.AlertDialog import androidx.core.view.isVisible import com.guerinet.morf.Morf import com.guerinet.morf.morf import com.guerinet.mymartlet.R import com.guerinet.mymartlet.model.Course import com.guerinet.mymartlet.model.Term import com.guerinet.mymartlet.model.place.Place import com.guerinet.mymartlet.ui.dialog.list.TermDialogHelper import com.guerinet.mymartlet.ui.walkthrough.WalkthroughActivity import com.guerinet.mymartlet.util.Constants import com.guerinet.mymartlet.util.DayUtils import com.guerinet.mymartlet.util.Prefs import com.guerinet.mymartlet.util.manager.HomepageManager import com.guerinet.mymartlet.util.prefs.DefaultTermPref import com.guerinet.mymartlet.util.retrofit.TranscriptConverter.TranscriptResponse import com.guerinet.mymartlet.util.room.daos.CourseDao import com.guerinet.mymartlet.util.room.daos.TranscriptDao import com.guerinet.suitcase.coroutines.bgDispatcher import com.guerinet.suitcase.coroutines.uiDispatcher import com.guerinet.suitcase.date.extensions.getLongDateString import com.guerinet.suitcase.prefs.BooleanPref import com.guerinet.suitcase.util.extensions.getColorCompat import com.guerinet.suitcase.util.extensions.openUrl import kotlinx.android.synthetic.main.activity_schedule.* import kotlinx.android.synthetic.main.fragment_day.view.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.jetbrains.anko.intentFor import org.jetbrains.anko.startActivity import org.jetbrains.anko.toast import org.koin.android.ext.android.inject import org.threeten.bp.LocalDate import org.threeten.bp.LocalTime import org.threeten.bp.format.DateTimeFormatter import org.threeten.bp.temporal.ChronoUnit import retrofit2.Call import retrofit2.Callback import retrofit2.Response import timber.log.Timber import java.util.Stack /** * Displays the user's schedule * @author Julien Guerinet * @since 1.0.0 */ class ScheduleActivity : DrawerActivity() { private val firstOpenPref by inject<BooleanPref>(Prefs.IS_FIRST_OPEN) private val twentyFourHourPref by inject<BooleanPref>(Prefs.SCHEDULE_24HR) private val defaultTermPref by inject<DefaultTermPref>() private val courseDao by inject<CourseDao>() private val transcriptDao by inject<TranscriptDao>() private var term: Term = defaultTermPref.term private val courses: MutableList<Course> = mutableListOf() // We need this to know which week to show in the landscape orientation private var date: LocalDate = LocalDate.now() override val currentPage = HomepageManager.HomePage.SCHEDULE override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_schedule) val savedTerm = savedInstanceState?.get(Constants.TERM) as? Term if (savedTerm != null) { term = savedTerm } // Update the list of courses for this currentTerm and the starting date updateCoursesAndDate() // // Render the right view based on the orientation // if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) { // renderLandscapeView() // } else { // renderPortraitView() // } // Check if this is the first time the user is using the app if (firstOpenPref.value) { // Show them the walkthrough if it is startActivity<WalkthroughActivity>(Prefs.IS_FIRST_OPEN to true) // Save the fact that the walkthrough has been seen at least once firstOpenPref.value = false } } // Only show the menu in portrait mode override fun onPrepareOptionsMenu(menu: Menu): Boolean = resources.configuration.orientation != Configuration.ORIENTATION_LANDSCAPE override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.refresh, menu) menuInflater.inflate(R.menu.change_semester, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_change_semester -> { TermDialogHelper(this, this, term) { // If it's the same currentTerm as now, do nothing if (it == term) { return@TermDialogHelper } // Set the instance currentTerm term = it // Set the default currentTerm defaultTermPref.term = term // Update the courses updateCoursesAndDate() // Refresh the content refreshCourses() } return true } R.id.action_refresh -> { refreshCourses() return true } else -> return super.onOptionsItemSelected(item) } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) // Save the currentTerm outState.putSerializable(Constants.TERM, term) } private suspend fun updateCourses() { withContext(bgDispatcher) { // Clear the current courses courses.clear() // Get the new courses for the current currentTerm val localCourses = courseDao.getTermCourses(term) courses.addAll(localCourses) } } /** * Gets the courses for the given [Term] */ private fun updateCoursesAndDate() { launch(Dispatchers.Default) { updateCourses() // Date is by default set to today date = LocalDate.now() // Check if we are in the current semester if (term != Term.currentTerm()) { // If not, find the starting date of this semester instead of using today for (course in courses) { if (course.startDate.isBefore(date)) { date = course.startDate } } } withContext(uiDispatcher) { // Title title = term.getString(this@ScheduleActivity) // TODO This only renders the portrait view renderPortraitView() } } } /** * Refreshes the list of courses for the given currentTerm and the user's transcript * (only available in portrait mode) */ private fun refreshCourses() { if (!canRefresh()) { return } // Download the courses for this currentTerm mcGillService.schedule(term).enqueue(object : Callback<List<Course>> { override fun onResponse(call: Call<List<Course>>, response: Response<List<Course>>) { launch(Dispatchers.IO) { courseDao.update(response.body() ?: listOf(), term) withContext(uiDispatcher) { // Update the view toolbarProgress.isVisible = false updateCourses() @Suppress("PLUGIN_WARNING") viewPager.adapter?.notifyDataSetChanged() } } // Download the transcript (if ever the user has new semesters on their transcript) mcGillService.oldTranscript().enqueue(object : Callback<TranscriptResponse> { override fun onResponse( call: Call<TranscriptResponse>, response: Response<TranscriptResponse> ) { launch(Dispatchers.IO) { transcriptDao.update(response.body()?.transcript!!) } } override fun onFailure(call: Call<TranscriptResponse>, t: Throwable) { handleError("refreshing the transcript", t) } }) } override fun onFailure(call: Call<List<Course>>, t: Throwable) { handleError("refreshing the courses", t) } }) } /* TODO Bring landscape view back /** * Renders the landscape view */ @Suppress("PLUGIN_WARNING") private fun renderLandscapeView() { // Leave space at the top for the day names var dayView = View.inflate(this, R.layout.fragment_day_name, null) // Black line to separate the timetable from the schedule val dayViewLine = dayView.findViewById<View>(R.id.day_line) dayViewLine.visibility = View.VISIBLE // Add the day view to the top of the timetable timetableContainer.addView(dayView) // Find the index of the given date val currentDayIndex = date.dayOfWeek.value // Go through the 7 days of the week for (i in 1..7) { val day = DayOfWeek.of(i) // Set up the day name dayView = View.inflate(this, R.layout.fragment_day_name, null) val dayViewTitle = dayView.findViewById<TextView>(R.id.day_name) dayViewTitle.setText(DayUtils.getStringId(day)) scheduleContainer!!.addView(dayView) // Set up the schedule container for that one day val scheduleContainer = LinearLayout(this) scheduleContainer.orientation = LinearLayout.VERTICAL scheduleContainer.layoutParams = LinearLayout.LayoutParams( resources.getDimensionPixelSize(R.dimen.cell_landscape_width), ViewGroup.LayoutParams.WRAP_CONTENT) // Fill the schedule for the current day fillSchedule(this.timetableContainer, scheduleContainer, date.plusDays((i - currentDayIndex).toLong()), false) // Add the current day to the schedule container this.scheduleContainer!!.addView(scheduleContainer) // Line val line = View(this) line.setBackgroundColor(Color.BLACK) line.layoutParams = ViewGroup.LayoutParams( resources.getDimensionPixelSize(R.dimen.schedule_line), ViewGroup.LayoutParams.MATCH_PARENT) this.scheduleContainer!!.addView(line) } } */ /** * Renders the portrait view */ private fun renderPortraitView() { val viewPager = this.viewPager ?: throw IllegalStateException("No ViewPager found") val adapter = ScheduleAdapter() // Set up the ViewPager viewPager.apply { this.adapter = adapter currentItem = adapter.startingDateIndex addOnPageChangeListener(object : androidx.viewpager.widget.ViewPager.OnPageChangeListener { override fun onPageScrolled(i: Int, v: Float, i2: Int) {} override fun onPageSelected(i: Int) { //Update the date every time the page is turned to have the right // week if ever the user rotates his device date = adapter.getDate(i) } override fun onPageScrollStateChanged(i: Int) {} }) } } /** * Fills the schedule based on given data * * @param timetableContainer Container for the timetable * @param scheduleContainer Container for the schedule * @param date Date to fill the schedule for * @param clickable True if the user can click on the courses (portrait), * false otherwise (landscape) */ private fun fillSchedule( timetableContainer: LinearLayout?, scheduleContainer: LinearLayout?, date: LocalDate, clickable: Boolean ) { if (timetableContainer == null || scheduleContainer == null) { return } // Clear everything out timetableContainer.removeAllViews() scheduleContainer.removeAllViews() // Go through the list of courses, find which ones are for the given date val courses = this.courses.filter { it.isForDate(date) } // Set up the DateTimeFormatter we're going to use for the hours val pattern = if (twentyFourHourPref.value) "HH:mm" else "hh a" val formatter = DateTimeFormatter.ofPattern(pattern) // This will be used of an end time of a course when it is added to the schedule container var currentCourseEndTime: LocalTime? = null // Cycle through the hours for (hour in 8..21) { // Start inflating a timetable cell val timetableCell = View.inflate(this, R.layout.item_day_timetable, null) // Put the correct time val time = timetableCell.findViewById<TextView>(R.id.cell_time) time.text = LocalTime.MIDNIGHT.withHour(hour).format(formatter) // Add it to the right container timetableContainer.addView(timetableCell) // Cycle through the half hours var min = 0 while (min < 31) { // Initialize the current course to null var currentCourse: Course? = null // Get the current time val currentTime = LocalTime.of(hour, min) // if currentCourseEndTime = null (no course is being added) or it is equal to // the current time in min (end of a course being added) we need to add a new view if (currentCourseEndTime == null || currentCourseEndTime == currentTime) { // Reset currentCourseEndTime currentCourseEndTime = null // Check if there is a course at this time for (course in courses) { // If there is, set the current course to that time, and calculate the // ending time of this course if (course.roundedStartTime == currentTime) { currentCourse = course currentCourseEndTime = course.roundedEndTime break } } val scheduleCell: View // There is a course at this time if (currentCourse != null) { // Inflate the right view scheduleCell = View.inflate(this, R.layout.item_day_class, null) // Set up all of the info val code = scheduleCell.findViewById<TextView>(R.id.code) code.text = currentCourse.code val type = scheduleCell.findViewById<TextView>(R.id.type) type.text = currentCourse.type val courseTime = scheduleCell.findViewById<TextView>(R.id.course_time) courseTime.text = currentCourse.timeString val location = scheduleCell.findViewById<TextView>(R.id.course_location) location.text = currentCourse.location // Find out how long this course is in terms of blocks of 30 min val length = ChronoUnit.MINUTES.between( currentCourse.roundedStartTime, currentCourse.roundedEndTime ).toInt() / 30 // Set the height of the view depending on this height val lp = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, resources .getDimension(R.dimen.cell_30min_height).toInt() * length ) scheduleCell.layoutParams = lp // Check if we need to make the course clickable if (clickable) { // We need a final variable for the onClick listener val course = currentCourse // OnClick: CourseActivity (for a detailed description of the course) scheduleCell.setOnClickListener { showCourseDialog(course) } } else { scheduleCell.isClickable = false } } else { // Inflate the empty view scheduleCell = View.inflate(this, R.layout.item_day_empty, null) } // Add the given view to the schedule container scheduleContainer.addView(scheduleCell) } min += 30 } } } /** * Shows a dialog with course information * * @param course Clicked [Course] */ private fun showCourseDialog(course: Course) { analytics.event("schedule_course_details") // Set up the view in the dialog val view = ScrollView(this) val container = LinearLayout(this) container.orientation = LinearLayout.VERTICAL view.addView(container) // Create the dialog val alert = AlertDialog.Builder(this) .setView(view) .setCancelable(true) .setNeutralButton(R.string.done) { dialog, _ -> dialog.dismiss() } .show() // Populate the form val shape = Morf.shape // .setShowLine(false) // .setInputDefaultBackground(android.R.color.transparent) container.morf(shape) { // Code addTextInput(R.string.course_code, course.code) // Title addTextInput(R.string.course_name, course.title) // Time addTextInput(R.string.course_time_title, course.timeString) // Location addTextInput(R.string.course_location, course.location) // Type addTextInput(R.string.schedule_type, course.type) // Instructor addTextInput(R.string.course_prof, course.instructor) // Section addTextInput(R.string.course_section, course.section) // Credits addTextInput(R.string.course_credits_title, course.credits.toString()) // CRN addTextInput(R.string.course_crn, course.crn.toString()) val color = getColorCompat(R.color.red) // Docuum borderlessButton { layoutParams( LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ), Gravity.CENTER ) textId = R.string.course_docuum textColor = color onClick { openUrl( "http://www.docuum.com/mcgill/${course.subject.toLowerCase()}" + "/${course.number}" ) } } // Maps borderlessButton { layoutParams( LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ), Gravity.CENTER ) textId = R.string.course_map textColor = color onClick { // Try to find a place that has the right name launch(uiDispatcher) { // Load the places from the Firestore val place = Place.loadPlaces().firstOrNull { course.location.contains(it.coursePlaceName, true) } if (place == null) { // Tell the user toast(getString(R.string.error_place_not_found, course.location)) // Send a Crashlytics report Timber.e(NullPointerException("Location not found: ${course.location}")) } else { // Close the dialog alert.dismiss() // Open the map to the given place val intent = intentFor<MapActivity>(Constants.ID to place.id) switchDrawerActivity(intent) } } } } } } private fun Morf.addTextInput(@StringRes hintId: Int, text: String) = textInput { this.hintId = hintId this.text = text isEnabled = false } /** * Adapter used for the ViewPager in the portrait view of the schedule */ internal inner class ScheduleAdapter : androidx.viewpager.widget.PagerAdapter() { /** * The initial date to use as a reference */ private val startingDate = date /** * The index of the starting date (offset of 500001 to get the right day) */ val startingDateIndex = 500001 + date.dayOfWeek.value private val holders = Stack<DayHolder>() override fun instantiateItem(collection: ViewGroup, position: Int): Any { val holder = if (holders.isNotEmpty()) { holders.pop() } else { DayHolder( LayoutInflater.from(collection.context) .inflate(R.layout.fragment_day, collection, false) ) } // Get the date for this view and set it holder.bind(getDate(position)) collection.addView(holder.view) return holder.view } override fun destroyItem(collection: ViewGroup, position: Int, view: Any) { val dayView = view as? View ?: error("PagerAdapter item was not View type") collection.removeView(dayView) holders.push(DayHolder(view)) } override fun getCount() = 1000000 fun getDate(position: Int): LocalDate = startingDate.plusDays((position - startingDateIndex).toLong()) // This is to force the refreshing of all of the views when the view is reloaded override fun getItemPosition(`object`: Any): Int = androidx.viewpager.widget.PagerAdapter.POSITION_NONE override fun isViewFromObject(view: View, `object`: Any): Boolean = view == `object` inner class DayHolder(val view: View) { internal fun bind(date: LocalDate) { // Set the titles view.apply { dayTitle.setText(DayUtils.getStringId(date.dayOfWeek)) dayDate.text = date.getLongDateString() // Fill the schedule up fillSchedule(timetableContainer, scheduleContainer, date, true) } } } } }
apache-2.0
f84bc15f6ed04d6aae530b12c6ea3737
36.563272
113
0.576805
5.363817
false
false
false
false
iSoron/uhabits
uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/ui/screens/habits/list/ListHabitsMenuBehavior.kt
1
4159
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker 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. * * Loop Habit Tracker 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 org.isoron.uhabits.core.ui.screens.habits.list import org.isoron.uhabits.core.models.HabitList import org.isoron.uhabits.core.models.HabitMatcher import org.isoron.uhabits.core.preferences.Preferences import org.isoron.uhabits.core.ui.ThemeSwitcher import javax.inject.Inject class ListHabitsMenuBehavior @Inject constructor( private val screen: Screen, private val adapter: Adapter, private val preferences: Preferences, private val themeSwitcher: ThemeSwitcher ) { private var showCompleted: Boolean private var showArchived: Boolean fun onCreateHabit() { screen.showSelectHabitTypeDialog() } fun onViewFAQ() { screen.showFAQScreen() } fun onViewAbout() { screen.showAboutScreen() } fun onViewSettings() { screen.showSettingsScreen() } fun onToggleShowArchived() { showArchived = !showArchived preferences.showArchived = showArchived updateAdapterFilter() } fun onToggleShowCompleted() { showCompleted = !showCompleted preferences.showCompleted = showCompleted updateAdapterFilter() } fun onSortByManually() { adapter.primaryOrder = HabitList.Order.BY_POSITION } fun onSortByColor() { onSortToggleBy(HabitList.Order.BY_COLOR_ASC, HabitList.Order.BY_COLOR_DESC) } fun onSortByScore() { onSortToggleBy(HabitList.Order.BY_SCORE_DESC, HabitList.Order.BY_SCORE_ASC) } fun onSortByName() { onSortToggleBy(HabitList.Order.BY_NAME_ASC, HabitList.Order.BY_NAME_DESC) } fun onSortByStatus() { onSortToggleBy(HabitList.Order.BY_STATUS_ASC, HabitList.Order.BY_STATUS_DESC) } private fun onSortToggleBy(defaultOrder: HabitList.Order, reversedOrder: HabitList.Order) { if (adapter.primaryOrder != defaultOrder) { if (adapter.primaryOrder != reversedOrder) { adapter.secondaryOrder = adapter.primaryOrder } adapter.primaryOrder = defaultOrder } else { adapter.primaryOrder = reversedOrder } } fun onToggleNightMode() { themeSwitcher.toggleNightMode() screen.applyTheme() } fun onPreferencesChanged() { updateAdapterFilter() } private fun updateAdapterFilter() { if (preferences.areQuestionMarksEnabled) { adapter.setFilter( HabitMatcher( isArchivedAllowed = showArchived, isEnteredAllowed = showCompleted, ) ) } else { adapter.setFilter( HabitMatcher( isArchivedAllowed = showArchived, isCompletedAllowed = showCompleted, ) ) } adapter.refresh() } interface Adapter { fun refresh() fun setFilter(matcher: HabitMatcher) var primaryOrder: HabitList.Order var secondaryOrder: HabitList.Order } interface Screen { fun applyTheme() fun showAboutScreen() fun showFAQScreen() fun showSettingsScreen() fun showSelectHabitTypeDialog() } init { showCompleted = preferences.showCompleted showArchived = preferences.showArchived updateAdapterFilter() } }
gpl-3.0
97daee37aefebc60134e026560f69be4
28.076923
95
0.652718
4.880282
false
false
false
false
McMoonLakeDev/MoonLake
API/src/main/kotlin/com/mcmoonlake/api/packet/PacketInSteerVehicle.kt
1
1565
/* * Copyright (C) 2016-Present The MoonLake ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mcmoonlake.api.packet data class PacketInSteerVehicle( var strafeSpeed: Float, var forwardSpeed: Float, var jumping: Boolean, var sneaking: Boolean ) : PacketInBukkitAbstract("PacketPlayInSteerVehicle") { @Deprecated("") constructor() : this(0f, 0f, false, false) override fun read(data: PacketBuffer) { strafeSpeed = data.readFloat() forwardSpeed = data.readFloat() val flag = data.readByte().toInt() jumping = (flag and 1) > 0 sneaking = (flag and 2) > 0 } override fun write(data: PacketBuffer) { data.writeFloat(strafeSpeed) data.writeFloat(forwardSpeed) var flag = 0 if(jumping) flag = flag or 1 if(sneaking) flag = flag or 2 data.writeByte(flag) } }
gpl-3.0
19c37c6b7cc619da653ff5283eb20680
31.604167
72
0.665176
4.151194
false
false
false
false
dahlstrom-g/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/action/GHPRViewedStateAction.kt
4
2805
// 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.plugins.github.pullrequest.action import com.intellij.collaboration.messages.CollaborationToolsBundle.messagePointer import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.util.NlsActions.ActionText import com.intellij.openapi.vcs.FilePath import com.intellij.vcsUtil.VcsFileUtil.relativePath import git4idea.repo.GitRepository import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestFileViewedState import org.jetbrains.plugins.github.api.data.pullrequest.isViewed import org.jetbrains.plugins.github.pullrequest.action.GHPRActionKeys.GIT_REPOSITORY import org.jetbrains.plugins.github.pullrequest.action.GHPRActionKeys.PULL_REQUEST_DATA_PROVIDER import org.jetbrains.plugins.github.pullrequest.action.GHPRActionKeys.PULL_REQUEST_FILES import java.util.function.Supplier internal abstract class GHPRViewedStateAction( dynamicText: Supplier<@ActionText String>, private val isViewed: Boolean ) : DumbAwareAction(dynamicText) { override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = false val repository = e.getData(GIT_REPOSITORY) ?: return val files = e.getData(PULL_REQUEST_FILES) ?: return val viewedStateProvider = e.getData(PULL_REQUEST_DATA_PROVIDER)?.viewedStateData ?: return val viewedState = viewedStateProvider.getViewedState() e.presentation.isEnabledAndVisible = files.any { viewedState.isViewed(repository, it) == !isViewed } } override fun actionPerformed(e: AnActionEvent) { val repository = e.getData(GIT_REPOSITORY)!! val files = e.getData(PULL_REQUEST_FILES)!! val viewedStateProvider = e.getData(PULL_REQUEST_DATA_PROVIDER)!!.viewedStateData val viewedState = viewedStateProvider.getViewedState() // todo seems we could make all mutations in single request for (file in files.filter { viewedState.isViewed(repository, it) == !isViewed }) { val repositoryRelativePath = relativePath(repository.root, file) viewedStateProvider.updateViewedState(repositoryRelativePath, isViewed) } } private fun Map<String, GHPullRequestFileViewedState>.isViewed(repository: GitRepository, file: FilePath): Boolean? { val repositoryRelativePath = relativePath(repository.root, file) return this[repositoryRelativePath]?.isViewed() } } internal class GHPRMarkFilesViewedAction : GHPRViewedStateAction(messagePointer("action.CodeReview.MarkChangesViewed.text"), true) internal class GHPRMarkFilesNotViewedAction : GHPRViewedStateAction(messagePointer("action.CodeReview.MarkChangesNotViewed.text"), false)
apache-2.0
a6e48078f7f2b505d95837112af22243
46.559322
158
0.803922
4.546191
false
false
false
false
alexxxdev/kGen
src/ru/alexxxdev/sample/Main.kt
1
1495
package ru.alexxxdev.sample import ru.alexxxdev.kGen.* import ru.alexxxdev.kGen.FieldSpec.PropertyType.MUTABLE import ru.alexxxdev.kGen.FieldSpec.ValueType.NULLABLE import java.io.File /** * Created by alexxxdev on 28.02.17. */ fun main(args: Array<String>) { val file = File("src") kotlinFile("ru.alexxxdev.sample", "Test") { indent = "\t" +import(String::class) +import(ClassName.get(File::class)) field("field1", MUTABLE, NULLABLE) { className = ClassName.get(File::class) "null" } field("field2") { +Modifier.PRIVATE "0" } method("fun2") { +import(String::class) +"val s = \"123\"" returns(ClassName.get(String::class)) { "s" } } method("fun1", Modifier.INTERNAL) { returns { "\"test\"" } } kotlinClass("Class1") { +Modifier.PRIVATE val pV = ParameterizedName.get("V", ClassName.get(String::class)) +pV +import(String::class) field("field11", MUTABLE, NULLABLE) { className = pV "null" } method("fun11") { +Modifier.INTERNAL +"val s = \"123\"" returns(pV) { "\"test\"" } } } kotlinInterface("Interface1") { } kotlinObject("Object1") { } }.writeTo(file) }
apache-2.0
7f1717b6e210c01202bf830ebee56787
21.666667
77
0.49097
4.164345
false
false
false
false
DreierF/MyTargets
app/src/main/java/de/dreier/mytargets/base/gallery/GalleryActivity.kt
1
9471
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets 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. */ package de.dreier.mytargets.base.gallery import android.Manifest import android.annotation.SuppressLint import android.content.Intent import android.os.AsyncTask import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.databinding.DataBindingUtil import androidx.recyclerview.widget.LinearLayoutManager import androidx.viewpager.widget.ViewPager import com.afollestad.materialdialogs.MaterialDialog import com.evernote.android.state.State import de.dreier.mytargets.R import de.dreier.mytargets.base.activities.ChildActivityBase import de.dreier.mytargets.base.gallery.adapters.HorizontalListAdapters import de.dreier.mytargets.base.gallery.adapters.ViewPagerAdapter import de.dreier.mytargets.base.navigation.NavigationController import de.dreier.mytargets.databinding.ActivityGalleryBinding import de.dreier.mytargets.utils.* import permissions.dispatcher.NeedsPermission import permissions.dispatcher.RuntimePermissions import pl.aprilapps.easyphotopicker.DefaultCallback import pl.aprilapps.easyphotopicker.EasyImage import java.io.File import java.io.IOException import java.util.* @RuntimePermissions class GalleryActivity : ChildActivityBase() { internal var adapter: ViewPagerAdapter? = null internal var layoutManager: LinearLayoutManager? = null internal lateinit var previewAdapter: HorizontalListAdapters @State lateinit var imageList: ImageList private lateinit var binding: ActivityGalleryBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_gallery) val title = intent.getStringExtra(EXTRA_TITLE) if (savedInstanceState == null) { imageList = intent.getParcelableExtra(EXTRA_IMAGES) } setSupportActionBar(binding.toolbar) ToolbarUtils.showHomeAsUp(this) ToolbarUtils.setTitle(this, title) Utils.showSystemUI(this) layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) binding.imagesHorizontalList.layoutManager = layoutManager adapter = ViewPagerAdapter(this, imageList, binding.toolbar, binding.imagesHorizontalList) binding.pager.adapter = adapter previewAdapter = HorizontalListAdapters(this, imageList, { this.goToImage(it) }) binding.imagesHorizontalList.adapter = previewAdapter previewAdapter.notifyDataSetChanged() binding.pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrolled( position: Int, positionOffset: Float, positionOffsetPixels: Int ) { } override fun onPageSelected(position: Int) { binding.imagesHorizontalList.smoothScrollToPosition(position) previewAdapter.setSelectedItem(position) } override fun onPageScrollStateChanged(state: Int) { } }) val currentPos = 0 previewAdapter.setSelectedItem(currentPos) binding.pager.currentItem = currentPos if (imageList.size() == 0 && savedInstanceState == null) { onTakePictureWithPermissionCheck() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.gallery, menu) return true } override fun onPrepareOptionsMenu(menu: Menu): Boolean { super.onPrepareOptionsMenu(menu) menu.findItem(R.id.action_share).isVisible = !imageList.isEmpty menu.findItem(R.id.action_delete).isVisible = !imageList.isEmpty return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_share -> { val currentItem = binding.pager.currentItem shareImage(currentItem) return true } R.id.action_delete -> { val currentItem = binding.pager.currentItem deleteImage(currentItem) return true } android.R.id.home -> { navigationController.finish() return true } else -> return super.onOptionsItemSelected(item) } } private fun shareImage(currentItem: Int) { val currentImage = imageList[currentItem] val file = File(filesDir, currentImage.fileName) val uri = file.toUri(this) val shareIntent = Intent(Intent.ACTION_SEND) shareIntent.type = "*/*" shareIntent.putExtra(Intent.EXTRA_STREAM, uri) startActivity(Intent.createChooser(shareIntent, getString(R.string.share))) } private fun deleteImage(currentItem: Int) { MaterialDialog.Builder(this) .content(R.string.delete_image) .negativeText(android.R.string.cancel) .negativeColorRes(R.color.md_grey_500) .positiveText(R.string.delete) .positiveColorRes(R.color.md_red_500) .onPositive { _, _ -> imageList.remove(currentItem) updateResult() invalidateOptionsMenu() adapter!!.notifyDataSetChanged() val nextItem = Math.min(imageList.size() - 1, currentItem) previewAdapter.setSelectedItem(nextItem) binding.pager.currentItem = nextItem } .show() } private fun updateResult() { navigationController.setResultSuccess(imageList) } @NeedsPermission(Manifest.permission.CAMERA) internal fun onTakePicture() { EasyImage.openCameraForImage(this, 0) } @NeedsPermission(Manifest.permission.READ_EXTERNAL_STORAGE) internal fun onSelectImage() { EasyImage.openGallery(this, 0) } @SuppressLint("NeedOnRequestPermissionsResult") override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) onRequestPermissionsResult(requestCode, grantResults) } public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) EasyImage.handleActivityResult(requestCode, resultCode, data, this, object : DefaultCallback() { override fun onImagesPicked( imageFiles: List<File>, source: EasyImage.ImageSource, type: Int ) { loadImages(imageFiles) } override fun onCanceled(source: EasyImage.ImageSource?, type: Int) { //Cancel handling, you might wanna remove taken photo if it was canceled if (source == EasyImage.ImageSource.CAMERA_IMAGE) { val photoFile = EasyImage .lastlyTakenButCanceledPhoto(applicationContext) photoFile?.delete() } } }) } private fun loadImages(imageFile: List<File>) { object : AsyncTask<Void, Void, List<String>>() { override fun doInBackground(vararg params: Void): List<String> { val internalFiles = ArrayList<String>() for (file in imageFile) { try { val internal = File.createTempFile("img", file.name, filesDir) internalFiles.add(internal.name) file.moveTo(internal) } catch (e: IOException) { e.printStackTrace() } } return internalFiles } override fun onPostExecute(files: List<String>) { super.onPostExecute(files) imageList.addAll(files) updateResult() invalidateOptionsMenu() previewAdapter.notifyDataSetChanged() adapter!!.notifyDataSetChanged() val currentPos = imageList.size() - 1 previewAdapter.setSelectedItem(currentPos) binding.pager.currentItem = currentPos } }.execute() } private fun goToImage(pos: Int) { if (imageList.size() == pos) { onTakePictureWithPermissionCheck() } else { binding.pager.setCurrentItem(pos, true) } } companion object { const val EXTRA_IMAGES = "images" const val EXTRA_TITLE = "title" fun getResult(data: Intent): ImageList { return data.getParcelableExtra(NavigationController.ITEM) } } }
gpl-2.0
b99520c193dd12aabd956ed7eea5458c
34.605263
98
0.637525
5.384309
false
false
false
false
Killian-LeClainche/Java-Base-Application-Engine
tests/polaris/okapi/tests/example1/Example.kt
1
1051
package polaris.okapi.tests.example1 import polaris.okapi.App import polaris.okapi.options.Settings import polaris.okapi.options.WindowMode /** * * Created by Killian Le Clainche on 12/15/2017. */ fun main(args: Array<String>) { val app = WindowCreation() app.init() app.run() } fun addCount(count: Int): Int = count + 1 fun addCount(count: Int, function: (Int) -> Int): Int = function(count) class WindowCreation : App(true) { override fun init(): Boolean { if(super.init()) { currentScreen = ExampleGui(this) return true } return false } override fun loadSettings(): Settings { val settings = Settings() settings["mipmap"] = 0 settings["oversample"] = 1 settings["icon"] = "resources/boilermake.png" //OPTIONAL, IN MOST CASES IT'S BEST TO LET DEFAULT BEHAVIOR PERSIST TO HAVE SAVED STATES settings.windowMode = WindowMode.WINDOWED settings.title = "Window Creation Test" return settings } }
gpl-2.0
3e2991971f5f682f8f276ec89b769046
20.44898
96
0.632731
3.981061
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/comprehend/src/main/kotlin/com/kotlin/comprehend/DetectSyntax.kt
1
1857
// snippet-sourcedescription:[DetectSyntax.kt demonstrates how to detect syntax in the text.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[Amazon Comprehend] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.comprehend // snippet-start:[comprehend.kotlin.detect_syntax.import] import aws.sdk.kotlin.services.comprehend.ComprehendClient import aws.sdk.kotlin.services.comprehend.model.DetectSyntaxRequest import aws.sdk.kotlin.services.comprehend.model.SyntaxLanguageCode // snippet-end:[comprehend.kotlin.detect_syntax.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main() { val text = "Amazon.com, Inc. is located in Seattle, WA and was founded July 5th, 1994 by Jeff Bezos, allowing customers to buy everything from books to blenders. Seattle is north of Portland and south of Vancouver, BC. Other notable Seattle - based companies are Starbucks and Boeing." detectAllSyntax(text) } // snippet-start:[comprehend.kotlin.detect_syntax.main] suspend fun detectAllSyntax(textVal: String) { val request = DetectSyntaxRequest { text = textVal languageCode = SyntaxLanguageCode.fromValue("en") } ComprehendClient { region = "us-east-1" }.use { comClient -> val response = comClient.detectSyntax(request) response.syntaxTokens?.forEach { token -> println("Language is ${token.text}") println("Part of speech is ${token.partOfSpeech}") } } } // snippet-end:[comprehend.kotlin.detect_syntax.main]
apache-2.0
b42a4ab6879393d50708496a21bd3023
37.510638
289
0.723748
3.876827
false
false
false
false
SteveChalker/kotlin-koans
src/i_introduction/_0_Hello_World/HelloWorld.kt
2
1219
package i_introduction._0_Hello_World import util.TODO import util.doc0 fun todoTask0(): Nothing = TODO( """ Introduction. Kotlin Koans project consists of 42 small tasks for you to solve. Typically you'll have to replace the function invocation 'todoTaskN()', which throws an exception, with the correct code according to the problem. Using 'documentation =' below the task description you can open the related part of the online documentation. Press 'Ctrl+Q'(Windows) or 'F1'(Mac OS) on 'doc0()' to call the "Quick Documentation" action; "See also" section gives you a link. You can see the shortcut for the "Quick Documentation" action used in your IntelliJ IDEA by choosing "Help -> Find Action..." (in the top menu), and typing the action name ("Quick Documentation"). The shortcut in use will be written next to the action name. Using 'references =' you can navigate to the code mentioned in the task description. Let's start! Make the function 'task0' return "OK". """, documentation = doc0(), references = { task0(); "OK" } ) fun task0(): String { return todoTask0() }
mit
f089dc3800bf018f31f3021bd050f9df
38.354839
119
0.663659
4.565543
false
false
false
false
Displee/RS2-Cache-Library
src/main/kotlin/com/displee/cache/CacheLibrary.kt
1
13789
package com.displee.cache import com.displee.cache.index.Index import com.displee.cache.index.Index.Companion.INDEX_SIZE import com.displee.cache.index.Index.Companion.WHIRLPOOL_SIZE import com.displee.cache.index.Index255 import com.displee.cache.index.Index317 import com.displee.cache.index.ReferenceTable.Companion.FLAG_4 import com.displee.cache.index.ReferenceTable.Companion.FLAG_8 import com.displee.cache.index.ReferenceTable.Companion.FLAG_NAME import com.displee.cache.index.ReferenceTable.Companion.FLAG_WHIRLPOOL import com.displee.cache.index.archive.Archive import com.displee.compress.CompressionType import com.displee.io.Buffer import com.displee.io.impl.OutputBuffer import com.displee.util.generateWhirlpool import java.io.File import java.io.FileNotFoundException import java.io.IOException import java.io.RandomAccessFile import java.math.BigInteger import java.util.* open class CacheLibrary(val path: String, val clearDataAfterUpdate: Boolean = false, private val listener: ProgressListener? = null) { lateinit var mainFile: RandomAccessFile private val indices: SortedMap<Int, Index> = TreeMap<Int, Index>() var index255: Index255? = null private var rs3 = false var closed = false init { init() } private fun init() { val mainFile317 = File(path, "$CACHE_FILE_NAME.dat") val index255 = File(path, "$CACHE_FILE_NAME.idx255") if (mainFile317.exists() && !index255.exists()) { load317() } else { load() } } /** * Re-create indices and re-read reference tables. */ fun reload() { indices.clear() init() } @Throws(IOException::class) private fun load() { val main = File(path, "$CACHE_FILE_NAME.dat2") mainFile = if (main.exists()) { RandomAccessFile(main, "rw") } else { listener?.notify(-1.0, "Error, main file could not be found") throw FileNotFoundException("File[path=${main.absolutePath}] could not be found.") } val index255File = File(path, "$CACHE_FILE_NAME.idx255") if (!index255File.exists()) { listener?.notify(-1.0, "Error, checksum file could not be found.") throw FileNotFoundException("File[path=${index255File.absolutePath}] could not be found.") } val index255 = Index255(this, RandomAccessFile(index255File, "rw")) this.index255 = index255 listener?.notify(0.0, "Reading indices...") val indicesLength = index255.raf.length().toInt() / INDEX_SIZE rs3 = indicesLength > 39 for (i in 0 until indicesLength) { val file = File(path, "$CACHE_FILE_NAME.idx$i") val progress = i / (indicesLength - 1.0) if (!file.exists()) { listener?.notify(progress, "Could not load index $i, missing idx file.") continue } try { indices[i] = Index(this, i, RandomAccessFile(file, "rw")) listener?.notify(progress, "Loaded index $i.") } catch (e: Exception) { e.printStackTrace() listener?.notify(progress, "Failed to load index $i.") } } } @Throws(IOException::class) private fun load317() { val main = File(path, "$CACHE_FILE_NAME.dat") mainFile = if (main.exists()) { RandomAccessFile(main, "rw") } else { listener?.notify(-1.0, "Error, main file could not be found") throw FileNotFoundException("File[path=${main.absolutePath}] could not be found.") } val indexFiles = File(path).listFiles { _: File, name: String -> return@listFiles name.startsWith("$CACHE_FILE_NAME.idx") } check(indexFiles != null) { "Files are null. Check your cache path." } listener?.notify(0.0, "Reading indices...") for (i in indexFiles.indices) { val file = File(path, "$CACHE_FILE_NAME.idx$i") val progress = i / (indexFiles.size - 1.0) if (!file.exists()) { continue } try { indices[i] = Index317(this, i, RandomAccessFile(file, "rw")) listener?.notify(progress, "Loaded index $i .") } catch (e: Exception) { e.printStackTrace() listener?.notify(progress, "Failed to load index $i.") } } } @JvmOverloads fun createIndex(compressionType: CompressionType = CompressionType.GZIP, version: Int = 6, revision: Int = 0, named: Boolean = false, whirlpool: Boolean = false, flag4: Boolean = false, flag8: Boolean = false, writeReferenceTable: Boolean = true): Index { val id = indices.size val raf = RandomAccessFile(File(path, "$CACHE_FILE_NAME.idx$id"), "rw") val index = (if (is317()) Index317(this, id, raf) else Index(this, id, raf)).also { indices[id] = it } if (!writeReferenceTable) { return index } index.version = version index.revision = revision index.compressionType = compressionType if (named) { index.flagMask(FLAG_NAME) } if (whirlpool) { index.flagMask(FLAG_WHIRLPOOL) } if (isRS3()) { if (flag4) { index.flagMask(FLAG_4) } if (flag8) { index.flagMask(FLAG_8) } } index.flag() check(index.update()) return index } fun createIndex(index: Index, writeReferenceTable: Boolean = true): Index { return createIndex(index.compressionType, index.version, index.revision, index.isNamed(), index.hasWhirlpool(), index.hasFlag4(), index.hasFlag8(), writeReferenceTable) } fun exists(id: Int): Boolean { return indices.containsKey(id) } fun index(id: Int): Index { val index = indices[id] checkNotNull(index) { "Index $id doesn't exist. Please use the {@link exists(int) exists} function to verify whether an index exists." } return index } @JvmOverloads fun put(index: Int, archive: Int, file: Int, data: ByteArray, xtea: IntArray? = null): com.displee.cache.index.archive.file.File { return index(index).add(archive, xtea = xtea).add(file, data) } @JvmOverloads fun put(index: Int, archive: Int, data: ByteArray, xtea: IntArray? = null): Archive { val currentArchive = index(index).add(archive, -1, xtea) currentArchive.add(0, data) return currentArchive } @JvmOverloads fun put(index: Int, archive: Int, file: String, data: ByteArray, xtea: IntArray? = null): com.displee.cache.index.archive.file.File { return index(index).add(archive, xtea = xtea).add(file, data) } @JvmOverloads fun put(index: Int, archive: String, data: ByteArray, xtea: IntArray? = null): Archive { val currentArchive = index(index).add(archive, xtea = xtea) currentArchive.add(0, data) return currentArchive } @JvmOverloads fun put(index: Int, archive: String, file: String, data: ByteArray, xtea: IntArray? = null): com.displee.cache.index.archive.file.File { return index(index).add(archive, xtea = xtea).add(file, data) } @JvmOverloads fun data(index: Int, archive: Int, file: Int = 0, xtea: IntArray? = null): ByteArray? { return index(index).archive(archive, xtea)?.file(file)?.data } @JvmOverloads fun data(index: Int, archive: Int, file: String, xtea: IntArray? = null): ByteArray? { return index(index).archive(archive, xtea)?.file(file)?.data } @JvmOverloads fun data(index: Int, archive: String, file: Int, xtea: IntArray? = null): ByteArray? { return index(index).archive(archive, xtea)?.file(file)?.data } @JvmOverloads fun data(index: Int, archive: String, file: String, xtea: IntArray? = null): ByteArray? { return index(index).archive(archive, xtea)?.file(file)?.data } @JvmOverloads fun data(index: Int, archive: String, xtea: IntArray? = null): ByteArray? { return data(index, archive, 0, xtea) } fun remove(index: Int, archive: Int, file: Int): com.displee.cache.index.archive.file.File? { return index(index).archive(archive)?.remove(file) } fun remove(index: Int, archive: Int, file: String): com.displee.cache.index.archive.file.File? { return index(index).archive(archive)?.remove(file) } fun remove(index: Int, archive: String, file: String): com.displee.cache.index.archive.file.File? { return index(index).archive(archive)?.remove(file) } fun remove(index: Int, archive: Int): Archive? { return index(index).remove(archive) } fun remove(index: Int, archive: String): Archive? { return index(index).remove(archive) } fun update() { for (index in indices.values) { if (index.flaggedArchives().isEmpty() && !index.flagged()) { continue } index.update() } } @Throws(RuntimeException::class) fun deleteLastIndex() { if (is317()) { throw UnsupportedOperationException("317 not supported to remove indices yet.") } val id = indices.size - 1 val index = indices[id] ?: return index.close() val file = File(path, "$CACHE_FILE_NAME.idx$id") if (!file.exists() || !file.delete()) { throw RuntimeException("Failed to remove the random access file of the argued index[id=$id, file exists=${file.exists()}]") } index255?.raf?.setLength(id * INDEX_SIZE.toLong()) indices.remove(id) } fun generateOldUkeys(): ByteArray { val buffer = OutputBuffer(indices.size * 8) for (index in indices()) { buffer.writeInt(index.crc) buffer.writeInt(index.revision) } return buffer.array() } fun generateNewUkeys(exponent: BigInteger, modulus: BigInteger): ByteArray { val buffer = OutputBuffer(6 + indices.size * 72) buffer.offset = 5 buffer.writeByte(indices.size) val emptyWhirlpool = ByteArray(WHIRLPOOL_SIZE) for (index in indices()) { buffer.writeInt(index.crc).writeInt(index.revision).writeBytes(index.whirlpool ?: emptyWhirlpool) } val indexArray = buffer.array() val whirlpoolBuffer = OutputBuffer(WHIRLPOOL_SIZE + 1).writeByte(1).writeBytes(indexArray.generateWhirlpool(5, indexArray.size - 5)) buffer.writeBytes(Buffer.cryptRSA(whirlpoolBuffer.array(), exponent, modulus)) val end = buffer.offset buffer.offset = 0 buffer.writeByte(0) buffer.writeInt(end - 5) buffer.offset = end return buffer.array() } fun rebuild(directory: File) { File(directory.path).mkdirs() if (is317()) { File(directory.path, "$CACHE_FILE_NAME.dat").createNewFile() } else { File(directory.path, "$CACHE_FILE_NAME.idx255").createNewFile() File(directory.path, "$CACHE_FILE_NAME.dat2").createNewFile() } val indicesSize = indices.values.size val newLibrary = CacheLibrary(directory.path) for (index in indices.values) { val id = index.id print("\rBuilding index $id/$indicesSize...") val archiveSector = index255?.readArchiveSector(id) var writeReferenceTable = true if (!is317() && archiveSector == null) { //some empty indices don't even have a reference table writeReferenceTable = false //in that case, don't write it } val newIndex = newLibrary.createIndex(index, writeReferenceTable) for (i in index.archiveIds()) { //only write referenced archives val data = index.readArchiveSector(i)?.data ?: continue newIndex.writeArchiveSector(i, data) } if (archiveSector != null) { newLibrary.index255?.writeArchiveSector(id, archiveSector.data) } } newLibrary.close() println("\rFinished building $indicesSize indices.") } fun fixCrcs(update: Boolean) { indices.values.forEach { if (it.archiveIds().isEmpty()) { return@forEach } it.fixCRCs(update) } } fun close() { if (closed) { return } mainFile.close() index255?.close() indices.values.forEach { it.close() } closed = true } fun first(): Index? { if (indices.isEmpty()) { return null } return indices[indices.firstKey()] } fun last(): Index? { if (indices.isEmpty()) { return null } return indices[indices.lastKey()] } fun is317(): Boolean { return index255 == null } fun isOSRS(): Boolean { val index = index(2) return index.revision >= 300 && indices.size <= 23 } fun isRS3(): Boolean { return rs3 } fun indices(): Array<Index> { return indices.values.toTypedArray() } companion object { const val CACHE_FILE_NAME = "main_file_cache" @JvmStatic @JvmOverloads fun create(path: String, clearDataAfterUpdate: Boolean = false, listener: ProgressListener? = null): CacheLibrary { return CacheLibrary(path, clearDataAfterUpdate, listener) } } }
mit
26d1cb2a22d3ff1f342a88bd8d402184
34.630491
144
0.597505
4.206528
false
false
false
false
apache/isis
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/ui/core/Constants.kt
2
1853
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.ui.core object Constants { const val restInfix = "restful/" const val stdMimeType = "text/plain" const val svgMimeType = "image/svg+xml" const val pngMimeType = "image/png" const val xmlMimeType = "application/xml" const val calcHeight = "calc(100vh - 113px)" const val actionSeparator = "\n" const val subTypeJson = "json" const val subTypeXml = "xml" //const val krokiUrl = "https://kroki.io/" //see: https://github.com/yuzutech/kroki const val krokiUrl = "http://localhost:8000/" //host:port depends on how docker is started // docker run -d --name kroki -p 8080:8000 yuzutech/kroki const val demoUrl = "http://localhost:8080/" const val demoUser = "sven" const val demoPass = "pass" const val demoUrlRemote = "https://demo-wicket.jdo.causeway.incode.work/" val demoRemoteImage = io.kvision.require("img/incode_we_share.jpg") const val domoxUrl = "http://localhost:8081/" const val spacing = 10 }
apache-2.0
8b4414a4ea106f3011a6a3feadc6fd5f
39.282609
87
0.704263
3.773931
false
false
false
false
algra/pact-jvm
pact-jvm-pact-broker/src/main/kotlin/au/com/dius/pact/pactbroker/HalClient.kt
1
16186
package au.com.dius.pact.pactbroker import au.com.dius.pact.provider.broker.com.github.kittinunf.result.Result import au.com.dius.pact.util.HttpClientUtils.buildUrl import au.com.dius.pact.util.HttpClientUtils.isJsonResponse import com.github.salomonbrys.kotson.array import com.github.salomonbrys.kotson.bool import com.github.salomonbrys.kotson.get import com.github.salomonbrys.kotson.keys import com.github.salomonbrys.kotson.nullObj import com.github.salomonbrys.kotson.obj import com.github.salomonbrys.kotson.string import com.google.common.net.UrlEscapers import com.google.gson.JsonElement import com.google.gson.JsonObject import com.google.gson.JsonParser import mu.KLogging import org.apache.http.HttpResponse import org.apache.http.auth.AuthScope import org.apache.http.auth.UsernamePasswordCredentials import org.apache.http.client.methods.CloseableHttpResponse import org.apache.http.client.methods.HttpGet import org.apache.http.client.methods.HttpPost import org.apache.http.client.methods.HttpPut import org.apache.http.entity.ContentType import org.apache.http.entity.StringEntity import org.apache.http.impl.client.BasicCredentialsProvider import org.apache.http.impl.client.CloseableHttpClient import org.apache.http.impl.client.HttpClients import org.apache.http.util.EntityUtils import java.net.URI import java.util.function.BiFunction import java.util.function.Consumer /** * Interface to a HAL Client */ interface IHalClient { /** * Navigates the URL associated with the given link using the current HAL document * @param options Map of key-value pairs to use for parsing templated links * @param link Link name to navigate */ fun navigate(options: Map<String, Any> = mapOf(), link: String): IHalClient /** * Navigates the URL associated with the given link using the current HAL document * @param link Link name to navigate */ fun navigate(link: String): IHalClient /** * Returns the HREF of the named link from the current HAL document */ fun linkUrl(name: String): String? /** * Calls the closure with a Map of attributes for all links associated with the link name * @param linkName Name of the link to loop over * @param closure Closure to invoke with the link attributes */ fun forAll(linkName: String, closure: Consumer<Map<String, Any?>>) /** * Upload the JSON document to the provided path, using a PUT request * @param path Path to upload the document * @param bodyJson JSON contents for the body */ fun uploadJson(path: String, bodyJson: String): Any? /** * Upload the JSON document to the provided path, using a PUT request * @param path Path to upload the document * @param bodyJson JSON contents for the body * @param closure Closure that will be invoked with details about the response. The result from the closure will be * returned. */ fun uploadJson(path: String, bodyJson: String, closure: BiFunction<String, String, Any?>): Any? /** * Upload the JSON document to the provided path, using a PUT request * @param path Path to upload the document * @param bodyJson JSON contents for the body * @param closure Closure that will be invoked with details about the response. The result from the closure will be * returned. * @param encodePath If the path must be encoded beforehand. */ fun uploadJson(path: String, bodyJson: String, closure: BiFunction<String, String, Any?>, encodePath: Boolean): Any? /** * Upload the JSON document to the provided URL, using a POST request * @param url Url to upload the document to * @param body JSON contents for the body * @return Returns a Success result object with a boolean value to indicate if the request was successful or not. Any * exception will be wrapped in a Failure */ fun postJson(url: String, body: String): Result<Boolean, Exception> /** * Upload the JSON document to the provided URL, using a POST request * @param url Url to upload the document to * @param body JSON contents for the body * @param handler Response handler * @return Returns a Success result object with the boolean value returned from the handler closure. Any * exception will be wrapped in a Failure */ fun postJson(url: String, body: String, handler: ((status: Int, response: CloseableHttpResponse) -> Boolean)?): Result<Boolean, Exception> /** * Fetches the HAL document from the provided path * @param path The path to the HAL document. If it is a relative path, it is relative to the base URL * @param encodePath If the path should be encoded to make a valid URL */ fun fetch(path: String, encodePath: Boolean): JsonElement /** * Fetches the HAL document from the provided path * @param path The path to the HAL document. If it is a relative path, it is relative to the base URL */ fun fetch(path: String): JsonElement } /** * HAL client base class */ abstract class HalClientBase @JvmOverloads constructor( val baseUrl: String, var options: Map<String, Any> = mapOf() ) : IHalClient { var httpClient: CloseableHttpClient? = null var pathInfo: JsonElement? = null var lastUrl: String? = null override fun postJson(url: String, body: String) = postJson(url, body, null) override fun postJson( url: String, body: String, handler: ((status: Int, response: CloseableHttpResponse) -> Boolean)? ): Result<Boolean, Exception> { val client = setupHttpClient() return Result.of { val httpPost = HttpPost(url) httpPost.addHeader("Content-Type", ContentType.APPLICATION_JSON.toString()) httpPost.entity = StringEntity(body, ContentType.APPLICATION_JSON) client.execute(httpPost).use { if (handler != null) { handler(it.statusLine.statusCode, it) } else { it.statusLine.statusCode < 300 } } } } open fun setupHttpClient(): CloseableHttpClient { if (httpClient == null) { val builder = HttpClients.custom().useSystemProperties() if (options["authentication"] is List<*>) { val authentication = options["authentication"] as List<*> val scheme = authentication.first().toString().toLowerCase() when (scheme) { "basic" -> { if (authentication.size > 2) { val credsProvider = BasicCredentialsProvider() val uri = URI(baseUrl) credsProvider.setCredentials(AuthScope(uri.host, uri.port), UsernamePasswordCredentials(authentication[1].toString(), authentication[2].toString())) builder.setDefaultCredentialsProvider(credsProvider) } else { logger.warn { "Basic authentication requires a username and password, ignoring." } } } else -> logger.warn { "Hal client Only supports basic authentication, got '$scheme', ignoring." } } } else if (options.containsKey("authentication")) { logger.warn { "Authentication options needs to be a list of values, ignoring." } } httpClient = builder.build() } return httpClient!! } override fun navigate(options: Map<String, Any>, link: String): IHalClient { pathInfo = pathInfo ?: fetch(ROOT) pathInfo = fetchLink(link, options) return this } override fun navigate(link: String) = navigate(mapOf(), link) override fun fetch(path: String) = fetch(path, true) override fun fetch(path: String, encodePath: Boolean): JsonElement { lastUrl = path logger.debug { "Fetching: $path" } val response = getJson(path, encodePath) when (response) { is Result.Success -> return response.value is Result.Failure -> throw response.error } } private fun getJson(path: String, encodePath: Boolean = true): Result<JsonElement, Exception> { setupHttpClient() return Result.of { val httpGet = HttpGet(buildUrl(baseUrl, path, encodePath)) httpGet.addHeader("Content-Type", "application/json") httpGet.addHeader("Accept", "application/hal+json, application/json") val response = httpClient!!.execute(httpGet) if (response.statusLine.statusCode < 300) { val contentType = ContentType.getOrDefault(response.entity) if (isJsonResponse(contentType)) { return@of JsonParser().parse(EntityUtils.toString(response.entity)) } else { throw InvalidHalResponse("Expected a HAL+JSON response from the pact broker, but got '$contentType'") } } else { when (response.statusLine.statusCode) { 404 -> throw NotFoundHalResponse("No HAL document found at path '$path'") else -> throw RequestFailedException("Request to path '$path' failed with response '${response.statusLine}'") } } } } private fun fetchLink(link: String, options: Map<String, Any>): JsonElement { if (pathInfo?.nullObj?.get(LINKS) == null) { throw InvalidHalResponse("Expected a HAL+JSON response from the pact broker, but got " + "a response with no '_links'. URL: '$baseUrl', LINK: '$link'") } val links = pathInfo!![LINKS] if (links.isJsonObject) { if (!links.obj.has(link)) { throw InvalidHalResponse("Link '$link' was not found in the response, only the following links where " + "found: ${links.obj.keys()}. URL: '$baseUrl', LINK: '$link'") } val linkData = links[link] if (linkData.isJsonArray) { if (options.containsKey("name")) { val linkByName = linkData.asJsonArray.find { it.isJsonObject && it["name"] == options["name"] } return if (linkByName != null && linkByName.isJsonObject && linkByName["templated"].isJsonPrimitive && linkByName["templated"].bool) { this.fetch(parseLinkUrl(linkByName["href"].toString(), options), false) } else if (linkByName != null && linkByName.isJsonObject) { this.fetch(linkByName["href"].string) } else { throw InvalidNavigationRequest("Link '$link' does not have an entry with name '${options["name"]}'. " + "URL: '$baseUrl', LINK: '$link'") } } else { throw InvalidNavigationRequest ("Link '$link' has multiple entries. You need to filter by the link name. " + "URL: '$baseUrl', LINK: '$link'") } } else if (linkData.isJsonObject) { return if (linkData.obj.has("templated") && linkData["templated"].isJsonPrimitive && linkData["templated"].bool) { fetch(parseLinkUrl(linkData["href"].string, options), false) } else { fetch(linkData["href"].string) } } else { throw InvalidHalResponse("Expected link in map form in the response, but " + "found: $linkData. URL: '$baseUrl', LINK: '$link'") } } else { throw InvalidHalResponse("Expected a map of links in the response, but " + "found: $links. URL: '$baseUrl', LINK: '$link'") } } fun parseLinkUrl(href: String, options: Map<String, Any>): String { var result = "" var match = URL_TEMPLATE_REGEX.find(href) var index = 0 while (match != null) { val start = match.range.start - 1 if (start >= index) { result += href.substring(index..start) } index = match.range.endInclusive + 1 val (key) = match.destructured result += encodePathParameter(options, key, match.value) match = URL_TEMPLATE_REGEX.find(href, index) } if (index < href.length) { result += href.substring(index) } return result } private fun encodePathParameter(options: Map<String, Any>, key: String, value: String): String? { return UrlEscapers.urlPathSegmentEscaper().escape(options[key]?.toString() ?: value) } fun initPathInfo() { pathInfo = pathInfo ?: fetch(ROOT) } override fun uploadJson(path: String, bodyJson: String) = uploadJson(path, bodyJson, BiFunction { _: String, _: String -> null }, true) override fun uploadJson(path: String, bodyJson: String, closure: BiFunction<String, String, Any?>) = uploadJson(path, bodyJson, closure, true) override fun uploadJson( path: String, bodyJson: String, closure: BiFunction<String, String, Any?>, encodePath: Boolean ): Any? { val client = setupHttpClient() val httpPut = HttpPut(buildUrl(baseUrl, path, encodePath)) httpPut.addHeader("Content-Type", ContentType.APPLICATION_JSON.toString()) httpPut.entity = StringEntity(bodyJson, ContentType.APPLICATION_JSON) client.execute(httpPut).use { return when { it.statusLine.statusCode < 300 -> { EntityUtils.consume(it.entity) closure.apply("OK", it.statusLine.toString()) } it.statusLine.statusCode == 409 -> { val body = it.entity.content.bufferedReader().readText() closure.apply("FAILED", "${it.statusLine.statusCode} ${it.statusLine.reasonPhrase} - $body") } else -> { val body = it.entity.content.bufferedReader().readText() handleFailure(it, body, closure) } } } } fun handleFailure(resp: HttpResponse, body: String?, closure: BiFunction<String, String, Any?>): Any? { if (resp.entity.contentType != null) { val contentType = ContentType.getOrDefault(resp.entity) if (isJsonResponse(contentType)) { var error = "Unknown error" if (body != null) { val jsonBody = JsonParser().parse(body) if (jsonBody != null && jsonBody.obj.has("errors")) { if (jsonBody["errors"].isJsonArray) { error = jsonBody["errors"].asJsonArray.joinToString(", ") { it.asString } } else if (jsonBody["errors"].isJsonObject) { error = jsonBody["errors"].asJsonObject.entrySet().joinToString(", ") { if (it.value.isJsonArray) { "${it.key}: ${it.value.array.joinToString(", ") { it.asString }}" } else { "${it.key}: ${it.value.asString}" } } } } } return closure.apply("FAILED", "${resp.statusLine.statusCode} ${resp.statusLine.reasonPhrase} - $error") } else { return closure.apply("FAILED", "${resp.statusLine.statusCode} ${resp.statusLine.reasonPhrase} - $body") } } else { return closure.apply("FAILED", "${resp.statusLine.statusCode} ${resp.statusLine.reasonPhrase} - $body") } } override fun linkUrl(name: String): String? { if (pathInfo!!.obj.has(LINKS)) { val links = pathInfo!![LINKS] if (links.isJsonObject && links.obj.has(name)) { val linkData = links[name] if (linkData.isJsonObject && linkData.obj.has("href")) { return fromJson(linkData["href"]).toString() } } } return null } override fun forAll(linkName: String, just: Consumer<Map<String, Any?>>) { initPathInfo() val links = pathInfo!![LINKS] if (links.isJsonObject && links.obj.has(linkName)) { val matchingLink = links[linkName] if (matchingLink.isJsonArray) { matchingLink.asJsonArray.forEach { just.accept(asMap(it.asJsonObject)) } } else { just.accept(asMap(matchingLink.asJsonObject)) } } } companion object : KLogging() { const val ROOT = "/" const val LINKS = "_links" val URL_TEMPLATE_REGEX = Regex("\\{(\\w+)\\}") @JvmStatic fun asMap(jsonObject: JsonObject) = jsonObject.entrySet().associate { entry -> entry.key to fromJson(entry.value) } @JvmStatic fun fromJson(jsonValue: JsonElement): Any? { return if (jsonValue.isJsonObject) { asMap(jsonValue.asJsonObject) } else if (jsonValue.isJsonArray) { jsonValue.asJsonArray.map { fromJson(it) } } else if (jsonValue.isJsonNull) { null } else { val primitive = jsonValue.asJsonPrimitive when { primitive.isBoolean -> primitive.asBoolean primitive.isNumber -> primitive.asBigDecimal else -> primitive.asString } } } } }
apache-2.0
cf4cf081cd1f1b60c0a0340621e728dd
36.729604
140
0.656308
4.351075
false
false
false
false
RuneSuite/client
api/src/main/java/org/runestar/client/api/game/Actor.kt
1
1672
package org.runestar.client.api.game import org.runestar.client.raw.access.XActor import org.runestar.client.raw.access.XHeadbar import org.runestar.client.raw.access.XHeadbarUpdate abstract class Actor(override val accessor: XActor) : Entity(accessor), ActorTargeting { abstract val plane: Int override val npcTargetIndex: Int get() = accessor.targetIndex.let { if (it in 0..32767) it else -1 } override val playerTargetIndex: Int get() = accessor.targetIndex.let { if (it > 32768) it - 32768 else -1 } override val modelPosition get() = Position(accessor.x, accessor.y, 0, plane) val location get() = SceneTile(accessor.pathX[0], accessor.pathY[0], plane) override val orientation get() = Angle.of(accessor.orientation) var overheadText: String? get() = accessor.overheadText set(value) { accessor.overheadText = value } var overheadTextCyclesRemaining: Int get() = accessor.overheadTextCyclesRemaining set(value) { accessor.overheadTextCyclesRemaining = value } /** * Health percent between `0.0` and `1.0` of limited precision. `null` if the health-bar is not visible. */ val health: Double? get() { val headbars = accessor.headbars ?: return null val headbar = headbars.sentinel.next if (headbar is XHeadbar) { val update = headbar.updates.sentinel.next if (update is XHeadbarUpdate) { val def = headbar.type ?: return null return update.health.toDouble() / def.width } } return null } val defaultHeight: Int get() = accessor.defaultHeight }
mit
7575400820c116657a0a22a029c5eb7d
33.854167
108
0.662679
3.952719
false
false
false
false