content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package org.tsdes.advanced.rest.exceptionhandling.db import org.springframework.data.repository.CrudRepository import org.springframework.stereotype.Repository @Repository interface UserRepository : CrudRepository<UserEntity, Long>
advanced/rest/exception-handling/src/main/kotlin/org/tsdes/advanced/rest/exceptionhandling/db/UserRepository.kt
2842562634
package nl.rsdt.japp.jotial.maps.wrapper import android.graphics.Bitmap import android.location.Location import android.util.Pair import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.model.* import nl.rsdt.japp.jotial.maps.window.CustomInfoWindowAdapter /** * Created by mattijn on 07/08/17. */ interface IJotiMap { val uiSettings: IUiSettings val previousCameraPosition: ICameraPosition fun delete() fun setInfoWindowAdapter(infoWindowAdapter: CustomInfoWindowAdapter) fun setGMapType(mapType: Int) fun setMapStyle(mapStyleOptions: MapStyleOptions): Boolean fun animateCamera(latLng: LatLng, zoom: Int) fun addMarker(markerOptions: Pair<MarkerOptions, Bitmap?>): IMarker fun addPolyline(polylineOptions: PolylineOptions): IPolyline fun addPolygon(polygonOptions: PolygonOptions): IPolygon fun addCircle(circleOptions: CircleOptions): ICircle fun setOnMapClickListener(onMapClickListener: OnMapClickListener?) fun snapshot(snapshotReadyCallback: IJotiMap.SnapshotReadyCallback?) fun animateCamera(latLng: LatLng, zoom: Int, cancelableCallback: IJotiMap.CancelableCallback?) fun setOnCameraMoveStartedListener(onCameraMoveStartedListener: GoogleMap.OnCameraMoveStartedListener?) fun cameraToLocation(b: Boolean, location: Location, zoom: Float, aoa: Float, bearing: Float) fun clear() fun setOnInfoWindowLongClickListener(onInfoWindowLongClickListener: GoogleMap.OnInfoWindowLongClickListener?) fun setMarkerOnClickListener(listener: IJotiMap.OnMarkerClickListener?) fun getMapAsync(callback: IJotiMap.OnMapReadyCallback) fun setPreviousCameraPosition(latitude: Double, longitude: Double) fun setPreviousZoom(zoom: Int) fun setPreviousRotation(rotation: Float) fun followLocation(followLocation:Boolean, keepNorth:Boolean) interface OnMapReadyCallback { fun onMapReady(map: IJotiMap) } interface OnMarkerClickListener { fun OnClick(m: IMarker): Boolean } interface OnMapClickListener { fun onMapClick(latLng: LatLng): Boolean } interface CancelableCallback { fun onFinish() fun onCancel() } interface SnapshotReadyCallback { fun onSnapshotReady(var1: Bitmap) } }
app/src/main/java/nl/rsdt/japp/jotial/maps/wrapper/IJotiMap.kt
3793264803
package domain.login internal class FailedLoginException(description: String) : Exception(description)
domain/src/main/kotlin/domain/login/FailedLoginException.kt
2977718945
package org.thoughtcrime.securesms.stories.viewer.reply.group import android.content.ClipData import android.os.Bundle import android.view.KeyEvent import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.annotation.ColorInt import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.bottomsheet.BottomSheetBehaviorHack import com.google.android.material.bottomsheet.BottomSheetDialog import com.google.android.material.dialog.MaterialAlertDialogBuilder import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.kotlin.subscribeBy import org.signal.core.util.concurrent.SignalExecutors import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.components.FixedRoundedCornerBottomSheetDialogFragment import org.thoughtcrime.securesms.components.emoji.MediaKeyboard import org.thoughtcrime.securesms.components.mention.MentionAnnotation import org.thoughtcrime.securesms.components.settings.DSLConfiguration import org.thoughtcrime.securesms.components.settings.configure import org.thoughtcrime.securesms.contacts.paged.ContactSearchKey import org.thoughtcrime.securesms.conversation.MarkReadHelper import org.thoughtcrime.securesms.conversation.colors.Colorizer import org.thoughtcrime.securesms.conversation.ui.inlinequery.InlineQuery import org.thoughtcrime.securesms.conversation.ui.inlinequery.InlineQueryChangedListener import org.thoughtcrime.securesms.conversation.ui.inlinequery.InlineQueryResultsController import org.thoughtcrime.securesms.conversation.ui.inlinequery.InlineQueryViewModel import org.thoughtcrime.securesms.conversation.ui.mentions.MentionsPickerFragment import org.thoughtcrime.securesms.conversation.ui.mentions.MentionsPickerViewModel import org.thoughtcrime.securesms.database.model.Mention import org.thoughtcrime.securesms.database.model.MessageId import org.thoughtcrime.securesms.database.model.MessageRecord import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.jobs.RetrieveProfileJob import org.thoughtcrime.securesms.keyboard.KeyboardPage import org.thoughtcrime.securesms.keyboard.KeyboardPagerViewModel import org.thoughtcrime.securesms.keyboard.emoji.EmojiKeyboardCallback import org.thoughtcrime.securesms.mediasend.v2.UntrustedRecords import org.thoughtcrime.securesms.notifications.v2.ConversationId import org.thoughtcrime.securesms.reactions.any.ReactWithAnyEmojiBottomSheetDialogFragment import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.recipients.RecipientId import org.thoughtcrime.securesms.recipients.ui.bottomsheet.RecipientBottomSheetDialogFragment import org.thoughtcrime.securesms.safety.SafetyNumberBottomSheet import org.thoughtcrime.securesms.sms.MessageSender import org.thoughtcrime.securesms.stories.viewer.reply.StoryViewsAndRepliesPagerChild import org.thoughtcrime.securesms.stories.viewer.reply.StoryViewsAndRepliesPagerParent import org.thoughtcrime.securesms.stories.viewer.reply.composer.StoryReactionBar import org.thoughtcrime.securesms.stories.viewer.reply.composer.StoryReplyComposer import org.thoughtcrime.securesms.util.DeleteDialog import org.thoughtcrime.securesms.util.FragmentDialogs.displayInDialogAboveAnchor import org.thoughtcrime.securesms.util.LifecycleDisposable import org.thoughtcrime.securesms.util.ServiceUtil import org.thoughtcrime.securesms.util.ViewUtil import org.thoughtcrime.securesms.util.adapter.mapping.PagingMappingAdapter import org.thoughtcrime.securesms.util.fragments.findListener import org.thoughtcrime.securesms.util.fragments.requireListener import org.thoughtcrime.securesms.util.visible /** * Fragment which contains UI to reply to a group story */ class StoryGroupReplyFragment : Fragment(R.layout.stories_group_replies_fragment), StoryViewsAndRepliesPagerChild, StoryReplyComposer.Callback, EmojiKeyboardCallback, ReactWithAnyEmojiBottomSheetDialogFragment.Callback, SafetyNumberBottomSheet.Callbacks { companion object { private val TAG = Log.tag(StoryGroupReplyFragment::class.java) private const val ARG_STORY_ID = "arg.story.id" private const val ARG_GROUP_RECIPIENT_ID = "arg.group.recipient.id" private const val ARG_IS_FROM_NOTIFICATION = "is_from_notification" private const val ARG_GROUP_REPLY_START_POSITION = "group_reply_start_position" fun create(storyId: Long, groupRecipientId: RecipientId, isFromNotification: Boolean, groupReplyStartPosition: Int): Fragment { return StoryGroupReplyFragment().apply { arguments = Bundle().apply { putLong(ARG_STORY_ID, storyId) putParcelable(ARG_GROUP_RECIPIENT_ID, groupRecipientId) putBoolean(ARG_IS_FROM_NOTIFICATION, isFromNotification) putInt(ARG_GROUP_REPLY_START_POSITION, groupReplyStartPosition) } } } } private val viewModel: StoryGroupReplyViewModel by viewModels( factoryProducer = { StoryGroupReplyViewModel.Factory(storyId, StoryGroupReplyRepository()) } ) private val mentionsViewModel: MentionsPickerViewModel by viewModels( factoryProducer = { MentionsPickerViewModel.Factory() }, ownerProducer = { requireActivity() } ) private val inlineQueryViewModel: InlineQueryViewModel by viewModels( ownerProducer = { requireActivity() } ) private val keyboardPagerViewModel: KeyboardPagerViewModel by viewModels( ownerProducer = { requireActivity() } ) private val recyclerListener: RecyclerView.OnItemTouchListener = object : RecyclerView.SimpleOnItemTouchListener() { override fun onInterceptTouchEvent(view: RecyclerView, e: MotionEvent): Boolean { recyclerView.isNestedScrollingEnabled = view == recyclerView composer.emojiPageView?.isNestedScrollingEnabled = view == composer.emojiPageView val dialog = (parentFragment as FixedRoundedCornerBottomSheetDialogFragment).dialog as BottomSheetDialog BottomSheetBehaviorHack.setNestedScrollingChild(dialog.behavior, view) dialog.findViewById<View>(R.id.design_bottom_sheet)?.invalidate() return false } } private val colorizer = Colorizer() private val lifecycleDisposable = LifecycleDisposable() private val storyId: Long get() = requireArguments().getLong(ARG_STORY_ID) private val groupRecipientId: RecipientId get() = requireArguments().getParcelable(ARG_GROUP_RECIPIENT_ID)!! private val isFromNotification: Boolean get() = requireArguments().getBoolean(ARG_IS_FROM_NOTIFICATION, false) private val groupReplyStartPosition: Int get() = requireArguments().getInt(ARG_GROUP_REPLY_START_POSITION, -1) private lateinit var recyclerView: RecyclerView private lateinit var adapter: PagingMappingAdapter<MessageId> private lateinit var dataObserver: RecyclerView.AdapterDataObserver private lateinit var composer: StoryReplyComposer private lateinit var notInGroup: View private var markReadHelper: MarkReadHelper? = null private var currentChild: StoryViewsAndRepliesPagerParent.Child? = null private var resendBody: CharSequence? = null private var resendMentions: List<Mention> = emptyList() private var resendReaction: String? = null private lateinit var inlineQueryResultsController: InlineQueryResultsController override fun onViewCreated(view: View, savedInstanceState: Bundle?) { SignalExecutors.BOUNDED.execute { RetrieveProfileJob.enqueue(groupRecipientId) } recyclerView = view.findViewById(R.id.recycler) composer = view.findViewById(R.id.composer) notInGroup = view.findViewById(R.id.not_in_group) lifecycleDisposable.bindTo(viewLifecycleOwner) val emptyNotice: View = requireView().findViewById(R.id.empty_notice) adapter = PagingMappingAdapter<MessageId>().apply { setPagingController(viewModel.pagingController) } val layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false) recyclerView.layoutManager = layoutManager recyclerView.adapter = adapter recyclerView.itemAnimator = null StoryGroupReplyItem.register(adapter) composer.callback = this composer.hint = getString(R.string.StoryViewerPageFragment__reply_to_group) onPageSelected(findListener<StoryViewsAndRepliesPagerParent>()?.selectedChild ?: StoryViewsAndRepliesPagerParent.Child.REPLIES) var firstSubmit = true lifecycleDisposable += viewModel.state .observeOn(AndroidSchedulers.mainThread()) .subscribeBy { state -> if (markReadHelper == null && state.threadId > 0L) { if (isResumed) { ApplicationDependencies.getMessageNotifier().setVisibleThread(ConversationId(state.threadId, storyId)) } markReadHelper = MarkReadHelper(ConversationId(state.threadId, storyId), requireContext(), viewLifecycleOwner) if (isFromNotification) { markReadHelper?.onViewsRevealed(System.currentTimeMillis()) } } emptyNotice.visible = state.noReplies && state.loadState == StoryGroupReplyState.LoadState.READY colorizer.onNameColorsChanged(state.nameColors) adapter.submitList(getConfiguration(state.replies).toMappingModelList()) { if (firstSubmit && (groupReplyStartPosition >= 0 && adapter.hasItem(groupReplyStartPosition))) { firstSubmit = false recyclerView.post { recyclerView.scrollToPosition(groupReplyStartPosition) } } } } dataObserver = GroupDataObserver() adapter.registerAdapterDataObserver(dataObserver) initializeMentions() initializeComposer(savedInstanceState) recyclerView.addOnScrollListener(GroupReplyScrollObserver()) } override fun onResume() { super.onResume() val threadId = viewModel.stateSnapshot.threadId if (threadId != 0L) { ApplicationDependencies.getMessageNotifier().setVisibleThread(ConversationId(threadId, storyId)) } } override fun onPause() { super.onPause() ApplicationDependencies.getMessageNotifier().setVisibleThread(null) } override fun onDestroyView() { super.onDestroyView() composer.input.setInlineQueryChangedListener(null) composer.input.setMentionValidator(null) } private fun postMarkAsReadRequest() { if (adapter.itemCount == 0 || markReadHelper == null) { return } val lastVisibleItem = (recyclerView.layoutManager as LinearLayoutManager).findLastVisibleItemPosition() val adapterItem = adapter.getItem(lastVisibleItem) if (adapterItem == null || adapterItem !is StoryGroupReplyItem.Model) { return } markReadHelper?.onViewsRevealed(adapterItem.replyBody.sentAtMillis) } private fun getConfiguration(pageData: List<ReplyBody>): DSLConfiguration { return configure { pageData.forEach { when (it) { is ReplyBody.Text -> { customPref( StoryGroupReplyItem.TextModel( text = it, nameColor = it.sender.getStoryGroupReplyColor(), onCopyClick = { s -> onCopyClick(s) }, onMentionClick = { recipientId -> RecipientBottomSheetDialogFragment .create(recipientId, null) .show(childFragmentManager, null) }, onDeleteClick = { m -> onDeleteClick(m) }, onTapForDetailsClick = { m -> onTapForDetailsClick(m) } ) ) } is ReplyBody.Reaction -> { customPref( StoryGroupReplyItem.ReactionModel( reaction = it, nameColor = it.sender.getStoryGroupReplyColor(), onCopyClick = { s -> onCopyClick(s) }, onDeleteClick = { m -> onDeleteClick(m) }, onTapForDetailsClick = { m -> onTapForDetailsClick(m) } ) ) } is ReplyBody.RemoteDelete -> { customPref( StoryGroupReplyItem.RemoteDeleteModel( remoteDelete = it, nameColor = it.sender.getStoryGroupReplyColor(), onDeleteClick = { m -> onDeleteClick(m) }, onTapForDetailsClick = { m -> onTapForDetailsClick(m) } ) ) } } } } } private fun onCopyClick(textToCopy: CharSequence) { val clipData = ClipData.newPlainText(requireContext().getString(R.string.app_name), textToCopy) ServiceUtil.getClipboardManager(requireContext()).setPrimaryClip(clipData) Toast.makeText(requireContext(), R.string.StoryGroupReplyFragment__copied_to_clipboard, Toast.LENGTH_SHORT).show() } private fun onDeleteClick(messageRecord: MessageRecord) { lifecycleDisposable += DeleteDialog.show(requireActivity(), setOf(messageRecord)).subscribe { didDeleteThread -> if (didDeleteThread) { throw AssertionError("We should never end up deleting a Group Thread like this.") } } } private fun onTapForDetailsClick(messageRecord: MessageRecord) { if (messageRecord.isRemoteDelete) { // TODO [cody] Android doesn't support resending remote deletes yet return } if (messageRecord.isIdentityMismatchFailure) { SafetyNumberBottomSheet .forMessageRecord(requireContext(), messageRecord) .show(childFragmentManager) } else if (messageRecord.hasFailedWithNetworkFailures()) { MaterialAlertDialogBuilder(requireContext()) .setMessage(R.string.conversation_activity__message_could_not_be_sent) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(R.string.conversation_activity__send) { _, _ -> SignalExecutors.BOUNDED.execute { MessageSender.resend(requireContext(), messageRecord) } } .show() } } override fun onPageSelected(child: StoryViewsAndRepliesPagerParent.Child) { currentChild = child updateNestedScrolling() } private fun updateNestedScrolling() { recyclerView.isNestedScrollingEnabled = currentChild == StoryViewsAndRepliesPagerParent.Child.REPLIES && !(mentionsViewModel.isShowing.value ?: false) } override fun onSendActionClicked() { val (body, mentions) = composer.consumeInput() performSend(body, mentions) } override fun onPickReactionClicked() { displayInDialogAboveAnchor(composer.reactionButton, R.layout.stories_reaction_bar_layout) { dialog, view -> view.findViewById<StoryReactionBar>(R.id.reaction_bar).apply { callback = object : StoryReactionBar.Callback { override fun onTouchOutsideOfReactionBar() { dialog.dismiss() } override fun onReactionSelected(emoji: String) { dialog.dismiss() sendReaction(emoji) } override fun onOpenReactionPicker() { dialog.dismiss() ReactWithAnyEmojiBottomSheetDialogFragment.createForStory().show(childFragmentManager, null) } } animateIn() } } } override fun onEmojiSelected(emoji: String?) { composer.onEmojiSelected(emoji) } private fun sendReaction(emoji: String) { findListener<Callback>()?.onReactionEmojiSelected(emoji) lifecycleDisposable += StoryGroupReplySender.sendReaction(requireContext(), storyId, emoji) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy( onError = { error -> if (error is UntrustedRecords.UntrustedRecordsException) { resendReaction = emoji SafetyNumberBottomSheet .forIdentityRecordsAndDestination(error.untrustedRecords, ContactSearchKey.RecipientSearchKey.Story(groupRecipientId)) .show(childFragmentManager) } else { Log.w(TAG, "Failed to send reply", error) val context = context if (context != null) { Toast.makeText(context, R.string.message_details_recipient__failed_to_send, Toast.LENGTH_SHORT).show() } } } ) } override fun onKeyEvent(keyEvent: KeyEvent?) = Unit override fun onInitializeEmojiDrawer(mediaKeyboard: MediaKeyboard) { keyboardPagerViewModel.setOnlyPage(KeyboardPage.EMOJI) mediaKeyboard.setFragmentManager(childFragmentManager) } override fun onShowEmojiKeyboard() { requireListener<Callback>().requestFullScreen(true) recyclerView.addOnItemTouchListener(recyclerListener) composer.emojiPageView?.addOnItemTouchListener(recyclerListener) } override fun onHideEmojiKeyboard() { recyclerView.removeOnItemTouchListener(recyclerListener) composer.emojiPageView?.removeOnItemTouchListener(recyclerListener) requireListener<Callback>().requestFullScreen(false) } override fun openEmojiSearch() { composer.openEmojiSearch() } override fun closeEmojiSearch() { composer.closeEmojiSearch() } override fun onReactWithAnyEmojiDialogDismissed() = Unit override fun onReactWithAnyEmojiSelected(emoji: String) { sendReaction(emoji) } private fun initializeComposer(savedInstanceState: Bundle?) { val isActiveGroup = Recipient.observable(groupRecipientId).map { it.isActiveGroup } if (savedInstanceState == null) { lifecycleDisposable += isActiveGroup.firstOrError().observeOn(AndroidSchedulers.mainThread()).subscribe { active -> if (active) { ViewUtil.focusAndShowKeyboard(composer) } } } lifecycleDisposable += isActiveGroup.distinctUntilChanged().observeOn(AndroidSchedulers.mainThread()).forEach { active -> composer.visible = active notInGroup.visible = !active } } private fun initializeMentions() { inlineQueryResultsController = InlineQueryResultsController( requireContext(), inlineQueryViewModel, composer, (requireView() as ViewGroup), composer.input, viewLifecycleOwner ) Recipient.live(groupRecipientId).observe(viewLifecycleOwner) { recipient -> mentionsViewModel.onRecipientChange(recipient) composer.input.setInlineQueryChangedListener(object : InlineQueryChangedListener { override fun onQueryChanged(inlineQuery: InlineQuery) { when (inlineQuery) { is InlineQuery.Mention -> { if (recipient.isPushV2Group) { ensureMentionsContainerFilled() mentionsViewModel.onQueryChange(inlineQuery.query) } inlineQueryViewModel.onQueryChange(inlineQuery) } is InlineQuery.Emoji -> { inlineQueryViewModel.onQueryChange(inlineQuery) mentionsViewModel.onQueryChange(null) } is InlineQuery.NoQuery -> { mentionsViewModel.onQueryChange(null) inlineQueryViewModel.onQueryChange(inlineQuery) } } } override fun clearQuery() { onQueryChanged(InlineQuery.NoQuery) } }) composer.input.setMentionValidator { annotations -> if (!recipient.isPushV2Group) { annotations } else { val validRecipientIds: Set<String> = recipient.participantIds .map { id -> MentionAnnotation.idToMentionAnnotationValue(id) } .toSet() annotations .filter { !validRecipientIds.contains(it.value) } .toList() } } } mentionsViewModel.selectedRecipient.observe(viewLifecycleOwner) { recipient -> composer.input.replaceTextWithMention(recipient.getDisplayName(requireContext()), recipient.id) } lifecycleDisposable += inlineQueryViewModel .selection .observeOn(AndroidSchedulers.mainThread()) .subscribe { r -> composer.input.replaceText(r) } mentionsViewModel.isShowing.observe(viewLifecycleOwner) { updateNestedScrolling() } } private fun ensureMentionsContainerFilled() { val mentionsFragment = childFragmentManager.findFragmentById(R.id.mentions_picker_container) if (mentionsFragment == null) { childFragmentManager .beginTransaction() .replace(R.id.mentions_picker_container, MentionsPickerFragment()) .commitNowAllowingStateLoss() } } private fun performSend(body: CharSequence, mentions: List<Mention>) { lifecycleDisposable += StoryGroupReplySender.sendReply(requireContext(), storyId, body, mentions) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy( onError = { throwable -> if (throwable is UntrustedRecords.UntrustedRecordsException) { resendBody = body resendMentions = mentions SafetyNumberBottomSheet .forIdentityRecordsAndDestination(throwable.untrustedRecords, ContactSearchKey.RecipientSearchKey.Story(groupRecipientId)) .show(childFragmentManager) } else { Log.w(TAG, "Failed to send reply", throwable) val context = context if (context != null) { Toast.makeText(context, R.string.message_details_recipient__failed_to_send, Toast.LENGTH_SHORT).show() } } } ) } override fun sendAnywayAfterSafetyNumberChangedInBottomSheet(destinations: List<ContactSearchKey.RecipientSearchKey>) { val resendBody = resendBody val resendReaction = resendReaction if (resendBody != null) { performSend(resendBody, resendMentions) } else if (resendReaction != null) { sendReaction(resendReaction) } } override fun onMessageResentAfterSafetyNumberChangeInBottomSheet() { Log.i(TAG, "Message resent") } override fun onCanceled() { resendBody = null resendMentions = emptyList() resendReaction = null } @ColorInt private fun Recipient.getStoryGroupReplyColor(): Int { return colorizer.getIncomingGroupSenderColor(requireContext(), this) } private inner class GroupReplyScrollObserver : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { postMarkAsReadRequest() } override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { postMarkAsReadRequest() } } private inner class GroupDataObserver : RecyclerView.AdapterDataObserver() { override fun onItemRangeInserted(positionStart: Int, itemCount: Int) { if (itemCount == 0) { return } val item = adapter.getItem(positionStart) if (positionStart == adapter.itemCount - 1 && item is StoryGroupReplyItem.Model) { val isOutgoing = item.replyBody.sender == Recipient.self() if (isOutgoing || (!isOutgoing && !recyclerView.canScrollVertically(1))) { recyclerView.post { recyclerView.scrollToPosition(positionStart) } } } } } interface Callback { fun onStartDirectReply(recipientId: RecipientId) fun requestFullScreen(fullscreen: Boolean) fun onReactionEmojiSelected(emoji: String) } }
app/src/main/java/org/thoughtcrime/securesms/stories/viewer/reply/group/StoryGroupReplyFragment.kt
3631854919
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.test internal actual fun identityHashCode(instance: Any?): Int = System.identityHashCode(instance)
compose/ui/ui-test/src/jvmMain/kotlin/androidx/compose/ui/test/Expect.jvm.kt
370777191
external interface Faye { fun subscribe(channel: String, callback: () -> Unit) } @JsName("faye") external val faye: Faye = definedExternally
src/main/kotlin/ch/grisu118/userscript/lib/faye.kt
3922446351
/* * Copyright (C) 2021 pedroSG94. * * 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.pedro.rtmp.rtmp.message.shared import com.pedro.rtmp.rtmp.chunk.ChunkStreamId import com.pedro.rtmp.rtmp.chunk.ChunkType import com.pedro.rtmp.rtmp.message.BasicHeader import com.pedro.rtmp.rtmp.message.RtmpMessage import java.io.InputStream /** * Created by pedro on 21/04/21. */ abstract class SharedObject: RtmpMessage(BasicHeader(ChunkType.TYPE_0, ChunkStreamId.PROTOCOL_CONTROL.mark)) { override fun readBody(input: InputStream) { TODO("Not yet implemented") } override fun storeBody(): ByteArray { TODO("Not yet implemented") } override fun getSize(): Int { TODO("Not yet implemented") } }
rtmp/src/main/java/com/pedro/rtmp/rtmp/message/shared/SharedObject.kt
1120510351
package org.catinthedark.example.client import org.catinthedark.client.TCPClient import org.catinthedark.shared.event_bus.BusRegister import org.catinthedark.shared.invokers.DeferrableInvoker import org.catinthedark.shared.invokers.SimpleInvoker import org.catinthedark.shared.serialization.KryoCustomizer val invoker: DeferrableInvoker = SimpleInvoker() class Main { companion object { @JvmStatic fun main(args: Array<String>) { BusRegister.register("org.catinthedark.example.client.handlers") val kryo = KryoCustomizer.buildAndRegister("org.catinthedark.example.shared.messages") val client = TCPClient(kryo, invoker) client.connect("0.0.0.0", 8080) } } }
example-client/src/main/kotlin/org/catinthedark/example/client/Main.kt
2319063496
package me.proxer.app.exception /** * @author Ruben Gees */ class ChatSendMessageException(innerError: Throwable, val id: Long) : ChatException(innerError)
src/main/kotlin/me/proxer/app/exception/ChatSendMessageException.kt
3737571956
package nsync.metadata import java.net.URI internal const val URI_SCHEMA = "nsync" internal fun buildIdentifier(folderId: String, fileId: String? = null): URI { val uri = "$URI_SCHEMA:$folderId" val uri1 = if (fileId != null) "$uri:$fileId" else uri return URI(uri1) } data class FS( val localFolder: URI, val remoteFolder: URI, val identifier: URI? = null) enum class Status { PENDING, TRANSFERRING, SYNCHRONIZED } interface Metadata { fun filesystems(): Sequence<FS> }
src/main/kotlin/nsync/metadata/Metadata.kt
4001343248
package eu.kanade.tachiyomi.extension.en.manwhaclub import eu.kanade.tachiyomi.multisrc.madara.Madara class ManwhaClub : Madara("Manhwa.club", "https://manhwa.club", "en") { override val id = 6951399865568003192 override fun getGenreList() = listOf( Genre("Action", "action"), Genre("Adult", "adult"), Genre("Adventure", "adventure"), Genre("Comedy", "comedy"), Genre("Crime", "crime"), Genre("Drama", "drama"), Genre("Fantasy", "fantasy"), Genre("Gender bender", "gender-bender"), Genre("Gossip", "gossip"), Genre("Harem", "harem"), Genre("Historical", "historical"), Genre("Horror", "horror"), Genre("Incest", "incest"), Genre("Isekai", "isekai"), Genre("Martial arts", "martial-arts"), Genre("Mecha", "mecha"), Genre("Medical", "medical"), Genre("Monster/Tentacle", "monster-tentacle"), Genre("Mystery", "mystery"), Genre("One shot", "one-shot"), Genre("Psychological", "psychological"), Genre("Revenge", "revenge"), Genre("Romance", "romance"), Genre("School Life", "school-life"), Genre("Sci Fi", "sci-fi"), Genre("Seinen", "seinen"), Genre("Shoujo", "shoujo"), Genre("Shounen", "shounen"), Genre("Slice of Life", "slice-of-life"), Genre("Smut", "smut"), Genre("Sports", "sports"), Genre("Supernatural", "supernatural"), Genre("Thriller", "thriller"), Genre("Tragedy", "tragedy"), Genre("Yaoi", "yaoi"), Genre("Yuri", "yuri"), ) }
multisrc/overrides/madara/manwhaclub/src/ManwhaClub.kt
118741374
//package y2k.joyreactor // //import org.robovm.apple.uikit.UITableViewCell //import org.robovm.objc.annotation.CustomClass //import org.robovm.objc.annotation.IBAction //import y2k.joyreactor.presenters.PostListPresenter // ///** // * Created by y2k on 05/10/15. // */ //@CustomClass("LoadMoreCell") //class LoadMoreCell : UITableViewCell() { // // lateinit var presenter: PostListPresenter // // @IBAction // internal fun clicked() { // presenter.loadMore() // } //}
ios/src/main/kotlin/y2k/joyreactor/LoadMoreCell.kt
3840956897
package net.treelzebub.sweepingcircleprogressview import android.content.Context import android.util.AttributeSet import android.view.View /** * Created by Tre Murillo on 12/21/16 * * Port from original Java by Aaron Sarazan (https://github.com/asarazan) */ open class EquilateralView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ): View(context, attrs, defStyle) { protected fun getDimension() = Math.min(width, height) /** * This view insists on a square layout, so it will always take the lesser of the two dimensions. */ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val wMode = View.MeasureSpec.getMode(widthMeasureSpec) var w = View.MeasureSpec.getSize(widthMeasureSpec) val hMode = View.MeasureSpec.getMode(heightMeasureSpec) var h = View.MeasureSpec.getSize(heightMeasureSpec) val dim = Math.min( if (wMode == View.MeasureSpec.UNSPECIFIED) Integer.MAX_VALUE else w, if (hMode == View.MeasureSpec.UNSPECIFIED) Integer.MAX_VALUE else h) w = dim h = dim setMeasuredDimension(w, h) } }
lib/src/main/java/net/treelzebub/sweepingcircleprogressview/EquilateralView.kt
1243753659
package com.habitrpg.android.habitica.models.social import com.google.gson.annotations.SerializedName import com.habitrpg.android.habitica.models.BaseMainObject import com.habitrpg.android.habitica.models.inventory.Quest import com.habitrpg.android.habitica.models.tasks.TaskList import com.habitrpg.shared.habitica.models.tasks.TasksOrder import io.realm.RealmList import io.realm.RealmObject import io.realm.annotations.Ignore import io.realm.annotations.PrimaryKey open class Group : RealmObject(), BaseMainObject { override val realmClass: Class<Group> get() = Group::class.java override val primaryIdentifier: String? get() = id override val primaryIdentifierName: String get() = "id" @SerializedName("_id") @PrimaryKey var id: String = "" var balance: Double = 0.toDouble() var description: String? = null var summary: String? = null var leaderID: String? = null var leaderName: String? = null var name: String? = null var memberCount: Int = 0 var type: String? = null var logo: String? = null var quest: Quest? = null var privacy: String? = null var challengeCount: Int = 0 var leaderMessage: String? = null var leaderOnlyChallenges: Boolean = false var leaderOnlyGetGems: Boolean = false var categories: RealmList<GroupCategory>? = null @Ignore var tasksOrder: TasksOrder? = null override fun equals(other: Any?): Boolean { if (this === other) { return true } val group = other as? Group return id == group?.id } override fun hashCode(): Int { return id.hashCode() } companion object { const val TAVERN_ID = "00000000-0000-4000-A000-000000000000" } val hasActiveQuest: Boolean get() { return quest?.active ?: false } val gemCount: Int get() { return (balance * 4.0).toInt() } }
Habitica/src/main/java/com/habitrpg/android/habitica/models/social/Group.kt
907308666
/* * Copyright (C) 2016, 2018, 2020-2021 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xquery.ast.xquery import com.intellij.openapi.util.TextRange import com.intellij.psi.HintedReferenceHost import com.intellij.psi.PsiLanguageInjectionHost /** * An XQuery 1.0 `DirAttributeValue` node in the XQuery AST. */ interface XQueryDirAttributeValue : PsiLanguageInjectionHost, HintedReferenceHost { val relevantTextRange: TextRange }
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/ast/xquery/XQueryDirAttributeValue.kt
3478319995
package com.habitrpg.shared.habitica.models.responses class Status { var status: String? = null }
shared/src/commonMain/kotlin/com/habitrpg/shared/habitica/models/responses/Status.kt
1146337146
fun main(args : Array<String>) { println(foo()) } fun foo(): Int { try { println("Done") return 0 } finally { println("Finally") } println("After") return 1 }
backend.native/tests/codegen/try/finally5.kt
1223380656
/* * Copyright 2017-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.koin.androidx.workmanager.factory import android.content.Context import androidx.work.ListenableWorker import androidx.work.WorkerFactory import androidx.work.WorkerParameters import org.koin.core.component.KoinComponent import org.koin.core.component.get import org.koin.core.parameter.parametersOf import org.koin.core.qualifier.named /** * Provides an implementation of [WorkerFactory] that ties into Koin DI. * * @author Fabio de Matos * @author Arnaud Giuliani * @author Konstantin Mutasov **/ class KoinWorkerFactory : WorkerFactory(), KoinComponent { override fun createWorker( appContext: Context, workerClassName: String, workerParameters: WorkerParameters, ): ListenableWorker? { return getKoin().getOrNull(qualifier = named(workerClassName)) { parametersOf(workerParameters) } } }
android/koin-androidx-workmanager/src/main/java/org/koin/androidx/workmanager/factory/KoinWorkerFactory.kt
383505304
package i_introduction._8_Smart_Casts import util.TODO import util.doc8 import kotlin.comparisons.reverseOrder interface Expr class Num(val value: Int) : Expr class Sum(val left: Expr, val right: Expr) : Expr fun eval(e: Expr): Int = when (e) { is Num -> e.value is Sum -> eval(e.left) + eval(e.right) else -> throw IllegalArgumentException("Unknown expression") } fun todoTask8(expr: Expr): Nothing = TODO( """ Task 8. Rewrite 'JavaCode8.eval()' in Kotlin using smart casts and 'when' expression. """, documentation = doc8(), references = { JavaCode8().eval(expr) })
src/i_introduction/_8_Smart_Casts/SmartCasts.kt
2538832435
package codecomputer /** * This `Ram` class represents a single unit of RAM, which stores multiple bits of data which are indexed by the `address` input. * The `data` input is written to the internal value addressed by the `address` input when the `write` input changes from * `false` to `true`. The output gives the current value stored at the location indicated by `address`. * * This class replicates the RAM configuration shown on page 1998 of *Code*. * * @see MultiRam */ class Ram(address: List<Readable>, data: Readable, write: Readable) : Readable by (MultiDecoder(address, write) .map { EdgeLatch(it, data) } .let { MultiSelector(address, it) }) /** * A `MultiRam` instance is an array of multiple [Ram] instances, corresponding to the `data` inputs. * * This class represents the RAM array shown on page 201 of *Code* * * @see Ram * @see ControlPanelRam */ class MultiRam(address: List<Readable>, data: List<Readable>, write: Readable) : List<Readable> by (data.map { Ram(address, it, write) }) /** * A `ControlPanelRam` provides extra inputs to [MultiRam] so that the internal state can be adjusted from two different * sources. * * This class represents the RAM/control panel configuration described on page 204 of *Code* * * @see MultiRam */ class ControlPanelRam(address: List<Readable>, data: List<Readable>, write: Readable, takeover: Readable, addressOverride: List<Readable>, dataOverride: List<Readable>, writeOverride: Readable) : List<Readable> by MultiRam( address.indices.map { Selector(takeover, address[it], addressOverride[it]) }, data.indices.map { Selector(takeover, data[it], dataOverride[it]) }, Selector(takeover, write, writeOverride) )
src/main/kotlin/codecomputer/Ram.kt
190729463
package com.rolandvitezhu.todocloud.ui.activity.main.dialogfragment import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.KeyEvent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import android.widget.TextView.OnEditorActionListener import androidx.appcompat.app.AppCompatDialogFragment import androidx.fragment.app.DialogFragment import androidx.lifecycle.ViewModelProvider import com.rolandvitezhu.todocloud.R import com.rolandvitezhu.todocloud.databinding.DialogModifylistBinding import com.rolandvitezhu.todocloud.helper.setSoftInputMode import com.rolandvitezhu.todocloud.ui.activity.main.fragment.MainListFragment import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.ListsViewModel import kotlinx.android.synthetic.main.dialog_modifylist.* import kotlinx.android.synthetic.main.dialog_modifylist.view.* class ModifyListDialogFragment : AppCompatDialogFragment() { private val listsViewModel by lazy { ViewModelProvider(requireActivity()).get(ListsViewModel::class.java) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setStyle(DialogFragment.STYLE_NORMAL, R.style.MyDialogTheme) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val dialogModifylistBinding: DialogModifylistBinding = DialogModifylistBinding.inflate(inflater, container, false) val view: View = dialogModifylistBinding.root dialogModifylistBinding.modifyListDialogFragment = this dialogModifylistBinding.listsViewModel = listsViewModel dialogModifylistBinding.executePendingBindings() requireDialog().setTitle(R.string.modifylist_title) setSoftInputMode() applyTextChangedEvents(view) applyEditorActionEvents(view) return view } private fun applyTextChangedEvents(view: View) { view.textinputedittext_modifylist_title.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {} override fun afterTextChanged(s: Editable) { validateTitle() } }) } private fun applyEditorActionEvents(view: View) { view.textinputedittext_modifylist_title.setOnEditorActionListener( OnEditorActionListener { v, actionId, event -> val pressDone = actionId == EditorInfo.IME_ACTION_DONE var pressEnter = false if (event != null) { val keyCode = event.keyCode pressEnter = keyCode == KeyEvent.KEYCODE_ENTER } if (pressEnter || pressDone) { view.button_modifylist_ok!!.performClick() return@OnEditorActionListener true } false }) } private fun validateTitle(): Boolean { return if (listsViewModel.list.title.isBlank()) { this.textinputlayout_modifylist_title.error = getString(R.string.all_entertitle) false } else { this.textinputlayout_modifylist_title.isErrorEnabled = false true } } fun onButtonOkClick(view: View) { if (validateTitle()) { listsViewModel.onModifyList() (targetFragment as MainListFragment?)?.finishActionMode() dismiss() } } fun onButtonCancelClick(view: View) { dismiss() } }
app/src/main/java/com/rolandvitezhu/todocloud/ui/activity/main/dialogfragment/ModifyListDialogFragment.kt
3657495768
package com.wix.rtk.cli import com.google.gson.GsonBuilder import com.google.gson.annotations.SerializedName import com.google.gson.reflect.TypeToken import com.intellij.execution.ExecutionException import com.wix.nodejs.NodeRunner import com.wix.rtk.cli.RTRunner.TIME_OUT as TIME_OUT object Npm { val REACT_TEMPLATES = "react-templates" val OUTDATED = "outdated" val VIEW = "view" val G = "-g" val JSON = "-json" // npm view react-templates fun view(cwd: String, npm: String): Output { return try { val command = CLI2(cwd, npm).param(VIEW).param(REACT_TEMPLATES).command val output = NodeRunner.execute(command, RTRunner.TIME_OUT) val json = output.stdout parseNpmOutdated(json) } catch (e: ExecutionException) { // RTRunner.LOG.warn("Could not build react-templates file", e) e.printStackTrace() Output() } } //npm ls react-templates -g --depth 0 --json //npm outdated react-templates -g -json fun outdated(cwd: String, npm: String): Outdated { return try { val command = CLI2(cwd, npm).param(OUTDATED).param(REACT_TEMPLATES).param(G).param(JSON).command val output = NodeRunner.execute(command, RTRunner.TIME_OUT) val json = output.stdout Outdated.parseNpmOutdated(json) } catch (e: ExecutionException) { // RTRunner.LOG.warn("Could not build react-templates file", e) e.printStackTrace() Outdated() } } fun parseNpmOutdated(json: String): Output { val builder = GsonBuilder() val g = builder.setPrettyPrinting().create() val listType = object : TypeToken<Output>() {}.type return g.fromJson<Output>(json, listType) } class Output(val name: String = "", @SerializedName("dist-tags") val distTags: Tags = Tags()) class Tags(val latest: String = "") }
src/com/wix/rtk/cli/Npm.kt
2114130272
package com.intellij.workspaceModel.codegen.deft.model import com.intellij.workspaceModel.codegen.deft.TBlob import com.intellij.workspaceModel.codegen.deft.TRef import com.intellij.workspaceModel.codegen.deft.* class DefField( val nameRange: SrcRange, val name: String, val type: KtType?, val expr: Boolean, val getterBody: String?, val constructorParam: Boolean, val suspend: Boolean, val annotations: KtAnnotations, val receiver: KtType? = null, val extensionDelegateModuleName: SrcRange? = null ) { val open: Boolean = annotations.flags.open val content: Boolean = annotations.flags.content val relation: Boolean = annotations.flags.relation val ignored: Boolean = annotations.flags.ignored var id = 0 override fun toString(): String = buildString { if (ignored) append("ignored ") if (content) append("content ") if (open) append("open ") if (relation) append("relation ") if (suspend) append("suspend ") append("def ") if (receiver != null) { append(receiver) append(".") } append("$name: $type") if (expr) append(" = ...") if (extensionDelegateModuleName != null) append(" by <extension in module ${extensionDelegateModuleName.text}>") } fun toMemberField(scope: KtScope, owner: DefType, diagnostics: Diagnostics, keepUnknownFields: Boolean) { if (type == null) { diagnostics.add(nameRange, "only properties with explicit type supported") return } if (receiver != null) { todoMemberExtField(diagnostics) return } val valueType = type.build(scope, diagnostics, annotations, keepUnknownFields) ?: return val field = Field(owner, id, name, valueType) configure(field) } fun todoMemberExtField(diagnostics: Diagnostics) { diagnostics.add(nameRange, "extension properties inside classes is not supported yet") } fun toExtField(scope: KtScope, module: KtObjModule, diagnostics: Diagnostics) { // if (extensionDelegateModuleName?.text != "Obj") return // if (type == null) { diagnostics.add(nameRange, "only properties with explicit type supported") return } if (receiver == null) { diagnostics.add(nameRange, "<ObjModule>.extensions() property should have receiver") return } val resolvedReceiver = receiver.build(scope, diagnostics, keepUnknownFields = module.keepUnknownFields) if (resolvedReceiver !is TRef) { diagnostics.add(receiver.classifierRange, "Only Obj types supported as receivers") return } id = module.extFields.size + 1 // todo: persistent ids val receiverObjType = resolvedReceiver.targetObjType val valueType = type.build(scope, diagnostics, annotations, keepUnknownFields = module.keepUnknownFields) ?: return val field = ExtField(ExtFieldId(id), receiverObjType, name, valueType) module.extFields.add(field) configure(field) } private fun configure(field: MemberOrExtField<*, *>) { field.exDef = this field.open = open if (expr) { field.hasDefault = if (suspend) Field.Default.suspend else Field.Default.plain field.defaultValue = getterBody } field.constructorField = constructorParam field.content = content field.ignored = ignored } companion object : TBlob<DefField>("") }
platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/model/DefField.kt
4131943928
package failchat.emoticon import failchat.Origin import kotlinx.coroutines.channels.ReceiveChannel interface EmoticonStreamLoader<T : Emoticon> { val origin: Origin fun loadEmoticons(): ReceiveChannel<T> }
src/main/kotlin/failchat/emoticon/EmoticonStreamLoader.kt
1886086842
package arcs.core.entity.integration import arcs.core.data.Capability.Ttl import arcs.core.data.CollectionType import arcs.core.data.EntityType import arcs.core.data.HandleMode import arcs.core.data.RawEntity import arcs.core.data.ReferenceType import arcs.core.data.SingletonType import arcs.core.entity.Entity import arcs.core.entity.EntitySpec import arcs.core.entity.ForeignReferenceChecker import arcs.core.entity.ForeignReferenceCheckerImpl import arcs.core.entity.HandleSpec import arcs.core.entity.ReadCollectionHandle import arcs.core.entity.ReadSingletonHandle import arcs.core.entity.ReadWriteCollectionHandle import arcs.core.entity.ReadWriteQueryCollectionHandle import arcs.core.entity.ReadWriteSingletonHandle import arcs.core.entity.ReadableHandle import arcs.core.entity.Reference import arcs.core.entity.WriteCollectionHandle import arcs.core.entity.WriteSingletonHandle import arcs.core.entity.awaitReady import arcs.core.entity.testutil.EmptyEntity import arcs.core.entity.testutil.FixtureEntities import arcs.core.entity.testutil.FixtureEntity import arcs.core.entity.testutil.FixtureEntitySlice import arcs.core.entity.testutil.InnerEntity import arcs.core.entity.testutil.InnerEntitySlice import arcs.core.entity.testutil.MoreNested import arcs.core.entity.testutil.MoreNestedSlice import arcs.core.entity.testutil.TestInlineParticle_Entities import arcs.core.entity.testutil.TestInlineParticle_Entities_InlineEntityField import arcs.core.entity.testutil.TestInlineParticle_Entities_InlineListField import arcs.core.entity.testutil.TestInlineParticle_Entities_InlineListField_MoreInlinesField import arcs.core.entity.testutil.TestInlineParticle_Entities_InlinesField import arcs.core.entity.testutil.TestNumQueryParticle_Entities import arcs.core.entity.testutil.TestParticle_Entities import arcs.core.entity.testutil.TestReferencesParticle_Entities import arcs.core.entity.testutil.TestReferencesParticle_Entities_ReferencesField import arcs.core.entity.testutil.TestTextQueryParticle_Entities import arcs.core.host.HandleManagerImpl import arcs.core.host.SchedulerProvider import arcs.core.host.SimpleSchedulerProvider import arcs.core.storage.StorageEndpointManager import arcs.core.storage.StorageKey import arcs.core.storage.api.DriverAndKeyConfigurator import arcs.core.storage.driver.RamDisk import arcs.core.storage.keys.ForeignStorageKey import arcs.core.storage.keys.RamDiskStorageKey import arcs.core.storage.referencemode.ReferenceModeStorageKey import arcs.core.storage.testutil.testStorageEndpointManager import arcs.core.storage.testutil.waitForEntity import arcs.core.storage.testutil.waitForKey import arcs.core.testutil.handles.dispatchClear import arcs.core.testutil.handles.dispatchCreateReference import arcs.core.testutil.handles.dispatchFetch import arcs.core.testutil.handles.dispatchFetchAll import arcs.core.testutil.handles.dispatchFetchById import arcs.core.testutil.handles.dispatchIsEmpty import arcs.core.testutil.handles.dispatchQuery import arcs.core.testutil.handles.dispatchRemove import arcs.core.testutil.handles.dispatchRemoveByQuery import arcs.core.testutil.handles.dispatchSize import arcs.core.testutil.handles.dispatchStore import arcs.core.util.ArcsStrictMode import arcs.core.util.testutil.LogRule import arcs.flags.testing.BuildFlagsRule import arcs.jvm.util.testutil.FakeTime import com.google.common.truth.Truth.assertThat import java.util.concurrent.Executors import kotlin.test.assertFailsWith import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.joinAll import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout import org.junit.After import org.junit.Ignore import org.junit.Rule import org.junit.Test /** * This is an integration test for handles. Its subclasses are used to test different * configurations. */ @Suppress("EXPERIMENTAL_API_USAGE", "UNCHECKED_CAST") open class HandlesTestBase(val params: Params) { @get:Rule val log = LogRule() @get:Rule val buildFlagsRule = BuildFlagsRule.create() private val fixtureEntities = FixtureEntities() protected open fun createStorageKey( unique: String, hash: String = FixtureEntity.SCHEMA.hash ): StorageKey = RamDiskStorageKey(unique) private fun backingKey( unique: String = "entities", hash: String = FixtureEntity.SCHEMA.hash ) = createStorageKey(unique, hash) private val moreNestedsBackingKey get() = createStorageKey("moreNesteds", MoreNested.SCHEMA.hash) protected lateinit var fakeTime: FakeTime private val entity1 = FixtureEntity( entityId = "entity1", inlineEntityField = fixtureEntities.generateInnerEntity() ) private val entity2 = FixtureEntity( entityId = "entity2", inlineEntityField = fixtureEntities.generateInnerEntity() ) private val singletonRefKey: StorageKey get() = createStorageKey("single-reference") private val singletonKey get() = ReferenceModeStorageKey( backingKey = backingKey(), storageKey = createStorageKey("single-ent") ) private val collectionRefKey get() = createStorageKey("set-references") private val collectionKey get() = ReferenceModeStorageKey( backingKey = backingKey(), storageKey = createStorageKey("set-ent") ) private val moreNestedCollectionRefKey get() = createStorageKey( "set-moreNesteds", MoreNested.SCHEMA.hash ) private val moreNestedCollectionKey get() = ReferenceModeStorageKey( backingKey = moreNestedsBackingKey, storageKey = moreNestedCollectionRefKey ) private val schedulerCoroutineContext = Executors.newSingleThreadExecutor().asCoroutineDispatcher() val schedulerProvider: SchedulerProvider = SimpleSchedulerProvider(schedulerCoroutineContext) private val validPackageName = "m.com.a" private val packageChecker: suspend (String) -> Boolean = { name: String -> name == validPackageName } val foreignReferenceChecker: ForeignReferenceChecker = ForeignReferenceCheckerImpl(mapOf(EmptyEntity.SCHEMA to packageChecker)) lateinit var readHandleManagerImpl: HandleManagerImpl lateinit var writeHandleManagerImpl: HandleManagerImpl private lateinit var monitorHandleManagerImpl: HandleManagerImpl var testTimeout: Long = 10000 private var i = 0 lateinit var monitorStorageEndpointManager: StorageEndpointManager open var testRunner = { block: suspend CoroutineScope.() -> Unit -> monitorHandleManagerImpl = HandleManagerImpl( arcId = "testArc", hostId = "monitorHost", time = fakeTime, scheduler = schedulerProvider("monitor"), storageEndpointManager = monitorStorageEndpointManager, foreignReferenceChecker = foreignReferenceChecker ) runBlocking { withTimeout(testTimeout) { block() } monitorHandleManagerImpl.close() readHandleManagerImpl.close() writeHandleManagerImpl.close() } } // Must call from subclasses. open fun setUp() = runBlocking { // We need to initialize to -1 instead of the default (999999) because our test cases around // deleted items where we look for "nulled-out" entities can result in the // `UNINITIALIZED_TIMESTAMP` being used for creationTimestamp, and others can result in the // current time being used. // TODO: Determine why this is happening. It seems for a nulled-out entity, we shouldn't // use the current time as the creationTimestamp. fakeTime = FakeTime(-1) DriverAndKeyConfigurator.configure(null) RamDisk.clear() } protected open fun initStorageEndpointManager(): StorageEndpointManager { return testStorageEndpointManager() } // This methodΒ needs to be called from setUp methods of [HandlesTestBase] subclasses after other // platform specific initialization has occured. Hence it is factored as a separate method, so // that each subclass could call it at the appropriate time. protected fun initHandleManagers() { i++ val readerStorageEndpointManager = initStorageEndpointManager() monitorStorageEndpointManager = readerStorageEndpointManager readHandleManagerImpl = HandleManagerImpl( arcId = "testArc", hostId = "testHost", time = fakeTime, scheduler = schedulerProvider("reader-#$i"), storageEndpointManager = readerStorageEndpointManager, foreignReferenceChecker = foreignReferenceChecker ) val writerStorageEndpointManager = if (params.isSameStore) { readerStorageEndpointManager } else initStorageEndpointManager() writeHandleManagerImpl = if (params.isSameManager) readHandleManagerImpl else { HandleManagerImpl( arcId = "testArc", hostId = "testHost", time = fakeTime, scheduler = schedulerProvider("writer-#$i"), storageEndpointManager = writerStorageEndpointManager, foreignReferenceChecker = foreignReferenceChecker ) } } @After open fun tearDown() = runBlocking { // TODO(b/151366899): this is less than ideal - we should investigate how to make the entire // test process cancellable/stoppable, even when we cross scopes into a BindingContext or // over to other RamDisk listeners. readHandleManagerImpl.close() writeHandleManagerImpl.close() schedulerProvider.cancelAll() } @Test fun singleton_initialStateAndSingleHandleOperations() = testRunner { val handle = writeHandleManagerImpl.createSingletonHandle() // Don't use the dispatchX helpers so we can test the immediate effect of the handle ops. withContext(handle.dispatcher) { // Initial state. assertThat(handle.fetch()).isNull() // Verify that clear works on an empty singleton. val jobs = mutableListOf<Job>() jobs.add(handle.clear()) assertThat(handle.fetch()).isNull() // All handle ops should be locally immediate (no joins needed). jobs.add(handle.store(entity1)) assertThat(handle.fetch()).isEqualTo(entity1) jobs.add(handle.clear()) assertThat(handle.fetch()).isNull() // The joins should still work. jobs.joinAll() } } @Test fun singleton_writeAndReadBack_unidirectional() = testRunner { // Write-only handle -> read-only handle val writeHandle = writeHandleManagerImpl.createHandle( HandleSpec( "writeOnlySingleton", HandleMode.Write, SingletonType(EntityType(FixtureEntity.SCHEMA)), FixtureEntity ), singletonKey ).awaitReady() as WriteSingletonHandle<FixtureEntitySlice> val readHandle = readHandleManagerImpl.createHandle( HandleSpec( "readOnlySingleton", HandleMode.Read, SingletonType(EntityType(FixtureEntity.SCHEMA)), FixtureEntity ), singletonKey ).awaitReady() as ReadSingletonHandle<FixtureEntity> var received = Job() readHandle.onUpdate { received.complete() } // Verify store against empty. writeHandle.dispatchStore(entity1) received.join() assertThat(readHandle.dispatchFetch()).isEqualTo(entity1) // Verify store overwrites existing. received = Job() writeHandle.dispatchStore(entity2) received.join() assertThat(readHandle.dispatchFetch()).isEqualTo(entity2) // Verify clear. received = Job() writeHandle.dispatchClear() received.join() assertThat(readHandle.dispatchFetch()).isNull() } @Test fun singleton_writeAndReadBack_bidirectional() = testRunner { // Read/write handle <-> read/write handle val handle1 = writeHandleManagerImpl.createHandle( HandleSpec( "readWriteSingleton1", HandleMode.ReadWrite, SingletonType(EntityType(FixtureEntity.SCHEMA)), FixtureEntity ), singletonKey ).awaitReady() as ReadWriteSingletonHandle<FixtureEntity, FixtureEntitySlice> val handle2 = readHandleManagerImpl.createHandle( HandleSpec( "readWriteSingleton2", HandleMode.ReadWrite, SingletonType(EntityType(FixtureEntity.SCHEMA)), FixtureEntity ), singletonKey ).awaitReady() as ReadWriteSingletonHandle<FixtureEntity, FixtureEntitySlice> // handle1 -> handle2 val received1to2 = Job() handle2.onUpdate { received1to2.complete() } // Verify that handle2 sees the entity stored by handle1. handle1.dispatchStore(entity1) received1to2.join() assertThat(handle2.dispatchFetch()).isEqualTo(entity1) // handle2 -> handle1 var received2to1 = Job() handle1.onUpdate { received2to1.complete() } // Verify that handle2 can clear the entity stored by handle1. handle2.dispatchClear() received2to1.join() assertThat(handle1.dispatchFetch()).isNull() // Verify that handle1 sees the entity stored by handle2. received2to1 = Job() handle2.dispatchStore(entity2) received2to1.join() assertThat(handle1.dispatchFetch()).isEqualTo(entity2) } @Test fun singleton_dereferenceEntity() = testRunner { // Arrange: reference handle. val innerEntitiesStorageKey = ReferenceModeStorageKey( backingKey(hash = InnerEntity.SCHEMA.hash), createStorageKey("innerEntities", InnerEntity.SCHEMA.hash) ) val innerEntitiesHandle = writeHandleManagerImpl.createSingletonHandle<InnerEntity, InnerEntitySlice>( storageKey = innerEntitiesStorageKey, entitySpec = InnerEntity ) val innerEntity1 = fixtureEntities.generateInnerEntity() innerEntitiesHandle.dispatchStore(innerEntity1) // Arrange: entity handle. val writeHandle = writeHandleManagerImpl.createSingletonHandle() val readHandle = readHandleManagerImpl.createSingletonHandle() val readHandleUpdated = readHandle.onUpdateDeferred() // Act. writeHandle.dispatchStore( entity1.mutate(referenceField = innerEntitiesHandle.dispatchCreateReference(innerEntity1)) ) readHandleUpdated.join() log("Wrote entity1 to writeHandle") // Assert: read back entity1, and dereference its inner entity. log("Checking entity1's reference field") val dereferencedInnerEntity = readHandle.dispatchFetch()!!.referenceField!!.dereference()!! assertThat(dereferencedInnerEntity).isEqualTo(innerEntity1) } @Test fun singleton_dereferenceEntity_nestedReference() = testRunner { // Create a stylish new entity, and create a reference to it inside an inlined entity. val moreNestedCollection = writeHandleManagerImpl.createHandle( HandleSpec( "moreNestedCollection", HandleMode.ReadWrite, CollectionType(EntityType(MoreNested.SCHEMA)), MoreNested ), moreNestedCollectionKey ) as ReadWriteCollectionHandle<MoreNested, MoreNestedSlice> val nested = fixtureEntities.generateMoreNested() moreNestedCollection.dispatchStore(nested) val nestedRef = moreNestedCollection.dispatchCreateReference(nested) // Give the moreNested to an entity and store it. val entityWithInnerNestedField = FixtureEntity( entityId = "entity-with-inner-nested-ref", inlineEntityField = InnerEntity(moreReferenceField = nestedRef) ) val writeHandle = writeHandleManagerImpl.createSingletonHandle() val readHandle = readHandleManagerImpl.createSingletonHandle() val readOnUpdate = readHandle.onUpdateDeferred() writeHandle.dispatchStore(entityWithInnerNestedField) waitForKey(nestedRef.toReferencable().referencedStorageKey(), MORE_NESTED_ENTITY_TYPE) readOnUpdate.join() // Read out the entity, and fetch its moreNested. val entityOut = readHandle.dispatchFetch()!! val moreNestedRef = entityOut.inlineEntityField.moreReferenceField!! assertThat(moreNestedRef).isEqualTo(nestedRef) val moreNested = moreNestedRef.dereference()!! assertThat(moreNested).isEqualTo(nested) } @Test fun singleton_referenceForeign() = testRunner { val writeHandle = writeHandleManagerImpl.createCollectionHandle(entitySpec = TestParticle_Entities) val reference = writeHandle.createForeignReference(EmptyEntity, validPackageName) assertThat(reference).isNotNull() assertThat(reference!!.toReferencable().storageKey).isEqualTo(ForeignStorageKey("EmptyEntity")) assertThat(reference.dereference()).isNotNull() val entity = TestParticle_Entities(textField = "Hello", foreignField = reference) writeHandle.dispatchStore(entity) val readHandle = readHandleManagerImpl.createCollectionHandle(entitySpec = TestParticle_Entities) assertThat(readHandle.dispatchFetchAll()).containsExactly(entity) val readBack = readHandle.dispatchFetchAll().single().foreignField!! assertThat(readBack.entityId).isEqualTo(validPackageName) assertThat(readBack.dereference()).isNotNull() // Make an invalid reference. assertThat(writeHandle.createForeignReference(EmptyEntity, "invalid")).isNull() } @Test fun singleton_noTTL() = testRunner { val handle = writeHandleManagerImpl.createSingletonHandle() val handleB = readHandleManagerImpl.createSingletonHandle() val handleBUpdated = handleB.onUpdateDeferred() val expectedCreateTime = 123456789L fakeTime.millis = expectedCreateTime handle.dispatchStore(entity1) handleBUpdated.join() val readBack = handleB.dispatchFetch()!! assertThat(readBack.creationTimestamp).isEqualTo(expectedCreateTime) assertThat(readBack.expirationTimestamp).isEqualTo(RawEntity.UNINITIALIZED_TIMESTAMP) } @Test fun singleton_withTTL() = testRunner { fakeTime.millis = 0 val handle = writeHandleManagerImpl.createSingletonHandle(ttl = Ttl.Days(2)) val handleB = readHandleManagerImpl.createSingletonHandle() var handleBUpdated = handleB.onUpdateDeferred() handle.dispatchStore(entity1) handleBUpdated.join() val readBack = handleB.dispatchFetch()!! assertThat(readBack.creationTimestamp).isEqualTo(0) assertThat(readBack.expirationTimestamp).isEqualTo(2 * 24 * 3600 * 1000) val handleC = readHandleManagerImpl.createSingletonHandle(ttl = Ttl.Minutes(2)) handleBUpdated = handleB.onUpdateDeferred() handleC.dispatchStore(entity2) handleBUpdated.join() val readBack2 = handleB.dispatchFetch()!! assertThat(readBack2.creationTimestamp).isEqualTo(0) assertThat(readBack2.expirationTimestamp).isEqualTo(2 * 60 * 1000) // Fast forward time to 5 minutes later, so entity2 expires. fakeTime.millis += 5 * 60 * 1000 assertThat(handleB.dispatchFetch()).isNull() } @Test fun referenceSingleton_withTtl() = testRunner { fakeTime.millis = 0 // Create and store an entity with no TTL. val entityHandle = writeHandleManagerImpl.createSingletonHandle() val refHandle = writeHandleManagerImpl.createReferenceSingletonHandle(ttl = Ttl.Minutes(2)) val updated = entityHandle.onUpdateDeferred() entityHandle.dispatchStore(entity1) updated.join() // Create and store a reference with TTL. val entity1Ref = entityHandle.dispatchCreateReference(entity1) refHandle.dispatchStore(entity1Ref) val readBack = refHandle.dispatchFetch()!! assertThat(readBack.creationTimestamp).isEqualTo(0) assertThat(readBack.expirationTimestamp).isEqualTo(2 * 60 * 1000) // Fast forward time to 5 minutes later, so the reference expires. fakeTime.millis += 5 * 60 * 1000 assertThat(refHandle.dispatchFetch()).isNull() } @Test fun singleton_referenceLiveness() = testRunner { // Create and store an entity. val writeEntityHandle = writeHandleManagerImpl.createCollectionHandle() val monitorHandle = monitorHandleManagerImpl.createCollectionHandle() val initialEntityStored = monitorHandle.onUpdateDeferred { it.size() == 1 } writeEntityHandle.dispatchStore(entity1) initialEntityStored.join() log("Created and stored an entity") // Create and store a reference to the entity. val entity1Ref = writeEntityHandle.dispatchCreateReference(entity1) val writeRefHandle = writeHandleManagerImpl.createReferenceSingletonHandle() val readRefHandle = readHandleManagerImpl.createReferenceSingletonHandle() val refHeard = readRefHandle.onUpdateDeferred() writeRefHandle.dispatchStore(entity1Ref) log("Created and stored a reference") waitForKey(entity1Ref.toReferencable().referencedStorageKey(), FIXTURE_ENTITY_TYPE) refHeard.join() // Now read back the reference from a different handle. var reference = readRefHandle.dispatchFetch()!! assertThat(reference).isEqualTo(entity1Ref) // Reference should be alive. assertThat(reference.dereference()).isEqualTo(entity1) var storageReference = reference.toReferencable() assertThat(storageReference.isAlive()).isTrue() assertThat(storageReference.isDead()).isFalse() // Modify the entity. val modEntity1 = entity1.mutate(textField = "Ben") val entityModified = monitorHandle.onUpdateDeferred { it.fetchAll().all { person -> person.textField == "Ben" } } writeEntityHandle.dispatchStore(modEntity1) assertThat(writeEntityHandle.dispatchSize()).isEqualTo(1) entityModified.join() waitForEntity(writeEntityHandle, modEntity1, FIXTURE_ENTITY_TYPE) // Reference should still be alive. reference = readRefHandle.dispatchFetch()!! val dereferenced = reference.dereference() log("Dereferenced: $dereferenced") assertThat(dereferenced).isEqualTo(modEntity1) storageReference = reference.toReferencable() assertThat(storageReference.isAlive()).isTrue() assertThat(storageReference.isDead()).isFalse() // Remove the entity from the collection. val heardTheDelete = monitorHandle.onUpdateDeferred { it.isEmpty() } writeEntityHandle.dispatchRemove(entity1) heardTheDelete.join() waitForEntity(writeEntityHandle, entity1, FIXTURE_ENTITY_TYPE) // Reference should be dead. (Removed entities currently aren't actually deleted, but // instead are "nulled out".) assertThat(storageReference.dereference()).isEqualTo( fixtureEntities.createNulledOutFixtureEntity("entity1") ) } @Test fun singleton_referenceHandle_referenceModeNotSupported() = testRunner { val e = assertFailsWith<IllegalArgumentException> { writeHandleManagerImpl.createReferenceSingletonHandle( ReferenceModeStorageKey( backingKey = backingKey(), storageKey = singletonRefKey ) ) } assertThat(e).hasMessageThat().isEqualTo( "Reference-mode storage keys are not supported for reference-typed handles." ) } @Test fun collection_initialStateAndSingleHandleOperations() = testRunner { val handle = writeHandleManagerImpl.createCollectionHandle() // Don't use the dispatchX helpers so we can test the immediate effect of the handle ops. withContext(handle.dispatcher) { // Initial state. assertThat(handle.size()).isEqualTo(0) assertThat(handle.isEmpty()).isEqualTo(true) assertThat(handle.fetchAll()).isEmpty() // Verify that both clear and removing a random entity with an empty collection are ok. val jobs = mutableListOf<Job>() jobs.add(handle.clear()) jobs.add(handle.remove(entity1)) // All handle ops should be locally immediate (no joins needed). jobs.add(handle.store(entity1)) jobs.add(handle.store(entity2)) assertThat(handle.size()).isEqualTo(2) assertThat(handle.isEmpty()).isEqualTo(false) assertThat(handle.fetchAll()).containsExactly(entity1, entity2) assertThat(handle.fetchById(entity1.entityId!!)).isEqualTo(entity1) assertThat(handle.fetchById(entity2.entityId!!)).isEqualTo(entity2) jobs.add(handle.remove(entity1)) assertThat(handle.size()).isEqualTo(1) assertThat(handle.isEmpty()).isEqualTo(false) assertThat(handle.fetchAll()).containsExactly(entity2) assertThat(handle.fetchById(entity1.entityId!!)).isNull() assertThat(handle.fetchById(entity2.entityId!!)).isEqualTo(entity2) jobs.add(handle.clear()) assertThat(handle.size()).isEqualTo(0) assertThat(handle.isEmpty()).isEqualTo(true) assertThat(handle.fetchAll()).isEmpty() assertThat(handle.fetchById(entity1.entityId!!)).isNull() assertThat(handle.fetchById(entity2.entityId!!)).isNull() // The joins should still work. jobs.joinAll() } } @Test fun collection_remove_needsId() = testRunner { val handle = writeHandleManagerImpl.createCollectionHandle(entitySpec = TestParticle_Entities) val entity = TestParticle_Entities(textField = "Hello") // Entity does not have an ID, it cannot be removed. assertFailsWith<IllegalStateException> { handle.dispatchRemove(entity) } // Entity with an ID, it can be removed val entity2 = TestParticle_Entities(textField = "Hello", entityId = "id") handle.dispatchRemove(entity2) } @Test fun removeByQuery_oneRemoved() = testRunner { val handle = writeHandleManagerImpl.createCollectionHandle( entitySpec = TestTextQueryParticle_Entities ) val entity = TestTextQueryParticle_Entities(textField = "one") val entity2 = TestTextQueryParticle_Entities(textField = "two") handle.dispatchStore(entity, entity2) handle.dispatchRemoveByQuery("two") assertThat(handle.dispatchFetchAll()).containsExactly(entity) } @Test fun removeByQuery_zeroRemoved() = testRunner { val handle = writeHandleManagerImpl.createCollectionHandle( entitySpec = TestTextQueryParticle_Entities ) val entity = TestTextQueryParticle_Entities(textField = "one") val entity2 = TestTextQueryParticle_Entities(textField = "two") handle.dispatchStore(entity, entity2) handle.dispatchRemoveByQuery("three") assertThat(handle.dispatchFetchAll()).containsExactly(entity, entity2) } @Test fun removeByQuery_emptyCollection() = testRunner { val handle = writeHandleManagerImpl.createCollectionHandle(entitySpec = TestParticle_Entities) handle.dispatchRemoveByQuery("one") assertThat(handle.dispatchFetchAll()).isEmpty() } @Test fun removeByQuery_allRemoved() = testRunner { val handle = writeHandleManagerImpl.createCollectionHandle(entitySpec = TestParticle_Entities) val entity = TestParticle_Entities(textField = "two") val entity2 = TestParticle_Entities(textField = "two") handle.dispatchStore(entity, entity2) handle.dispatchRemoveByQuery("two") assertThat(handle.dispatchFetchAll()).isEmpty() } @Test fun collection_writeAndReadBack_unidirectional() = testRunner { // Write-only handle -> read-only handle val writeHandle = writeHandleManagerImpl.createHandle( HandleSpec( "writeOnlyCollection", HandleMode.Write, CollectionType(EntityType(FixtureEntity.SCHEMA)), FixtureEntity ), collectionKey ).awaitReady() as WriteCollectionHandle<FixtureEntitySlice> val readHandle = readHandleManagerImpl.createHandle( HandleSpec( "readOnlyCollection", HandleMode.Read, CollectionType(EntityType(FixtureEntity.SCHEMA)), FixtureEntity ), collectionKey ).awaitReady() as ReadCollectionHandle<FixtureEntity> val entity3 = fixtureEntities.generate(entityId = "entity3") var received = Job() var size = 3 readHandle.onUpdate { if (readHandle.size() == size) received.complete() } // Verify store. writeHandle.dispatchStore(entity1, entity2, entity3) received.join() assertThat(readHandle.dispatchSize()).isEqualTo(3) assertThat(readHandle.dispatchIsEmpty()).isEqualTo(false) assertThat(readHandle.dispatchFetchAll()).containsExactly(entity1, entity2, entity3) assertThat(readHandle.dispatchFetchById(entity1.entityId!!)).isEqualTo(entity1) assertThat(readHandle.dispatchFetchById(entity2.entityId!!)).isEqualTo(entity2) assertThat(readHandle.dispatchFetchById(entity3.entityId!!)).isEqualTo(entity3) // Verify remove. received = Job() size = 2 writeHandle.dispatchRemove(entity2) received.join() assertThat(readHandle.dispatchSize()).isEqualTo(2) assertThat(readHandle.dispatchIsEmpty()).isEqualTo(false) assertThat(readHandle.dispatchFetchAll()).containsExactly(entity1, entity3) assertThat(readHandle.dispatchFetchById(entity1.entityId!!)).isEqualTo(entity1) assertThat(readHandle.dispatchFetchById(entity2.entityId!!)).isNull() assertThat(readHandle.dispatchFetchById(entity3.entityId!!)).isEqualTo(entity3) // Verify clear. received = Job() size = 0 writeHandle.dispatchClear() received.join() assertThat(readHandle.dispatchSize()).isEqualTo(0) assertThat(readHandle.dispatchIsEmpty()).isEqualTo(true) assertThat(readHandle.dispatchFetchAll()).isEmpty() assertThat(readHandle.dispatchFetchById(entity1.entityId!!)).isNull() assertThat(readHandle.dispatchFetchById(entity2.entityId!!)).isNull() assertThat(readHandle.dispatchFetchById(entity3.entityId!!)).isNull() } @Test fun collection_writeAndReadBack_bidirectional() = testRunner { // Read/write handle <-> read/write handle val handle1 = writeHandleManagerImpl.createHandle( HandleSpec( "readWriteCollection1", HandleMode.ReadWrite, CollectionType(EntityType(FixtureEntity.SCHEMA)), FixtureEntity ), collectionKey ).awaitReady() as ReadWriteCollectionHandle<FixtureEntity, FixtureEntitySlice> val handle2 = readHandleManagerImpl.createHandle( HandleSpec( "readWriteCollection2", HandleMode.ReadWrite, CollectionType(EntityType(FixtureEntity.SCHEMA)), FixtureEntity ), collectionKey ).awaitReady() as ReadWriteCollectionHandle<FixtureEntity, FixtureEntitySlice> val entity3 = fixtureEntities.generate(entityId = "entity3") // handle1 -> handle2 val received1to2 = Job() handle2.onUpdate { if (handle2.size() == 3) received1to2.complete() } // Verify that handle2 sees entities stored by handle1. handle1.dispatchStore(entity1, entity2, entity3) received1to2.join() assertThat(handle2.dispatchSize()).isEqualTo(3) assertThat(handle2.dispatchIsEmpty()).isEqualTo(false) assertThat(handle2.dispatchFetchAll()).containsExactly(entity1, entity2, entity3) assertThat(handle2.dispatchFetchById(entity1.entityId!!)).isEqualTo(entity1) assertThat(handle2.dispatchFetchById(entity2.entityId!!)).isEqualTo(entity2) assertThat(handle2.dispatchFetchById(entity3.entityId!!)).isEqualTo(entity3) // handle2 -> handle1 var received2to1 = Job() var size2to1 = 2 handle1.onUpdate { if (handle1.size() == size2to1) received2to1.complete() } // Verify that handle2 can remove entities stored by handle1. handle2.dispatchRemove(entity2) received2to1.join() assertThat(handle1.dispatchSize()).isEqualTo(2) assertThat(handle1.dispatchIsEmpty()).isEqualTo(false) assertThat(handle1.dispatchFetchAll()).containsExactly(entity1, entity3) assertThat(handle2.dispatchFetchById(entity1.entityId!!)).isEqualTo(entity1) assertThat(handle2.dispatchFetchById(entity2.entityId!!)).isNull() assertThat(handle2.dispatchFetchById(entity3.entityId!!)).isEqualTo(entity3) // Verify that handle1 sees an empty collection after a clear op from handle2. received2to1 = Job() size2to1 = 0 handle2.dispatchClear() received2to1.join() assertThat(handle1.dispatchSize()).isEqualTo(0) assertThat(handle1.dispatchIsEmpty()).isEqualTo(true) assertThat(handle1.dispatchFetchAll()).isEmpty() assertThat(handle2.dispatchFetchById(entity1.entityId!!)).isNull() assertThat(handle2.dispatchFetchById(entity2.entityId!!)).isNull() assertThat(handle2.dispatchFetchById(entity3.entityId!!)).isNull() } @Test fun collection_writeMutatedEntityReplaces() = testRunner { val entity = TestParticle_Entities(textField = "Hello") val handle = writeHandleManagerImpl.createCollectionHandle(entitySpec = TestParticle_Entities) handle.dispatchStore(entity) assertThat(handle.dispatchFetchAll()).containsExactly(entity) val modified = entity.mutate(textField = "Changed") assertThat(modified).isNotEqualTo(entity) // Entity internals should not change. assertThat(modified.entityId).isEqualTo(entity.entityId) assertThat(modified.creationTimestamp).isEqualTo(entity.creationTimestamp) assertThat(modified.expirationTimestamp).isEqualTo(entity.expirationTimestamp) handle.dispatchStore(modified) assertThat(handle.dispatchFetchAll()).containsExactly(modified) assertThat(handle.dispatchFetchById(entity.entityId!!)).isEqualTo(modified) } @Test fun collection_writeMutatedInlineEntitiesReplaces() = testRunner { val inline = TestInlineParticle_Entities_InlineEntityField( longField = 32L, textField = "inlineString" ) val inlineSet = setOf( TestInlineParticle_Entities_InlinesField(numberField = 10.0), TestInlineParticle_Entities_InlinesField(numberField = 20.0), TestInlineParticle_Entities_InlinesField(numberField = 30.0) ) val inlineList = listOf( TestInlineParticle_Entities_InlineListField( moreInlinesField = setOf( TestInlineParticle_Entities_InlineListField_MoreInlinesField( textsField = setOf("so inline") ) ) ), TestInlineParticle_Entities_InlineListField( moreInlinesField = setOf( TestInlineParticle_Entities_InlineListField_MoreInlinesField( textsField = setOf("very inline") ) ) ) ) val entity = TestInlineParticle_Entities(inline, inlineSet, inlineList) val handle = writeHandleManagerImpl.createCollectionHandle( entitySpec = TestInlineParticle_Entities ) handle.dispatchStore(entity) val modified = entity.mutate( inlineEntityField = TestInlineParticle_Entities_InlineEntityField( longField = 33L, textField = "inlineString2" ), inlinesField = setOf( TestInlineParticle_Entities_InlinesField(numberField = 11.0), TestInlineParticle_Entities_InlinesField(numberField = 22.0), TestInlineParticle_Entities_InlinesField(numberField = 33.0) ), inlineListField = listOf( TestInlineParticle_Entities_InlineListField( moreInlinesField = setOf( TestInlineParticle_Entities_InlineListField_MoreInlinesField( textsField = setOf("so inline v2") ) ) ), TestInlineParticle_Entities_InlineListField( moreInlinesField = setOf( TestInlineParticle_Entities_InlineListField_MoreInlinesField( textsField = setOf("very inline v2") ) ) ) ) ) handle.dispatchStore(modified) assertThat(handle.dispatchFetchAll()).containsExactly(modified) } @Test fun listsWorkEndToEnd() = testRunner { val entity = TestParticle_Entities( textField = "Hello", numField = 1.0, longListField = listOf(1L, 2L, 4L, 2L) ) val writeHandle = writeHandleManagerImpl.createCollectionHandle( entitySpec = TestParticle_Entities ) val readHandle = readHandleManagerImpl.createCollectionHandle( entitySpec = TestParticle_Entities ) val updateDeferred = readHandle.onUpdateDeferred { it.size() == 1 } writeHandle.dispatchStore(entity) updateDeferred.join() assertThat(readHandle.dispatchFetchAll()).containsExactly(entity) } @Test fun inlineEntitiesWorkEndToEnd() = testRunner { val inline = TestInlineParticle_Entities_InlineEntityField( longField = 32L, textField = "inlineString" ) val inlineSet = setOf( TestInlineParticle_Entities_InlinesField(numberField = 10.0), TestInlineParticle_Entities_InlinesField(numberField = 20.0), TestInlineParticle_Entities_InlinesField(numberField = 30.0) ) val inlineList = listOf( TestInlineParticle_Entities_InlineListField( moreInlinesField = setOf( TestInlineParticle_Entities_InlineListField_MoreInlinesField( textsField = setOf("so inline") ), TestInlineParticle_Entities_InlineListField_MoreInlinesField(textsField = setOf("like")) ) ), TestInlineParticle_Entities_InlineListField( moreInlinesField = setOf( TestInlineParticle_Entities_InlineListField_MoreInlinesField(textsField = setOf("very")), TestInlineParticle_Entities_InlineListField_MoreInlinesField( textsField = setOf("very inline") ) ) ) ) val entity = TestInlineParticle_Entities(inline, inlineSet, inlineList) val writeHandle = writeHandleManagerImpl.createCollectionHandle( entitySpec = TestInlineParticle_Entities ) val readHandle = readHandleManagerImpl.createCollectionHandle( entitySpec = TestInlineParticle_Entities ) val updateDeferred = readHandle.onUpdateDeferred { it.size() == 1 } writeHandle.dispatchStore(entity) updateDeferred.join() assertThat(readHandle.dispatchFetchAll()).containsExactly(entity) } @Test fun collectionsOfReferencesWorkEndToEnd() = testRunner { fun toReferencedEntity(value: Int) = TestReferencesParticle_Entities_ReferencesField( numberField = value.toDouble() ) val referencedEntitiesKey = ReferenceModeStorageKey( backingKey = createStorageKey("referencedEntities"), storageKey = createStorageKey("set-referencedEntities") ) val referencedEntityHandle = writeHandleManagerImpl.createCollectionHandle( referencedEntitiesKey, entitySpec = TestReferencesParticle_Entities_ReferencesField ) suspend fun toReferences(values: Iterable<Int>) = values .map { toReferencedEntity(it) } .map { referencedEntityHandle.dispatchStore(it) referencedEntityHandle.dispatchCreateReference(it) } suspend fun toEntity(values: Set<Int>, valueList: List<Int>) = TestReferencesParticle_Entities( toReferences(values).toSet(), toReferences(valueList) ) val entities = setOf( toEntity(setOf(1, 2, 3), listOf(3, 3, 4)), toEntity(setOf(200, 100, 300), listOf(2, 10, 2)), toEntity(setOf(34, 2145, 1, 11), listOf(3, 4, 5)) ) val writeHandle = writeHandleManagerImpl.createCollectionHandle( entitySpec = TestReferencesParticle_Entities ) val readHandle = readHandleManagerImpl.createCollectionHandle( entitySpec = TestReferencesParticle_Entities ) val updateDeferred = readHandle.onUpdateDeferred { it.size() == 3 } entities.forEach { writeHandle.dispatchStore(it) } updateDeferred.join() val entitiesOut = readHandle.dispatchFetchAll() assertThat(entitiesOut).containsExactlyElementsIn(entities) entitiesOut.forEach { entity -> entity.referencesField.forEach { it.dereference() } entity.referenceListField.forEach { it.dereference() } } } @Test fun clientCanSetEntityId() = testRunner { fakeTime.millis = 0 // Ask faketime to increment to test with changing timestamps. fakeTime.autoincrement = 1 val id = "MyId" val entity = TestParticle_Entities(textField = "Hello", numField = 1.0, entityId = id) val handle = writeHandleManagerImpl.createCollectionHandle(entitySpec = TestParticle_Entities) handle.dispatchStore(entity) assertThat(handle.dispatchFetchAll()).containsExactly(entity) // A different entity, with the same ID, should replace the first. val entity2 = TestParticle_Entities(textField = "New Hello", numField = 1.1, entityId = id) handle.dispatchStore(entity2) assertThat(handle.dispatchFetchAll()).containsExactly(entity2) // Timestamps also get updated. assertThat(entity2.creationTimestamp).isEqualTo(2) // An entity with a different ID. val entity3 = TestParticle_Entities(textField = "Bye", numField = 2.0, entityId = "OtherId") handle.dispatchStore(entity3) assertThat(handle.dispatchFetchAll()).containsExactly(entity3, entity2) } @Test fun clientCanSetCreationTimestamp() = testRunner { fakeTime.millis = 100 val creationTime = 20L val entity = TestParticle_Entities( textField = "Hello", numField = 1.0, creationTimestamp = creationTime ) val handle = writeHandleManagerImpl.createCollectionHandle(entitySpec = TestParticle_Entities) handle.dispatchStore(entity) assertThat(handle.dispatchFetchAll()).containsExactly(entity) assertThat(entity.creationTimestamp).isEqualTo(20) // A different entity that reuses the same creation timestamp. val entity2 = TestParticle_Entities( textField = "New Hello", numField = 1.1, creationTimestamp = entity.creationTimestamp ) handle.dispatchStore(entity2) assertThat(handle.dispatchFetchAll()).containsExactly(entity, entity2) assertThat(entity2.creationTimestamp).isEqualTo(20) } @Test fun collection_entityDereference() = testRunner { // Arrange: reference handle. val innerEntitiesStorageKey = ReferenceModeStorageKey( backingKey(hash = InnerEntity.SCHEMA.hash), createStorageKey("innerEntities", InnerEntity.SCHEMA.hash) ) val innerEntitiesHandle = writeHandleManagerImpl.createCollectionHandle( storageKey = innerEntitiesStorageKey, entitySpec = InnerEntity ) val innerEntity1 = fixtureEntities.generateInnerEntity() innerEntitiesHandle.dispatchStore(innerEntity1) // Arrange: entity handle. val writeHandle = writeHandleManagerImpl.createCollectionHandle() val readHandle = readHandleManagerImpl.createCollectionHandle() val monitorHandle = monitorHandleManagerImpl.createCollectionHandle() val monitorInitialized = monitorHandle.onUpdateDeferred { it.size() == 1 } val readUpdated = readHandle.onUpdateDeferred { it.size() == 1 } // Act. writeHandle.dispatchStore( entity1.mutate(referenceField = innerEntitiesHandle.dispatchCreateReference(innerEntity1)) ) log("wrote entity1 to writeHandle") monitorInitialized.join() readUpdated.join() log("readHandle and the ramDisk have heard of the update") // Assert: read back entity1, and dereference its inner entity. log("Checking entity1's reference field") val dereferencedInnerEntity = readHandle.dispatchFetchAll().single().referenceField!!.dereference()!! assertThat(dereferencedInnerEntity).isEqualTo(innerEntity1) } @Test fun collection_dereferenceEntity_nestedReference() = testRunner { // Create an entity of type MoreNested, and create a reference to it. val moreNestedSpec = HandleSpec( "moreNestedCollection", HandleMode.ReadWrite, CollectionType(EntityType(MoreNested.SCHEMA)), MoreNested ) val moreNestedCollection = writeHandleManagerImpl.createHandle( moreNestedSpec, moreNestedCollectionKey ).awaitReady() as ReadWriteCollectionHandle<MoreNested, MoreNestedSlice> val moreNestedMonitor = monitorHandleManagerImpl.createHandle( moreNestedSpec, moreNestedCollectionKey ).awaitReady() as ReadWriteCollectionHandle<MoreNested, MoreNestedSlice> val writeHandle = writeHandleManagerImpl.createCollectionHandle() val readHandle = readHandleManagerImpl.createCollectionHandle() val nested = MoreNested(entityId = "nested-id", textsField = setOf("nested")) val moreNestedMonitorKnows = moreNestedMonitor.onUpdateDeferred { it.fetchAll().find { moreNested -> moreNested.entityId == "nested-id" } != null } moreNestedCollection.dispatchStore(nested) val nestedRef = moreNestedCollection.dispatchCreateReference(nested) // Give the moreNested to an entity and store it. val entityWithInnerNestedField = FixtureEntity( entityId = "entity-with-inner-nested-ref", inlineEntityField = InnerEntity(moreReferenceField = nestedRef) ) val readHandleKnows = readHandle.onUpdateDeferred { it.fetchAll().find { person -> person.entityId == "entity-with-inner-nested-ref" } != null } writeHandle.dispatchStore(entityWithInnerNestedField) // Read out the entity, and fetch its moreNested. readHandleKnows.join() val entityOut = readHandle.dispatchFetchAll().single { it.entityId == "entity-with-inner-nested-ref" } val moreNestedRef = entityOut.inlineEntityField.moreReferenceField!! assertThat(moreNestedRef).isEqualTo(nestedRef) moreNestedMonitorKnows.join() val moreNested = moreNestedRef.dereference()!! assertThat(moreNested).isEqualTo(nested) } @Test fun collection_noTTL() = testRunner { val monitor = monitorHandleManagerImpl.createCollectionHandle() val handle = writeHandleManagerImpl.createCollectionHandle() val handleB = readHandleManagerImpl.createCollectionHandle() val handleBChanged = handleB.onUpdateDeferred() val monitorNotified = monitor.onUpdateDeferred() val expectedCreateTime = 123456789L fakeTime.millis = expectedCreateTime handle.dispatchStore(entity1) monitorNotified.join() handleBChanged.join() val readBack = handleB.dispatchFetchAll().first { it.entityId == entity1.entityId } assertThat(readBack.creationTimestamp).isEqualTo(expectedCreateTime) assertThat(readBack.expirationTimestamp).isEqualTo(RawEntity.UNINITIALIZED_TIMESTAMP) } @Test fun collection_withTTL() = testRunner { fakeTime.millis = 0 val handle = writeHandleManagerImpl.createCollectionHandle(ttl = Ttl.Days(2)) val handleB = readHandleManagerImpl.createCollectionHandle() var handleBChanged = handleB.onUpdateDeferred() handle.dispatchStore(entity1) handleBChanged.join() val readBack = handleB.dispatchFetchAll().first { it.entityId == entity1.entityId } assertThat(readBack.creationTimestamp).isEqualTo(0) assertThat(readBack.expirationTimestamp).isEqualTo(2 * 24 * 3600 * 1000) val handleC = readHandleManagerImpl.createCollectionHandle(ttl = Ttl.Minutes(2)) handleBChanged = handleB.onUpdateDeferred() handleC.dispatchStore(entity2) handleBChanged.join() val readBack2 = handleB.dispatchFetchAll().first { it.entityId == entity2.entityId } assertThat(readBack2.creationTimestamp).isEqualTo(0) assertThat(readBack2.expirationTimestamp).isEqualTo(2 * 60 * 1000) // Fast forward time to 5 minutes later, so entity2 expires, entity1 doesn't. fakeTime.millis += 5 * 60 * 1000 assertThat(handleB.dispatchSize()).isEqualTo(1) assertThat(handleB.dispatchFetchAll()).containsExactly(entity1) } @Test fun referenceCollection_withTtl() = testRunner { fakeTime.millis = 0 val entityHandle = writeHandleManagerImpl.createCollectionHandle() val refHandle = writeHandleManagerImpl.createReferenceCollectionHandle(ttl = Ttl.Minutes(2)) // Create and store an entity with no TTL. val updated = entityHandle.onUpdateDeferred() entityHandle.dispatchStore(entity1) updated.join() // Create and store a reference with TTL. val entity1Ref = entityHandle.dispatchCreateReference(entity1) refHandle.dispatchStore(entity1Ref) val readBack = refHandle.dispatchFetchAll().first() assertThat(readBack.creationTimestamp).isEqualTo(0) assertThat(readBack.expirationTimestamp).isEqualTo(2 * 60 * 1000) // Fast forward time to 5 minutes later, so the reference expires. fakeTime.millis += 5 * 60 * 1000 assertThat(refHandle.dispatchFetchAll()).isEmpty() assertThat(refHandle.dispatchSize()).isEqualTo(0) } @Test fun collection_addingToA_showsUpInQueryOnB() = testRunner { val writeHandle = writeHandleManagerImpl.createCollectionHandle( entitySpec = TestTextQueryParticle_Entities ) val readHandle = readHandleManagerImpl.createCollectionHandle( entitySpec = TestTextQueryParticle_Entities ) val entity1 = TestTextQueryParticle_Entities(textField = "21.0") val entity2 = TestTextQueryParticle_Entities(textField = "22.0") val readUpdatedTwice = readHandle.onUpdateDeferred { it.size() == 2 } writeHandle.dispatchStore(entity1, entity2) readUpdatedTwice.join() // Ensure that the query argument is being used. assertThat(readHandle.dispatchQuery("21.0")).containsExactly(entity1) assertThat(readHandle.dispatchQuery("22.0")).containsExactly(entity2) // Ensure that an empty set of results can be returned. assertThat(readHandle.dispatchQuery("60.0")).isEmpty() } @Test fun collection_dataConsideredInvalidByRefinementThrows() = testRunner { val handle = writeHandleManagerImpl.createCollectionHandle( entitySpec = TestNumQueryParticle_Entities ) val entityOne = TestNumQueryParticle_Entities(textField = "one", numField = 1.0) val entityTwo = TestNumQueryParticle_Entities(textField = "two", numField = 2.0) handle.dispatchStore(entityOne, entityTwo) assertThat(handle.dispatchFetchAll()).containsExactly(entityOne, entityTwo) val invalidEntity = TestNumQueryParticle_Entities(textField = "two", numField = -15.0) assertFailsWith<IllegalArgumentException> { handle.dispatchStore(invalidEntity) } } @Test @Ignore("Need to patch ExpressionEvaluator to check types") fun collection_queryWithInvalidQueryThrows() = testRunner { val handle = writeHandleManagerImpl.createCollectionHandle() handle.dispatchStore(entity1, entity2) assertThat(handle.dispatchFetchAll()).containsExactly(entity1, entity2) // Ensure that queries can be performed with the correct query type. (handle as ReadWriteQueryCollectionHandle<FixtureEntity, FixtureEntitySlice, Double>) .dispatchQuery(44.0) // Ensure that queries cannot be performed with an incorrect query type. assertFailsWith<ClassCastException> { (handle as ReadWriteQueryCollectionHandle<FixtureEntity, FixtureEntitySlice, String>) .dispatchQuery("44") } } @Test fun collection_referenceLiveness() = testRunner { // Create and store some entities. val writeEntityHandle = writeHandleManagerImpl.createCollectionHandle() val monitorHandle = monitorHandleManagerImpl.createCollectionHandle() monitorHandle.onUpdate { log("Monitor Handle: $it") } val monitorSawEntities = monitorHandle.onUpdateDeferred { it.size() == 2 } writeEntityHandle.dispatchStore(entity1, entity2) // Wait for the monitor to see the entities (monitor handle is on a separate storage proxy // with a separate stores-cache, so it requires the entities to have made it to the storage // media. monitorSawEntities.join() // Create a store a reference to the entity. val entity1Ref = writeEntityHandle.dispatchCreateReference(entity1) val entity2Ref = writeEntityHandle.dispatchCreateReference(entity2) val writeRefHandle = writeHandleManagerImpl.createReferenceCollectionHandle() val readRefHandle = readHandleManagerImpl.createReferenceCollectionHandle() val refWritesHappened = readRefHandle.onUpdateDeferred { log("References created so far: $it") it.size() == 2 } writeRefHandle.dispatchStore(entity1Ref, entity2Ref) // Now read back the references from a different handle. refWritesHappened.join() var references = readRefHandle.dispatchFetchAll() assertThat(references).containsExactly(entity1Ref, entity2Ref) // References should be alive. // TODO(b/163308113): There's no way to wait for a reference's value to update right now, // so polling is required. var values = emptyList<FixtureEntity?>() while (true) { values = references.map { it.dereference() } if (values.containsAll(listOf(entity1, entity2))) { break } } assertThat(values).containsExactly(entity1, entity2) references.forEach { val storageReference = it.toReferencable() assertThat(storageReference.isAlive()).isTrue() assertThat(storageReference.isDead()).isFalse() } // Modify the entities. val modEntity1 = entity1.mutate(textField = "Ben") val modEntity2 = entity2.mutate(textField = "Ben") val entitiesWritten = monitorHandle.onUpdateDeferred { log("Heard update with $it") it.fetchAll().all { person -> person.textField == "Ben" } } writeEntityHandle.dispatchStore(modEntity1, modEntity2) entitiesWritten.join() waitForEntity(writeEntityHandle, modEntity1, FIXTURE_ENTITY_TYPE) waitForEntity(writeEntityHandle, modEntity2, FIXTURE_ENTITY_TYPE) // Reference should still be alive. // TODO(b/163308113): There's no way to wait for a reference's value to update right now, // so polling is required. references = readRefHandle.dispatchFetchAll() while (true) { values = references.map { it.dereference() } if (values[0]?.textField == "Ben" && values[1]?.textField == "Ben") { break } } assertThat(values).containsExactly(modEntity1, modEntity2) references.forEach { val storageReference = it.toReferencable() assertThat(storageReference.isAlive()).isTrue() assertThat(storageReference.isDead()).isFalse() } log("Removing the entities") // Remove the entities from the collection. val entitiesDeleted = monitorHandle.onUpdateDeferred { it.isEmpty() } writeEntityHandle.dispatchRemove(entity1, entity2) entitiesDeleted.join() waitForEntity(writeEntityHandle, entity1, FIXTURE_ENTITY_TYPE) waitForEntity(writeEntityHandle, entity2, FIXTURE_ENTITY_TYPE) log("Checking that they are empty when de-referencing.") // Reference should be dead. (Removed entities currently aren't actually deleted, but // instead are "nulled out".) assertThat(references.map { it.toReferencable().dereference() }).containsExactly( fixtureEntities.createNulledOutFixtureEntity("entity1"), fixtureEntities.createNulledOutFixtureEntity("entity2") ) } @Test fun collection_referenceHandle_referenceModeNotSupported() = testRunner { val e = assertFailsWith<IllegalArgumentException> { writeHandleManagerImpl.createReferenceCollectionHandle( ReferenceModeStorageKey( backingKey = backingKey(), storageKey = collectionRefKey ) ) } assertThat(e).hasMessageThat().isEqualTo( "Reference-mode storage keys are not supported for reference-typed handles." ) } @Test fun arcsStrictMode_handle_operation_fails() = testRunner { val handle = writeHandleManagerImpl.createCollectionHandle() ArcsStrictMode.enableStrictHandlesForTest { assertFailsWith<IllegalStateException> { handle.clear() } } } private suspend fun <E : I, I : Entity> HandleManagerImpl.createSingletonHandle( storageKey: StorageKey = singletonKey, name: String = "singletonWriteHandle", ttl: Ttl = Ttl.Infinite(), entitySpec: EntitySpec<E> ) = createHandle( HandleSpec( name, HandleMode.ReadWrite, SingletonType(EntityType(entitySpec.SCHEMA)), entitySpec ), storageKey, ttl ).awaitReady() as ReadWriteSingletonHandle<E, I> private suspend fun HandleManagerImpl.createSingletonHandle( storageKey: StorageKey = singletonKey, name: String = "singletonWriteHandle", ttl: Ttl = Ttl.Infinite() ) = createSingletonHandle(storageKey, name, ttl, FixtureEntity) private suspend fun HandleManagerImpl.createCollectionHandle( storageKey: StorageKey = collectionKey, name: String = "collectionReadHandle", ttl: Ttl = Ttl.Infinite() ) = createCollectionHandle(storageKey, name, ttl, FixtureEntity) private suspend fun <E : I, I : Entity> HandleManagerImpl.createCollectionHandle( storageKey: StorageKey = collectionKey, name: String = "collectionReadHandle", ttl: Ttl = Ttl.Infinite(), entitySpec: EntitySpec<E> ) = createHandle( HandleSpec( name, HandleMode.ReadWriteQuery, CollectionType(EntityType(entitySpec.SCHEMA)), entitySpec ), storageKey, ttl ).awaitReady() as ReadWriteQueryCollectionHandle<E, I, Any> private suspend fun HandleManagerImpl.createReferenceSingletonHandle( storageKey: StorageKey = singletonRefKey, name: String = "referenceSingletonWriteHandle", ttl: Ttl = Ttl.Infinite() ) = createHandle( HandleSpec( name, HandleMode.ReadWrite, SingletonType(ReferenceType(EntityType(FixtureEntity.SCHEMA))), FixtureEntity ), storageKey, ttl ).awaitReady() as ReadWriteSingletonHandle<Reference<FixtureEntity>, Reference<FixtureEntity>> private suspend fun HandleManagerImpl.createReferenceCollectionHandle( storageKey: StorageKey = collectionRefKey, name: String = "referenceCollectionReadHandle", ttl: Ttl = Ttl.Infinite() ) = createHandle( HandleSpec( name, HandleMode.ReadWriteQuery, CollectionType(ReferenceType(EntityType(FixtureEntity.SCHEMA))), FixtureEntity ), storageKey, ttl ).awaitReady() as ReadWriteQueryCollectionHandle< Reference<FixtureEntity>, Reference<FixtureEntity>, Any> // Note the predicate receives the *handle*, not onUpdate's delta argument. private fun <H : ReadableHandle<T, U>, T, U> H.onUpdateDeferred( predicate: (H) -> Boolean = { true } ) = Job().also { deferred -> onUpdate { if (deferred.isActive && predicate(this)) { deferred.complete() } } } data class Params( val name: String, val isSameManager: Boolean, val isSameStore: Boolean ) { override fun toString(): String = name } companion object { val SAME_MANAGER = Params( name = "Same Manager", isSameManager = true, isSameStore = true ) val DIFFERENT_MANAGER = Params( name = "Different Manager", isSameManager = false, isSameStore = true ) val DIFFERENT_MANAGER_DIFFERENT_STORES = Params( name = "Different Manager&Different Stores", isSameManager = false, isSameStore = false ) private val FIXTURE_ENTITY_TYPE = EntityType(FixtureEntity.SCHEMA) private val MORE_NESTED_ENTITY_TYPE = EntityType(MoreNested.SCHEMA) } }
javatests/arcs/core/entity/integration/HandlesTestBase.kt
4157408485
/* * 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.crdt import arcs.core.common.Referencable import arcs.core.common.ReferenceId import arcs.core.crdt.CrdtSet.Data as SetData import arcs.core.crdt.CrdtSet.IOperation as ISetOp import arcs.core.crdt.CrdtSet.Operation as SetOp import arcs.core.crdt.CrdtSingleton.Data as SingletonData import arcs.core.crdt.CrdtSingleton.IOperation as ISingletonOp import arcs.core.crdt.CrdtSingleton.Operation as SingletonOp import arcs.core.data.FieldName import arcs.core.data.RawEntity import arcs.core.data.util.ReferencableList import arcs.core.data.util.ReferencablePrimitive import java.lang.UnsupportedOperationException /** * A [CrdtModel] capable of managing a complex entity consisting of named [CrdtSingleton]s and named * [CrdtSet]s, each of which can manage various types of [Referencable] data. * * The only valid ways to build a [CrdtEntity] are: * 1. Build an empty one. [RawEntity] can describe the singleton and collection fields that * exist on an entity without having any of those fields set; by using a [RawEntity] thus * configured and calling [CrdtEntity.newWithEmptyEntity] one can construct an empty * [CrdtEntity]. * 2. From valid [CrdtEntity.Data]. This is currently performed in prod by constructing an empty * [CrdtEntity] of the appropriate shape, and calling [merge] on it with the valid data. * However, note that it's also valid to directly construct a [CrdtEntity] from Data. * * There's also [CrdtEntity.newAtVersionForTest] which takes a [VersionMap] and a [RawEntity]. * Note that this will give all fields in the constructed [CrdtEntity] the same [VersionMap], * which is generally not what we would expect in production. */ class CrdtEntity( private var _data: Data = Data() ) : CrdtModel<CrdtEntity.Data, CrdtEntity.Operation, RawEntity> { override val versionMap: VersionMap get() = _data.versionMap.copy() override val data: Data get() = _data.copy() override val consumerView: RawEntity get() = data.toRawEntity() /** * Builds a [CrdtEntity] from a [RawEntity] with its clock starting at the given [VersionMap]. */ private constructor( versionMap: VersionMap, rawEntity: RawEntity, /** * Function to convert the [Referencable]s within [rawEntity] into [Reference] objects * needed by [CrdtEntity]. */ referenceBuilder: (Referencable) -> Reference = Reference.Companion::defaultReferenceBuilder ) : this(Data(versionMap, rawEntity, referenceBuilder)) override fun merge(other: Data): MergeChanges<Data, Operation> { /* ktlint-disable max-line-length */ val singletonChanges = mutableMapOf<FieldName, MergeChanges<SingletonData<Reference>, ISingletonOp<Reference>>>() /* ktlint-enable max-line-length */ val collectionChanges = mutableMapOf<FieldName, MergeChanges<SetData<Reference>, ISetOp<Reference>>>() var allOps = true _data.singletons.forEach { (fieldName, singleton) -> val otherSingleton = other.singletons[fieldName] if (otherSingleton != null) { singletonChanges[fieldName] = singleton.merge(otherSingleton.data) } if (singletonChanges[fieldName]?.modelChange is CrdtChange.Data || singletonChanges[fieldName]?.otherChange is CrdtChange.Data ) { allOps = false } } _data.collections.forEach { (fieldName, collection) -> val otherCollection = other.collections[fieldName] if (otherCollection != null) { collectionChanges[fieldName] = collection.merge(otherCollection.data) } if (collectionChanges[fieldName]?.modelChange is CrdtChange.Data || collectionChanges[fieldName]?.otherChange is CrdtChange.Data ) { allOps = false } } if (_data.creationTimestamp != other.creationTimestamp) { allOps = false if (_data.creationTimestamp == RawEntity.UNINITIALIZED_TIMESTAMP) { _data.creationTimestamp = other.creationTimestamp } else if (other.creationTimestamp != RawEntity.UNINITIALIZED_TIMESTAMP) { // Two different values, take minimum. _data.creationTimestamp = minOf(_data.creationTimestamp, other.creationTimestamp) } } if (_data.expirationTimestamp != other.expirationTimestamp) { allOps = false if (_data.expirationTimestamp == RawEntity.UNINITIALIZED_TIMESTAMP) { _data.expirationTimestamp = other.expirationTimestamp } else if (other.expirationTimestamp != RawEntity.UNINITIALIZED_TIMESTAMP) { // Two different values, take minimum. _data.expirationTimestamp = minOf(_data.expirationTimestamp, other.expirationTimestamp) } } if (_data.id != other.id) { allOps = false if (_data.id == RawEntity.NO_REFERENCE_ID) { _data.id = other.id } else if (other.id != RawEntity.NO_REFERENCE_ID) { // Two different ids, this cannot be as this crdts are keyed by id in the backing store. throw CrdtException("Found two different values for id, this should be impossible.") } } val oldVersionMap = _data.versionMap.copy() _data.versionMap = _data.versionMap mergeWith other.versionMap if (oldVersionMap == other.versionMap) { @Suppress("RemoveExplicitTypeArguments") return MergeChanges( CrdtChange.Operations(mutableListOf<Operation>()), CrdtChange.Operations(mutableListOf<Operation>()) ) } return if (allOps) { val modelOps = mutableListOf<Operation>() val otherOps = mutableListOf<Operation>() // Convert all of our CrdtSingleton.Operations and CrdtSet.Operations into // CrdtEntity.Operations. singletonChanges.forEach { (fieldName, mergeChanges) -> modelOps += when (val changes = mergeChanges.modelChange) { is CrdtChange.Operations -> changes.ops.map { it.toEntityOp(fieldName) } // This shouldn't happen, but strong typing forces us to check. else -> throw CrdtException("Found a Data change when Operations expected") } otherOps += when (val changes = mergeChanges.otherChange) { is CrdtChange.Operations -> changes.ops.map { it.toEntityOp(fieldName) } // This shouldn't happen, but strong typing forces us to check. else -> throw CrdtException("Found a Data change when Operations expected") } } collectionChanges.forEach { (fieldName, mergeChanges) -> modelOps += when (val changes = mergeChanges.modelChange) { is CrdtChange.Operations -> changes.ops.map { it.toEntityOp(fieldName) } // This shouldn't happen, but strong typing forces us to check. else -> throw CrdtException("Found a Data change when Operations expected") } otherOps += when (val changes = mergeChanges.otherChange) { is CrdtChange.Operations -> changes.ops.map { it.toEntityOp(fieldName) } // This shouldn't happen, but strong typing forces us to check. else -> throw CrdtException("Found a Data change when Operations expected") } } MergeChanges( modelChange = CrdtChange.Operations(modelOps), otherChange = CrdtChange.Operations(otherOps) ) } else { val resultData = data // call `data` only once, since it's nontrivial to copy. // Check if there are no other changes. val otherChangesEmpty = singletonChanges.values.all { it.otherChange.isEmpty() } && collectionChanges.values.all { it.otherChange.isEmpty() } val otherChange: CrdtChange<Data, Operation> = if (otherChangesEmpty) { CrdtChange.Operations(mutableListOf()) } else { CrdtChange.Data(resultData) } if (oldVersionMap == _data.versionMap) { return MergeChanges( modelChange = CrdtChange.Operations(mutableListOf<Operation>()), otherChange = otherChange ) } MergeChanges( modelChange = CrdtChange.Data(resultData), otherChange = otherChange ) } } override fun applyOperation(op: Operation): Boolean { return when (op) { is Operation.SetSingleton -> _data.singletons[op.field]?.applyOperation(op.toSingletonOp()) is Operation.ClearSingleton -> _data.singletons[op.field]?.applyOperation(op.toSingletonOp()) is Operation.AddToSet -> _data.collections[op.field]?.applyOperation(op.toSetOp()) is Operation.RemoveFromSet -> _data.collections[op.field]?.applyOperation(op.toSetOp()) is Operation.ClearAll -> { _data.singletons.values.forEach { it.applyOperation(CrdtSingleton.Operation.Clear(op.actor, versionMap)) } _data.collections.values.forEach { it.applyOperation(CrdtSet.Operation.Clear(op.actor, versionMap)) } _data.creationTimestamp = RawEntity.UNINITIALIZED_TIMESTAMP _data.expirationTimestamp = RawEntity.UNINITIALIZED_TIMESTAMP return true } }?.also { success -> if (success) { _data.versionMap = _data.versionMap mergeWith op.versionMap } } ?: throw CrdtException("Invalid op: $op.") } /** Defines the type of data managed by [CrdtEntity] for its singletons and collections. */ interface Reference : Referencable { companion object { /** Simple converter from [Referencable] to [Reference]. */ fun buildReference(referencable: Referencable): Reference = ReferenceImpl(referencable.id) fun wrapReferencable(referencable: Referencable): Reference = WrappedReferencable(referencable) fun defaultReferenceBuilder(referencable: Referencable): Reference { return when (referencable) { is ReferencableList<*> -> wrapReferencable(referencable) is ReferencablePrimitive<*> -> buildReference(referencable) is RawEntity -> wrapReferencable(referencable) else -> { throw UnsupportedOperationException( "Can't use entities with ${referencable::class} fields without " + "installing a reference builder that can handle them" ) } } } } } data class WrappedReferencable(val referencable: Referencable) : Reference { override fun unwrap(): Referencable = referencable override val id: String get() = referencable.id } /** Minimal [Reference] for contents of a singletons/collections in [Data]. */ data class ReferenceImpl(override val id: ReferenceId) : Reference { override fun unwrap(): Referencable = ReferencablePrimitive.unwrap(id) ?: this override fun toString(): String = when (val deref = unwrap()) { this -> "Reference($id)" else -> "Reference($deref)" } } /** Data contained within a [CrdtEntity]. */ data class Data( /** Master version of the entity. */ override var versionMap: VersionMap = VersionMap(), /** Singleton fields. */ val singletons: Map<FieldName, CrdtSingleton<Reference>> = emptyMap(), /** Collection fields. */ val collections: Map<FieldName, CrdtSet<Reference>> = emptyMap(), var creationTimestamp: Long = RawEntity.UNINITIALIZED_TIMESTAMP, var expirationTimestamp: Long = RawEntity.UNINITIALIZED_TIMESTAMP, var id: ReferenceId = RawEntity.NO_REFERENCE_ID ) : CrdtData { /** Builds a [CrdtEntity.Data] object from an initial version and a [RawEntity]. */ constructor( versionMap: VersionMap, rawEntity: RawEntity, referenceBuilder: (Referencable) -> Reference ) : this( versionMap, rawEntity.buildCrdtSingletonMap({ versionMap }, referenceBuilder), rawEntity.buildCrdtSetMap({ versionMap }, referenceBuilder), rawEntity.creationTimestamp, rawEntity.expirationTimestamp, rawEntity.id ) constructor( rawEntity: RawEntity, entityVersion: VersionMap, versionProvider: (FieldName) -> VersionMap, referenceBuilder: (Referencable) -> Reference ) : this( entityVersion, rawEntity.buildCrdtSingletonMap(versionProvider, referenceBuilder), rawEntity.buildCrdtSetMap(versionProvider, referenceBuilder), rawEntity.creationTimestamp, rawEntity.expirationTimestamp, rawEntity.id ) fun toRawEntity() = RawEntity( id, singletons.mapValues { it.value.consumerView?.unwrap() }, collections.mapValues { it.value.consumerView.map { item -> item.unwrap() }.toSet() }, creationTimestamp, expirationTimestamp ) fun toRawEntity(refId: ReferenceId) = RawEntity( refId, singletons.mapValues { it.value.consumerView?.unwrap() }, collections.mapValues { it.value.consumerView.map { item -> item.unwrap() }.toSet() }, creationTimestamp, expirationTimestamp ) /** Makes a deep copy of this [CrdtEntity.Data] object. */ // We can't rely on the Data Class's .copy(param=val,..) because it doesn't deep-copy the // inners, unfortunately. /* internal */ fun copy(): Data = Data( versionMap.copy(), HashMap(singletons.mapValues { it.value.copy() }), HashMap(collections.mapValues { it.value.copy() }), creationTimestamp, expirationTimestamp, id ) companion object { private fun RawEntity.buildCrdtSingletonMap( versionProvider: (FieldName) -> VersionMap, referenceBuilder: (Referencable) -> Reference ): Map<FieldName, CrdtSingleton<Reference>> = singletons.mapValues { entry -> CrdtSingleton( versionProvider(entry.key).copy(), entry.value?.let { referenceBuilder(it) } ) } @Suppress("UNCHECKED_CAST") private fun RawEntity.buildCrdtSetMap( versionProvider: (FieldName) -> VersionMap, referenceBuilder: (Referencable) -> Reference ): Map<FieldName, CrdtSet<Reference>> = collections.mapValues { entry -> val version = versionProvider(entry.key).copy() CrdtSet( CrdtSet.DataImpl( version, entry.value.map { CrdtSet.DataValue(version.copy(), referenceBuilder(it)) } .associateBy { it.value.id } .toMutableMap() ) ) } } } /** Valid [CrdtOperation]s for [CrdtEntity]. */ sealed class Operation( open val actor: Actor, override val versionMap: VersionMap ) : CrdtOperation { /** * Represents an [actor] having set the value of a member [CrdtSingleton] [field] to the * specified [value] at the time denoted by [versionMap]. */ data class SetSingleton( override val actor: Actor, override val versionMap: VersionMap, val field: FieldName, val value: Reference ) : Operation(actor, versionMap) { /** * Converts the [CrdtEntity.Operation] into its corresponding [CrdtSingleton.Operation]. */ fun toSingletonOp(): SingletonOp.Update<Reference> = CrdtSingleton.Operation.Update(actor, versionMap, value) } /** * Represents an [actor] having cleared the value from a member [CrdtSingleton] [field] to * at the time denoted by [versionMap]. */ data class ClearSingleton( override val actor: Actor, override val versionMap: VersionMap, val field: FieldName ) : Operation(actor, versionMap) { /** * Converts the [CrdtEntity.Operation] into its corresponding [CrdtSingleton.Operation]. */ fun toSingletonOp(): SingletonOp.Clear<Reference> = CrdtSingleton.Operation.Clear(actor, versionMap) } /** * Represents an [actor] having added a [Reference] to a member [CrdtSet] [field] at the * time denoted by [versionMap]. */ data class AddToSet( override val actor: Actor, override val versionMap: VersionMap, val field: FieldName, val added: Reference ) : Operation(actor, versionMap) { /** * Converts the [CrdtEntity.Operation] into its corresponding [CrdtSet.Operation]. */ fun toSetOp(): SetOp.Add<Reference> = CrdtSet.Operation.Add(actor, versionMap, added) } /** * Represents an [actor] having removed the a value from a member [CrdtSet] [field] at the * time denoted by [versionMap]. */ data class RemoveFromSet( override val actor: Actor, override val versionMap: VersionMap, val field: FieldName, val removed: ReferenceId ) : Operation(actor, versionMap) { /** * Converts the [CrdtEntity.Operation] into its corresponding [CrdtSet.Operation]. */ fun toSetOp(): SetOp.Remove<Reference> = CrdtSet.Operation.Remove(actor, versionMap, removed) } data class ClearAll( override val actor: Actor, override val versionMap: VersionMap ) : Operation(actor, versionMap) } companion object { /** * Builds a [CrdtEntity] from a [RawEntity] with its clock starting at the given [VersionMap]. * * This is probably not what you want to do in production; all fields end up being given * the version provided by the [VersionMap]. */ fun newAtVersionForTest(versionMap: VersionMap, rawEntity: RawEntity): CrdtEntity { return CrdtEntity(versionMap, rawEntity) } /** * Builds a [CrdtEntity] with no version map information. This is only intended to be used * with [RawEntity]s that have no field values set! */ fun newWithEmptyEntity(rawEntity: RawEntity): CrdtEntity { return CrdtEntity(VersionMap(), rawEntity) } } } /** Converts the [RawEntity] into a [CrdtEntity.Data] model, at the given version. */ fun RawEntity.toCrdtEntityData( versionMap: VersionMap, referenceBuilder: (Referencable) -> CrdtEntity.Reference = { CrdtEntity.ReferenceImpl(it.id) } ): CrdtEntity.Data = CrdtEntity.Data(versionMap.copy(), this, referenceBuilder) /** Visible for testing. */ fun ISingletonOp<CrdtEntity.Reference>.toEntityOp( fieldName: FieldName ): CrdtEntity.Operation = when (this) { is SingletonOp.Update -> CrdtEntity.Operation.SetSingleton(actor, versionMap, fieldName, value) is SingletonOp.Clear -> CrdtEntity.Operation.ClearSingleton(actor, versionMap, fieldName) else -> throw CrdtException("Invalid operation") } /** Visible for testing. */ fun ISetOp<CrdtEntity.Reference>.toEntityOp( fieldName: FieldName ): CrdtEntity.Operation = when (this) { is SetOp.Add -> CrdtEntity.Operation.AddToSet(actor, versionMap, fieldName, added) is SetOp.Remove -> CrdtEntity.Operation.RemoveFromSet(actor, versionMap, fieldName, removed) else -> throw CrdtException("Cannot convert FastForward or Clear to CrdtEntity Operation") }
java/arcs/core/crdt/CrdtEntity.kt
1819162403
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.action.change.insert import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.MutableVimEditor import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimVisualPosition import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.lineLength import com.maddyhome.idea.vim.api.visualLineToBufferLine import com.maddyhome.idea.vim.command.Argument import com.maddyhome.idea.vim.command.Command import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.handler.ChangeEditorActionHandler class InsertCharacterAboveCursorAction : ChangeEditorActionHandler.ForEachCaret() { override val type: Command.Type = Command.Type.INSERT override fun execute( editor: VimEditor, caret: VimCaret, context: ExecutionContext, argument: Argument?, operatorArguments: OperatorArguments, ): Boolean { return if (editor.isOneLineMode()) { false } else insertCharacterAroundCursor(editor, caret, -1) } } class InsertCharacterBelowCursorAction : ChangeEditorActionHandler.ForEachCaret() { override val type: Command.Type = Command.Type.INSERT override fun execute( editor: VimEditor, caret: VimCaret, context: ExecutionContext, argument: Argument?, operatorArguments: OperatorArguments, ): Boolean { return if (editor.isOneLineMode()) { false } else insertCharacterAroundCursor(editor, caret, 1) } } /** * Inserts the character above/below the cursor at the cursor location * * @param editor The editor to insert into * @param caret The caret to insert after * @param dir 1 for getting from line below cursor, -1 for getting from line above cursor * @return true if able to get the character and insert it, false if not */ private fun insertCharacterAroundCursor(editor: VimEditor, caret: VimCaret, dir: Int): Boolean { var res = false var vp = caret.getVisualPosition() vp = VimVisualPosition(vp.line + dir, vp.column, false) val len = editor.lineLength(editor.visualLineToBufferLine(vp.line)) if (vp.column < len) { val offset = editor.visualPositionToOffset(VimVisualPosition(vp.line, vp.column, false)).point val charsSequence = editor.text() if (offset < charsSequence.length) { val ch = charsSequence[offset] (editor as MutableVimEditor).insertText(caret.offset, ch.toString()) caret.moveToOffset(injector.motion.getOffsetOfHorizontalMotion(editor, caret, 1, true)) res = true } } return res }
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/change/insert/InsertCharacterAroundCursorAction.kt
1003223290
package org.hexworks.zircon.api.component import org.hexworks.zircon.api.behavior.Selectable import org.hexworks.zircon.api.behavior.TextOverride import org.hexworks.zircon.internal.component.impl.DefaultCheckBox.CheckBoxAlignment import org.hexworks.zircon.internal.component.impl.DefaultCheckBox.CheckBoxState /** * A [CheckBox] is a [Selectable] that represents its [Selectable.isSelected] * state with a check box. */ interface CheckBox : Component, Selectable, TextOverride { /** * Contains the current state of the [CheckBox] * @see CheckBoxState */ val checkBoxState: CheckBoxState /** * Contains the [CheckBoxAlignment]. * @see CheckBoxAlignment */ val labelAlignment: CheckBoxAlignment }
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/component/CheckBox.kt
1254170794
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.integration import org.gradle.integtests.fixtures.ToBeFixedForConfigurationCache import org.gradle.kotlin.dsl.fixtures.AbstractKotlinIntegrationTest import org.gradle.kotlin.dsl.fixtures.containsMultiLineString import org.gradle.kotlin.dsl.fixtures.normalisedPath import org.hamcrest.CoreMatchers.containsString import org.hamcrest.MatcherAssert.assertThat import org.junit.Test class DependencyManagementIntegrationTest : AbstractKotlinIntegrationTest() { @Test @ToBeFixedForConfigurationCache(because = ":dependencies") fun `declare dependency constraints`() { withFile("repo/in-block/accessor-1.0.jar") withFile("repo/in-block/accessor-with-action-1.0.jar") withFile("repo/in-block/string-invoke-1.0.jar") withFile("repo/in-block/string-invoke-with-action-1.0.jar") withFile("repo/direct/accessor-1.0.jar") withFile("repo/direct/accessor-with-action-1.0.jar") withFile("repo/direct-block/string-invoke-1.0.jar") withFile("repo/direct-block/string-invoke-with-action-1.0.jar") withBuildScript( """ plugins { `java-library` } // Declare some dependencies dependencies { api("in-block:accessor") api("in-block:accessor-with-action") api("in-block:string-invoke") api("in-block:string-invoke-with-action") api("direct:accessor") api("direct:accessor-with-action") api("direct-block:string-invoke") api("direct-block:string-invoke-with-action") } // Declare dependency constraints dependencies { constraints { api("in-block:accessor:1.0") api("in-block:accessor-with-action") { version { strictly("1.0") } } } (constraints) { "api"("in-block:string-invoke:1.0") "api"("in-block:string-invoke-with-action") { version { strictly("1.0") } } } } dependencies.constraints.api("direct:accessor:1.0") dependencies.constraints.api("direct:accessor-with-action") { version { strictly("1.0") } } (dependencies.constraints) { "api"("direct-block:string-invoke:1.0") "api"("direct-block:string-invoke-with-action") { version { strictly("1.0") } } } repositories { ivy { url = uri("${existing("repo").normalisedPath}") patternLayout { artifact("[organisation]/[module]-[revision].[ext]") } } } """ ) build("dependencies", "--configuration", "api").apply { assertThat( output, containsMultiLineString( """ api - API dependencies for source set 'main'. (n) +--- in-block:accessor (n) +--- in-block:accessor-with-action (n) +--- in-block:string-invoke (n) +--- in-block:string-invoke-with-action (n) +--- direct:accessor (n) +--- direct:accessor-with-action (n) +--- direct-block:string-invoke (n) \--- direct-block:string-invoke-with-action (n) """ ) ) } listOf( "in-block:accessor", "in-block:accessor-with-action", "in-block:string-invoke", "in-block:string-invoke-with-action", "direct:accessor", "direct:accessor-with-action", "direct-block:string-invoke", "direct-block:string-invoke-with-action" ).forEach { dep -> build("dependencyInsight", "--configuration", "compileClasspath", "--dependency", dep).apply { assertThat(output, containsString("$dep:1.0 (by constraint)")) } } } }
subprojects/kotlin-dsl-integ-tests/src/integTest/kotlin/org/gradle/kotlin/dsl/integration/DependencyManagementIntegrationTest.kt
4264528876
package kebab.core import js.JavascriptInterface import kebab.navigator.Navigable import kebab.support.alert.AlertAndConfirmSupport import kebab.support.alert.DefaultAlertAndConfirmSupport import kebab.support.alert.UninitializedAlertAndConfirmSupport import kebab.support.download.DefaultDownloadSupport import kebab.support.download.DownloadSupport import kebab.support.download.UninitializedDownloadSupport import kebab.support.frame.DefaultFrameSupport import kebab.support.frame.FrameSupport import kebab.support.frame.UninitializedFrameSupport import kebab.support.interaction.DefaultInteractionsSupport import kebab.support.interaction.InteractionsSupport import kebab.support.interaction.UninitializedInteractionSupport import kebab.support.navigate.NavigableSupport import kebab.support.navigate.Navigatable import kebab.support.navigate.UninitializedNavigableSupport import kebab.support.page.DefaultPageContentSupport import kebab.support.page.PageContentSupport import kebab.support.page.UninitializedPageContentSupport import kebab.support.waiting.DefaultWaitingSupport import kebab.support.waiting.UninitializedWaitingSupport import kebab.support.waiting.WaitingSupport import org.openqa.selenium.By import support.text.TextMatchingSupport /** * Created by yy_yank on 2015/12/19. */ class Page : Navigatable, PageContentContainer, Initializable, WaitingSupport { var at = null var url = "" var atCheckWaiting = null private var browser: Browser? = null var title: String? = null get () { return this.browser?.config?.driver?.title } // @Delegate var pageContentSupport: PageContentSupport? = UninitializedPageContentSupport(this) // @Delegate var downloadSupport: DownloadSupport? = UninitializedDownloadSupport(this) var waitingSupport: WaitingSupport = UninitializedWaitingSupport(this) var textMatchingSupport: TextMatchingSupport = TextMatchingSupport() var alertAndConfirmSupport: AlertAndConfirmSupport = UninitializedAlertAndConfirmSupport(this) var navigableSupport: Navigable = UninitializedNavigableSupport(this) // @Delegate var frameSupport: FrameSupport = UninitializedFrameSupport(this) // @Delegate var interactionsSupport: InteractionsSupport = UninitializedInteractionSupport(this) /** * Initialises this page instance, connecting it to the browser. * <p> * <b>This method is called internally, and should not be called by users of Kebab.</b> */ fun init(browser: Browser): Page { this.browser = browser title = browser.config.driver.title val contentTemplates = PageContentTemplateBuilder.build(browser, DefaultPageContentContainer(), browser.navigatorFactory, "content", this.javaClass) pageContentSupport = DefaultPageContentSupport(this, contentTemplates, browser.navigatorFactory) navigableSupport = NavigableSupport(browser.navigatorFactory!!) downloadSupport = DefaultDownloadSupport(browser) waitingSupport = DefaultWaitingSupport(browser.config) frameSupport = DefaultFrameSupport(browser) interactionsSupport = DefaultInteractionsSupport(browser) alertAndConfirmSupport = DefaultAlertAndConfirmSupport({ this.getJs() }, browser.config) return this } fun find() = navigableSupport.find() fun find(index: Int) = navigableSupport.find(index) fun find(range: ClosedRange<Int>) = navigableSupport.find(range) fun find(selector: String) = navigableSupport.find(selector) fun find(selector: String, index: Int) = navigableSupport.find(selector, index) fun find(selector: String, range: ClosedRange<Int>) = navigableSupport.find(selector, range) fun find(attributes: MutableMap<String, Any>) = navigableSupport.find(attributes) fun find(attributes: MutableMap<String, Any>, index: Int) = navigableSupport.find(attributes, index) fun find(attributes: MutableMap<String, Any>, range: ClosedRange<Int>) = navigableSupport.find(attributes, range) fun find(attributes: MutableMap<String, Any>, selector: String) = navigableSupport.find(attributes, selector) fun find(attributes: MutableMap<String, Any>, selector: String, index: Int) = navigableSupport.find(attributes, selector, index) fun find(attributes: MutableMap<String, Any>, selector: String, range: ClosedRange<Int>) = navigableSupport.find(attributes, selector, range) fun find(attributes: MutableMap<String, Any>, bySelector: By) = navigableSupport.find(attributes, bySelector) fun find(attributes: MutableMap<String, Any>, bySelector: By, index: Int) = navigableSupport.find(attributes, bySelector, index) fun find(attributes: MutableMap<String, Any>, bySelector: By, range: ClosedRange<Int>) = navigableSupport.find(attributes, bySelector, range) fun find(bySelector: By) = navigableSupport.find(bySelector) fun find(bySelector: By, index: Int) = navigableSupport.find(bySelector, index) fun find(bySelector: By, range: ClosedRange<Int>) = navigableSupport.find(bySelector, range) override fun <T> waitFor(waitPreset: String, f: () -> T): T { throw UnsupportedOperationException() } override fun <T> waitFor(params: Map<String, Any>, waitPreset: String, f: () -> T): T { throw UnsupportedOperationException() } override fun <T> waitFor(f: () -> T): T = waitingSupport.waitFor(f) override fun <T> waitFor(params: Map<String, Any>, f: () -> T): T { throw UnsupportedOperationException() } override fun <T> waitFor(timeout: Double, f: () -> T): T { throw UnsupportedOperationException() } override fun <T> waitFor(params: Map<String, Any>, timeout: Double, f: () -> T): T { throw UnsupportedOperationException() } override fun <T> waitFor(timeout: Double, interval: Double, f: () -> T): T { throw UnsupportedOperationException() } override fun <T> waitFor(params: Map<String, Any>, timeout: Double, interval: Double, f: () -> T): T { throw UnsupportedOperationException() } fun getJs() = JavascriptInterface(this.browser) } interface Initializable {}
src/main/kotlin/core/Page.kt
2450786284
package org.wordpress.android.ui.uploads import android.app.Activity import android.content.Intent import android.view.View import android.view.View.OnClickListener import dagger.Reusable import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.model.MediaModel import org.wordpress.android.fluxc.model.PostModel import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.post.PostStatus import org.wordpress.android.fluxc.store.PostStore.PostError import org.wordpress.android.ui.uploads.UploadActionUseCase.UploadAction import org.wordpress.android.ui.uploads.UploadUtils.OnPublishingCallback import org.wordpress.android.util.SnackbarSequencer import javax.inject.Inject /** * Injectable wrapper around UploadUtils. * * UploadUtils interface is consisted of static methods, which makes the client code difficult to test/mock. * Main purpose of this wrapper is to make testing easier. */ @Reusable class UploadUtilsWrapper @Inject constructor( private val sequencer: SnackbarSequencer, private val dispatcher: Dispatcher ) { fun userCanPublish(site: SiteModel): Boolean { return UploadUtils.userCanPublish(site) } @Suppress("LongParameterList") fun onMediaUploadedSnackbarHandler( activity: Activity?, snackbarAttachView: View?, isError: Boolean, mediaList: List<MediaModel?>?, site: SiteModel?, messageForUser: String? ) = UploadUtils.onMediaUploadedSnackbarHandler( activity, snackbarAttachView, isError, mediaList, site, messageForUser, sequencer ) @JvmOverloads @Suppress("LongParameterList") fun onPostUploadedSnackbarHandler( activity: Activity?, snackbarAttachView: View?, isError: Boolean, isFirstTimePublish: Boolean, post: PostModel?, errorMessage: String?, site: SiteModel?, onPublishingCallback: OnPublishingCallback? = null ) = UploadUtils.onPostUploadedSnackbarHandler( activity, snackbarAttachView, isError, isFirstTimePublish, post, errorMessage, site, dispatcher, sequencer, onPublishingCallback ) @JvmOverloads @Suppress("LongParameterList") fun handleEditPostResultSnackbars( activity: Activity, snackbarAttachView: View, data: Intent, post: PostModel, site: SiteModel, uploadAction: UploadAction, publishPostListener: OnClickListener?, onPublishingCallback: OnPublishingCallback? = null ) = UploadUtils.handleEditPostModelResultSnackbars( activity, dispatcher, snackbarAttachView, data, post, site, uploadAction, sequencer, publishPostListener, onPublishingCallback ) fun showSnackbarError( view: View?, message: String?, buttonTitleRes: Int, buttonListener: OnClickListener? ) = UploadUtils.showSnackbarError(view, message, buttonTitleRes, buttonListener, sequencer) fun showSnackbarError( view: View?, message: String? ) = UploadUtils.showSnackbarError(view, message, sequencer) fun showSnackbar( view: View?, messageRes: Int ) = UploadUtils.showSnackbar(view, messageRes, sequencer) fun showSnackbar( view: View?, messageText: String ) = UploadUtils.showSnackbar(view, messageText, sequencer) fun getErrorMessageResIdFromPostError( postStatus: PostStatus, isPage: Boolean, postError: PostError, isEligibleForAutoUpload: Boolean ) = UploadUtils.getErrorMessageResIdFromPostError( postStatus, isPage, postError, isEligibleForAutoUpload ) fun publishPost( activity: Activity, post: PostModel, site: SiteModel, onPublishingCallback: OnPublishingCallback? = null ) = UploadUtils.publishPost(activity, post, site, dispatcher, onPublishingCallback) }
WordPress/src/main/java/org/wordpress/android/ui/uploads/UploadUtilsWrapper.kt
2086117848
public inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block() fun aaGlobalFun(){} val aaGlobalProp = 1 open class Base { fun aaBaseFun(){} val aaBaseProp = 1 } class Derived : Base(), Common { fun aaDerivedFun(){} val aaDerivedProp = 1 fun foo(y: Y) { val aaLocalVal = 1 fun aaLocalFun(){} with (y) { if (this is Z1 && this is Z2) { aa<caret> } } } } interface X { fun aaX() } interface Y : X { fun aaY() } interface Z1 : Common { fun aaaZ1() fun aabZ1() } interface Z2 { fun aaaZ2() fun aabZ2() } interface Common { fun aazCommon() } fun Any.aaAnyExtensionFun(){} fun Derived.aaExtensionFun(){} val Any.aaAnyExtensionProp: Int get() = 1 val Derived.aaExtensionProp: Int get() = 1 fun <T> T.aaTypeParamExt(){} fun X.aaXExt(){} fun Y.aaYExt(){} // ORDER: aaLocalVal // ORDER: aaLocalFun // ORDER: aaY // ORDER: aaaZ1 // ORDER: aaaZ2 // ORDER: aabZ1 // ORDER: aabZ2 // ORDER: aaX // ORDER: aaYExt // ORDER: aaXExt // ORDER: aaDerivedProp // ORDER: aaDerivedFun // ORDER: aaBaseProp // ORDER: aaBaseFun // ORDER: aaExtensionProp // ORDER: aaExtensionFun // ORDER: aazCommon // ORDER: aaAnyExtensionProp // ORDER: aaAnyExtensionFun // ORDER: aaGlobalProp // ORDER: aaGlobalFun // ORDER: aaTypeParamExt
plugins/kotlin/completion/tests/testData/weighers/basic/Callables.kt
3441266435
package test class Foo
plugins/kotlin/idea/tests/testData/resolve/referenceWithLib/sameNameInLibSrc/libFile.kt
1224292410
fun f() { val v = 150 - 150 println(<caret>v + 1) }
plugins/kotlin/idea/tests/testData/refactoring/inline/inlineVariableOrProperty/addParenthesis/LeftAssociativeDontAdd.kt
363062146
package io.sneakspeak.sneakspeak.fragments import android.content.Intent import android.os.Bundle import android.os.Handler import android.support.annotation.UiThread import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.text.format.Time import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.android.gms.gcm.GoogleCloudMessaging import io.sneakspeak.sneakspeak.activities.MainActivity import io.sneakspeak.sneakspeak.R import io.sneakspeak.sneakspeak.SneakSpeak import io.sneakspeak.sneakspeak.adapters.ChatAdapter import io.sneakspeak.sneakspeak.data.Channel import io.sneakspeak.sneakspeak.data.Message import io.sneakspeak.sneakspeak.managers.DatabaseManager import io.sneakspeak.sneakspeak.managers.HttpManager import io.sneakspeak.sneakspeak.managers.SettingsManager import io.sneakspeak.sneakspeak.receiver.MessageResultReceiver import kotlinx.android.synthetic.main.fragment_chat.* import org.jetbrains.anko.async import org.jetbrains.anko.support.v4.toast import org.jetbrains.anko.uiThread import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.atomic.AtomicInteger class ChatFragment(user: String?) : Fragment(), View.OnClickListener, MessageResultReceiver.Receiver { init { chatUser = user chatChannel = null } constructor(channel: Channel) : this(null) { chatChannel = channel } val TAG = "ChatFragment" companion object { var messageReceiver: MessageResultReceiver? = null var chatUser: String? = null var chatChannel: Channel? = null } lateinit var adapter: ChatAdapter override fun onReceiveResult(resultCode: Int, resultData: Bundle?) { if (resultData == null) return adapter.addMessage(Message(resultData.getString("sender"), resultData.getString("message"), resultData.getString("time"))) messageList.scrollToPosition(adapter.itemCount - 1) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, bundle: Bundle?) = inflater?.inflate(R.layout.fragment_chat, container, false) override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { sendButton.setOnClickListener(this) adapter = ChatAdapter() messageList.adapter = adapter val manager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false) manager.stackFromEnd = true messageList.layoutManager = manager messageReceiver = MessageResultReceiver(Handler()) } override fun onClick(button: View?) { if (messageText.text.isEmpty()) return val df = SimpleDateFormat("HH:mm:ss") val time = df.format(Calendar.getInstance().time) adapter.addMessage(Message(SettingsManager.getUsername(), messageText.text.toString(), time)) messageList.scrollToPosition(adapter.itemCount - 1) val server = DatabaseManager.getCurrentServer() if (server == null) { toast("Something is wrong.") return } async() { if (chatUser != null) { HttpManager.sendMessage(server, chatUser ?: return@async, messageText.text.toString()) } else { HttpManager.sendChannelMessage(server, chatChannel ?: return@async, messageText.text.toString()) } uiThread { messageText.text.clear() } } } override fun onResume() { super.onResume() messageReceiver?.receiver = this } override fun onPause() { super.onPause() messageReceiver?.receiver = null } }
app/src/main/kotlin/io/sneakspeak/sneakspeak/fragments/ChatFragment.kt
3234479194
package org.sjoblomj.travellingantcolony import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.immutableListOf import kotlinx.collections.immutable.toImmutableList import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.sjoblomj.travellingantcolony.domain.Place import java.lang.Math.sqrt class BruteforcerTest { @Test fun calculateLength_EmptyInput() { val emptyList = immutableListOf<Place>() assertThat(calculateLength(emptyList)).isEqualTo(0.0) val listOfOne = immutableListOf(Place(1.0, 2.0, "Oslo")) assertThat(calculateLength(listOfOne)).isEqualTo(0.0) } @Test fun calculateLength_ManyPlaces() { val listOfTwo = immutableListOf(Place(2.0, 1.0, "Oslo"), Place(2.0, 6.0, "Gothenburg")) assertThat(calculateLength(listOfTwo)).isEqualTo(5.0) val listWithTwoIdenticalPlaces = immutableListOf(Place(2.0, 1.0), Place(2.0, 6.0), Place(2.0, 6.0)) assertThat(calculateLength(listWithTwoIdenticalPlaces)).isEqualTo(5.0) val thereAndBackAgain = immutableListOf(Place(2.0, 1.0), Place(2.0, 6.0), Place(2.0, 1.0)) assertThat(calculateLength(thereAndBackAgain)).isEqualTo(10.0) val listOfThree = immutableListOf(Place(2.0, 1.0), Place(2.0, 6.0), Place(7.0, 6.0)) assertThat(calculateLength(listOfThree)).isEqualTo(10.0) val listOfFour = immutableListOf(Place(2.0, 1.0), Place(12.0, 6.0), Place(7.0, 6.0), Place(7.0, 61.0)) assertThat(calculateLength(listOfFour)).isEqualTo(5 * sqrt(5.0) + 5 + 55) } @Test fun permutationTest() { val a = Place(0.0, 0.0, "a") val b = Place(1.0, 1.0, "b") val c = Place(2.0, 2.0, "c") val emptyList = immutableListOf<Place>() assertThat(permutation(emptyList)).isEqualTo(immutableListOf(immutableListOf<ImmutableList<Place>>())) val listOfOne = immutableListOf(a) assertThat(permutation(listOfOne)).isEqualTo(immutableListOf(immutableListOf(a))) val listOfTwo = immutableListOf(a, b) assertThat(permutation(listOfTwo)).isEqualTo(immutableListOf(immutableListOf(a, b), immutableListOf(b, a))) val listOfThree = immutableListOf(a, b, c) val expected = immutableListOf( immutableListOf(a, b, c), immutableListOf(a, c, b), immutableListOf(b, a, c), immutableListOf(b, c, a), immutableListOf(c, a, b), immutableListOf(c, b, a)) assertThat(permutation(listOfThree)).isEqualTo(expected) } @Test fun permutation2Test() { val a = Place(0.0, 0.0, "a") val b = Place(1.0, 1.0, "b") val c = Place(2.0, 2.0, "c") val emptyList = immutableListOf<Place>() assertThat(permutation2(emptyList).toList()).isEqualTo(immutableListOf(immutableListOf<ImmutableList<Place>>())) val listOfOne = immutableListOf(a) assertThat(permutation2(listOfOne).toList()).isEqualTo(immutableListOf(immutableListOf(a))) val listOfTwo = immutableListOf(a, b) assertThat(permutation2(listOfTwo).toList()).isEqualTo(immutableListOf(immutableListOf(a, b), immutableListOf(b, a))) val listOfThree = immutableListOf(a, b, c) val expected = immutableListOf( immutableListOf(a, b, c), immutableListOf(a, c, b), immutableListOf(b, a, c), immutableListOf(b, c, a), immutableListOf(c, a, b), immutableListOf(c, b, a)) assertThat(permutation2(listOfThree).toList()).containsAll(expected) } @Test fun greedySolver() { val a = Place(0.0, 0.0, "a") val b = Place(4.0, 1.0, "b") val c = Place(5.0, 6.0, "c") val d = Place(2.0, 2.0, "d") val e = Place(9.0, 7.0, "e") val list = immutableListOf(b, c, d, e) val expected = immutableListOf(a, d, b, c, e, a) assertThat(greedySolution(list, a)).isEqualTo(expected) } @Test fun bruteforceWithInvalidInputs() { val emptyList = immutableListOf<Place>() assertThat(bruteforce(emptyList)).isEqualTo(emptyList) val listOfOne = immutableListOf(Place(1.0, 2.0)) assertThat(bruteforce(listOfOne)).isEqualTo(listOfOne) } @Test fun bruteforceInputOfTwo() { val a = Place(0.0, 0.0, "a") val b = Place(4.0, 1.0, "b") val listOfTwo = immutableListOf(a, b) val expected = immutableListOf(a, b, a) assertThat(bruteforce(listOfTwo)).isEqualTo(expected) } @Test fun bruteforce() { val list = mutableListOf<Place>() list.add(Place(14.843435, 64.155902)) list.add(Place(369.829464, 394.798983)) list.add(Place(70.148814, 102.961104)) list.add(Place(216.875209, 260.844929)) list.add(Place(499.454448, 196.360554)) list.add(Place(276.895963, 4.798338)) list.add(Place(450.317844, 463.120257)) list.add(Place(144.357250, 48.303781)) list.add(Place(229.398167, 340.463102)) // list.add(Place(221.398167, 341.463102)) list.add(Place(108.504974, 460.106655)) val expected = mutableListOf<Place>() expected.add(Place(14.843435, 64.155902)) expected.add(Place(70.148814, 102.961104)) expected.add(Place(216.875209, 260.844929)) expected.add(Place(229.398167, 340.463102)) expected.add(Place(108.504974, 460.106655)) expected.add(Place(369.829464, 394.798983)) expected.add(Place(450.317844, 463.120257)) expected.add(Place(499.454448, 196.360554)) expected.add(Place(276.895963, 4.798338)) expected.add(Place(144.357250, 48.303781)) expected.add(Place(14.843435, 64.155902)) assertThat(bruteforce(list.toImmutableList())).isEqualTo(expected.toImmutableList()) } @Test fun bruteforce2() { val list = mutableListOf<Place>() list.add(Place(14.843435, 64.155902)) list.add(Place(369.829464, 394.798983)) list.add(Place(70.148814, 102.961104)) list.add(Place(216.875209, 260.844929)) list.add(Place(499.454448, 196.360554)) list.add(Place(276.895963, 4.798338)) list.add(Place(450.317844, 463.120257)) list.add(Place(144.357250, 48.303781)) list.add(Place(229.398167, 340.463102)) list.add(Place(221.398167, 341.463102)) list.add(Place(222.398167, 342.463102)) list.add(Place(108.504974, 460.106655)) val expected = mutableListOf<Place>() expected.add(Place(14.843435, 64.155902)) expected.add(Place(70.148814, 102.961104)) expected.add(Place(216.875209, 260.844929)) expected.add(Place(229.398167, 340.463102)) expected.add(Place(222.398167, 342.463102)) expected.add(Place(221.398167, 341.463102)) expected.add(Place(108.504974, 460.106655)) expected.add(Place(369.829464, 394.798983)) expected.add(Place(450.317844, 463.120257)) expected.add(Place(499.454448, 196.360554)) expected.add(Place(276.895963, 4.798338)) expected.add(Place(144.357250, 48.303781)) expected.add(Place(14.843435, 64.155902)) assertThat(bruteforce2(list.toImmutableList())).isEqualTo(expected.toImmutableList()) } }
src/test/kotlin/org/sjoblomj/travellingantcolony/BruteforcerTest.kt
4267919091
/* * IntercodeLookupSTR.kt * * Copyright 2018 Google * * 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 au.id.micolous.metrodroid.transit.intercode import au.id.micolous.metrodroid.transit.en1545.En1545LookupSTR internal abstract class IntercodeLookupSTR(str: String) : En1545LookupSTR(str), IntercodeLookup
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/intercode/IntercodeLookupSTR.kt
336478377
package org.pmiops.workbench.actionaudit.targetproperties data class PreviousNewValuePair(var previousValue: String?, var newValue: String?) { val valueChanged: Boolean get() { return previousValue == null && newValue != null || newValue == null && previousValue != null || previousValue != newValue } }
api/src/main/java/org/pmiops/workbench/actionaudit/targetproperties/PreviousNewValuePair.kt
2181267410
package <%= appPackage %>.data.source import <%= appPackage %>.data.repository.BufferooCache import <%= appPackage %>.data.repository.BufferooDataStore import javax.inject.Inject /** * Create an instance of a BufferooDataStore */ open class BufferooDataStoreFactory @Inject constructor( private val bufferooCache: BufferooCache, private val bufferooCacheDataStore: BufferooCacheDataStore, private val bufferooRemoteDataStore: BufferooRemoteDataStore) { /** * Returns a DataStore based on whether or not there is content in the cache and the cache * has not expired */ open fun retrieveDataStore(isCached: Boolean): BufferooDataStore { if (isCached && !bufferooCache.isExpired()) { return retrieveCacheDataStore() } return retrieveRemoteDataStore() } /** * Return an instance of the Cache Data Store */ open fun retrieveCacheDataStore(): BufferooDataStore { return bufferooCacheDataStore } /** * Return an instance of the Remote Data Store */ open fun retrieveRemoteDataStore(): BufferooDataStore { return bufferooRemoteDataStore } }
templates/buffer-clean-architecture-components-kotlin/data/src/main/java/org/buffer/android/boilerplate/data/source/BufferooDataStoreFactory.kt
3307309326
package cf.reol.stingy.act.recycler.item import android.graphics.Color import cf.reol.stingy.act.recycler.TypeFactory /** * Created by reol on 2017/8/29. */ class AccountingItem(var leftColor: Int= Color.BLACK, var rightColor: Int = Color.RED, var title: String, var description: String, var content: String, var time: Long) : Visitable { override fun type(typeFactory: TypeFactory): Int = typeFactory.type(this) }
app/src/main/java/cf/reol/stingy/act/recycler/item/AccountingItem.kt
2114272779
package fi.tuska.jalkametri.gui import android.content.Context import android.view.LayoutInflater import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import fi.tuska.jalkametri.R class TextIconView(context: Context, vertical: Boolean, gravity: Int) : LinearLayout(context) { private lateinit var textView: TextView private lateinit var iconView: ImageView init { this.gravity = gravity } var text: String get() = textView.text.toString() set(text) { textView.text = text } private fun initView(vertical: Boolean) { val li = context.getSystemService( Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater li.inflate(layout(vertical), this, true) textView = findViewById(R.id.text) as TextView iconView = findViewById(R.id.icon) as ImageView } fun layout(vertical: Boolean) = if (vertical) R.layout.text_icon_vertical else R.layout.text_icon_horizontal fun setImageResource(resID: Int) { iconView.setImageResource(resID) } override fun toString(): String = text init { initView(vertical) } }
app/src/main/java/fi/tuska/jalkametri/gui/TextIconView.kt
1940423988
package io.ipoli.android.challenge.list import io.ipoli.android.challenge.entity.Challenge import io.ipoli.android.common.AppState import io.ipoli.android.common.BaseViewStateReducer import io.ipoli.android.common.DataLoadedAction import io.ipoli.android.common.redux.Action import io.ipoli.android.common.redux.BaseViewState /** * Created by Venelin Valkov <[email protected]> * on 03/05/2018. */ sealed class ChallengeListAction : Action { object Load : ChallengeListAction() object AddChallenge : ChallengeListAction() } object ChallengeListReducer : BaseViewStateReducer<ChallengeListViewState>() { override fun reduce( state: AppState, subState: ChallengeListViewState, action: Action ) = when (action) { is ChallengeListAction.Load -> createState(state.dataState.challenges, subState) is ChallengeListAction.AddChallenge -> subState.copy( type = ChallengeListViewState.StateType.SHOW_ADD ) is DataLoadedAction.ChallengesChanged -> createState(action.challenges, subState) else -> subState } private fun createState(challenges: List<Challenge>?, state: ChallengeListViewState) = when { challenges == null -> state.copy(type = ChallengeListViewState.StateType.LOADING) challenges.isEmpty() -> state.copy(type = ChallengeListViewState.StateType.EMPTY) else -> state.copy( type = ChallengeListViewState.StateType.DATA_CHANGED, challenges = createChallengeItems(challenges) ) } override fun defaultState() = ChallengeListViewState( type = ChallengeListViewState.StateType.LOADING, challenges = emptyList() ) override val stateKey = key<ChallengeListViewState>() } data class ChallengeListViewState(val type: StateType, val challenges: List<ChallengeItem>) : BaseViewState() { enum class StateType { LOADING, EMPTY, SHOW_ADD, DATA_CHANGED } }
app/src/main/java/io/ipoli/android/challenge/list/ChallengeListViewState.kt
688208362
package io.ipoli.android.quest.schedule import android.content.Context import io.ipoli.android.common.AppDataState import io.ipoli.android.common.AppState import io.ipoli.android.common.BaseViewStateReducer import io.ipoli.android.common.redux.Action import io.ipoli.android.common.redux.BaseViewState import io.ipoli.android.common.text.CalendarFormatter import io.ipoli.android.player.data.Player import io.ipoli.android.quest.schedule.agenda.view.AgendaAction import io.ipoli.android.quest.schedule.calendar.CalendarAction import org.threeten.bp.LocalDate /** * Created by Venelin Valkov <[email protected]> * on 10/21/17. */ sealed class ScheduleAction : Action { object ToggleViewMode : ScheduleAction() object ToggleAgendaPreviewMode : ScheduleAction() data class Load(val viewMode: Player.Preferences.AgendaScreen) : ScheduleAction() object GoToToday : ScheduleAction() object ResetAgendaDate : ScheduleAction() } object ScheduleReducer : BaseViewStateReducer<ScheduleViewState>() { override val stateKey = key<ScheduleViewState>() override fun defaultState() = ScheduleViewState( type = ScheduleViewState.StateType.LOADING, currentDate = LocalDate.now(), viewMode = Player.Preferences.AgendaScreen.AGENDA ) override fun reduce(state: AppState, subState: ScheduleViewState, action: Action) = when (action) { is ScheduleAction -> reduceCalendarAction( state.dataState, subState, action ) is CalendarAction.ChangeDate -> subState.copy( type = ScheduleViewState.StateType.SWIPE_DATE_CHANGED, currentDate = action.date ) is AgendaAction.AutoChangeDate -> autoChangeDate(subState, action.date) is AgendaAction.ChangePreviewDate -> autoChangeDate(subState, action.date) else -> subState } private fun autoChangeDate( subState: ScheduleViewState, date: LocalDate ) = if (subState.currentDate.isEqual(date)) { subState.copy( type = ScheduleViewState.StateType.IDLE ) } else { subState.copy( type = ScheduleViewState.StateType.DATE_AUTO_CHANGED, currentDate = date ) } private fun reduceCalendarAction( dataState: AppDataState, state: ScheduleViewState, action: ScheduleAction ) = when (action) { is ScheduleAction.Load -> { if (state.type != ScheduleViewState.StateType.LOADING) { state.copy( currentDate = dataState.agendaDate ) } else { state.copy( type = ScheduleViewState.StateType.INITIAL, viewMode = action.viewMode, currentDate = dataState.agendaDate ) } } is ScheduleAction.ToggleViewMode -> { state.copy( type = ScheduleViewState.StateType.VIEW_MODE_CHANGED, viewMode = if (state.viewMode == Player.Preferences.AgendaScreen.DAY) Player.Preferences.AgendaScreen.AGENDA else Player.Preferences.AgendaScreen.DAY ) } is ScheduleAction.GoToToday -> { state.copy( type = ScheduleViewState.StateType.DATE_AUTO_CHANGED, currentDate = LocalDate.now() ) } else -> state } } data class ScheduleViewState( val type: StateType, val currentDate: LocalDate, val viewMode: Player.Preferences.AgendaScreen ) : BaseViewState() { enum class StateType { LOADING, INITIAL, IDLE, CALENDAR_DATE_CHANGED, SWIPE_DATE_CHANGED, DATE_PICKER_CHANGED, VIEW_MODE_CHANGED, DATE_AUTO_CHANGED } } val ScheduleViewState.viewModeTitle get() = if (viewMode == Player.Preferences.AgendaScreen.DAY) "Agenda" else "Calendar" fun ScheduleViewState.dayText(context: Context) = CalendarFormatter(context).day(currentDate) fun ScheduleViewState.dateText(context: Context) = CalendarFormatter(context).date(currentDate)
app/src/main/java/io/ipoli/android/quest/schedule/ScheduleViewState.kt
3571899014
package com.andgate.ikou.ui; import com.andgate.ikou.Constants; import com.andgate.ikou.Ikou; import com.andgate.ikou.actor.maze.MazeActor; import com.andgate.ikou.actor.player.PlayerActor; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.Vector3 import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.utils.Disposable; class SinglePlayerUI(val game: Ikou, val maze: MazeActor, val player: PlayerActor) : Disposable { private val TAG: String = "HelpScreen" val stage = Stage() private val uiLabelStyle = Label.LabelStyle(game.arial_fnt, Color.BLACK) private var depthLabel = Label("", uiLabelStyle) private var fpsLabel = Label("", uiLabelStyle) private var game_ui_font_scale: Float = 0f private var debug_font_scale: Float = 0f init { val bg = Constants.BACKGROUND_COLOR Gdx.gl.glClearColor(bg.r, bg.g, bg.b, bg.a) } fun build() { stage.clear() stage.getViewport().setWorldSize(Gdx.graphics.getWidth().toFloat(), Gdx.graphics.getHeight().toFloat()) stage.getViewport().update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true) calc_font_size() val depthString: String = "" + player.model.transform.getTranslation(Vector3()).y depthLabel = Label(depthString, uiLabelStyle) depthLabel.setText(depthString) depthLabel.setFontScale(game_ui_font_scale) fpsLabel.setFontScale(debug_font_scale) val seedString: String = "Seed: " + maze.seed_phrase val seedLabel = Label(seedString, uiLabelStyle) seedLabel.setFontScale(debug_font_scale) val infoTable = Table() infoTable.add(depthLabel).expandX().row() if(game.debug) { infoTable.add(fpsLabel).left().row() infoTable.add(seedLabel).left().row() } infoTable.setBackground(game.whiteTransparentOverlay) val table = Table() table.setFillParent(true) table.top().left() table.add(infoTable).expandX().fillX() stage.addActor(table) //stage.setDebugAll(true) } fun update() { val depthString: String = "" + (player.model.transform.getTranslation(Vector3()).y) depthLabel.setText(depthString) val fpsString: String = "FPS: " + Gdx.graphics.getFramesPerSecond() fpsLabel.setText(fpsString) } private fun calc_font_size() { val font_scale_factor: Float = game.ppu / Constants.ARIAL_FONT_SIZE game_ui_font_scale = Constants.GAME_UI_FONT_UNIT_SIZE * font_scale_factor debug_font_scale = Constants.DEBUG_FONT_UNIT_SIZE * font_scale_factor } override fun dispose() { stage.dispose() } }
core/src/com/andgate/ikou/ui/SinglePlayerUI.kt
1671273249
package com.ianhanniballake.contractiontimer.ui import android.app.Dialog import android.app.TimePickerDialog import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import android.text.format.DateFormat import android.util.Log import androidx.fragment.app.DialogFragment import androidx.localbroadcastmanager.content.LocalBroadcastManager import com.ianhanniballake.contractiontimer.BuildConfig import com.ikovac.timepickerwithseconds.view.MyTimePickerDialog import java.util.Calendar /** * Provides a DialogFragment for selecting a time */ class TimePickerDialogFragment : DialogFragment() { companion object { private const val TAG = "TimePickerDialog" /** * Argument key for storing/retrieving the callback action */ const val CALLBACK_ACTION = "com.ianhanniballake.contractiontimer.CALLBACK_ACTION_ARGUMENT" /** * Extra corresponding with the hour of the day that was set */ const val HOUR_OF_DAY_EXTRA = "com.ianhanniballake.contractionTimer.HOUR_OF_DAY_EXTRA" /** * Extra corresponding with the minute that was set */ const val MINUTE_EXTRA = "com.ianhanniballake.contractionTimer.MINUTE_EXTRA" /** * Extra corresponding with the second that was set */ const val SECOND_EXTRA = "com.ianhanniballake.contractionTimer.SECOND_EXTRA" /** * Argument key for storing/retrieving the time associated with this dialog */ const val TIME_ARGUMENT = "com.ianhanniballake.contractiontimer.TIME_ARGUMENT" /** * Gets an API level specific implementation of the time picker * * @param context context used to create the Dialog * @param callback Callback to pass the returned time to * @param date starting date * @return A valid TimePickerDialog */ private fun getTimePickerDialog( context: Context, callback: TimePickerDialogFragment, date: Calendar ): Dialog { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { val onTimeSetListener = MyTimePickerDialog.OnTimeSetListener { _, hourOfDay, minute, seconds -> callback.onTimeSet(hourOfDay, minute, seconds) } return MyTimePickerDialog(context, onTimeSetListener, date.get(Calendar.HOUR_OF_DAY), date.get(Calendar.MINUTE), date.get(Calendar.SECOND), DateFormat.is24HourFormat(context)) } else { val onTimeSetListener = TimePickerDialog.OnTimeSetListener { _, hourOfDay, minute -> callback.onTimeSet(hourOfDay, minute, 0) } return TimePickerDialog(context, onTimeSetListener, date.get(Calendar.HOUR_OF_DAY), date.get(Calendar.MINUTE), DateFormat.is24HourFormat(context)) } } } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val date = requireArguments().getSerializable(TIME_ARGUMENT) as Calendar val dialog = getTimePickerDialog(requireContext(), this, date) dialog.setOnDismissListener(this) return dialog } internal fun onTimeSet(hourOfDay: Int, minute: Int, second: Int) { val action = requireArguments().getString(CALLBACK_ACTION) if (BuildConfig.DEBUG) Log.d(TAG, "onTimeSet: $action") val broadcast = Intent(action).apply { putExtra(HOUR_OF_DAY_EXTRA, hourOfDay) putExtra(MINUTE_EXTRA, minute) putExtra(SECOND_EXTRA, second) } val localBroadcastManager = LocalBroadcastManager.getInstance(requireContext()) localBroadcastManager.sendBroadcast(broadcast) } }
mobile/src/main/java/com/ianhanniballake/contractiontimer/ui/TimePickerDialogFragment.kt
2022166887
package com.onyx.exception /** * Created by timothy.osborn on 12/6/14. * * Class that is trying to work on is not a persistable type */ class EntityClassNotFoundException @JvmOverloads constructor(message: String? = "") : OnyxException(message) { private var entityClassName: String? = null /** * Constructor with message * * @param message Error message */ constructor(message: String, entityType: Class<*>) : this(message + " for class " + entityType.name) { entityClassName = entityType.name } companion object { const val RELATIONSHIP_ENTITY_BASE_NOT_FOUND = "Relationship type does not extend from ManagedEntity" const val RELATIONSHIP_ENTITY_NOT_FOUND = "Relationship type does not have entity annotation" const val ENTITY_NOT_FOUND = "Entity is not able to persist because entity annotation does not exist" const val PERSISTED_NOT_FOUND = "Entity is not able to persist because entity does not implement IManagedEntity" const val EXTENSION_NOT_FOUND = "Entity is not able to persist because entity does not extend from ManagedEntity" const val TO_MANY_INVALID_TYPE = "To Many relationship must by type List.class" } }
onyx-database/src/main/kotlin/com/onyx/exception/EntityClassNotFoundException.kt
100275641
package io.quartz.gen.jvm.asm import io.quartz.gen.jvm.JvmGenerator import io.quartz.gen.jvm.tree.* import io.quartz.nil import io.quartz.tree.util.Name import org.objectweb.asm.* import org.objectweb.asm.commons.* fun JvmClass.generate(jg: JvmGenerator) = run { val cg = ClassGenerator(jg, name, ClassWriter(ClassWriter.COMPUTE_FRAMES)) val access = Opcodes.ACC_PUBLIC + (if (isFinal) Opcodes.ACC_FINAL else 0) + (if (isInterface) Opcodes.ACC_INTERFACE + Opcodes.ACC_ABSTRACT else 0) annotations.forEach { it.generate(cg) } cg.run { cw.visit( Opcodes.V1_8, access, name.locatableString, classSignature(foralls, listOf(JvmType.`object`) + interfaces), "java/lang/Object", interfaces.map { it.qualified }.toTypedArray() ) if (!isInterface) visitDefaultConstructor() decls.forEach { it.generate(cg) } cw.visitEnd() cw } } fun ClassGenerator.visitDefaultConstructor() = run { val ga = GeneratorAdapter(Opcodes.ACC_PUBLIC, Method.getMethod("void <init> ()"), null, emptyArray(), cw) ga.loadThis() ga.invokeConstructor(JvmType.`object`.asmType, Method.getMethod("void <init> ()")) ga.returnValue() ga.visitEnd() } fun classSignature( foralls: Set<Name>, superTypes: List<JvmType> ) = when (foralls) { nil -> "" else -> foralls.joinToString(prefix = "<", postfix = ">", separator = "") { "${it.string}:Ljava/lang/Object;" } } + superTypes.joinToString(separator = "", prefix = "", postfix = "") { it.signature }
compiler/src/main/kotlin/io/quartz/gen/jvm/asm/JvmClassGenerator.kt
912962562
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.bookmark.actions import com.intellij.ide.bookmark.* import com.intellij.ide.bookmark.BookmarkBundle.messagePointer import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.components.service import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import java.util.concurrent.atomic.AtomicReference import java.util.function.Supplier internal class NextBookmarkAction : IterateBookmarksAction(true, messagePointer("bookmark.go.to.next.action.text")) internal class PreviousBookmarkAction : IterateBookmarksAction(false, messagePointer("bookmark.go.to.previous.action.text")) internal abstract class IterateBookmarksAction(val forward: Boolean, dynamicText: Supplier<String>) : DumbAwareAction(dynamicText) { private val AnActionEvent.nextBookmark get() = project?.service<NextBookmarkService>()?.next(forward, contextBookmark as? LineBookmark) override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT override fun update(event: AnActionEvent) { event.presentation.isEnabled = when (val view = event.bookmarksView) { null -> event.nextBookmark != null else -> if (forward) view.hasNextOccurence() else view.hasPreviousOccurence() } } override fun actionPerformed(event: AnActionEvent) { when (val view = event.bookmarksView) { null -> event.nextBookmark?.run { if (canNavigate()) navigate(true) } else -> if (forward) view.goNextOccurence() else view.goPreviousOccurence() } } } internal class NextBookmarkService(private val project: Project) : BookmarksListener, Comparator<LineBookmark> { private val cache = AtomicReference<List<LineBookmark>>() private val bookmarks: List<LineBookmark> get() = BookmarksManager.getInstance(project)?.bookmarks?.filterIsInstance<LineBookmark>()?.sortedWith(this) ?: emptyList() private fun getCachedBookmarks() = synchronized(cache) { cache.get() ?: bookmarks.also { cache.set(it) } } override fun bookmarkAdded(group: BookmarkGroup, bookmark: Bookmark) = bookmarksChanged(bookmark) override fun bookmarkRemoved(group: BookmarkGroup, bookmark: Bookmark) = bookmarksChanged(bookmark) private fun bookmarksChanged(bookmark: Bookmark) { if (bookmark is LineBookmark) cache.set(null) } private fun compareFiles(bookmark1: LineBookmark, bookmark2: LineBookmark) = bookmark1.file.path.compareTo(bookmark2.file.path) private fun compareLines(bookmark1: LineBookmark, bookmark2: LineBookmark) = bookmark1.line.compareTo(bookmark2.line) override fun compare(bookmark1: LineBookmark, bookmark2: LineBookmark) = when (val result = compareFiles(bookmark1, bookmark2)) { 0 -> compareLines(bookmark1, bookmark2) else -> result } private fun next(forward: Boolean, index: Int) = when { index < 0 -> (-index - if (forward) 1 else 2) else -> (index - if (forward) -1 else 1) } fun next(forward: Boolean, bookmark: LineBookmark?): LineBookmark? { val bookmarks = getCachedBookmarks().ifEmpty { return null } if (bookmark != null) { val next = bookmarks.getOrNull(next(forward, bookmarks.binarySearch(bookmark, this))) if (next != null || !BookmarkOccurrence.cyclic) return next } return if (forward) bookmarks.first() else bookmarks.last() } init { project.messageBus.connect(project).subscribe(BookmarksListener.TOPIC, this) } }
platform/lang-impl/src/com/intellij/ide/bookmark/actions/NextBookmarkService.kt
3296332171
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.vcs.log import com.intellij.util.Consumer import org.jetbrains.annotations.ApiStatus /** * Commit selection in the Vcs Log table. * * @see VcsLogDataKeys.VCS_LOG_COMMIT_SELECTION */ @ApiStatus.Experimental interface VcsLogCommitSelection { /** * Selection size. */ val size: Int /** * Identifiers of the commits selected in the table. * * @see com.intellij.vcs.log.data.VcsLogStorage.getCommitIndex */ val ids: List<Int> /** * [CommitId] of the commits selected in the table. */ val commits: List<CommitId> /** * Cached metadata of the commits selected in the table. * When metadata of the commit is not available in the cache, a placeholder object * (an instance of [com.intellij.vcs.log.data.LoadingDetails]) is returned. * * Metadata are loaded faster than full details and since it is done while scrolling, * there is a better chance that details for a commit are loaded when user selects it. * * @see com.intellij.vcs.log.data.LoadingDetails */ val cachedMetadata: List<VcsCommitMetadata> /** * Cached full details of the commits selected in the table. * When full details of the commit are not available in the cache, a placeholder object * (an instance of [com.intellij.vcs.log.data.LoadingDetails]) is returned. * * @see com.intellij.vcs.log.data.LoadingDetails */ val cachedFullDetails: List<VcsFullCommitDetails> /** * Sends a request to load full details of the selected commits in a background thread. * After all details are loaded they are provided to the consumer in the EDT. * * @param consumer called in EDT after all details are loaded. */ fun requestFullDetails(consumer: Consumer<in List<VcsFullCommitDetails>>) companion object { @JvmStatic fun VcsLogCommitSelection.isEmpty() = size == 0 @JvmStatic fun VcsLogCommitSelection.isNotEmpty() = size != 0 } }
platform/vcs-log/api/src/com/intellij/vcs/log/VcsLogCommitSelection.kt
4003734116
// 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.debugger.coroutine.proxy import com.intellij.debugger.engine.DebuggerManagerThreadImpl import com.intellij.debugger.engine.SuspendContextImpl import com.intellij.openapi.util.registry.Registry import org.jetbrains.kotlin.idea.debugger.coroutine.CoroutinesInfoFromJsonAndReferencesProvider import org.jetbrains.kotlin.idea.debugger.coroutine.data.CoroutineInfoCache import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.mirror.DebugProbesImpl import org.jetbrains.kotlin.idea.debugger.coroutine.util.executionContext import org.jetbrains.kotlin.idea.debugger.coroutine.util.logger import org.jetbrains.kotlin.idea.debugger.base.util.evaluate.DefaultExecutionContext class CoroutineDebugProbesProxy(val suspendContext: SuspendContextImpl) { /** * Invokes DebugProbes from debugged process's classpath and returns states of coroutines * Should be invoked on debugger manager thread */ @Synchronized fun dumpCoroutines(): CoroutineInfoCache { DebuggerManagerThreadImpl.assertIsManagerThread() val coroutineInfoCache = CoroutineInfoCache() try { val executionContext = suspendContext.executionContext() ?: return coroutineInfoCache.fail() val libraryAgentProxy = findProvider(executionContext) ?: return coroutineInfoCache.ok() val infoList = libraryAgentProxy.dumpCoroutinesInfo() coroutineInfoCache.ok(infoList) } catch (e: Throwable) { log.error("Exception is thrown by calling dumpCoroutines.", e) coroutineInfoCache.fail() } return coroutineInfoCache } private fun findProvider(executionContext: DefaultExecutionContext): CoroutineInfoProvider? { val debugProbesImpl = DebugProbesImpl.instance(executionContext) return when { debugProbesImpl != null && debugProbesImpl.isInstalled -> CoroutinesInfoFromJsonAndReferencesProvider.instance(executionContext, debugProbesImpl) ?: CoroutineLibraryAgent2Proxy(executionContext, debugProbesImpl) standaloneCoroutineDebuggerEnabled() -> CoroutineNoLibraryProxy(executionContext) else -> null } } companion object { private val log by logger } } fun standaloneCoroutineDebuggerEnabled() = Registry.`is`("kotlin.debugger.coroutines.standalone")
plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/proxy/CoroutineDebugProbesProxy.kt
2084381513
import com.intellij.openapi.components.ApplicationComponent class RegisteredApplicationComponent : ApplicationComponent { class InnerStaticClassApplicationContext : ApplicationComponent }
plugins/devkit/devkit-kotlin-tests/testData/inspections/componentNotRegistered/RegisteredApplicationComponent.kt
3931310921
package org.thoughtcrime.securesms.components.settings.app.changenumber import android.content.Context import android.content.Intent import android.os.Bundle import com.google.android.material.dialog.MaterialAlertDialogBuilder import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.kotlin.subscribeBy import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.MainActivity import org.thoughtcrime.securesms.PassphraseRequiredActivity import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.logsubmit.SubmitDebugLogActivity import org.thoughtcrime.securesms.phonenumbers.PhoneNumberFormatter import org.thoughtcrime.securesms.util.DynamicNoActionBarTheme import org.thoughtcrime.securesms.util.DynamicTheme import org.thoughtcrime.securesms.util.LifecycleDisposable import org.whispersystems.signalservice.api.push.PNI import java.util.Objects private val TAG: String = Log.tag(ChangeNumberLockActivity::class.java) /** * A captive activity that can determine if an interrupted/erred change number request * caused a disparity between the server and our locally stored number. */ class ChangeNumberLockActivity : PassphraseRequiredActivity() { private val dynamicTheme: DynamicTheme = DynamicNoActionBarTheme() private val disposables: LifecycleDisposable = LifecycleDisposable() private lateinit var changeNumberRepository: ChangeNumberRepository override fun onCreate(savedInstanceState: Bundle?, ready: Boolean) { dynamicTheme.onCreate(this) disposables.bindTo(lifecycle) setContentView(R.layout.activity_change_number_lock) changeNumberRepository = ChangeNumberRepository(applicationContext) checkWhoAmI() } override fun onResume() { super.onResume() dynamicTheme.onResume(this) } override fun onBackPressed() = Unit private fun checkWhoAmI() { disposables.add( changeNumberRepository.whoAmI() .flatMap { whoAmI -> if (Objects.equals(whoAmI.number, SignalStore.account().e164)) { Log.i(TAG, "Local and remote numbers match, nothing needs to be done.") Single.just(false) } else { Log.i(TAG, "Local (${SignalStore.account().e164}) and remote (${whoAmI.number}) numbers do not match, updating local.") changeNumberRepository.changeLocalNumber(whoAmI.number, PNI.parseOrThrow(whoAmI.pni)) .map { true } } } .observeOn(AndroidSchedulers.mainThread()) .subscribeBy(onSuccess = { onChangeStatusConfirmed() }, onError = this::onFailedToGetChangeNumberStatus) ) } private fun onChangeStatusConfirmed() { SignalStore.misc().unlockChangeNumber() MaterialAlertDialogBuilder(this) .setTitle(R.string.ChangeNumberLockActivity__change_status_confirmed) .setMessage(getString(R.string.ChangeNumberLockActivity__your_number_has_been_confirmed_as_s, PhoneNumberFormatter.prettyPrint(SignalStore.account().e164!!))) .setPositiveButton(android.R.string.ok) { _, _ -> startActivity(MainActivity.clearTop(this)) finish() } .setCancelable(false) .show() } private fun onFailedToGetChangeNumberStatus(error: Throwable) { Log.w(TAG, "Unable to determine status of change number", error) MaterialAlertDialogBuilder(this) .setTitle(R.string.ChangeNumberLockActivity__change_status_unconfirmed) .setMessage(getString(R.string.ChangeNumberLockActivity__we_could_not_determine_the_status_of_your_change_number_request, error.javaClass.simpleName)) .setPositiveButton(R.string.ChangeNumberLockActivity__retry) { _, _ -> checkWhoAmI() } .setNegativeButton(R.string.ChangeNumberLockActivity__leave) { _, _ -> finish() } .setNeutralButton(R.string.ChangeNumberLockActivity__submit_debug_log) { _, _ -> startActivity(Intent(this, SubmitDebugLogActivity::class.java)) finish() } .setCancelable(false) .show() } companion object { @JvmStatic fun createIntent(context: Context): Intent { return Intent(context, ChangeNumberLockActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_SINGLE_TOP } } } }
app/src/main/java/org/thoughtcrime/securesms/components/settings/app/changenumber/ChangeNumberLockActivity.kt
2992055281
package me.ycdev.android.lib.common.activity import android.app.Activity import android.app.Application import android.content.ComponentName import android.content.pm.ActivityInfo.LAUNCH_MULTIPLE import android.content.pm.ActivityInfo.LAUNCH_SINGLE_TASK import android.content.pm.ActivityInfo.LAUNCH_SINGLE_TOP import com.google.common.truth.Truth.assertThat import io.mockk.Runs import io.mockk.every import io.mockk.just import io.mockk.mockk import org.junit.After import org.junit.Before import org.junit.BeforeClass import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class ActivityTaskTrackerTest { @Before fun setup() { ActivityTaskTracker.reset() } @After fun tearDown() { assertThat(ActivityTaskTracker.getAllTasks()).hasSize(0) } @Test fun oneTask() { // start Activity 1 val activity1 = mockActivity(testComponent1, 10) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity1, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity1) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity1) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(1) var focusedTask = ActivityTaskTracker.getFocusedTask() assertThat(focusedTask).isNotNull() assertThat(focusedTask!!.taskId).isEqualTo(10) assertThat(focusedTask.topActivity().componentName).isEqualTo(testComponent1) // start Activity 2 val activity2 = mockActivity(testComponent2, 10) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity2, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity2) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity2) // activity 1 went to background ActivityTaskTracker.lifecycleCallback.onActivityPaused(activity1) ActivityTaskTracker.lifecycleCallback.onActivityStopped(activity1) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(2) focusedTask = ActivityTaskTracker.getFocusedTask() assertThat(focusedTask).isNotNull() assertThat(focusedTask!!.topActivity().componentName).isEqualTo(testComponent2) // start Activity 3 val activity3 = mockActivity(testComponent3, 10) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity3, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity3) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity3) // activity 2 went to background ActivityTaskTracker.lifecycleCallback.onActivityPaused(activity2) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(3) focusedTask = ActivityTaskTracker.getFocusedTask() assertThat(focusedTask).isNotNull() assertThat(focusedTask!!.topActivity().componentName).isEqualTo(testComponent3) assertThat(ActivityTaskTracker.getAllTasks()).hasSize(1) // clean up ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity3) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(2) ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity2) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(1) ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity1) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(0) } @Test fun oneTask_resumePrevious() { // start Activity 1 val activity1 = mockActivity(testComponent1, 10) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity1, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity1) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity1) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(1) var focusedTask = ActivityTaskTracker.getFocusedTask() assertThat(focusedTask).isNotNull() assertThat(focusedTask!!.taskId).isEqualTo(10) assertThat(focusedTask.topActivity().componentName).isEqualTo(testComponent1) // start Activity 2 // activity 1 went to background first ActivityTaskTracker.lifecycleCallback.onActivityPaused(activity1) val activity2 = mockActivity(testComponent2, 10) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity2, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity2) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity2) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(2) focusedTask = ActivityTaskTracker.getFocusedTask() assertThat(focusedTask).isNotNull() assertThat(focusedTask!!.topActivity().componentName).isEqualTo(testComponent2) // resume Activity 1 ActivityTaskTracker.lifecycleCallback.onActivityPaused(activity2) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity1) ActivityTaskTracker.lifecycleCallback.onActivityStopped(activity2) ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity2) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(1) focusedTask = ActivityTaskTracker.getFocusedTask() assertThat(focusedTask).isNotNull() assertThat(focusedTask!!.topActivity().componentName).isEqualTo(testComponent1) // clean up ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity1) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(0) } @Test fun twoTasks() { // start Activity 1 val activity1 = mockActivity(testComponent1, 10) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity1, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity1) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity1) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(1) var focusedTask = ActivityTaskTracker.getFocusedTask() assertThat(focusedTask).isNotNull() assertThat(focusedTask!!.taskId).isEqualTo(10) assertThat(focusedTask.topActivity().componentName).isEqualTo(testComponent1) // start Activity 2 val activity2 = mockActivity(testComponent2, 5) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity2, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity2) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity2) // activity 1 went to background ActivityTaskTracker.lifecycleCallback.onActivityPaused(activity1) ActivityTaskTracker.lifecycleCallback.onActivityStopped(activity1) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(2) focusedTask = ActivityTaskTracker.getFocusedTask() assertThat(focusedTask).isNotNull() assertThat(focusedTask!!.taskId).isEqualTo(5) assertThat(focusedTask.topActivity().componentName).isEqualTo(testComponent2) // start Activity 3 val activity3 = mockActivity(testComponent3, 10) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity3, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity3) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity3) // activity 2 went to background ActivityTaskTracker.lifecycleCallback.onActivityPaused(activity2) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(3) focusedTask = ActivityTaskTracker.getFocusedTask() assertThat(focusedTask).isNotNull() assertThat(focusedTask!!.taskId).isEqualTo(10) assertThat(focusedTask.topActivity().componentName).isEqualTo(testComponent3) assertThat(ActivityTaskTracker.getAllTasks()).hasSize(2) // clean up ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity3) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(2) ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity2) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(1) ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity1) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(0) } @Test fun getFocusedTask_none() { // start Activity 1 val activity1 = mockActivity(testComponent1, 10) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity1, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity1) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity1) val focusedTask = ActivityTaskTracker.getFocusedTask() assertThat(focusedTask).isNotNull() assertThat(focusedTask!!.taskId).isEqualTo(10) assertThat(focusedTask.topActivity().state).isEqualTo(ActivityRunningState.State.Resumed) ActivityTaskTracker.lifecycleCallback.onActivityPaused(activity1) assertThat(ActivityTaskTracker.getFocusedTask()).isNull() // clean up ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity1) } @Test fun getFocusedTask_order() { // start Activity 1 val activity1 = mockActivity(testComponent1, 10) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity1, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity1) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity1) var focusedTask = ActivityTaskTracker.getFocusedTask() assertThat(focusedTask).isNotNull() assertThat(focusedTask!!.taskId).isEqualTo(10) assertThat(focusedTask.topActivity().componentName).isEqualTo(testComponent1) // start Activity 2 (order case 1) val activity2 = mockActivity(testComponent2, 10) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity2, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity2) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity2) // activity 1 went to background ActivityTaskTracker.lifecycleCallback.onActivityPaused(activity1) ActivityTaskTracker.lifecycleCallback.onActivityStopped(activity1) focusedTask = ActivityTaskTracker.getFocusedTask() assertThat(focusedTask).isNotNull() assertThat(focusedTask!!.topActivity().componentName).isEqualTo(testComponent2) // start Activity 3 (order case 2) val activity3 = mockActivity(testComponent3, 10) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity3, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity3) // activity 2 went to background ActivityTaskTracker.lifecycleCallback.onActivityPaused(activity2) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity3) focusedTask = ActivityTaskTracker.getFocusedTask() assertThat(focusedTask).isNotNull() assertThat(focusedTask!!.topActivity().componentName).isEqualTo(testComponent3) // clean up ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity3) ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity2) ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity1) } @Test fun getFocusedTask_makeCopy() { // start Activity 1 val activity1 = mockActivity(testComponent1, 10) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity1, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity1) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity1) var focusedTask = ActivityTaskTracker.getFocusedTask() assertThat(focusedTask).isNotNull() assertThat(focusedTask!!.taskId).isEqualTo(10) assertThat(focusedTask.topActivity().state).isEqualTo(ActivityRunningState.State.Resumed) // clear the task focusedTask.popActivity(testComponent1, activity1.hashCode()) assertThat(focusedTask.isEmpty()).isTrue() // get again focusedTask = ActivityTaskTracker.getFocusedTask() assertThat(focusedTask).isNotNull() assertThat(focusedTask!!.taskId).isEqualTo(10) assertThat(focusedTask.topActivity().state).isEqualTo(ActivityRunningState.State.Resumed) // clean up ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity1) } @Test fun getAllTasks_focused_position() { // start Activity 1 val activity1 = mockActivity(testComponent1, 10) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity1, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity1) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity1) // start Activity 2 val activity2 = mockActivity(testComponent2, 5) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity2, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity2) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity2) // activity 1 went to background ActivityTaskTracker.lifecycleCallback.onActivityStopped(activity1) // start Activity 3 val activity3 = mockActivity(testComponent3, 10) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity3, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity3) // activity 2 went to background ActivityTaskTracker.lifecycleCallback.onActivityPaused(activity2) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity3) val allTasks = ActivityTaskTracker.getAllTasks() assertThat(allTasks).hasSize(2) val focusedTask = allTasks[0] assertThat(focusedTask).isNotNull() assertThat(focusedTask.taskId).isEqualTo(10) assertThat(focusedTask.topActivity().state).isEqualTo(ActivityRunningState.State.Resumed) assertThat(focusedTask.topActivity().componentName).isEqualTo(testComponent3) // clean up ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity3) ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity2) ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity1) } @Test fun getAllTasks_makeCopy() { // start Activity 1 val activity1 = mockActivity(testComponent1, 10) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity1, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity1) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity1) val allTasks = ActivityTaskTracker.getAllTasks() assertThat(allTasks).hasSize(1) assertThat(allTasks[0].taskId).isEqualTo(10) assertThat(allTasks[0].topActivity().state).isEqualTo(ActivityRunningState.State.Resumed) assertThat(allTasks[0].topActivity().componentName).isEqualTo(testComponent1) // start Activity 2 val activity2 = mockActivity(testComponent2, 5) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity2, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity2) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity2) // activity 1 went to background ActivityTaskTracker.lifecycleCallback.onActivityStopped(activity1) // start Activity 3 val activity3 = mockActivity(testComponent3, 10) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity3, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity3) // activity 2 went to background ActivityTaskTracker.lifecycleCallback.onActivityPaused(activity2) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity3) // check the preivous copied tasks again assertThat(allTasks).hasSize(1) assertThat(allTasks[0].taskId).isEqualTo(10) assertThat(allTasks[0].topActivity().state).isEqualTo(ActivityRunningState.State.Resumed) assertThat(allTasks[0].topActivity().componentName).isEqualTo(testComponent1) assertThat(ActivityTaskTracker.getAllTasks()).hasSize(2) val focusedTask = ActivityTaskTracker.getFocusedTask() assertThat(focusedTask).isNotNull() assertThat(focusedTask!!.taskId).isEqualTo(10) assertThat(focusedTask.topActivity().state).isEqualTo(ActivityRunningState.State.Resumed) assertThat(focusedTask.topActivity().componentName).isEqualTo(testComponent3) // clean up ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity3) ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity2) ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity1) } @Test fun activityTaskReparenting() { // task1 // start Activity 1 val activity1 = mockActivity(testComponent1, 10) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity1, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity1) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity1) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(1) // start Activity 2 val activity2 = mockActivity(testComponent2, 10) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity2, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity2) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity2) // activity 1 went to background ActivityTaskTracker.lifecycleCallback.onActivityStopped(activity1) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(2) // task 2 // start Activity 3 val activity3 = mockActivity(testComponent3, 5) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity3, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity3) // activity 2 went to background ActivityTaskTracker.lifecycleCallback.onActivityPaused(activity2) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity3) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(3) // start Activity 4 val taskIdProvider4 = TaskIdProvider(5) val activity4 = mockActivity(testComponent4, taskIdProvider4) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity4, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity4) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity4) // activity 3 went to background ActivityTaskTracker.lifecycleCallback.onActivityStopped(activity3) // All tasks go to background ActivityTaskTracker.lifecycleCallback.onActivityStopped(activity4) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(4) // Activity 4 was re-parented to task1 taskIdProvider4.taskId = 10 assertThat(activity4.taskId).isEqualTo(10) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity4) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity4) val allTasks = ActivityTaskTracker.getAllTasks() assertThat(allTasks).hasSize(2) assertThat(allTasks[0].taskId).isEqualTo(10) assertThat(allTasks[0].taskAffinity).isEqualTo(taskAffinity1) assertThat(allTasks[0].topActivity().state).isEqualTo(ActivityRunningState.State.Resumed) assertThat(allTasks[0].topActivity().componentName).isEqualTo(testComponent4) assertThat(allTasks[0].getActivityStack()).hasSize(3) assertThat(allTasks[1].taskId).isEqualTo(5) assertThat(allTasks[1].taskAffinity).isEqualTo(taskAffinity2) assertThat(allTasks[1].topActivity().state).isEqualTo(ActivityRunningState.State.Stopped) assertThat(allTasks[1].topActivity().componentName).isEqualTo(testComponent3) assertThat(allTasks[1].getActivityStack()).hasSize(1) // clean up ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity4) ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity2) ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity1) ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity3) } @Test fun taskClear() { // start Activity 1 val activity1 = mockActivity(testComponent1, 10) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity1, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity1) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity1) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(1) // start Activity 2 val activity2 = mockActivity(testComponent2, 10) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity2, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity2) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity2) // activity 1 went to background ActivityTaskTracker.lifecycleCallback.onActivityStopped(activity1) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(2) // start Activity 2 again and clear the task (all existing Activities will be destroyed) // Activity 1 destroyed first ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity1) ActivityTaskTracker.lifecycleCallback.onActivityPaused(activity2) // a new instance of Activity 2 created val activity2n = mockActivity(testComponent2, 10) ActivityTaskTracker.lifecycleCallback.onActivityCreated(activity2n, null) ActivityTaskTracker.lifecycleCallback.onActivityStarted(activity2n) ActivityTaskTracker.lifecycleCallback.onActivityResumed(activity2n) // old Activity 2 destroyed ActivityTaskTracker.lifecycleCallback.onActivityStopped(activity2) ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity2) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(1) ActivityTaskTracker.getAllTasks().let { allTasks -> assertThat(allTasks).hasSize(1) allTasks[0].getActivityStack().let { assertThat(it).hasSize(1) assertThat(it[0].componentName).isEqualTo(testComponent2) assertThat(it[0].state).isEqualTo(ActivityRunningState.State.Resumed) assertThat(it[0].hashCode).isEqualTo(activity2n.hashCode()) } } // clean up ActivityTaskTracker.lifecycleCallback.onActivityDestroyed(activity2n) assertThat(ActivityTaskTracker.getTotalActivitiesCount()).isEqualTo(0) } private fun mockActivity(componentName: ComponentName, taskId: Int): Activity { val activity = mockk<Activity>() every { activity.componentName } returns componentName every { activity.taskId } returns taskId return activity } private fun mockActivity(componentName: ComponentName, taskIdProvider: TaskIdProvider): Activity { val activity = mockk<Activity>() every { activity.componentName } returns componentName every { activity.taskId }.answers { taskIdProvider.taskId } return activity } private data class TaskIdProvider(var taskId: Int) companion object { private const val taskAffinity1 = "me.ycdev.test.pkg" private const val taskAffinity2 = "me.ycdev.taks2" private val testComponent1 = ComponentName("me.ycdev.test.pkg", "me.ycdev.test.clazz1") private val testMeta1 = ActivityMeta(testComponent1, taskAffinity1, LAUNCH_MULTIPLE, false) private val testComponent2 = ComponentName("me.ycdev.test.pkg", "me.ycdev.test.clazz2") private val testMeta2 = ActivityMeta(testComponent2, taskAffinity1, LAUNCH_SINGLE_TOP, false) private val testComponent3 = ComponentName("me.ycdev.test.pkg", "me.ycdev.test.clazz3") private val testMeta3 = ActivityMeta(testComponent3, taskAffinity2, LAUNCH_SINGLE_TASK, false) private val testComponent4 = ComponentName("me.ycdev.test.pkg", "me.ycdev.test.clazz4") private val testMeta4 = ActivityMeta(testComponent4, taskAffinity1, LAUNCH_MULTIPLE, true) @BeforeClass @JvmStatic fun setupClass() { ActivityMeta.initCache(testMeta1, testMeta2, testMeta3, testMeta4) val app = mockk<Application>() every { app.registerActivityLifecycleCallbacks(any()) } just Runs ActivityTaskTracker.init(app) } } }
baseLib/src/test/java/me/ycdev/android/lib/common/activity/ActivityTaskTrackerTest.kt
2288552706
/* * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.auth /** * A configuration that creates a provider based on the [AuthenticationConfig.provider] block. */ public class DynamicProviderConfig(name: String?) : AuthenticationProvider.Config(name) { private lateinit var authenticateFunction: (context: AuthenticationContext) -> Unit public fun authenticate(block: (context: AuthenticationContext) -> Unit) { authenticateFunction = block } internal fun buildProvider(): AuthenticationProvider { check(::authenticateFunction.isInitialized) { "Please configure authentication by calling authenticate() function" } return object : AuthenticationProvider(this) { override suspend fun onAuthenticate(context: AuthenticationContext) { authenticateFunction(context) } } } }
ktor-server/ktor-server-plugins/ktor-server-auth/jvmAndNix/src/io/ktor/server/auth/DynamicProviderConfig.kt
746431768
package com.czbix.v2ex import android.content.ContentProvider import android.content.ContentValues import android.content.Context import android.database.Cursor import android.database.MatrixCursor import android.graphics.drawable.Drawable import android.net.Uri import android.os.ParcelFileDescriptor import android.provider.OpenableColumns import com.bumptech.glide.RequestManager import com.bumptech.glide.request.target.CustomTarget import com.bumptech.glide.request.transition.Transition import com.czbix.v2ex.util.MiscUtils import java.io.File import java.io.IOException class ViewerProvider : ContentProvider() { override fun onCreate(): Boolean { return true } override fun query(uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor? { @Suppress("NAME_SHADOWING") var projection = projection // ContentProvider has already checked granted permissions val file = getFileForUri(uri) if (projection == null) { projection = COLUMNS } var cols = arrayOfNulls<String>(projection.size) var values = arrayOfNulls<Any>(projection.size) var i = 0 for (col in projection) { when (col) { OpenableColumns.DISPLAY_NAME -> { cols[i] = OpenableColumns.DISPLAY_NAME values[i++] = file.name } OpenableColumns.SIZE -> { cols[i] = OpenableColumns.SIZE values[i++] = file.length() } } } cols = cols.sliceArray(0 until i) values = values.sliceArray(0 until i) val cursor = MatrixCursor(cols, 1) cursor.addRow(values) return cursor } override fun getType(uri: Uri): String? { return "application/octet-stream" } override fun insert(uri: Uri, values: ContentValues?): Uri? { throw UnsupportedOperationException("No external inserts") } override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int { throw UnsupportedOperationException("No external updates") } override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int { throw UnsupportedOperationException("No external deletes") } override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? { // ContentProvider has already checked granted permissions val file = getFileForUri(uri) return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY) } private fun getFileForUri(uri: Uri): File { val path = uri.encodedPath if (path != "/image" || tempPath == null) { throw IllegalArgumentException("Invalid file path") } var file = File(tempPath) try { file = file.canonicalFile } catch (e: IOException) { throw IllegalArgumentException("Failed to resolve canonical path for $file") } return file } companion object { private const val AUTHORITY = BuildConfig.APPLICATION_ID + ".viewer" var tempPath: String? = null private val COLUMNS = arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE) fun getUriForFile(): Uri { return Uri.Builder().scheme("content") .authority(AUTHORITY).encodedPath("image").build() } fun viewImage(context: Context, glide: RequestManager, url: String) { @Suppress("NAME_SHADOWING") val url = MiscUtils.formatUrl(url) glide.downloadOnly().load(url).into(object : CustomTarget<File>() { override fun onResourceReady(resource: File, transition: Transition<in File>?) { tempPath = resource.canonicalPath val contentUri = getUriForFile() val intent = MiscUtils.getViewImageIntent(context, contentUri) context.startActivity(intent) } override fun onLoadCleared(placeholder: Drawable?) {} }) } } }
app/src/main/kotlin/com/czbix/v2ex/ViewerProvider.kt
93169846
/* * Ad Free * Copyright (c) 2017 by abertschi, www.abertschi.ch * See the file "LICENSE" for the full license governing this code. */ package ch.abertschi.adfree.util /** * Created by abertschi on 29.04.17. */ class Serializer { private object Holder { val INSTANCE = ch.abertschi.adfree.util.Serializer() } companion object { val instance: ch.abertschi.adfree.util.Serializer by lazy { ch.abertschi.adfree.util.Serializer.Holder.INSTANCE } } private val xstream: com.thoughtworks.xstream.XStream = com.thoughtworks.xstream.XStream() fun prettyPrint(obj: Any): String { return xstream.toXML(obj) } }
app/src/main/java/ch/abertschi/adfree/util/Serializer.kt
4039798698
/* package me.camdenorrb.minibus import me.camdenorrb.minibus.event.EventWatcher import me.camdenorrb.minibus.listener.ListenerPriority import me.camdenorrb.minibus.listener.MiniListener import kotlin.system.measureNanoTime open class BenchmarkEvent class GenericEvent(var called: Boolean = false) : BenchmarkEvent() class GenericEvent2<T : Any>(var called: Boolean = false) : BenchmarkEvent() fun main() { MiniBusTest().apply { setUp() eventTest() tearDown() } } class MiniBusTest: MiniListener { val miniBus = MiniBus() fun setUp() { miniBus.register(this) } fun eventTest() { val calledEvent = miniBus(TestEvent()) println("Count: ${calledEvent.count} Order: ${calledEvent.abc}") check(calledEvent.count == 6) { "Not all events were called!" } check(calledEvent.abc == "a1 a2 b1 b2 c1 c2") { "The events were not called in order!" } check(calledEvent.isCancelled) { "Event was not cancelled after the last listener!" } var totalTime = 0L val benchmarkEvent = BenchmarkEvent() val genericEventString = GenericEvent2<String>() miniBus(genericEventString) println(genericEventString.called) */ /* val genericEvent: BenchmarkEvent = GenericEvent() miniBus(genericEvent) check((genericEvent as GenericEvent).called) { "Generic event wasn't called!" } *//* */ /* Warm Up *//* for (i in 0..100_000) miniBus(benchmarkEvent) for (i in 1..1000) totalTime += measureNanoTime { miniBus(benchmarkEvent) } println("1000 * BenchEvent { Average: ${totalTime / 1000}/ns Total: $totalTime/ns }") totalTime = 0 val meow = "Meow" */ /* Warm Up *//* for (i in 0..100_000) miniBus(meow) for (i in 1..1000) totalTime += measureNanoTime { miniBus(meow) } println("1000 * NonExistent Event { Average: ${totalTime / 1000}/ns Total: $totalTime/ns }") } fun tearDown() { miniBus.cleanUp() } @EventWatcher fun onBenchMark(event: BenchmarkEvent) = Unit @EventWatcher fun onGenericEvent(event: GenericEvent) { event.called = true } @EventWatcher fun onGenericEventString(event: GenericEvent2<String>) { event.called = true } @EventWatcher fun onGenericEventInt(event: GenericEvent2<Int>) { error("Int generic event shouldn't have been called!") } @EventWatcher(ListenerPriority.FIRST) fun onTest1(event: TestEvent) { event.count++ event.abc += "a1 " } @EventWatcher(ListenerPriority.FIRST) fun onTest2(event: TestEvent) { event.count++ event.abc += "a2 " } @EventWatcher(ListenerPriority.NORMAL) fun onTest3(event: TestEvent) { event.count++ event.abc += "b1 " } @EventWatcher(ListenerPriority.NORMAL) fun onTest4(event: TestEvent) { event.count++ event.abc += "b2 " } @EventWatcher(ListenerPriority.LAST) fun onTest5(event: TestEvent) { event.count++ event.abc += "c1 " } @EventWatcher(ListenerPriority.LAST) fun onTest6(event: TestEvent) { event.count++ event.abc += "c2" event.isCancelled = true } } */
src/main/kotlin/me/camdenorrb/minibus/EasyTesting2.kt
2870957350
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package openxr.templates import org.lwjgl.generator.* import openxr.* val FB_composition_layer_secure_content = "FBCompositionLayerSecureContent".nativeClassXR("FB_composition_layer_secure_content", type = "instance", postfix = "FB") { documentation = """ The <a href="https://registry.khronos.org/OpenXR/specs/1.0/html/xrspec.html\#XR_FB_composition_layer_secure_content">XR_FB_composition_layer_secure_content</a> extension. This extension does not define a new composition layer type, but rather it provides support for the application to specify an existing composition layer type has secure content and whether it must be completely excluded from external outputs, like video or screen capture, or if proxy content must be rendered in its place. In order to enable the functionality of this extension, you <b>must</b> pass the name of the extension into #CreateInstance() via the ##XrInstanceCreateInfo{@code ::enabledExtensionNames} parameter as indicated in the <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#extensions">extensions</a> section. """ IntConstant( "The extension specification version.", "FB_composition_layer_secure_content_SPEC_VERSION".."1" ) StringConstant( "The extension name.", "FB_COMPOSITION_LAYER_SECURE_CONTENT_EXTENSION_NAME".."XR_FB_composition_layer_secure_content" ) EnumConstant( "Extends {@code XrStructureType}.", "TYPE_COMPOSITION_LAYER_SECURE_CONTENT_FB".."1000072000" ) EnumConstant( "XrCompositionLayerSecureContentFlagBitsFB", "COMPOSITION_LAYER_SECURE_CONTENT_EXCLUDE_LAYER_BIT_FB".enum(0x00000001), "COMPOSITION_LAYER_SECURE_CONTENT_REPLACE_LAYER_BIT_FB".enum(0x00000002) ) }
modules/lwjgl/openxr/src/templates/kotlin/openxr/templates/FB_composition_layer_secure_content.kt
1929898576
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.at import com.demonwav.mcdev.facet.MinecraftFacet import com.demonwav.mcdev.platform.mcp.McpModuleType import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtClassName import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtEntry import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtFieldName import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtFuncName import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtFunction import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtTypes import com.demonwav.mcdev.util.findQualifiedClass import com.demonwav.mcdev.util.getPrimitiveType import com.demonwav.mcdev.util.parseClassDescriptor import com.intellij.codeInsight.navigation.actions.GotoDeclarationHandler import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Editor import com.intellij.openapi.module.ModuleUtilCore import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiElement import com.intellij.psi.search.GlobalSearchScope class AtGotoDeclarationHandler : GotoDeclarationHandler { override fun getGotoDeclarationTargets(sourceElement: PsiElement?, offset: Int, editor: Editor): Array<out PsiElement>? { if (sourceElement?.language !== AtLanguage) { return null } val module = ModuleUtilCore.findModuleForPsiElement(sourceElement) ?: return null val instance = MinecraftFacet.getInstance(module) ?: return null val mcpModule = instance.getModuleOfType(McpModuleType) ?: return null val srgMap = mcpModule.srgManager?.srgMapNow ?: return null return when { sourceElement.node.treeParent.elementType === AtTypes.CLASS_NAME -> { val className = sourceElement.parent as AtClassName val classSrgToMcp = srgMap.mapToMcpClass(className.classNameText) val psiClass = findQualifiedClass(sourceElement.project, classSrgToMcp) ?: return null arrayOf(psiClass) } sourceElement.node.treeParent.elementType === AtTypes.FUNC_NAME -> { val funcName = sourceElement.parent as AtFuncName val function = funcName.parent as AtFunction val entry = function.parent as AtEntry val reference = srgMap.mapToMcpMethod(AtMemberReference.get(entry, function) ?: return null) val member = reference.resolveMember(sourceElement.project) ?: return null arrayOf(member) } sourceElement.node.treeParent.elementType === AtTypes.FIELD_NAME -> { val fieldName = sourceElement.parent as AtFieldName val entry = fieldName.parent as AtEntry val reference = srgMap.mapToMcpField(AtMemberReference.get(entry, fieldName) ?: return null) val member = reference.resolveMember(sourceElement.project) ?: return null arrayOf(member) } sourceElement.node.elementType === AtTypes.CLASS_VALUE -> { val className = srgMap.mapToMcpClass(parseClassDescriptor(sourceElement.text)) val psiClass = findQualifiedClass(sourceElement.project, className) ?: return null arrayOf(psiClass) } sourceElement.node.elementType === AtTypes.PRIMITIVE -> { val text = sourceElement.text if (text.length != 1) { return null } val type = getPrimitiveType(text[0]) ?: return null val boxedType = type.boxedTypeName ?: return null val psiClass = JavaPsiFacade.getInstance(sourceElement.project).findClass(boxedType, GlobalSearchScope.allScope(sourceElement.project)) ?: return null arrayOf(psiClass) } else -> null } } override fun getActionText(context: DataContext): String? = null }
src/main/kotlin/com/demonwav/mcdev/platform/mcp/at/AtGotoDeclarationHandler.kt
764505389
package graphics.scenery.backends.opengl import cleargl.GLFramebuffer import org.joml.Vector3f import graphics.scenery.Settings import graphics.scenery.backends.RenderConfigReader import graphics.scenery.utils.LazyLogger import graphics.scenery.utils.StickyBoolean import org.joml.Vector2f import org.joml.Vector4f import java.util.concurrent.ConcurrentHashMap /** * Class to contain an OpenGL render pass with name [passName] and associated configuration * [passConfig]. * * @author Ulrik Guenther <[email protected]> */ class OpenGLRenderpass(var passName: String = "", var passConfig: RenderConfigReader.RenderpassConfig) { private val logger by LazyLogger() /** OpenGL metadata */ var openglMetadata: OpenGLMetadata = OpenGLMetadata() /** Output(s) of the pass */ var output = ConcurrentHashMap<String, GLFramebuffer>() /** Inputs of the pass */ var inputs = ConcurrentHashMap<String, GLFramebuffer>() /** The default shader the pass uses */ var defaultShader: OpenGLShaderProgram? = null /** UBOs required by this pass */ var UBOs = ConcurrentHashMap<String, OpenGLUBO>() /** Class to store 2D rectangles with [width], [height] and offsets [offsetX] and [offsetY] */ data class Rect2D(var width: Int = 0, var height: Int = 0, var offsetX: Int = 0, var offsetY: Int = 0) /** Class to store viewport information, [area], and minimal/maximal depth coordinates ([minDepth] and [maxDepth]). */ data class Viewport(var area: Rect2D = Rect2D(), var minDepth: Float = 0.0f, var maxDepth: Float = 1.0f) /** Class to store clear values for color targets ([clearColor]) and depth targets ([clearDepth]) */ data class ClearValue(var clearColor: Vector4f = Vector4f(0.0f, 0.0f, 0.0f, 1.0f), var clearDepth: Float = 0.0f) /** * OpenGL metadata class, storing [scissor] areas, [renderArea]s, [clearValues], [viewports], and * for which [eye] this metadata is valid. */ data class OpenGLMetadata( var scissor: Rect2D = Rect2D(), var renderArea: Rect2D = Rect2D(), var clearValues: ClearValue = ClearValue(), var viewport: Viewport = Viewport(), var eye: Int = 0 ) /** * Initialises shader parameters for this pass from [settings], which will be serialised * into [backingBuffer]. */ fun initializeShaderParameters(settings: Settings, backingBuffer: OpenGLRenderer.OpenGLBuffer) { val ubo = OpenGLUBO(backingBuffer) ubo.name = "ShaderParameters-$passName" passConfig.parameters.forEach { entry -> // Entry could be created in Java, so we check for both Java and Kotlin strings @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") val value = if (entry.value is String || entry.value is java.lang.String) { val s = entry.value as String val split = s.split(",").map { it.trim().trimStart().toFloat() }.toFloatArray() when(split.size) { 2 -> Vector2f(split[0], split[1]) 3 -> Vector3f(split[0], split[1], split[2]) 4 -> Vector4f(split[0], split[1], split[2], split[3]) else -> throw IllegalStateException("Dont know how to handle ${split.size} elements in Shader Parameter split") } } else if (entry.value is Double) { (entry.value as Double).toFloat() } else { entry.value } val settingsKey = when { entry.key.startsWith("System") -> "System.${entry.key.substringAfter("System.")}" entry.key.startsWith("Global") -> "Renderer.${entry.key.substringAfter("Global.")}" entry.key.startsWith("Pass") -> "Renderer.$passName.${entry.key.substringAfter("Pass.")}" else -> "Renderer.$passName.${entry.key}" } if (!entry.key.startsWith("Global") && !entry.key.startsWith("Pass.") && !entry.key.startsWith("System.")) { settings.setIfUnset(settingsKey, value) } ubo.add(entry.key, { settings.get(settingsKey) }) } ubo.setOffsetFromBackingBuffer() ubo.populate() UBOs.put(ubo.name, ubo) } /** * Updates previously set-up shader parameters. * * Returns true if the parameters have been updated, and false if not. */ fun updateShaderParameters(): Boolean { var updated: Boolean by StickyBoolean(false) logger.trace("Updating shader parameters for ${this.passName}") UBOs.forEach { uboName, ubo -> if(uboName.startsWith("ShaderParameters-")) { ubo.setOffsetFromBackingBuffer() updated = ubo.populate() } } return updated } }
src/main/kotlin/graphics/scenery/backends/opengl/OpenGLRenderpass.kt
388994240
package com.stanfy.helium.handler.codegen.swift.entity.entities data class SwiftProperty(val name: String, val type: SwiftEntity, val originalName: String) { constructor(name: String, type: SwiftEntity) : this(name, type, name) }
codegen/swift/swift-entities/src/main/kotlin/com/stanfy/helium/handler/codegen/swift/entity/entities/SwiftProperty.kt
2782286269
/* * Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores> * * The MIT License (MIT) * * Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]> * Copyright (c) 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 com.github.jonathanxd.kores.base import com.github.jonathanxd.kores.Instruction import com.github.jonathanxd.kores.Instructions import com.github.jonathanxd.kores.common.MethodTypeSpec /** * For each statement. * * For each statement behavior depends on [IterationType]. For Source generation [iterationType] is useless, * but for bytecode generation it is useful because `foreach` is translated to a [ForStatement], and arrays * requires a special treatment to access length and values. * * @property variable Variable to store each element * @property iterationType Type of the iteration * @property iterableElement Element to iterate * @see IterationType */ data class ForEachStatement( val variable: VariableDeclaration, val iterationType: IterationType, val iterableElement: Instruction, override val body: Instructions ) : BodyHolder, Instruction { init { BodyHolder.checkBody(this) } override fun builder(): Builder = Builder(this) class Builder() : BodyHolder.Builder<ForEachStatement, Builder> { lateinit var variable: VariableDeclaration lateinit var iterationType: IterationType lateinit var iterableElement: Instruction var body: Instructions = Instructions.empty() constructor(defaults: ForEachStatement) : this() { this.variable = defaults.variable this.iterationType = defaults.iterationType this.iterableElement = defaults.iterableElement } /** * See [ForEachStatement.variable] */ fun variable(value: VariableDeclaration): Builder { this.variable = value return this } /** * See [ForEachStatement.iterationType] */ fun iterationType(value: IterationType): Builder { this.iterationType = value return this } /** * See [ForEachStatement.iterableElement] */ fun iterableElement(value: Instruction): Builder { this.iterableElement = value return this } override fun body(value: Instructions): Builder { this.body = value return this } override fun build(): ForEachStatement = ForEachStatement(this.variable, this.iterationType, this.iterableElement, this.body) companion object { @JvmStatic fun builder(): Builder = Builder() @JvmStatic fun builder(defaults: ForEachStatement): Builder = Builder(defaults) } } } /** * Iteration type used to generate bytecode and source code iterations. * * @property iteratorMethodSpec Specification of iterator method. * @property hasNextName Name of method which returns true if has next elements. * @property nextMethodSpec Specification of method which returns the next element. */ data class IterationType( val iteratorMethodSpec: MethodTypeSpec, val hasNextName: String, val nextMethodSpec: MethodTypeSpec ) { companion object { private val NOTHING_SPEC = MethodTypeSpec(Nothing::class.java, "", TypeSpec(Nothing::class.java)) /** * Foreach on array. Requires special handling. */ @JvmField val ARRAY = IterationType(NOTHING_SPEC, "", NOTHING_SPEC) /** * Foreach on an element which extends iterable */ @JvmField val ITERABLE_ELEMENT = IterationType( MethodTypeSpec( localization = Iterable::class.java, methodName = "iterator", typeSpec = TypeSpec(Iterator::class.java) ), "hasNext", MethodTypeSpec( localization = Iterator::class.java, methodName = "next", typeSpec = TypeSpec(Any::class.java) ) ) } }
src/main/kotlin/com/github/jonathanxd/kores/base/ForEachStatement.kt
567226701
class Point(val x: Int, val y: Int) fun foo() { val p: <caret>Point = Point(1, 2) }
plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantExplicitType/constructor.kt
4186423905
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.CleanupLocalInspectionTool import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.canDropCurlyBrackets import org.jetbrains.kotlin.idea.base.psi.dropCurlyBracketsIfPossible import org.jetbrains.kotlin.psi.KtBlockStringTemplateEntry class RemoveCurlyBracesFromTemplateInspection(@JvmField var reportWithoutWhitespace: Boolean = false) : AbstractApplicabilityBasedInspection<KtBlockStringTemplateEntry>(KtBlockStringTemplateEntry::class.java), CleanupLocalInspectionTool { override fun inspectionText(element: KtBlockStringTemplateEntry): String = KotlinBundle.message("redundant.curly.braces.in.string.template") override fun inspectionHighlightType(element: KtBlockStringTemplateEntry) = if (reportWithoutWhitespace || element.hasWhitespaceAround()) ProblemHighlightType.GENERIC_ERROR_OR_WARNING else ProblemHighlightType.INFORMATION override val defaultFixText: String get() = KotlinBundle.message("remove.curly.braces") override fun isApplicable(element: KtBlockStringTemplateEntry): Boolean = element.canDropCurlyBrackets() override fun applyTo(element: KtBlockStringTemplateEntry, project: Project, editor: Editor?) { element.dropCurlyBracketsIfPossible() } override fun createOptionsPanel() = MultipleCheckboxOptionsPanel(this).apply { addCheckbox(KotlinBundle.message("report.also.for.a.variables.without.a.whitespace.around"), "reportWithoutWhitespace") } } private fun KtBlockStringTemplateEntry.hasWhitespaceAround(): Boolean = prevSibling?.isWhitespaceOrQuote(true) == true && nextSibling?.isWhitespaceOrQuote(false) == true private fun PsiElement.isWhitespaceOrQuote(prev: Boolean): Boolean { val char = if (prev) text.lastOrNull() else text.firstOrNull() return char != null && (char.isWhitespace() || char == '"') }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RemoveCurlyBracesFromTemplateInspection.kt
4198691173
package io.github.tobyhs.weatherweight.data.model import com.squareup.moshi.JsonClass import java.time.ZonedDateTime /** * A result set for weather forecasts * * @property location location this forecast is for * @property publicationTime time of this forecast * @property forecasts daily forecasts for today and upcoming days */ @JsonClass(generateAdapter = true) data class ForecastResultSet( val location: String, val publicationTime: ZonedDateTime, val forecasts: List<DailyForecast>, )
app/src/main/java/io/github/tobyhs/weatherweight/data/model/ForecastResultSet.kt
3064157209
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ui.jcef import com.intellij.ide.IdeBundle import com.intellij.ide.caches.CachesInvalidator import com.intellij.openapi.application.ApplicationManager class JBCefAppCacheInvalidator : CachesInvalidator() { override fun getComment(): String = IdeBundle.message("jcef.local.cache.invalidate.action.description") override fun getDescription(): String = IdeBundle.message("jcef.local.cache.invalidate.checkbox.description") override fun optionalCheckboxDefaultValue(): Boolean = false override fun invalidateCaches() { ApplicationManager.getApplication().getService(JBCefAppCache::class.java).markInvalidated() } }
platform/platform-api/src/com/intellij/ui/jcef/JBCefAppCacheInvalidator.kt
4102804979
/* * 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.features.statistics import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.Rect import android.os.Build import android.print.PageRange import androidx.annotation.RequiresApi import de.dreier.mytargets.features.settings.SettingsManager import de.dreier.mytargets.shared.targets.drawable.TargetImpactAggregationDrawable import de.dreier.mytargets.utils.print.CustomPrintDocumentAdapter import de.dreier.mytargets.utils.print.DrawableToPdfWriter import de.dreier.mytargets.utils.writeToJPGFile import java.io.File import java.io.FileNotFoundException import java.io.FileOutputStream import java.io.IOException object DispersionPatternUtils { @Throws(IOException::class) fun createDispersionPatternImageFile(size: Int, file: File, statistic: ArrowStatistic) { val bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) canvas.drawColor(Color.WHITE) val target = targetFromArrowStatistics(statistic) target.bounds = Rect(0, 0, size, size) target.draw(canvas) bitmap.writeToJPGFile(file) } @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Throws(FileNotFoundException::class) fun generatePdf(f: File, statistic: ArrowStatistic) { FileOutputStream(f).use { outputStream -> val target = targetFromArrowStatistics(statistic) val pdfWriter = DrawableToPdfWriter(target) pdfWriter.layoutPages( CustomPrintDocumentAdapter.DEFAULT_RESOLUTION, CustomPrintDocumentAdapter.DEFAULT_MEDIA_SIZE ) pdfWriter.writePdfDocument(arrayOf(PageRange(0, 0)), outputStream) } } fun targetFromArrowStatistics(statistic: ArrowStatistic): TargetImpactAggregationDrawable { val target = TargetImpactAggregationDrawable(statistic.target) target.replaceShotsWith(statistic.shots) target.setAggregationStrategy(SettingsManager.statisticsDispersionPatternAggregationStrategy) target.setArrowDiameter(statistic.arrowDiameter, SettingsManager.inputArrowDiameterScale) return target } }
app/src/main/java/de/dreier/mytargets/features/statistics/DispersionPatternUtils.kt
2431095753
package org.amshove.kluent.tests.assertions.file import org.amshove.kluent.internal.assertFails import org.amshove.kluent.shouldContainLineWithString import org.amshove.kluent.shouldNotContainLineWithString import org.junit.Test import java.io.File class ShouldNotContainLineWithStringShould { private val file = File("test") @Test fun passWhenFileDoesNotContainsLineWithString() { file.useFile { it.shouldNotContainLineWithString("brown dog") } } @Test fun failWhenFileContainsLineWithString() { assertFails { file.shouldNotContainLineWithString("lazy dog") } } }
jvm/src/test/kotlin/org/amshove/kluent/tests/assertions/file/ShouldNotContainLineWithStringShould.kt
3823596751
package org.amshove.kluent.tests.assertions.time.localtime import org.amshove.kluent.shouldBeInMinute import java.time.LocalTime import kotlin.test.Test import kotlin.test.assertFails class ShouldBeInMinuteShould { val loginTime = LocalTime.of(15, 40) @Test fun passWhenTestingATimeWithinTheSameMinute() { loginTime shouldBeInMinute 40 } @Test fun failWhenTestingATimeOutsideTheMinute() { assertFails { loginTime shouldBeInMinute 30 } assertFails { loginTime shouldBeInMinute 41 } } }
jvm/src/test/kotlin/org/amshove/kluent/tests/assertions/time/localtime/ShouldBeInMinuteShould.kt
2709766853
// snippet-sourcedescription:[CreateInstance.kt demonstrates how to create an Amazon Elastic Compute Cloud (Amazon EC2) instance.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[Amazon EC2] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.ec2 // snippet-start:[ec2.kotlin.create_instance.import] import aws.sdk.kotlin.services.ec2.Ec2Client import aws.sdk.kotlin.services.ec2.model.CreateTagsRequest import aws.sdk.kotlin.services.ec2.model.InstanceType import aws.sdk.kotlin.services.ec2.model.RunInstancesRequest import aws.sdk.kotlin.services.ec2.model.Tag import kotlin.system.exitProcess // snippet-end:[ec2.kotlin.create_instance.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(args: Array<String>) { val usage = """ Usage: <name> <amiId> Where: name - An instance name that you can obtain from the AWS Management Console (for example, ami-xxxxxx5c8b987b1a0). amiId - An Amazon Machine Image (AMI) value that you can obtain from the AWS Management Console (for example, i-xxxxxx2734106d0ab). """ if (args.size != 2) { println(usage) exitProcess(0) } val name = args[0] val amiId = args[1] createEC2Instance(name, amiId) } // snippet-start:[ec2.kotlin.create_instance.main] suspend fun createEC2Instance(name: String, amiId: String): String? { val request = RunInstancesRequest { imageId = amiId instanceType = InstanceType.T1Micro maxCount = 1 minCount = 1 } Ec2Client { region = "us-west-2" }.use { ec2 -> val response = ec2.runInstances(request) val instanceId = response.instances?.get(0)?.instanceId val tag = Tag { key = "Name" value = name } val requestTags = CreateTagsRequest { resources = listOf(instanceId.toString()) tags = listOf(tag) } ec2.createTags(requestTags) println("Successfully started EC2 Instance $instanceId based on AMI $amiId") return instanceId } } // snippet-end:[ec2.kotlin.create_instance.main]
kotlin/services/ec2/src/main/kotlin/com/kotlin/ec2/CreateInstance.kt
333392641
import org.junit.Assert import org.junit.Test import koans.util.inEquals class TestStringAndMapBuilders { @Test fun testBuildMap() { val map: Map<Int, String> = buildMap { put(0, "0") for (i in 1..10) { put(i, "$i") } } val expected = hashMapOf<Int, String>() for (i in 0..10) { expected[i] = "$i" } Assert.assertEquals("Map should be filled with the right values".inEquals(), expected, map) } }
lesson5/task2/src/tests.kt
3286647293
package com.esafirm.androidplayground.androidarch.room.database import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.PrimaryKey @Entity( tableName = "car", foreignKeys = [ForeignKey( entity = User::class, parentColumns = ["userId"], childColumns = ["owner"] )] ) data class Car( @PrimaryKey(autoGenerate = true) val carId: Int? = null, val name: String, val owner: Int )
app/src/main/java/com/esafirm/androidplayground/androidarch/room/database/Car.kt
1869246415
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.log.visible import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.Computable import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.containers.ContainerUtil import com.intellij.util.ui.UIUtil import com.intellij.vcs.log.* import com.intellij.vcs.log.data.* import com.intellij.vcs.log.data.index.IndexDataGetter import com.intellij.vcs.log.data.index.VcsLogIndex import com.intellij.vcs.log.graph.PermanentGraph import com.intellij.vcs.log.graph.VisibleGraph import com.intellij.vcs.log.graph.api.permanent.PermanentGraphInfo import com.intellij.vcs.log.graph.impl.facade.PermanentGraphImpl import com.intellij.vcs.log.graph.utils.DfsWalk import com.intellij.vcs.log.history.FileNamesData import com.intellij.vcs.log.history.removeTrivialMerges import com.intellij.vcs.log.impl.HashImpl import com.intellij.vcs.log.util.* import com.intellij.vcs.log.util.VcsLogUtil.FULL_HASH_LENGTH import com.intellij.vcs.log.util.VcsLogUtil.SHORT_HASH_LENGTH import com.intellij.vcs.log.visible.filters.VcsLogFilterObject import com.intellij.vcs.log.visible.filters.VcsLogFilterObject.fromHashes import com.intellij.vcs.log.visible.filters.with import com.intellij.vcs.log.visible.filters.without import gnu.trove.TIntHashSet import java.util.stream.Collectors class VcsLogFiltererImpl(private val logProviders: Map<VirtualFile, VcsLogProvider>, private val storage: VcsLogStorage, private val topCommitsDetailsCache: TopCommitsCache, private val commitDetailsGetter: DataGetter<out VcsFullCommitDetails>, private val index: VcsLogIndex) : VcsLogFilterer { override fun canFilterEmptyPack(filters: VcsLogFilterCollection): Boolean = false override fun filter(dataPack: DataPack, sortType: PermanentGraph.SortType, allFilters: VcsLogFilterCollection, commitCount: CommitCountStage): Pair<VisiblePack, CommitCountStage> { val hashFilter = allFilters.get(VcsLogFilterCollection.HASH_FILTER) val filters = allFilters.without(VcsLogFilterCollection.HASH_FILTER) val start = System.currentTimeMillis() if (hashFilter != null && !hashFilter.hashes.isEmpty()) { // hashes should be shown, no matter if they match other filters or not val hashFilterResult = applyHashFilter(dataPack, hashFilter.hashes, sortType, commitCount) if (hashFilterResult != null) { LOG.debug(StopWatch.formatTime(System.currentTimeMillis() - start) + " for filtering by " + hashFilterResult.first.filters) return hashFilterResult } } val visibleRoots = VcsLogUtil.getAllVisibleRoots(dataPack.logProviders.keys, filters) var matchingHeads = getMatchingHeads(dataPack.refsModel, visibleRoots, filters) val rangeFilters = allFilters.get(VcsLogFilterCollection.RANGE_FILTER) val commitCandidates: TIntHashSet? val forceFilterByVcs: Boolean if (rangeFilters != null) { /* If we have both a range filter and a branch filter (e.g. `183\nmaster..feature`) they should be united: the graph should show both commits contained in the range, and commits reachable from branches. But the main filtering logic is opposite: matchingHeads + some other filter => makes the intersection of commits. To overcome this logic for the range filter case, we are not using matchingHeads, but are collecting all commits reachable from matchingHeads, and unite them with commits belonging to the range. */ val branchFilter = filters.get(VcsLogFilterCollection.BRANCH_FILTER) val revisionFilter = filters.get(VcsLogFilterCollection.REVISION_FILTER) val explicitMatchingHeads = getMatchingHeads(dataPack.refsModel, visibleRoots, branchFilter, revisionFilter) val commitsReachableFromHeads = if (explicitMatchingHeads != null) collectCommitsReachableFromHeads(dataPack, explicitMatchingHeads) else TIntHashSet() val commitsForRangeFilter = filterByRange(dataPack, rangeFilters) if (commitsForRangeFilter != null) { commitCandidates = TroveUtil.union(listOf(commitsReachableFromHeads, commitsForRangeFilter)) forceFilterByVcs = false } else { commitCandidates = null forceFilterByVcs = true } /* At the same time, the root filter should intersect with the range filter (and the branch filter), therefore we take matching heads from the root filter, but use reachable commits set for the branch filter. */ val matchingHeadsFromRoots = getMatchingHeads(dataPack.refsModel, visibleRoots) matchingHeads = matchingHeadsFromRoots } else { commitCandidates = null forceFilterByVcs = false } val filterResult = filterByDetails(dataPack, filters, commitCount, visibleRoots, matchingHeads, commitCandidates, forceFilterByVcs) val visibleGraph = createVisibleGraph(dataPack, sortType, matchingHeads, filterResult.matchingCommits, filterResult.fileNamesData) val visiblePack = VisiblePack(dataPack, visibleGraph, filterResult.canRequestMore, filters) LOG.debug(StopWatch.formatTime(System.currentTimeMillis() - start) + " for filtering by " + filters) return Pair(visiblePack, filterResult.commitCount) } private fun collectCommitsReachableFromHeads(dataPack: DataPack, matchingHeads: Set<Int>): TIntHashSet { @Suppress("UNCHECKED_CAST") val permanentGraph = dataPack.permanentGraph as? PermanentGraphInfo<Int> ?: return TIntHashSet() val startIds = matchingHeads.map { permanentGraph.permanentCommitsInfo.getNodeId(it) } val result = TIntHashSet() DfsWalk(startIds, permanentGraph.linearGraph).walk(true) { node: Int -> result.add(permanentGraph.permanentCommitsInfo.getCommitId(node)) true } return result } fun createVisibleGraph(dataPack: DataPack, sortType: PermanentGraph.SortType, matchingHeads: Set<Int>?, matchingCommits: Set<Int>?, fileNamesData: FileNamesData? = null): VisibleGraph<Int> { return if (matchingHeads.matchesNothing() || matchingCommits.matchesNothing()) { EmptyVisibleGraph.getInstance() } else { val permanentGraph = dataPack.permanentGraph if (permanentGraph !is PermanentGraphImpl || fileNamesData == null) { permanentGraph.createVisibleGraph(sortType, matchingHeads, matchingCommits) } else { permanentGraph.createVisibleGraph(sortType, matchingHeads, matchingCommits) { controller, permanentGraphInfo -> removeTrivialMerges(controller, permanentGraphInfo, fileNamesData) { trivialMerges -> LOG.debug("Removed ${trivialMerges.size} trivial merges") } } } } } private fun filterByDetails(dataPack: DataPack, filters: VcsLogFilterCollection, commitCount: CommitCountStage, visibleRoots: Collection<VirtualFile>, matchingHeads: Set<Int>?, commitCandidates: TIntHashSet?, forceFilterByVcs: Boolean): FilterByDetailsResult { val detailsFilters = filters.detailsFilters if (!forceFilterByVcs && detailsFilters.isEmpty()) { val matchingCommits = if (commitCandidates != null) TroveUtil.createJavaSet(commitCandidates) else null return FilterByDetailsResult(matchingCommits, false, commitCount) } val dataGetter = index.dataGetter val (rootsForIndex, rootsForVcs) = if (dataGetter != null && dataGetter.canFilter(detailsFilters) && !forceFilterByVcs) { visibleRoots.partition { index.isIndexed(it) } } else { Pair(emptyList(), visibleRoots.toList()) } val (filteredWithIndex, namesData) = if (rootsForIndex.isNotEmpty()) filterWithIndex(dataGetter!!, detailsFilters, commitCandidates) else Pair(null, null) if (rootsForVcs.isEmpty()) return FilterByDetailsResult(filteredWithIndex, false, commitCount, namesData) val filterAllWithVcs = rootsForVcs.containsAll(visibleRoots) val filtersForVcs = if (filterAllWithVcs) filters else filters.with(VcsLogFilterObject.fromRoots(rootsForVcs)) val headsForVcs = if (filterAllWithVcs) matchingHeads else getMatchingHeads(dataPack.refsModel, rootsForVcs, filtersForVcs) val filteredWithVcs = filterWithVcs(dataPack.permanentGraph, filtersForVcs, headsForVcs, commitCount, commitCandidates) val filteredCommits: Set<Int>? = union(filteredWithIndex, filteredWithVcs.matchingCommits) return FilterByDetailsResult(filteredCommits, filteredWithVcs.canRequestMore, filteredWithVcs.commitCount, namesData) } private fun filterByRange(dataPack: DataPack, rangeFilter: VcsLogRangeFilter): TIntHashSet? { val set = TIntHashSet() for (range in rangeFilter.ranges) { var rangeResolvedAnywhere = false for ((root, _) in logProviders) { val resolvedRange = resolveCommits(dataPack, root, range) if (resolvedRange != null) { val commits = getCommitsByRange(dataPack, root, resolvedRange) if (commits == null) return null // error => will be handled by the VCS provider else TroveUtil.addAll(set, commits) rangeResolvedAnywhere = true } } // If a range is resolved in some roots, but not all of them => skip others and handle those which know about the range. // Otherwise, if none of the roots know about the range => return null and let VcsLogProviders handle the range if (!rangeResolvedAnywhere) { LOG.warn("Range limits unresolved for: $range") return null } } return set } private fun resolveCommits(dataPack: DataPack, root: VirtualFile, range: VcsLogRangeFilter.RefRange): Pair<CommitId, CommitId>? { val from = resolveCommit(dataPack, root, range.exclusiveRef) val to = resolveCommit(dataPack, root, range.inclusiveRef) if (from == null || to == null) { LOG.debug("Range limits unresolved for: $range in $root") return null } return from to to } private fun getCommitsByRange(dataPack: DataPack, root: VirtualFile, range: Pair<CommitId, CommitId>): TIntHashSet? { val fromIndex = storage.getCommitIndex(range.first.hash, root) val toIndex = storage.getCommitIndex(range.second.hash, root) return dataPack.subgraphDifference(toIndex, fromIndex) } private fun resolveCommit(dataPack: DataPack, root: VirtualFile, refName: String): CommitId? { if (refName.length == FULL_HASH_LENGTH && VcsLogUtil.HASH_REGEX.matcher(refName).matches()) { return CommitId(HashImpl.build(refName), root) } val ref = dataPack.refsModel.findBranch(refName, root) return if (ref != null) { CommitId(ref.commitHash, root) } else if (refName.length >= SHORT_HASH_LENGTH && VcsLogUtil.HASH_REGEX.matcher(refName).matches()) { // don't search for too short hashes: high probability to treat a ref, existing not in all roots, as a hash storage.findCommitId(CommitIdByStringCondition(refName)) } else null } private fun filterWithIndex(dataGetter: IndexDataGetter, detailsFilters: List<VcsLogDetailsFilter>, commitCandidates: TIntHashSet?): Pair<Set<Int>?, FileNamesData?> { val structureFilter = detailsFilters.filterIsInstance(VcsLogStructureFilter::class.java).singleOrNull() ?: return Pair(dataGetter.filter(detailsFilters, commitCandidates), null) val namesData = dataGetter.createFileNamesData(structureFilter.files) val candidates = TroveUtil.intersect(TroveUtil.createTroveSet(namesData.getCommits()), commitCandidates) val filtersWithoutStructure = detailsFilters.filterNot { it is VcsLogStructureFilter } if (filtersWithoutStructure.isEmpty()) return Pair(TroveUtil.createJavaSet(candidates), namesData) return Pair(dataGetter.filter(filtersWithoutStructure, candidates), namesData) } private fun filterWithVcs(graph: PermanentGraph<Int>, filters: VcsLogFilterCollection, matchingHeads: Set<Int>?, commitCount: CommitCountStage, commitCandidates: TIntHashSet?): FilterByDetailsResult { var commitCountToTry = commitCount if (commitCountToTry == CommitCountStage.INITIAL) { val commitsFromMemory = filterDetailsInMemory(graph, filters.detailsFilters, matchingHeads, commitCandidates).toCommitIndexes() if (commitsFromMemory.size >= commitCountToTry.count) { return FilterByDetailsResult(commitsFromMemory, true, commitCountToTry) } commitCountToTry = commitCountToTry.next() } try { val commitsFromVcs = filteredDetailsInVcs(logProviders, filters, commitCountToTry.count).toCommitIndexes() return FilterByDetailsResult(commitsFromVcs, commitsFromVcs.size >= commitCountToTry.count, commitCountToTry) } catch (e: VcsException) { //TODO show an error balloon or something else for non-ea guys. LOG.error(e) return FilterByDetailsResult(emptySet(), true, commitCountToTry) } } @Throws(VcsException::class) private fun filteredDetailsInVcs(providers: Map<VirtualFile, VcsLogProvider>, filterCollection: VcsLogFilterCollection, maxCount: Int): Collection<CommitId> { val commits = mutableListOf<CommitId>() val visibleRoots = VcsLogUtil.getAllVisibleRoots(providers.keys, filterCollection) for (root in visibleRoots) { val userFilter = filterCollection.get(VcsLogFilterCollection.USER_FILTER) if (userFilter != null && userFilter.getUsers(root).isEmpty()) { // there is a structure or user filter, but it doesn't match this root continue } val filesForRoot = VcsLogUtil.getFilteredFilesForRoot(root, filterCollection) val rootSpecificCollection = if (filesForRoot.isEmpty()) { filterCollection.without(VcsLogFilterCollection.STRUCTURE_FILTER) } else { filterCollection.with(VcsLogFilterObject.fromPaths(filesForRoot)) } val matchingCommits = providers[root]!!.getCommitsMatchingFilter(root, rootSpecificCollection, maxCount) commits.addAll(matchingCommits.map { commit -> CommitId(commit.id, root) }) } return commits } private fun applyHashFilter(dataPack: DataPack, hashes: Collection<String>, sortType: PermanentGraph.SortType, commitCount: CommitCountStage): Pair<VisiblePack, CommitCountStage>? { val hashFilterResult = hashSetOf<Int>() for (partOfHash in hashes) { if (partOfHash.length == FULL_HASH_LENGTH) { val hash = HashImpl.build(partOfHash) for (root in dataPack.logProviders.keys) { if (storage.containsCommit(CommitId(hash, root))) { hashFilterResult.add(storage.getCommitIndex(hash, root)) } } } else { val commitId = storage.findCommitId(CommitIdByStringCondition(partOfHash)) if (commitId != null) hashFilterResult.add(storage.getCommitIndex(commitId.hash, commitId.root)) } } if (!Registry.`is`("vcs.log.filter.messages.by.hash")) { if (hashFilterResult.isEmpty()) return null val visibleGraph = dataPack.permanentGraph.createVisibleGraph(sortType, null, hashFilterResult) val visiblePack = VisiblePack(dataPack, visibleGraph, false, VcsLogFilterObject.collection(fromHashes(hashes))) return Pair(visiblePack, CommitCountStage.ALL) } val textFilter = VcsLogFilterObject.fromPatternsList(ArrayList(hashes), false) val textFilterResult = filterByDetails(dataPack, VcsLogFilterObject.collection(textFilter), commitCount, dataPack.logProviders.keys, null, null, false) if (hashFilterResult.isEmpty() && textFilterResult.matchingCommits.matchesNothing()) return null val filterResult = union(textFilterResult.matchingCommits, hashFilterResult) val visibleGraph = dataPack.permanentGraph.createVisibleGraph(sortType, null, filterResult) val visiblePack = VisiblePack(dataPack, visibleGraph, textFilterResult.canRequestMore, VcsLogFilterObject.collection(fromHashes(hashes), textFilter)) return Pair(visiblePack, textFilterResult.commitCount) } fun getMatchingHeads(refs: RefsModel, roots: Collection<VirtualFile>, filters: VcsLogFilterCollection): Set<Int>? { val branchFilter = filters.get(VcsLogFilterCollection.BRANCH_FILTER) val revisionFilter = filters.get(VcsLogFilterCollection.REVISION_FILTER) if (branchFilter == null && revisionFilter == null && filters.get(VcsLogFilterCollection.ROOT_FILTER) == null && filters.get(VcsLogFilterCollection.STRUCTURE_FILTER) == null) { return null } if (revisionFilter != null) { if (branchFilter == null) { return getMatchingHeads(roots, revisionFilter) } return getMatchingHeads(refs, roots, branchFilter).union(getMatchingHeads(roots, revisionFilter)) } if (branchFilter == null) return getMatchingHeads(refs, roots) return getMatchingHeads(refs, roots, branchFilter) } private fun getMatchingHeads(refs: RefsModel, roots: Collection<VirtualFile>, branchFilter: VcsLogBranchFilter?, revisionFilter: VcsLogRevisionFilter?): Set<Int>? { if (branchFilter == null && revisionFilter == null) return null val branchMatchingHeads = if (branchFilter != null) getMatchingHeads(refs, roots, branchFilter) else emptySet() val revisionMatchingHeads = if (revisionFilter != null) getMatchingHeads(roots, revisionFilter) else emptySet() return branchMatchingHeads.union(revisionMatchingHeads) } private fun getMatchingHeads(refsModel: RefsModel, roots: Collection<VirtualFile>, filter: VcsLogBranchFilter): Set<Int> { return mapRefsForRoots(refsModel, roots) { refs -> refs.streamBranches().filter { filter.matches(it.name) }.collect(Collectors.toList()) }.toReferencedCommitIndexes() } private fun getMatchingHeads(roots: Collection<VirtualFile>, filter: VcsLogRevisionFilter): Set<Int> { return filter.heads.filter { roots.contains(it.root) }.toCommitIndexes() } private fun getMatchingHeads(refsModel: RefsModel, roots: Collection<VirtualFile>): Set<Int> { return mapRefsForRoots(refsModel, roots) { refs -> refs.commits } } private fun <T> mapRefsForRoots(refsModel: RefsModel, roots: Collection<VirtualFile>, mapping: (CompressedRefs) -> Iterable<T>) = refsModel.allRefsByRoot.filterKeys { roots.contains(it) }.values.flatMapTo(mutableSetOf(), mapping) private fun filterDetailsInMemory(permanentGraph: PermanentGraph<Int>, detailsFilters: List<VcsLogDetailsFilter>, matchingHeads: Set<Int>?, commitCandidates: TIntHashSet?): Collection<CommitId> { val result = mutableListOf<CommitId>() for (commit in permanentGraph.allCommits) { if (commitCandidates == null || commitCandidates.contains(commit.id)) { val data = getDetailsFromCache(commit.id) ?: // no more continuous details in the cache break if (matchesAllFilters(data, permanentGraph, detailsFilters, matchingHeads)) { result.add(CommitId(data.id, data.root)) } } } return result } private fun matchesAllFilters(commit: VcsCommitMetadata, permanentGraph: PermanentGraph<Int>, detailsFilters: List<VcsLogDetailsFilter>, matchingHeads: Set<Int>?): Boolean { val matchesAllDetails = detailsFilters.all { filter -> filter.matches(commit) } return matchesAllDetails && matchesAnyHead(permanentGraph, commit, matchingHeads) } private fun matchesAnyHead(permanentGraph: PermanentGraph<Int>, commit: VcsCommitMetadata, matchingHeads: Set<Int>?): Boolean { if (matchingHeads == null) { return true } // TODO O(n^2) val commitIndex = storage.getCommitIndex(commit.id, commit.root) return ContainerUtil.intersects(permanentGraph.getContainingBranches(commitIndex), matchingHeads) } private fun getDetailsFromCache(commitIndex: Int): VcsCommitMetadata? { return topCommitsDetailsCache.get(commitIndex) ?: UIUtil.invokeAndWaitIfNeeded( Computable<VcsCommitMetadata> { commitDetailsGetter.getCommitDataIfAvailable(commitIndex) }) } private fun Collection<CommitId>.toCommitIndexes(): Set<Int> { return this.mapTo(mutableSetOf()) { commitId -> storage.getCommitIndex(commitId.hash, commitId.root) } } private fun Collection<VcsRef>.toReferencedCommitIndexes(): Set<Int> { return this.mapTo(mutableSetOf()) { ref -> storage.getCommitIndex(ref.commitHash, ref.root) } } } private val LOG = Logger.getInstance(VcsLogFiltererImpl::class.java) private data class FilterByDetailsResult(val matchingCommits: Set<Int>?, val canRequestMore: Boolean, val commitCount: CommitCountStage, val fileNamesData: FileNamesData? = null) fun areFiltersAffectedByIndexing(filters: VcsLogFilterCollection, roots: List<VirtualFile>): Boolean { val detailsFilters = filters.detailsFilters if (detailsFilters.isEmpty()) return false val affectedRoots = VcsLogUtil.getAllVisibleRoots(roots, filters) val needsIndex = affectedRoots.isNotEmpty() if (needsIndex) { LOG.debug("$filters are affected by indexing of $affectedRoots") } return needsIndex } internal fun <T> Collection<T>?.matchesNothing(): Boolean { return this != null && this.isEmpty() } internal fun <T> union(c1: Set<T>?, c2: Set<T>?): Set<T>? { if (c1 == null) return c2 if (c2 == null) return c1 return c1.union(c2) }
platform/vcs-log/impl/src/com/intellij/vcs/log/visible/VcsLogFiltererImpl.kt
547008949
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.base.util.caching import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.libraries.Library import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener import com.intellij.workspaceModel.storage.EntityChange import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.VersionedStorageChange import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.bridgeEntities.api.LibraryEntity import com.intellij.workspaceModel.storage.bridgeEntities.api.ModuleEntity abstract class WorkspaceEntityChangeListener<Entity : WorkspaceEntity, Value : Any>( protected val project: Project, private val afterChangeApplied: Boolean = true ) : WorkspaceModelChangeListener { protected abstract val entityClass: Class<Entity> protected abstract fun map(storage: EntityStorage, entity: Entity): Value? protected abstract fun entitiesChanged(outdated: List<Value>) final override fun beforeChanged(event: VersionedStorageChange) { if (!afterChangeApplied) { handleEvent(event) } } final override fun changed(event: VersionedStorageChange) { if (afterChangeApplied) { handleEvent(event) } } private fun handleEvent(event: VersionedStorageChange) { val storageBefore = event.storageBefore val changes = event.getChanges(entityClass).ifEmpty { return } val outdatedEntities: List<Value> = changes.asSequence() .mapNotNull(EntityChange<Entity>::oldEntity) .mapNotNull { map(storageBefore, it) } .toList() if (outdatedEntities.isNotEmpty()) { entitiesChanged(outdatedEntities) } } } abstract class ModuleEntityChangeListener(project: Project, afterChangeApplied: Boolean = true) : WorkspaceEntityChangeListener<ModuleEntity, Module>(project, afterChangeApplied) { override val entityClass: Class<ModuleEntity> get() = ModuleEntity::class.java override fun map(storage: EntityStorage, entity: ModuleEntity): Module? = storage.findModuleByEntityWithHack(entity, project) } abstract class LibraryEntityChangeListener(project: Project, afterChangeApplied: Boolean = true) : WorkspaceEntityChangeListener<LibraryEntity, Library>(project, afterChangeApplied) { override val entityClass: Class<LibraryEntity> get() = LibraryEntity::class.java override fun map(storage: EntityStorage, entity: LibraryEntity): Library? = storage.findLibraryByEntityWithHack(entity, project) }
plugins/kotlin/base/util/src/org/jetbrains/kotlin/idea/base/util/caching/WorkspaceEntityChangeListener.kt
148624469
// 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.j2k.post.processing.inference.nullability import javaslang.control.Option import org.jetbrains.kotlin.descriptors.ConstructorDescriptor import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isNullExpression import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.* import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.resolve.dataFlowValueFactory import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValue import org.jetbrains.kotlin.resolve.calls.smartcasts.Nullability import org.jetbrains.kotlin.resolve.jvm.checkers.mustNotBeNull import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.isNullable private fun <T> Option<T>.getOrNull(): T? = getOrElse(null as T?) class NullabilityBoundTypeEnhancer(private val resolutionFacade: ResolutionFacade) : BoundTypeEnhancer() { override fun enhance( expression: KtExpression, boundType: BoundType, inferenceContext: InferenceContext ): BoundType = when { expression.isNullExpression() -> WithForcedStateBoundType(boundType, State.UPPER) expression is KtCallExpression -> enhanceCallExpression(expression, boundType, inferenceContext) expression is KtQualifiedExpression && expression.selectorExpression is KtCallExpression -> enhanceCallExpression(expression.selectorExpression as KtCallExpression, boundType, inferenceContext) expression is KtNameReferenceExpression -> boundType.enhanceWith(expression.smartCastEnhancement()) expression is KtLambdaExpression -> WithForcedStateBoundType(boundType, State.LOWER) else -> boundType } private fun enhanceCallExpression( expression: KtCallExpression, boundType: BoundType, inferenceContext: InferenceContext ): BoundType { if (expression.resolveToCall(resolutionFacade)?.candidateDescriptor is ConstructorDescriptor) { return WithForcedStateBoundType(boundType, State.LOWER) } val resolved = expression.calleeExpression?.mainReference?.resolve() ?: return boundType if (inferenceContext.isInConversionScope(resolved)) return boundType return boundType.enhanceWith(expression.getExternallyAnnotatedForcedState()) } override fun enhanceKotlinType( type: KotlinType, boundType: BoundType, allowLowerEnhancement: Boolean, inferenceContext: InferenceContext ): BoundType { if (type.arguments.size != boundType.typeParameters.size) return boundType val inner = BoundTypeImpl( boundType.label, boundType.typeParameters.zip(type.arguments) { typeParameter, typeArgument -> TypeParameter( enhanceKotlinType( typeArgument.type, typeParameter.boundType, allowLowerEnhancement, inferenceContext ), typeParameter.variance ) } ) val enhancement = when { type.isMarkedNullable -> State.UPPER allowLowerEnhancement -> State.LOWER else -> null } return inner.enhanceWith(enhancement) } private fun KtReferenceExpression.smartCastEnhancement() = analyzeExpressionUponTheTypeInfo { dataFlowValue, dataFlowInfo, _ -> if (dataFlowInfo.completeNullabilityInfo.get(dataFlowValue)?.getOrNull() == Nullability.NOT_NULL) State.LOWER else null } private inline fun KtExpression.analyzeExpressionUponTheTypeInfo(analyzer: (DataFlowValue, DataFlowInfo, KotlinType) -> State?): State? { val bindingContext = analyze(resolutionFacade) val type = getType(bindingContext) ?: return null val dataFlowValue = resolutionFacade.dataFlowValueFactory .createDataFlowValue(this, type, bindingContext, resolutionFacade.moduleDescriptor) val dataFlowInfo = bindingContext[BindingContext.EXPRESSION_TYPE_INFO, this]?.dataFlowInfo ?: return null return analyzer(dataFlowValue, dataFlowInfo, type) } private fun KtExpression.getExternallyAnnotatedForcedState() = analyzeExpressionUponTheTypeInfo { dataFlowValue, dataFlowInfo, type -> if (!type.isNullable()) return@analyzeExpressionUponTheTypeInfo State.LOWER when { dataFlowInfo.completeNullabilityInfo.get(dataFlowValue)?.getOrNull() == Nullability.NOT_NULL -> State.LOWER type.isExternallyAnnotatedNotNull(dataFlowInfo, dataFlowValue) -> State.LOWER else -> null } } private fun KotlinType.isExternallyAnnotatedNotNull(dataFlowInfo: DataFlowInfo, dataFlowValue: DataFlowValue): Boolean = mustNotBeNull()?.isFromJava == true && dataFlowInfo.getStableNullability(dataFlowValue).canBeNull() }
plugins/kotlin/j2k/post-processing/src/org/jetbrains/kotlin/idea/j2k/post/processing/inference/nullability/NullabilityBoundTypeEnhancer.kt
2734273478
package com.werb.moretype.multi import android.Manifest import android.app.Activity import android.content.Intent import android.os.Bundle import android.text.TextUtils import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import com.werb.library.MoreAdapter import com.werb.library.link.MultiLink import com.werb.library.link.RegisterItem import com.werb.moretype.R import com.werb.moretype.TitleViewHolder import com.werb.moretype.Utils import com.werb.moretype.data.DataServer import com.werb.permissionschecker.PermissionChecker import com.werb.pickphotoview.PickPhotoView import com.werb.pickphotoview.util.PickConfig import kotlinx.android.synthetic.main.activity_multi_register.* import kotlinx.android.synthetic.main.widget_view_message_input.* /** * Created by wanbo on 2017/7/14. */ class MultiRegisterActivity : AppCompatActivity() { val PERMISSIONS = arrayOf(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE) private var permissionChecker: PermissionChecker? = null private val adapter = MoreAdapter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_multi_register) // permission check permissionChecker = PermissionChecker(this) toolbar.setNavigationIcon(R.mipmap.ic_close_white_24dp) toolbar.setNavigationOnClickListener { finish() } multi_register_list.layoutManager = LinearLayoutManager(this) adapter.apply { register(RegisterItem(R.layout.item_view_title, TitleViewHolder::class.java)) multiRegister(object : MultiLink<Message>() { override fun link(data: Message): RegisterItem { return if (data.me){ RegisterItem(R.layout.item_view_multi_message_out, MessageOutViewHolder::class.java) }else { RegisterItem(R.layout.item_view_multi_message_in, MessageInViewHolder::class.java) } } }) attachTo(multi_register_list) } adapter.loadData(DataServer.getMultiRegisterData()) input_edit.setOnFocusChangeListener { view, hasFocus -> run { if (hasFocus) { view.postDelayed({ multi_register_list.smoothScrollToPosition(adapter.itemCount -1) }, 250) } } } layout_send.setOnClickListener(sendClick) input_image_layout.setOnClickListener(imageClick) } private val sendClick = View.OnClickListener { if (!TextUtils.isEmpty(input_edit.text.toString())) { adapter.loadData(buildSendMessageText()) input_edit.setText("") multi_register_list.smoothScrollToPosition(adapter.itemCount) it.postDelayed({ adapter.loadData(buildInMessageText()) multi_register_list.smoothScrollToPosition(adapter.itemCount) }, 200) } } private val imageClick = View.OnClickListener { permissionChecker?.let { if (it.isLackPermissions(PERMISSIONS)) { it.requestPermissions() } else { pickPhoto() } } } private fun pickPhoto() { PickPhotoView.Builder(this@MultiRegisterActivity) .setPickPhotoSize(1) .setShowCamera(true) .setSpanCount(4) .setLightStatusBar(true) .setStatusBarColor(R.color.colorTextLight) .setToolbarColor(R.color.colorTextLight) .setToolbarTextColor(R.color.colorAccent) .setSelectIconColor(R.color.colorPrimary) .setShowGif(false) .start() } private fun buildSendMessageText(): Message { return Message( "", "text", true, input_edit.text.toString(), "", "", "", "", false ) } private fun buildInMessageText(): Message { return Message( "https://avatars5.githubusercontent.com/u/12763277?v=4&s=460", "text", false, "ζ”Άεˆ°δ½ ηš„ζΆˆζ―", "", "", "", "", false ) } private fun buildSendMessageImage(url: String, size: ImageSize): Message { return Message( "", "image", true, input_edit.text.toString(), url, "", size.width.toString(), size.height.toString(), false ) } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { permissionChecker?.let { when (requestCode) { PermissionChecker.PERMISSION_REQUEST_CODE -> { if (it.hasAllPermissionsGranted(grantResults)) { pickPhoto() } } else -> { it.showDialog() } } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == 0) { return } if (data == null) { return } if (requestCode == PickConfig.PICK_PHOTO_DATA) { val selectPaths = data.getSerializableExtra(PickConfig.INTENT_IMG_LIST_SELECT) as ArrayList<*> // do something u want val path = selectPaths[0] as String val imageSize = Utils.readImageSize(path) imageSize?.let { adapter.loadData(buildSendMessageImage(path, imageSize)) multi_register_list.smoothScrollToPosition(adapter.itemCount) } } } companion object { fun startActivity(activity: Activity){ activity.startActivity(Intent(activity, MultiRegisterActivity::class.java)) } } }
app/src/main/java/com/werb/moretype/multi/MultiRegisterActivity.kt
459045500
// 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.debugger.test.mock import com.sun.jdi.* import org.jetbrains.kotlin.backend.common.output.OutputFile import org.jetbrains.kotlin.backend.common.output.OutputFileCollection import org.jetbrains.org.objectweb.asm.ClassReader import org.jetbrains.org.objectweb.asm.Opcodes import org.jetbrains.org.objectweb.asm.tree.ClassNode import org.jetbrains.org.objectweb.asm.tree.LineNumberNode import org.jetbrains.org.objectweb.asm.tree.MethodNode class SmartMockReferenceTypeContext(outputFiles: List<OutputFile>) { constructor(outputFiles: OutputFileCollection) : this(outputFiles.asList()) val virtualMachine = MockVirtualMachine() val classes = outputFiles .filter { it.relativePath.endsWith(".class") } .map { it.readClass() } private val referenceTypes: List<ReferenceType> by lazy { classes.map { SmartMockReferenceType(it, this) } } val referenceTypesByName by lazy { referenceTypes.map { Pair(it.name(), it) }.toMap() } } private fun OutputFile.readClass(): ClassNode { val classNode = ClassNode() ClassReader(asByteArray()).accept(classNode, ClassReader.EXPAND_FRAMES) return classNode } class SmartMockReferenceType(val classNode: ClassNode, private val context: SmartMockReferenceTypeContext) : ReferenceType { override fun instances(maxInstances: Long) = emptyList<ObjectReference>() override fun isPublic() = (classNode.access and Opcodes.ACC_PUBLIC) != 0 override fun classLoader() = null override fun sourceName(): String? = classNode.sourceFile override fun defaultStratum() = "Java" override fun isStatic() = (classNode.access and Opcodes.ACC_STATIC) != 0 override fun modifiers() = classNode.access override fun isProtected() = (classNode.access and Opcodes.ACC_PROTECTED) != 0 override fun isFinal() = (classNode.access and Opcodes.ACC_FINAL) != 0 override fun allLineLocations() = methodsCached.flatMap { it.allLineLocations() } override fun genericSignature(): String? = classNode.signature override fun isAbstract() = (classNode.access and Opcodes.ACC_ABSTRACT) != 0 override fun isPrepared() = true override fun name() = classNode.name.replace('/', '.') override fun isInitialized() = true override fun sourcePaths(stratum: String) = listOf(classNode.sourceFile) override fun failedToInitialize() = false override fun virtualMachine() = context.virtualMachine override fun isPrivate() = (classNode.access and Opcodes.ACC_PRIVATE) != 0 override fun signature(): String? = classNode.signature override fun sourceNames(stratum: String) = listOf(classNode.sourceFile) override fun availableStrata() = emptyList<String>() private val methodsCached by lazy { classNode.methods.map { MockMethod(it, this) } } override fun methods() = methodsCached override fun nestedTypes(): List<ReferenceType> { val fromInnerClasses = classNode.innerClasses .filter { it.outerName == classNode.name } .mapNotNull { context.classes.find { c -> it.name == c.name } } val fromOuterClasses = context.classes.filter { it.outerClass == classNode.name } return (fromInnerClasses + fromOuterClasses).distinctBy { it.name }.map { SmartMockReferenceType(it, context) } } override fun isPackagePrivate(): Boolean { return ((classNode.access and Opcodes.ACC_PUBLIC) == 0 && (classNode.access and Opcodes.ACC_PROTECTED) == 0 && (classNode.access and Opcodes.ACC_PRIVATE) == 0) } override fun isVerified() = true override fun fields() = TODO() override fun allFields() = TODO() override fun fieldByName(fieldName: String) = TODO() override fun getValue(p0: Field?) = TODO() override fun visibleFields() = TODO() override fun allLineLocations(stratum: String, sourceName: String) = TODO() override fun majorVersion() = TODO() override fun constantPoolCount() = TODO() override fun constantPool() = TODO() override fun compareTo(other: ReferenceType?) = TODO() override fun sourceDebugExtension() = TODO() override fun visibleMethods() = TODO() override fun locationsOfLine(lineNumber: Int) = TODO() override fun locationsOfLine(stratum: String, sourceName: String, lineNumber: Int) = TODO() override fun getValues(p0: List<Field>?) = TODO() override fun minorVersion() = TODO() override fun classObject() = TODO() override fun methodsByName(p0: String?) = TODO() override fun methodsByName(p0: String?, p1: String?) = TODO() override fun allMethods() = TODO() override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as SmartMockReferenceType return classNode.name == other.classNode.name } override fun hashCode(): Int { return classNode.name.hashCode() } class MockMethod(private val methodNode: MethodNode, val containingClass: SmartMockReferenceType) : Method { override fun virtualMachine() = containingClass.context.virtualMachine override fun modifiers() = methodNode.access override fun isStaticInitializer() = methodNode.name == "<clinit>" override fun isPublic() = (methodNode.access and Opcodes.ACC_PUBLIC) != 0 override fun isNative() = (methodNode.access and Opcodes.ACC_NATIVE) != 0 override fun isStatic() = (methodNode.access and Opcodes.ACC_STATIC) != 0 override fun isBridge() = (methodNode.access and Opcodes.ACC_BRIDGE) != 0 override fun isProtected() = (methodNode.access and Opcodes.ACC_PROTECTED) != 0 override fun isFinal() = (methodNode.access and Opcodes.ACC_FINAL) != 0 override fun isAbstract() = (methodNode.access and Opcodes.ACC_ABSTRACT) != 0 override fun isSynthetic() = (methodNode.access and Opcodes.ACC_SYNTHETIC) != 0 override fun isConstructor() = methodNode.name == "<init>" override fun isPrivate() = (methodNode.access and Opcodes.ACC_PRIVATE) != 0 override fun isPackagePrivate(): Boolean { return ((methodNode.access and Opcodes.ACC_PUBLIC) == 0 && (methodNode.access and Opcodes.ACC_PROTECTED) == 0 && (methodNode.access and Opcodes.ACC_PRIVATE) == 0) } override fun declaringType() = containingClass override fun name(): String? = methodNode.name override fun signature(): String? = methodNode.signature override fun location(): Location? { val instructionList = methodNode.instructions ?: return null var current = instructionList.first while (current != null) { if (current is LineNumberNode) { return MockLocation(this, current.line) } current = current.next } return null } override fun allLineLocations(): List<Location> { val instructionList = methodNode.instructions ?: return emptyList() var current = instructionList.first val locations = mutableListOf<Location>() while (current != null) { if (current is LineNumberNode) { locations += MockLocation(this, current.line) } current = current.next } return locations } override fun argumentTypeNames() = TODO() override fun arguments() = TODO() override fun allLineLocations(p0: String?, p1: String?) = TODO() override fun genericSignature() = TODO() override fun returnType() = TODO() override fun compareTo(other: Method?) = TODO() override fun isObsolete() = false override fun variablesByName(p0: String?) = TODO() override fun argumentTypes() = TODO() override fun locationOfCodeIndex(p0: Long) = TODO() override fun bytecodes() = TODO() override fun returnTypeName() = TODO() override fun locationsOfLine(p0: Int) = TODO() override fun locationsOfLine(p0: String?, p1: String?, p2: Int) = TODO() override fun variables() = TODO() override fun isVarArgs() = TODO() override fun isSynchronized() = TODO() } private class MockLocation(val method: MockMethod, val line: Int) : Location { override fun virtualMachine() = method.containingClass.context.virtualMachine override fun sourceName() = method.containingClass.sourceName() override fun lineNumber() = line override fun sourcePath() = sourceName() override fun declaringType() = method.containingClass override fun method() = method override fun sourceName(stratum: String) = TODO() override fun codeIndex() = TODO() override fun lineNumber(stratum: String) = TODO() override fun sourcePath(stratum: String) = TODO() override fun compareTo(other: Location?) = TODO() } }
plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/mock/SmartMockReferenceType.kt
3368868292
// 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.j2k.post.processing.processings import com.intellij.openapi.application.runReadAction import com.intellij.psi.PsiElement import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.idea.j2k.post.processing.ElementsBasedPostProcessing import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.BoundTypeCalculatorImpl import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ByInfoSuperFunctionsProvider import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintsCollectorAggregator import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.InferenceFacade import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.collectors.CallExpressionConstraintCollector import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.collectors.CommonConstraintsCollector import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.collectors.FunctionConstraintsCollector import org.jetbrains.kotlin.idea.j2k.post.processing.inference.mutability.* import org.jetbrains.kotlin.idea.j2k.post.processing.inference.nullability.* import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.psi.KtElement internal abstract class InferenceProcessing : ElementsBasedPostProcessing() { override fun runProcessing(elements: List<PsiElement>, converterContext: NewJ2kConverterContext) { val kotlinElements = elements.filterIsInstance<KtElement>() if (kotlinElements.isEmpty()) return val resolutionFacade = runReadAction { KotlinCacheService.getInstance(converterContext.project).getResolutionFacade(kotlinElements) } createInferenceFacade(resolutionFacade, converterContext).runOn(kotlinElements) } abstract fun createInferenceFacade( resolutionFacade: ResolutionFacade, converterContext: NewJ2kConverterContext ): InferenceFacade } internal class NullabilityInferenceProcessing : InferenceProcessing() { override fun createInferenceFacade( resolutionFacade: ResolutionFacade, converterContext: NewJ2kConverterContext ): InferenceFacade = InferenceFacade( NullabilityContextCollector(resolutionFacade, converterContext), ConstraintsCollectorAggregator( resolutionFacade, NullabilityConstraintBoundProvider(), listOf( CommonConstraintsCollector(), CallExpressionConstraintCollector(), FunctionConstraintsCollector(ByInfoSuperFunctionsProvider(resolutionFacade, converterContext)), NullabilityConstraintsCollector() ) ), BoundTypeCalculatorImpl(resolutionFacade, NullabilityBoundTypeEnhancer(resolutionFacade)), NullabilityStateUpdater(), NullabilityDefaultStateProvider() ) } internal class MutabilityInferenceProcessing : InferenceProcessing() { override fun createInferenceFacade( resolutionFacade: ResolutionFacade, converterContext: NewJ2kConverterContext ): InferenceFacade = InferenceFacade( MutabilityContextCollector(resolutionFacade, converterContext), ConstraintsCollectorAggregator( resolutionFacade, MutabilityConstraintBoundProvider(), listOf( CommonConstraintsCollector(), CallExpressionConstraintCollector(), FunctionConstraintsCollector(ByInfoSuperFunctionsProvider(resolutionFacade, converterContext)), MutabilityConstraintsCollector() ) ), MutabilityBoundTypeCalculator(resolutionFacade, MutabilityBoundTypeEnhancer()), MutabilityStateUpdater(), MutabilityDefaultStateProvider() ) }
plugins/kotlin/j2k/post-processing/src/org/jetbrains/kotlin/idea/j2k/post/processing/processings/InferenceProcessing.kt
4230490303
/* * Copyright 2020 StΓ©phane Baiget * * 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.sbgapps.scoreit.core.ui import io.uniflow.androidx.flow.AndroidDataFlow open class BaseViewModel : AndroidDataFlow()
core/src/main/kotlin/com/sbgapps/scoreit/core/ui/BaseViewModel.kt
916084331
package test import com.apollographql.apollo3.ApolloClient import com.apollographql.apollo3.annotations.ApolloExperimental import com.apollographql.apollo3.api.CompiledField import com.apollographql.apollo3.api.Executable import com.apollographql.apollo3.cache.normalized.ApolloStore import com.apollographql.apollo3.cache.normalized.api.CacheResolver import com.apollographql.apollo3.cache.normalized.api.DefaultCacheResolver import com.apollographql.apollo3.cache.normalized.api.MemoryCacheFactory import com.apollographql.apollo3.cache.normalized.store import com.apollographql.apollo3.integration.normalizer.HeroNameQuery import com.apollographql.apollo3.testing.runTest import kotlin.test.Test import kotlin.test.assertEquals @OptIn(ApolloExperimental::class) class CacheResolverTest { @Test fun cacheResolverCanResolveQuery() = runTest { val resolver = object : CacheResolver { override fun resolveField(field: CompiledField, variables: Executable.Variables, parent: Map<String, Any?>, parentId: String): Any? { return when (field.name) { "hero" -> mapOf("name" to "Luke") else -> DefaultCacheResolver.resolveField(field, variables, parent, parentId) } } } val apolloClient = ApolloClient.Builder().serverUrl(serverUrl = "") .store( ApolloStore( normalizedCacheFactory = MemoryCacheFactory(), cacheResolver = resolver ) ) .build() val response = apolloClient.query(HeroNameQuery()).execute() assertEquals("Luke", response.data?.hero?.name) } }
tests/integration-tests/src/commonTest/kotlin/test/CacheResolverTest.kt
2340716114
/* * 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. */ @file:Suppress("FunctionName") package com.google.samples.apps.iosched.ui.schedule import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.google.samples.apps.iosched.R import com.google.samples.apps.iosched.model.ConferenceData import com.google.samples.apps.iosched.model.TestDataRepository import com.google.samples.apps.iosched.model.TestDataSource import com.google.samples.apps.iosched.shared.data.ConferenceDataRepository import com.google.samples.apps.iosched.shared.data.ConferenceDataSource import com.google.samples.apps.iosched.shared.data.prefs.PreferenceStorage import com.google.samples.apps.iosched.shared.data.session.DefaultSessionRepository import com.google.samples.apps.iosched.shared.data.signin.AuthenticatedUserInfoBasic import com.google.samples.apps.iosched.shared.data.signin.datasources.AuthStateUserDataSource import com.google.samples.apps.iosched.shared.data.signin.datasources.RegisteredUserDataSource import com.google.samples.apps.iosched.shared.data.userevent.DefaultSessionAndUserEventRepository import com.google.samples.apps.iosched.shared.data.userevent.UserEventDataSource import com.google.samples.apps.iosched.shared.data.userevent.UserEventMessage import com.google.samples.apps.iosched.shared.data.userevent.UserEventMessageChangeType import com.google.samples.apps.iosched.shared.data.userevent.UserEventsResult import com.google.samples.apps.iosched.shared.domain.RefreshConferenceDataUseCase import com.google.samples.apps.iosched.shared.domain.auth.ObserveUserAuthStateUseCase import com.google.samples.apps.iosched.shared.domain.prefs.ScheduleUiHintsShownUseCase import com.google.samples.apps.iosched.shared.domain.prefs.StopSnackbarActionUseCase import com.google.samples.apps.iosched.shared.domain.sessions.LoadScheduleUserSessionsParameters import com.google.samples.apps.iosched.shared.domain.sessions.LoadScheduleUserSessionsResult import com.google.samples.apps.iosched.shared.domain.sessions.LoadScheduleUserSessionsUseCase import com.google.samples.apps.iosched.shared.domain.sessions.ObserveConferenceDataUseCase import com.google.samples.apps.iosched.shared.domain.settings.GetTimeZoneUseCase import com.google.samples.apps.iosched.shared.fcm.TopicSubscriber import com.google.samples.apps.iosched.shared.result.Result import com.google.samples.apps.iosched.test.data.CoroutineScope import com.google.samples.apps.iosched.test.data.MainCoroutineRule import com.google.samples.apps.iosched.test.data.TestData import com.google.samples.apps.iosched.test.util.fakes.FakeAppDatabase import com.google.samples.apps.iosched.test.util.fakes.FakePreferenceStorage import com.google.samples.apps.iosched.test.util.fakes.FakeSignInViewModelDelegate import com.google.samples.apps.iosched.ui.messages.SnackbarMessageManager import com.google.samples.apps.iosched.ui.signin.FirebaseSignInViewModelDelegate import com.google.samples.apps.iosched.ui.signin.SignInViewModelDelegate import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.toList import kotlinx.coroutines.launch import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.core.Is.`is` import org.hamcrest.core.IsEqual import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.mockito.Mockito.verify /** * Unit tests for the [ScheduleViewModel]. */ class ScheduleViewModelTest { // Executes tasks in the Architecture Components in the same thread @get:Rule var instantTaskExecutorRule = InstantTaskExecutorRule() // Overrides Dispatchers.Main used in Coroutines @get:Rule var coroutineRule = MainCoroutineRule() private val testDispatcher = coroutineRule.testDispatcher private val coroutineScope = coroutineRule.CoroutineScope() @Test fun testDataIsLoaded_ObservablesUpdated() = runTest { // Create a delegate so we can load a user val signInDelegate = FakeSignInViewModelDelegate() // Create ViewModel with the use cases val viewModel = createScheduleViewModel(signInViewModelDelegate = signInDelegate) // Kick off the viewmodel by loading a user. signInDelegate.loadUser("test") // Observe viewmodel to load sessions val scheduleUiData = viewModel.scheduleUiData.first() // Check that data were loaded correctly assertEquals( TestData.userSessionList, scheduleUiData.list ) assertFalse(viewModel.isLoading.first()) } @Test fun testDataIsLoaded_Fails() = runTest { // Create ViewModel val viewModel = createScheduleViewModel( loadScheduleSessionsUseCase = createExceptionUseCase() ) // Trigger data load viewModel.scheduleUiData.first() assertNotNull(viewModel.errorMessage.first()) } /** New reservation / waitlist **/ @Test fun reservationReceived() = runTest { // Create test use cases with test data val testUserId = "test" val source = TestUserEventDataSource() val loadSessionsUseCase = createTestLoadUserSessionsByDayUseCase(source) val signInDelegate = FakeSignInViewModelDelegate() val snackbarMessageManager = createSnackbarMessageManager() val viewModel = createScheduleViewModel( loadScheduleSessionsUseCase = loadSessionsUseCase, signInViewModelDelegate = signInDelegate, snackbarMessageManager = snackbarMessageManager ) // Kick off the viewmodel by loading a user. signInDelegate.loadUser(testUserId) // Observe viewmodel to load sessions viewModel.scheduleUiData.first() // A session goes from not-reserved to reserved val oldValue = UserEventsResult(TestData.userEvents) val newValue = oldValue.copy( userEventsMessage = UserEventMessage( UserEventMessageChangeType.CHANGES_IN_RESERVATIONS ) ) source.newObservableUserEvents.value = newValue val message = snackbarMessageManager.currentSnackbar.value assertEquals( message?.messageId, R.string.reservation_new ) } @Test fun waitlistReceived() = runTest { // Create test use cases with test data val source = TestUserEventDataSource() val loadSessionsUseCase = createTestLoadUserSessionsByDayUseCase(source) val signInDelegate = FakeSignInViewModelDelegate() val snackbarMessageManager = createSnackbarMessageManager() val viewModel = createScheduleViewModel( loadScheduleSessionsUseCase = loadSessionsUseCase, signInViewModelDelegate = signInDelegate, snackbarMessageManager = snackbarMessageManager ) // Kick off the viewmodel by loading a user. signInDelegate.loadUser("test") // Observe viewmodel to load sessions viewModel.scheduleUiData.first() // A session goes from not-reserved to reserved val oldValue = UserEventsResult(TestData.userEvents) val newValue = oldValue.copy( userEventsMessage = UserEventMessage(UserEventMessageChangeType.CHANGES_IN_WAITLIST) ) source.newObservableUserEvents.value = newValue val message = snackbarMessageManager.currentSnackbar.value assertEquals( message?.messageId, R.string.waitlist_new ) } @Test fun noLoggedInUser_showsReservationButton() = runTest { // Given no logged in user val noFirebaseUser = null // Create ViewModel val observableFirebaseUserUseCase = FakeObserveUserAuthStateUseCase( user = Result.Success(noFirebaseUser), isRegistered = Result.Success(false), coroutineScope = coroutineRule.CoroutineScope(), coroutineDispatcher = testDispatcher ) val signInViewModelComponent = FirebaseSignInViewModelDelegate( observableFirebaseUserUseCase, mock {}, testDispatcher, testDispatcher, true, coroutineScope ) val viewModel = createScheduleViewModel(signInViewModelDelegate = signInViewModelComponent) // Check that reservation buttons are shown assertTrue(viewModel.showReservations.first()) } @Test fun loggedInUser_registered_showsReservationButton() = runTest { // Given a logged in user val mockUser = mock<AuthenticatedUserInfoBasic> { on { getUid() }.doReturn("uuid") on { isSignedIn() }.doReturn(true) } // Who is registered val observableFirebaseUserUseCase = FakeObserveUserAuthStateUseCase( user = Result.Success(mockUser), isRegistered = Result.Success(true), coroutineScope = coroutineRule.CoroutineScope(), coroutineDispatcher = testDispatcher ) val signInViewModelComponent = FirebaseSignInViewModelDelegate( observableFirebaseUserUseCase, mock {}, testDispatcher, testDispatcher, true, coroutineScope ) // Create ViewModel val viewModel = createScheduleViewModel(signInViewModelDelegate = signInViewModelComponent) // Trigger data load viewModel.userInfo.first() viewModel.isUserSignedIn.first() viewModel.isUserRegistered.first() // Check that reservation buttons are shown assertTrue(viewModel.showReservations.first()) } @Test fun loggedInUser_notRegistered_hidesReservationButton() = runTest { // Given a logged in user val mockUser = mock<AuthenticatedUserInfoBasic> { on { getUid() }.doReturn("uuid") on { isSignedIn() }.doReturn(true) } // Who isn't registered val observableFirebaseUserUseCase = FakeObserveUserAuthStateUseCase( user = Result.Success(mockUser), isRegistered = Result.Success(false), coroutineScope = coroutineRule.CoroutineScope(), coroutineDispatcher = testDispatcher ) val signInViewModelComponent = FirebaseSignInViewModelDelegate( observableFirebaseUserUseCase, mock {}, testDispatcher, testDispatcher, true, coroutineRule.CoroutineScope() ) // Create ViewModel val viewModel = createScheduleViewModel(signInViewModelDelegate = signInViewModelComponent) // Trigger data load viewModel.userInfo.first() viewModel.isUserSignedIn.first() viewModel.isUserRegistered.first() // Check that *no* reservation buttons are shown assertFalse(viewModel.showReservations.first()) } @Test fun scheduleHints_shownOnLaunch() = runTest { val viewModel = createScheduleViewModel() val firstNavAction = viewModel.navigationActions.firstOrNull() assertEquals(firstNavAction, ScheduleNavigationAction.ShowScheduleUiHints) } @Test fun swipeRefresh_refreshesRemoteConfData() = runTest { // Given a view model with a mocked remote data source val remoteDataSource = mock<ConferenceDataSource> {} val viewModel = createScheduleViewModel( refreshConferenceDataUseCase = RefreshConferenceDataUseCase( ConferenceDataRepository( remoteDataSource = remoteDataSource, boostrapDataSource = TestDataSource, appDatabase = FakeAppDatabase() ), testDispatcher ) ) // When swipe refresh is called viewModel.onSwipeRefresh() // Then the remote data source attempts to fetch new data verify(remoteDataSource).getRemoteConferenceData() // And the swipe refreshing status is set to false assertEquals(false, viewModel.swipeRefreshing.first()) } @Test fun newDataFromConfRepo_scheduleUpdated() = runTest { val repo = ConferenceDataRepository( remoteDataSource = TestConfDataSourceSession0(), boostrapDataSource = BootstrapDataSourceSession3(), appDatabase = FakeAppDatabase() ) val loadUserSessionsByDayUseCase = createTestLoadUserSessionsByDayUseCase( conferenceDataRepo = repo ) val viewModel = createScheduleViewModel( loadScheduleSessionsUseCase = loadUserSessionsByDayUseCase, observeConferenceDataUseCase = ObserveConferenceDataUseCase(repo, testDispatcher) ) // Observe viewmodel to load sessions viewModel.scheduleUiData.first() // Trigger a refresh on the repo repo.refreshCacheWithRemoteConferenceData() // The new value should be present val newValue = viewModel.scheduleUiData.first() assertThat( newValue.list?.first()?.session, `is`(IsEqual.equalTo(TestData.session0)) ) } @Test fun scrollToEvent_beforeconference() { scrollToEvent_beforeConference(dayIndex = 0, targetPosition = 0) } @Test fun scrollToEvent_beforeConference_clickOnSecondDay() { scrollToEvent_beforeConference(dayIndex = 1, targetPosition = 2) } private fun scrollToEvent_beforeConference(dayIndex: Int, targetPosition: Int) = runTest { val viewModel = createScheduleViewModel() // Start observing viewModel.scheduleUiData.first() // Trigger to generate indexer viewModel.scrollToStartOfDay(TestData.TestConferenceDays[0]) val result = mutableListOf<ScheduleScrollEvent>() val job = launch(UnconfinedTestDispatcher()) { viewModel.scrollToEvent.toList(result) } // Trigger to generate a result in scrollToEvent viewModel.scrollToStartOfDay(TestData.TestConferenceDays[dayIndex]) assertTrue(result.size == 1) assertEquals( result[0], ScheduleScrollEvent(targetPosition = targetPosition, smoothScroll = false) ) job.cancel() } @Test fun scrollToEvent_beforeConference_userHasInteracted() = runTest { val viewModel = createScheduleViewModel() viewModel.userHasInteracted = true // Start observing viewModel.scheduleUiData.first() // Trigger to generate indexer viewModel.scrollToStartOfDay(TestData.TestConferenceDays[0]) val result = mutableListOf<ScheduleScrollEvent>() val job = launch(UnconfinedTestDispatcher()) { viewModel.scrollToEvent.toList(result) } // Trigger to generate a result in scrollToEvent viewModel.scrollToStartOfDay(TestData.TestConferenceDays[1]) assertEquals(1, result.size) assertEquals(result[0], ScheduleScrollEvent(targetPosition = 2, smoothScroll = false)) job.cancel() } private fun createScheduleViewModel( loadScheduleSessionsUseCase: LoadScheduleUserSessionsUseCase = createTestLoadUserSessionsByDayUseCase(), signInViewModelDelegate: SignInViewModelDelegate = FakeSignInViewModelDelegate(), snackbarMessageManager: SnackbarMessageManager = createSnackbarMessageManager(), scheduleUiHintsShownUseCase: ScheduleUiHintsShownUseCase = FakeScheduleUiHintsShownUseCase(testDispatcher), getTimeZoneUseCase: GetTimeZoneUseCase = createGetTimeZoneUseCase(), topicSubscriber: TopicSubscriber = mock {}, refreshConferenceDataUseCase: RefreshConferenceDataUseCase = RefreshConferenceDataUseCase(TestDataRepository, testDispatcher), observeConferenceDataUseCase: ObserveConferenceDataUseCase = ObserveConferenceDataUseCase(TestDataRepository, testDispatcher) ): ScheduleViewModel { return ScheduleViewModel( loadScheduleUserSessionsUseCase = loadScheduleSessionsUseCase, signInViewModelDelegate = signInViewModelDelegate, scheduleUiHintsShownUseCase = scheduleUiHintsShownUseCase, topicSubscriber = topicSubscriber, snackbarMessageManager = snackbarMessageManager, getTimeZoneUseCase = getTimeZoneUseCase, refreshConferenceDataUseCase = refreshConferenceDataUseCase, observeConferenceDataUseCase = observeConferenceDataUseCase ) } /** * Creates a test [LoadScheduleUserSessionsUseCase]. */ private fun createTestLoadUserSessionsByDayUseCase( userEventDataSource: UserEventDataSource = TestUserEventDataSource(), conferenceDataRepo: ConferenceDataRepository = TestDataRepository ): LoadScheduleUserSessionsUseCase { val sessionRepository = DefaultSessionRepository(conferenceDataRepo) val userEventRepository = DefaultSessionAndUserEventRepository( userEventDataSource, sessionRepository ) return LoadScheduleUserSessionsUseCase(userEventRepository, testDispatcher) } /** * Creates a use case that throws an exception. */ private fun createExceptionUseCase(): LoadScheduleUserSessionsUseCase { return object : LoadScheduleUserSessionsUseCase(mock {}, testDispatcher) { override fun execute(parameters: LoadScheduleUserSessionsParameters): Flow<Result<LoadScheduleUserSessionsResult>> = flow { throw Exception("Loading failed") } } } private fun createGetTimeZoneUseCase() = GetTimeZoneUseCase(FakePreferenceStorage(), testDispatcher) private fun createSnackbarMessageManager( preferenceStorage: PreferenceStorage = FakePreferenceStorage() ): SnackbarMessageManager { return SnackbarMessageManager( preferenceStorage, coroutineRule.CoroutineScope(), StopSnackbarActionUseCase(preferenceStorage, testDispatcher) ) } } class TestRegisteredUserDataSource(private val isRegistered: Result<Boolean?>) : RegisteredUserDataSource { override fun observeUserChanges(userId: String): Flow<Result<Boolean?>> = flow { emit(isRegistered) } } class TestAuthStateUserDataSource( private val user: Result<AuthenticatedUserInfoBasic?> ) : AuthStateUserDataSource { override fun getBasicUserInfo(): Flow<Result<AuthenticatedUserInfoBasic?>> = flow { emit(user) } } class FakeObserveUserAuthStateUseCase( user: Result<AuthenticatedUserInfoBasic?>, isRegistered: Result<Boolean?>, coroutineScope: CoroutineScope, coroutineDispatcher: CoroutineDispatcher ) : ObserveUserAuthStateUseCase( TestRegisteredUserDataSource(isRegistered), TestAuthStateUserDataSource(user), mock {}, coroutineScope, coroutineDispatcher ) class FakeScheduleUiHintsShownUseCase( dispatcher: CoroutineDispatcher ) : ScheduleUiHintsShownUseCase( preferenceStorage = FakePreferenceStorage(), dispatcher = dispatcher, ) class TestConfDataSourceSession0 : ConferenceDataSource { override fun getRemoteConferenceData(): ConferenceData? { return conferenceData } override fun getOfflineConferenceData(): ConferenceData? { return conferenceData } private val conferenceData = ConferenceData( sessions = listOf(TestData.session0), speakers = listOf(TestData.speaker1), rooms = emptyList(), codelabs = emptyList(), tags = listOf(TestData.androidTag, TestData.webTag), version = 42 ) } class BootstrapDataSourceSession3 : ConferenceDataSource { override fun getRemoteConferenceData(): ConferenceData? { throw NotImplementedError() // Not used } override fun getOfflineConferenceData(): ConferenceData? { return ConferenceData( sessions = listOf(TestData.session3), speakers = listOf(TestData.speaker1), rooms = emptyList(), codelabs = emptyList(), tags = listOf(TestData.androidTag, TestData.webTag), version = 42 ) } }
mobile/src/test/java/com/google/samples/apps/iosched/ui/schedule/ScheduleViewModelTest.kt
3482971727
package io.multifunctions import io.multifunctions.models.Hepta import io.multifunctions.models.Hexa import io.multifunctions.models.Penta import io.multifunctions.models.Quad /** * Performs the given [action] on each element, providing sequential index with the element. * @param [action] function that takes the index of an element and the element itself * and performs the desired action on the element. */ public inline infix fun <A, B> Iterable<Pair<A?, B?>>.forEachIndexed(action: (Int, A?, B?) -> Unit) = forEachIndexed { index, (first, second) -> action(index, first, second) } /** * Performs the given [action] on each element, providing sequential index with the element. * @param [action] function that takes the index of an element and the element itself * and performs the desired action on the element. */ public inline infix fun <A, B, C> Iterable<Triple<A?, B?, C?>>.forEachIndexed(action: (Int, A?, B?, C?) -> Unit) = forEachIndexed { index, (first, second, third) -> action(index, first, second, third) } /** * Performs the given [action] on each element, providing sequential index with the element. * @param [action] function that takes the index of an element and the element itself * and performs the desired action on the element. */ public inline infix fun <A, B, C, D> Iterable<Quad<A?, B?, C?, D?>>.forEachIndexed(action: (Int, A?, B?, C?, D?) -> Unit) = forEachIndexed { index, (first, second, third, fourth) -> action(index, first, second, third, fourth) } /** * Performs the given [action] on each element, providing sequential index with the element. * @param [action] function that takes the index of an element and the element itself * and performs the desired action on the element. */ public inline infix fun <A, B, C, D, E> Iterable<Penta<A?, B?, C?, D?, E?>>.forEachIndexed(action: (Int, A?, B?, C?, D?, E?) -> Unit) = forEachIndexed { index, (first, second, third, fourth, fifth) -> action(index, first, second, third, fourth, fifth) } /** * Performs the given [action] on each element, providing sequential index with the element. * @param [action] function that takes the index of an element and the element itself * and performs the desired action on the element. */ public inline infix fun <A, B, C, D, E, F> Iterable<Hexa<A?, B?, C?, D?, E?, F?>>.forEachIndexed( action: (Int, A?, B?, C?, D?, E?, F?) -> Unit ) = forEachIndexed { index, (first, second, third, fourth, fifth, sixth) -> action(index, first, second, third, fourth, fifth, sixth) } /** * Performs the given [action] on each element, providing sequential index with the element. * @param [action] function that takes the index of an element and the element itself * and performs the desired action on the element. */ public inline infix fun <A, B, C, D, E, F, G> Iterable<Hepta<A?, B?, C?, D?, E?, F?, G?>>.forEachIndexed( action: (Int, A?, B?, C?, D?, E?, F?, G?) -> Unit ) = forEachIndexed { index, (first, second, third, fourth, fifth, sixth, seventh) -> action(index, first, second, third, fourth, fifth, sixth, seventh) }
multi-functions/src/main/kotlin/io/multifunctions/MultiForEachIndexed.kt
1444123143
// "Add 'return' to last expression" "false" // WITH_STDLIB // ACTION: Add 'return' expression // ACTION: Remove explicitly specified return type of enclosing function 'some' // ERROR: A 'return' expression required in a function with a block body ('{...}') // ERROR: Unresolved reference: FunctionReference fun some(): Any { FunctionReference::class }<caret>
plugins/kotlin/idea/tests/testData/quickfix/addReturnToLastExpressionInFunction/typeError2.kt
3402299264
package com.github.vhromada.catalog.controller import com.github.vhromada.catalog.entity.ChangeCheatRequest import com.github.vhromada.catalog.entity.Cheat import com.github.vhromada.catalog.facade.CheatFacade import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.PutMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.ResponseStatus import org.springframework.web.bind.annotation.RestController /** * A class represents controller for cheats. * * @author Vladimir Hromada */ @RestController("cheatController") @RequestMapping("rest/games/{gameUuid}/cheats") class CheatController( /** * Facade for cheats */ private val facade: CheatFacade ) { /** * Returns cheat for game's UUID. * <br></br> * Validation errors: * * * Game doesn't exist in data storage * * @param gameUuid game's UUID * @return cheat for game's UUID */ @GetMapping fun find(@PathVariable("gameUuid") gameUuid: String): Cheat { return facade.find(game = gameUuid) } /** * Returns cheat. * <br></br> * Validation errors: * * * Game doesn't exist in data storage * * Cheat doesn't exist in data storage * * @param gameUuid game's UUID * @param cheatUuid cheat's UUID * @return cheat */ @GetMapping("{cheatUuid}") fun get( @PathVariable("gameUuid") gameUuid: String, @PathVariable("cheatUuid") cheatUuid: String ): Cheat { return facade.get(game = gameUuid, uuid = cheatUuid) } /** * Adds cheat. * <br></br> * Validation errors: * * * Cheat's data are null * * Cheat's data contain null value * * Action is null * * Action is empty string * * Description is null * * Description is empty string * * Game has already cheat in data storage * * Game doesn't exist in data storage * * @param gameUuid game's UUID * @param request request for changing game * @return add cheat */ @PutMapping @ResponseStatus(HttpStatus.CREATED) @Suppress("GrazieInspection") fun add( @PathVariable("gameUuid") gameUuid: String, @RequestBody request: ChangeCheatRequest ): Cheat { return facade.add(game = gameUuid, request = request) } /** * Updates cheat. * <br></br> * Validation errors: * * * Cheat's data are null * * Cheat's data contain null value * * Action is null * * Action is empty string * * Description is null * * Description is empty string * * Game doesn't exist in data storage * * Cheat doesn't exist in data storage * * @param gameUuid game's UUID * @param gameUuid cheat's UUID * @param request request for changing game * @return updated cheat */ @PostMapping("{cheatUuid}") fun update( @PathVariable("gameUuid") gameUuid: String, @PathVariable("cheatUuid") cheatUuid: String, @RequestBody request: ChangeCheatRequest ): Cheat { return facade.update(game = gameUuid, uuid = cheatUuid, request = request) } /** * Removes cheat. * <br></br> * Validation errors: * * * Game doesn't exist in data storage * * Cheat doesn't exist in data storage * * @param gameUuid game's UUID * @param gameUuid cheat's UUID */ @DeleteMapping("{cheatUuid}") @ResponseStatus(HttpStatus.NO_CONTENT) fun remove( @PathVariable("gameUuid") gameUuid: String, @PathVariable("cheatUuid") cheatUuid: String ) { facade.remove(game = gameUuid, uuid = cheatUuid) } }
core/src/main/kotlin/com/github/vhromada/catalog/controller/CheatController.kt
1824042068
object Wordy { fun answer(input: String): Int { TODO("Implement this to complete the task") } }
exercises/practice/wordy/src/main/kotlin/Wordy.kt
2315403138
/* * Copyright (c) 2019 Mike Penz * * 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.mikepenz.iconics.internal import android.content.Context import android.graphics.drawable.StateListDrawable import com.mikepenz.iconics.IconicsDrawable import com.mikepenz.iconics.utils.IconicsUtils /** * @author pa.gulko zTrap (07.07.2017) */ internal class CheckableIconBundle { var animateChanges: Boolean = false var checkedIcon: IconicsDrawable? = null var uncheckedIcon: IconicsDrawable? = null fun createIcons(ctx: Context) { checkedIcon = IconicsDrawable(ctx) uncheckedIcon = IconicsDrawable(ctx) } fun createStates(ctx: Context): StateListDrawable { return IconicsUtils.getCheckableIconStateList( ctx, uncheckedIcon, checkedIcon, animateChanges ) } }
iconics-views/src/main/java/com/mikepenz/iconics/internal/CheckableIconBundle.kt
1936158364
/* * Copyright (C) 2012 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. */ @file:JvmName("Util") package okhttp3.internal import java.io.Closeable import java.io.FileNotFoundException import java.io.IOException import java.io.InterruptedIOException import java.net.InetSocketAddress import java.net.ServerSocket import java.net.Socket import java.net.SocketTimeoutException import java.nio.charset.Charset import java.nio.charset.StandardCharsets.UTF_16BE import java.nio.charset.StandardCharsets.UTF_16LE import java.nio.charset.StandardCharsets.UTF_8 import java.util.Collections import java.util.Comparator import java.util.LinkedHashMap import java.util.Locale import java.util.TimeZone import java.util.concurrent.ThreadFactory import java.util.concurrent.TimeUnit import kotlin.text.Charsets.UTF_32BE import kotlin.text.Charsets.UTF_32LE import okhttp3.EventListener import okhttp3.Headers import okhttp3.Headers.Companion.headersOf import okhttp3.HttpUrl import okhttp3.OkHttp import okhttp3.OkHttpClient import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response import okhttp3.ResponseBody.Companion.toResponseBody import okhttp3.internal.http2.Header import okio.Buffer import okio.BufferedSink import okio.BufferedSource import okio.ByteString.Companion.decodeHex import okio.ExperimentalFileSystem import okio.FileSystem import okio.Options import okio.Path import okio.Source @JvmField val EMPTY_BYTE_ARRAY = ByteArray(0) @JvmField val EMPTY_HEADERS = headersOf() @JvmField val EMPTY_RESPONSE = EMPTY_BYTE_ARRAY.toResponseBody() @JvmField val EMPTY_REQUEST = EMPTY_BYTE_ARRAY.toRequestBody() /** Byte order marks. */ private val UNICODE_BOMS = Options.of( "efbbbf".decodeHex(), // UTF-8 "feff".decodeHex(), // UTF-16BE "fffe".decodeHex(), // UTF-16LE "0000ffff".decodeHex(), // UTF-32BE "ffff0000".decodeHex() // UTF-32LE ) /** GMT and UTC are equivalent for our purposes. */ @JvmField val UTC = TimeZone.getTimeZone("GMT")!! /** * Quick and dirty pattern to differentiate IP addresses from hostnames. This is an approximation * of Android's private InetAddress#isNumeric API. * * This matches IPv6 addresses as a hex string containing at least one colon, and possibly * including dots after the first colon. It matches IPv4 addresses as strings containing only * decimal digits and dots. This pattern matches strings like "a:.23" and "54" that are neither IP * addresses nor hostnames; they will be verified as IP addresses (which is a more strict * verification). */ private val VERIFY_AS_IP_ADDRESS = "([0-9a-fA-F]*:[0-9a-fA-F:.]*)|([\\d.]+)".toRegex() fun checkOffsetAndCount(arrayLength: Long, offset: Long, count: Long) { if (offset or count < 0L || offset > arrayLength || arrayLength - offset < count) { throw ArrayIndexOutOfBoundsException() } } fun threadFactory( name: String, daemon: Boolean ): ThreadFactory = ThreadFactory { runnable -> Thread(runnable, name).apply { isDaemon = daemon } } /** * Returns an array containing only elements found in this array and also in [other]. The returned * elements are in the same order as in this. */ fun Array<String>.intersect( other: Array<String>, comparator: Comparator<in String> ): Array<String> { val result = mutableListOf<String>() for (a in this) { for (b in other) { if (comparator.compare(a, b) == 0) { result.add(a) break } } } return result.toTypedArray() } /** * Returns true if there is an element in this array that is also in [other]. This method terminates * if any intersection is found. The sizes of both arguments are assumed to be so small, and the * likelihood of an intersection so great, that it is not worth the CPU cost of sorting or the * memory cost of hashing. */ fun Array<String>.hasIntersection( other: Array<String>?, comparator: Comparator<in String> ): Boolean { if (isEmpty() || other == null || other.isEmpty()) { return false } for (a in this) { for (b in other) { if (comparator.compare(a, b) == 0) { return true } } } return false } fun HttpUrl.toHostHeader(includeDefaultPort: Boolean = false): String { val host = if (":" in host) { "[$host]" } else { host } return if (includeDefaultPort || port != HttpUrl.defaultPort(scheme)) { "$host:$port" } else { host } } fun Array<String>.indexOf(value: String, comparator: Comparator<String>): Int = indexOfFirst { comparator.compare(it, value) == 0 } @Suppress("UNCHECKED_CAST") fun Array<String>.concat(value: String): Array<String> { val result = copyOf(size + 1) result[result.lastIndex] = value return result as Array<String> } /** * Increments [startIndex] until this string is not ASCII whitespace. Stops at [endIndex]. */ fun String.indexOfFirstNonAsciiWhitespace(startIndex: Int = 0, endIndex: Int = length): Int { for (i in startIndex until endIndex) { when (this[i]) { '\t', '\n', '\u000C', '\r', ' ' -> Unit else -> return i } } return endIndex } /** * Decrements [endIndex] until `input[endIndex - 1]` is not ASCII whitespace. Stops at [startIndex]. */ fun String.indexOfLastNonAsciiWhitespace(startIndex: Int = 0, endIndex: Int = length): Int { for (i in endIndex - 1 downTo startIndex) { when (this[i]) { '\t', '\n', '\u000C', '\r', ' ' -> Unit else -> return i + 1 } } return startIndex } /** Equivalent to `string.substring(startIndex, endIndex).trim()`. */ fun String.trimSubstring(startIndex: Int = 0, endIndex: Int = length): String { val start = indexOfFirstNonAsciiWhitespace(startIndex, endIndex) val end = indexOfLastNonAsciiWhitespace(start, endIndex) return substring(start, end) } /** * Returns the index of the first character in this string that contains a character in * [delimiters]. Returns endIndex if there is no such character. */ fun String.delimiterOffset(delimiters: String, startIndex: Int = 0, endIndex: Int = length): Int { for (i in startIndex until endIndex) { if (this[i] in delimiters) return i } return endIndex } /** * Returns the index of the first character in this string that is [delimiter]. Returns [endIndex] * if there is no such character. */ fun String.delimiterOffset(delimiter: Char, startIndex: Int = 0, endIndex: Int = length): Int { for (i in startIndex until endIndex) { if (this[i] == delimiter) return i } return endIndex } /** * Returns the index of the first character in this string that is either a control character (like * `\u0000` or `\n`) or a non-ASCII character. Returns -1 if this string has no such characters. */ fun String.indexOfControlOrNonAscii(): Int { for (i in 0 until length) { val c = this[i] if (c <= '\u001f' || c >= '\u007f') { return i } } return -1 } /** Returns true if this string is not a host name and might be an IP address. */ fun String.canParseAsIpAddress(): Boolean { return VERIFY_AS_IP_ADDRESS.matches(this) } /** Returns true if we should void putting this this header in an exception or toString(). */ fun isSensitiveHeader(name: String): Boolean { return name.equals("Authorization", ignoreCase = true) || name.equals("Cookie", ignoreCase = true) || name.equals("Proxy-Authorization", ignoreCase = true) || name.equals("Set-Cookie", ignoreCase = true) } /** Returns a [Locale.US] formatted [String]. */ fun format(format: String, vararg args: Any): String { return String.format(Locale.US, format, *args) } @Throws(IOException::class) fun BufferedSource.readBomAsCharset(default: Charset): Charset { return when (select(UNICODE_BOMS)) { 0 -> UTF_8 1 -> UTF_16BE 2 -> UTF_16LE 3 -> UTF_32BE 4 -> UTF_32LE -1 -> default else -> throw AssertionError() } } fun checkDuration(name: String, duration: Long, unit: TimeUnit?): Int { check(duration >= 0L) { "$name < 0" } check(unit != null) { "unit == null" } val millis = unit.toMillis(duration) require(millis <= Integer.MAX_VALUE) { "$name too large." } require(millis != 0L || duration <= 0L) { "$name too small." } return millis.toInt() } fun Char.parseHexDigit(): Int = when (this) { in '0'..'9' -> this - '0' in 'a'..'f' -> this - 'a' + 10 in 'A'..'F' -> this - 'A' + 10 else -> -1 } fun List<Header>.toHeaders(): Headers { val builder = Headers.Builder() for ((name, value) in this) { builder.addLenient(name.utf8(), value.utf8()) } return builder.build() } fun Headers.toHeaderList(): List<Header> = (0 until size).map { Header(name(it), value(it)) } /** Returns true if an HTTP request for this URL and [other] can reuse a connection. */ fun HttpUrl.canReuseConnectionFor(other: HttpUrl): Boolean = host == other.host && port == other.port && scheme == other.scheme fun EventListener.asFactory() = EventListener.Factory { this } infix fun Byte.and(mask: Int): Int = toInt() and mask infix fun Short.and(mask: Int): Int = toInt() and mask infix fun Int.and(mask: Long): Long = toLong() and mask @Throws(IOException::class) fun BufferedSink.writeMedium(medium: Int) { writeByte(medium.ushr(16) and 0xff) writeByte(medium.ushr(8) and 0xff) writeByte(medium and 0xff) } @Throws(IOException::class) fun BufferedSource.readMedium(): Int { return (readByte() and 0xff shl 16 or (readByte() and 0xff shl 8) or (readByte() and 0xff)) } /** * Reads until this is exhausted or the deadline has been reached. This is careful to not extend the * deadline if one exists already. */ @Throws(IOException::class) fun Source.skipAll(duration: Int, timeUnit: TimeUnit): Boolean { val nowNs = System.nanoTime() val originalDurationNs = if (timeout().hasDeadline()) { timeout().deadlineNanoTime() - nowNs } else { Long.MAX_VALUE } timeout().deadlineNanoTime(nowNs + minOf(originalDurationNs, timeUnit.toNanos(duration.toLong()))) return try { val skipBuffer = Buffer() while (read(skipBuffer, 8192) != -1L) { skipBuffer.clear() } true // Success! The source has been exhausted. } catch (_: InterruptedIOException) { false // We ran out of time before exhausting the source. } finally { if (originalDurationNs == Long.MAX_VALUE) { timeout().clearDeadline() } else { timeout().deadlineNanoTime(nowNs + originalDurationNs) } } } /** * Attempts to exhaust this, returning true if successful. This is useful when reading a complete * source is helpful, such as when doing so completes a cache body or frees a socket connection for * reuse. */ fun Source.discard(timeout: Int, timeUnit: TimeUnit): Boolean = try { this.skipAll(timeout, timeUnit) } catch (_: IOException) { false } fun Socket.peerName(): String { val address = remoteSocketAddress return if (address is InetSocketAddress) address.hostName else address.toString() } /** * Returns true if new reads and writes should be attempted on this. * * Unfortunately Java's networking APIs don't offer a good health check, so we go on our own by * attempting to read with a short timeout. If the fails immediately we know the socket is * unhealthy. * * @param source the source used to read bytes from the socket. */ fun Socket.isHealthy(source: BufferedSource): Boolean { return try { val readTimeout = soTimeout try { soTimeout = 1 !source.exhausted() } finally { soTimeout = readTimeout } } catch (_: SocketTimeoutException) { true // Read timed out; socket is good. } catch (_: IOException) { false // Couldn't read; socket is closed. } } /** Run [block] until it either throws an [IOException] or completes. */ inline fun ignoreIoExceptions(block: () -> Unit) { try { block() } catch (_: IOException) { } } inline fun threadName(name: String, block: () -> Unit) { val currentThread = Thread.currentThread() val oldName = currentThread.name currentThread.name = name try { block() } finally { currentThread.name = oldName } } fun Buffer.skipAll(b: Byte): Int { var count = 0 while (!exhausted() && this[0] == b) { count++ readByte() } return count } /** * Returns the index of the next non-whitespace character in this. Result is undefined if input * contains newline characters. */ fun String.indexOfNonWhitespace(startIndex: Int = 0): Int { for (i in startIndex until length) { val c = this[i] if (c != ' ' && c != '\t') { return i } } return length } /** Returns the Content-Length as reported by the response headers. */ fun Response.headersContentLength(): Long { return headers["Content-Length"]?.toLongOrDefault(-1L) ?: -1L } fun String.toLongOrDefault(defaultValue: Long): Long { return try { toLong() } catch (_: NumberFormatException) { defaultValue } } /** * Returns this as a non-negative integer, or 0 if it is negative, or [Int.MAX_VALUE] if it is too * large, or [defaultValue] if it cannot be parsed. */ fun String?.toNonNegativeInt(defaultValue: Int): Int { try { val value = this?.toLong() ?: return defaultValue return when { value > Int.MAX_VALUE -> Int.MAX_VALUE value < 0 -> 0 else -> value.toInt() } } catch (_: NumberFormatException) { return defaultValue } } /** Returns an immutable copy of this. */ fun <T> List<T>.toImmutableList(): List<T> { return Collections.unmodifiableList(toMutableList()) } /** Returns an immutable list containing [elements]. */ @SafeVarargs fun <T> immutableListOf(vararg elements: T): List<T> { return Collections.unmodifiableList(listOf(*elements.clone())) } /** Returns an immutable copy of this. */ fun <K, V> Map<K, V>.toImmutableMap(): Map<K, V> { return if (isEmpty()) { emptyMap() } else { Collections.unmodifiableMap(LinkedHashMap(this)) } } /** Closes this, ignoring any checked exceptions. */ fun Closeable.closeQuietly() { try { close() } catch (rethrown: RuntimeException) { throw rethrown } catch (_: Exception) { } } /** Closes this, ignoring any checked exceptions. */ fun Socket.closeQuietly() { try { close() } catch (e: AssertionError) { throw e } catch (rethrown: RuntimeException) { if (rethrown.message == "bio == null") { // Conscrypt in Android 10 and 11 may throw closing an SSLSocket. This is safe to ignore. // https://issuetracker.google.com/issues/177450597 return } throw rethrown } catch (_: Exception) { } } /** Closes this, ignoring any checked exceptions. */ fun ServerSocket.closeQuietly() { try { close() } catch (rethrown: RuntimeException) { throw rethrown } catch (_: Exception) { } } /** * Returns true if file streams can be manipulated independently of their paths. This is typically * true for systems like Mac, Unix, and Linux that use inodes in their file system interface. It is * typically false on Windows. * * If this returns false we won't permit simultaneous reads and writes. When writes commit we need * to delete the previous snapshots, and that won't succeed if the file is open. (We do permit * multiple simultaneous reads.) * * @param file a file in the directory to check. This file shouldn't already exist! */ @OptIn(ExperimentalFileSystem::class) fun FileSystem.isCivilized(file: Path): Boolean { sink(file).use { try { delete(file) return true } catch (_: IOException) { } } delete(file) return false } /** Delete file we expect but don't require to exist. */ @OptIn(ExperimentalFileSystem::class) fun FileSystem.deleteIfExists(path: Path) { try { delete(path) } catch (fnfe: FileNotFoundException) { return } } /** * Tolerant delete, try to clear as many files as possible even after a failure. */ @OptIn(ExperimentalFileSystem::class) fun FileSystem.deleteContents(directory: Path) { var exception: IOException? = null val files = try { list(directory) } catch (fnfe: FileNotFoundException) { return } for (file in files) { try { if (metadata(file).isDirectory) { deleteContents(file) } delete(file) } catch (ioe: IOException) { if (exception == null) { exception = ioe } } } if (exception != null) { throw exception } } fun Long.toHexString(): String = java.lang.Long.toHexString(this) fun Int.toHexString(): String = Integer.toHexString(this) @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "NOTHING_TO_INLINE") inline fun Any.wait() = (this as Object).wait() @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "NOTHING_TO_INLINE") inline fun Any.notify() = (this as Object).notify() @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "NOTHING_TO_INLINE") inline fun Any.notifyAll() = (this as Object).notifyAll() fun <T> readFieldOrNull(instance: Any, fieldType: Class<T>, fieldName: String): T? { var c: Class<*> = instance.javaClass while (c != Any::class.java) { try { val field = c.getDeclaredField(fieldName) field.isAccessible = true val value = field.get(instance) return if (!fieldType.isInstance(value)) null else fieldType.cast(value) } catch (_: NoSuchFieldException) { } c = c.superclass } // Didn't find the field we wanted. As a last gasp attempt, // try to find the value on a delegate. if (fieldName != "delegate") { val delegate = readFieldOrNull(instance, Any::class.java, "delegate") if (delegate != null) return readFieldOrNull(delegate, fieldType, fieldName) } return null } internal fun <E> MutableList<E>.addIfAbsent(element: E) { if (!contains(element)) add(element) } @JvmField val assertionsEnabled = OkHttpClient::class.java.desiredAssertionStatus() /** * Returns the string "OkHttp" unless the library has been shaded for inclusion in another library, * or obfuscated with tools like R8 or ProGuard. In such cases it'll return a longer string like * "com.example.shaded.okhttp3.OkHttp". In large applications it's possible to have multiple OkHttp * instances; this makes it clear which is which. */ @JvmField internal val okHttpName = OkHttpClient::class.java.name.removePrefix("okhttp3.").removeSuffix("Client") @Suppress("NOTHING_TO_INLINE") inline fun Any.assertThreadHoldsLock() { if (assertionsEnabled && !Thread.holdsLock(this)) { throw AssertionError("Thread ${Thread.currentThread().name} MUST hold lock on $this") } } @Suppress("NOTHING_TO_INLINE") inline fun Any.assertThreadDoesntHoldLock() { if (assertionsEnabled && Thread.holdsLock(this)) { throw AssertionError("Thread ${Thread.currentThread().name} MUST NOT hold lock on $this") } } fun Exception.withSuppressed(suppressed: List<Exception>): Throwable = apply { for (e in suppressed) addSuppressed(e) } inline fun <T> Iterable<T>.filterList(predicate: T.() -> Boolean): List<T> { var result: List<T> = emptyList() for (i in this) { if (predicate(i)) { if (result.isEmpty()) result = mutableListOf() (result as MutableList<T>).add(i) } } return result } const val userAgent = "okhttp/${OkHttp.VERSION}"
okhttp/src/main/kotlin/okhttp3/internal/Util.kt
655403453
package com.github.laurenttreguier.deck class Constants { companion object { val POST_URL = "https://sola.ai/posts/" } }
app/src/main/java/com/github/laurenttreguier/deck/Constants.kt
1130505733
package test.kotlin.integration.proxying import android.content.Intent import android.content.Context import android.net.ConnectivityManager import android.net.Proxy import android.net.ProxyInfo import androidx.test.core.app.ApplicationProvider import io.envoyproxy.envoymobile.LogLevel import io.envoyproxy.envoymobile.Custom import io.envoyproxy.envoymobile.Engine import io.envoyproxy.envoymobile.UpstreamHttpProtocol import io.envoyproxy.envoymobile.AndroidEngineBuilder import io.envoyproxy.envoymobile.RequestHeadersBuilder import io.envoyproxy.envoymobile.RequestMethod import io.envoyproxy.envoymobile.ResponseHeaders import io.envoyproxy.envoymobile.StreamIntel import io.envoyproxy.envoymobile.engine.JniLibrary import java.util.concurrent.CountDownLatch import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito import org.robolectric.RobolectricTestRunner // β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” // β”‚ Proxy Engine β”‚ // β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ // β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”Όβ”€β–Ίlistener_proxyβ”‚ β”‚ // β”‚https://api.lyft.com/pingβ”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” // β”‚ Request β”œβ”€β”€β–ΊAndroid Engineβ”‚ β”‚ β”‚ β”‚ β”‚api.lyft.comβ”‚ // β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β” β”‚ β””β”€β”€β”€β”€β”€β”€β–²β”€β”€β”€β”€β”€β”˜ // β”‚ β”‚cluster_proxyβ”‚ β”‚ β”‚ // β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”˜ // β”‚ β”‚ // β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ @RunWith(RobolectricTestRunner::class) class PerformHTTPSRequestBadHostname { init { JniLibrary.loadTestLibrary() } @Test fun `attempts an HTTPs request through a proxy using an async DNS resolution that fails`() { val port = (10001..11000).random() val context = Mockito.spy(ApplicationProvider.getApplicationContext<Context>()) val connectivityManager: ConnectivityManager = Mockito.mock(ConnectivityManager::class.java) Mockito.doReturn(connectivityManager).`when`(context).getSystemService(Context.CONNECTIVITY_SERVICE) Mockito.`when`(connectivityManager.getDefaultProxy()).thenReturn(ProxyInfo.buildDirectProxy("loopback", port)) val onEngineRunningLatch = CountDownLatch(1) val onProxyEngineRunningLatch = CountDownLatch(1) val onErrorLatch = CountDownLatch(1) val proxyEngineBuilder = Proxy(context, port).https() val proxyEngine = proxyEngineBuilder .addLogLevel(LogLevel.DEBUG) .addDNSQueryTimeoutSeconds(2) .setOnEngineRunning { onProxyEngineRunningLatch.countDown() } .build() onProxyEngineRunningLatch.await(10, TimeUnit.SECONDS) assertThat(onProxyEngineRunningLatch.count).isEqualTo(0) context.sendStickyBroadcast(Intent(Proxy.PROXY_CHANGE_ACTION)) val builder = AndroidEngineBuilder(context) val engine = builder .addLogLevel(LogLevel.DEBUG) .enableProxying(true) .setOnEngineRunning { onEngineRunningLatch.countDown() } .build() onEngineRunningLatch.await(10, TimeUnit.SECONDS) assertThat(onEngineRunningLatch.count).isEqualTo(0) val requestHeaders = RequestHeadersBuilder( method = RequestMethod.GET, scheme = "https", authority = "api.lyft.com", path = "/ping" ) .build() engine .streamClient() .newStreamPrototype() .setOnError { _, _ -> onErrorLatch.countDown() } .start(Executors.newSingleThreadExecutor()) .sendHeaders(requestHeaders, true) onErrorLatch.await(15, TimeUnit.SECONDS) assertThat(onErrorLatch.count).isEqualTo(0) engine.terminate() proxyEngine.terminate() } }
test/kotlin/integration/proxying/PerformHTTPSRequestBadHostname.kt
3191392220
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.rx3 import io.reactivex.rxjava3.core.* import io.reactivex.rxjava3.disposables.Disposable import kotlinx.coroutines.CancellableContinuation import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Job import kotlinx.coroutines.suspendCancellableCoroutine import kotlin.coroutines.* // ------------------------ CompletableSource ------------------------ /** * Awaits for completion of this completable without blocking the thread. * Returns `Unit`, or throws the corresponding exception if this completable produces an error. * * This suspending function is cancellable. If the [Job] of the invoking coroutine is cancelled or completed while this * suspending function is suspended, this function immediately resumes with [CancellationException] and disposes of its * subscription. */ public suspend fun CompletableSource.await(): Unit = suspendCancellableCoroutine { cont -> subscribe(object : CompletableObserver { override fun onSubscribe(d: Disposable) { cont.disposeOnCancellation(d) } override fun onComplete() { cont.resume(Unit) } override fun onError(e: Throwable) { cont.resumeWithException(e) } }) } // ------------------------ MaybeSource ------------------------ /** * Awaits for completion of the [MaybeSource] without blocking the thread. * Returns the resulting value, or `null` if no value is produced, or throws the corresponding exception if this * [MaybeSource] produces an error. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this * function immediately resumes with [CancellationException] and disposes of its subscription. */ @Suppress("UNCHECKED_CAST") public suspend fun <T> MaybeSource<T>.awaitSingleOrNull(): T? = suspendCancellableCoroutine { cont -> subscribe(object : MaybeObserver<T> { override fun onSubscribe(d: Disposable) { cont.disposeOnCancellation(d) } override fun onComplete() { cont.resume(null) } override fun onSuccess(t: T) { cont.resume(t) } override fun onError(error: Throwable) { cont.resumeWithException(error) } }) } /** * Awaits for completion of the [MaybeSource] without blocking the thread. * Returns the resulting value, or throws if either no value is produced or this [MaybeSource] produces an error. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this * function immediately resumes with [CancellationException] and disposes of its subscription. * * @throws NoSuchElementException if no elements were produced by this [MaybeSource]. */ public suspend fun <T> MaybeSource<T>.awaitSingle(): T = awaitSingleOrNull() ?: throw NoSuchElementException() /** * Awaits for completion of the maybe without blocking a thread. * Returns the resulting value, null if no value was produced or throws the corresponding exception if this * maybe had produced error. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function * immediately resumes with [CancellationException]. * * ### Deprecation * * Deprecated in favor of [awaitSingleOrNull] in order to reflect that `null` can be returned to denote the absence of * a value, as opposed to throwing in such case. * * @suppress */ @Deprecated( message = "Deprecated in favor of awaitSingleOrNull()", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith("this.awaitSingleOrNull()") ) // Warning since 1.5, error in 1.6, hidden in 1.7 public suspend fun <T> MaybeSource<T>.await(): T? = awaitSingleOrNull() /** * Awaits for completion of the maybe without blocking a thread. * Returns the resulting value, [default] if no value was produced or throws the corresponding exception if this * maybe had produced error. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function * immediately resumes with [CancellationException]. * * ### Deprecation * * Deprecated in favor of [awaitSingleOrNull] for naming consistency (see the deprecation of [MaybeSource.await] for * details). * * @suppress */ @Deprecated( message = "Deprecated in favor of awaitSingleOrNull()", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith("this.awaitSingleOrNull() ?: default") ) // Warning since 1.5, error in 1.6, hidden in 1.7 public suspend fun <T> MaybeSource<T>.awaitOrDefault(default: T): T = awaitSingleOrNull() ?: default // ------------------------ SingleSource ------------------------ /** * Awaits for completion of the single value response without blocking the thread. * Returns the resulting value, or throws the corresponding exception if this response produces an error. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while the suspending function is waiting, this * function immediately disposes of its subscription and resumes with [CancellationException]. */ public suspend fun <T> SingleSource<T>.await(): T = suspendCancellableCoroutine { cont -> subscribe(object : SingleObserver<T> { override fun onSubscribe(d: Disposable) { cont.disposeOnCancellation(d) } override fun onSuccess(t: T) { cont.resume(t) } override fun onError(error: Throwable) { cont.resumeWithException(error) } }) } // ------------------------ ObservableSource ------------------------ /** * Awaits the first value from the given [Observable] without blocking the thread and returns the resulting value, or, * if the observable has produced an error, throws the corresponding exception. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while the suspending function is waiting, this * function immediately disposes of its subscription and resumes with [CancellationException]. * * @throws NoSuchElementException if the observable does not emit any value */ public suspend fun <T> ObservableSource<T>.awaitFirst(): T = awaitOne(Mode.FIRST) /** * Awaits the first value from the given [Observable], or returns the [default] value if none is emitted, without * blocking the thread, and returns the resulting value, or, if this observable has produced an error, throws the * corresponding exception. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while the suspending function is waiting, this * function immediately disposes of its subscription and resumes with [CancellationException]. */ public suspend fun <T> ObservableSource<T>.awaitFirstOrDefault(default: T): T = awaitOne(Mode.FIRST_OR_DEFAULT, default) /** * Awaits the first value from the given [Observable], or returns `null` if none is emitted, without blocking the * thread, and returns the resulting value, or, if this observable has produced an error, throws the corresponding * exception. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while the suspending function is waiting, this * function immediately disposes of its subscription and resumes with [CancellationException]. */ public suspend fun <T> ObservableSource<T>.awaitFirstOrNull(): T? = awaitOne(Mode.FIRST_OR_DEFAULT) /** * Awaits the first value from the given [Observable], or calls [defaultValue] to get a value if none is emitted, * without blocking the thread, and returns the resulting value, or, if this observable has produced an error, throws * the corresponding exception. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while the suspending function is waiting, this * function immediately disposes of its subscription and resumes with [CancellationException]. */ public suspend fun <T> ObservableSource<T>.awaitFirstOrElse(defaultValue: () -> T): T = awaitOne(Mode.FIRST_OR_DEFAULT) ?: defaultValue() /** * Awaits the last value from the given [Observable] without blocking the thread and * returns the resulting value, or, if this observable has produced an error, throws the corresponding exception. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while the suspending function is waiting, this * function immediately disposes of its subscription and resumes with [CancellationException]. * * @throws NoSuchElementException if the observable does not emit any value */ public suspend fun <T> ObservableSource<T>.awaitLast(): T = awaitOne(Mode.LAST) /** * Awaits the single value from the given observable without blocking the thread and returns the resulting value, or, * if this observable has produced an error, throws the corresponding exception. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while the suspending function is waiting, this * function immediately disposes of its subscription and resumes with [CancellationException]. * * @throws NoSuchElementException if the observable does not emit any value * @throws IllegalArgumentException if the observable emits more than one value */ public suspend fun <T> ObservableSource<T>.awaitSingle(): T = awaitOne(Mode.SINGLE) // ------------------------ private ------------------------ internal fun CancellableContinuation<*>.disposeOnCancellation(d: Disposable) = invokeOnCancellation { d.dispose() } private enum class Mode(val s: String) { FIRST("awaitFirst"), FIRST_OR_DEFAULT("awaitFirstOrDefault"), LAST("awaitLast"), SINGLE("awaitSingle"); override fun toString(): String = s } private suspend fun <T> ObservableSource<T>.awaitOne( mode: Mode, default: T? = null ): T = suspendCancellableCoroutine { cont -> subscribe(object : Observer<T> { private lateinit var subscription: Disposable private var value: T? = null private var seenValue = false override fun onSubscribe(sub: Disposable) { subscription = sub cont.invokeOnCancellation { sub.dispose() } } override fun onNext(t: T) { when (mode) { Mode.FIRST, Mode.FIRST_OR_DEFAULT -> { if (!seenValue) { seenValue = true cont.resume(t) subscription.dispose() } } Mode.LAST, Mode.SINGLE -> { if (mode == Mode.SINGLE && seenValue) { if (cont.isActive) cont.resumeWithException(IllegalArgumentException("More than one onNext value for $mode")) subscription.dispose() } else { value = t seenValue = true } } } } @Suppress("UNCHECKED_CAST") override fun onComplete() { if (seenValue) { if (cont.isActive) cont.resume(value as T) return } when { mode == Mode.FIRST_OR_DEFAULT -> { cont.resume(default as T) } cont.isActive -> { cont.resumeWithException(NoSuchElementException("No value received via onNext for $mode")) } } } override fun onError(e: Throwable) { cont.resumeWithException(e) } }) }
reactive/kotlinx-coroutines-rx3/src/RxAwait.kt
2173437394
/* * Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.flow import kotlinx.coroutines.* import kotlinx.coroutines.flow.internal.* import kotlinx.coroutines.scheduling.* import org.junit.Assume.* import org.junit.Test import java.util.concurrent.atomic.* import kotlin.test.* class FlatMapStressTest : TestBase() { private val iterations = 2000 * stressTestMultiplier private val expectedSum = iterations.toLong() * (iterations + 1) / 2 @Test fun testConcurrencyLevel() = runTest { withContext(Dispatchers.Default) { testConcurrencyLevel(2) } } @Test fun testConcurrencyLevel2() = runTest { withContext(Dispatchers.Default) { testConcurrencyLevel(3) } } @Test fun testBufferSize() = runTest { val bufferSize = 5 withContext(Dispatchers.Default) { val inFlightElements = AtomicLong(0L) var result = 0L (1..iterations step 4).asFlow().flatMapMerge { value -> unsafeFlow { repeat(4) { emit(value + it) inFlightElements.incrementAndGet() } } }.buffer(bufferSize).collect { value -> val inFlight = inFlightElements.get() assertTrue(inFlight <= bufferSize + 1, "Expected less in flight elements than ${bufferSize + 1}, but had $inFlight") inFlightElements.decrementAndGet() result += value } assertEquals(0, inFlightElements.get()) assertEquals(expectedSum, result) } } @Test fun testDelivery() = runTest { withContext(Dispatchers.Default) { val result = (1L..iterations step 4).asFlow().flatMapMerge { value -> unsafeFlow { repeat(4) { emit(value + it) } } }.longSum() assertEquals(expectedSum, result) } } @Test fun testIndependentShortBursts() = runTest { withContext(Dispatchers.Default) { repeat(iterations) { val result = (1L..4L).asFlow().flatMapMerge { value -> unsafeFlow { emit(value) emit(value) } }.longSum() assertEquals(20, result) } } } private suspend fun testConcurrencyLevel(maxConcurrency: Int) { assumeTrue(maxConcurrency <= CORE_POOL_SIZE) val concurrency = AtomicLong() val result = (1L..iterations).asFlow().flatMapMerge(concurrency = maxConcurrency) { value -> unsafeFlow { val current = concurrency.incrementAndGet() assertTrue(current in 1..maxConcurrency) emit(value) concurrency.decrementAndGet() } }.longSum() assertEquals(0, concurrency.get()) assertEquals(expectedSum, result) } }
kotlinx-coroutines-core/jvm/test/flow/FlatMapStressTest.kt
4291388641
/** * <slate_header> * author: Kishore Reddy * url: www.github.com/code-helix/slatekit * copyright: 2016 Kishore Reddy * license: www.github.com/code-helix/slatekit/blob/master/LICENSE.md * desc: A tool-kit, utility library and server-backend * usage: Please refer to license on github for more info. * </slate_header> */ package slatekit.examples //<doc:import_required> import slatekit.common.DateTime import slatekit.common.DateTimes //</doc:import_required> //<doc:import_examples> import slatekit.results.Try import slatekit.results.Success //import java.time.ZoneId import org.threeten.bp.* import slatekit.common.ext.* //</doc:import_examples> class Example_DateTime : Command("datetime") { override fun execute(request: CommandRequest) : Try<Any> { //<doc:examples> // // NOTE: // When working with new Java 8 Date/Time, which is a significant // improvement over the older mutable Java Date/Time models, // there is still some "cognitive overhead" ( IMHO ) in mentally // managing the different LocalDateTime, ZonedDateTime and conversion // to and from local/zoned functionality // // DESIGN: // This DateTime is a unified DateTime for both LocalDateTime and ZonedDateime // that wraps uses a ZonedDateTime internally ( defaulted to local timezone ) // and is used for representing a DateTime for either Local and/or other Zones. // This makes the Java 8 datetime/zones a bit simpler & concise while // essentially adding syntactic sugar using Kotlin operators and extension methods // // IMPORTANT: // This does NOT change the functionality of the Java 8 classes at all. // It is simply "syntactic sugar" for using the classes. // Case 1. Get datetime now, either locally, at utc and other zones // These will return a DateTime that wraps a ZonedDateTime. println( DateTime.now() ) println( DateTimes.nowUtc() ) println( DateTimes.nowAt("America/New_York")) println( DateTimes.nowAt("Europe/Athens")) println( DateTimes.nowAt(ZoneId.of("Europe/Athens"))) // Case 2: Build datetime explicitly println( DateTimes.of(2017, 7, 10)) println( DateTimes.of(2017, 7, 10, 11, 30, 0)) println( DateTimes.of(2017, 7, 10, 11, 30, 0, 0)) println( DateTime.of(2017, 7, 10, 11, 30, 0, 0, ZoneId.of("America/New_York"))) // Case 3. Get datetime fields val dt = DateTime.now() println( "year : " + dt.year ) println( "month : " + dt.month ) println( "day : " + dt.dayOfMonth) println( "hour : " + dt.hour ) println( "mins : " + dt.minute ) println( "secs : " + dt.second ) println( "nano : " + dt.nano ) println( "zone : " + dt.zone.id ) // Case 4: Conversion from now( local ) to utc, specific zone, // LocalDate, LocalTime, and LocalDateTime val now = DateTime.now() println( now.date() ) println( now.time() ) println( now.local() ) println( now.atUtc() ) println( now.atUtcLocal() ) println( now.atZone("Europe/Athens") ) // Case 5: Idiomatic use of Kotlin operators and extension methods // This uses the extensions from slatekit.common.ext.IntExtensions val later = DateTime.now() + 3.minutes println( DateTime.now() + 3.days ) println( DateTime.now() - 3.minutes ) println( DateTime.now() - 3.months ) // Case 6. Add time ( just like Java 8 ) val dt1 = DateTime.now() println( dt1.plusYears (1).toString() ) println( dt1.plusMonths (1).toString() ) println( dt1.plusDays (1).toString() ) println( dt1.plusHours (1).toString() ) println( dt1.plusMinutes(1).toString() ) println( dt1.plusSeconds(1).toString() ) // Case 7. Compare println( dt1 > dt1.plusYears (1) ) println( dt1 >= dt1.plusMonths (1) ) println( dt1 >= dt1.plusDays (1) ) println( dt1 < dt1.plusHours (1) ) println( dt1 <= dt1.plusMinutes(1) ) println( dt1 <= dt1.plusSeconds(1) ) // Case 8. Get duration (hours,mins,seconds) or period(days,months,years) println( dt1.plusSeconds(2).durationFrom( dt1 ) ) println( dt1.plusMinutes(2).durationFrom( dt1 ) ) println( dt1.plusHours(2).durationFrom( dt1 ) ) println( dt1.plusDays(2).periodFrom( dt1 ) ) println( dt1.plusMonths(2).periodFrom( dt1 ) ) println( dt1.plusYears(2).periodFrom( dt1 ) ) //</doc:examples> return Success("") } }
src/apps/kotlin/slatekit-examples/src/main/kotlin/slatekit/examples/Example_DateTime.kt
2551945117
/* * Copyright 2017 Rod MacKenzie. * * 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.rodm.teamcity.gradle.scripts.agent import com.github.rodm.teamcity.gradle.scripts.GradleInitScriptsPlugin.FEATURE_TYPE import com.github.rodm.teamcity.gradle.scripts.GradleInitScriptsPlugin.INIT_SCRIPT_CONTENT import com.github.rodm.teamcity.gradle.scripts.GradleInitScriptsPlugin.INIT_SCRIPT_CONTENT_PARAMETER import com.github.rodm.teamcity.gradle.scripts.GradleInitScriptsPlugin.INIT_SCRIPT_NAME import com.github.rodm.teamcity.gradle.scripts.GradleInitScriptsPlugin.INIT_SCRIPT_NAME_PARAMETER import jetbrains.buildServer.agent.* import jetbrains.buildServer.log.Loggers.AGENT_CATEGORY import jetbrains.buildServer.util.EventDispatcher import jetbrains.buildServer.util.FileUtil import org.apache.log4j.Logger import java.io.File import java.io.IOException import java.lang.RuntimeException open class GradleInitScriptsFeature(eventDispatcher: EventDispatcher<AgentLifeCycleListener>) : AgentLifeCycleAdapter() { private val LOG = Logger.getLogger(AGENT_CATEGORY + ".GradleInitScriptsFeature") private val GRADLE_CMD_PARAMS = "ui.gradleRunner.additional.gradle.cmd.params" private val initScriptFiles = mutableListOf<File>() init { eventDispatcher.addListener(this) } override fun beforeRunnerStart(runner: BuildRunnerContext) { val runnerParameters = runner.runnerParameters val initScriptName = runnerParameters[INIT_SCRIPT_NAME_PARAMETER] if (initScriptName != null) { addInitScriptParameters(runner, initScriptName, runnerParameters[INIT_SCRIPT_CONTENT_PARAMETER]) } if (hasGradleInitScriptFeature(runner)) { addInitScriptParameters(runner, runnerParameters[INIT_SCRIPT_NAME], runnerParameters[INIT_SCRIPT_CONTENT]) } } private fun addInitScriptParameters(runner: BuildRunnerContext, name: String?, content: String?) { if (name != null) { if (content == null) { throw RuntimeException("Runner is configured to use init script '$name', but no content was found. Please check runner settings.") } try { val initScriptFile = FileUtil.createTempFile(getBuildTempDirectory(runner), "init_", ".gradle", true) if (initScriptFile != null) { FileUtil.writeFile(initScriptFile, content, "UTF-8") initScriptFiles.add(initScriptFile) val params = runner.runnerParameters.getOrDefault(GRADLE_CMD_PARAMS, "") val initScriptParams = "--init-script " + initScriptFile.absolutePath runner.addRunnerParameter(GRADLE_CMD_PARAMS, initScriptParams + " " + params) } } catch (e: IOException) { LOG.info("Failed to write init script: " + e.message) } } } override fun runnerFinished(runner: BuildRunnerContext, status: BuildFinishedStatus) { initScriptFiles.forEach { file -> FileUtil.delete(file) } initScriptFiles.clear() } open fun hasGradleInitScriptFeature(context: BuildRunnerContext) : Boolean { return !context.build.getBuildFeaturesOfType(FEATURE_TYPE).isEmpty() } open fun getBuildTempDirectory(context: BuildRunnerContext) : File { return context.build.getBuildTempDirectory() } }
agent/src/main/kotlin/com/github/rodm/teamcity/gradle/scripts/agent/GradleInitScriptsFeature.kt
2584331489
package slatekit.data.syntax import slatekit.common.Types import slatekit.common.data.DataType import slatekit.common.data.DataTypeMap /** * Maps the DataTypes * Java types to MySql * https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-type-conversions.html */ open class Types { /** * BOOL */ open val boolType = DataTypeMap(DataType.DTBool, "BIT", Types.JBoolClass) /** * STRINGS */ open val charType = DataTypeMap(DataType.DTChar, "CHAR", Types.JCharClass) open val stringType = DataTypeMap(DataType.DTString, "NVARCHAR", Types.JStringClass) open val textType = DataTypeMap(DataType.DTText, "TEXT", Types.JStringClass) /** * UUID */ open val uuidType = DataTypeMap(DataType.DTUUID, "NVARCHAR", Types.JStringClass) open val ulidType = DataTypeMap(DataType.DTULID, "NVARCHAR", Types.JStringClass) open val upidType = DataTypeMap(DataType.DTUPID, "NVARCHAR", Types.JStringClass) /** * NUMBERS * https://dev.mysql.com/doc/refman/8.0/en/integer-types.html * Type Storage (Bytes) Minimum Value Signed Minimum Value Unsigned Maximum Value Signed Maximum Value Unsigned * TINYINT 1 -128 0 127 255 * SMALLINT 2 -32768 0 32767 65535 * MEDIUMINT 3 -8388608 0 8388607 16777215 * INT 4 -2147483648 0 2147483647 4294967295 * BIGINT 8 -263 0 263-1 264-1 */ open val shortType = DataTypeMap(DataType.DTShort, "SMALLINT", Types.JShortClass) open val intType = DataTypeMap(DataType.DTInt, "INTEGER", Types.JIntClass) open val longType = DataTypeMap(DataType.DTLong, "BIGINT", Types.JLongClass) open val floatType = DataTypeMap(DataType.DTFloat, "FLOAT", Types.JFloatClass) open val doubleType = DataTypeMap(DataType.DTDouble, "DOUBLE", Types.JDoubleClass) //open val decimalType = DataTypeMap(DataType.DbDecimal, "DECIMAL", Types.JDecimalClass) /** * DATES / TIMES */ open val localdateType = DataTypeMap(DataType.DTLocalDate, "DATE", Types.JLocalDateClass) open val localtimeType = DataTypeMap(DataType.DTLocalTime, "TIME", Types.JLocalTimeClass) open val localDateTimeType = DataTypeMap(DataType.DTLocalDateTime, "DATETIME", Types.JLocalDateTimeClass) open val zonedDateTimeType = DataTypeMap(DataType.DTZonedDateTime, "DATETIME", Types.JZonedDateTimeClass) open val dateTimeType = DataTypeMap(DataType.DTDateTime, "DATETIME", Types.JDateTimeClass) open val instantType = DataTypeMap(DataType.DTInstant, "INSTANT", Types.JInstantClass) open val lookup = mapOf( boolType.metaType to boolType, charType.metaType to charType, stringType.metaType to stringType, textType.metaType to textType, uuidType.metaType to uuidType, shortType.metaType to shortType, intType.metaType to intType, longType.metaType to longType, floatType.metaType to floatType, doubleType.metaType to doubleType, //decimalType.metaType to decimalType, localdateType.metaType to localdateType, localtimeType.metaType to localtimeType, localDateTimeType.metaType to localDateTimeType, zonedDateTimeType.metaType to zonedDateTimeType, dateTimeType.metaType to dateTimeType, instantType.metaType to instantType, uuidType.metaType to uuidType, ulidType.metaType to ulidType, upidType.metaType to upidType ) }
src/lib/kotlin/slatekit-data/src/main/kotlin/slatekit/data/sql/Types.kt
2391269687
/* * Copyright 2015-2019 The twitlatte authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.moko256.twitlatte import android.os.Bundle import android.view.Menu import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.SearchView import com.github.moko256.latte.client.twitter.CLIENT_TYPE_TWITTER /** * Created by moko256 on 2017/07/05. * * @author moko256 */ class TrendsActivity : AppCompatActivity(), BaseListFragment.GetViewForSnackBar { public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) supportActionBar?.let { it.title = intent.getStringExtra("query") it.setDisplayHomeAsUpEnabled(true) it.setHomeAsUpIndicator(R.drawable.ic_back_white_24dp) } if (savedInstanceState == null && getClient()?.accessToken?.clientType == CLIENT_TYPE_TWITTER) { supportFragmentManager .beginTransaction() .add(android.R.id.content, TrendsFragment()) .commit() } } override fun getViewForSnackBar(): View { return findViewById(android.R.id.content) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.activity_search_toolbar, menu) val searchMenu = menu.findItem(R.id.action_search) val searchView = searchMenu.actionView as SearchView searchMenu.expandActionView() searchView.onActionViewExpanded() searchView.clearFocus() searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(searchWord: String): Boolean { searchView.clearFocus() searchView.setQuery("", false) startActivity(SearchResultActivity.getIntent(this@TrendsActivity, searchWord)) return false } override fun onQueryTextChange(newText: String): Boolean { return false } }) searchView.setOnCloseListener { finish() false } return super.onCreateOptionsMenu(menu) } override fun onSupportNavigateUp(): Boolean { finish() return true } }
app/src/main/java/com/github/moko256/twitlatte/TrendsActivity.kt
1345593147
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND_WITHOUT_CHECK: JS tailrec fun test(x : Int) : Int { if (x == 1) { if (x != 1) { <!NON_TAIL_RECURSIVE_CALL!>test<!>(0) return test(0) } else { return test(x + <!NON_TAIL_RECURSIVE_CALL!>test<!>(0)) } } else if (x > 0) { return test(x - 1) } return -1 } fun box() : String = if (test(1000000) == -1) "OK" else "FAIL"
backend.native/tests/external/codegen/box/diagnostics/functions/tailRecursion/multilevelBlocks.kt
2047370901
class A { private val sb: StringBuilder = StringBuilder() operator fun String.unaryPlus() { sb.append(this) } fun foo(): String { +"OK" return sb.toString()!! } } fun box(): String = A().foo()
backend.native/tests/external/codegen/box/extensionFunctions/kt1953_class.kt
4175074637
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_RUNTIME object A { val b: String = "OK" @JvmStatic val c: String = "OK" @JvmStatic fun test1() : String { return {b}() } @JvmStatic fun test2() : String { return {test1()}() } fun test3(): String { return {"1".test5()}() } @JvmStatic fun test4(): String { return {"1".test5()}() } @JvmStatic fun String.test5() : String { return {this + b}() } fun test6(): String { return {c}() } } fun box(): String { if (A.test1() != "OK") return "fail 1" if (A.test2() != "OK") return "fail 2" if (A.test3() != "1OK") return "fail 3" if (A.test4() != "1OK") return "fail 4" if (with(A) {"1".test5()} != "1OK") return "fail 5" if (A.test6() != "OK") return "fail 6" return "OK" }
backend.native/tests/external/codegen/box/jvmStatic/closure.kt
1788987122
// IGNORE_BACKEND: NATIVE // FILE: A.kt package test import java.util.* fun printStream() = System.out fun list() = Collections.emptyList<String>() fun array(a: Array<Int>) = Arrays.copyOf(a, 2) // FILE: B.kt import java.io.PrintStream import java.util.ArrayList import test.* // To check that flexible types are loaded class Inv<T> fun <T> inv(t: T): Inv<T> = Inv<T>() fun box(): String { printStream().checkError() val p: Inv<PrintStream> = inv(printStream()) val p1: Inv<PrintStream?> = inv(printStream()) list().size val l: Inv<List<String>> = inv(list()) val l1: Inv<MutableList<String>?> = inv(list()) val a = array(arrayOfNulls<Int>(1) as Array<Int>) a[0] = 1 val a1: Inv<Array<Int>> = inv(a) val a2: Inv<Array<out Int>?> = inv(a) return "OK" }
backend.native/tests/external/compileKotlinAgainstKotlin/platformTypes.kt
282879323
class A( private val x: String, private var y: Double ) { fun foo() { val r = { if (x != "abc") throw AssertionError("$x") y = 0.0 if (y != 0.0) throw AssertionError("$y") } r() } } fun box(): String { A("abc", 3.14).foo() return "OK" }
backend.native/tests/external/codegen/box/properties/privatePropertyInConstructor.kt
2583734758