repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
genobis/tornadofx
src/main/java/tornadofx/TreeView.kt
1
6970
package tornadofx import javafx.beans.property.* import javafx.scene.Node import javafx.scene.control.TreeCell import javafx.scene.control.TreeItem import javafx.scene.control.TreeView import javafx.scene.input.KeyCode import javafx.scene.input.KeyEvent import javafx.util.Callback import tornadofx.FX.IgnoreParentBuilder.Once import kotlin.reflect.KClass /** * Base class for all TreeCellFragments. */ abstract class TreeCellFragment<T> : ItemFragment<T>() { val cellProperty: ObjectProperty<TreeCell<T>?> = SimpleObjectProperty() var cell by cellProperty val editingProperty = SimpleBooleanProperty(false) val editing by editingProperty open fun startEdit() { cell?.startEdit() } open fun commitEdit(newValue: T) { cell?.commitEdit(newValue) } open fun cancelEdit() { cell?.cancelEdit() } open fun onEdit(op: () -> Unit) { editingProperty.onChange { if (it) op() } } } open class SmartTreeCell<T>(val scope: Scope = DefaultScope, treeView: TreeView<T>?): TreeCell<T>() { private val editSupport: (TreeCell<T>.(EditEventType, T?) -> Unit)? get() = treeView.properties["tornadofx.editSupport"] as (TreeCell<T>.(EditEventType, T?) -> Unit)? private val cellFormat: (TreeCell<T>.(T) -> Unit)? get() = treeView.properties["tornadofx.cellFormat"] as (TreeCell<T>.(T) -> Unit)? private val cellCache: TreeCellCache<T>? get() = treeView.properties["tornadofx.cellCache"] as TreeCellCache<T>? private var cellFragment: TreeCellFragment<T>? = null private var fresh = true init { if (treeView != null) { treeView.properties["tornadofx.cellFormatCapable"] = true treeView.properties["tornadofx.cellCacheCapable"] = true treeView.properties["tornadofx.editCapable"] = true } indexProperty().onChange { if (it == -1) clearCellFragment() } } override fun startEdit() { super.startEdit() editSupport?.invoke(this, EditEventType.StartEdit, null) } override fun commitEdit(newValue: T) { super.commitEdit(newValue) editSupport?.invoke(this, EditEventType.CommitEdit, newValue) } override fun cancelEdit() { super.cancelEdit() editSupport?.invoke(this, EditEventType.CancelEdit, null) } override fun updateItem(item: T, empty: Boolean) { super.updateItem(item, empty) if (item == null || empty) { cleanUp() clearCellFragment() } else { FX.ignoreParentBuilder = Once try { cellCache?.apply { graphic = getOrCreateNode(item) } } finally { FX.ignoreParentBuilder = FX.IgnoreParentBuilder.No } if (fresh) { val cellFragmentType = treeView.properties["tornadofx.cellFragment"] as KClass<TreeCellFragment<T>>? cellFragment = if (cellFragmentType != null) find(cellFragmentType, scope) else null fresh = false } cellFragment?.apply { editingProperty.cleanBind(editingProperty()) itemProperty.value = item cellProperty.value = this@SmartTreeCell graphic = root } cellFormat?.invoke(this, item) } } private fun cleanUp() { textProperty().unbind() graphicProperty().unbind() text = null graphic = null } private fun clearCellFragment() { cellFragment?.apply { cellProperty.value = null itemProperty.value = null editingProperty.unbind() editingProperty.value = false } } } class TreeCellCache<T>(private val cacheProvider: (T) -> Node) { private val store = mutableMapOf<T, Node>() fun getOrCreateNode(value: T) = store.getOrPut(value, { cacheProvider(value) }) } fun <T> TreeView<T>.bindSelected(property: Property<T>) { selectionModel.selectedItemProperty().onChange { property.value = it?.value } } /** * Binds the currently selected object of type [T] in the given [TreeView] to the corresponding [ItemViewModel]. */ fun <T> TreeView<T>.bindSelected(model: ItemViewModel<T>) = this.bindSelected(model.itemProperty) fun <T> TreeView<T>.onUserDelete(action: (T) -> Unit) { addEventFilter(KeyEvent.KEY_PRESSED, { event -> if (event.code == KeyCode.BACK_SPACE && selectionModel.selectedItem?.value != null) action(selectedValue!!) }) } fun <T> TreeView<T>.onUserSelect(action: (T) -> Unit) { selectionModel.selectedItemProperty().addListener { obs, old, new -> if (new != null && new.value != null) action(new.value) } } /** * <p>This method will attempt to select the first index in the control. * If clearSelection is not called first, this method * will have the result of selecting the first index, whilst retaining * the selection of any other currently selected indices.</p> * * <p>If the first index is already selected, calling this method will have * no result, and no selection event will take place.</p> * * This functions is the same as calling. * ``` * selectionModel.selectFirst() * * ``` */ fun <T> TreeView<T>.selectFirst() = selectionModel.selectFirst() fun <T> TreeView<T>.populate(itemFactory: (T) -> TreeItem<T> = { TreeItem(it) }, childFactory: (TreeItem<T>) -> Iterable<T>?) = populateTree(root, itemFactory, childFactory) /** * Registers a `Fragment` which should be used to represent a [TreeItem] for the given [TreeView]. */ fun <T, F : TreeCellFragment<T>> TreeView<T>.cellFragment(scope: Scope = DefaultScope, fragment: KClass<F>) { properties["tornadofx.cellFragment"] = fragment if (properties["tornadofx.cellFormatCapable"] != true) cellFactory = Callback { SmartTreeCell(scope, it) } } fun <S> TreeView<S>.cellFormat(scope: Scope = DefaultScope, formatter: (TreeCell<S>.(S) -> Unit)) { properties["tornadofx.cellFormat"] = formatter if (properties["tornadofx.cellFormatCapable"] != true) { cellFactory = Callback { SmartTreeCell(scope, it) } } } fun <S> TreeView<S>.cellDecorator(decorator: (TreeCell<S>.(S) -> Unit)) { val originalFactory = cellFactory if (originalFactory == null) cellFormat(formatter = decorator) else { cellFactory = Callback { treeView: TreeView<S> -> val cell = originalFactory.call(treeView) cell.itemProperty().onChange { decorator(cell, cell.item) } cell } } } // -- Properties /** * Returns the currently selected value of type [T] (which is currently the * selected value represented by the current selection model). If there * are multiple values selected, it will return the most recently selected * value. * * <p>Note that the returned value is a snapshot in time. */ val <T> TreeView<T>.selectedValue: T? get() = this.selectionModel.selectedItem?.value
apache-2.0
0ed7d13acd2537f1345d3f98c08f5d47
33.50495
170
0.652798
4.348097
false
false
false
false
mrmike/DiffUtil-sample
app/src/main/java/com/moczul/diffutilsample/ActorDiffCallback.kt
1
649
package com.moczul.diffutilsample import android.support.v7.util.DiffUtil class ActorDiffCallback( private val oldList: List<Actor>, private val newList: List<Actor> ) : DiffUtil.Callback() { override fun getOldListSize() = oldList.size override fun getNewListSize() = newList.size override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldList[oldItemPosition].id == newList[newItemPosition].id } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldList[oldItemPosition].name == newList[newItemPosition].name } }
apache-2.0
be4f106f556a8bd987458427015745d3
28.545455
90
0.738059
4.772059
false
false
false
false
stoman/competitive-programming
problems/2021adventofcode13b/submissions/accepted/Stefan.kt
2
896
import java.util.* @ExperimentalStdlibApi fun main() { val s = Scanner(System.`in`).useDelimiter("\n\n") var dots = buildSet { val sDots = Scanner(s.next()).useDelimiter("""[,\n]""") while (sDots.hasNext()) { add(Pair(sDots.nextInt(), sDots.nextInt())) } } val sFolds = Scanner(s.next()).useDelimiter("""\s*fold along\s*|=|\s""") while (sFolds.hasNext()) { val horizontal = sFolds.next() == "x" val foldLine = sFolds.nextInt() dots = if (horizontal) { dots.map { Pair(if (it.first < foldLine) it.first else (2 * foldLine - it.first), it.second) }.toSet() } else { dots.map { Pair(it.first, if (it.second < foldLine) it.second else (2 * foldLine - it.second)) }.toSet() } } for(y in 0..dots.maxOf { it.second }) { for(x in 0..dots.maxOf { it.first }) { print(if(Pair(x, y) in dots) '#' else '.') } println() } }
mit
3f01611ecb32ca036ea18eb11ab9ea17
31
110
0.577009
3.089655
false
false
false
false
is00hcw/anko
dsl/testData/functional/gridlayout-v7/LayoutsTest.kt
2
2560
private val defaultInit: Any.() -> Unit = {} public open class _GridLayout(ctx: Context): android.support.v7.widget.GridLayout(ctx) { public fun <T: View> T.lparams( rowSpec: android.support.v7.widget.GridLayout.Spec?, columnSpec: android.support.v7.widget.GridLayout.Spec?, init: android.support.v7.widget.GridLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.v7.widget.GridLayout.LayoutParams(rowSpec!!, columnSpec!!) layoutParams.init() [email protected] = layoutParams return this } public fun <T: View> T.lparams( init: android.support.v7.widget.GridLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.v7.widget.GridLayout.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } public fun <T: View> T.lparams( params: android.view.ViewGroup.LayoutParams?, init: android.support.v7.widget.GridLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.v7.widget.GridLayout.LayoutParams(params!!) layoutParams.init() [email protected] = layoutParams return this } public fun <T: View> T.lparams( params: android.view.ViewGroup.MarginLayoutParams?, init: android.support.v7.widget.GridLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.v7.widget.GridLayout.LayoutParams(params!!) layoutParams.init() [email protected] = layoutParams return this } public fun <T: View> T.lparams( source: android.support.v7.widget.GridLayout.LayoutParams?, init: android.support.v7.widget.GridLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.v7.widget.GridLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } public fun <T: View> T.lparams( context: android.content.Context?, attrs: android.util.AttributeSet?, init: android.support.v7.widget.GridLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.v7.widget.GridLayout.LayoutParams(context!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } }
apache-2.0
554b79307bf14a8002234575dbd71823
38.4
101
0.647656
4.45993
false
false
false
false
karollewandowski/aem-intellij-plugin
src/main/kotlin/co/nums/intellij/aem/htl/psi/search/HtlJavaSearch.kt
1
1620
package co.nums.intellij.aem.htl.psi.search import com.intellij.openapi.project.Project import com.intellij.psi.* import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.searches.* object HtlJavaSearch { private val USE_INTERFACES = arrayOf("io.sightly.java.api.Use", "org.apache.sling.scripting.sightly.pojo.Use") private val SLING_MODEL_ANNOTATION = "org.apache.sling.models.annotations.Model" fun useApiClasses(project: Project) = useApiImplementers(project) + slingModels(project) private fun useApiImplementers(project: Project): Collection<PsiClass> = USE_INTERFACES .mapNotNull { it.toPsiClass(project) } .flatMap { project.findImplementers(it) } .filterNot { it.hasModifierProperty(PsiModifier.ABSTRACT) } private fun slingModels(project: Project): Collection<PsiClass> = SLING_MODEL_ANNOTATION .toPsiClass(project) ?.let { project.findAnnotatedClasses(it) } .orEmpty() private fun String.toPsiClass(project: Project) = JavaPsiFacade.getInstance(project).findClass(this, GlobalSearchScope.allScope(project)) private fun Project.findImplementers(implementedInterface: PsiClass): Collection<PsiClass> = ClassInheritorsSearch.search(implementedInterface, GlobalSearchScope.allScope(this), true).findAll() private fun Project.findAnnotatedClasses(annotation: PsiClass) = AnnotatedElementsSearch.searchPsiClasses(annotation, GlobalSearchScope.allScope(this)).findAll() }
gpl-3.0
29e47eb5ab1812454a86f25840e6a7dc
44
114
0.709259
4.550562
false
false
false
false
donald-w/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/dialogs/DeckSelectionDialog.kt
1
15456
/* Copyright (c) 2020 David Allison <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.anki.dialogs import android.app.Activity import android.app.Dialog import android.os.Bundle import android.os.Parcel import android.os.Parcelable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Filter import android.widget.Filterable import android.widget.TextView import androidx.appcompat.widget.SearchView import androidx.appcompat.widget.Toolbar import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.afollestad.materialdialogs.DialogAction import com.afollestad.materialdialogs.MaterialDialog import com.ichi2.anki.R import com.ichi2.anki.UIUtils.showThemedToast import com.ichi2.anki.analytics.AnalyticsDialogFragment import com.ichi2.libanki.Collection import com.ichi2.libanki.CollectionGetter import com.ichi2.libanki.Deck import com.ichi2.libanki.DeckManager import com.ichi2.libanki.backend.exception.DeckRenameException import com.ichi2.libanki.stats.Stats import com.ichi2.utils.DeckNameComparator import com.ichi2.utils.FilterResultsUtils import com.ichi2.utils.FunctionalInterfaces import com.ichi2.utils.KotlinCleanup import timber.log.Timber import java.util.* import java.util.Objects.requireNonNull /** * The dialog which allow to select a deck. It is opened when the user click on a deck name in stats, browser or note editor. * It allows to filter decks by typing part of its name. */ open class DeckSelectionDialog : AnalyticsDialogFragment() { private var mDialog: MaterialDialog? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) isCancelable = true } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialogView = LayoutInflater.from(activity) .inflate(R.layout.deck_picker_dialog, null, false) val summary = dialogView.findViewById<TextView>(R.id.deck_picker_dialog_summary) val arguments = requireArguments() if (getSummaryMessage(arguments) == null) { summary.visibility = View.GONE } else { summary.visibility = View.VISIBLE summary.text = getSummaryMessage(arguments) } val recyclerView: RecyclerView = dialogView.findViewById(R.id.deck_picker_dialog_list) recyclerView.requestFocus() val deckLayoutManager: RecyclerView.LayoutManager = LinearLayoutManager(requireActivity()) recyclerView.layoutManager = deckLayoutManager val dividerItemDecoration = DividerItemDecoration(recyclerView.context, DividerItemDecoration.VERTICAL) recyclerView.addItemDecoration(dividerItemDecoration) val decks: List<SelectableDeck> = getDeckNames(arguments) val adapter = DecksArrayAdapter(decks) recyclerView.adapter = adapter adjustToolbar(dialogView, adapter) var builder = MaterialDialog.Builder(requireActivity()) .neutralText(R.string.dialog_cancel) .customView(dialogView, false) if (arguments.getBoolean(KEEP_RESTORE_DEFAULT_BUTTON)) { builder = builder.negativeText(R.string.restore_default).onNegative { _: MaterialDialog?, _: DialogAction? -> onDeckSelected(null) } } mDialog = builder.build() return mDialog!! } private fun getSummaryMessage(arguments: Bundle): String? { return arguments.getString(SUMMARY_MESSAGE) } private fun getDeckNames(arguments: Bundle): ArrayList<SelectableDeck> { return requireNonNull(arguments.getParcelableArrayList<SelectableDeck>(DECK_NAMES)) as ArrayList<SelectableDeck> } private val title: String? get() = requireNonNull(requireArguments().getString(TITLE)) private fun adjustToolbar(dialogView: View, adapter: DecksArrayAdapter) { val toolbar: Toolbar = dialogView.findViewById(R.id.deck_picker_dialog_toolbar) toolbar.title = title toolbar.inflateMenu(R.menu.deck_picker_dialog_menu) val searchItem = toolbar.menu.findItem(R.id.deck_picker_dialog_action_filter) val searchView = searchItem.actionView as SearchView searchView.queryHint = getString(R.string.deck_picker_dialog_filter_decks) searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean { searchView.clearFocus() return true } override fun onQueryTextChange(newText: String): Boolean { adapter.filter.filter(newText) return true } }) val addDecks = toolbar.menu.findItem(R.id.deck_picker_dialog_action_add_deck) addDecks.setOnMenuItemClickListener { // creating new deck without any parent deck showDeckDialog() true } } private fun showSubDeckDialog(parentDeckPath: String) { try { // create subdeck val parentId = decks.id(parentDeckPath) val createDeckDialog = CreateDeckDialog(requireActivity(), R.string.create_subdeck, CreateDeckDialog.DeckDialogType.SUB_DECK, parentId) createDeckDialog.setOnNewDeckCreated { id: Long? -> // a sub deck was created selectDeckWithDeckName(decks.name(id!!)) } createDeckDialog.showDialog() } catch (ex: DeckRenameException) { Timber.w(ex) } } private fun showDeckDialog() { val createDeckDialog = CreateDeckDialog(requireActivity(), R.string.new_deck, CreateDeckDialog.DeckDialogType.DECK, null) // todo // setOnNewDeckCreated parameter to be made non null createDeckDialog.setOnNewDeckCreated { id: Long? -> // a deck was created selectDeckWithDeckName(decks.name(id!!)) } createDeckDialog.showDialog() } protected fun requireCollectionGetter(): CollectionGetter { return requireContext() as CollectionGetter } protected val decks: DeckManager get() = requireCollectionGetter().col.decks /** * Create the deck if it does not exists. * If name is valid, send the deck with this name to listener and close the dialog. */ private fun selectDeckWithDeckName(deckName: String) { try { val id = decks.id(deckName) val dec = SelectableDeck(id, deckName) selectDeckAndClose(dec) } catch (ex: DeckRenameException) { showThemedToast(requireActivity(), ex.getLocalizedMessage(resources), false) } } /** * @param deck deck sent to the listener. */ protected fun onDeckSelected(deck: SelectableDeck?) { deckSelectionListener.onDeckSelected(deck) } private val deckSelectionListener: DeckSelectionListener get() { val activity: Activity = requireActivity() if (activity is DeckSelectionListener) { return activity } val parentFragment = parentFragment if (parentFragment is DeckSelectionListener) { return parentFragment } throw IllegalStateException("Neither activity or parent fragment were a selection listener") } /** * Same action as pressing on the deck in the list. I.e. send the deck to listener and close the dialog. */ protected fun selectDeckAndClose(deck: SelectableDeck) { onDeckSelected(deck) mDialog!!.dismiss() } protected fun displayErrorAndCancel() { mDialog!!.dismiss() } open inner class DecksArrayAdapter(deckNames: List<SelectableDeck>) : RecyclerView.Adapter<DecksArrayAdapter.ViewHolder>(), Filterable { inner class ViewHolder(val deckTextView: TextView) : RecyclerView.ViewHolder(deckTextView) { fun setDeck(deck: SelectableDeck) { deckTextView.text = deck.name } init { deckTextView.setOnClickListener { val deckName = deckTextView.text.toString() selectDeckByNameAndClose(deckName) } deckTextView.setOnLongClickListener { // creating sub deck with parent deck path showSubDeckDialog(deckTextView.text.toString()) true } } } private val mAllDecksList = ArrayList<SelectableDeck>() private val mCurrentlyDisplayedDecks = ArrayList<SelectableDeck>() protected fun selectDeckByNameAndClose(deckName: String) { for (d in mAllDecksList) { if (d.name == deckName) { selectDeckAndClose(d) return } } displayErrorAndCancel() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val v = LayoutInflater.from(parent.context) .inflate(R.layout.deck_picker_dialog_list_item, parent, false) return ViewHolder(v.findViewById(R.id.deck_picker_dialog_list_item_value)) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val deck = mCurrentlyDisplayedDecks[position] holder.setDeck(deck) } override fun getItemCount(): Int { return mCurrentlyDisplayedDecks.size } override fun getFilter(): Filter { return DecksFilter() } /* Custom Filter class - as seen in http://stackoverflow.com/a/29792313/1332026 */ private inner class DecksFilter : Filter() { private val mFilteredDecks: ArrayList<SelectableDeck> = ArrayList() override fun performFiltering(constraint: CharSequence): FilterResults { mFilteredDecks.clear() val allDecks = mAllDecksList if (constraint.isEmpty()) { mFilteredDecks.addAll(allDecks) } else { val filterPattern = constraint.toString().lowercase(Locale.getDefault()).trim { it <= ' ' } for (deck in allDecks) { if (deck.name.lowercase(Locale.getDefault()).contains(filterPattern)) { mFilteredDecks.add(deck) } } } return FilterResultsUtils.fromCollection(mFilteredDecks) } override fun publishResults(charSequence: CharSequence, filterResults: FilterResults) { val currentlyDisplayedDecks = mCurrentlyDisplayedDecks currentlyDisplayedDecks.clear() currentlyDisplayedDecks.addAll(mFilteredDecks) currentlyDisplayedDecks.sort() notifyDataSetChanged() } } init { mAllDecksList.addAll(deckNames) mCurrentlyDisplayedDecks.addAll(deckNames) mCurrentlyDisplayedDecks.sort() } } @KotlinCleanup("auto parcel is needed") open class SelectableDeck : Comparable<SelectableDeck>, Parcelable { /** * Either a deck id or ALL_DECKS_ID */ val deckId: Long /** * Name of the deck, or localization of "all decks" */ val name: String constructor(deckId: Long, name: String) { this.deckId = deckId this.name = name } protected constructor(d: Deck) : this(d.getLong("id"), d.getString("name")) protected constructor(`in`: Parcel) { deckId = `in`.readLong() name = `in`.readString()!! } /** "All decks" comes first. Then usual deck name order. */ override fun compareTo(other: SelectableDeck): Int { if (deckId == Stats.ALL_DECKS_ID) { return if (other.deckId == Stats.ALL_DECKS_ID) { 0 } else -1 } return if (other.deckId == Stats.ALL_DECKS_ID) { 1 } else DeckNameComparator.INSTANCE.compare(name, other.name) } override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeLong(deckId) dest.writeString(name) } companion object { /** * @param filter A method deciding which deck to add * @return the list of all SelectableDecks from the collection satisfying filter */ @JvmStatic @JvmOverloads fun fromCollection(c: Collection, filter: FunctionalInterfaces.Filter<Deck?> = FunctionalInterfaces.Filters.allowAll()): List<SelectableDeck> { val all = c.decks.all() val ret: MutableList<SelectableDeck> = ArrayList(all.size) for (d in all) { if (!filter.shouldInclude(d)) { continue } ret.add(SelectableDeck(d)) } return ret } val CREATOR: Parcelable.Creator<SelectableDeck?> = object : Parcelable.Creator<SelectableDeck?> { override fun createFromParcel(`in`: Parcel): SelectableDeck { return SelectableDeck(`in`) } override fun newArray(size: Int): Array<SelectableDeck?> { return arrayOfNulls(size) } } } } interface DeckSelectionListener { fun onDeckSelected(deck: SelectableDeck?) } companion object { private const val SUMMARY_MESSAGE = "summaryMessage" private const val TITLE = "title" private const val KEEP_RESTORE_DEFAULT_BUTTON = "keepRestoreDefaultButton" private const val DECK_NAMES = "deckNames" /** * A dialog which handles selecting a deck */ @JvmStatic fun newInstance(title: String, summaryMessage: String?, keepRestoreDefaultButton: Boolean, decks: List<SelectableDeck>): DeckSelectionDialog { val f = DeckSelectionDialog() val args = Bundle() args.putString(SUMMARY_MESSAGE, summaryMessage) args.putString(TITLE, title) args.putBoolean(KEEP_RESTORE_DEFAULT_BUTTON, keepRestoreDefaultButton) args.putParcelableArrayList(DECK_NAMES, ArrayList(decks)) f.arguments = args return f } } }
gpl-3.0
5f6bb3d5ef4b2e72a133a6ecdfca462c
38.228426
155
0.634834
5.060904
false
false
false
false
iceboundrock/android-playground
app/src/main/kotlin/li/ruoshi/playground/ActivitiesAdapter.kt
1
1688
package li.ruoshi.playground import android.app.Activity import android.content.Intent import android.content.pm.ActivityInfo import android.content.pm.PackageManager import android.util.Log import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.Button /** * Created by ruoshili on 5/9/15. */ public class ActivitiesAdapter(context: Activity) : ArrayAdapter<ActivityInfo>(context, R.layout.activity_item, R.id.lanuch_activity_button) { companion object { val TAG = ActivitiesAdapter::class.java.simpleName val PackageName = "li.ruoshi.playground" } val activity = context init { val pkgMgr = context.packageManager val pkgInfo = pkgMgr.getPackageInfo(PackageName, PackageManager.GET_ACTIVITIES) val launchIntent = pkgMgr.getLaunchIntentForPackage(PackageName) pkgInfo.activities.filter { a -> !a.name.equals(launchIntent.resolveActivityInfo(pkgMgr, 0).name) }.forEach { a -> this.add(a) } } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? { val ret = super.getView(position, convertView, parent) val btn = ret.findViewById(R.id.lanuch_activity_button) as Button val ai = getItem(position) val btnText = context.resources.getString(ai.labelRes) Log.d(TAG, "Button text: $btnText, position: $position") btn.text = btnText val cls = Class.forName (ai.name) btn.setOnClickListener { v -> val intent = Intent(activity, cls); activity.startActivity(intent) } return ret } }
apache-2.0
f7ef8e30b5a060e75303717b3edb29e5
30.867925
92
0.681872
4.209476
false
false
false
false
vondear/RxTools
RxKit/src/main/java/com/tamsiree/rxkit/demodata/bank/BankCardNumberValidator.kt
1
1073
package com.tamsiree.rxkit.demodata.bank import com.tamsiree.rxkit.demodata.kit.LuhnUtils import org.apache.commons.lang3.StringUtils import org.apache.commons.lang3.math.NumberUtils /** * <pre> * 银行卡号校验类 * Created by Binary Wang on 2018/3/22. </pre> * * * @author [Binary Wang](https://github.com/binarywang) */ object BankCardNumberValidator { /** * 校验银行卡号是否合法 * * @param cardNo 银行卡号 * @return 是否合法 */ fun validate(cardNo: String): Boolean { if (StringUtils.isEmpty(cardNo)) { return false } if (!NumberUtils.isDigits(cardNo)) { return false } if (cardNo.length > 19 || cardNo.length < 16) { return false } val luhnSum = LuhnUtils.getLuhnSum(cardNo.substring(0, cardNo.length - 1).trim { it <= ' ' }.toCharArray()) val checkCode = if (luhnSum % 10 == 0) '0' else (10 - luhnSum % 10 + '0'.toInt()).toChar() return cardNo.substring(cardNo.length - 1)[0] == checkCode } }
apache-2.0
f42845ec00d0bcfc6f4434e84d33c2c9
27.444444
115
0.605083
3.216981
false
false
false
false
android/health-samples
health-connect/HealthConnectSample/app/src/main/java/com/example/healthconnectsample/presentation/HealthConnectApp.kt
1
4682
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.healthconnectsample.presentation import android.annotation.SuppressLint import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.Scaffold import androidx.compose.material.Snackbar import androidx.compose.material.SnackbarHost import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Menu import androidx.compose.material.rememberScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.res.stringResource import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import com.example.healthconnectsample.R import com.example.healthconnectsample.data.HealthConnectAvailability import com.example.healthconnectsample.data.HealthConnectManager import com.example.healthconnectsample.presentation.navigation.Drawer import com.example.healthconnectsample.presentation.navigation.HealthConnectNavigation import com.example.healthconnectsample.presentation.navigation.Screen import com.example.healthconnectsample.presentation.theme.HealthConnectTheme import kotlinx.coroutines.launch const val TAG = "Health Connect sample" @SuppressLint("UnusedMaterialScaffoldPaddingParameter") @Composable fun HealthConnectApp(healthConnectManager: HealthConnectManager) { HealthConnectTheme { val scaffoldState = rememberScaffoldState() val navController = rememberNavController() val scope = rememberCoroutineScope() val navBackStackEntry by navController.currentBackStackEntryAsState() val currentRoute = navBackStackEntry?.destination?.route val availability by healthConnectManager.availability Scaffold( scaffoldState = scaffoldState, topBar = { TopAppBar( title = { val titleId = when (currentRoute) { Screen.ExerciseSessions.route -> Screen.ExerciseSessions.titleId Screen.SleepSessions.route -> Screen.SleepSessions.titleId Screen.InputReadings.route -> Screen.InputReadings.titleId Screen.DifferentialChanges.route -> Screen.DifferentialChanges.titleId else -> R.string.app_name } Text(stringResource(titleId)) }, navigationIcon = { IconButton( onClick = { if (availability == HealthConnectAvailability.INSTALLED) { scope.launch { scaffoldState.drawerState.open() } } } ) { Icon( imageVector = Icons.Rounded.Menu, stringResource(id = R.string.menu) ) } } ) }, drawerContent = { if (availability == HealthConnectAvailability.INSTALLED) { Drawer( scope = scope, scaffoldState = scaffoldState, navController = navController ) } }, snackbarHost = { SnackbarHost(it) { data -> Snackbar(snackbarData = data) } } ) { HealthConnectNavigation( healthConnectManager = healthConnectManager, navController = navController, scaffoldState = scaffoldState ) } } }
apache-2.0
b12a4dba99d0c663f70acfe98ca96024
41.563636
98
0.623024
6.112272
false
false
false
false
Popalay/Cardme
presentation/src/main/kotlin/com/popalay/cardme/presentation/screens/addcard/AddCardActivity.kt
1
2510
package com.popalay.cardme.presentation.screens.addcard import android.arch.lifecycle.ViewModelProvider import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import com.popalay.cardme.R import com.popalay.cardme.data.models.Card import com.popalay.cardme.databinding.ActivityAddCardBinding import com.popalay.cardme.presentation.base.RightSlidingActivity import com.popalay.cardme.utils.extensions.getDataBinding import com.popalay.cardme.utils.extensions.getViewModel import io.reactivex.rxkotlin.addTo import javax.inject.Inject class AddCardActivity : RightSlidingActivity() { companion object { const val KEY_CARD_NUMBER = "KEY_CARD_NUMBER" const val KEY_FORMATTED_CARD_NUMBER = "KEY_FORMATTED_CARD_NUMBER" fun getIntent(context: Context, card: Card) = Intent(context, AddCardActivity::class.java).apply { putExtra(KEY_CARD_NUMBER, card.number) putExtra(KEY_FORMATTED_CARD_NUMBER, card.redactedNumber) } } @Inject lateinit var factory: ViewModelProvider.Factory @Inject lateinit var viewModelFacade: AddCardViewModelFacade private lateinit var b: ActivityAddCardBinding private lateinit var acceptMenuItem: MenuItem override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) b = getDataBinding(R.layout.activity_add_card) b.vm = getViewModel<AddCardViewModel>(factory) initUI() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.accept_menu, menu) acceptMenuItem = menu.findItem(R.id.action_accept) viewModelFacade.onCanSaveStateChanged() .subscribe { acceptMenuItem.isEnabled = it } .addTo(disposables) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_accept -> viewModelFacade.onAcceptClick() } return super.onOptionsItemSelected(item) } override fun getRootView(): View = b.root private fun initUI() { setSupportActionBar(b.toolbar) b.textTitle.setOnFocusChangeListener { _, focus -> b.appBarLayout.setExpanded(!focus) } b.textHolder.setOnFocusChangeListener { _, focus -> b.appBarLayout.setExpanded(!focus) } } }
apache-2.0
9c54758d30cd4efcbf42586d2d586eba
32.466667
106
0.713546
4.514388
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/MessageDialogFragment.kt
1
2443
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.fragment import android.app.Dialog import android.os.Bundle import android.support.v4.app.FragmentManager import android.support.v7.app.AlertDialog import org.mariotaku.ktextension.Bundle import org.mariotaku.ktextension.set import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_MESSAGE import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_TITLE import de.vanita5.twittnuker.extension.applyTheme import de.vanita5.twittnuker.extension.onShow class MessageDialogFragment : BaseDialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val activity = activity val builder = AlertDialog.Builder(activity) val args = arguments builder.setTitle(args.getString(EXTRA_TITLE)) builder.setMessage(args.getString(EXTRA_MESSAGE)) builder.setPositiveButton(android.R.string.ok, null) val dialog = builder.create() dialog.onShow { it.applyTheme() } return dialog } companion object { fun show(fm: FragmentManager, title: String? = null, message: String, tag: String): MessageDialogFragment { val df = create(title, message) df.show(fm, tag) return df } fun create(title: String? = null, message: String): MessageDialogFragment { val df = MessageDialogFragment() df.arguments = Bundle { this[EXTRA_TITLE] = title this[EXTRA_MESSAGE] = message } return df } } }
gpl-3.0
81180f35bc5a167b6144d5b2dc7ee286
35.477612
115
0.702824
4.378136
false
false
false
false
AndroidX/androidx
collection/collection/src/nativeMain/kotlin/androidx/collection/internal/LruHashMap.native.kt
3
2300
/* * 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.collection.internal @Suppress("ACTUAL_WITHOUT_EXPECT") // https://youtrack.jetbrains.com/issue/KT-37316 internal actual class LruHashMap<K : Any, V : Any> actual constructor( initialCapacity: Int, loadFactor: Float, ) { actual constructor(original: LruHashMap<out K, V>) : this( /* * We can't call the primary constructor without passing values, * even though the expect constructor has all default values. * See https://youtrack.jetbrains.com/issue/KT-52193. */ initialCapacity = 16, loadFactor = 0.75F, ) { for ((key, value) in original.entries) { put(key, value) } } private val map = LinkedHashMap<K, V>(initialCapacity, loadFactor) actual val isEmpty: Boolean get() = map.isEmpty() actual val entries: Set<Map.Entry<K, V>> get() = map.entries /** * Works similarly to Java LinkedHashMap with LRU order enabled. * Removes the existing item from the map if there is one, and then adds it back, * so the item is moved to the end. */ actual operator fun get(key: K): V? { val item = map.remove(key) if (item != null) { map[key] = item } return item } /** * Works similarly to Java LinkedHashMap with LRU order enabled. * Removes the existing item from the map if there is one, * then inserts the new item to the map, so the item is moved to the end. */ actual fun put(key: K, value: V): V? { val item = map.remove(key) map[key] = value return item } actual fun remove(key: K): V? = map.remove(key) }
apache-2.0
11f9721a36d1e8c38aad36b2aaac091c
31.394366
85
0.643478
4.078014
false
false
false
false
brianwernick/RecyclerExt
library/src/main/kotlin/com/devbrackets/android/recyclerext/adapter/HeaderAdapter.kt
1
6147
/* * Copyright (C) 2016 - 2020 Brian Wernick * * 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.devbrackets.android.recyclerext.adapter import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ViewHolder import com.devbrackets.android.recyclerext.adapter.header.HeaderApi import com.devbrackets.android.recyclerext.adapter.header.HeaderCore import com.devbrackets.android.recyclerext.adapter.header.HeaderDataGenerator.HeaderData /** * A RecyclerView adapter that adds support for dynamically placing headers in the view. * * @param <H> The Header [RecyclerView.ViewHolder] * @param <C> The Child or content [RecyclerView.ViewHolder] */ abstract class HeaderAdapter<H : ViewHolder, C : ViewHolder> : ActionableAdapter<ViewHolder>(), HeaderApi<H, C> { /** * Contains the base processing for the header adapters */ protected lateinit var core: HeaderCore /** * Initializes the non-super components for the Adapter */ protected fun init() { core = HeaderCore(this) } init { init() } /** * Called to display the header information with the `firstChildPosition` being the * position of the first child after this header. * * @param holder The ViewHolder which should be updated * @param firstChildPosition The position of the child immediately after this header */ abstract fun onBindHeaderViewHolder(holder: H, firstChildPosition: Int) /** * Called to display the child information with the `childPosition` being the * position of the child, excluding headers. * * @param holder The ViewHolder which should be updated * @param childPosition The position of the child */ abstract fun onBindChildViewHolder(holder: C, childPosition: Int) /** * This method shouldn't be used directly, instead use * [onCreateHeaderViewHolder] and * [onCreateChildViewHolder] * * @param parent The parent ViewGroup for the ViewHolder * @param viewType The type for the ViewHolder * @return The correct ViewHolder for the specified viewType */ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return core.onCreateViewHolder(parent, viewType) } /** * This method shouldn't be used directly, instead use * [onBindHeaderViewHolder] and * [onBindChildViewHolder] * * @param holder The ViewHolder to update * @param position The position to update the `holder` with */ @Suppress("UNCHECKED_CAST") override fun onBindViewHolder(holder: ViewHolder, position: Int) { val viewType = getItemViewType(position) val childPosition = getChildPosition(position) if (viewType and HeaderApi.HEADER_VIEW_TYPE_MASK != 0) { onBindHeaderViewHolder(holder as H, childPosition) return } onBindChildViewHolder(holder as C, childPosition) } override var headerData: HeaderData get() = core.headerData set(headerData) { core.headerData = headerData } override var autoUpdateHeaders: Boolean get() = core.autoUpdateHeaders set(autoUpdateHeaders) { core.setAutoUpdateHeaders(this, autoUpdateHeaders) } /** * Retrieves the view type for the specified adapterPosition. * * @param adapterPosition The position to determine the view type for * @return The type of ViewHolder for the `adapterPosition` */ override fun getItemViewType(adapterPosition: Int): Int { return core.getItemViewType(adapterPosition) } /** * When the RecyclerView is attached a data observer is registered * in order to determine when to re-calculate the headers * * @param recyclerView The RecyclerView that was attached */ override fun onAttachedToRecyclerView(recyclerView: RecyclerView) { super.onAttachedToRecyclerView(recyclerView) core.registerObserver(this) } /** * When the RecyclerView is detached the registered data observer * will be unregistered. See [.onAttachedToRecyclerView] * for more information * * @param recyclerView The RecyclerView that has been detached */ override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) { super.onDetachedFromRecyclerView(recyclerView) core.unregisterObserver(this) } /** * Returns the total number of items in the data set hold by the adapter, this includes * both the Headers and the Children views * * * **NOTE:** [.getChildCount] should be overridden instead of this method * * @return The total number of items in this adapter. */ override fun getItemCount(): Int { return core.itemCount } override fun getHeaderViewType(childPosition: Int): Int { return HeaderApi.HEADER_VIEW_TYPE_MASK } override fun getChildViewType(childPosition: Int): Int { return 0 } override fun getChildCount(headerId: Long): Int { return core.getChildCount(headerId) } override fun getHeaderId(childPosition: Int): Long { return RecyclerView.NO_ID } override fun getChildPosition(adapterPosition: Int): Int { return core.getChildPosition(adapterPosition) } override fun getChildIndex(adapterPosition: Int): Int? { return core.getChildIndex(adapterPosition) } override fun getAdapterPositionForChild(childPosition: Int): Int { return core.getAdapterPositionForChild(childPosition) } override fun getHeaderPosition(headerId: Long): Int { return core.getHeaderPosition(headerId) } override fun showHeaderAsChild(enabled: Boolean) { core.showHeaderAsChild(enabled) } override val customStickyHeaderViewId: Int get() = 0 }
apache-2.0
f6c7200daba08ce5bae808e750bcc01f
30.367347
113
0.732878
4.670973
false
false
false
false
androidx/androidx
sqlite/sqlite/src/main/java/androidx/sqlite/db/SupportSQLiteQueryBuilder.kt
3
5307
/* * Copyright (C) 2017 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.sqlite.db import java.util.regex.Pattern /** * A simple query builder to create SQL SELECT queries. */ class SupportSQLiteQueryBuilder private constructor(private val table: String) { private var distinct = false private var columns: Array<out String>? = null private var selection: String? = null private var bindArgs: Array<out Any?>? = null private var groupBy: String? = null private var having: String? = null private var orderBy: String? = null private var limit: String? = null /** * Adds DISTINCT keyword to the query. * * @return this */ fun distinct(): SupportSQLiteQueryBuilder = apply { this.distinct = true } /** * Sets the given list of columns as the columns that will be returned. * * @param columns The list of column names that should be returned. * * @return this */ fun columns(columns: Array<out String>?): SupportSQLiteQueryBuilder = apply { this.columns = columns } /** * Sets the arguments for the WHERE clause. * * @param selection The list of selection columns * @param bindArgs The list of bind arguments to match against these columns * * @return this */ fun selection( selection: String?, bindArgs: Array<out Any?>? ): SupportSQLiteQueryBuilder = apply { this.selection = selection this.bindArgs = bindArgs } /** * Adds a GROUP BY statement. * * @param groupBy The value of the GROUP BY statement. * * @return this */ fun groupBy(groupBy: String?): SupportSQLiteQueryBuilder = apply { this.groupBy = groupBy } /** * Adds a HAVING statement. You must also provide [groupBy] for this to work. * * @param having The having clause. * * @return this */ fun having(having: String?): SupportSQLiteQueryBuilder = apply { this.having = having } /** * Adds an ORDER BY statement. * * @param orderBy The order clause. * * @return this */ fun orderBy(orderBy: String?): SupportSQLiteQueryBuilder = apply { this.orderBy = orderBy } /** * Adds a LIMIT statement. * * @param limit The limit value. * * @return this */ fun limit(limit: String): SupportSQLiteQueryBuilder = apply { val patternMatches = limitPattern.matcher( limit ).matches() require(limit.isEmpty() || patternMatches) { "invalid LIMIT clauses:$limit" } this.limit = limit } /** * Creates the [SupportSQLiteQuery] that can be passed into * [SupportSQLiteDatabase.query]. * * @return a new query */ fun create(): SupportSQLiteQuery { require(!groupBy.isNullOrEmpty() || having.isNullOrEmpty()) { "HAVING clauses are only permitted when using a groupBy clause" } val query = buildString(120) { append("SELECT ") if (distinct) { append("DISTINCT ") } if (columns?.size != 0) { appendColumns(columns!!) } else { append("* ") } append("FROM ") append(table) appendClause(" WHERE ", selection) appendClause(" GROUP BY ", groupBy) appendClause(" HAVING ", having) appendClause(" ORDER BY ", orderBy) appendClause(" LIMIT ", limit) } return SimpleSQLiteQuery(query, bindArgs) } private fun StringBuilder.appendClause(name: String, clause: String?) { if (clause?.isNotEmpty() == true) { append(name) append(clause) } } /** * Add the names that are non-null in columns to string, separating * them with commas. */ private fun StringBuilder.appendColumns(columns: Array<out String>) { val n = columns.size for (i in 0 until n) { val column = columns[i] if (i > 0) { append(", ") } append(column) } append(' ') } companion object { private val limitPattern = Pattern.compile("\\s*\\d+\\s*(,\\s*\\d+\\s*)?") /** * Creates a query for the given table name. * * @param tableName The table name(s) to query. * * @return A builder to create a query. */ @JvmStatic fun builder(tableName: String): SupportSQLiteQueryBuilder { return SupportSQLiteQueryBuilder(tableName) } } }
apache-2.0
9de7d87495da28b8da8c3c3a78a9af37
27.537634
85
0.582815
4.655263
false
false
false
false
androidx/androidx
room/room-compiler/src/main/kotlin/androidx/room/ext/string_ext.kt
3
2281
/* * Copyright (C) 2016 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.room.ext import java.util.Locale private fun String.toCamelCase(): String { val split = this.split("_") if (split.isEmpty()) return "" if (split.size == 1) return split[0].capitalize(Locale.US) return split.joinToCamelCase() } private fun String.toCamelCaseAsVar(): String { val split = this.split("_") if (split.isEmpty()) return "" if (split.size == 1) return split[0] return split.joinToCamelCaseAsVar() } private fun List<String>.joinToCamelCase(): String = when (size) { 0 -> throw IllegalArgumentException("invalid section size, cannot be zero") 1 -> this[0].toCamelCase() else -> this.joinToString("") { it.toCamelCase() } } private fun List<String>.joinToCamelCaseAsVar(): String = when (size) { 0 -> throw IllegalArgumentException("invalid section size, cannot be zero") 1 -> this[0].toCamelCaseAsVar() else -> get(0).toCamelCaseAsVar() + drop(1).joinToCamelCase() } private val javaCharRegex = "[^a-zA-Z0-9]".toRegex() fun String.stripNonJava(): String { return this.split(javaCharRegex) .map(String::trim) .joinToCamelCaseAsVar() } // TODO: Replace this with the function from the Kotlin stdlib once the API becomes stable fun String.capitalize(locale: Locale): String = if (isNotEmpty() && this[0].isLowerCase()) { substring(0, 1).uppercase(locale) + substring(1) } else { this } // TODO: Replace this with the function from the Kotlin stdlib once the API becomes stable fun String.decapitalize(locale: Locale): String = if (isNotEmpty() && this[0].isUpperCase()) { substring(0, 1).lowercase(locale) + substring(1) } else { this }
apache-2.0
7d3b8c6308f9b456e3a1354c2b47926d
33.560606
94
0.698816
3.88586
false
false
false
false
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/core-kotlin-2/src/main/kotlin/com/baeldung/annotations/Validator.kt
1
1283
package com.baeldung.annotations /** * Naive annotation-based validator. * @author A.Shcherbakov */ class Validator() { /** * Return true if every item's property annotated with @Positive is positive and if * every item's property annotated with @AllowedNames has a value specified in that annotation. */ fun isValid(item: Item): Boolean { val fields = item::class.java.declaredFields for (field in fields) { field.isAccessible = true for (annotation in field.annotations) { val value = field.get(item) if (field.isAnnotationPresent(Positive::class.java)) { val amount = value as Float if (amount < 0) { return false } } if (field.isAnnotationPresent(AllowedNames::class.java)) { val allowedNames = field.getAnnotation(AllowedNames::class.java)?.names val name = value as String allowedNames?.let { if (!it.contains(name)) { return false } } } } } return true } }
gpl-3.0
5aa3990bb5376373bde8406b38df8119
32.789474
99
0.501949
5.345833
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/account/AccountSelector.kt
1
5680
/* * Copyright (c) 2016 yvolk (Yuri Volkov), http://yurivolkov.com * * 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.andstatus.app.account import android.content.Intent import android.os.Bundle import android.provider.BaseColumns import android.view.View import android.widget.AdapterView import android.widget.AdapterView.OnItemClickListener import android.widget.TextView import androidx.fragment.app.FragmentActivity import org.andstatus.app.ActivityRequestCode import org.andstatus.app.IntentExtra import org.andstatus.app.R import org.andstatus.app.context.MyContextHolder import org.andstatus.app.net.social.Actor import org.andstatus.app.origin.Origin import org.andstatus.app.view.MyContextMenu import org.andstatus.app.view.MySimpleAdapter import org.andstatus.app.view.SelectorDialog import java.util.* import java.util.function.Predicate import java.util.stream.Collectors /** * @author [email protected] */ class AccountSelector : SelectorDialog() { override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) setTitle(R.string.label_accountselector) val listData = newListData() if (listData.isEmpty()) { returnSelectedAccount(MyAccount.EMPTY) return } else if (listData.size == 1) { returnSelectedAccount(listData[0]) return } setListAdapter(newListAdapter(listData)) listView?.onItemClickListener = OnItemClickListener { _: AdapterView<*>?, view: View, _: Int, _: Long -> val actorId = (view.findViewById<View?>(R.id.id) as TextView).text.toString().toLong() returnSelectedAccount( MyContextHolder.myContextHolder.getNow().accounts.fromActorId(actorId)) } } private fun newListData(): MutableList<MyAccount> { val originId = Optional.ofNullable(arguments) .map { bundle: Bundle -> bundle.getLong(IntentExtra.ORIGIN_ID.key) }.orElse(0L) val origin: Origin = MyContextHolder.myContextHolder.getNow().origins.fromId(originId) val origins: MutableList<Origin> = if (origin.isValid) mutableListOf(origin) else getOriginsForActor() val predicate = if (origins.isEmpty()) Predicate { true } else Predicate { ma: MyAccount -> origins.contains(ma.origin) } return MyContextHolder.myContextHolder.getNow().accounts.get().stream() .filter(predicate) .collect(Collectors.toList()) } private fun getOriginsForActor(): MutableList<Origin> { val actorId = Optional.ofNullable(arguments) .map { bundle: Bundle -> bundle.getLong(IntentExtra.ACTOR_ID.key) }.orElse(0L) return Actor.load( MyContextHolder.myContextHolder.getNow(), actorId) .user.knownInOrigins( MyContextHolder.myContextHolder.getNow()) } private fun newListAdapter(listData: MutableList<MyAccount>): MySimpleAdapter { val list: MutableList<MutableMap<String, String>> = ArrayList() val syncText = getText(R.string.synced_abbreviated).toString() for (ma in listData) { val map: MutableMap<String, String> = HashMap() var visibleName = ma.getAccountName() if (!ma.isValidAndSucceeded()) { visibleName = "($visibleName)" } map[KEY_VISIBLE_NAME] = visibleName map[KEY_SYNC_AUTO] = if (ma.isSyncedAutomatically && ma.isValidAndSucceeded()) syncText else "" map[BaseColumns._ID] = ma.actorId.toString() list.add(map) } return MySimpleAdapter(activity ?: throw IllegalStateException("No activity"), list, R.layout.accountlist_item, arrayOf(KEY_VISIBLE_NAME, KEY_SYNC_AUTO, BaseColumns._ID), intArrayOf(R.id.visible_name, R.id.sync_auto, R.id.id), true) } private fun returnSelectedAccount(ma: MyAccount) { returnSelected(Intent() .putExtra(IntentExtra.ACCOUNT_NAME.key, ma.getAccountName()) .putExtra(IntentExtra.MENU_GROUP.key, myGetArguments().getInt(IntentExtra.MENU_GROUP.key, MyContextMenu.MENU_GROUP_NOTE)) ) } companion object { private val KEY_VISIBLE_NAME: String = "visible_name" private val KEY_SYNC_AUTO: String = "sync_auto" fun selectAccountOfOrigin(activity: FragmentActivity, requestCode: ActivityRequestCode, originId: Long) { val selector: SelectorDialog = AccountSelector() selector.setRequestCode(requestCode).putLong(IntentExtra.ORIGIN_ID.key, originId) selector.show(activity) } fun selectAccountForActor(activity: FragmentActivity, menuGroup: Int, requestCode: ActivityRequestCode, actor: Actor) { val selector: SelectorDialog = AccountSelector() selector.setRequestCode(requestCode).putLong(IntentExtra.ACTOR_ID.key, actor.actorId) selector.myGetArguments().putInt(IntentExtra.MENU_GROUP.key, menuGroup) selector.show(activity) } } }
apache-2.0
7d3315863a542a9aa372d524e563aa5a
44.44
113
0.680634
4.576954
false
false
false
false
InfiniteSoul/ProxerAndroid
src/main/kotlin/me/proxer/app/util/wrapper/MaterialDrawerWrapper.kt
1
13599
package me.proxer.app.util.wrapper import android.app.Activity import android.content.Context import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.view.View import androidx.appcompat.widget.Toolbar import com.mikepenz.crossfader.Crossfader import com.mikepenz.crossfader.view.GmailStyleCrossFadeSlidingPaneLayout import com.mikepenz.iconics.IconicsDrawable import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial import com.mikepenz.iconics.utils.sizeDp import com.mikepenz.materialdrawer.AccountHeader import com.mikepenz.materialdrawer.AccountHeaderBuilder import com.mikepenz.materialdrawer.Drawer import com.mikepenz.materialdrawer.DrawerBuilder import com.mikepenz.materialdrawer.MiniDrawer import com.mikepenz.materialdrawer.interfaces.ICrossfader import com.mikepenz.materialdrawer.model.PrimaryDrawerItem import com.mikepenz.materialdrawer.model.ProfileDrawerItem import com.mikepenz.materialdrawer.model.ProfileSettingDrawerItem import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem import com.mikepenz.materialdrawer.model.interfaces.IProfile import io.reactivex.subjects.PublishSubject import me.proxer.app.R import me.proxer.app.util.DeviceUtils import me.proxer.app.util.data.StorageHelper import me.proxer.app.util.extension.backgroundColorAttr import me.proxer.app.util.extension.colorAttr import me.proxer.app.util.extension.dip import me.proxer.app.util.extension.resolveColor import me.proxer.app.util.extension.safeInject import me.proxer.library.util.ProxerUrls import org.koin.core.KoinComponent /** * @author Ruben Gees */ class MaterialDrawerWrapper( context: Activity, toolbar: Toolbar, savedInstanceState: Bundle?, private val isRoot: Boolean, private val isMain: Boolean ) : KoinComponent { val itemClickSubject: PublishSubject<DrawerItem> = PublishSubject.create() val accountClickSubject: PublishSubject<AccountItem> = PublishSubject.create() val currentItem: DrawerItem? get() { val idToUse = when { drawer.currentSelection >= 0 -> drawer.currentSelection else -> drawer.currentStickyFooterSelectedPosition + 10L } return DrawerItem.fromIdOrNull(idToUse) } private val storageHelper by safeInject<StorageHelper>() private val header: AccountHeader private val drawer: Drawer private val miniDrawer: MiniDrawer? private val crossfader: Crossfader<*>? init { header = buildAccountHeader(context, savedInstanceState) drawer = buildDrawer(context, toolbar, header, savedInstanceState) miniDrawer = when (DeviceUtils.isTablet(context)) { true -> buildMiniDrawer(drawer) false -> null } crossfader = when { miniDrawer != null -> buildCrossfader(context, drawer, miniDrawer, savedInstanceState) else -> null } if (!isRoot) { drawer.deselect() miniDrawer?.setSelection(-1) } } fun onBackPressed() = when { header.isSelectionListShown -> { header.toggleSelectionList(header.view.context) // Return true (handled) if the drawer is open. // Otherwise return false to let the caller handle the back press. crossfader?.isCrossFaded == true || drawer.isDrawerOpen } crossfader?.isCrossFaded == true -> { crossfader.crossFade() true } drawer.isDrawerOpen -> { drawer.closeDrawer() true } else -> false } fun saveInstanceState(outState: Bundle) { header.saveInstanceState(outState) drawer.saveInstanceState(outState) crossfader?.saveInstanceState(outState) } fun select(item: DrawerItem, fireOnClick: Boolean = true) { if (item.id >= 10) { drawer.setStickyFooterSelection(item.id, fireOnClick) } else { drawer.setSelection(item.id, fireOnClick) miniDrawer?.setSelection(item.id) } } fun refreshHeader(context: Context) { val oldProfiles = header.profiles val newProfiles = generateAccountItems(context) if ( oldProfiles == null || oldProfiles.size != newProfiles.size || oldProfiles.withIndex().any { (index, item) -> item.identifier != newProfiles[index].identifier || item.name?.text != newProfiles[index].name?.text } ) { header.profiles = generateAccountItems(context) drawer.recyclerView.adapter?.notifyDataSetChanged() miniDrawer?.createItems() } } fun disableSelectivity() { drawer.drawerItems.forEach { it.isSelectable = false } } private fun buildAccountHeader(context: Activity, savedInstanceState: Bundle?) = AccountHeaderBuilder() .withActivity(context) .withCompactStyle(true) .withHeaderBackground(ColorDrawable(context.resolveColor(R.attr.colorPrimary))) .withTextColor(context.resolveColor(R.attr.colorOnPrimary)) .withSavedInstance(savedInstanceState) .withProfiles(generateAccountItems(context)) .withOnAccountHeaderListener(object : AccountHeader.OnAccountHeaderListener { override fun onProfileChanged(view: View?, profile: IProfile<*>, current: Boolean): Boolean { return onAccountItemClick(profile) } }) .build() private fun buildDrawer( context: Activity, toolbar: Toolbar, accountHeader: AccountHeader, savedInstanceState: Bundle? ) = DrawerBuilder(context) .withToolbar(toolbar) .withAccountHeader(accountHeader) .withDrawerItems(generateDrawerItems()) .withStickyDrawerItems(generateStickyDrawerItems()) .withShowDrawerOnFirstLaunch(true) .withTranslucentStatusBar(true) .withGenerateMiniDrawer(DeviceUtils.isTablet(context)) .withSavedInstance(savedInstanceState) .withOnDrawerItemClickListener(object : Drawer.OnDrawerItemClickListener { override fun onItemClick(view: View?, position: Int, drawerItem: IDrawerItem<*>): Boolean { return onDrawerItemClick(drawerItem) } }) .withOnDrawerNavigationListener(object : Drawer.OnDrawerNavigationListener { override fun onNavigationClickListener(clickedView: View): Boolean { if (!isRoot) context.onBackPressed() return !isRoot } }) .let { if (DeviceUtils.isTablet(context)) it.buildView() else it.build() } .apply { actionBarDrawerToggle?.isDrawerIndicatorEnabled = isRoot } private fun buildMiniDrawer(drawer: Drawer) = drawer.miniDrawer?.apply { withIncludeSecondaryDrawerItems(true) } private fun buildCrossfader( context: Activity, drawer: Drawer, miniDrawer: MiniDrawer, savedInstanceState: Bundle? ) = Crossfader<GmailStyleCrossFadeSlidingPaneLayout>() .withContent(context.findViewById(R.id.root)) .withFirst(drawer.slider, context.dip(300)) .withSecond(miniDrawer.build(context), context.dip(72)) .withSavedInstance(savedInstanceState) .withGmailStyleSwiping() .build() .apply { miniDrawer.withCrossFader(CrossfaderWrapper(this)) getCrossFadeSlidingPaneLayout()?.setShadowResourceLeft(R.drawable.material_drawer_shadow_left) } private fun onDrawerItemClick(item: IDrawerItem<*>) = DrawerItem.fromIdOrDefault(item.identifier).let { if (it.id >= 10L) { miniDrawer?.setSelection(-1) } itemClickSubject.onNext(it) false } private fun onAccountItemClick(profile: IProfile<*>) = AccountItem.fromIdOrDefault(profile.identifier).let { accountClickSubject.onNext(it) // Workaround for crash in current MaterialDrawer version. when { crossfader?.isCrossFaded == true -> { crossfader.crossFade() true } drawer.isDrawerOpen -> { drawer.closeDrawer() true } else -> false } } private fun generateAccountItems(context: Context): MutableList<IProfile<*>> = storageHelper.user.let { when (it) { null -> mutableListOf( ProfileDrawerItem() .withName(R.string.section_guest) .withIcon(R.mipmap.ic_launcher) .withIdentifier(AccountItem.GUEST.id), ProfileSettingDrawerItem() .withName(R.string.section_login) .withIcon(CommunityMaterial.Icon4.cmd_account_key) .withIdentifier(AccountItem.LOGIN.id) ) else -> mutableListOf( ProfileDrawerItem() .withName(it.name) .withEmail(R.string.section_user_subtitle) .apply { if (it.image.isBlank()) { withIcon( IconicsDrawable(context, CommunityMaterial.Icon4.cmd_account) .sizeDp(48) .colorAttr(context, R.attr.colorOnPrimary) .backgroundColorAttr(context, R.attr.colorPrimary) ) } else { withIcon(ProxerUrls.userImage(it.image).toString()) } } .withIdentifier(AccountItem.USER.id), ProfileSettingDrawerItem() .withName(R.string.section_notifications) .withIcon(CommunityMaterial.Icon4.cmd_bell_outline) .withIdentifier(AccountItem.NOTIFICATIONS.id), ProfileSettingDrawerItem() .withName(R.string.section_profile_settings) .withIcon(CommunityMaterial.Icon4.cmd_account_settings) .withIdentifier(AccountItem.PROFILE_SETTINGS.id), ProfileSettingDrawerItem() .withName(R.string.section_logout) .withIcon(CommunityMaterial.Icon4.cmd_account_remove) .withIdentifier(AccountItem.LOGOUT.id) ) } } private fun generateDrawerItems() = listOf( PrimaryDrawerItem() .withName(R.string.section_news) .withIcon(CommunityMaterial.Icon2.cmd_newspaper) .withSelectable(isMain) .withIdentifier(DrawerItem.NEWS.id), PrimaryDrawerItem() .withName(R.string.section_chat) .withIcon(CommunityMaterial.Icon2.cmd_message_text) .withSelectable(isMain) .withIdentifier(DrawerItem.CHAT.id), PrimaryDrawerItem() .withName(R.string.section_bookmarks) .withIcon(CommunityMaterial.Icon4.cmd_bookmark) .withSelectable(isMain) .withIdentifier(DrawerItem.BOOKMARKS.id), PrimaryDrawerItem() .withName(R.string.section_anime) .withIcon(CommunityMaterial.Icon.cmd_television) .withSelectable(isMain) .withIdentifier(DrawerItem.ANIME.id), PrimaryDrawerItem() .withName(R.string.section_schedule) .withIcon(CommunityMaterial.Icon4.cmd_calendar) .withSelectable(isMain) .withIdentifier(DrawerItem.SCHEDULE.id), PrimaryDrawerItem() .withName(R.string.section_manga) .withIcon(CommunityMaterial.Icon4.cmd_book_open_page_variant) .withSelectable(isMain) .withIdentifier(DrawerItem.MANGA.id) ) private fun generateStickyDrawerItems(): MutableList<IDrawerItem<*>> = mutableListOf( PrimaryDrawerItem() .withName(R.string.section_info) .withIcon(CommunityMaterial.Icon2.cmd_information_outline) .withSelectable(isMain) .withIdentifier(DrawerItem.INFO.id), PrimaryDrawerItem() .withName(R.string.section_settings) .withIcon(CommunityMaterial.Icon.cmd_settings) .withSelectable(isMain) .withIdentifier(DrawerItem.SETTINGS.id) ) enum class DrawerItem(val id: Long) { NEWS(0L), CHAT(1L), MESSENGER(1L), BOOKMARKS(2L), ANIME(3L), SCHEDULE(4L), MANGA(5L), INFO(10L), SETTINGS(11L); companion object { fun fromIdOrNull(id: Long?) = values().firstOrNull { it.id == id } fun fromIdOrDefault(id: Long?) = fromIdOrNull(id) ?: NEWS } } enum class AccountItem(val id: Long) { GUEST(100L), LOGIN(101L), USER(102L), LOGOUT(103L), NOTIFICATIONS(104L), PROFILE_SETTINGS(106L); companion object { fun fromIdOrNull(id: Long?) = values().firstOrNull { it.id == id } fun fromIdOrDefault(id: Long?) = fromIdOrNull(id) ?: USER } } private class CrossfaderWrapper(private val crossfader: Crossfader<*>) : ICrossfader { override val isCrossfaded get() = crossfader.isCrossFaded override fun crossfade() = crossfader.crossFade() } }
gpl-3.0
a192b176a45f1e6ab84717d2fbb9995f
36.155738
112
0.627105
4.867215
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/translations/lang/colors/LangColorSettingsPage.kt
1
1549
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.translations.lang.colors import com.demonwav.mcdev.asset.PlatformAssets import com.demonwav.mcdev.translations.lang.LangLexerAdapter import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.options.colors.AttributesDescriptor import com.intellij.openapi.options.colors.ColorDescriptor import com.intellij.openapi.options.colors.ColorSettingsPage class LangColorSettingsPage : ColorSettingsPage { override fun getIcon() = PlatformAssets.MINECRAFT_ICON override fun getHighlighter() = LangSyntaxHighlighter(LangLexerAdapter()) override fun getAdditionalHighlightingTagToDescriptorMap() = emptyMap<String, TextAttributesKey>() override fun getAttributeDescriptors() = DESCRIPTORS override fun getColorDescriptors(): Array<out ColorDescriptor> = ColorDescriptor.EMPTY_ARRAY override fun getDisplayName() = "Minecraft localization" override fun getDemoText() = """ # This is a comment path.to.key=This is a value """.trimIndent() companion object { private val DESCRIPTORS = arrayOf( AttributesDescriptor("Key", LangSyntaxHighlighter.KEY), AttributesDescriptor("Separator", LangSyntaxHighlighter.EQUALS), AttributesDescriptor("Value", LangSyntaxHighlighter.VALUE), AttributesDescriptor("Comments", LangSyntaxHighlighter.COMMENT) ) } }
mit
130a91b87aad89fece57693ad44a9a08
36.780488
102
0.748225
5.323024
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/appwidget/MyRemoteViewData.kt
1
4430
package org.andstatus.app.appwidget import android.app.PendingIntent import android.content.Context import android.text.format.DateFormat import android.text.format.DateUtils import android.text.format.Time import org.andstatus.app.R import org.andstatus.app.notification.NotificationData import org.andstatus.app.util.MyLog import org.andstatus.app.util.RelativeTime internal class MyRemoteViewData { /** "Text" is what is shown in bold */ var widgetText: String = "" /** And the "Comment" is less visible, below the "Text" */ var widgetComment: String = "" /** Construct period of counting... */ var widgetTime: String = "" var onClickIntent: PendingIntent? = null private fun getViewData(context: Context, widgetData: MyAppWidgetData) { val method = "updateView" if (widgetData.dateLastChecked == 0L) { MyLog.d(this, "dateLastChecked==0 ?? " + widgetData.toString()) widgetComment = context.getString(R.string.appwidget_nodata) } else { widgetTime = formatWidgetTime(context, widgetData.dateSince, widgetData.dateLastChecked) widgetData.events.map.values.stream().filter { detail: NotificationData -> detail.count > 0 } .forEach { detail: NotificationData -> widgetText += ((if (widgetText.length > 0) "\n" else "") + context.getText(detail.event.titleResId) + ": " + detail.count) } if (widgetData.events.isEmpty()) { widgetComment = widgetData.nothingPref ?: "" } } onClickIntent = widgetData.events.getPendingIntent() MyLog.v(this) { (method + "; text=\"" + widgetText.replace("\n".toRegex(), "; ") + "\"; comment=\"" + widgetComment + "\"") } } companion object { fun fromViewData(context: Context, widgetData: MyAppWidgetData): MyRemoteViewData { val viewData = MyRemoteViewData() viewData.getViewData(context, widgetData) return viewData } fun formatWidgetTime(context: Context, startMillis: Long, endMillis: Long): String { var formatted = "" var strStart = "" var strEnd = "" if (endMillis == 0L) { formatted = "=0 ???" MyLog.w(context, "formatWidgetTime: endMillis == 0") } else { val timeStart = Time() timeStart.set(startMillis) val timeEnd = Time() timeEnd.set(endMillis) var flags: Int if (timeStart.yearDay < timeEnd.yearDay) { strStart = RelativeTime.getDifference(context, startMillis) if (DateUtils.isToday(endMillis)) { // End - today flags = DateUtils.FORMAT_SHOW_TIME if (DateFormat.is24HourFormat(context)) { flags = flags or DateUtils.FORMAT_24HOUR } strEnd = DateUtils.formatDateTime(context, endMillis, flags) } else { strEnd = RelativeTime.getDifference(context, endMillis) } } else { // Same day if (DateUtils.isToday(endMillis)) { // Start and end - today flags = DateUtils.FORMAT_SHOW_TIME if (DateFormat.is24HourFormat(context)) { flags = flags or DateUtils.FORMAT_24HOUR } strStart = DateUtils.formatDateTime(context, startMillis, flags) strEnd = DateUtils.formatDateTime(context, endMillis, flags) } else { strStart = RelativeTime.getDifference(context, endMillis) } } formatted = strStart if (strEnd.length > 0 && strEnd.compareTo(strStart) != 0) { if (formatted.length > 0) { formatted += " - " } formatted += strEnd } } return formatted } } }
apache-2.0
98edadc7a1cd8a1d437eb4ae7b7fb060
41.190476
105
0.518962
5.011312
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/widgets/dialog/ListDialogView.kt
2
2652
package ru.fantlab.android.ui.widgets.dialog import android.content.Context import android.os.Bundle import android.os.Parcelable import android.view.View import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.android.synthetic.main.simple_list_dialog.* import ru.fantlab.android.R import ru.fantlab.android.helper.BundleConstant import ru.fantlab.android.helper.Bundler import ru.fantlab.android.ui.adapter.SimpleListAdapter import ru.fantlab.android.ui.base.BaseDialogFragment import ru.fantlab.android.ui.base.mvp.BaseMvp import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter import ru.fantlab.android.ui.widgets.recyclerview.BaseViewHolder import java.util.* class ListDialogView<T : Parcelable> : BaseDialogFragment<BaseMvp.View, BasePresenter<BaseMvp.View>>(), BaseViewHolder.OnItemClickListener<T> { private var callbacks: ListDialogViewActionCallback? = null override fun fragmentLayout(): Int { return R.layout.simple_list_dialog } override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) { val objects = arguments!!.getParcelableArrayList<T>(BundleConstant.ITEM) if (objects.size == 1) { onItemClick(0, view, objects[0]) return } val titleText = arguments!!.getString(BundleConstant.EXTRA) title.text = titleText if (objects != null) { val adapter = SimpleListAdapter<T>(objects) adapter.listener = this recycler.addDivider() recycler.adapter = adapter recycler.layoutManager = LinearLayoutManager(activity) } else { dismiss() } fastScroller.attachRecyclerView(recycler) } override fun providePresenter(): BasePresenter<BaseMvp.View> { return BasePresenter() } override fun onMessageDialogActionClicked(isOk: Boolean, bundle: Bundle?) { } override fun onDialogDismissed() { } override fun onItemClick(position: Int, v: View?, item: T) { dismiss() if (callbacks != null) callbacks!!.onItemSelected(item, position) } override fun onItemLongClick(position: Int, v: View?, item: T) { } fun initArguments(title: String, objects: ArrayList<T>) { arguments = Bundler.start() .put(BundleConstant.EXTRA, title) .put(BundleConstant.ITEM, objects) .end() } override fun onAttach(context: Context) { super.onAttach(context) if (parentFragment != null && parentFragment is ListDialogViewActionCallback) { callbacks = parentFragment as ListDialogViewActionCallback } else if (context is ListDialogViewActionCallback) { callbacks = context } } override fun onDetach() { super.onDetach() callbacks = null } interface ListDialogViewActionCallback { fun <T> onItemSelected(item: T, position: Int) } }
gpl-3.0
6594e92a51792def1cd7377609a2ee51
28.808989
143
0.762821
3.911504
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/adapter/viewholder/NewsViewHolder.kt
2
2232
package ru.fantlab.android.ui.adapter.viewholder import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.news_row_item.view.* import ru.fantlab.android.R import ru.fantlab.android.data.dao.model.News import ru.fantlab.android.helper.InputHelper import ru.fantlab.android.helper.getTimeAgo import ru.fantlab.android.helper.parseFullDate import ru.fantlab.android.provider.scheme.LinkParserHelper import ru.fantlab.android.ui.widgets.recyclerview.BaseRecyclerAdapter import ru.fantlab.android.ui.widgets.recyclerview.BaseViewHolder class NewsViewHolder(itemView: View, adapter: BaseRecyclerAdapter<News, NewsViewHolder>) : BaseViewHolder<News>(itemView, adapter) { override fun bind(news: News) { val authorId = "user(\\d+)\\D".toRegex().find(news.author) itemView.avatarLayout.setUrl("https://${LinkParserHelper.HOST_DATA}/images/users/${authorId?.groupValues?.get(1)}") itemView.coverLayout.setUrl("https:${news.image}", "file:///android_asset/svg/fl_news.svg") if (!InputHelper.isEmpty(news.title)) { itemView.title.text = news.title itemView.title.visibility = View.VISIBLE } else itemView.title.visibility = View.GONE if (!InputHelper.isEmpty(news.description) && !news.newsText.contains("\\[print_contest=(\\d+)\\]".toRegex())) { itemView.newsText.text = news.description.replace("<.*>(.*?)<\\/.*>".toRegex(), "$1") itemView.newsText.visibility = View.VISIBLE } else itemView.newsText.visibility = View.GONE itemView.category.text = news.category.capitalize() itemView.date.text = news.newsDateIso.parseFullDate(true).getTimeAgo() itemView.author.text = news.author.replace("<.*>(.*?)<.*>".toRegex(), "$1") itemView.userInfo.setOnClickListener { listener?.onOpenContextMenu(news) } } interface OnOpenContextMenu { fun onOpenContextMenu(news: News) } companion object { private var listener: OnOpenContextMenu? = null fun newInstance( viewGroup: ViewGroup, adapter: BaseRecyclerAdapter<News, NewsViewHolder> ): NewsViewHolder { return NewsViewHolder(getView(viewGroup, R.layout.news_row_item), adapter) } fun setOnContextMenuListener(listener: NewsViewHolder.OnOpenContextMenu) { this.listener = listener } } }
gpl-3.0
38c7f0329c73d709ffb3dd5db8529616
36.216667
117
0.755824
3.701493
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/modules/editor/popup/linkimage/EditorLinkImageDialogFragment.kt
2
2623
package ru.fantlab.android.ui.modules.editor.popup.linkimage import android.content.Context import android.os.Bundle import android.view.View import kotlinx.android.synthetic.main.editor_link_image_dialog_layout.* import ru.fantlab.android.R import ru.fantlab.android.helper.BundleConstant import ru.fantlab.android.helper.Bundler import ru.fantlab.android.helper.InputHelper import ru.fantlab.android.ui.base.BaseDialogFragment class EditorLinkImageDialogFragment : BaseDialogFragment<EditorLinkImageMvp.View, EditorLinkImagePresenter>(), EditorLinkImageMvp.View { private var callbacks: EditorLinkImageMvp.EditorLinkCallback? = null private val isLink: Boolean get() = arguments != null && arguments!!.getBoolean(BundleConstant.YES_NO_EXTRA) override fun onAttach(context: Context) { super.onAttach(context) if (parentFragment is EditorLinkImageMvp.EditorLinkCallback) { callbacks = parentFragment as EditorLinkImageMvp.EditorLinkCallback? } else if (context is EditorLinkImageMvp.EditorLinkCallback) { callbacks = context } } override fun onDetach() { callbacks = null super.onDetach() } override fun onUploaded(title: String, link: String) { hideProgress() if (callbacks != null) { callbacks!!.onAppendLink(title, link.replace("http:", "https:"), isLink) } dismiss() } override fun fragmentLayout() = R.layout.editor_link_image_dialog_layout override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) { if (savedInstanceState == null) { link_title.editText!!.setText(arguments!!.getString(BundleConstant.ITEM)) if (!isLink) { link_title.isEnabled = false link_title.hint = getString(R.string.no_title) } } cancel.setOnClickListener { dismiss() } insert.setOnClickListener { onInsertClicked() } } override fun providePresenter(): EditorLinkImagePresenter { return EditorLinkImagePresenter() } private fun onInsertClicked() { if (callbacks != null) { callbacks!!.onAppendLink(InputHelper.toString(link_title), InputHelper.toString(link_link), isLink) } dismiss() } override fun onMessageDialogActionClicked( isOk: Boolean, bundle: Bundle? ) { } override fun onDialogDismissed() { } fun newInstance(): EditorLinkImageDialogFragment { return EditorLinkImageDialogFragment() } companion object { fun newInstance(isLink: Boolean, link: String): EditorLinkImageDialogFragment { val fragment = EditorLinkImageDialogFragment() fragment.arguments = Bundler .start() .put(BundleConstant.YES_NO_EXTRA, isLink) .put(BundleConstant.ITEM, link) .end() return fragment } } }
gpl-3.0
2064e43ad5dc8315e6e0b64934f2df1d
27.204301
136
0.754098
3.768678
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/controls/UploadButton.kt
1
1115
package de.westnordost.streetcomplete.controls import android.content.Context import android.util.AttributeSet import android.widget.RelativeLayout import androidx.core.view.isInvisible import de.westnordost.streetcomplete.R import kotlinx.android.synthetic.main.view_upload_button.view.* /** A view that shows an upload-icon, with a counter at the top right and an (upload) progress view * */ class UploadButton @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : RelativeLayout(context, attrs, defStyleAttr) { var uploadableCount: Int = 0 set(value) { field = value textView.text = value.toString() textView.isInvisible = value == 0 } override fun setEnabled(enabled: Boolean) { super.setEnabled(enabled) iconView.alpha = if (enabled) 1f else 0.5f } var showProgress: Boolean = false set(value) { field = value progressView.isInvisible = !value } init { inflate(context, R.layout.view_upload_button, this) clipToPadding = false } }
gpl-3.0
acf3d67896b7316c17784fecb645af5b
26.875
99
0.688789
4.207547
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/operatorConventions/augmentedAssignmentInInitializer.kt
4
659
abstract class A { val b = B("O") open val c: B val d: B get() = field var e: String get() = field init { c = B("O") d = B("O") e = "O" b += "," c += "." d += ";" e += "|" } } class B(var value: String) { operator fun plusAssign(o: String) { value += o } } class C : A() { init { b += "K" c += "K" d += "K" e += "K" } } fun box(): String { val c = C() val result = "${c.b.value} ${c.c.value} ${c.d.value} ${c.e}" if (result != "O,K O.K O;K O|K") return "fail: $result" return "OK" }
apache-2.0
bd48b1b29819d855140044de5d1b3668
13.666667
64
0.361153
2.928889
false
false
false
false
olivierperez/crapp
lib/src/main/java/fr/o80/sample/lib/utils/GenericDiffCallback.kt
1
719
package fr.o80.sample.lib.utils /** * @author Olivier Perez */ import android.support.v7.util.DiffUtil abstract class GenericDiffCallback<in T>(private val oldList: List<T>, private val newList: List<T>) : DiffUtil.Callback() { override fun getOldListSize(): Int = oldList.size override fun getNewListSize(): Int = newList.size override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) = isSameItem(oldList[oldItemPosition], newList[newItemPosition]) override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) = oldList[oldItemPosition] == newList[newItemPosition] protected abstract fun isSameItem(oldItem: T, newItem: T): Boolean }
apache-2.0
71c111c86616b313386117630e85d596
31.727273
124
0.735744
4.550633
false
false
false
false
Maccimo/intellij-community
tools/intellij.ide.starter/testSrc/com/intellij/ide/starter/tests/unit/RunIdeEventsTest.kt
1
2719
package com.intellij.ide.starter.tests.unit import com.intellij.ide.starter.bus.EventState import com.intellij.ide.starter.bus.StarterListener import com.intellij.ide.starter.bus.subscribe import com.intellij.ide.starter.di.di import com.intellij.ide.starter.ide.IDETestContext import com.intellij.ide.starter.ide.InstalledIDE import com.intellij.ide.starter.ide.command.CommandChain import com.intellij.ide.starter.models.TestCase import com.intellij.ide.starter.path.IDEDataPaths import com.intellij.ide.starter.runner.IdeLaunchEvent import com.intellij.ide.starter.utils.catchAll import com.intellij.ide.starter.utils.hyphenateTestName import io.kotest.assertions.assertSoftly import io.kotest.assertions.withClue import io.kotest.inspectors.shouldForAtLeastOne import io.kotest.matchers.shouldBe import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.junit.jupiter.api.io.TempDir import org.kodein.di.direct import org.kodein.di.instance import org.mockito.Mock import org.mockito.junit.jupiter.MockitoExtension import java.nio.file.Path import kotlin.time.Duration @ExtendWith(MockitoExtension::class) class RunIdeEventsTest { @TempDir lateinit var testDirectory: Path @Mock private lateinit var testCase: TestCase @Mock private lateinit var ide: InstalledIDE @Disabled("Rewrite the test to be more stable") @Test fun eventsForIdeLaunchShouldBeFired() { val testName = object {}.javaClass.enclosingMethod.name.hyphenateTestName() val paths = IDEDataPaths.createPaths(testName, testDirectory, useInMemoryFs = false) val projectHome = testCase.projectInfo?.resolveProjectHome() val context = IDETestContext(paths = paths, ide = ide, testCase = testCase, testName = testName, _resolvedProjectHome = projectHome, patchVMOptions = { this }, ciServer = di.direct.instance()) val firedEvents = mutableListOf<IdeLaunchEvent>() StarterListener.subscribe { event: IdeLaunchEvent -> firedEvents.add(event) } catchAll { context.runIDE(commands = CommandChain()) } runBlocking { delay(Duration.seconds(3)) } assertSoftly { withClue("During IDE run should be fired 2 events: before ide start and after ide finished") { firedEvents.shouldForAtLeastOne { it.state.shouldBe(EventState.BEFORE) } firedEvents.shouldForAtLeastOne { it.state.shouldBe(EventState.AFTER) } } } } }
apache-2.0
eee82826986682a508352aa39ee9f054
34.324675
100
0.731151
4.295419
false
true
false
false
orbite-mobile/monastic-jerusalem-community
app/src/main/java/pl/orbitemobile/wspolnoty/activities/article/ArticlePresenter.kt
1
2253
/* * Copyright (c) 2017. All Rights Reserved. Michal Jankowski orbitemobile.pl */ package pl.orbitemobile.wspolnoty.activities.article import android.content.Intent import android.net.Uri import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable import pl.orbitemobile.wspolnoty.activities.article.domain.ArticleUseCase import pl.orbitemobile.wspolnoty.data.dto.ArticleDTO class ArticlePresenter(override var view: ArticleContract.View? = null, override var disposable: CompositeDisposable? = CompositeDisposable()) : ArticleContract.Presenter { private val useCase: ArticleContract.UseCase = ArticleUseCase() private val ARTICLE_URL = "ARTICLE_URL" var articleUrl: String? = null override fun onViewAttached() { view?.showLoadingScreen() setArticleUrl() issueDataDownloadIfNetworkIsAvailable() } private fun setArticleUrl() { val intent = view?.getIntent() if (intent?.hasArticleUrl() == true) { intent.setArticleUrl() } } override fun onRetryClick() = issueDataDownloadIfNetworkIsAvailable() override fun onShowWebsiteClick() { val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(articleUrl)) view?.context?.startActivity(browserIntent) } private fun issueDataDownloadIfNetworkIsAvailable() { if (isNetwork()) { view?.showLoadingScreen() issueDataDownload() } else { view?.showErrorMessage() view?.showNetworkToast() } } private fun issueDataDownload() { val articleUrl = articleUrl if (articleUrl != null) { useCase.getRemoteArticleDetails(articleUrl).subscribe(this) } } private fun Intent.hasArticleUrl(): Boolean = hasExtra(ARTICLE_URL) private fun Intent.setArticleUrl() { articleUrl = getStringExtra(ARTICLE_URL) } override fun onSubscribe(d: Disposable) { disposable?.add(d) } override fun onError(e: Throwable) { view?.showErrorMessage() e.printStackTrace() } override fun onSuccess(article: ArticleDTO) { view?.showArticleDetails(article) } }
agpl-3.0
18e271a6c438db9d501bb6c2458bd442
28.25974
123
0.673324
4.733193
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/sitecreation/domains/SiteCreationDomainSanitizer.kt
1
1326
package org.wordpress.android.ui.sitecreation.domains import java.util.Locale import javax.inject.Inject class SiteCreationDomainSanitizer @Inject constructor() { private val String.removeProtocol: String get() = this.replace("http://", "").replace("https://", "") private val String.removeNonAlphanumeric: String get() = this.replace("[^a-zA-Z0-9]".toRegex(), "") private val String.firstPeriodIndex: Int? get() = this.indexOf(".").let { return if (it > 0) it else null } private val String.firstPart: String get() = this.firstPeriodIndex?.let { return substring(0, it) } ?: this private val String.lastPart: String get() = this.firstPeriodIndex?.let { return substring(it) } ?: this /** * Returns the first part of the domain */ fun getName(url: String) = url.firstPart.removeProtocol /** * Returns the last part of the domain (after the first .) */ fun getDomain(url: String) = url.lastPart /** * Sanitizes a query by taking the value before it's first period if it's present, * removes it's scheme and finally, removes any characters that aren't alphanumeric. */ fun sanitizeDomainQuery(query: String) = query.firstPart.removeProtocol.removeNonAlphanumeric.lowercase(Locale.ROOT) }
gpl-2.0
28df7f9ca021d078bf5662a551790e69
33
88
0.666667
4.105263
false
false
false
false
SnakeEys/MessagePlus
app/src/main/java/info/fox/messup/contacts/AdapterContact.kt
1
2086
package info.fox.messup.contacts import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import info.fox.messup.R import info.fox.messup.listener.RecyclerItemClickListener import info.fox.messup.listener.RecyclerItemLongClickListener /** * Created by snake * on 17/6/9. */ internal class AdapterContact(private var data: List<*>) : RecyclerView.Adapter<AdapterContact.ViewHolder>() { private var mClickListener: RecyclerItemClickListener? = null private var mLongClickListener: RecyclerItemLongClickListener? = null fun getData(): List<*> { return data } fun setClickListener(listener: RecyclerItemClickListener) { mClickListener = listener } fun setLongClickListener(listener: RecyclerItemLongClickListener) { mLongClickListener = listener } override fun getItemCount(): Int { return data.size } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent?.context).inflate(R.layout.item_messages, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val msg = data[position] } inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val icon = itemView.findViewById(R.id.iv_icon) as ImageView val person = itemView.findViewById(R.id.tv_person) as TextView val body = itemView.findViewById(R.id.tv_body) as TextView val count = itemView.findViewById(R.id.tv_count) as TextView val date = itemView.findViewById(R.id.tv_date) as TextView init { itemView.setOnClickListener { mClickListener?.onRecyclerItemClicked(it, adapterPosition) } itemView.setOnLongClickListener { mLongClickListener?.onRecyclerItemLongClicked(it, adapterPosition) true } } } }
mit
9fd7472025dbcb1daf6943bbf4b6828b
31.609375
110
0.710451
4.751708
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/inline/namedFunction/expressionBody/FunctionalParameterPassed.kt
4
248
fun <caret>foo(p1: String, p2: () -> Boolean) = bar(p1, null, p2) fun bar(p1: String, p2: String?, p3: () -> Boolean) = Unit fun check(s: String) = s == "baz" fun foo(i: I) { foo("foo") { println("bar") check("baz") } }
apache-2.0
15f9bc5fa6667e4b608db191096b090e
18.076923
65
0.504032
2.48
false
false
false
false
MER-GROUP/intellij-community
platform/script-debugger/backend/src/org/jetbrains/debugger/SuspendContextManagerBase.kt
4
2961
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.rejectedPromise import org.jetbrains.concurrency.resolvedPromise import java.util.concurrent.atomic.AtomicReference abstract class SuspendContextManagerBase<T : SuspendContextBase<*, *, CALL_FRAME>, CALL_FRAME : CallFrame> : SuspendContextManager<CALL_FRAME> { val contextRef = AtomicReference<T>() protected val suspendCallback = AtomicReference<AsyncPromise<Void>>() protected abstract val debugListener: DebugEventListener fun setContext(newContext: T) { if (!contextRef.compareAndSet(null, newContext)) { throw IllegalStateException("Attempt to set context, but current suspend context is already exists") } } // dismiss context on resumed protected fun dismissContext() { val context = contextRef.get() if (context != null) { contextDismissed(context) } } protected fun dismissContextOnDone(promise: Promise<*>): Promise<*> { val context = contextOrFail promise.done { contextDismissed(context) } return promise } fun contextDismissed(context: T) { if (!contextRef.compareAndSet(context, null)) { throw IllegalStateException("Expected $context, but another suspend context exists") } context.valueManager.markObsolete() debugListener.resumed() } override val context: SuspendContext<CALL_FRAME>? get() = contextRef.get() override val contextOrFail: T get() = contextRef.get() ?: throw IllegalStateException("No current suspend context") override fun suspend(): Promise<*> { val callback = suspendCallback.get() if (callback != null) { return callback } return if (context != null) resolvedPromise() else doSuspend() } protected abstract fun doSuspend(): Promise<*> override fun isContextObsolete(context: SuspendContext<CALL_FRAME>) = this.context !== context override fun setOverlayMessage(message: String?) { } override fun restartFrame(callFrame: CALL_FRAME): Promise<Boolean> = restartFrame(callFrame, contextOrFail) protected open fun restartFrame(callFrame: CALL_FRAME, currentContext: T) = rejectedPromise<Boolean>("Unsupported") override fun canRestartFrame(callFrame: CallFrame) = false override val isRestartFrameSupported = false }
apache-2.0
7e91882ba285178e676d37086c882870
33.045977
144
0.741979
4.626563
false
false
false
false
spinnaker/orca
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/RunTaskHandlerTest.kt
1
72242
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.netflix.spectator.api.NoopRegistry import com.netflix.spinnaker.kork.dynamicconfig.DynamicConfigService import com.netflix.spinnaker.orca.DefaultStageResolver import com.netflix.spinnaker.orca.api.pipeline.TaskExecutionInterceptor import com.netflix.spinnaker.orca.TaskResolver import com.netflix.spinnaker.orca.api.pipeline.Task import com.netflix.spinnaker.orca.api.pipeline.TaskResult import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.CANCELED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.FAILED_CONTINUE import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.PAUSED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SKIPPED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.STOPPED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SUCCEEDED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.TERMINAL import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType.PIPELINE import com.netflix.spinnaker.orca.api.pipeline.models.PipelineExecution.PausedDetails import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution import com.netflix.spinnaker.orca.api.test.pipeline import com.netflix.spinnaker.orca.api.test.stage import com.netflix.spinnaker.orca.api.test.task import com.netflix.spinnaker.orca.echo.pipeline.ManualJudgmentStage import com.netflix.spinnaker.orca.exceptions.ExceptionHandler import com.netflix.spinnaker.orca.pipeline.DefaultStageDefinitionBuilderFactory import com.netflix.spinnaker.orca.pipeline.RestrictExecutionDuringTimeWindow import com.netflix.spinnaker.orca.pipeline.model.DefaultTrigger import com.netflix.spinnaker.orca.pipeline.model.StageExecutionImpl.STAGE_TIMEOUT_OVERRIDE_KEY import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.pipeline.tasks.WaitTask import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor import com.netflix.spinnaker.orca.pipeline.util.StageNavigator import com.netflix.spinnaker.orca.q.DummyTask import com.netflix.spinnaker.orca.q.singleTaskStage import com.netflix.spinnaker.orca.q.DummyCloudProviderAwareTask import com.netflix.spinnaker.orca.q.DummyTimeoutOverrideTask import com.netflix.spinnaker.orca.q.TasksProvider import com.netflix.spinnaker.orca.q.RunTask import com.netflix.spinnaker.orca.q.CompleteTask import com.netflix.spinnaker.orca.q.PauseTask import com.netflix.spinnaker.orca.q.InvalidTask import com.netflix.spinnaker.orca.q.InvalidTaskType import com.netflix.spinnaker.q.Queue import com.netflix.spinnaker.spek.and import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.anyOrNull import com.nhaarman.mockito_kotlin.check import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.doThrow import com.nhaarman.mockito_kotlin.eq import com.nhaarman.mockito_kotlin.isA import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.never import com.nhaarman.mockito_kotlin.reset import com.nhaarman.mockito_kotlin.times import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.verifyNoMoreInteractions import com.nhaarman.mockito_kotlin.whenever import java.time.Clock import java.time.Duration import java.time.Instant import java.time.ZoneId import java.time.temporal.ChronoUnit import kotlin.collections.set import kotlin.reflect.jvm.jvmName import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP import org.jetbrains.spek.subject.SubjectSpek import org.junit.jupiter.api.Assertions.assertEquals import org.mockito.Mockito.spy import org.threeten.extra.Minutes object RunTaskHandlerTest : SubjectSpek<RunTaskHandler>({ val queue: Queue = mock() val repository: ExecutionRepository = mock() val task: DummyTask = mock { on { extensionClass } doReturn DummyTask::class.java on { aliases() } doReturn emptyList<String>() } val cloudProviderAwareTask: DummyCloudProviderAwareTask = mock { on { extensionClass } doReturn DummyCloudProviderAwareTask::class.java } val timeoutOverrideTask: DummyTimeoutOverrideTask = mock { on { extensionClass } doReturn DummyTimeoutOverrideTask::class.java on { aliases() } doReturn emptyList<String>() } val tasks = mutableListOf(task, cloudProviderAwareTask, timeoutOverrideTask) val exceptionHandler: ExceptionHandler = mock() // Stages store times as ms-since-epoch, and we do a lot of tests to make sure things run at the // appropriate time, so we need to make sure // clock.instant() == Instant.ofEpochMilli(clock.instant()) val clock = Clock.fixed(Instant.now().truncatedTo(ChronoUnit.MILLIS), ZoneId.systemDefault()) val contextParameterProcessor = ContextParameterProcessor() val dynamicConfigService: DynamicConfigService = mock() val taskExecutionInterceptors: List<TaskExecutionInterceptor> = listOf(mock()) val stageResolver : DefaultStageResolver = mock() val manualJudgmentStage : ManualJudgmentStage = ManualJudgmentStage() val stageNavigator: StageNavigator = mock() subject(GROUP) { whenever(dynamicConfigService.getConfig(eq(Int::class.java), eq("tasks.warningInvocationTimeMs"), any())) doReturn 0 RunTaskHandler( queue, repository, stageNavigator, DefaultStageDefinitionBuilderFactory(stageResolver), contextParameterProcessor, TaskResolver(TasksProvider(mutableListOf(task, timeoutOverrideTask, cloudProviderAwareTask) as Collection<Task>)), clock, listOf(exceptionHandler), taskExecutionInterceptors, NoopRegistry(), dynamicConfigService ) } fun resetMocks() = reset(queue, repository, task, timeoutOverrideTask, cloudProviderAwareTask, exceptionHandler) describe("running a task") { describe("that completes successfully") { val pipeline = pipeline { stage { type = "whatever" task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) and("has no context updates outputs") { val taskResult = TaskResult.SUCCEEDED beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("executes the task") { verify(task).execute(pipeline.stages.first()) } it("completes the task") { verify(queue).push( check<CompleteTask> { assertThat(it.status).isEqualTo(SUCCEEDED) } ) } it("does not update the stage or global context") { verify(repository, never()).storeStage(any()) } } and("has context updates") { val stageOutputs = mapOf("foo" to "covfefe") val taskResult = TaskResult.builder(SUCCEEDED).context(stageOutputs).build() beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("updates the stage context") { verify(repository).storeStage( check { assertThat(stageOutputs).isEqualTo(it.context) } ) } } and("has outputs") { val outputs = mapOf("foo" to "covfefe") val taskResult = TaskResult.builder(SUCCEEDED).outputs(outputs).build() beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("updates the stage outputs") { verify(repository).storeStage( check { assertThat(it.outputs).isEqualTo(outputs) } ) } } and("outputs a stageTimeoutMs value") { val outputs = mapOf( "foo" to "covfefe", "stageTimeoutMs" to Long.MAX_VALUE ) val taskResult = TaskResult.builder(SUCCEEDED).outputs(outputs).build() beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("does not write stageTimeoutMs to outputs") { verify(repository).storeStage( check { assertThat(it.outputs) .containsKey("foo") .doesNotContainKey("stageTimeoutMs") } ) } } } describe("that completes successfully prefering specified TaskExecution implementingClass") { val pipeline = pipeline { stage { type = "whatever" task { id = "1" startTime = clock.instant().toEpochMilli() implementingClass = task.javaClass.canonicalName } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", WaitTask::class.java) and("has no context updates outputs") { val taskResult = TaskResult.SUCCEEDED beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("executes the task") { verify(task).execute(pipeline.stages.first()) } it("completes the task") { verify(queue).push( check<CompleteTask> { assertThat(it.status).isEqualTo(SUCCEEDED) } ) } it("does not update the stage or global context") { verify(repository, never()).storeStage(any()) } } and("has context updates") { val stageOutputs = mapOf("foo" to "covfefe") val taskResult = TaskResult.builder(SUCCEEDED).context(stageOutputs).build() beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("updates the stage context") { verify(repository).storeStage( check { assertThat(stageOutputs).isEqualTo(it.context) } ) } } and("has outputs") { val outputs = mapOf("foo" to "covfefe") val taskResult = TaskResult.builder(SUCCEEDED).outputs(outputs).build() beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("updates the stage outputs") { verify(repository).storeStage( check { assertThat(it.outputs).isEqualTo(outputs) } ) } } and("outputs a stageTimeoutMs value") { val outputs = mapOf( "foo" to "covfefe", "stageTimeoutMs" to Long.MAX_VALUE ) val taskResult = TaskResult.builder(SUCCEEDED).outputs(outputs).build() beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("does not write stageTimeoutMs to outputs") { verify(repository).storeStage( check { assertThat(it.outputs) .containsKey("foo") .doesNotContainKey("stageTimeoutMs") } ) } } } describe("that is not yet complete") { val pipeline = pipeline { stage { type = "whatever" task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) val taskResult = TaskResult.RUNNING val taskBackoffMs = 30_000L val maxBackOffLimit = 120_000L beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.maxTaskBackoff()) doReturn maxBackOffLimit } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(task.getDynamicBackoffPeriod(any(), any())) doReturn taskBackoffMs whenever(dynamicConfigService.getConfig(eq(Long::class.java), eq("tasks.global.backOffPeriod"), any())) doReturn 0L whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("re-queues the command") { verify(queue).push(message, Duration.ofMillis(taskBackoffMs)) } } setOf(TERMINAL, CANCELED).forEach { taskStatus -> describe("that fails with $taskStatus") { val pipeline = pipeline { stage { refId = "1" type = "whatever" task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) val taskResult = TaskResult.ofStatus(taskStatus) and("no overrides are in place") { beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("marks the task $taskStatus") { verify(queue).push( check<CompleteTask> { assertThat(it.status).isEqualTo(taskStatus) } ) } } and("the task should not fail the whole pipeline, only the branch") { beforeGroup { pipeline.stageByRef("1").apply { context["failPipeline"] = false context["continuePipeline"] = false } tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) afterGroup { pipeline.stages.first().context.clear() } action("the handler receives a message") { subject.handle(message) } it("marks the task STOPPED") { verify(queue).push( check<CompleteTask> { assertThat(it.status).isEqualTo(STOPPED) } ) } } and("the task should allow the pipeline to proceed") { beforeGroup { pipeline.stageByRef("1").apply { context["failPipeline"] = false context["continuePipeline"] = true } tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) afterGroup { pipeline.stages.first().context.clear() } action("the handler receives a message") { subject.handle(message) } it("marks the task FAILED_CONTINUE") { verify(queue).push( check<CompleteTask> { assertThat(it.status).isEqualTo(FAILED_CONTINUE) } ) } } } } describe("that throws an exception") { val pipeline = pipeline { stage { refId = "1" type = "whatever" task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) val taskResult = TaskResult.ofStatus(TERMINAL) and("it is not recoverable") { val exceptionDetails = ExceptionHandler.Response( RuntimeException::class.qualifiedName, "o noes", ExceptionHandler.responseDetails("o noes"), false ) and("the task should fail the pipeline") { beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doThrow RuntimeException("o noes") } whenever(task.execute(any())) doThrow RuntimeException("o noes") whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(exceptionHandler.handles(any())) doReturn true whenever(exceptionHandler.handle(anyOrNull(), any())) doReturn exceptionDetails } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("marks the task as terminal") { verify(queue).push( check<CompleteTask> { assertThat(it.status).isEqualTo(TERMINAL) } ) } it("attaches the exception to the stageContext and taskExceptionDetails") { verify(repository).storeStage( check { assertThat(it.context["exception"]).isEqualTo(exceptionDetails) assertThat(it.tasks[0].taskExceptionDetails["exception"]).isEqualTo(exceptionDetails) } ) } } and("the task should not fail the whole pipeline, only the branch") { beforeGroup { pipeline.stageByRef("1").apply { context["failPipeline"] = false context["continuePipeline"] = false } tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } whenever(task.execute(any())) doThrow RuntimeException("o noes") whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(exceptionHandler.handles(any())) doReturn true whenever(exceptionHandler.handle(anyOrNull(), any())) doReturn exceptionDetails } afterGroup(::resetMocks) afterGroup { pipeline.stages.first().context.clear() } action("the handler receives a message") { subject.handle(message) } it("marks the task STOPPED") { verify(queue).push( check<CompleteTask> { assertThat(it.status).isEqualTo(STOPPED) } ) } } and("the task should allow the pipeline to proceed") { beforeGroup { pipeline.stageByRef("1").apply { context["failPipeline"] = false context["continuePipeline"] = true } tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } whenever(task.execute(any())) doThrow RuntimeException("o noes") whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(exceptionHandler.handles(any())) doReturn true whenever(exceptionHandler.handle(anyOrNull(), any())) doReturn exceptionDetails } afterGroup(::resetMocks) afterGroup { pipeline.stages.first().context.clear() } action("the handler receives a message") { subject.handle(message) } it("marks the task FAILED_CONTINUE") { verify(queue).push( check<CompleteTask> { assertThat(it.status).isEqualTo(FAILED_CONTINUE) } ) } } } and("it is recoverable") { val taskBackoffMs = 30_000L val exceptionDetails = ExceptionHandler.Response( RuntimeException::class.qualifiedName, "o noes", ExceptionHandler.responseDetails("o noes"), true ) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } whenever(task.getDynamicBackoffPeriod(any(), any())) doReturn taskBackoffMs whenever(task.execute(any())) doThrow RuntimeException("o noes") whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(exceptionHandler.handles(any())) doReturn true whenever(exceptionHandler.handle(anyOrNull(), any())) doReturn exceptionDetails } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("re-runs the task") { verify(queue).push(eq(message), eq(Duration.ofMillis(taskBackoffMs))) } } } describe("when the execution has stopped") { val pipeline = pipeline { status = TERMINAL stage { type = "whatever" task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("emits an event indicating that the task was canceled") { verify(queue).push( CompleteTask( message.executionType, message.executionId, "foo", message.stageId, message.taskId, CANCELED, CANCELED ) ) } it("does not execute the task") { verify(task, times(1)).aliases() verify(task, times(3)).extensionClass verifyNoMoreInteractions(task) } } describe("when the execution has been canceled") { val pipeline = pipeline { status = RUNNING isCanceled = true stage { type = "whatever" task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("marks the task as canceled") { verify(queue).push( CompleteTask( message.executionType, message.executionId, "foo", message.stageId, message.taskId, CANCELED, CANCELED ) ) } it("it tries to cancel the task") { verify(task).onCancelWithResult(any()) } } describe("when the execution has been paused") { val pipeline = pipeline { status = PAUSED stage { type = "whatever" status = RUNNING task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("marks the task as paused") { verify(queue).push(PauseTask(message)) } it("does not execute the task") { verify(task, times(1)).aliases() verify(task, times(3)).extensionClass verifyNoMoreInteractions(task) } } describe("when the task has exceeded its timeout") { given("the execution was never paused") { val timeout = Duration.ofMinutes(5) val pipeline = pipeline { stage { type = "whatever" task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("fails the task") { verify(queue).push(CompleteTask(message, TERMINAL)) } it("does not execute the task") { verify(task, never()).execute(any()) } } given("the execution was marked to continue") { val timeout = Duration.ofMinutes(5) val pipeline = pipeline { stage { type = "whatever" task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli() } context["failPipeline"] = false context["continuePipeline"] = true } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("marks the task as failed but continue") { verify(queue).push(CompleteTask(message, FAILED_CONTINUE, TERMINAL)) } } given("the execution is marked to succeed on timeout") { val timeout = Duration.ofMinutes(5) val pipeline = pipeline { stage { type = "whatever" context = hashMapOf<String, Any>("markSuccessfulOnTimeout" to true) task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("marks the task as succeeded") { verify(queue).push(CompleteTask(message, SUCCEEDED)) } it("does not execute the task") { verify(task, never()).execute(any()) } } given("the execution had been paused") { val timeout = Duration.ofMinutes(5) val pipeline = pipeline { paused = PausedDetails().apply { pauseTime = clock.instant().minus(Minutes.of(3)).toEpochMilli() resumeTime = clock.instant().minus(Minutes.of(2)).toEpochMilli() } stage { type = "whatever" task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("executes the task") { verify(task).execute(any()) } } given("the execution had been paused but is timed out anyway") { val timeout = Duration.ofMinutes(5) val pipeline = pipeline { paused = PausedDetails().apply { pauseTime = clock.instant().minus(Minutes.of(3)).toEpochMilli() resumeTime = clock.instant().minus(Minutes.of(2)).toEpochMilli() } stage { type = "whatever" task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.plusMinutes(1).toMillis() + 1).toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("fails the task") { verify(queue).push(CompleteTask(message, TERMINAL)) } it("does not execute the task") { verify(task, never()).execute(any()) } } given("the execution had been paused but only before this task started running") { val timeout = Duration.ofMinutes(5) val pipeline = pipeline { paused = PausedDetails().apply { pauseTime = clock.instant().minus(Minutes.of(10)).toEpochMilli() resumeTime = clock.instant().minus(Minutes.of(9)).toEpochMilli() } stage { type = "whatever" task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("fails the task") { verify(queue).push(CompleteTask(message, TERMINAL)) } it("does not execute the task") { verify(task, never()).execute(any()) } } given("the stage waited for an execution window") { val timeout = Duration.ofMinutes(5) val windowDuration = Duration.ofHours(1) val windowStartedAt = clock.instant().minus(timeout).minus(windowDuration).plusSeconds(1) val windowEndedAt = clock.instant().minus(timeout).plusSeconds(1) val pipeline = pipeline { stage { stage { type = RestrictExecutionDuringTimeWindow.TYPE status = SUCCEEDED startTime = windowStartedAt.toEpochMilli() endTime = windowEndedAt.toEpochMilli() } refId = "1" type = "whatever" context[STAGE_TIMEOUT_OVERRIDE_KEY] = timeout.toMillis() startTime = windowStartedAt.toEpochMilli() task { id = "1" startTime = windowEndedAt.toEpochMilli() status = RUNNING } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, pipeline.application, stage.id, "1", DummyTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("executes the task") { verify(task).execute(pipeline.stageByRef("1")) } } given("the stage waited for an execution window but is timed out anyway") { val timeout = Duration.ofMinutes(5) val windowDuration = Duration.ofHours(1) val windowStartedAt = clock.instant().minus(timeout).minus(windowDuration).minusSeconds(1) val windowEndedAt = clock.instant().minus(timeout).minusSeconds(1) val pipeline = pipeline { stage { stage { type = RestrictExecutionDuringTimeWindow.TYPE status = SUCCEEDED startTime = windowStartedAt.toEpochMilli() endTime = windowEndedAt.toEpochMilli() } refId = "1" type = "whatever" context[STAGE_TIMEOUT_OVERRIDE_KEY] = timeout.toMillis() startTime = windowStartedAt.toEpochMilli() task { id = "1" startTime = windowEndedAt.toEpochMilli() status = RUNNING } } } val message = RunTask(pipeline.type, pipeline.id, pipeline.application, pipeline.stages.first().id, "1", DummyTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("fails the task") { verify(queue).push(CompleteTask(message, TERMINAL)) } it("does not execute the task") { verify(task, never()).execute(any()) } } } describe("handles onTimeout responses") { val timeout = Duration.ofMinutes(5) val pipeline = pipeline { stage { type = "whatever" task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli() } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) given("the task returns fail_continue") { beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() whenever(task.onTimeout(any())) doReturn TaskResult.ofStatus(FAILED_CONTINUE) } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("marks the task fail_continue") { verify(queue).push(CompleteTask(message, FAILED_CONTINUE)) } it("does not execute the task") { verify(task, never()).execute(any()) } } given("the task returns terminal") { beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() whenever(task.onTimeout(any())) doReturn TaskResult.ofStatus(TERMINAL) } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("marks the task terminal") { verify(queue).push(CompleteTask(message, TERMINAL)) } it("does not execute the task") { verify(task, never()).execute(any()) } } given("the task returns succeeded") { beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() whenever(task.onTimeout(any())) doReturn TaskResult.ofStatus(SUCCEEDED) } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) subject } it("marks the task terminal") { verify(queue).push(CompleteTask(message, TERMINAL)) } it("does not execute the task") { verify(task, never()).execute(any()) } } } given("there is a timeout override") { val timeout = Duration.ofMinutes(5) val timeoutOverride = Duration.ofMinutes(10) timeoutOverride.toMillis().let { listOf(it.toInt(), it, it.toDouble()) }.forEach { stageTimeoutMs -> and("the override is a ${stageTimeoutMs.javaClass.simpleName}") { and("the stage is between the default and overridden duration") { val pipeline = pipeline { stage { type = "whatever" context["stageTimeoutMs"] = stageTimeoutMs startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli() task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() - 1).toEpochMilli() } } } val stage = pipeline.stages.first() val taskResult = TaskResult.RUNNING val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) on("receiving $message") { subject.handle(message) } it("executes the task") { verify(task).execute(any()) } } and("the timeout override has been exceeded by stage") { and("the stage has never been paused") { val pipeline = pipeline { stage { type = "whatever" context["stageTimeoutMs"] = stageTimeoutMs startTime = clock.instant().minusMillis(timeoutOverride.toMillis() + 1).toEpochMilli() task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() - 1).toEpochMilli() } } } val stage = pipeline.stages.first() val taskResult = TaskResult.RUNNING val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) on("receiving $message") { subject.handle(message) } it("fails the task") { verify(queue).push(CompleteTask(message, TERMINAL)) } it("does not execute the task") { verify(task, never()).execute(any()) } } and("the execution had been paused") { val pipeline = pipeline { paused = PausedDetails().apply { pauseTime = clock.instant().minus(Minutes.of(3)).toEpochMilli() resumeTime = clock.instant().minus(Minutes.of(2)).toEpochMilli() } stage { type = "whatever" context["stageTimeoutMs"] = stageTimeoutMs startTime = clock.instant().minusMillis(timeoutOverride.toMillis() + 1).toEpochMilli() task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() - 1).toEpochMilli() } } } val stage = pipeline.stages.first() val taskResult = TaskResult.RUNNING val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("executes the task") { verify(task).execute(any()) } } and("the execution had been paused but is timed out anyway") { val pipeline = pipeline { paused = PausedDetails().apply { pauseTime = clock.instant().minus(Minutes.of(3)).toEpochMilli() resumeTime = clock.instant().minus(Minutes.of(2)).toEpochMilli() } stage { type = "whatever" context["stageTimeoutMs"] = stageTimeoutMs startTime = clock.instant().minusMillis(timeoutOverride.plusMinutes(1).toMillis() + 1).toEpochMilli() task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() - 1).toEpochMilli() } } } val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("fails the task") { verify(queue).push(CompleteTask(message, TERMINAL)) } it("does not execute the task") { verify(task, never()).execute(any()) } } and("the execution had been paused but only before this stage started running") { val pipeline = pipeline { paused = PausedDetails().apply { pauseTime = clock.instant().minus(Minutes.of(15)).toEpochMilli() resumeTime = clock.instant().minus(Minutes.of(14)).toEpochMilli() } stage { type = "whatever" context["stageTimeoutMs"] = stageTimeoutMs startTime = clock.instant().minusMillis(timeoutOverride.toMillis() + 1).toEpochMilli() task { id = "1" status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() - 1).toEpochMilli() } } } val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("fails the task") { verify(queue).push(CompleteTask(message, TERMINAL)) } it("does not execute the task") { verify(task, never()).execute(any()) } } } and("the task is an overridabletimeout task that shouldn't time out") { val pipeline = pipeline { stage { type = "whatever" context["stageTimeoutMs"] = stageTimeoutMs startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli() // started 5.1 minutes ago task { id = "1" implementingClass = DummyTimeoutOverrideTask::class.jvmName status = RUNNING startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli() // started 5.1 minutes ago } } } val stage = pipeline.stages.first() val taskResult = TaskResult.RUNNING val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTimeoutOverrideTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(timeoutOverrideTask, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(timeoutOverrideTask, stage, taskResult)) doReturn taskResult } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(timeoutOverrideTask.timeout) doReturn timeout.toMillis() } afterGroup(::resetMocks) on("receiving $message") { subject.handle(message) } it("executes the task") { verify(timeoutOverrideTask).execute(any()) } } } } } } describe("expressions in the context") { mapOf( "\${1 == 2}" to false, "\${1 == 1}" to true, mapOf("key" to "\${1 == 2}") to mapOf("key" to false), mapOf("key" to "\${1 == 1}") to mapOf("key" to true), mapOf("key" to mapOf("key" to "\${1 == 2}")) to mapOf("key" to mapOf("key" to false)), mapOf("key" to mapOf("key" to "\${1 == 1}")) to mapOf("key" to mapOf("key" to true)) ).forEach { expression, expected -> given("an expression $expression in the stage context") { val pipeline = pipeline { stage { refId = "1" type = "whatever" context["expr"] = expression task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stages.first() val taskResult = TaskResult.SUCCEEDED val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stageByRef("1").id, "1", DummyTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("parses the expression") { verify(task).execute( check { assertThat(it.context["expr"]).isEqualTo(expected) } ) } } } describe("can reference non-existent trigger props") { mapOf( "\${trigger.type == 'manual'}" to true, "\${trigger.buildNumber == null}" to true, "\${trigger.quax ?: 'no quax'}" to "no quax" ).forEach { expression, expected -> given("an expression $expression in the stage context") { val pipeline = pipeline { stage { refId = "1" type = "whatever" context["expr"] = expression trigger = DefaultTrigger("manual") task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stages.first() val taskResult = TaskResult.SUCCEEDED val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stageByRef("1").id, "1", DummyTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("evaluates the expression") { verify(task).execute( check { assertThat(it.context["expr"]).isEqualTo(expected) } ) } } } } given("a reference to deployedServerGroups in the stage context") { val pipeline = pipeline { stage { refId = "1" type = "createServerGroup" context = mapOf( "deploy.server.groups" to mapOf( "us-west-1" to listOf( "spindemo-test-v008" ) ), "account" to "mgmttest", "region" to "us-west-1" ) status = SUCCEEDED } stage { refId = "2" requisiteStageRefIds = setOf("1") type = "whatever" context["command"] = "serverGroupDetails.groovy \${ deployedServerGroups[0].account } \${ deployedServerGroups[0].region } \${ deployedServerGroups[0].serverGroup }" task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stageByRef("2") val taskResult = TaskResult.SUCCEEDED val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stageByRef("2").id, "1", DummyTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("resolves deployed server groups") { verify(task).execute( check { assertThat(it.context["command"]).isEqualTo("serverGroupDetails.groovy mgmttest us-west-1 spindemo-test-v008") } ) } } given("parameters in the context and in the pipeline") { val pipeline = pipeline { trigger = DefaultTrigger(type = "manual", parameters = mutableMapOf("dummy" to "foo")) stage { refId = "1" type = "jenkins" context["parameters"] = mutableMapOf( "message" to "o hai" ) task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stages.first() val taskResult = TaskResult.SUCCEEDED val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stageByRef("1").id, "1", DummyTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("does not overwrite the stage's parameters with the pipeline's") { verify(task).execute( check { assertThat(it.context["parameters"]).isEqualTo(mapOf("message" to "o hai")) } ) } } given("an expression in the context that refers to a prior stage output") { val pipeline = pipeline { stage { refId = "1" outputs["foo"] = "bar" } stage { refId = "2" requisiteStageRefIds = setOf("1") context["expression"] = "\${foo}" type = "whatever" task { id = "1" startTime = clock.instant().toEpochMilli() } } } val stage = pipeline.stageByRef("2") val taskResult = TaskResult.SUCCEEDED val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(task.execute(any())) doReturn taskResult whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving $message") { subject.handle(message) } it("passes the decoded expression to the task") { verify(task).execute( check { assertThat(it.context["expression"]).isEqualTo("bar") } ) } } } describe("no such task") { val pipeline = pipeline { stage { type = "whatever" task { id = "1" implementingClass = InvalidTask::class.jvmName } } } val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1", InvalidTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("does not run any tasks") { verify(task, times(1)).aliases() verify(task, times(5)).extensionClass verifyNoMoreInteractions(task) } it("emits an error event") { verify(queue).push(isA<InvalidTaskType>()) } } describe("manual skip behavior") { given("a stage with a manual skip flag") { val pipeline = pipeline { stage { type = singleTaskStage.type task { id = "1" implementingClass = DummyTask::class.jvmName } context["manualSkip"] = true } } val stage = pipeline.stageByRef("1") val taskResult = TaskResult.SUCCEEDED val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("sets the task's status to SKIPPED and completes the task") { verify(queue).push(CompleteTask(message, SKIPPED)) } } } describe("max configurable back off value") { setOf( BackOff(5_000L, 10_000L, 20_000L, 30_000L, 30_000L), BackOff(10_000L, 20_000L, 30_000L, 5_000L, 30_000L), BackOff(20_000L, 30_000L, 5_000L, 10_000L, 30_000L), BackOff(30_000L, 5_000L, 10_000L, 20_000L, 30_000L), BackOff(20_000L, 5_000L, 10_000L, 30_002L, 30_001L) ).forEach { backOff -> given("the back off values $backOff") { val pipeline = pipeline { stage { type = "whatever" task { id = "1" implementingClass = DummyCloudProviderAwareTask::class.jvmName startTime = clock.instant().toEpochMilli() context["cloudProvider"] = "aws" context["deploy.account.name"] = "someAccount" } } } val stage = pipeline.stages.first() val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyCloudProviderAwareTask::class.java) val taskResult = TaskResult.RUNNING beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } whenever(cloudProviderAwareTask.execute(any())) doReturn taskResult taskExecutionInterceptors.forEach { whenever(it.maxTaskBackoff()) doReturn backOff.limit } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(cloudProviderAwareTask, stage)) doReturn stage } taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(cloudProviderAwareTask, stage, taskResult)) doReturn taskResult } whenever(cloudProviderAwareTask.getDynamicBackoffPeriod(any(), any())) doReturn backOff.taskBackOffMs whenever(dynamicConfigService.getConfig(eq(Long::class.java), eq("tasks.global.backOffPeriod"), any())) doReturn backOff.globalBackOffMs whenever(cloudProviderAwareTask.hasCloudProvider(any())) doReturn true whenever(cloudProviderAwareTask.getCloudProvider(any<StageExecution>())) doReturn "aws" whenever(dynamicConfigService.getConfig(eq(Long::class.java), eq("tasks.aws.backOffPeriod"), any())) doReturn backOff.cloudProviderBackOffMs whenever(cloudProviderAwareTask.hasCredentials(any())) doReturn true whenever(cloudProviderAwareTask.getCredentials(any<StageExecution>())) doReturn "someAccount" whenever(dynamicConfigService.getConfig(eq(Long::class.java), eq("tasks.aws.someAccount.backOffPeriod"), any())) doReturn backOff.accountBackOffMs whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("selects the max value, unless max value is over limit ${backOff.limit} in which case limit is used") { verify(queue).push(message, Duration.ofMillis(backOff.expectedMaxBackOffMs)) } } } } describe("when a previous stage was a skipped manual judgment stage with auth propagated") { given("a stage with a manual judgment type and auth propagated") { val timeout = Duration.ofMinutes(5) val lastModifiedUser = StageExecution.LastModifiedDetails() lastModifiedUser.user = "user" lastModifiedUser.allowedAccounts = listOf("user") val pipeline = pipeline { stage { refId = "1" type = manualJudgmentStage.type manualJudgmentStage.plan(this) status = SUCCEEDED context["propagateAuthenticationContext"] = true context["judgmentStatus"] = "continue" lastModified = lastModifiedUser } } val stageSkipped : StageExecution = stage { refId = "2" type = manualJudgmentStage.type manualJudgmentStage.plan(this) context["manualSkip"] = true status = SKIPPED requisiteStageRefIds = setOf("1") } val stageSpy = spy(stageSkipped) val stageResult1 : com.netflix.spinnaker.orca.pipeline.util.StageNavigator.Result = mock() whenever(stageResult1.stage) doReturn pipeline.stageByRef("1") whenever(stageResult1.stageBuilder) doReturn manualJudgmentStage val stageResult2 : com.netflix.spinnaker.orca.pipeline.util.StageNavigator.Result = mock() whenever(stageResult2.stage) doReturn stageSpy whenever(stageResult2.stageBuilder) doReturn manualJudgmentStage pipeline.stages.add(stageSpy) val stage = pipeline.stageByRef("2") val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java) beforeGroup { tasks.forEach { whenever(it.extensionClass) doReturn it::class.java } taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis() whenever(stageNavigator.ancestors(stage)) doReturn listOf(stageResult2, stageResult1) } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("marks the task as skipped") { verify(queue).push(CompleteTask(message, SKIPPED)) } it("verify if last authenticated user was retrieved from candidate stage") { assertEquals(stageSpy.lastModified, lastModifiedUser) } } } }) data class BackOff( val taskBackOffMs: Long, val globalBackOffMs: Long, val cloudProviderBackOffMs: Long, val accountBackOffMs: Long, val expectedMaxBackOffMs: Long, val limit: Long = 30_001L )
apache-2.0
9379ef358555f61693c34e15fb7e71c5
36.489362
175
0.609908
4.904413
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/writer/apiCode.kt
1
8197
// 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.workspaceModel.codegen import com.intellij.openapi.util.registry.Registry import com.intellij.workspaceModel.codegen.classes.* import com.intellij.workspaceModel.codegen.deft.meta.ObjClass import com.intellij.workspaceModel.codegen.deft.meta.ObjProperty import com.intellij.workspaceModel.codegen.deft.meta.OwnProperty import com.intellij.workspaceModel.codegen.deft.meta.ValueType import com.intellij.workspaceModel.codegen.engine.GenerationProblem import com.intellij.workspaceModel.codegen.engine.ProblemLocation import com.intellij.workspaceModel.codegen.engine.impl.ProblemReporter import com.intellij.workspaceModel.codegen.fields.javaMutableType import com.intellij.workspaceModel.codegen.fields.javaType import com.intellij.workspaceModel.codegen.fields.wsCode import com.intellij.workspaceModel.codegen.utils.fqn import com.intellij.workspaceModel.codegen.utils.fqn7 import com.intellij.workspaceModel.codegen.utils.lines import com.intellij.workspaceModel.codegen.writer.* import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceSet import com.intellij.workspaceModel.storage.url.VirtualFileUrl import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type val SKIPPED_TYPES: Set<String> = setOfNotNull(WorkspaceEntity::class.simpleName, WorkspaceEntity.Builder::class.simpleName, WorkspaceEntityWithSymbolicId::class.simpleName) fun ObjClass<*>.generateBuilderCode(reporter: ProblemReporter): String = lines { checkSuperTypes(this@generateBuilderCode, reporter) line("@${GeneratedCodeApiVersion::class.fqn}(${CodeGeneratorVersions.API_VERSION})") val (typeParameter, typeDeclaration) = if (openness.extendable) "T" to "<T: $javaFullName>" else javaFullName to "" val superBuilders = superTypes.filterIsInstance<ObjClass<*>>().filter { !it.isStandardInterface }.joinToString { ", ${it.name}.Builder<$typeParameter>" } val header = "interface Builder$typeDeclaration: $javaFullName$superBuilders, ${WorkspaceEntity.Builder::class.fqn}<$typeParameter>, ${ObjBuilder::class.fqn}<$typeParameter>" section(header) { list(allFields.noSymbolicId()) { checkProperty(this, reporter) wsBuilderApi } } } fun checkSuperTypes(objClass: ObjClass<*>, reporter: ProblemReporter) { objClass.superTypes.filterIsInstance<ObjClass<*>>().forEach {superClass -> if (!superClass.openness.extendable) { reporter.reportProblem(GenerationProblem("Class '${superClass.name}' cannot be extended", GenerationProblem.Level.ERROR, ProblemLocation.Class(objClass))) } else if (!superClass.openness.openHierarchy && superClass.module != objClass.module) { reporter.reportProblem(GenerationProblem("Class '${superClass.name}' cannot be extended from other modules", GenerationProblem.Level.ERROR, ProblemLocation.Class(objClass))) } } } private fun checkProperty(objProperty: ObjProperty<*, *>, reporter: ProblemReporter) { checkInheritance(objProperty, reporter) checkPropertyType(objProperty, reporter) } fun checkInheritance(objProperty: ObjProperty<*, *>, reporter: ProblemReporter) { objProperty.receiver.allSuperClasses.mapNotNull { it.fieldsByName[objProperty.name] }.forEach { overriddenField -> if (!overriddenField.open) { reporter.reportProblem( GenerationProblem("Property '${overriddenField.receiver.name}::${overriddenField.name}' cannot be overriden", GenerationProblem.Level.ERROR, ProblemLocation.Property(objProperty))) } } } private fun checkPropertyType(objProperty: ObjProperty<*, *>, reporter: ProblemReporter) { val errorMessage = when (val type = objProperty.valueType) { is ValueType.ObjRef<*> -> { if (type.child) "Child references should always be nullable" else null } else -> checkType(type) } if (errorMessage != null) { reporter.reportProblem(GenerationProblem(errorMessage, GenerationProblem.Level.ERROR, ProblemLocation.Property(objProperty))) } } private fun checkType(type: ValueType<*>): String? = when (type) { is ValueType.Optional -> when (type.type) { is ValueType.List<*> -> "Optional lists aren't supported" is ValueType.Set<*> -> "Optional sets aren't supported" else -> checkType(type.type) } is ValueType.Set<*> -> { if (type.elementType.isRefType()) { "Set of references isn't supported" } else checkType(type.elementType) } is ValueType.Map<*, *> -> { checkType(type.keyType) ?: checkType(type.valueType) } is ValueType.Blob<*> -> { if (!keepUnknownFields && type.javaClassName !in knownInterfaces) { "Unsupported type '${type.javaClassName}'" } else null } else -> null } private val keepUnknownFields: Boolean get() = Registry.`is`("workspace.model.generator.keep.unknown.fields") private val knownInterfaces = setOf( VirtualFileUrl::class.qualifiedName!!, EntitySource::class.qualifiedName!!, SymbolicEntityId::class.qualifiedName!!, ) fun ObjClass<*>.generateCompanionObject(): String = lines { val builderGeneric = if (openness.extendable) "<$javaFullName>" else "" val companionObjectHeader = buildString { append("companion object: ${Type::class.fqn}<$javaFullName, Builder$builderGeneric>(") val base = superTypes.filterIsInstance<ObjClass<*>>().firstOrNull() if (base != null && base.name !in SKIPPED_TYPES) append(base.javaFullName) append(")") } val mandatoryFields = allFields.mandatoryFields() if (mandatoryFields.isNotEmpty()) { val fields = mandatoryFields.joinToString { "${it.name}: ${it.valueType.javaType}" } section(companionObjectHeader) { section("operator fun invoke($fields, init: (Builder$builderGeneric.() -> Unit)? = null): $javaFullName") { line("val builder = builder()") list(mandatoryFields) { if (this.valueType is ValueType.Set<*> && !this.valueType.isRefType()) { "builder.$name = $name.${fqn7(Collection<*>::toMutableWorkspaceSet)}()" } else if (this.valueType is ValueType.List<*> && !this.valueType.isRefType()) { "builder.$name = $name.${fqn7(Collection<*>::toMutableWorkspaceList)}()" } else { "builder.$name = $name" } } line("init?.invoke(builder)") line("return builder") } } } else { section(companionObjectHeader) { section("operator fun invoke(init: (Builder$builderGeneric.() -> Unit)? = null): $javaFullName") { line("val builder = builder()") line("init?.invoke(builder)") line("return builder") } } } } fun List<OwnProperty<*, *>>.mandatoryFields(): List<ObjProperty<*, *>> { var fields = this.noRefs().noOptional().noSymbolicId().noDefaultValue() if (fields.isNotEmpty()) { fields = fields.noEntitySource() + fields.single { it.name == "entitySource" } } return fields } fun ObjClass<*>.generateExtensionCode(): String? { val fields = module.extensions.filter { it.receiver == this || it.receiver.module != module && it.valueType.isRefType() && it.valueType.getRefType().target == this } if (openness.extendable && fields.isEmpty()) return null return lines { if (!openness.extendable) { line("fun ${MutableEntityStorage::class.fqn}.modifyEntity(entity: $name, modification: $name.Builder.() -> Unit) = modifyEntity($name.Builder::class.java, entity, modification)") } fields.sortedWith(compareBy({ it.receiver.name }, { it.name })).forEach { line(it.wsCode) } } } val ObjProperty<*, *>.wsBuilderApi: String get() { val returnType = if (valueType is ValueType.Collection<*, *> && !valueType.isRefType()) valueType.javaMutableType else valueType.javaType return "override var $javaName: $returnType" }
apache-2.0
75c82ed9deffe7cbd3afe10964e9b011
42.601064
184
0.705624
4.501373
false
false
false
false
GunoH/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/ProductModulesLayout.kt
2
8271
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceJavaStaticMethodWithKotlinAnalog") package org.jetbrains.intellij.build import com.intellij.util.containers.MultiMap import it.unimi.dsi.fastutil.Hash import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenCustomHashSet import kotlinx.collections.immutable.* import org.jetbrains.intellij.build.impl.PlatformLayout import org.jetbrains.intellij.build.impl.PluginLayout import java.util.function.BiConsumer /** * Default bundled plugins for all products. * See also [JB_BUNDLED_PLUGINS]. */ val DEFAULT_BUNDLED_PLUGINS: PersistentList<String> = persistentListOf( "intellij.platform.images", "intellij.dev", ) class ProductModulesLayout { /** * Name of the main product JAR file. Outputs of {@link #productImplementationModules} will be packed into it. */ lateinit var mainJarName: String /** * Names of the additional product-specific modules which need to be packed into openapi.jar in the product's 'lib' directory. */ var productApiModules: List<String> = emptyList() /** * Names of the additional product-specific modules which need to be included into {@link #mainJarName} in the product's 'lib' directory */ var productImplementationModules: List<String> = emptyList() /** * Names of the main modules (containing META-INF/plugin.xml) of the plugins which need to be bundled with the product. Layouts of the * bundled plugins are specified in {@link [pluginLayouts]} list. */ var bundledPluginModules: MutableList<String> = DEFAULT_BUNDLED_PLUGINS.toMutableList() /** * Names of the main modules (containing META-INF/plugin.xml) of the plugins which aren't bundled with the product but may be installed * into it. Zip archives of these plugins will be built and placed under "&lt;product-code&gt;-plugins" directory in the build artifacts. * Layouts of the plugins are specified in {@link [pluginLayouts]} list. */ var pluginModulesToPublish: Collection<String> = LinkedHashSet() get() = java.util.Set.copyOf(field) set(value) { field = LinkedHashSet(value) } /** * Describes layout of non-trivial plugins which may be included into the product. The actual list of the plugins need to be bundled * with the product is specified by {@link [bundledPluginModules]}, the actual list of plugins which need to be prepared for publishing * is specified by {@link [pluginModulesToPublish]}. */ var pluginLayouts: PersistentList<PluginLayout> = CommunityRepositoryModules.COMMUNITY_REPOSITORY_PLUGINS set(value) { val nameGuard = createPluginLayoutSet(value.size) for (layout in value) { check(nameGuard.add(layout)) { val bundlingRestrictionsAsString = if (layout.bundlingRestrictions == PluginBundlingRestrictions.NONE) { "" } else { ", bundlingRestrictions=${layout.bundlingRestrictions}" } "PluginLayout(mainModule=${layout.mainModule}$bundlingRestrictionsAsString) is duplicated" } } field = value } /** * Names of the project libraries which JARs' contents should be extracted into {@link #mainJarName} JAR. */ var projectLibrariesToUnpackIntoMainJar: PersistentList<String> = persistentListOf() /** * Maps names of JARs to names of the modules; these modules will be packed into these JARs and copied to the product's 'lib' directory. */ val additionalPlatformJars: MultiMap<String, String> = MultiMap.createLinkedSet() /** * Module name to list of Ant-like patterns describing entries which should be excluded from its output. * <strong>This is a temporary property added to keep layout of some products. If some directory from a module shouldn't be included into the * product JAR it's strongly recommended to move that directory outside of the module source roots.</strong> */ internal val moduleExcludes: MutableMap<String, MutableList<String>> = LinkedHashMap() /** * Additional customizations of platform JARs. <strong>This is a temporary property added to keep layout of some products.</strong> */ internal var platformLayoutCustomizers = persistentListOf<BiConsumer<PlatformLayout, BuildContext>>() fun addPlatformCustomizer(customizer: BiConsumer<PlatformLayout, BuildContext>) { platformLayoutCustomizers = platformLayoutCustomizers.add(customizer) } fun excludeModuleOutput(module: String, path: String) { moduleExcludes.computeIfAbsent(module) { mutableListOf() }.add(path) } fun excludeModuleOutput(module: String, path: Collection<String>) { moduleExcludes.computeIfAbsent(module) { mutableListOf() }.addAll(path) } /** * Names of the modules which classpath will be used to build searchable options index <br> * //todo[nik] get rid of this property and automatically include all platform and plugin modules to the classpath when building searchable options index */ var mainModules: List<String> = emptyList() /** * If {@code true} a special xml descriptor in custom plugin repository format will be generated for {@link #setPluginModulesToPublish} plugins. * This descriptor and the plugin *.zip files can be uploaded to the URL specified in 'plugins@builtin-url' attribute in *ApplicationInfo.xml file * to allow installing custom plugins directly from IDE. If {@link ProprietaryBuildTools#artifactsServer} is specified, {@code __BUILTIN_PLUGINS_URL__} in * *ApplicationInfo.xml file will be automatically replaced by the plugin repository URL provided by the artifact server. * * @see #setPluginModulesToPublish */ var prepareCustomPluginRepositoryForPublishedPlugins = true /** * If {@code true} then all plugins that compatible with an IDE will be built. By default, these plugins will be placed to "auto-uploading" * subdirectory and may be automatically uploaded to plugins.jetbrains.com. * <br> * If {@code false} only plugins from {@link #setPluginModulesToPublish} will be considered. */ var buildAllCompatiblePlugins = true /** * List of plugin names which should not be built even if they are compatible and {@link #buildAllCompatiblePlugins} is true */ var compatiblePluginsToIgnore: PersistentList<String> = persistentListOf() /** * Module names which should be excluded from this product. * Allows to filter out default platform modules (both api and implementation) as well as product modules. * This API is experimental, use with care */ var excludedModuleNames: PersistentSet<String> = persistentSetOf() /** * @return list of all modules which output is included into the plugin's JARs */ fun getIncludedPluginModules(enabledPluginModules: Collection<String>): Collection<String> { val result = LinkedHashSet<String>() result.addAll(enabledPluginModules) pluginLayouts.asSequence() .filter { enabledPluginModules.contains(it.mainModule) } .flatMapTo(result) { it.includedModuleNames } return result } /** * Map name of JAR to names of the modules; these modules will be packed into these JARs and copied to the product's 'lib' directory. */ fun withAdditionalPlatformJar(jarName: String, vararg moduleNames: String) { additionalPlatformJars.putValues(jarName, moduleNames.asList()) } fun withoutAdditionalPlatformJar(jarName: String, moduleName: String) { additionalPlatformJars.remove(jarName, moduleName) } } internal fun createPluginLayoutSet(expectedSize: Int): MutableSet<PluginLayout> { return ObjectLinkedOpenCustomHashSet(expectedSize, object : Hash.Strategy<PluginLayout?> { override fun hashCode(layout: PluginLayout?): Int { if (layout == null) { return 0 } var result = layout.mainModule.hashCode() result = 31 * result + layout.bundlingRestrictions.hashCode() return result } override fun equals(a: PluginLayout?, b: PluginLayout?): Boolean { if (a == b) { return true } if (a == null || b == null) { return false } return a.mainModule == b.mainModule && a.bundlingRestrictions == b.bundlingRestrictions } }) }
apache-2.0
b1299556456e1d76f00abb936f2f6580
41.634021
156
0.732076
4.742546
false
false
false
false
GunoH/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/GHSuggestedChangeApplier.kt
8
5117
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.github.pullrequest.comment import com.intellij.openapi.diff.impl.patch.ApplyPatchStatus import com.intellij.openapi.diff.impl.patch.PatchHunk import com.intellij.openapi.diff.impl.patch.PatchLine import com.intellij.openapi.diff.impl.patch.TextFilePatch import com.intellij.openapi.diff.impl.patch.apply.GenericPatchApplier import com.intellij.openapi.diff.impl.patch.formove.PatchApplier import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.LocalFilePath import com.intellij.vcsUtil.VcsImplUtil import git4idea.GitUtil import git4idea.checkin.GitCheckinEnvironment import git4idea.checkin.GitCommitOptions import git4idea.index.GitIndexUtil import git4idea.repo.GitRepository import git4idea.util.GitFileUtils import org.jetbrains.plugins.github.util.GithubUtil import java.nio.charset.Charset import java.nio.file.Path class GHSuggestedChangeApplier( private val project: Project, private val repository: GitRepository, private val suggestedChange: GHSuggestedChange ) { private val virtualBaseDir = repository.root fun applySuggestedChange(): ApplyPatchStatus { val suggestedChangePatch = createSuggestedChangePatch(suggestedChange) val patchApplier = PatchApplier(project, virtualBaseDir, listOf(suggestedChangePatch), null, null) return patchApplier.execute(true, false) } private fun createSuggestedChangePatchHunk(suggestedChange: GHSuggestedChange): PatchHunk { val suggestedChangeContent = suggestedChange.cutSuggestedChangeContent() val suggestedChangePatchHunk = PatchHunk(suggestedChange.startLine, suggestedChange.endLine, suggestedChange.startLine, suggestedChange.startLine + suggestedChangeContent.size - 1) suggestedChange.cutContextContent().forEach { suggestedChangePatchHunk.addLine(PatchLine(PatchLine.Type.CONTEXT, it)) } suggestedChange.cutChangedContent().forEach { suggestedChangePatchHunk.addLine(PatchLine(PatchLine.Type.REMOVE, it)) } suggestedChangeContent.forEach { suggestedChangePatchHunk.addLine(PatchLine(PatchLine.Type.ADD, it)) } return suggestedChangePatchHunk } fun commitSuggestedChanges(commitMessage: String): ApplyPatchStatus { // Apply patch val suggestedChangePatch = createSuggestedChangePatch(suggestedChange) val patchApplier = PatchApplier(project, virtualBaseDir, listOf(suggestedChangePatch), null, null) val patchStatus = patchApplier.execute(true, false) if (patchStatus == ApplyPatchStatus.ALREADY_APPLIED) { return patchStatus } // Create suggested change revision val beforeLocalFilePath = createLocalFilePath(suggestedChangePatch.beforeName) val afterLocalFilePath = createLocalFilePath(suggestedChangePatch.afterName) val bytes = GitFileUtils.getFileContent(project, virtualBaseDir, GitUtil.HEAD, suggestedChangePatch.beforeName) val revisionContent = VcsImplUtil.loadTextFromBytes(project, bytes, beforeLocalFilePath) val appliedPatch = GenericPatchApplier.apply(revisionContent, suggestedChangePatch.hunks) if (appliedPatch == null || appliedPatch.status != ApplyPatchStatus.SUCCESS) { return appliedPatch?.status ?: ApplyPatchStatus.FAILURE } val virtualFile = beforeLocalFilePath.virtualFile ?: return ApplyPatchStatus.FAILURE val fileContent = GitCheckinEnvironment.convertDocumentContentToBytesWithBOM(repository, appliedPatch.patchedText, virtualFile) val stagedFile = GitIndexUtil.listStaged(repository, beforeLocalFilePath) ?: return ApplyPatchStatus.FAILURE GitIndexUtil.write(repository, beforeLocalFilePath, fileContent, stagedFile.isExecutable) // Commit suggested change val suggestedChangedPath = GitCheckinEnvironment.ChangedPath(beforeLocalFilePath, afterLocalFilePath) val commitMessageFile = GitCheckinEnvironment.createCommitMessageFile(project, virtualBaseDir, commitMessage) val exceptions = GitCheckinEnvironment.commitUsingIndex(project, repository, listOf(suggestedChangedPath), setOf(suggestedChangedPath), commitMessageFile, GitCommitOptions()) if (exceptions.isNotEmpty()) { val messages = exceptions.flatMap { it.messages.toList() }.toTypedArray() GithubUtil.LOG.error("Failed to commit suggested change", *messages) return ApplyPatchStatus.FAILURE } return ApplyPatchStatus.SUCCESS } private fun createSuggestedChangePatch(suggestedChange: GHSuggestedChange): TextFilePatch { val suggestedChangePatchHunk = createSuggestedChangePatchHunk(suggestedChange) return TextFilePatch(Charset.defaultCharset()).apply { beforeName = suggestedChange.filePath afterName = suggestedChange.filePath addHunk(suggestedChangePatchHunk) } } private fun createLocalFilePath(filename: String): LocalFilePath = LocalFilePath(Path.of(virtualBaseDir.path, filename), false) }
apache-2.0
0d73198e1ee12eb794cc60e0a2c0cbb4
49.673267
132
0.78503
4.656051
false
false
false
false
GunoH/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/references/KotlinWebReferenceContributor.kt
4
2689
// 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.references import com.intellij.openapi.paths.GlobalPathReferenceProvider import com.intellij.openapi.paths.WebReference import com.intellij.openapi.util.TextRange import com.intellij.patterns.PlatformPatterns.psiElement import com.intellij.psi.* import com.intellij.util.ProcessingContext import com.intellij.util.SmartList import org.jetbrains.kotlin.psi.KtStringTemplateExpression internal class KotlinWebReferenceContributor : PsiReferenceContributor() { private val spaceSymbolsSplitter: Regex = Regex("\\s") override fun registerReferenceProviders(registrar: PsiReferenceRegistrar) { // see org.jetbrains.kotlin.idea.references.KtIdeReferenceProviderService.getReferences // ContributedReferenceHost elements are not queried for Kotlin-specific references, contribute using PsiReferenceRegistrar registrar.registerReferenceProvider( psiElement(KtStringTemplateExpression::class.java), object : PsiReferenceProvider() { override fun acceptsTarget(target: PsiElement): Boolean { return false // web references do not point to any real PsiElement } override fun getReferencesByElement( element: PsiElement, context: ProcessingContext ): Array<PsiReference> { val stringTemplateExpression = element as? KtStringTemplateExpression ?: return PsiReference.EMPTY_ARRAY if (!stringTemplateExpression.textContains(':')) { return PsiReference.EMPTY_ARRAY } val results = SmartList<PsiReference>() for (entry in stringTemplateExpression.entries) { if (entry.expression != null) continue val texts = entry.text.split(spaceSymbolsSplitter) var startIndex = entry.startOffsetInParent for (text in texts) { if (text.isNotEmpty() && GlobalPathReferenceProvider.isWebReferenceUrl(text)) { results.add(WebReference(stringTemplateExpression, TextRange(startIndex, startIndex + text.length), text)) } startIndex += text.length + 1 } } return results.toArray(PsiReference.EMPTY_ARRAY) } }) } }
apache-2.0
934ca5dab782c2f8e119d42ec33c8c69
48.814815
158
0.63518
6.002232
false
false
false
false
chiclaim/android-sample
language-kotlin/kotlin-sample/kotlin-in-action/src/collection/LazyCollectionTest.kt
1
2592
package collection import lambda.Person import lambda.list /** * desc: lazy collection和非 lazy collection 对比演示 * * Created by Chiclaim on 2018/09/23 */ fun main(args: Array<String>) { // lazyCollectionTest() // println("============================") // lazyCollectionTest2() lazyCollectionTest3() } fun collectionTest() { list.map(Person::age).filter { age -> age > 18 } /* 通过编译后对应的Java代码可以发现,经过map和filter函数,创建了两个临时集合: Iterable $receiver$iv = (Iterable)PersonKt.getList(); //创建集合 Collection destination$iv$iv = (Collection)(new ArrayList(CollectionsKt.collectionSizeOrDefault($receiver$iv, 10))); Iterator var4 = $receiver$iv.iterator(); Object element$iv$iv; while(var4.hasNext()) { element$iv$iv = var4.next(); Integer var11 = ((Person)element$iv$iv).getAge(); destination$iv$iv.add(var11); } $receiver$iv = (Iterable)((List)destination$iv$iv); //创建集合 destination$iv$iv = (Collection)(new ArrayList()); var4 = $receiver$iv.iterator(); while(var4.hasNext()) { element$iv$iv = var4.next(); int age = ((Number)element$iv$iv).intValue(); if (age > 18) { destination$iv$iv.add(element$iv$iv); } } */ } fun lazyCollectionTest() { list.asSequence().map { person -> println("map ${person.age}") person.age }.filter { age -> println("filter $age") age > 20 }//.toList() //或者下面的遍历 .forEach { println("---------forEach $it") } } fun lazyCollectionTest2() { //把filter函数放置前面,可以有效减少map函数的调用次数 list.asSequence().filter { person -> println("filter ${person.age}") person.age > 20 }.map { person -> println("map ${person.age}") person.age }.forEach { println("---------forEach $it") } } //create sequence fun lazyCollectionTest3() { generateSequence(0) { it + 1 }.takeWhile { it <= 100 }.sum().apply { println(this) } } /* 经过分析class字节码、对应的Java代码以及debug跟踪调试,lazy collection 有如下优点: 1,不会创建临时集合 2,用到集合元素的时候,如遍历或转化成新集合(forEach,toList),才会触发集合的过滤、转化等操作。(某种意义上讲和RxJava有点类似) */
apache-2.0
ef08467302573a4bd3b04435411e539d
20.064815
122
0.568162
3.404192
false
true
false
false
abertschi/ad-free
app/src/main/java/ch/abertschi/adfree/detector/TidalDebugTracer.kt
1
619
package ch.abertschi.adfree.detector import org.jetbrains.anko.AnkoLogger import java.io.File class TidalDebugTracer(storageFolder: File?) : AdDetectable, AnkoLogger, AbstractDebugTracer(storageFolder) { private val PACKAGE = "com.aspiro.tidal" private val FILENAME = "adfree-tidal.txt" override fun getPackage() = PACKAGE override fun getFileName() = FILENAME override fun getMeta(): AdDetectorMeta = AdDetectorMeta( "Tidal tracer", "dump tidal notifications to a file. This is for debugging only. ", false, category = "Developer", debugOnly = true ) }
apache-2.0
0996d5c3ee3c855182e0ccbcf8cea694
28.47619
82
0.704362
4.154362
false
false
false
false
marius-m/wt4
app/src/main/java/lt/markmerkk/ui_2/views/calendar_edit/QuickEditWidgetScale.kt
1
4248
package lt.markmerkk.ui_2.views.calendar_edit import com.jfoenix.controls.JFXComboBox import com.jfoenix.svg.SVGGlyph import javafx.beans.property.SimpleStringProperty import javafx.geometry.Insets import javafx.geometry.Pos import javafx.scene.layout.* import javafx.scene.paint.Color import javafx.scene.paint.Paint import lt.markmerkk.Glyph import lt.markmerkk.Graphics import lt.markmerkk.Tags import lt.markmerkk.ui_2.views.* import org.slf4j.LoggerFactory import tornadofx.* class QuickEditWidgetScale( private val presenter: QuickEditContract.ScalePresenter, private val uiPrefs: QuickEditUiPrefs, private val quickEditActions: Set<QuickEditAction>, private val graphics: Graphics<SVGGlyph>, private val scaleStepMinutes: Int, private val quickEditActionChangeListener: QuickEditActionChangeListener ): Fragment(), QuickEditChangableAction, QuickEditContract.ScaleView, VisibilityChangeableView { private val quickEditActionsAsString = quickEditActions.map { it.name } private val jfxComboBox: JFXComboBox<String> override val root = HBox() init { with(root) { jfxButton { setOnAction { presenter.expandToStart(scaleStepMinutes) } prefWidth = uiPrefs.prefWidthActionIcons graphic = graphics.from( Glyph.ARROW_REWIND, Color.BLACK, uiPrefs.widthActionIcon, uiPrefs.heightActionIcon ) } jfxButton { setOnAction { presenter.shrinkFromStart(scaleStepMinutes) } prefWidth = uiPrefs.prefWidthActionIcons graphic = graphics.from( Glyph.ARROW_FORWARD, Color.BLACK, uiPrefs.widthActionIcon, uiPrefs.heightActionIcon ) } jfxComboBox = jfxCombobox(SimpleStringProperty(QuickEditAction.SCALE.name), quickEditActionsAsString) { minWidth = uiPrefs.prefWidthTypeSelector prefWidth = uiPrefs.prefWidthTypeSelector setOnAction { val selectAction = QuickEditAction .valueOf((it.source as JFXComboBox<String>).selectedItem!!) quickEditActionChangeListener.onActiveActionChange(selectAction) } } jfxButton { setOnAction { presenter.shrinkFromEnd(scaleStepMinutes) } prefWidth = uiPrefs.prefWidthActionIcons graphic = graphics.from( Glyph.ARROW_REWIND, Color.BLACK, uiPrefs.widthActionIcon, uiPrefs.heightActionIcon ) } jfxButton { setOnAction { presenter.expandToEnd(scaleStepMinutes) } prefWidth = uiPrefs.prefWidthActionIcons graphic = graphics.from( Glyph.ARROW_FORWARD, Color.BLACK, uiPrefs.widthActionIcon, uiPrefs.heightActionIcon ) } } root.alignment = Pos.CENTER root.maxWidth = uiPrefs.maxWidthContainer root.maxHeight = uiPrefs.prefHeightContainer root.prefHeight = uiPrefs.prefHeightContainer root.vgrow = Priority.NEVER root.hgrow = Priority.NEVER } override fun onDock() { super.onDock() presenter.onAttach(this) } override fun onUndock() { presenter.onDetach() super.onUndock() } override fun changeActiveAction(quickEditAction: QuickEditAction) { val actionIndex = quickEditActionsAsString .indexOf(quickEditAction.name) jfxComboBox.selectionModel.clearAndSelect(actionIndex) } override fun changeVisibility(isVisible: Boolean) { root.isVisible = isVisible root.isManaged = isVisible } companion object { val logger = LoggerFactory.getLogger(Tags.CALENDAR)!! } }
apache-2.0
d2f6c4b281f3b96000f562595af37102
34.705882
115
0.599105
5.257426
false
false
false
false
ktorio/ktor
ktor-network/jvm/src/io/ktor/network/selector/SelectorManager.kt
1
2465
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.selector import io.ktor.utils.io.core.* import kotlinx.coroutines.* import java.nio.channels.* import java.nio.channels.spi.* import kotlin.coroutines.* public actual fun SelectorManager(dispatcher: CoroutineContext): SelectorManager = ActorSelectorManager(dispatcher) /** * Selector manager is a service that manages NIO selectors and selection threads */ public actual interface SelectorManager : CoroutineScope, Closeable { /** * NIO selector provider */ public val provider: SelectorProvider /** * Notifies the selector that selectable has been closed. */ public actual fun notifyClosed(selectable: Selectable) /** * Suspends until [interest] is selected for [selectable] * May cause manager to allocate and run selector instance if not yet created. * * Only one selection is allowed per [interest] per [selectable] but you can * select for different interests for the same selectable simultaneously. * In other words you can select for read and write at the same time but should never * try to read twice for the same selectable. */ public actual suspend fun select(selectable: Selectable, interest: SelectInterest) public actual companion object } /** * Creates a NIO entity via [create] and calls [setup] on it. If any exception happens then the entity will be closed * and an exception will be propagated. */ public inline fun <C : Closeable, R> SelectorManager.buildOrClose( create: SelectorProvider.() -> C, setup: C.() -> R ): R { while (true) { val result = create(provider) try { return setup(result) } catch (t: Throwable) { result.close() throw t } } } /** * Select interest kind * @property [flag] to be set in NIO selector */ @Suppress("KDocMissingDocumentation") public actual enum class SelectInterest(public val flag: Int) { READ(SelectionKey.OP_READ), WRITE(SelectionKey.OP_WRITE), ACCEPT(SelectionKey.OP_ACCEPT), CONNECT(SelectionKey.OP_CONNECT); public actual companion object { public actual val AllInterests: Array<SelectInterest> = values() public val flags: IntArray = values().map { it.flag }.toIntArray() public val size: Int = values().size } }
apache-2.0
971d111014e67af6f2cd814d13f184ce
29.432099
118
0.689655
4.401786
false
false
false
false
ktorio/ktor
ktor-server/ktor-server-plugins/ktor-server-conditional-headers/jvmAndNix/src/io/ktor/server/plugins/conditionalheaders/ConditionalHeaders.kt
1
6363
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.plugins.conditionalheaders import io.ktor.http.* import io.ktor.http.content.* import io.ktor.server.application.* import io.ktor.server.application.hooks.* import io.ktor.server.http.content.* import io.ktor.server.response.* import io.ktor.util.* /** * A configuration for the [ConditionalHeaders] plugin. */ @KtorDsl public class ConditionalHeadersConfig { internal val versionProviders = mutableListOf<suspend (ApplicationCall, OutgoingContent) -> List<Version>>() init { versionProviders.add { _, content -> content.versions } versionProviders.add { call, content -> content.headers.parseVersions().takeIf { it.isNotEmpty() } ?: call.response.headers.allValues().parseVersions() } } /** * Registers a function that can fetch a version list for a given [ApplicationCall] and [OutgoingContent]. * * @see [ConditionalHeaders] */ public fun version(provider: suspend (ApplicationCall, OutgoingContent) -> List<Version>) { versionProviders.add(provider) } } internal val VersionProvidersKey: AttributeKey<List<suspend (ApplicationCall, OutgoingContent) -> List<Version>>> = AttributeKey("ConditionalHeadersKey") /** * Retrieves versions such as [LastModifiedVersion] or [EntityTagVersion] for a given content. */ public suspend fun ApplicationCall.versionsFor(content: OutgoingContent): List<Version> { val versionProviders = application.attributes.getOrNull(VersionProvidersKey) return versionProviders?.flatMap { it(this, content) } ?: emptyList() } /** * A plugin that avoids sending the body of content if it has not changed since the last request. * This is achieved by using the following headers: * - The `Last-Modified` response header contains a resource modification time. * For example, if the client request contains the `If-Modified-Since` value, * Ktor will send a full response only if a resource has been modified after the given date. * - The `Etag` response header is an identifier for a specific resource version. * For instance, if the client request contains the `If-None-Match` value, * Ktor won't send a full response in case this value matches the `Etag`. * * The code snippet below shows how to add a `Etag` and `Last-Modified` headers for `CSS`: * ```kotlin * install(ConditionalHeaders) { * version { call, outgoingContent -> * when (outgoingContent.contentType?.withoutParameters()) { * ContentType.Text.CSS -> listOf(EntityTagVersion("abc123"), LastModifiedVersion(Date(1646387527500))) * else -> emptyList() * } * } * } * ``` * * You can learn more from [Conditional headers](https://ktor.io/docs/conditional-headers.html). */ public val ConditionalHeaders: RouteScopedPlugin<ConditionalHeadersConfig> = createRouteScopedPlugin( "ConditionalHeaders", ::ConditionalHeadersConfig ) { val versionProviders = pluginConfig.versionProviders application.attributes.put(VersionProvidersKey, versionProviders) fun checkVersions(call: ApplicationCall, versions: List<Version>): VersionCheckResult { for (version in versions) { val result = version.check(call.request.headers) if (result != VersionCheckResult.OK) { return result } } return VersionCheckResult.OK } on(ResponseBodyReadyForSend) { call, content -> val versions = call.versionsFor(content) if (versions.isNotEmpty()) { val headers = Headers.build { versions.forEach { it.appendHeadersTo(this) } } val responseHeaders = call.response.headers headers.forEach { name, values -> if (!responseHeaders.contains(name)) { values.forEach { responseHeaders.append(name, it) } } } } val checkResult = checkVersions(call, versions) if (checkResult != VersionCheckResult.OK) { transformBodyTo(HttpStatusCodeContent(checkResult.statusCode)) } } } /** * Checks the current [etag] value and pass it through conditions supplied by the remote client. * Depending on the conditions, it produces `410 Precondition Failed` or `304 Not modified` responses when necessary. * Otherwise, sets the `ETag` header and delegates to the [block] function * * It never handles If-None-Match: * as it is related to non-etag logic (for example, Last modified checks). * See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26 for more details */ @Deprecated( "Use configuration for ConditionalHeaders or configure block of call.respond function.", level = DeprecationLevel.ERROR ) public suspend fun ApplicationCall.withETag(etag: String, putHeader: Boolean = true, block: suspend () -> Unit) { val version = EntityTagVersion(etag) val result = version.check(request.headers) if (putHeader) { response.header(HttpHeaders.ETag, etag) } when (result) { VersionCheckResult.NOT_MODIFIED, VersionCheckResult.PRECONDITION_FAILED -> respond(result.statusCode) VersionCheckResult.OK -> block() } } /** * Retrieves the `LastModified` and `ETag` versions from this [OutgoingContent] headers. */ @Deprecated( "Use versions or headers.parseVersions()", level = DeprecationLevel.ERROR ) public val OutgoingContent.defaultVersions: List<Version> get() { val extensionVersions = versions if (extensionVersions.isNotEmpty()) { return extensionVersions } return headers.parseVersions() } /** * Retrieves the `LastModified` and `ETag` versions from headers. */ public fun Headers.parseVersions(): List<Version> { val lastModifiedHeaders = getAll(HttpHeaders.LastModified) ?: emptyList() val etagHeaders = getAll(HttpHeaders.ETag) ?: emptyList() val versions = ArrayList<Version>(lastModifiedHeaders.size + etagHeaders.size) lastModifiedHeaders.mapTo(versions) { LastModifiedVersion(it.fromHttpToGmtDate()) } etagHeaders.mapTo(versions) { EntityTagVersion(it) } return versions }
apache-2.0
b0dc822b8d4486f1c0d721c347a4bf3b
35.994186
119
0.689926
4.415684
false
false
false
false
Tickaroo/tikxml
annotationprocessortesting-kt/src/main/java/com/tickaroo/tikxml/annotationprocessing/propertyelement/EmptyLongPropertyElement.kt
1
652
package com.tickaroo.tikxml.annotationprocessing.propertyelement import com.tickaroo.tikxml.annotation.PropertyElement import com.tickaroo.tikxml.annotation.Xml /** * @author Hannes Dorfmann */ @Xml(name = "emptyPropertyTag") class EmptyLongPropertyElement { @PropertyElement var empty: Long = 0 override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is EmptyLongPropertyElement) return false val that = other as EmptyLongPropertyElement? return empty == that!!.empty } override fun hashCode(): Int { return (empty xor empty.ushr(32)).toInt() } }
apache-2.0
89fd6d9d795297bd1f216da14fb7de16
23.148148
64
0.690184
4.405405
false
false
false
false
mdanielwork/intellij-community
plugins/gradle/java/src/service/project/data/ExternalAnnotationsDataService.kt
1
3119
// 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 org.jetbrains.plugins.gradle.service.project.data import com.intellij.codeInsight.ExternalAnnotationsArtifactsResolver import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.Key import com.intellij.openapi.externalSystem.model.ProjectKeys import com.intellij.openapi.externalSystem.model.project.LibraryData import com.intellij.openapi.externalSystem.model.project.ProjectData import com.intellij.openapi.externalSystem.service.project.IdeModelsProvider import com.intellij.openapi.externalSystem.service.project.manage.AbstractProjectDataService import com.intellij.openapi.externalSystem.util.ExternalSystemConstants import com.intellij.openapi.externalSystem.util.Order import com.intellij.openapi.progress.runBackgroundableTask import com.intellij.openapi.project.Project import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.util.registry.Registry import org.jetbrains.plugins.gradle.settings.GradleSettings @Order(value = ExternalSystemConstants.UNORDERED) class ExternalAnnotationsDataService: AbstractProjectDataService<LibraryData, Library>() { override fun getTargetDataKey(): Key<LibraryData> = ProjectKeys.LIBRARY override fun onSuccessImport(imported: MutableCollection<DataNode<LibraryData>>, projectData: ProjectData?, project: Project, modelsProvider: IdeModelsProvider) { if (!Registry.`is`("external.system.import.resolve.annotations")) { return } projectData?.apply { val importRepositories = GradleSettings .getInstance(project) .linkedProjectsSettings .find { settings -> settings.externalProjectPath == linkedExternalProjectPath } ?.isResolveExternalAnnotations ?: false if (!importRepositories) { return } } val resolver = ExternalAnnotationsArtifactsResolver.EP_NAME.extensionList.firstOrNull() ?: return val totalSize = imported.size.toDouble() runBackgroundableTask("Resolving external annotations", project) { indicator -> indicator.isIndeterminate = false imported.forEachIndexed { index, dataNode -> if (indicator.isCanceled) { return@runBackgroundableTask } indicator.fraction = (index.toDouble() + 1) / totalSize val libraryData = dataNode.data val libraryName = libraryData.internalName val library = modelsProvider.getLibraryByName(libraryName) if (library != null) { indicator.text = "Looking for annotations for '$libraryName'" val mavenId = "${libraryData.groupId}:${libraryData.artifactId}:${libraryData.version}" resolver.resolve(project, library, mavenId) } } } } companion object { val LOG = Logger.getInstance(ExternalAnnotationsDataService::class.java) } }
apache-2.0
7735666ab870af6daa0cd481964bc2d1
43.571429
140
0.73966
5.207012
false
false
false
false
songful/PocketHub
app/src/main/java/com/github/pockethub/android/util/ImageBinPoster.kt
1
1936
package com.github.pockethub.android.util import android.content.Context import android.net.Uri import io.reactivex.Single import okhttp3.* import okio.Okio import java.io.IOException object ImageBinPoster { private val client = OkHttpClient() /** * Post the image to ImageBin * * @param context A context * @param uri The content URI * @return Single containing the network Response */ @JvmStatic fun post(context: Context, uri: Uri): Single<Response> { var bytes: ByteArray? = null try { val stream = context.contentResolver.openInputStream(uri) if (stream != null) { val source = Okio.source(stream) bytes = Okio.buffer(source).readByteArray() } } catch (e: IOException) { return Single.error(e) } return post(bytes) } /** * Post the image to ImageBin * * @param bytes Bytes of the image to post * @return Single containing the network Response */ @JvmStatic fun post(bytes: ByteArray?): Single<Response> { val requestBody = MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", "test", RequestBody.create(MediaType.parse("image/*"), bytes!!)) .build() val request = Request.Builder() .url("https://imagebin.ca/upload.php") .post(requestBody) .build() return Single.fromCallable { client.newCall(request).execute() } } @JvmStatic fun getUrl(body: String): String? { var url: String? = null val pairs = body.split("\n") for (string in pairs) { if (string.startsWith("url")) { val index = string.indexOf(":") url = string.substring(index + 1) } } return url } }
apache-2.0
1561a21fe768d0c7eb9e30306a1218d6
26.267606
105
0.565599
4.555294
false
false
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/tracker/importer/internal/JobReportHandler.kt
1
5806
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.tracker.importer.internal import dagger.Reusable import javax.inject.Inject import org.hisp.dhis.android.core.common.internal.DataStatePropagator import org.hisp.dhis.android.core.common.internal.DataStateUidHolder import org.hisp.dhis.android.core.tracker.importer.internal.TrackerImporterObjectType.* @Reusable internal class JobReportHandler @Inject internal constructor( private val eventHandler: JobReportEventHandler, private val enrollmentHandler: JobReportEnrollmentHandler, private val trackedEntityHandler: JobReportTrackedEntityHandler, private val relationshipHandler: JobReportRelationshipHandler, private val dataStatePropagator: DataStatePropagator ) { fun handle(o: JobReport, jobObjects: List<TrackerJobObject>) { val jobObjectsMap = jobObjects.associateBy { jo -> Pair(jo.trackerType(), jo.objectUid()) } val relatedUids = getRelatedUids(jobObjects) handleErrors(o, jobObjectsMap) handleSuccesses(o, jobObjectsMap) handleNotPresent(o, jobObjectsMap) dataStatePropagator.refreshAggregatedSyncStates(relatedUids) } private fun handleErrors( o: JobReport, jobObjectsMap: Map<Pair<TrackerImporterObjectType, String>, TrackerJobObject> ) { o.validationReport.errorReports.forEach { errorReport -> jobObjectsMap[Pair(errorReport.trackerType, errorReport.uid)]?.let { getHandler(it.trackerType()).handleError(it, errorReport) } } } private fun handleSuccesses( o: JobReport, jobObjectsMap: Map<Pair<TrackerImporterObjectType, String>, TrackerJobObject> ) { if (o.bundleReport != null) { val typeMap = o.bundleReport.typeReportMap applySuccess(typeMap.event, jobObjectsMap, eventHandler) applySuccess(typeMap.enrollment, jobObjectsMap, enrollmentHandler) applySuccess(typeMap.trackedEntity, jobObjectsMap, trackedEntityHandler) applySuccess(typeMap.relationship, jobObjectsMap, relationshipHandler) } } private fun handleNotPresent( o: JobReport, jobObjectsMap: Map<Pair<TrackerImporterObjectType, String>, TrackerJobObject> ) { val presentSuccesses = if (o.bundleReport == null) emptySet<Pair<TrackerImporterObjectType, String>>() else { val tm = o.bundleReport.typeReportMap setOf(tm.event, tm.trackedEntity, tm.enrollment, tm.relationship).flatMap { it.objectReports }.map { Pair(it.trackerType, it.uid) } }.toSet() val presentErrors = o.validationReport.errorReports.map { Pair(it.trackerType, it.uid) }.toSet() val expectedObjects = jobObjectsMap.keys val notPresentObjects = expectedObjects - presentSuccesses - presentErrors notPresentObjects .mapNotNull { jobObjectsMap[it] } .forEach { getHandler(it.trackerType()).handleNotPresent(it) } } private fun applySuccess( typeReport: JobTypeReport, jobObjects: Map<Pair<TrackerImporterObjectType, String>, TrackerJobObject>, typeHandler: JobReportTypeHandler ) { typeReport.objectReports .mapNotNull { jobObjects[Pair(it.trackerType, it.uid)] } .forEach { typeHandler.handleSuccess(it) } } private fun getRelatedUids(jobObjects: List<TrackerJobObject>): DataStateUidHolder { return dataStatePropagator.getRelatedUids( jobObjects.filter { it.trackerType() == TRACKED_ENTITY }.map { it.objectUid() }, jobObjects.filter { it.trackerType() == ENROLLMENT }.map { it.objectUid() }, jobObjects.filter { it.trackerType() == EVENT }.map { it.objectUid() }, jobObjects.filter { it.trackerType() == RELATIONSHIP }.map { it.objectUid() } ) } private fun getHandler(type: TrackerImporterObjectType): JobReportTypeHandler { return when (type) { EVENT -> eventHandler ENROLLMENT -> enrollmentHandler TRACKED_ENTITY -> trackedEntityHandler RELATIONSHIP -> relationshipHandler } } }
bsd-3-clause
3eea8550536bd4f744892853ae420e77
43.320611
117
0.707027
4.712662
false
false
false
false
dahlstrom-g/intellij-community
platform/workspaceModel/jps/src/com/intellij/workspaceModel/ide/impl/jps/serialization/JpsArtifactEntitiesSerializer.kt
4
18056
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.ide.impl.jps.serialization import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.JDOMUtil import com.intellij.util.xmlb.SkipDefaultsSerializationFilter import com.intellij.util.xmlb.XmlSerializer import com.intellij.workspaceModel.ide.JpsFileEntitySource import com.intellij.workspaceModel.ide.JpsImportedEntitySource import com.intellij.workspaceModel.ide.JpsProjectConfigLocation import com.intellij.workspaceModel.ide.impl.JpsEntitySourceFactory import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryNameGenerator import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.bridgeEntities.* import com.intellij.workspaceModel.storage.bridgeEntities.api.* import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jdom.Element import org.jetbrains.jps.model.serialization.JDomSerializationUtil import org.jetbrains.jps.model.serialization.SerializationConstants import org.jetbrains.jps.model.serialization.artifact.ArtifactPropertiesState import org.jetbrains.jps.model.serialization.artifact.ArtifactState import org.jetbrains.jps.util.JpsPathUtil import com.intellij.workspaceModel.storage.bridgeEntities.api.modifyEntity internal class JpsArtifactsDirectorySerializerFactory(override val directoryUrl: String) : JpsDirectoryEntitiesSerializerFactory<ArtifactEntity> { override val componentName: String get() = ARTIFACT_MANAGER_COMPONENT_NAME override val entityClass: Class<ArtifactEntity> get() = ArtifactEntity::class.java override fun createSerializer(fileUrl: String, entitySource: JpsFileEntitySource.FileInDirectory, virtualFileManager: VirtualFileUrlManager): JpsArtifactEntitiesSerializer { return JpsArtifactEntitiesSerializer(virtualFileManager.fromUrl(fileUrl), entitySource, false, virtualFileManager) } override fun getDefaultFileName(entity: ArtifactEntity): String { return entity.name } override fun changeEntitySourcesToDirectoryBasedFormat(builder: MutableEntityStorage, configLocation: JpsProjectConfigLocation) { /// XXX In fact, we suppose that all packaging element have a connection to the corresponding artifact. // However, technically, it's possible to create a packaging element without artifact or connection to another packaging element. // Here we could check that the amount of "processed" packaging elements equals to the amount of packaging elements in store, // but unfortunately [WorkspaceModel.entities] function doesn't work with abstract entities at the moment. builder.entities(ArtifactEntity::class.java).forEach { // Convert artifact to the new source val artifactSource = JpsEntitySourceFactory.createJpsEntitySourceForArtifact(configLocation) builder.modifyEntity(it) { this.entitySource = artifactSource } // Convert it's packaging elements it.rootElement!!.forThisAndFullTree { builder.modifyEntity(PackagingElementEntity.Builder::class.java, it) { this.entitySource = artifactSource } } } // Convert properties builder.entities(ArtifactPropertiesEntity::class.java).forEach { builder.modifyEntity(it) { this.entitySource = it.artifact.entitySource } } } private fun PackagingElementEntity.forThisAndFullTree(action: (PackagingElementEntity) -> Unit) { action(this) if (this is CompositePackagingElementEntity) { this.children.forEach { if (it is CompositePackagingElementEntity) { it.forThisAndFullTree(action) } else { action(it) } } } } } private const val ARTIFACT_MANAGER_COMPONENT_NAME = "ArtifactManager" internal class JpsArtifactsExternalFileSerializer(private val externalFile: JpsFileEntitySource.ExactFile, private val internalArtifactsDirUrl: VirtualFileUrl, private val fileInDirectorySourceNames: FileInDirectorySourceNames, virtualFileManager: VirtualFileUrlManager) : JpsArtifactEntitiesSerializer(externalFile.file, externalFile, false, virtualFileManager), JpsFileEntityTypeSerializer<ArtifactEntity> { override val isExternalStorage: Boolean get() = true override val entityFilter: (ArtifactEntity) -> Boolean get() = { (it.entitySource as? JpsImportedEntitySource)?.storedExternally == true } override val additionalEntityTypes: List<Class<out WorkspaceEntity>> get() = listOf(ArtifactsOrderEntity::class.java) override fun createEntitySource(artifactTag: Element): EntitySource? { val externalSystemId = artifactTag.getAttributeValue(SerializationConstants.EXTERNAL_SYSTEM_ID_ATTRIBUTE) ?: return null val artifactName = XmlSerializer.deserialize(artifactTag, ArtifactState::class.java).name val existingInternalSource = fileInDirectorySourceNames.findSource(mainEntityClass, artifactName) val internalEntitySource = if (existingInternalSource != null && existingInternalSource.directory == internalArtifactsDirUrl) { logger<JpsLibrariesExternalFileSerializer>().debug{ "Reuse existing source for artifact: ${existingInternalSource.fileNameId}=$artifactName" } existingInternalSource } else { JpsFileEntitySource.FileInDirectory(internalArtifactsDirUrl, externalFile.projectLocation) } return JpsImportedEntitySource(internalEntitySource, externalSystemId, true) } override fun getExternalSystemId(artifactEntity: ArtifactEntity): String? { val source = artifactEntity.entitySource return (source as? JpsImportedEntitySource)?.externalSystemId } override fun deleteObsoleteFile(fileUrl: String, writer: JpsFileContentWriter) { writer.saveComponent(fileUrl, ARTIFACT_MANAGER_COMPONENT_NAME, null) } } internal class JpsArtifactsFileSerializer(fileUrl: VirtualFileUrl, entitySource: JpsFileEntitySource, virtualFileManager: VirtualFileUrlManager) : JpsArtifactEntitiesSerializer(fileUrl, entitySource, true, virtualFileManager), JpsFileEntityTypeSerializer<ArtifactEntity> { override val isExternalStorage: Boolean get() = false override val entityFilter: (ArtifactEntity) -> Boolean get() = { (it.entitySource as? JpsImportedEntitySource)?.storedExternally != true } override val additionalEntityTypes: List<Class<out WorkspaceEntity>> get() = listOf(ArtifactsOrderEntity::class.java) override fun deleteObsoleteFile(fileUrl: String, writer: JpsFileContentWriter) { writer.saveComponent(fileUrl, ARTIFACT_MANAGER_COMPONENT_NAME, null) } } internal open class JpsArtifactEntitiesSerializer(override val fileUrl: VirtualFileUrl, override val internalEntitySource: JpsFileEntitySource, private val preserveOrder: Boolean, private val virtualFileManager: VirtualFileUrlManager) : JpsFileEntitiesSerializer<ArtifactEntity> { open val isExternalStorage: Boolean get() = false override val mainEntityClass: Class<ArtifactEntity> get() = ArtifactEntity::class.java override fun loadEntities(builder: MutableEntityStorage, reader: JpsFileContentReader, errorReporter: ErrorReporter, virtualFileManager: VirtualFileUrlManager) { val artifactListElement = reader.loadComponent(fileUrl.url, ARTIFACT_MANAGER_COMPONENT_NAME) if (artifactListElement == null) return val orderOfItems = ArrayList<String>() artifactListElement.getChildren("artifact").forEach { actifactElement -> val entitySource = createEntitySource(actifactElement) ?: return@forEach val state = XmlSerializer.deserialize(actifactElement, ArtifactState::class.java) val outputUrl = state.outputPath?.let { path -> if (path.isNotEmpty()) virtualFileManager.fromPath(path) else null } val rootElement = loadPackagingElement(state.rootElement, entitySource, builder) val artifactEntity = builder.addArtifactEntity(state.name, state.artifactType, state.isBuildOnMake, outputUrl, rootElement as CompositePackagingElementEntity, entitySource) for (propertiesState in state.propertiesList) { builder.addArtifactPropertiesEntity(artifactEntity, propertiesState.id, JDOMUtil.write(propertiesState.options), entitySource) } val externalSystemId = actifactElement.getAttributeValue(SerializationConstants.EXTERNAL_SYSTEM_ID_IN_INTERNAL_STORAGE_ATTRIBUTE) if (externalSystemId != null && !isExternalStorage) { builder.addEntity(ArtifactExternalSystemIdEntity(externalSystemId, entitySource) { this.artifactEntity = artifactEntity }) } orderOfItems += state.name } if (preserveOrder) { val entity = builder.entities(ArtifactsOrderEntity::class.java).firstOrNull() if (entity != null) { builder.modifyEntity(entity) { orderOfArtifacts = orderOfItems } } else { builder.addEntity(ArtifactsOrderEntity(orderOfItems, internalEntitySource)) } } } protected open fun createEntitySource(artifactTag: Element): EntitySource? = internalEntitySource protected open fun getExternalSystemId(artifactEntity: ArtifactEntity): String? { return artifactEntity.artifactExternalSystemIdEntity?.externalSystemId } private fun loadPackagingElement(element: Element, source: EntitySource, builder: MutableEntityStorage): PackagingElementEntity { fun loadElementChildren() = element.children.mapTo(ArrayList()) { loadPackagingElement(it, source, builder) } fun getAttribute(name: String) = element.getAttributeValue(name)!! fun getOptionalAttribute(name: String) = element.getAttributeValue(name) fun getPathAttribute(name: String) = element.getAttributeValue(name)!!.let { virtualFileManager.fromPath(it) } return when (val typeId = getAttribute("id")) { "root" -> builder.addArtifactRootElementEntity(loadElementChildren(), source) "directory" -> builder.addDirectoryPackagingElementEntity(getAttribute("name"), loadElementChildren(), source) "archive" -> builder.addArchivePackagingElementEntity(getAttribute("name"), loadElementChildren(), source) "dir-copy" -> builder.addDirectoryCopyPackagingElementEntity(getPathAttribute("path"), source) "file-copy" -> builder.addFileCopyPackagingElementEntity(getPathAttribute("path"), getOptionalAttribute("output-file-name"), source) "extracted-dir" -> builder.addExtractedDirectoryPackagingElementEntity(getPathAttribute("path"), getAttribute("path-in-jar"), source) "artifact" -> builder.addArtifactOutputPackagingElementEntity(getOptionalAttribute("artifact-name")?.let { ArtifactId(it) }, source) "module-output" -> builder.addModuleOutputPackagingElementEntity(getOptionalAttribute("name")?.let { ModuleId(it) }, source) "module-test-output" -> builder.addModuleTestOutputPackagingElementEntity(getOptionalAttribute("name")?.let { ModuleId(it) }, source) "module-source" -> builder.addModuleSourcePackagingElementEntity(getOptionalAttribute("name")?.let { ModuleId(it) }, source) "library" -> { val level = getOptionalAttribute("level") val name = getOptionalAttribute("name") if (level != null && name != null) { val moduleName = getOptionalAttribute("module-name") val parentId = when { moduleName != null -> LibraryTableId.ModuleLibraryTableId(ModuleId(moduleName)) else -> LibraryNameGenerator.getLibraryTableId(level) } builder.addLibraryFilesPackagingElementEntity(LibraryId(name, parentId), source) } else { builder.addLibraryFilesPackagingElementEntity(null, source) } } else -> { val cloned = element.clone() cloned.removeContent() builder.addCustomPackagingElementEntity(typeId, JDOMUtil.write(cloned), loadElementChildren(), source) } } } override fun saveEntities(mainEntities: Collection<ArtifactEntity>, entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>, storage: EntityStorage, writer: JpsFileContentWriter) { if (mainEntities.isEmpty()) return val componentTag = JDomSerializationUtil.createComponentElement(ARTIFACT_MANAGER_COMPONENT_NAME) val artifactsByName = mainEntities.groupByTo(HashMap()) { it.name } val orderOfItems = if (preserveOrder) (entities[ArtifactsOrderEntity::class.java]?.firstOrNull() as? ArtifactsOrderEntity?)?.orderOfArtifacts else null orderOfItems?.forEach { name -> val artifacts = artifactsByName.remove(name) artifacts?.forEach { componentTag.addContent(saveArtifact(it)) } } artifactsByName.values.forEach { it.forEach { artifact -> componentTag.addContent(saveArtifact(artifact)) } } writer.saveComponent(fileUrl.url, ARTIFACT_MANAGER_COMPONENT_NAME, componentTag) } private fun saveArtifact(artifact: ArtifactEntity): Element { val artifactState = ArtifactState() artifactState.name = artifact.name artifactState.artifactType = artifact.artifactType artifactState.isBuildOnMake = artifact.includeInProjectBuild artifactState.outputPath = JpsPathUtil.urlToPath(artifact.outputUrl?.url) val customProperties = artifact.customProperties.filter { it.entitySource == artifact.entitySource } artifactState.propertiesList = customProperties.mapNotNullTo(ArrayList()) { if (it.propertiesXmlTag == null) return@mapNotNullTo null ArtifactPropertiesState().apply { id = it.providerType options = it.propertiesXmlTag?.let { JDOMUtil.load(it) } } } artifactState.rootElement = savePackagingElement(artifact.rootElement!!) val externalSystemId = getExternalSystemId(artifact) if (externalSystemId != null) { if (isExternalStorage) artifactState.externalSystemId = externalSystemId else artifactState.externalSystemIdInInternalStorage = externalSystemId } return XmlSerializer.serialize(artifactState, SkipDefaultsSerializationFilter()) } private fun savePackagingElement(element: PackagingElementEntity): Element { val tag = Element("element") fun setId(typeId: String) = tag.setAttribute("id", typeId) fun setAttribute(name: String, value: String) = tag.setAttribute(name, value) fun setPathAttribute(name: String, value: VirtualFileUrl) = tag.setAttribute(name, JpsPathUtil.urlToPath(value.url)) fun saveElementChildren(composite: CompositePackagingElementEntity) { composite.children.forEach { tag.addContent(savePackagingElement(it)) } } when (element) { is ArtifactRootElementEntity -> { setId("root") saveElementChildren(element) } is DirectoryPackagingElementEntity -> { setId("directory") setAttribute("name", element.directoryName) saveElementChildren(element) } is ArchivePackagingElementEntity -> { setId("archive") setAttribute("name", element.fileName) saveElementChildren(element) } is DirectoryCopyPackagingElementEntity -> { setId("dir-copy") setPathAttribute("path", element.filePath) } is FileCopyPackagingElementEntity -> { setId("file-copy") setPathAttribute("path", element.filePath) element.renamedOutputFileName?.let { setAttribute("output-file-name", it) } } is ExtractedDirectoryPackagingElementEntity -> { setId("extracted-dir") setPathAttribute("path", element.filePath) setAttribute("path-in-jar", element.pathInArchive) } is ArtifactOutputPackagingElementEntity -> { setId("artifact") element.artifact?.let { setAttribute("artifact-name", it.name) } } is ModuleOutputPackagingElementEntity -> { setId("module-output") element.module?.let { setAttribute("name", it.name) } } is ModuleTestOutputPackagingElementEntity -> { setId("module-test-output") element.module?.let { setAttribute("name", it.name) } } is ModuleSourcePackagingElementEntity -> { setId("module-source") element.module?.let { setAttribute("name", it.name) } } is LibraryFilesPackagingElementEntity -> { setId("library") val library = element.library if (library != null) { val tableId = library.tableId setAttribute("level", tableId.level) setAttribute("name", library.name) if (tableId is LibraryTableId.ModuleLibraryTableId) { setAttribute("module-name", tableId.moduleId.name) } } } is CustomPackagingElementEntity -> { setId(element.typeId) val customElement = JDOMUtil.load(element.propertiesXmlTag) customElement.attributes.forEach { attribute -> setAttribute(attribute.name, attribute.value) } saveElementChildren(element) } } return tag } override fun toString(): String = "${javaClass.simpleName.substringAfterLast('.')}($fileUrl)" }
apache-2.0
073144e7952e432138f14c8c2b045eeb
47.8
155
0.721478
5.548863
false
false
false
false
EddieRingle/statesman
runtime/src/main/kotlin/io/ringle/statesman/Statesman.kt
1
1350
package io.ringle.statesman import android.app.Activity import android.app.Fragment import android.os.Bundle class Statesman() : Fragment(), StateHost { companion object { @JvmStatic val sKeyPrefix = "__statesman_" @JvmStatic val sKeyFragment = "${sKeyPrefix}fragment" @JvmStatic val sKeyKeyList = "${sKeyPrefix}keyList" @JvmStatic val sKeyNewState = "${sKeyPrefix}newState" @JvmStatic val sKeyState = { key: Int -> "${sKeyPrefix}state[$key]" } fun of(activity: Activity): Statesman { val fm = activity.fragmentManager var sm = fm.findFragmentByTag(sKeyFragment) as? Statesman if (sm == null) { sm = Statesman() fm.beginTransaction().add(sm, sKeyFragment).commit() } return sm } } override val managedStates = StateHost.newManagedStates() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) retainInstance = true } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) restoreState(savedInstanceState) } override fun onSaveInstanceState(outState: Bundle) { saveState(outState) super.onSaveInstanceState(outState) } }
mit
046cb7f18afdeac08ebe002f24efd1c7
27.125
77
0.642963
4.72028
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/action/Action_Timeline.kt
1
8003
package jp.juggler.subwaytooter.action import jp.juggler.subwaytooter.ActMain import jp.juggler.subwaytooter.R import jp.juggler.subwaytooter.actmain.addColumn import jp.juggler.subwaytooter.api.entity.EntityId import jp.juggler.subwaytooter.api.entity.Host import jp.juggler.subwaytooter.api.entity.TootAccount import jp.juggler.subwaytooter.api.entity.TootStatus import jp.juggler.subwaytooter.api.runApiTask import jp.juggler.subwaytooter.api.syncStatus import jp.juggler.subwaytooter.column.ColumnType import jp.juggler.subwaytooter.dialog.pickAccount import jp.juggler.subwaytooter.table.SavedAccount import jp.juggler.subwaytooter.util.matchHost import jp.juggler.util.launchMain import jp.juggler.util.showToast import java.util.* // アカウントを選んでタイムラインカラムを追加 fun ActMain.timeline( pos: Int, type: ColumnType, args: Array<out Any> = emptyArray(), ) { launchMain { pickAccount( bAllowPseudo = type.bAllowPseudo, bAllowMisskey = type.bAllowMisskey, bAllowMastodon = type.bAllowMastodon, bAuto = true, message = getString(R.string.account_picker_add_timeline_of, type.name1(applicationContext)) )?.let { account -> when (type) { ColumnType.PROFILE -> account.loginAccount?.id?.let { addColumn(pos, account, type, it) } ColumnType.PROFILE_DIRECTORY -> addColumn(pos, account, type, account.apiHost) else -> addColumn(pos, account, type, *args) } } } } // アカウント選択付きでタイムラインを追加 // その際にアカウントをラムダ式でフィルタする //fun ActMain.timelineWithFilter( // pos: Int, // type: ColumnType, // args: Array<out Any> = emptyArray(), // filter: suspend (SavedAccount) -> Boolean //) { // launchMain { // val accountList = accountListWithFilter { _, a -> // when { // a.isPseudo && !type.bAllowPseudo -> false // a.isMisskey && !type.bAllowMisskey -> false // a.isMastodon && !type.bAllowMastodon -> false // else -> filter(a) // } // }?.toMutableList() ?: return@launchMain // // pickAccount( // accountListArg = accountList, // bAuto = true, // message = getString( // R.string.account_picker_add_timeline_of, // type.name1(applicationContext) // ) // )?.let { ai -> // when (type) { // ColumnType.PROFILE -> // ai.loginAccount?.id?.let { addColumn(pos, ai, type, it) } // // ColumnType.PROFILE_DIRECTORY -> // addColumn(pos, ai, type, ai.apiHost) // // else -> // addColumn(pos, ai, type, *args) // } // } // } //} // 指定アカウントで指定タンスのドメインタイムラインを開く // https://fedibird.com/@noellabo/103266814160117397 fun ActMain.timelineDomain( pos: Int, accessInfo: SavedAccount, host: Host, ) = addColumn(pos, accessInfo, ColumnType.DOMAIN_TIMELINE, host) // 指定タンスのローカルタイムラインを開く fun ActMain.timelineLocal( pos: Int, host: Host, ) { launchMain { // 指定タンスのアカウントを持ってるか? val accountList = ArrayList<SavedAccount>() for (a in SavedAccount.loadAccountList(applicationContext)) { if (a.matchHost(host)) accountList.add(a) } if (accountList.isEmpty()) { // 持ってないなら疑似アカウントを追加する addPseudoAccount(host)?.let { ai -> addColumn(pos, ai, ColumnType.LOCAL) } } else { // 持ってるならアカウントを選んで開く SavedAccount.sort(accountList) pickAccount( bAllowPseudo = true, bAuto = false, message = getString(R.string.account_picker_add_timeline_of, host), accountListArg = accountList )?.let { addColumn(pos, it, ColumnType.LOCAL) } } } } private fun ActMain.timelineAround( accessInfo: SavedAccount, pos: Int, id: EntityId, type: ColumnType, ) = addColumn(pos, accessInfo, type, id) // 投稿を同期してstatusIdを調べてから指定アカウントでタイムラインを開く private fun ActMain.timelineAroundByStatus( accessInfo: SavedAccount, pos: Int, status: TootStatus, type: ColumnType, ) { launchMain { var resultStatus: TootStatus? = null runApiTask(accessInfo) { client -> val pair = client.syncStatus(accessInfo, status) resultStatus = pair.second pair.first }?.let { result -> when (val localStatus = resultStatus) { null -> showToast(true, result.error) else -> timelineAround(accessInfo, pos, localStatus.id, type) } } } } // 指定タンスの指定投稿付近のタイムラインを開く。アカウント選択あり。 fun ActMain.timelineAroundByStatusAnotherAccount( accessInfo: SavedAccount, pos: Int, host: Host?, status: TootStatus?, type: ColumnType, allowPseudo: Boolean = true, ) { host?.valid() ?: return status ?: return // 利用可能なアカウントを列挙する val accountList1 = ArrayList<SavedAccount>() // 閲覧アカウントとホストが同じ val accountList2 = ArrayList<SavedAccount>() // その他実アカウント label@ for (a in SavedAccount.loadAccountList(this)) { // Misskeyアカウントはステータスの同期が出来ないので選択させない if (a.isNA || a.isMisskey) continue when { // 閲覧アカウントとホスト名が同じならステータスIDの変換が必要ない a.matchHost(accessInfo) -> if (allowPseudo || !a.isPseudo) accountList1.add(a) // 実アカウントならステータスを同期して同時間帯のTLを見れる !a.isPseudo -> accountList2.add(a) } } SavedAccount.sort(accountList1) SavedAccount.sort(accountList2) accountList1.addAll(accountList2) if (accountList1.isEmpty()) { showToast(false, R.string.missing_available_account) return } launchMain { pickAccount( bAuto = true, message = "select account to read timeline", accountListArg = accountList1 )?.let { ai -> if (!ai.isNA && ai.matchHost(accessInfo)) { timelineAround(ai, pos, status.id, type) } else { timelineAroundByStatus(ai, pos, status, type) } } } } fun ActMain.clickAroundAccountTL(accessInfo: SavedAccount, pos: Int, who: TootAccount, status: TootStatus?) = timelineAroundByStatusAnotherAccount( accessInfo, pos, who.apiHost, status, ColumnType.ACCOUNT_AROUND, allowPseudo = false ) fun ActMain.clickAroundLTL(accessInfo: SavedAccount, pos: Int, who: TootAccount, status: TootStatus?) = timelineAroundByStatusAnotherAccount( accessInfo, pos, who.apiHost, status, ColumnType.LOCAL_AROUND ) fun ActMain.clickAroundFTL(accessInfo: SavedAccount, pos: Int, who: TootAccount, status: TootStatus?) = timelineAroundByStatusAnotherAccount( accessInfo, pos, who.apiHost, status, ColumnType.FEDERATED_AROUND )
apache-2.0
d847f5043c37f15d3e574b3df623ef6d
29.925764
109
0.587471
3.80385
false
false
false
false
tommyli/nem12-manager
fenergy-service/src/main/kotlin/co/firefire/fenergy/nem12/service/Nem12Parser.kt
1
15283
// Tommy Li ([email protected]), 2017-05-27 package co.firefire.fenergy.nem12.service import co.firefire.fenergy.nem12.domain.IntervalDay import co.firefire.fenergy.nem12.domain.IntervalEvent import co.firefire.fenergy.nem12.domain.IntervalQuality import co.firefire.fenergy.nem12.domain.IntervalValue import co.firefire.fenergy.nem12.domain.MINUTES_IN_DAY import co.firefire.fenergy.nem12.domain.NmiMeterRegister import co.firefire.fenergy.nem12.domain.Quality import co.firefire.fenergy.nem12.domain.forEachNem12Line import co.firefire.fenergy.shared.domain.DEFAULT_DATE_TIME_FORMATTER import co.firefire.fenergy.shared.domain.DomainException import co.firefire.fenergy.shared.domain.IntervalLength import co.firefire.fenergy.shared.domain.Login import co.firefire.fenergy.shared.domain.LoginNmi import co.firefire.fenergy.shared.domain.NEM12_DELIMITER import co.firefire.fenergy.shared.domain.UnitOfMeasure import org.slf4j.LoggerFactory import org.springframework.core.io.Resource import java.io.InputStreamReader import java.math.BigDecimal import java.time.LocalDate import java.time.LocalDateTime import java.time.format.DateTimeFormatter interface Nem12Parser { fun parseNem12Resource(resource: Resource): Collection<NmiMeterRegister> } interface Nem12ParserContext { fun getCurrentLogin(): Login fun getCurrentRecordType(): Nem12RecordType? fun updateCurrentRecordType(recordType: Nem12RecordType) fun getCurrentNmiMeterRegister(): NmiMeterRegister? fun updateCurrentNmiMeterRegister(nmiMeterRegister: NmiMeterRegister) fun getCurrentIntervalDay(): IntervalDay? fun updateCurrentIntervalDay(intervalDay: IntervalDay) fun mergeNmiMeterRegisterResult() fun mergeIntervalDayResult() fun getProcessedResults(): MutableList<NmiMeterRegister> } interface ErrorCollector { fun addError(error: String) } enum class Nem12RecordId(val id: String) { ID_100("100"), ID_200("200"), ID_300("300"), ID_400("400"), ID_500("500"), ID_900("600"); } sealed class Nem12RecordType(val nem12RecordId: Nem12RecordId, val nextValidRecordTypes: Set<Nem12RecordType>) { fun isNextRecordTypeValid(recordType: Nem12RecordType): Boolean { return nextValidRecordTypes.contains(recordType) } companion object { operator fun invoke(nem12RecordId: Nem12RecordId): Nem12RecordType { return when (nem12RecordId) { Nem12RecordId.ID_100 -> Record100 Nem12RecordId.ID_200 -> Record200 Nem12RecordId.ID_300 -> Record300 Nem12RecordId.ID_400 -> Record400 Nem12RecordId.ID_500 -> Record500 Nem12RecordId.ID_900 -> Record900 } } } object Record100 : Nem12RecordType(Nem12RecordId.ID_100, setOf(Record200, Record900)) object Record200 : Nem12RecordType(Nem12RecordId.ID_200, setOf(Record300, Record900)) object Record300 : Nem12RecordType(Nem12RecordId.ID_300, setOf(Record200, Record300, Record400, Record900)) object Record400 : Nem12RecordType(Nem12RecordId.ID_400, setOf(Record200, Record300, Record400, Record500, Record900)) object Record500 : Nem12RecordType(Nem12RecordId.ID_500, setOf(Record200, Record300, Record500, Record900)) object Record900 : Nem12RecordType(Nem12RecordId.ID_900, setOf()) } data class Nem12Line(val lineNumber: Int, val recordType: Nem12RecordType, val lineItems: List<String>) { companion object { var log = LoggerFactory.getLogger(this::class.java) } fun handleLine(parsingContext: Nem12ParserContext, errorCollector: ErrorCollector): Unit { val currentRecordType: Nem12RecordType? = parsingContext.getCurrentRecordType() if (currentRecordType != null && currentRecordType.isNextRecordTypeValid(currentRecordType)) { throw DomainException("Invalid next record type [${recordType}], current record type [${currentRecordType}]") } try { when (recordType) { is Nem12RecordType.Record100 -> { log.info("Ignoring Record Type 100") } is Nem12RecordType.Record200 -> { parsingContext.mergeIntervalDayResult() parsingContext.mergeNmiMeterRegisterResult() val nmi = parseMandatory("nmi", 1, lineNumber, lineItems, { it }) val nmiConfig = parseOptional("nmiConfig", 2, lineNumber, lineItems, { it }) val registerId = parseMandatory("registerId", 3, lineNumber, lineItems, { it }) val nmiSuffix = parseMandatory("nmiSuffix", 4, lineNumber, lineItems, { it }) val mdmDataStreamId = parseOptional("mdmDataStreamId", 5, lineNumber, lineItems, { it }) val meterSerial = parseMandatory("meterSerial", 6, lineNumber, lineItems, { it }) val uom = parseMandatory("uom", 7, lineNumber, lineItems, { UnitOfMeasure.valueOf(it) }) val intervalLength = parseMandatory("intervalLength", 8, lineNumber, lineItems, { IntervalLength.fromMinute(it.toInt()) }) val nextScheduledReadDate = parseOptional("nextScheduledReadDate", 9, lineNumber, lineItems, { LocalDate.parse(it, DateTimeFormatter.BASIC_ISO_DATE) }) val currentLogin = parsingContext.getCurrentLogin() val loginNmi = LoginNmi(currentLogin, nmi) val existingNmr = parsingContext.getProcessedResults().find { it.loginNmi == loginNmi && it.meterSerial == meterSerial && it.registerId == registerId && it.nmiSuffix == nmiSuffix } val nmiMeterRegister = existingNmr ?: NmiMeterRegister(loginNmi, meterSerial, registerId, nmiSuffix) loginNmi.addNmiMeterRegister(nmiMeterRegister) nmiMeterRegister.nmiConfig = nmiConfig nmiMeterRegister.mdmDataStreamId = mdmDataStreamId nmiMeterRegister.nextScheduledReadDate = nextScheduledReadDate nmiMeterRegister.uom = uom nmiMeterRegister.intervalLength = intervalLength parsingContext.updateCurrentNmiMeterRegister(nmiMeterRegister) } is Nem12RecordType.Record300 -> { parsingContext.mergeIntervalDayResult() val currNmiMeterRegister = parsingContext.getCurrentNmiMeterRegister() if (currNmiMeterRegister != null) { val intervalDate = parseMandatory("intervalDate", 1, lineNumber, lineItems, { LocalDate.parse(it, DateTimeFormatter.BASIC_ISO_DATE) }) val quality = parseMandatory("intervalQuality", 50, lineNumber, lineItems, { Quality.valueOf(it.substring(0, 1)) }) val qualityMethod = parseOptional("qualityMethod", 50, lineNumber, lineItems, { it?.substring(1, 3) ?: "" }) var interval = 1 val valuesOffset = 2 val valuesCount: Int = (MINUTES_IN_DAY / currNmiMeterRegister.intervalLength.minute) val values = parseMandatory("values", 2, lineNumber, lineItems, { lineItems.subList(valuesOffset, valuesCount + valuesOffset).associateBy({ interval++ }, { BigDecimal(it) }) }) val reasonCode = parseOptional("reasonCode", 51, lineNumber, lineItems, { it }) val reasonDescription = parseOptional("reasonDescription", 52, lineNumber, lineItems, { it }) val updateDateTime = parseOptional("updateDateTime", 53, lineNumber, lineItems, { LocalDateTime.parse(it, DEFAULT_DATE_TIME_FORMATTER) }) val msatsLoadDateTime = parseOptional("msatsLoadDateTime", 54, lineNumber, lineItems, { LocalDateTime.parse(it, DEFAULT_DATE_TIME_FORMATTER) }) val intervalQuality = IntervalQuality(quality, qualityMethod, reasonCode, reasonDescription) val intervalDay = IntervalDay(currNmiMeterRegister, intervalDate, intervalQuality) intervalDay.updateDateTime = updateDateTime intervalDay.msatsLoadDateTime = msatsLoadDateTime intervalDay.mergeNewIntervalValues(values.mapValues { (interval, value) -> IntervalValue( intervalDay, interval, value, IntervalQuality(if (quality == Quality.V) Quality.A else quality)) }, updateDateTime, msatsLoadDateTime ) parsingContext.updateCurrentIntervalDay(intervalDay) } else { throw DomainException("Error, processing record 300 before any associated 200 was processed, line $lineNumber") } } is Nem12RecordType.Record400 -> { val currIntervalDay = parsingContext.getCurrentIntervalDay() if (currIntervalDay != null) { val startInterval = parseMandatory("startInterval", 1, lineNumber, lineItems, { it.toInt() }) val endInterval = parseMandatory("endInterval", 2, lineNumber, lineItems, { it.toInt() }) val quality = parseMandatory("intervalQuality", 3, lineNumber, lineItems, { Quality.valueOf(it.substring(0, 1)) }) val qualityMethod = parseOptional("qualityMethod", 3, lineNumber, lineItems, { it?.substring(1, 3) ?: "" }) val reasonCode = parseOptional("reasonCode", 4, lineNumber, lineItems, { it }) val reasonDescription = parseOptional("reasonDescription", 5, lineNumber, lineItems, { it }) val intervalEvent = IntervalEvent(startInterval..endInterval, IntervalQuality(quality, qualityMethod, reasonCode, reasonDescription)) currIntervalDay.appendIntervalEvent(intervalEvent) } else { throw DomainException("Error, processing record 400 before any associated record 300 was processed, line $lineNumber") } } is Nem12RecordType.Record500 -> { log.info("Ignoring Record Type 500") } is Nem12RecordType.Record900 -> { parsingContext.mergeIntervalDayResult() parsingContext.mergeNmiMeterRegisterResult() } } } catch (de: DomainException) { errorCollector.addError("$de") } catch (e: Exception) { val message = "Unexpected exception thrown, line $lineNumber, $lineItems, $e" log.error(message, e) throw RuntimeException(message, e) } } private fun <R> parseMandatory(propertyName: String, position: Int, lineNumber: Int, lineItems: List<String>, transformer: (str: String) -> R): R { return try { val result = if (lineItems[position].isNotBlank()) transformer(lineItems[position]) else null if (result == null) { throw DomainException("$propertyName is mandatory and cannot be blank") } else { result } } catch (e: Exception) { throw DomainException("Error parsing $propertyName, position $position, line $lineNumber, exception: $e, cause: ${e.cause}") } } private fun <R> parseOptional(propertyName: String, position: Int, lineNumber: Int, lineItems: List<String>, transformer: (str: String?) -> R?): R? { return try { if (lineItems[position].isNotBlank()) transformer(lineItems[position]) else null } catch (e: Exception) { log.debug("Parsing $propertyName, position $position, line $lineNumber, exception: $e, cause: ${e.cause}") null } } } class Nem12ParserImpl(var login: Login) : Nem12Parser, Nem12ParserContext, ErrorCollector { var currRecordType: Nem12RecordType? = null var currNmiMeterRegister: NmiMeterRegister? = null var currIntervalDay: IntervalDay? = null var result: MutableList<NmiMeterRegister> = arrayListOf() var errors: MutableList<String> = arrayListOf() override fun parseNem12Resource(resource: Resource): Collection<NmiMeterRegister> { try { InputStreamReader(resource.inputStream).forEachNem12Line( NEM12_DELIMITER, { it.handleLine(this, this) }, { mergeIntervalDayResult(); mergeNmiMeterRegisterResult() } ) } catch (e: Exception) { errors.add("Error reading file ${resource.filename}: $e") } if (errors.isNotEmpty()) { throw DomainException("${errors.joinToString("\n", "Found following errors when parsing resource [${resource.filename}]:\n", "\n", 100, "...")}") } else { return result } } override fun getCurrentLogin(): Login { return login } override fun getCurrentRecordType(): Nem12RecordType? { return currRecordType } override fun updateCurrentRecordType(recordType: Nem12RecordType) { currRecordType = recordType } override fun getCurrentNmiMeterRegister(): NmiMeterRegister? { return currNmiMeterRegister } override fun updateCurrentNmiMeterRegister(nmiMeterRegister: NmiMeterRegister) { currNmiMeterRegister = nmiMeterRegister } override fun getCurrentIntervalDay(): IntervalDay? { return currIntervalDay } override fun updateCurrentIntervalDay(intervalDay: IntervalDay) { currIntervalDay = intervalDay } override fun mergeNmiMeterRegisterResult() { val currNmiMeterRegister = currNmiMeterRegister if (currNmiMeterRegister != null) { val existingNmiMeterRegister = result.find { it.loginNmi == currNmiMeterRegister.loginNmi && it.meterSerial == currNmiMeterRegister.meterSerial && it.registerId == currNmiMeterRegister.registerId && it.nmiSuffix == currNmiMeterRegister.nmiSuffix } if (existingNmiMeterRegister != null) { existingNmiMeterRegister.mergeIntervalDays(currNmiMeterRegister.intervalDays.values) } else { result.add(currNmiMeterRegister) } this.currNmiMeterRegister = null } } override fun mergeIntervalDayResult() { val currNmiMeterRegister = currNmiMeterRegister val currIntervalDay = currIntervalDay if (currNmiMeterRegister != null && currIntervalDay != null) { currIntervalDay.applyIntervalEvents() currNmiMeterRegister.mergeIntervalDay(currIntervalDay) this.currIntervalDay = null } } override fun addError(error: String) { errors.add(error) } override fun getProcessedResults(): MutableList<NmiMeterRegister> { return result } }
apache-2.0
d2ae8932006cad8cafb290a4cd4bdbd0
47.211356
259
0.64117
4.805975
false
false
false
false
kurtyan/fanfou4j
src/main/java/com/github/kurtyan/fanfou4j/core/AbstractRequest.kt
1
1485
package com.github.kurtyan.fanfou4j.core import com.github.kurtyan.fanfou4j.request.RequestMode import com.github.kurtyan.fanfou4j.util.CapitalizeUtil import java.lang.reflect.ParameterizedType import java.lang.reflect.Type import java.util.* import kotlin.reflect.KProperty /** * Created by yanke on 2016/12/1. */ abstract class AbstractRequest<T>(open val action: String, val httpMethod: HttpMethod) { protected val parameterMap: HashMap<String, Any?> = HashMap<String, Any?>() val longDelegate = RequestParameterDelegate<Long>(parameterMap) val intDelegate = RequestParameterDelegate<Int>(parameterMap) val booleanDelegate = RequestParameterDelegate<Boolean>(parameterMap) val stringDelegate = RequestParameterDelegate<String>(parameterMap) val requestModeDelegate = RequestParameterDelegate<RequestMode>(parameterMap) public fun getResponseType(): Type { val superClass = javaClass.genericSuperclass if (superClass is Class<*>) { // sanity check, should never happen throw IllegalArgumentException("Internal error: TypeReference constructed without actual type information") } return (superClass as ParameterizedType).actualTypeArguments[0] } public open fun getParameter(): Map<String, String> { return parameterMap .filter { it.value != null } .mapKeys { CapitalizeUtil.toUnderScore(it.key) } .mapValues { it.value.toString() } } }
mit
5d4dd606f1d3e229b2e4e595ff988d3f
39.162162
119
0.729293
4.626168
false
false
false
false
cbeust/klaxon
klaxon/src/main/kotlin/com/beust/klaxon/JsonObject.kt
1
2567
package com.beust.klaxon import java.math.BigInteger import java.util.* fun JsonObject(map : Map<String, Any?> = emptyMap()) : JsonObject = JsonObject(LinkedHashMap(map)) data class JsonObject(val map: MutableMap<String, Any?>) : JsonBase, MutableMap<String, Any?> by map { // constructor() : this(mutableMapOf<String, Any?>()) {} override fun appendJsonStringImpl(result: Appendable, prettyPrint: Boolean, canonical: Boolean, level: Int) { fun indent(a: Appendable, level: Int) { for (i in 1..level) { a.append(" ") } } result.append("{") var comma = false for ((k, v) in (if(canonical) map.toSortedMap() else map)) { if (comma) { result.append(",") } else { comma = true } if (prettyPrint && !canonical) { result.appendln() indent(result, level + 1) } // Do not remove k::toString, it allows any data type (that needs to be casted to a string before), without crashing result.append(Render.renderString(k.toString())).append(":") if (prettyPrint && !canonical) { result.append(" ") } Render.renderValue(v, result, prettyPrint, canonical, level + 1) } if (prettyPrint && !canonical && map.isNotEmpty()) { result.appendln() indent(result, level) } result.append("}") } override fun toString() = keys.joinToString(",") @Suppress("UNCHECKED_CAST") fun <T> array(fieldName: String) : JsonArray<T>? = get(fieldName) as JsonArray<T>? fun obj(fieldName: String) : JsonObject? = get(fieldName) as JsonObject? fun int(fieldName: String) : Int? { val value = get(fieldName) return when (value) { is Number -> value.toInt() else -> value as Int? } } fun long(fieldName: String) : Long? { val value = get(fieldName) return when (value) { is Number -> value.toLong() else -> value as Long? } } fun bigInt(fieldName: String) : BigInteger? = get(fieldName) as BigInteger fun string(fieldName: String) : String? = get(fieldName) as String? fun double(fieldName: String) : Double? = get(fieldName) as Double? fun float(fieldName: String) : Float? = (get(fieldName) as Double?)?.toFloat() fun boolean(fieldName: String) : Boolean? = get(fieldName) as Boolean? }
apache-2.0
3999a434a1824d4f608ba89dd30d0aad
30.691358
128
0.562914
4.314286
false
false
false
false
paplorinc/intellij-community
java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/inference/MethodDataExternalizer.kt
6
5907
// 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.codeInspection.dataFlow.inference import com.intellij.codeInsight.Nullability import com.intellij.codeInspection.dataFlow.ContractReturnValue import com.intellij.codeInspection.dataFlow.StandardMethodContract import com.intellij.codeInspection.dataFlow.StandardMethodContract.ValueConstraint import com.intellij.util.io.DataExternalizer import com.intellij.util.io.DataInputOutputUtil.* import java.io.DataInput import java.io.DataOutput import java.util.* /** * @author peter */ internal object MethodDataExternalizer : DataExternalizer<Map<Int, MethodData>> { override fun save(out: DataOutput, value: Map<Int, MethodData>?) { writeSeq(out, value!!.toList()) { writeINT(out, it.first); writeMethod( out, it.second) } } override fun read(input: DataInput) = readSeq(input) { readINT(input) to readMethod( input) }.toMap() private fun writeMethod(out: DataOutput, data: MethodData) { writeNullable(out, data.methodReturn) { writeNullity(out, it) } writeNullable(out, data.purity) { writePurity(out, it) } writeSeq(out, data.contracts) { writeContract(out, it) } writeBitSet(out, data.notNullParameters) writeINT(out, data.bodyStart) writeINT(out, data.bodyEnd) } private fun readMethod(input: DataInput): MethodData { val nullity = readNullable(input) { readNullity(input) } val purity = readNullable(input) { readPurity(input) } val contracts = readSeq(input) { readContract(input) } val notNullParameters = readBitSet(input) return MethodData(nullity, purity, contracts, notNullParameters, readINT(input), readINT(input)) } private fun writeBitSet(out: DataOutput, bitSet: BitSet) { val bytes = bitSet.toByteArray() val size = bytes.size // Write up to 255 bytes, thus up to 2040 bits which is far more than number of allowed Java method parameters assert(size in 0..255) out.writeByte(size) out.write(bytes) } private fun readBitSet(input: DataInput): BitSet { val size = input.readUnsignedByte() val bytes = ByteArray(size) input.readFully(bytes) return BitSet.valueOf(bytes) } private fun writeNullity(out: DataOutput, methodReturn: MethodReturnInferenceResult) = when (methodReturn) { is MethodReturnInferenceResult.Predefined -> { out.writeByte(0); out.writeByte(methodReturn.value.ordinal) } is MethodReturnInferenceResult.FromDelegate -> { out.writeByte(1); out.writeByte(methodReturn.value.ordinal); writeRanges( out, methodReturn.delegateCalls) } else -> throw IllegalArgumentException(methodReturn.toString()) } private fun readNullity(input: DataInput): MethodReturnInferenceResult = when (input.readByte().toInt()) { 0 -> MethodReturnInferenceResult.Predefined( Nullability.values()[input.readByte().toInt()]) else -> MethodReturnInferenceResult.FromDelegate( Nullability.values()[input.readByte().toInt()], readRanges(input)) } private fun writeRanges(out: DataOutput, ranges: List<ExpressionRange>) = writeSeq(out, ranges) { writeRange(out, it) } private fun readRanges(input: DataInput) = readSeq(input) { readRange(input) } private fun writeRange(out: DataOutput, range: ExpressionRange) { writeINT(out, range.startOffset) writeINT(out, range.endOffset) } private fun readRange(input: DataInput) = ExpressionRange(readINT(input), readINT(input)) private fun writePurity(out: DataOutput, purity: PurityInferenceResult) { writeRanges(out, purity.mutatedRefs) writeNullable(out, purity.singleCall) { writeRange(out, it) } } private fun readPurity(input: DataInput) = PurityInferenceResult( readRanges(input), readNullable(input) { readRange(input) }) private fun writeContract(out: DataOutput, contract: PreContract): Unit = when (contract) { is DelegationContract -> { out.writeByte(0); writeRange( out, contract.expression); out.writeBoolean(contract.negated) } is KnownContract -> { out.writeByte(1) writeContractArguments(out, contract.contract.constraints) out.writeByte(contract.contract.returnValue.ordinal()) } is MethodCallContract -> { out.writeByte(2) writeRange(out, contract.call) writeSeq(out, contract.states) { writeContractArguments(out, it) } } is NegatingContract -> { out.writeByte(3); writeContract( out, contract.negated) } is SideEffectFilter -> { out.writeByte(4) writeRanges(out, contract.expressionsToCheck) writeSeq(out, contract.contracts) { writeContract(out, it) } } else -> throw IllegalArgumentException(contract.toString()) } private fun readContract(input: DataInput): PreContract = when (input.readByte().toInt()) { 0 -> DelegationContract( readRange(input), input.readBoolean()) 1 -> KnownContract(StandardMethodContract( readContractArguments(input).toTypedArray(), readReturnValue(input))) 2 -> MethodCallContract( readRange(input), readSeq(input) { readContractArguments(input) }) 3 -> NegatingContract( readContract(input)) else -> SideEffectFilter( readRanges(input), readSeq(input) { readContract(input) }) } private fun writeContractArguments(out: DataOutput, arguments: List<ValueConstraint>) = writeSeq(out, arguments) { out.writeByte(it.ordinal) } private fun readContractArguments(input: DataInput) = readSeq(input, { readValueConstraint(input) }) private fun readValueConstraint(input: DataInput) = ValueConstraint.values()[input.readByte().toInt()] private fun readReturnValue(input: DataInput) = ContractReturnValue.valueOf(input.readByte().toInt()) }
apache-2.0
d436b6b31cc7ac27ab94783410e0bea6
38.912162
140
0.717285
4.365854
false
false
false
false
paplorinc/intellij-community
platform/script-debugger/debugger-ui/src/com/intellij/javascript/debugger/NameMapper.kt
3
6620
// 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.javascript.debugger import com.google.common.base.CharMatcher import com.intellij.openapi.editor.Document import com.intellij.openapi.util.TextRange import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.psi.SyntaxTraverser import gnu.trove.THashMap import org.jetbrains.debugger.sourcemap.MappingEntry import org.jetbrains.debugger.sourcemap.Mappings import org.jetbrains.debugger.sourcemap.MappingsProcessorInLine import org.jetbrains.debugger.sourcemap.SourceMap import org.jetbrains.rpc.LOG import java.util.concurrent.atomic.AtomicInteger private const val S1 = ",()[]{}=" // don't trim trailing .&: - could be part of expression private val OPERATOR_TRIMMER = CharMatcher.invisible().or(CharMatcher.anyOf(S1)) val NAME_TRIMMER: CharMatcher = CharMatcher.invisible().or(CharMatcher.anyOf("$S1.&:")) // generateVirtualFile only for debug purposes open class NameMapper(private val document: Document, private val transpiledDocument: Document, private val sourceMappings: Mappings, protected val sourceMap: SourceMap, private val transpiledFile: VirtualFile? = null) { var rawNameToSource: MutableMap<String, String>? = null private set // PsiNamedElement, JSVariable for example // returns generated name open fun map(identifierOrNamedElement: PsiElement): String? { return doMap(identifierOrNamedElement, false) } protected fun doMap(identifierOrNamedElement: PsiElement, mapBySourceCode: Boolean): String? { val mappings = getMappingsForElement(identifierOrNamedElement) if (mappings == null || mappings.isEmpty()) return null val sourceEntry = mappings[0] val generatedName: String? try { generatedName = extractName(getGeneratedName(identifierOrNamedElement, transpiledDocument, sourceMap, mappings), identifierOrNamedElement) } catch (e: IndexOutOfBoundsException) { LOG.warn("Cannot get generated name: source entry (${sourceEntry.generatedLine}, ${sourceEntry.generatedColumn}). Transpiled File: " + transpiledFile?.path) return null } if (generatedName == null || generatedName.isEmpty()) { return null } var sourceName = sourceEntry.name if (sourceName == null || mapBySourceCode) { sourceName = (identifierOrNamedElement as? PsiNamedElement)?.name ?: identifierOrNamedElement.text ?: sourceName ?: return null } addMapping(generatedName, sourceName) return generatedName } protected open fun getMappingsForElement(element: PsiElement): List<MappingEntry>? { val mappings = mutableListOf<MappingEntry>() val offset = element.textOffset val line = document.getLineNumber(offset) val elementColumn = offset - document.getLineStartOffset(line) val elementEndColumn = elementColumn + element.textLength - 1 val sourceEntryIndex = sourceMappings.indexOf(line, elementColumn) if (sourceEntryIndex == -1) { return null } val sourceEntry = sourceMappings.getByIndex(sourceEntryIndex) val next = sourceMappings.getNextOnTheSameLine(sourceEntryIndex, false) if (next != null && sourceMappings.getColumn(next) == sourceMappings.getColumn(sourceEntry)) { warnSeveralMapping(element) return null } val file = element.containingFile val namedElementsCounter = AtomicInteger(0) val processor = object : MappingsProcessorInLine { override fun process(entry: MappingEntry, nextEntry: MappingEntry?): Boolean { val entryColumn = entry.sourceColumn // next entry column could be equal to prev, see https://code.google.com/p/google-web-toolkit/issues/detail?id=9103 val isSuitable = if (nextEntry == null || (entryColumn == 0 && nextEntry.sourceColumn == 0)) { entryColumn <= elementColumn } else { entryColumn in elementColumn..elementEndColumn } if (isSuitable) { val startOffset = document.getLineStartOffset(line) + entryColumn val endOffset = if (nextEntry != null) document.getLineStartOffset(line) + nextEntry.sourceColumn else document.getLineEndOffset(line) if (collectNamedElementsInRange(TextRange(startOffset, endOffset))) { return false } mappings.add(entry) } return true } private fun collectNamedElementsInRange(range: TextRange): Boolean { return SyntaxTraverser.psiTraverser(file) .onRange(range) .filter { it is PsiNamedElement && range.contains(it.textRange) && namedElementsCounter.incrementAndGet() > 1 } .traverse() .isNotEmpty } } if (!sourceMap.processSourceMappingsInLine(sourceEntry.source, sourceEntry.sourceLine, processor)) { return null } return mappings } fun addMapping(generatedName: String, sourceName: String) { if (rawNameToSource == null) { rawNameToSource = THashMap<String, String>() } rawNameToSource!!.put(generatedName, sourceName) } protected open fun extractName(rawGeneratedName: CharSequence?, context: PsiElement? = null):String? = rawGeneratedName?.let { NAME_TRIMMER.trimFrom(it) } companion object { fun trimName(rawGeneratedName: CharSequence, isLastToken: Boolean): String? = (if (isLastToken) NAME_TRIMMER else OPERATOR_TRIMMER).trimFrom(rawGeneratedName) } protected open fun getGeneratedName(element: PsiElement, document: Document, sourceMap: SourceMap, mappings: List<MappingEntry>): CharSequence? { val sourceEntry = mappings[0] val lineStartOffset = document.getLineStartOffset(sourceEntry.generatedLine) val nextGeneratedMapping = sourceMap.generatedMappings.getNextOnTheSameLine(sourceEntry) val endOffset: Int if (nextGeneratedMapping == null) { endOffset = document.getLineEndOffset(sourceEntry.generatedLine) } else { endOffset = lineStartOffset + nextGeneratedMapping.generatedColumn } return document.immutableCharSequence.subSequence(lineStartOffset + sourceEntry.generatedColumn, endOffset) } } fun warnSeveralMapping(element: PsiElement) { // see https://dl.dropboxusercontent.com/u/43511007/s/Screen%20Shot%202015-01-21%20at%2020.33.44.png // var1 mapped to the whole "var c, notes, templates, ..." expression text + unrelated text " ;" LOG.warn("incorrect sourcemap, several mappings for named element ${element.text}") }
apache-2.0
07117313fa991e3b17e5263a7c42c39e
41.165605
220
0.731873
4.549828
false
false
false
false
miguelfs/desafio-mobile
app/src/main/java/com/partiufast/mercadodoimperador/model/Store.kt
1
1089
package com.partiufast.mercadodoimperador.model import java.util.* class Store { private val cartProducts: ArrayList<Product> = ArrayList<Product>() private val availableProducts: ArrayList<Product> = ArrayList<Product>() fun setAvailableProducts(products: ArrayList<Product>) { availableProducts.addAll(products) } fun addProductToCart(product: Product) { if (cartProducts.size == 0) cartProducts.add(product) else { if (getProductIndexIfContains(product) == -1) cartProducts.add(product) } } private fun getProductIndexIfContains(product: Product): Int { for (i in cartProducts.indices) { if (cartProducts[i].title == (product.title)) { cartProducts[i].productCount = product.productCount return i } } return -1 } fun getAvailableProducts(): ArrayList<Product> { return availableProducts } fun getCartProducts(): ArrayList<Product> { return cartProducts } }
mit
4313b4390745a47942fe5fb5b5acfe40
23.2
76
0.618916
4.481481
false
false
false
false
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/platform/mixin/reference/target/TargetReference.kt
1
9383
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.reference.target import com.demonwav.mcdev.platform.mixin.reference.MethodReference import com.demonwav.mcdev.platform.mixin.reference.MixinReference import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.AT import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.SLICE import com.demonwav.mcdev.platform.mixin.util.MixinMemberReference import com.demonwav.mcdev.platform.mixin.util.findSource import com.demonwav.mcdev.util.annotationFromArrayValue import com.demonwav.mcdev.util.annotationFromValue import com.demonwav.mcdev.util.constantStringValue import com.demonwav.mcdev.util.equivalentTo import com.demonwav.mcdev.util.getQualifiedMemberReference import com.demonwav.mcdev.util.internalName import com.demonwav.mcdev.util.mapToArray import com.demonwav.mcdev.util.notNullToArray import com.demonwav.mcdev.util.reference.PolyReferenceResolver import com.demonwav.mcdev.util.reference.completeToLiteral import com.demonwav.mcdev.util.shortName import com.intellij.codeInsight.completion.JavaLookupElementBuilder import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.psi.JavaRecursiveElementWalkingVisitor import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiClass import com.intellij.psi.PsiClassType import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementResolveResult import com.intellij.psi.PsiExpression import com.intellij.psi.PsiMember import com.intellij.psi.PsiMethod import com.intellij.psi.PsiQualifiedReference import com.intellij.psi.PsiReference import com.intellij.psi.PsiSubstitutor import com.intellij.psi.PsiThisExpression import com.intellij.psi.ResolveResult import com.intellij.psi.util.parentOfType import com.intellij.util.ArrayUtil object TargetReference : PolyReferenceResolver(), MixinReference { override val description: String get() = "target reference '%s'" override fun isValidAnnotation(name: String) = name == AT private fun getHandler(at: PsiAnnotation): Handler<*>? { val injectionPointType = at.findDeclaredAttributeValue("value")?.constantStringValue ?: return null return when (injectionPointType) { "INVOKE", "INVOKE_ASSIGN" -> MethodTargetReference "INVOKE_STRING" -> ConstantStringMethodTargetReference "FIELD" -> FieldTargetReference "NEW" -> ConstructorTargetReference else -> null // Unsupported injection point type } } fun usesMemberReference(context: PsiElement): Boolean { val handler = getHandler(context.annotationFromArrayValue!!) ?: return false return handler.usesMemberReference() } fun resolveTarget(context: PsiElement): PsiElement? { val handler = getHandler(context.annotationFromValue ?: return null) ?: return null return handler.resolveTarget(context) } private fun getTargetMethod(at: PsiAnnotation): PsiMethod? { // TODO: Right now this will only work for Mixins with a single target class val parentAnnotation = at.annotationFromArrayValue ?: return null val injectorAnnotation = if (parentAnnotation.qualifiedName == SLICE) { parentAnnotation.annotationFromValue ?: return null } else { parentAnnotation } val methodValue = injectorAnnotation.findDeclaredAttributeValue("method") ?: return null return MethodReference.resolveIfUnique(methodValue)?.findSource() } override fun isUnresolved(context: PsiElement): Boolean { val result = resolve(context, checkOnly = true) ?: return false return result.isEmpty() } override fun resolveReference(context: PsiElement): Array<ResolveResult> { val result = resolve(context, checkOnly = false) ?: return ResolveResult.EMPTY_ARRAY return result.mapToArray(::PsiElementResolveResult) } private fun resolve(context: PsiElement, checkOnly: Boolean): List<PsiElement>? { val at = context.parentOfType<PsiAnnotation>() ?: return null // @At val handler = getHandler(at) ?: return null val targetMethod = getTargetMethod(at) ?: return null val codeBlock = targetMethod.body ?: return null val visitor = handler.createFindUsagesVisitor(context, targetMethod.containingClass!!, checkOnly) ?: return null codeBlock.accept(visitor) return visitor.result } override fun collectVariants(context: PsiElement): Array<Any> { val at = context.annotationFromValue ?: return ArrayUtil.EMPTY_OBJECT_ARRAY // @At val handler = getHandler(at) ?: return ArrayUtil.EMPTY_OBJECT_ARRAY val targetMethod = getTargetMethod(at) ?: return ArrayUtil.EMPTY_OBJECT_ARRAY val codeBlock = targetMethod.body ?: return ArrayUtil.EMPTY_OBJECT_ARRAY val containingClass = targetMethod.containingClass ?: return ArrayUtil.EMPTY_OBJECT_ARRAY return collectUsages(context, handler, codeBlock, containingClass) } private fun <T> collectUsages( context: PsiElement, handler: Handler<T>, codeBlock: PsiElement, targetClass: PsiClass ): Array<Any> { // Collect all possible targets val visitor = handler.createCollectUsagesVisitor() codeBlock.accept(visitor) return visitor.result.asSequence() .map { handler.createLookup(targetClass, it)?.completeToLiteral(context) } .notNullToArray() } abstract class Handler<T> { open fun usesMemberReference() = false abstract fun resolveTarget(context: PsiElement): PsiElement? abstract fun createFindUsagesVisitor( context: PsiElement, targetClass: PsiClass, checkOnly: Boolean ): CollectVisitor<out PsiElement>? abstract fun createCollectUsagesVisitor(): CollectVisitor<T> abstract fun createLookup(targetClass: PsiClass, element: T): LookupElementBuilder? } abstract class QualifiedHandler<T : PsiMember> : Handler<QualifiedMember<T>>() { final override fun usesMemberReference() = true protected abstract fun createLookup(targetClass: PsiClass, m: T, owner: PsiClass): LookupElementBuilder override fun resolveTarget(context: PsiElement): PsiElement? { val value = context.constantStringValue ?: return null val ref = MixinMemberReference.parse(value) ref?.owner ?: return null return ref.resolveMember(context.project, context.resolveScope) } protected open fun getInternalName(m: QualifiedMember<T>): String { return m.member.name!! } final override fun createLookup(targetClass: PsiClass, element: QualifiedMember<T>): LookupElementBuilder? { return qualifyLookup( createLookup(targetClass, element.member, element.qualifier ?: targetClass), targetClass, element ) } private fun qualifyLookup( builder: LookupElementBuilder, targetClass: PsiClass, m: QualifiedMember<T> ): LookupElementBuilder { val owner = m.member.containingClass!! return if (targetClass equivalentTo owner) { builder } else { // Qualify member with name of owning class builder.withPresentableText(owner.shortName + '.' + getInternalName(m)) } } } abstract class MethodHandler : QualifiedHandler<PsiMethod>() { override fun createLookup(targetClass: PsiClass, m: PsiMethod, owner: PsiClass): LookupElementBuilder { return JavaLookupElementBuilder.forMethod( m, MixinMemberReference.toString(m.getQualifiedMemberReference(owner)), PsiSubstitutor.EMPTY, targetClass ) .withPresentableText(m.internalName) // Display internal name (e.g. <init> for constructors) .withLookupString(m.internalName) // Allow looking up targets by their method name } override fun getInternalName(m: QualifiedMember<PsiMethod>): String { return m.member.internalName } } } data class QualifiedMember<T : PsiMember>(val member: T, val qualifier: PsiClass?) { constructor(member: T, reference: PsiQualifiedReference) : this(member, resolveQualifier(reference)) companion object { fun resolveQualifier(reference: PsiQualifiedReference): PsiClass? { val qualifier = reference.qualifier ?: return null if (qualifier is PsiThisExpression) { return null } ((qualifier as? PsiReference)?.resolve() as? PsiClass)?.let { return it } ((qualifier as? PsiExpression)?.type as? PsiClassType)?.resolve()?.let { return it } return null } } } abstract class CollectVisitor<T>(private val checkOnly: Boolean) : JavaRecursiveElementWalkingVisitor() { val result = ArrayList<T>() protected fun addResult(element: T) { this.result.add(element) if (checkOnly) { stopWalking() } } }
mit
89c1e3c80e2dba7420227b0cd6e12901
38.095833
120
0.696366
5.085637
false
false
false
false
Zeyad-37/RxRedux
core/src/main/java/com/zeyad/rxredux/core/vm/viewmodel/PModel.kt
1
1880
package com.zeyad.rxredux.core.vm.viewmodel import com.zeyad.rxredux.core.vm.rxvm.Input import com.zeyad.rxredux.core.vm.rxvm.State sealed class PModel<S, I> { abstract val input: I? override fun toString() = "Input: $input" } sealed class PState<S, I> : PModel<S, I>() { abstract val bundle: S } sealed class PEffect<E, I> : PModel<E, I>() { abstract val bundle: E? } internal data class LoadingEffect<E, I>(override val bundle: E, override val input: I) : PEffect<E, I>() { override fun toString() = "Effect: Loading, " + super.toString() } internal data class ErrorEffect<E, I>(val error: Throwable, val errorMessage: String, override val bundle: E?, override val input: I? = null) : PEffect<E, I>() { override fun toString() = "Effect: Error, ${super.toString()}, Throwable: $error" } internal data class SuccessEffect<E, I>(override val bundle: E, override val input: I) : PEffect<E, I>() { override fun toString() = "Effect: Success, ${super.toString()}, Bundle: $bundle" } internal object InitialSuccessEffect : PEffect<Unit?, Any?>() { override val bundle: Unit = Unit override val input: Any? = null } internal data class EmptySuccessEffect<E, I>(override val input: I? = null, override val bundle: E? = null) : PEffect<E, I>() data class SuccessState<S, I>(override val bundle: S, override val input: I?) : PState<S, I>() { override fun toString() = "State: Success, ${super.toString()}, Bundle: $bundle" } internal object EmptySuccessState : PState<State?, Input?>() { override val input: Input? = null override val bundle: State? = null }
apache-2.0
a65c6e690a6da46be5a631e654b78ec8
34.471698
94
0.583511
3.884298
false
false
false
false
google/intellij-community
platform/lang-impl/src/com/intellij/ide/bookmark/actions/NodeDeleteAction.kt
3
3787
// 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.CommonBundle.messagePointer import com.intellij.ide.bookmark.BookmarkBundle import com.intellij.ide.bookmark.BookmarkGroup import com.intellij.ide.bookmark.BookmarksListProviderService import com.intellij.ide.bookmark.FileBookmark import com.intellij.ide.bookmark.ui.tree.FileNode import com.intellij.ide.bookmark.ui.tree.GroupNode import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.DoNotAskOption import com.intellij.openapi.ui.MessageDialogBuilder internal class NodeDeleteAction : DumbAwareAction(messagePointer("button.delete")) { override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT override fun update(event: AnActionEvent) { event.presentation.isEnabledAndVisible = false val project = event.project ?: return val nodes = event.bookmarkNodes ?: return val provider = BookmarksListProviderService.findProvider(project) { it.canDelete(nodes) } ?: return provider.deleteActionText?.let { event.presentation.text = it } event.presentation.isEnabledAndVisible = true } override fun actionPerformed(event: AnActionEvent) { val project = event.project ?: return val view = event.bookmarksView ?: return val nodes = event.bookmarkNodes ?: return val bookmarksViewState = event.bookmarksViewState val shouldDelete = when { bookmarksViewState == null -> true nodes.any { it is GroupNode || it is FileNode } -> { if (!bookmarksViewState.askBeforeDeletingLists || nodes.size == 1 && nodes.first().children.size <= 1) true else { val fileNode = nodes.any { it is FileNode } val title = when { fileNode && nodes.size == 1 -> BookmarkBundle.message("dialog.message.delete.single.node.title") fileNode -> BookmarkBundle.message("dialog.message.delete.multiple.nodes.title") nodes.size == 1 -> BookmarkBundle.message("dialog.message.delete.single.list.title") else -> BookmarkBundle.message("dialog.message.delete.multiple.lists.title") } val message = when { fileNode && nodes.size == 1 -> BookmarkBundle.message("dialog.message.delete.single.node", nodes.first().children.size, (nodes.first().value as FileBookmark).file.name) fileNode -> BookmarkBundle.message("dialog.message.delete.multiple.nodes") nodes.size == 1 -> BookmarkBundle.message("dialog.message.delete.single.list", (nodes.first { it is GroupNode }.value as BookmarkGroup).name) else -> BookmarkBundle.message("dialog.message.delete.multiple.lists") } MessageDialogBuilder .yesNo(title, message) .yesText(BookmarkBundle.message("dialog.message.delete.button")) .noText(BookmarkBundle.message("dialog.message.cancel.button")) .doNotAsk(object : DoNotAskOption.Adapter() { override fun rememberChoice(isSelected: Boolean, exitCode: Int) { bookmarksViewState.askBeforeDeletingLists = !isSelected } }) .asWarning() .ask(project) } } else -> true } if (shouldDelete) { BookmarksListProviderService.findProvider(project) { it.canDelete(nodes) }?.performDelete(nodes, view.tree) } } init { isEnabledInModalContext = true } }
apache-2.0
f0400b4f99cd78f26f5d2a9c6c1be4c4
46.936709
153
0.679694
4.757538
false
false
false
false
google/intellij-community
uast/uast-common/src/org/jetbrains/uast/baseElements/UElement.kt
11
5021
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast import com.intellij.lang.Language import com.intellij.psi.PsiElement import org.jetbrains.uast.visitor.UastTypedVisitor import org.jetbrains.uast.visitor.UastVisitor @JvmField val EMPTY_ARRAY: Array<UElement> = emptyArray() /** * The common interface for all Uast elements. */ interface UElement { /** * Returns the element parent. */ val uastParent: UElement? /** * Returns the PSI element underlying this element. Note that some UElements are synthetic and do not have * an underlying PSI element; this doesn't mean that they are invalid. * * **Node for implementors**: please implement both [sourcePsi] and [javaPsi] fields or make them return `null` explicitly * if implementing is not possible. Redirect `psi` to one of them keeping existing behavior, use [sourcePsi] if nothing else is specified. */ @Deprecated("ambiguous psi element, use `sourcePsi` or `javaPsi`", ReplaceWith("javaPsi")) val psi: PsiElement? /** * Returns the PSI element in original (physical) tree to which this UElement corresponds. * **Note**: that some UElements are synthetic and do not have an underlying PSI element; * this doesn't mean that they are invalid. */ @Suppress("DEPRECATION") val sourcePsi: PsiElement? get() = psi /** * Returns the element which try to mimic Java-api psi element: [com.intellij.psi.PsiClass], [com.intellij.psi.PsiMethod] or [com.intellij.psi.PsiAnnotation] etc. * Will return null if this UElement doesn't have Java representation or it is not implemented. */ @Suppress("DEPRECATION") val javaPsi: PsiElement? get() = psi /** * Returns true if this element is valid, false otherwise. */ val isPsiValid: Boolean get() = sourcePsi?.isValid ?: true /** * Returns the list of comments for this element. */ val comments: List<UComment> get() = emptyList() /** * Returns the log string (usually one line containing the class name and some additional information). * * Examples: * UWhileExpression * UBinaryExpression (>) * UCallExpression (println) * USimpleReferenceExpression (i) * ULiteralExpression (5) * * @return the expression tree for this element. * @see [UIfExpression] for example. */ fun asLogString(): String /** * Returns the string in pseudo-code. * * Output example (should be something like this): * while (i > 5) { * println("Hello, world") * i-- * } * * @return the rendered text. * @see [UIfExpression] for example. */ fun asRenderString(): String = asLogString() /** * Returns the string as written in the source file. * Use this String only for logging and diagnostic text messages. * * @return the original text. */ fun asSourceString(): String = asRenderString() /** * Passes the element to the specified visitor. * * @param visitor the visitor to pass the element to. */ fun accept(visitor: UastVisitor) { visitor.visitElement(this) visitor.afterVisitElement(this) } /** * Passes the element to the specified typed visitor. * * @param visitor the visitor to pass the element to. */ fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D): R = visitor.visitElement(this, data) /** * NOTE: it is called `lang` instead of "language" to avoid clash with [PsiElement.getLanguage] in classes which implements both interfaces, * @return language of the physical [PsiElement] this [UElement] was made from, or `UAST` language if no "physical" language could be found */ @JvmDefault val lang: Language get() = withContainingElements.mapNotNull { it.sourcePsi }.firstOrNull()?.language // ok. another try ?: withContainingElements.mapNotNull { it.getContainingUFile()?.sourcePsi?.language }.firstOrNull() // UAST in the end, hope it will never happen ?: Language.findLanguageByID("UAST")!! } val UElement?.sourcePsiElement: PsiElement? get() = this?.sourcePsi @Suppress("UNCHECKED_CAST") fun <T : PsiElement> UElement?.getAsJavaPsiElement(clazz: Class<T>): T? = this?.javaPsi?.takeIf { clazz.isAssignableFrom(it.javaClass) } as? T /** * Returns a sequence including this element and its containing elements. */ val UElement.withContainingElements: Sequence<UElement> get() = generateSequence(this, UElement::uastParent)
apache-2.0
79a8742044475e8ff0bf876f4db2bd05
31.603896
164
0.696076
4.28413
false
false
false
false
vhromada/Catalog
web/src/test/kotlin/com/github/vhromada/catalog/web/utils/EpisodeUtils.kt
1
2419
package com.github.vhromada.catalog.web.utils import com.github.vhromada.catalog.web.connector.entity.ChangeEpisodeRequest import com.github.vhromada.catalog.web.connector.entity.Episode import com.github.vhromada.catalog.web.fo.EpisodeFO import org.assertj.core.api.SoftAssertions.assertSoftly /** * A class represents utility class for episodes. * * @author Vladimir Hromada */ object EpisodeUtils { /** * Returns FO for episode. * * @return FO for episode */ fun getEpisodeFO(): EpisodeFO { return EpisodeFO( uuid = TestConstants.UUID, number = TestConstants.NUMBER.toString(), name = TestConstants.NAME, length = TimeUtils.getTimeFO(), note = TestConstants.NOTE ) } /** * Returns episode. * * @return episode */ fun getEpisode(): Episode { return Episode( uuid = TestConstants.UUID, number = TestConstants.NUMBER, name = TestConstants.NAME, length = TestConstants.LENGTH, formattedLength = TestConstants.FORMATTED_LENGTH, note = TestConstants.NOTE ) } /** * Asserts episode deep equals. * * @param expected expected episode * @param actual actual FO for episode */ fun assertEpisodeDeepEquals(expected: Episode, actual: EpisodeFO) { assertSoftly { it.assertThat(actual.uuid).isEqualTo(expected.uuid) it.assertThat(actual.number).isEqualTo(expected.number.toString()) it.assertThat(actual.name).isEqualTo(expected.name) it.assertThat(actual.note).isEqualTo(expected.note) } TimeUtils.assertTimeDeepEquals(expected = expected.length, actual = actual.length) } /** * Asserts FO for episode and request deep equals. * * @param expected expected FO for episode * @param actual actual request for changing episode */ fun assertRequestDeepEquals(expected: EpisodeFO, actual: ChangeEpisodeRequest) { assertSoftly { it.assertThat(actual.number).isEqualTo(expected.number!!.toInt()) it.assertThat(actual.name).isEqualTo(expected.name) it.assertThat(actual.note).isEqualTo(expected.note) } TimeUtils.assertTimeDeepEquals(expected = expected.length, actual = actual.length) } }
mit
b6bd05c629fffb436ffebae53cfa7daa
30.415584
90
0.640347
4.651923
false
true
false
false
vanniktech/RxBinding
rxbinding-appcompat-v7-kotlin/src/main/kotlin/com/jakewharton/rxbinding2/support/v7/widget/RxToolbar.kt
1
2653
@file:Suppress("NOTHING_TO_INLINE") package com.jakewharton.rxbinding2.support.v7.widget import android.support.annotation.CheckResult import android.support.v7.widget.Toolbar import android.view.MenuItem import com.jakewharton.rxbinding2.internal.VoidToUnit import io.reactivex.Observable import io.reactivex.functions.Consumer import kotlin.Deprecated import kotlin.Int import kotlin.Suppress import kotlin.Unit /** * Create an observable which emits the clicked item in `view`'s menu. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ @CheckResult inline fun Toolbar.itemClicks(): Observable<MenuItem> = RxToolbar.itemClicks(this) /** * Create an observable which emits on `view` navigation click events. The emitted value is * unspecified and should only be used as notification. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [Toolbar.setNavigationOnClickListener] * to observe clicks. Only one observable can be used for a view at a time. */ @CheckResult inline fun Toolbar.navigationClicks(): Observable<Unit> = RxToolbar.navigationClicks(this).map(VoidToUnit) /** * An action which sets the title property of `view` with character sequences. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ @Deprecated("Use view::setTitle method reference.") @CheckResult inline fun Toolbar.title(): Consumer<in CharSequence?> = RxToolbar.title(this) /** * An action which sets the title property of `view` string resource IDs. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ @Deprecated("Use view::setTitle method reference.") @CheckResult inline fun Toolbar.titleRes(): Consumer<in Int> = RxToolbar.titleRes(this) /** * An action which sets the subtitle property of `view` with character sequences. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ @Deprecated("Use view::setSubtitle method reference.") @CheckResult inline fun Toolbar.subtitle(): Consumer<in CharSequence?> = RxToolbar.subtitle(this) /** * An action which sets the subtitle property of `view` string resource IDs. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ @Deprecated("Use view::setSubtitle method reference.") @CheckResult inline fun Toolbar.subtitleRes(): Consumer<in Int> = RxToolbar.subtitleRes(this)
apache-2.0
38a4ea069c258e0847ef28afab86dd82
33.907895
106
0.764418
4.2448
false
false
false
false
StephaneBg/ScoreIt
data/src/main/kotlin/com/sbgapps/scoreit/data/solver/CoincheSolver.kt
1
4313
/* * 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.data.solver import com.sbgapps.scoreit.data.model.BeloteBonus import com.sbgapps.scoreit.data.model.BeloteBonusValue import com.sbgapps.scoreit.data.model.CoincheLap import com.sbgapps.scoreit.data.model.PlayerPosition import com.sbgapps.scoreit.data.solver.CoincheSolver.Companion.POINTS_CAPOT import com.sbgapps.scoreit.data.solver.CoincheSolver.Companion.POINTS_TOTAL import com.sbgapps.scoreit.data.source.DataStore class CoincheSolver(private val dataStore: DataStore) { fun getResults(lap: CoincheLap): Pair<List<Int>, Boolean> { val takerIndex = lap.taker.index val counterIndex = lap.counter().index val (results, isWon) = computeResults(lap) if (isWon) { results[takerIndex] += lap.bid results[takerIndex] *= lap.coinche.coefficient } else { results[takerIndex] = 0 results[counterIndex] = POINTS_TOTAL + lap.bid results[counterIndex] *= lap.coinche.coefficient addBonuses(results, lap.bonuses, true) } return results.toList() to isWon } fun getDisplayResults(lap: CoincheLap): Pair<List<String>, Boolean> { val (results, isWon) = getResults(lap) return results.toList().mapIndexed { index, points -> listOfNotNull( getPointsForDisplay(points).toString(), "♛".takeIf { lap.bonuses.find { it.bonus == BeloteBonusValue.BELOTE && it.player.index == index } != null }, "★".takeIf { lap.bonuses.find { it.bonus != BeloteBonusValue.BELOTE && it.player.index == index } != null } ).joinToString(" ") } to isWon } private fun computeResults(lap: CoincheLap): Pair<IntArray, Boolean> { val takerIndex = lap.taker.index val counterIndex = lap.counter().index val results = IntArray(2) if (POINTS_TOTAL == lap.points) { results[takerIndex] = POINTS_CAPOT results[counterIndex] = 0 } else { results[takerIndex] = lap.points results[counterIndex] = lap.counterPoints() } addBonuses(results, lap.bonuses) val isWon = results[takerIndex] >= lap.bid && results[takerIndex] > results[counterIndex] return results to isWon } private fun addBonuses(results: IntArray, bonuses: List<BeloteBonus>, toCounter: Boolean = false) { if (toCounter) { for ((player, bonus) in bonuses) { if (bonus == BeloteBonusValue.BELOTE) results[player.index] += bonus.points else results[player.counter().index] += bonus.points } } else { for ((player, bonus) in bonuses) results[player.index] += bonus.points } } fun computeScores(laps: List<CoincheLap>): List<Int> { val scores = MutableList(2) { 0 } laps.map { getResults(it).first }.forEach { points -> for (player in 0 until 2) scores[player] += points[player] } return scores.map { getPointsForDisplay(it) } } private fun getPointsForDisplay(points: Int): Int = if (dataStore.isCoincheScoreRounded()) roundPoint(points) else points private fun roundPoint(score: Int): Int = when (score) { POINTS_TOTAL -> 160 POINTS_CAPOT -> 250 else -> (score + 5) / 10 * 10 } companion object { const val POINTS_TOTAL = 162 const val POINTS_CAPOT = 252 const val BID_MIN = 80 const val BID_MAX = 650 } } fun CoincheLap.counterPoints(): Int = if (points == POINTS_CAPOT) 0 else POINTS_TOTAL - points fun CoincheLap.counter(): PlayerPosition = taker.counter()
apache-2.0
0e2a2ed26eed5dbfd6ff263d9a9189b7
38.163636
124
0.643686
3.891599
false
false
false
false
youdonghai/intellij-community
platform/platform-impl/src/com/intellij/openapi/keymap/impl/DefaultKeymap.kt
1
4734
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.keymap.impl import com.intellij.configurationStore.SchemeDataHolder import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.catchAndLog import com.intellij.openapi.extensions.Extensions import com.intellij.openapi.keymap.Keymap import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtilRt import gnu.trove.THashMap import org.jdom.Element import java.net.URL import java.util.* private val LOG = Logger.getInstance("#com.intellij.openapi.keymap.impl.DefaultKeymap") open class DefaultKeymap { private val myKeymaps = ArrayList<Keymap>() private val nameToScheme = THashMap<String, Keymap>() protected open val providers: Array<BundledKeymapProvider> get() = Extensions.getExtensions(BundledKeymapProvider.EP_NAME) init { for (provider in providers) { for (fileName in provider.keymapFileNames) { // backward compatibility (no external usages of BundledKeymapProvider, but maybe it is not published to plugin manager) val key = when (fileName) { "Keymap_Default.xml" -> "\$default.xml" "Keymap_Mac.xml" -> "Mac OS X 10.5+.xml" "Keymap_MacClassic.xml" -> "Mac OS X.xml" "Keymap_GNOME.xml" -> "Default for GNOME.xml" "Keymap_KDE.xml" -> "Default for KDE.xml" "Keymap_XWin.xml" -> "Default for XWin.xml" "Keymap_EclipseMac.xml" -> "Eclipse (Mac OS X).xml" "Keymap_Eclipse.xml" -> "Eclipse.xml" "Keymap_Emacs.xml" -> "Emacs.xml" "JBuilderKeymap.xml" -> "JBuilder.xml" "Keymap_Netbeans.xml" -> "NetBeans 6.5.xml" "Keymap_ReSharper_OSX.xml" -> "ReSharper OSX.xml" "Keymap_ReSharper.xml" -> "ReSharper.xml" "RM_TextMateKeymap.xml" -> "TextMate.xml" "Keymap_Xcode.xml" -> "Xcode.xml" else -> fileName } LOG.catchAndLog { loadKeymapsFromElement(object: SchemeDataHolder<KeymapImpl> { override fun read() = JDOMUtil.loadResourceDocument(URL("file:///keymaps/$key")).rootElement override fun updateDigest(scheme: KeymapImpl) { } override fun updateDigest(data: Element) { } }, FileUtilRt.getNameWithoutExtension(key)) } } } } companion object { @JvmStatic val instance: DefaultKeymap get() = ServiceManager.getService(DefaultKeymap::class.java) @JvmStatic fun matchesPlatform(keymap: Keymap): Boolean { val name = keymap.name return when (name) { KeymapManager.DEFAULT_IDEA_KEYMAP -> SystemInfo.isWindows KeymapManager.MAC_OS_X_KEYMAP, KeymapManager.MAC_OS_X_10_5_PLUS_KEYMAP -> SystemInfo.isMac KeymapManager.X_WINDOW_KEYMAP, "Default for GNOME", KeymapManager.KDE_KEYMAP -> SystemInfo.isXWindow else -> true } } } private fun loadKeymapsFromElement(dataHolder: SchemeDataHolder<KeymapImpl>, keymapName: String) { val keymap = if (keymapName.startsWith(KeymapManager.MAC_OS_X_KEYMAP)) MacOSDefaultKeymap(dataHolder, this) else DefaultKeymapImpl(dataHolder, this) keymap.name = keymapName myKeymaps.add(keymap) nameToScheme.put(keymapName, keymap) } val keymaps: Array<Keymap> get() = myKeymaps.toTypedArray() internal fun findScheme(name: String) = nameToScheme.get(name) open val defaultKeymapName: String get() = when { SystemInfo.isMac -> KeymapManager.MAC_OS_X_KEYMAP SystemInfo.isXWindow -> if (SystemInfo.isKDE) KeymapManager.KDE_KEYMAP else KeymapManager.X_WINDOW_KEYMAP else -> KeymapManager.DEFAULT_IDEA_KEYMAP } open fun getKeymapPresentableName(keymap: KeymapImpl): String { val name = keymap.name // Netbeans keymap is no longer for version 6.5, but we need to keep the id if (name == "NetBeans 6.5") { return "NetBeans" } return if (KeymapManager.DEFAULT_IDEA_KEYMAP == name) "Default" else name } }
apache-2.0
b0f5149ee8c81be2941fb5b11681763a
36.275591
152
0.69286
4.098701
false
false
false
false
allotria/intellij-community
plugins/ide-features-trainer/src/training/ui/StepAnimator.kt
2
2031
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package training.ui import com.intellij.util.ui.Animator import javax.swing.JScrollBar internal class StepAnimator(val verticalScrollBar: JScrollBar, val messagePane: LessonMessagePane) { private var animator: Animator? = null private val totalMessageAnimationCycles = 15 fun startAnimation(needScroll: Int) { animator?.let { it.suspend() stopMessageAnimation() } messagePane.totalAnimation = totalMessageAnimationCycles messagePane.currentAnimation = 0 scrollAnimation(needScroll) } private fun scrollAnimation(needScrollTo: Int) { val start = verticalScrollBar.value if (needScrollTo <= start) { rectangleAnimation() verticalScrollBar.value = needScrollTo return } val needAdd = needScrollTo - start animator = object : Animator("Scroll animation", needAdd, 5 * needAdd, false) { override fun paintNow(frame: Int, totalFrames: Int, cycle: Int) { verticalScrollBar.value = start + frame } override fun paintCycleEnd() { if (this == animator) { verticalScrollBar.value = needScrollTo animator = null rectangleAnimation() } } } animator?.resume() } private fun rectangleAnimation() { animator = object : Animator("Scroll animation", totalMessageAnimationCycles, 100, false) { override fun paintNow(frame: Int, totalFrames: Int, cycle: Int) { messagePane.totalAnimation = totalFrames messagePane.currentAnimation = frame messagePane.repaint() } override fun paintCycleEnd() { if (this == animator) { stopMessageAnimation() messagePane.repaint() animator = null } } } animator?.resume() } private fun stopMessageAnimation() { messagePane.totalAnimation = 0 messagePane.currentAnimation = 0 } }
apache-2.0
18277e309811e1c0ea76c0b2426fe062
28.028571
140
0.670113
4.574324
false
false
false
false
ursjoss/sipamato
core/core-web/src/main/java/ch/difty/scipamato/core/web/behavior/AjaxDownload.kt
2
2158
package ch.difty.scipamato.core.web.behavior import org.apache.wicket.ajax.AjaxRequestTarget import org.apache.wicket.behavior.AbstractAjaxBehavior import org.apache.wicket.request.handler.resource.ResourceStreamRequestHandler import org.apache.wicket.request.resource.ContentDisposition import org.apache.wicket.util.resource.IResourceStream import org.apache.wicket.util.resource.StringResourceStream /** * @author Sven Meier * @author Ernesto Reinaldo Barreiro ([email protected]) * @author Jordi Deu-Pons ([email protected]) */ @Suppress("SpellCheckingInspection") sealed class AjaxDownload(private val addAntiCache: Boolean) : AbstractAjaxBehavior() { var fileName: String? = null /** * Hook method providing the actual resource stream. */ protected abstract val resourceStream: IResourceStream /** * Call this method to initiate the download. * The timeout is needed to let Wicket release the channel */ fun initiate(target: AjaxRequestTarget) { target.appendJavaScript( """setTimeout("window.location.href='${callbackUrl.toUrl(addAntiCache)}'", 100);""" ) } override fun onRequest() { val handler = ResourceStreamRequestHandler(resourceStream, fileName) handler.contentDisposition = ContentDisposition.ATTACHMENT component.requestCycle.scheduleRequestHandlerAfterCurrent(handler) } } open class AjaxTextDownload @JvmOverloads constructor( addAntiCache: Boolean = true ) : AbstractAjaxTextDownload("application/text", addAntiCache) open class AjaxCsvDownload @JvmOverloads constructor( addAntiCache: Boolean = true ) : AbstractAjaxTextDownload("text/csv", addAntiCache) abstract class AbstractAjaxTextDownload( val contentType: String, addAntiCache: Boolean, ) : AjaxDownload(addAntiCache) { var content: String? = null override val resourceStream: IResourceStream get() = StringResourceStream(content, contentType) } private fun CharSequence.toUrl(antiCache: Boolean): String = if (!antiCache) toString() else "$this${if (this.contains("?")) "&" else "?"}antiCache=${System.currentTimeMillis()}"
gpl-3.0
b91211fcd5add58db57b2e67574370f7
34.966667
99
0.748378
4.290258
false
false
false
false
ursjoss/sipamato
core/core-sync/src/main/kotlin/ch/difty/scipamato/core/sync/jobs/newsletter/NewStudyTopicSyncConfig.kt
1
6349
package ch.difty.scipamato.core.sync.jobs.newsletter import ch.difty.scipamato.common.DateTimeService import ch.difty.scipamato.core.db.tables.Newsletter import ch.difty.scipamato.core.db.tables.NewsletterNewsletterTopic import ch.difty.scipamato.core.db.tables.NewsletterTopicTr import ch.difty.scipamato.core.db.tables.PaperNewsletter import ch.difty.scipamato.core.sync.PublicNewStudyTopic import ch.difty.scipamato.core.sync.jobs.SyncConfig import ch.difty.scipamato.publ.db.tables.NewStudyTopic import ch.difty.scipamato.publ.db.tables.NewsletterTopic import ch.difty.scipamato.publ.db.tables.records.NewStudyTopicRecord import org.jooq.DSLContext import org.jooq.DeleteConditionStep import org.jooq.TableField import org.jooq.conf.ParamType import org.springframework.batch.core.Job import org.springframework.batch.core.configuration.annotation.JobBuilderFactory import org.springframework.batch.core.configuration.annotation.StepBuilderFactory import org.springframework.batch.item.ItemWriter import org.springframework.beans.factory.annotation.Qualifier import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Profile import java.sql.ResultSet import java.sql.SQLException import java.sql.Timestamp import javax.sql.DataSource private const val NTTLM = "NTTLM" private const val NNTLM = "NNTLM" /** * Defines the newStudyTopic synchronization job, applying two steps: * * 1. insertingOrUpdating: inserts new records or updates if already present * 1. purging: removes records that have not been touched during the first step (within a defined grace time in minutes) */ @Configuration @Profile("!wickettest") open class NewStudyTopicSyncConfig( @Qualifier("dslContext") jooqCore: DSLContext, @Qualifier("publicDslContext") jooqPublic: DSLContext, @Qualifier("dataSource") coreDataSource: DataSource, jobBuilderFactory: JobBuilderFactory, stepBuilderFactory: StepBuilderFactory, dateTimeService: DateTimeService ) : SyncConfig<PublicNewStudyTopic, NewStudyTopicRecord>(TOPIC, CHUNK_SIZE, jooqCore, jooqPublic, coreDataSource, jobBuilderFactory, stepBuilderFactory, dateTimeService ) { @Bean open fun syncNewStudyTopicJob(): Job = createJob() override val jobName: String get() = "syncNewStudyTopicJob" override fun publicWriter(): ItemWriter<PublicNewStudyTopic> = NewStudyTopicItemWriter(jooqPublic) override fun selectSql(): String = jooqCore .select(PN_NEWSLETTER_ID, NTT_NEWSLETTER_TOPIC_ID, NTT_VERSION, NTT_CREATED, NTT_LAST_MODIFIED.`as`(NTTLM), NNT_SORT, NNT_LAST_MODIFIED.`as`(NNTLM)) .from(PaperNewsletter.PAPER_NEWSLETTER) .innerJoin(ch.difty.scipamato.core.db.tables.NewsletterTopic.NEWSLETTER_TOPIC) .on(PaperNewsletter.PAPER_NEWSLETTER.NEWSLETTER_TOPIC_ID.eq(ch.difty.scipamato.core.db.tables.NewsletterTopic.NEWSLETTER_TOPIC.ID)) .innerJoin(NewsletterTopicTr.NEWSLETTER_TOPIC_TR) .on(ch.difty.scipamato.core.db.tables.NewsletterTopic.NEWSLETTER_TOPIC.ID.eq(NewsletterTopicTr.NEWSLETTER_TOPIC_TR.NEWSLETTER_TOPIC_ID)) .leftOuterJoin(NewsletterNewsletterTopic.NEWSLETTER_NEWSLETTER_TOPIC) .on(PaperNewsletter.PAPER_NEWSLETTER.NEWSLETTER_ID.eq(NewsletterNewsletterTopic.NEWSLETTER_NEWSLETTER_TOPIC.NEWSLETTER_ID)) .and(ch.difty.scipamato.core.db.tables.NewsletterTopic.NEWSLETTER_TOPIC.ID.eq(NewsletterNewsletterTopic.NEWSLETTER_NEWSLETTER_TOPIC.NEWSLETTER_TOPIC_ID)) .innerJoin(Newsletter.NEWSLETTER) .on(PaperNewsletter.PAPER_NEWSLETTER.NEWSLETTER_ID.eq(Newsletter.NEWSLETTER.ID)) .where(Newsletter.NEWSLETTER.PUBLICATION_STATUS.eq(PUBLICATION_STATUS_PUBLISHED)) .getSQL(ParamType.INLINED) @Throws(SQLException::class) override fun makeEntity(rs: ResultSet): PublicNewStudyTopic = PublicNewStudyTopic( newsletterId = getInteger(PN_NEWSLETTER_ID, rs), newsletterTopicId = getInteger(NTT_NEWSLETTER_TOPIC_ID, rs), sort = getSortOrMaxIntFrom(rs), version = getInteger(NTT_VERSION, rs), created = getTimestamp(NTT_CREATED, rs), lastModified = getLaterTimeStampFrom(NTTLM, NNTLM, rs), lastSynched = getNow(), ) @Throws(SQLException::class) private fun getSortOrMaxIntFrom(rs: ResultSet): Int = getInteger(NNT_SORT, rs) ?: Int.MAX_VALUE @Suppress("SameParameterValue") @Throws(SQLException::class) private fun getLaterTimeStampFrom( nttLastModified: String, nntLastModified: String, rs: ResultSet ): Timestamp? { val ts1 = getTimestamp(nttLastModified, rs) val ts2 = getTimestamp(nntLastModified, rs) if (ts1 == null || ts2 == null) return ts1 ?: ts2 return if (ts1.after(ts2)) ts1 else ts2 } override fun lastSynchedField(): TableField<NewStudyTopicRecord, Timestamp> = NewStudyTopic.NEW_STUDY_TOPIC.LAST_SYNCHED override val pseudoFkDcs: DeleteConditionStep<NewStudyTopicRecord>? get() = jooqPublic .delete(NewStudyTopic.NEW_STUDY_TOPIC) .where(NewStudyTopic.NEW_STUDY_TOPIC.NEWSLETTER_TOPIC_ID.notIn(jooqPublic .selectDistinct(NewsletterTopic.NEWSLETTER_TOPIC.ID) .from(NewsletterTopic.NEWSLETTER_TOPIC))) companion object { private const val TOPIC = "newStudyTopic" private const val CHUNK_SIZE = 100 // relevant fields of the core paperNewsletter as well as newsletter_topic and newsletter_topic_tr records private val PN_NEWSLETTER_ID = PaperNewsletter.PAPER_NEWSLETTER.NEWSLETTER_ID private val NTT_NEWSLETTER_TOPIC_ID = NewsletterTopicTr.NEWSLETTER_TOPIC_TR.NEWSLETTER_TOPIC_ID private val NTT_VERSION = NewsletterTopicTr.NEWSLETTER_TOPIC_TR.VERSION private val NTT_CREATED = NewsletterTopicTr.NEWSLETTER_TOPIC_TR.CREATED private val NTT_LAST_MODIFIED = NewsletterTopicTr.NEWSLETTER_TOPIC_TR.LAST_MODIFIED private val NNT_SORT = NewsletterNewsletterTopic.NEWSLETTER_NEWSLETTER_TOPIC.SORT private val NNT_LAST_MODIFIED = NewsletterNewsletterTopic.NEWSLETTER_NEWSLETTER_TOPIC.LAST_MODIFIED } }
gpl-3.0
175f4fad4cfda4d8bf99888e573b8078
46.736842
165
0.747204
4.176974
false
true
false
false
anthonycr/Lightning-Browser
app/src/main/java/acr/browser/lightning/extensions/BitmapExtensions.kt
1
1368
package acr.browser.lightning.extensions import acr.browser.lightning.utils.Utils import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.ColorMatrix import android.graphics.ColorMatrixColorFilter import android.graphics.Paint import androidx.core.graphics.createBitmap /** * Creates and returns a new favicon which is the same as the provided favicon but with horizontal * and vertical padding of 4dp * * @return the padded bitmap. */ fun Bitmap.pad(): Bitmap = let { val padding = Utils.dpToPx(4f) val width = it.width + padding val height = it.height + padding Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888).apply { Canvas(this).apply { drawARGB(0x00, 0x00, 0x00, 0x00) // this represents white color drawBitmap( it, (padding / 2).toFloat(), (padding / 2).toFloat(), Paint(Paint.FILTER_BITMAP_FLAG) ) } } } private val desaturatedPaint = Paint().apply { colorFilter = ColorMatrixColorFilter(ColorMatrix().apply { setSaturation(0.5f) }) } /** * Desaturates a [Bitmap] to 50% grayscale. Note that a new bitmap will be created. */ fun Bitmap.desaturate(): Bitmap = createBitmap(width, height).also { Canvas(it).drawBitmap(this, 0f, 0f, desaturatedPaint) }
mpl-2.0
24eb902e91d9b1a6f7f02bc30a3e67e0
28.106383
98
0.671784
3.931034
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/types/Version.kt
1
2129
package slatekit.common.types import slatekit.common.checks.Check import slatekit.results.Failure import slatekit.results.Notice import slatekit.results.Success data class Version( val major: Int, val minor: Int, val patch: Int, val build: Int, val label: String = "" ) { constructor(major:Int) : this(major, 0, 0, 0) constructor(major:Int, minor:Int) : this(major, minor, 0, 0) constructor(major:Int, minor:Int, patch:Int) : this(major, minor, patch, 0) operator fun compareTo(other: Version): Int = when { major < other.major -> -1 major > other.major -> 1 minor < other.minor -> -1 minor > other.minor -> 1 patch < other.patch -> -1 patch > other.patch -> 1 build < other.build -> -1 build > other.build -> 1 else -> 0 } /** * Considered empty if all parts are 0 */ fun isEmpty():Boolean = this == empty || major == 0 && minor == 0 && patch == 0 && build == 0 companion object { @JvmStatic val empty = Version(0, 0, 0, 0) @JvmStatic fun parse(text:String): Notice<Version> { val tokens = text.trim().split('.') val numeric = tokens.all { Check.isWholeNumber(it) } return if(!numeric) { Failure("Not all parts of the version are numeric") } else { val parts = tokens.map { it.trim() } when (tokens.size) { 1 -> Success(Version(parts[0].toInt())) 2 -> Success(Version(parts[0].toInt(), parts[1].toInt())) 3 -> Success(Version(parts[0].toInt(), parts[1].toInt(), parts[2].toInt())) 4 -> Success(Version(parts[0].toInt(), parts[1].toInt(), parts[2].toInt(), parts[3].toInt())) 5 -> Success(Version(parts[0].toInt(), parts[1].toInt(), parts[2].toInt(), parts[3].toInt(), parts[4])) else -> Failure("Invalid version, expected 4-5 parts separated by . e.g. 1.2.3.4.ABC") } } } } }
apache-2.0
0d4964ab240472a77f9d8250a43d0b1f
32.28125
123
0.530296
3.906422
false
false
false
false
kkirstein/kotlin-benchmark
src/main/kotlin/benchmark/mandelbrot.kt
1
2251
/* mandelbrot.kt * Calculate Mandelbrot sets in the Kotlin * (http://kotlinlang.org) programming language */ package benchmark.mandelbrot import java.awt.image.BufferedImage import complex.Complex import kotlinx.coroutines.experimental.CommonPool import kotlinx.coroutines.experimental.Deferred import kotlinx.coroutines.experimental.async // first we need an container for the image data data class Image<T>(val width: Int, val height: Int, val channels: Int, val data: Array<T>) // calculates pixel values fun pixelVal(z0: Complex, maxIter: Int = 255, zMax: Double = 2.0): Int { var iter = 0 var z = Complex.zero while (iter <= maxIter) { if (z.abs() > zMax) return iter z = z * z + z0 iter++ } return maxIter } // convert pixel value to RGB fun toRGB(value: Int) = if (value == 0) { 0 } else { val r = 5 * (value % 15) val g = 32 * (value % 7) val b = 8 *(value % 31) (r.shl(16) or g.shl(8) or b) } // calculate a single line of Mandelbrot set fun mandelbrotLine(y: Int, width: Int, xCenter: Double, yCenter: Double, pixSize: Double = 4.0 / width): IntArray { val imgLine = IntArray(width) val yCoord = yCenter + 0.5 * y.toDouble() * pixSize for (x in 0.rangeTo(width-1)) { val xCoord = xCenter - 0.5 * x.toDouble() * pixSize val pixVal = toRGB(pixelVal(Complex(re = xCoord, im = yCoord))) imgLine[x] = pixVal } return imgLine } // generates Mandelbrot set for given coordinates suspend fun mandelbrot(width: Int, height: Int, xCenter: Double, yCenter: Double, pixSize: Double = 4.0 / width): BufferedImage { val img = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB) //val imgData = Array<Int>(width*height) { _ -> 0 } val imgData = IntArray(width*height) //var imgDataAsync = Array<Deferred<Int>>(0) for (y in 0.rangeTo(height-1)) { val imgLine = async(CommonPool) { mandelbrotLine(y, width, xCenter, yCenter, pixSize) } img.setRGB(0, y, width, 1, imgLine.await(), 0, width) } //img.setRGB(0, 0, width, height, imgData, 0, width) return img }
mit
94999d87ff941e7d7d2e088747a7a3ae
27.858974
95
0.617503
3.436641
false
false
false
false
salRoid/Filmy
app/src/main/java/tech/salroid/filmy/ui/fragment/InTheaters.kt
1
3873
package tech.salroid.filmy.ui.fragment import android.content.Intent import android.content.res.Configuration import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.GridLayoutManager import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import tech.salroid.filmy.ui.activities.MovieDetailsActivity import tech.salroid.filmy.ui.adapters.MoviesAdapter import tech.salroid.filmy.data.local.db.FilmyDbHelper import tech.salroid.filmy.data.local.db.entity.Movie import tech.salroid.filmy.databinding.FragmentInTheatersBinding import tech.salroid.filmy.data.network.NetworkUtil class InTheaters : Fragment() { private var adapter: MoviesAdapter? = null private var isShowingFromDatabase = false private var gridLayoutManager: GridLayoutManager? = null private var showingFromDb = false private lateinit var binding: FragmentInTheatersBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentInTheatersBinding.inflate(inflater, container, false) val view = binding.root if (activity?.resources?.configuration?.orientation == Configuration.ORIENTATION_PORTRAIT) { gridLayoutManager = GridLayoutManager( context, 2, GridLayoutManager.HORIZONTAL, false ) binding.recycler.layoutManager = gridLayoutManager } else { gridLayoutManager = GridLayoutManager( context, 1, GridLayoutManager.HORIZONTAL, false ) binding.recycler.layoutManager = gridLayoutManager } adapter = MoviesAdapter { itemClicked(it) } binding.recycler.adapter = adapter return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Get movies from DB viewLifecycleOwner.lifecycleScope.launch(Dispatchers.IO) { val movies = FilmyDbHelper .getDb(requireContext().applicationContext) .movieDao() .getAllInTheaters() if (movies.isNotEmpty()) { showMovies(movies) showingFromDb = true } } // Get movies from Network NetworkUtil.getInTheatersMovies({ moviesResponse -> moviesResponse?.results?.let { if(!showingFromDb) { showMovies(it) } saveMoviesInDb(it) } }, { }) } private fun saveMoviesInDb(movies: List<Movie>) { viewLifecycleOwner.lifecycleScope.launch(Dispatchers.IO) { movies.forEach { it.type = 1 } FilmyDbHelper .getDb(requireContext().applicationContext) .movieDao() .insertAll(movies) } } private fun showMovies(movies: List<Movie>) { isShowingFromDatabase = true adapter?.swapData(movies) } private fun itemClicked(movie: Movie) { val intent = Intent(activity, MovieDetailsActivity::class.java) intent.putExtra("title", movie.title) intent.putExtra("activity", true) intent.putExtra("type", 1) intent.putExtra("database_applicable", true) intent.putExtra("network_applicable", true) intent.putExtra("id", movie.id.toString()) startActivity(intent) activity?.overridePendingTransition(0, 0) } }
apache-2.0
99fa03903e90845ec5d04a91a647f314
31.283333
100
0.632326
5.327373
false
false
false
false
smmribeiro/intellij-community
platform/diff-impl/tests/testSrc/com/intellij/diff/tools/fragmented/LineNumberConvertorTest.kt
31
5557
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diff.tools.fragmented import junit.framework.TestCase class LineNumberConvertorTest : TestCase() { fun testEmpty() { doTest( { }, { checkEmpty(-5, 20) checkEmptyInv(-5, 20) } ) } fun testSingleRange() { doTest( { put(2, 3, 2) }, { checkMatch(2, 3, 2) checkEmpty(-5, 1) checkEmpty(4, 10) checkEmptyInv(-5, 2) checkEmptyInv(5, 10) } ) } fun testTwoRanges() { doTest( { put(2, 3, 2) put(10, 7, 1) }, { checkMatch(2, 3, 2) checkMatch(10, 7, 1) checkEmpty(-5, 1) checkEmpty(4, 9) checkEmpty(11, 15) checkEmptyInv(-5, 2) checkEmptyInv(5, 6) checkEmptyInv(8, 12) } ) } fun testAdjustmentRanges() { doTest( { put(2, 3, 2) put(4, 5, 3) }, { checkMatch(2, 3, 5) checkEmpty(-5, 1) checkEmpty(7, 10) checkEmptyInv(-5, 2) checkEmptyInv(8, 10) } ) } fun testPartiallyAdjustmentRanges() { doTest( { put(2, 3, 2) put(4, 10, 3) }, { checkMatch(2, 3, 2) checkMatch(4, 10, 3) checkEmpty(-5, 1) checkEmpty(7, 10) checkEmptyInv(-5, 2) checkEmptyInv(5, 9) checkEmptyInv(13, 15) } ) } fun testTwoRangesApproximate() { doTest( { put(1, 2, 1) put(6, 5, 2) }, { checkEmpty(-5, 0) checkMatch(1, 2, 1) checkEmpty(3, 5) checkMatch(6, 5, 2) checkEmpty(8, 20) checkApproximate(0, 0) checkApproximate(1, 2) checkApproximate(2, 3) checkApproximate(3, 3) checkApproximate(4, 3) checkApproximate(5, 3) checkApproximate(6, 5) checkApproximate(7, 6) checkApproximate(8, 7) checkApproximate(9, 7) checkApproximate(10, 7) checkApproximate(11, 7) checkApproximateInv(0, 0) checkApproximateInv(0, 1) checkApproximateInv(1, 2) checkApproximateInv(2, 3) checkApproximateInv(2, 4) checkApproximateInv(6, 5) checkApproximateInv(7, 6) checkApproximateInv(8, 7) checkApproximateInv(8, 8) checkApproximateInv(8, 9) checkApproximateInv(8, 10) checkApproximateInv(8, 11) } ) } fun testNonFairRange() { doTest( { put(1, 2, 1) put(6, 5, 2, 4) }, { checkEmpty(-5, 0) checkMatch(1, 2, 1) checkEmpty(3, 20) checkApproximate(0, 0) checkApproximate(1, 2) checkApproximate(2, 3) checkApproximate(3, 3) checkApproximate(4, 3) checkApproximate(5, 3) checkApproximate(6, 5) checkApproximate(7, 6) checkApproximate(8, 7) checkApproximate(9, 8) checkApproximate(10, 9) checkApproximate(11, 9) checkApproximate(12, 9) checkApproximateInv(0, 0) checkApproximateInv(0, 1) checkApproximateInv(1, 2) checkApproximateInv(2, 3) checkApproximateInv(2, 4) checkApproximateInv(6, 5) checkApproximateInv(7, 6) checkApproximateInv(8, 7) checkApproximateInv(8, 8) checkApproximateInv(8, 9) checkApproximateInv(8, 10) checkApproximateInv(8, 11) }) } // // Impl // private fun doTest(prepare: TestBuilder.() -> Unit, check: Test.() -> Unit) { val builder = TestBuilder() builder.prepare() val test = builder.finish() test.check() } private class TestBuilder { private val builder = LineNumberConvertor.Builder() fun put(left: Int, right: Int, length: Int) { builder.put(left, right, length) } fun put(left: Int, right: Int, lengthLeft: Int, lengthRight: Int) { builder.put(left, right, lengthLeft, lengthRight) } fun finish(): Test = Test(builder.build()) } private class Test(val convertor: LineNumberConvertor) { fun checkMatch(left: Int, right: Int, length: Int = 1) { for (i in 0..length - 1) { assertEquals(right + i, convertor.convert(left + i)) assertEquals(left + i, convertor.convertInv(right + i)) } } fun checkApproximate(left: Int, right: Int) { assertEquals(right, convertor.convertApproximate(left)) } fun checkApproximateInv(left: Int, right: Int) { assertEquals(left, convertor.convertApproximateInv(right)) } fun checkEmpty(startLeft: Int, endLeft: Int) { for (i in startLeft..endLeft) { assertEquals(-1, convertor.convert(i)) } } fun checkEmptyInv(startRight: Int, endRight: Int) { for (i in startRight..endRight) { assertEquals(-1, convertor.convertInv(i)) } } } }
apache-2.0
c563e7f86a309ae20bab55194f678be7
21.868313
79
0.564333
3.615485
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/KotlinLiteralCopyPasteProcessor.kt
5
12397
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.editor import com.intellij.codeInsight.editorActions.CopyPastePreProcessor import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.RawText import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.text.LineTokenizer import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.idea.editor.fixers.range import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.lexer.KotlinLexer import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtEscapeStringTemplateEntry import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtStringTemplateExpression import org.jetbrains.kotlin.psi.psiUtil.* private val PsiElement.templateContentRange: TextRange? get() = this.getParentOfType<KtStringTemplateExpression>(false)?.let { it.textRange.cutOut(it.getContentRange()) } private fun PsiFile.getTemplateIfAtLiteral(offset: Int, at: PsiElement? = findElementAt(offset)): KtStringTemplateExpression? { if (at == null) return null return when (at.node?.elementType) { KtTokens.REGULAR_STRING_PART, KtTokens.ESCAPE_SEQUENCE, KtTokens.LONG_TEMPLATE_ENTRY_START, KtTokens.SHORT_TEMPLATE_ENTRY_START -> at.parent .parent as? KtStringTemplateExpression KtTokens.CLOSING_QUOTE -> if (offset == at.startOffset) at.parent as? KtStringTemplateExpression else null else -> null } } //Copied from StringLiteralCopyPasteProcessor to avoid erroneous inheritance private fun deduceBlockSelectionWidth(startOffsets: IntArray, endOffsets: IntArray, text: String): Int { val fragmentCount = startOffsets.size assert(fragmentCount > 0) var totalLength = fragmentCount - 1 // number of line breaks inserted between fragments for (i in 0 until fragmentCount) { totalLength += endOffsets[i] - startOffsets[i] } return if (totalLength < text.length && (text.length + 1) % fragmentCount == 0) { (text.length + 1) / fragmentCount - 1 } else { -1 } } class KotlinLiteralCopyPasteProcessor : CopyPastePreProcessor { override fun preprocessOnCopy(file: PsiFile, startOffsets: IntArray, endOffsets: IntArray, text: String): String? { if (file !is KtFile) { return null } val buffer = StringBuilder() var changed = false val fileText = file.text val deducedBlockSelectionWidth = deduceBlockSelectionWidth(startOffsets, endOffsets, text) for (i in startOffsets.indices) { if (i > 0) { buffer.append('\n') // LF is added for block selection } val fileRange = TextRange(startOffsets[i], endOffsets[i]) var givenTextOffset = fileRange.startOffset while (givenTextOffset < fileRange.endOffset) { val element: PsiElement? = file.findElementAt(givenTextOffset) if (element == null) { buffer.append(fileText.substring(givenTextOffset, fileRange.endOffset - 1)) break } val elTp = element.node.elementType if (elTp == KtTokens.ESCAPE_SEQUENCE && fileRange.contains(element.range) && element.templateContentRange?.contains(fileRange) == true ) { val tpEntry = element.parent as KtEscapeStringTemplateEntry changed = true buffer.append(tpEntry.unescapedValue) givenTextOffset = element.endOffset } else if (elTp == KtTokens.SHORT_TEMPLATE_ENTRY_START || elTp == KtTokens.LONG_TEMPLATE_ENTRY_START) { //Process inner templates without escaping val tpEntry = element.parent val inter = fileRange.intersection(tpEntry.range)!! buffer.append(fileText.substring(inter.startOffset, inter.endOffset)) givenTextOffset = inter.endOffset } else { val inter = fileRange.intersection(element.range)!! buffer.append(fileText.substring(inter.startOffset, inter.endOffset)) givenTextOffset = inter.endOffset } } val blockSelectionPadding = deducedBlockSelectionWidth - fileRange.length for (j in 0 until blockSelectionPadding) { buffer.append(' ') } } return if (changed) buffer.toString() else null } override fun preprocessOnPaste(project: Project, file: PsiFile, editor: Editor, text: String, rawText: RawText?): String { if (file !is KtFile) { return text } PsiDocumentManager.getInstance(project).commitDocument(editor.document) val selectionModel = editor.selectionModel val begin = file.findElementAt(selectionModel.selectionStart) ?: return text val beginTp = file.getTemplateIfAtLiteral(selectionModel.selectionStart, begin) ?: return text val endTp = file.getTemplateIfAtLiteral(selectionModel.selectionEnd) ?: return text if (beginTp.isSingleQuoted() != endTp.isSingleQuoted()) { return text } val templateTokenSequence = TemplateTokenSequence(text) return if (beginTp.isSingleQuoted()) { val res = StringBuilder() val lineBreak = "\\n\"+\n \"" var endsInLineBreak = false templateTokenSequence.forEach { when (it) { is LiteralChunk -> StringUtil.escapeStringCharacters(it.text.length, it.text, "\$\"", res) is EntryChunk -> res.append(it.text) is NewLineChunk -> res.append(lineBreak) } endsInLineBreak = it is NewLineChunk } return if (endsInLineBreak) { res.removeSuffix(lineBreak).toString() + "\\n" } else { res.toString() } } else { fun TemplateChunk?.indent() = when (this) { is LiteralChunk -> this.text is EntryChunk -> this.text else -> "" }.takeWhile { it.isWhitespace() } val indent = if (beginTp.firstChild?.text == "\"\"\"" && beginTp.getQualifiedExpressionForReceiver()?.callExpression?.calleeExpression?.text == "trimIndent" && templateTokenSequence.firstOrNull()?.indent() == templateTokenSequence.lastOrNull()?.indent() ) { begin.parent?.prevSibling?.text?.takeIf { it.all { c -> c == ' ' || c == '\t' } } } else { null } ?: "" buildString { val tripleQuoteRe = Regex("[\"]{3,}") var indentToAdd = "" for (chunk in templateTokenSequence) { when (chunk) { is LiteralChunk -> { val replaced = chunk.text.replace("\$", "\${'$'}").let { escapedDollar -> tripleQuoteRe.replace(escapedDollar) { "\"\"" + "\${'\"'}".repeat(it.value.count() - 2) } } append(indentToAdd + replaced) indentToAdd = "" } is EntryChunk -> { append(indentToAdd + chunk.text) indentToAdd = "" } is NewLineChunk -> { appendLine() indentToAdd = indent } } } } } } } private sealed class TemplateChunk private data class LiteralChunk(val text: String) : TemplateChunk() private data class EntryChunk(val text: String) : TemplateChunk() private object NewLineChunk : TemplateChunk() private class TemplateTokenSequence(private val inputString: String) : Sequence<TemplateChunk> { private fun String.guessIsTemplateEntryStart(): Boolean = if (this.startsWith("\${")) { true } else if (this.length > 1 && this[0] == '$') { val guessedIdentifier = substring(1) val tokenType = KotlinLexer().apply { start(guessedIdentifier) }.tokenType tokenType == KtTokens.IDENTIFIER || tokenType == KtTokens.THIS_KEYWORD } else { false } private fun findTemplateEntryEnd(input: String, from: Int): Int { val wrapped = '"' + input.substring(from) + '"' val lexer = KotlinLexer().apply { start(wrapped) }.apply { advance() } when (lexer.tokenType) { KtTokens.SHORT_TEMPLATE_ENTRY_START -> { lexer.advance() val tokenType = lexer.tokenType return if (tokenType == KtTokens.IDENTIFIER || tokenType == KtTokens.THIS_KEYWORD) { from + lexer.tokenEnd - 1 } else { -1 } } KtTokens.LONG_TEMPLATE_ENTRY_START -> { var depth = 0 while (lexer.tokenType != null) { if (lexer.tokenType == KtTokens.LONG_TEMPLATE_ENTRY_START) { depth++ } else if (lexer.tokenType == KtTokens.LONG_TEMPLATE_ENTRY_END) { depth-- if (depth == 0) { return from + lexer.currentPosition.offset } } lexer.advance() } return -1 } else -> return -1 } } private suspend fun SequenceScope<TemplateChunk>.yieldLiteral(chunk: String) { val splitLines = LineTokenizer.tokenize(chunk, false, false) for (i in splitLines.indices) { if (i != 0) { yield(NewLineChunk) } splitLines[i].takeIf { it.isNotEmpty() }?.let { yield(LiteralChunk(it)) } } } private fun iterTemplateChunks(): Iterator<TemplateChunk> { if (inputString.isEmpty()) { return emptySequence<TemplateChunk>().iterator() } return iterator { var from = 0 var to = 0 while (to < inputString.length) { val c = inputString[to] if (c == '\\') { to += 1.toInt() if (to < inputString.length) to += 1.toInt() continue } else if (c == '$') { if (inputString.substring(to).guessIsTemplateEntryStart()) { if (from < to) yieldLiteral(inputString.substring(from until to)) from = to to = findTemplateEntryEnd(inputString, from) if (to != -1) { yield(EntryChunk(inputString.substring(from until to))) } else { to = inputString.length yieldLiteral(inputString.substring(from until to)) } from = to continue } } to++ } if (from < to) { yieldLiteral(inputString.substring(from until to)) } } } override fun iterator(): Iterator<TemplateChunk> = iterTemplateChunks() } @TestOnly fun createTemplateSequenceTokenString(input: String): String { return TemplateTokenSequence(input).map { when (it) { is LiteralChunk -> "LITERAL_CHUNK(${it.text})" is EntryChunk -> "ENTRY_CHUNK(${it.text})" is NewLineChunk -> "NEW_LINE()" } }.joinToString(separator = "") }
apache-2.0
c90c158f17da2a9e1d8ba8bb5cdfd79a
41.455479
158
0.559652
5.025132
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/ui/viewholders/projectcampaign/TextElementViewHolder.kt
1
1179
package com.kickstarter.ui.viewholders.projectcampaign import android.text.method.LinkMovementMethod import android.widget.TextView import com.kickstarter.R import com.kickstarter.databinding.ViewElementTextFromHtmlBinding import com.kickstarter.libs.htmlparser.TextViewElement import com.kickstarter.libs.htmlparser.getStyledComponents import com.kickstarter.ui.viewholders.KSViewHolder class TextElementViewHolder( val binding: ViewElementTextFromHtmlBinding ) : KSViewHolder(binding.root) { private val textView: TextView = binding.textView fun configure(element: TextViewElement) { // - Allow clickable spans textView.linksClickable = true textView.isClickable = true textView.movementMethod = LinkMovementMethod.getInstance() val headerSize = context().resources.getDimensionPixelSize(R.dimen.title_3) val bodySize = context().resources.getDimensionPixelSize(R.dimen.callout) textView.text = element.getStyledComponents(bodySize, headerSize, context()) } override fun bindData(data: Any?) { (data as? TextViewElement).apply { this?.let { configure(it) } } } }
apache-2.0
db71d44095528a0fd9949cb810e08546
34.727273
84
0.750636
4.73494
false
true
false
false
MyPureCloud/platform-client-sdk-common
resources/sdk/purecloudkotlin/extensions/connector/apache/ApacheHttpClientConnectorProvider.kt
1
3309
package com.mypurecloud.sdk.v2.connector.apache import com.google.common.util.concurrent.ThreadFactoryBuilder import com.mypurecloud.sdk.v2.DetailLevel import com.mypurecloud.sdk.v2.connector.ApiClientConnector import com.mypurecloud.sdk.v2.connector.ApiClientConnectorProperties import com.mypurecloud.sdk.v2.connector.ApiClientConnectorProperty import com.mypurecloud.sdk.v2.connector.ApiClientConnectorProvider import org.apache.http.HttpHost import org.apache.http.HttpRequestInterceptor import org.apache.http.HttpResponseInterceptor import org.apache.http.client.config.RequestConfig import org.apache.http.impl.client.HttpClients import java.net.InetSocketAddress import java.net.Proxy import java.util.concurrent.ExecutorService import java.util.concurrent.Executors class ApacheHttpClientConnectorProvider : ApiClientConnectorProvider { override fun create(properties: ApiClientConnectorProperties): ApiClientConnector { var requestBuilder = RequestConfig.custom() val connectionTimeout = properties.getProperty(ApiClientConnectorProperty.CONNECTION_TIMEOUT, Int::class.java, null) if (connectionTimeout != null && connectionTimeout > 0) { requestBuilder = requestBuilder.setConnectTimeout(connectionTimeout) .setSocketTimeout(connectionTimeout) .setConnectionRequestTimeout(connectionTimeout) } val proxy = properties.getProperty(ApiClientConnectorProperty.PROXY, Proxy::class.java, null) var credentialsProvider: ApacheHttpCredentialsProvider? = null if (proxy != null) { val address = proxy.address() if (address is InetSocketAddress) { val inetAddress = address val proxyHost = HttpHost(inetAddress.address, inetAddress.port) requestBuilder.setProxy(proxyHost) val user = properties.getProperty(ApiClientConnectorProperty.PROXY_USER, String::class.java, null) val pass = properties.getProperty(ApiClientConnectorProperty.PROXY_PASS, String::class.java, null) if (user != null && pass != null) { credentialsProvider = ApacheHttpCredentialsProvider(inetAddress.hostName, inetAddress.port, user, pass) } } } val detailLevel = properties.getProperty(ApiClientConnectorProperty.DETAIL_LEVEL, DetailLevel::class.java, DetailLevel.MINIMAL) val interceptor = SLF4JInterceptor(detailLevel) val builder = HttpClients.custom() .setDefaultRequestConfig(requestBuilder.build()) .addInterceptorFirst(interceptor as HttpRequestInterceptor) .addInterceptorLast(interceptor as HttpResponseInterceptor) if (credentialsProvider != null) { builder.setDefaultCredentialsProvider(credentialsProvider) } val client = builder.build() var executorService = properties.getProperty(ApiClientConnectorProperty.ASYNC_EXECUTOR_SERVICE, ExecutorService::class.java, null) if (executorService == null) { executorService = Executors.newCachedThreadPool(ThreadFactoryBuilder().setNameFormat("purecloud-sdk-%d").build()) } return ApacheHttpClientConnector(client, executorService) } }
mit
c7ce2d76baa6dcf4575e4675fac37998
55.084746
138
0.729223
5.154206
false
true
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/utils/OwnedItemListDeserializer.kt
1
872
package com.habitrpg.android.habitica.utils import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.habitrpg.android.habitica.models.user.OwnedItem import io.realm.RealmList import java.lang.reflect.Type class OwnedItemListDeserializer: JsonDeserializer<List<OwnedItem>> { override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): List<OwnedItem> { val ownedItems = RealmList<OwnedItem>() val entrySet = json?.asJsonObject?.entrySet() if (entrySet != null) { for (entry in entrySet) { val item = OwnedItem() item.key = entry.key item.numberOwned = entry.value.asInt ownedItems.add(item) } } return ownedItems } }
gpl-3.0
10e46d94ecb496cc3d6268d51c81507f
35.375
121
0.677752
4.765027
false
false
false
false
leafclick/intellij-community
platform/credential-store/src/PasswordSafeSettings.kt
1
2920
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.credentialStore import com.intellij.ide.passwordSafe.impl.getDefaultKeePassDbFile import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* import com.intellij.openapi.util.SystemInfo import com.intellij.util.messages.Topic import com.intellij.util.text.nullize import com.intellij.util.xmlb.annotations.OptionTag @Service @State(name = "PasswordSafe", storages = [Storage(value = "security.xml", roamingType = RoamingType.DISABLED)]) class PasswordSafeSettings : PersistentStateComponentWithModificationTracker<PasswordSafeSettings.PasswordSafeOptions> { companion object { @JvmField val TOPIC = Topic.create("PasswordSafeSettingsListener", PasswordSafeSettingsListener::class.java) private val defaultProviderType: ProviderType get() = if (SystemInfo.isWindows) ProviderType.KEEPASS else ProviderType.KEYCHAIN } private var state = PasswordSafeOptions() var keepassDb: String? get() { val result = state.keepassDb return when { result == null && providerType === ProviderType.KEEPASS -> getDefaultKeePassDbFile().toString() else -> result } } set(value) { var v = value.nullize(nullizeSpaces = true) if (v != null && v == getDefaultKeePassDbFile().toString()) { v = null } state.keepassDb = v } var providerType: ProviderType get() = if (SystemInfo.isWindows && state.provider === ProviderType.KEYCHAIN) ProviderType.KEEPASS else state.provider set(value) { var newValue = value @Suppress("DEPRECATION") if (newValue === ProviderType.DO_NOT_STORE) { newValue = ProviderType.MEMORY_ONLY } val oldValue = state.provider if (newValue !== oldValue) { state.provider = newValue ApplicationManager.getApplication()?.messageBus?.syncPublisher(TOPIC)?.typeChanged(oldValue, newValue) } } override fun getState() = state override fun loadState(state: PasswordSafeOptions) { this.state = state providerType = state.provider state.keepassDb = state.keepassDb.nullize(nullizeSpaces = true) } override fun getStateModificationCount() = state.modificationCount class PasswordSafeOptions : BaseState() { // do not use it directly @get:OptionTag("PROVIDER") var provider by enum(defaultProviderType) // do not use it directly var keepassDb by string() var isRememberPasswordByDefault by property(true) // do not use it directly var pgpKeyId by string() } } enum class ProviderType { MEMORY_ONLY, KEYCHAIN, KEEPASS, // unused, but we cannot remove it because enum value maybe stored in the config and we must correctly deserialize it @Deprecated("") DO_NOT_STORE }
apache-2.0
ff7c69119767d8b0611dea0efde3cbf6
32.574713
140
0.718836
4.39759
false
false
false
false
siosio/intellij-community
java/idea-ui/src/com/intellij/codeInsight/daemon/impl/LibrarySourceNotificationProvider.kt
1
5516
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.daemon.impl import com.intellij.diff.DiffContentFactory import com.intellij.diff.DiffManager import com.intellij.diff.requests.SimpleDiffRequest import com.intellij.ide.JavaUiBundle import com.intellij.ide.util.PsiNavigationSupport import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileTypes.LanguageFileType import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.* import com.intellij.psi.impl.source.PsiExtensibleClass import com.intellij.psi.util.PsiFormatUtil.* import com.intellij.ui.EditorNotificationPanel import com.intellij.ui.EditorNotifications import com.intellij.ui.LightColors import com.intellij.util.diff.Diff class LibrarySourceNotificationProvider : EditorNotifications.Provider<EditorNotificationPanel>() { private companion object { private val LOG = Logger.getInstance(LibrarySourceNotificationProvider::class.java) private val KEY = Key.create<EditorNotificationPanel>("library.source.mismatch.panel") private val ANDROID_SDK_PATTERN = ".*/platforms/android-\\d+/android.jar!/.*".toRegex() private const val FIELD = SHOW_NAME or SHOW_TYPE or SHOW_FQ_CLASS_NAMES or SHOW_RAW_TYPE private const val METHOD = SHOW_NAME or SHOW_PARAMETERS or SHOW_RAW_TYPE private const val PARAMETER = SHOW_TYPE or SHOW_FQ_CLASS_NAMES or SHOW_RAW_TYPE private const val CLASS = SHOW_NAME or SHOW_FQ_CLASS_NAMES or SHOW_EXTENDS_IMPLEMENTS or SHOW_RAW_TYPE } override fun getKey(): Key<EditorNotificationPanel> = KEY override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor, project: Project): EditorNotificationPanel? { if (file.fileType is LanguageFileType && ProjectRootManager.getInstance(project).fileIndex.isInLibrarySource(file)) { val psiFile = PsiManager.getInstance(project).findFile(file) if (psiFile is PsiJavaFile) { val offender = psiFile.classes.find { differs(it) } if (offender != null) { val clsFile = offender.originalElement.containingFile?.virtualFile if (clsFile != null && !clsFile.path.matches(ANDROID_SDK_PATTERN)) { val panel = EditorNotificationPanel(LightColors.RED) panel.setText(JavaUiBundle.message("library.source.mismatch", offender.name)) panel.createActionLabel(JavaUiBundle.message("library.source.open.class")) { if (!project.isDisposed && clsFile.isValid) { PsiNavigationSupport.getInstance().createNavigatable(project, clsFile, -1).navigate(true) } } panel.createActionLabel(JavaUiBundle.message("library.source.show.diff")) { if (!project.isDisposed && clsFile.isValid) { val cf = DiffContentFactory.getInstance() val request = SimpleDiffRequest(null, cf.create(project, clsFile), cf.create(project, file), clsFile.path, file.path) DiffManager.getInstance().showDiff(project, request) } } logMembers(offender) return panel } } } } return null } private fun differs(src: PsiClass): Boolean { val cls = src.originalElement return cls !== src && cls is PsiClass && (differs(fields(src), fields(cls), ::format) || differs(methods(src), methods(cls), ::format) || differs(inners(src), inners(cls), ::format)) } private fun <T : PsiMember> differs(srcMembers: List<T>, clsMembers: List<T>, format: (T) -> String) = srcMembers.size != clsMembers.size || srcMembers.map(format).sorted() != clsMembers.map(format).sorted() private fun fields(c: PsiClass) = if (c is PsiExtensibleClass) c.ownFields else c.fields.asList() private fun methods(c: PsiClass) = (if (c is PsiExtensibleClass) c.ownMethods else c.methods.asList()).filterNot(::ignoreMethod) private fun ignoreMethod(m: PsiMethod): Boolean { if (m.isConstructor) { return m.parameterList.parametersCount == 0 // default constructor } else { return m.name.contains("$\$bridge") // org.jboss.bridger.Bridger adds ACC_BRIDGE | ACC_SYNTHETIC to such methods } } private fun inners(c: PsiClass) = if (c is PsiExtensibleClass) c.ownInnerClasses else c.innerClasses.asList() private fun format(f: PsiField) = formatVariable(f, FIELD, PsiSubstitutor.EMPTY) private fun format(m: PsiMethod) = formatMethod(m, PsiSubstitutor.EMPTY, METHOD, PARAMETER) private fun format(c: PsiClass) = formatClass(c, CLASS).removeSuffix(" extends java.lang.Object") private fun logMembers(offender: PsiClass) { if (!LOG.isTraceEnabled) { return } val cls = offender.originalElement as? PsiClass ?: return val sourceMembers = formatMembers(offender) val clsMembers = formatMembers(cls) val diff = Diff.linesDiff(sourceMembers.toTypedArray(), clsMembers.toTypedArray()) ?: return LOG.trace("Class: ${cls.qualifiedName}\n$diff") } private fun formatMembers(c: PsiClass): List<String> { return fields(c).map(::format).sorted() + methods(c).map(::format).sorted() + inners(c).map(::format).sorted() } }
apache-2.0
a63cfe264745140a3fad867555309b55
45.352941
158
0.711929
4.239816
false
false
false
false
rei-m/HBFav_material
app/src/main/kotlin/me/rei_m/hbfavmaterial/presentation/widget/adapter/EntryListAdapter.kt
1
3172
/* * Copyright (c) 2017. Rei Matsushita * * 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 me.rei_m.hbfavmaterial.presentation.widget.adapter import android.content.Context import android.databinding.DataBindingUtil import android.databinding.ObservableArrayList import android.databinding.ObservableList import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import me.rei_m.hbfavmaterial.databinding.ListItemEntryBinding import me.rei_m.hbfavmaterial.model.entity.Bookmark import me.rei_m.hbfavmaterial.model.entity.Entry import me.rei_m.hbfavmaterial.viewmodel.widget.adapter.EntryListItemViewModel /** * エントリー一覧を管理するAdaptor. */ class EntryListAdapter(context: Context?, private val injector: Injector, private val entryList: ObservableArrayList<Entry>) : ArrayAdapter<Entry>(context, 0, entryList) { private val inflater: LayoutInflater = LayoutInflater.from(context) private val entryListChangedCallback = object : ObservableList.OnListChangedCallback<ObservableArrayList<Bookmark>>() { override fun onItemRangeInserted(p0: ObservableArrayList<Bookmark>?, p1: Int, p2: Int) { notifyDataSetChanged() } override fun onItemRangeRemoved(p0: ObservableArrayList<Bookmark>?, p1: Int, p2: Int) { notifyDataSetChanged() } override fun onItemRangeMoved(p0: ObservableArrayList<Bookmark>?, p1: Int, p2: Int, p3: Int) { notifyDataSetChanged() } override fun onChanged(p0: ObservableArrayList<Bookmark>?) { notifyDataSetChanged() } override fun onItemRangeChanged(p0: ObservableArrayList<Bookmark>?, p1: Int, p2: Int) { notifyDataSetChanged() } } init { entryList.addOnListChangedCallback(entryListChangedCallback) } fun releaseCallback() { entryList.removeOnListChangedCallback(entryListChangedCallback) } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? { val binding: ListItemEntryBinding if (convertView == null) { binding = ListItemEntryBinding.inflate(inflater, parent, false) binding.viewModel = injector.entryListItemViewModel() } else { binding = DataBindingUtil.getBinding(convertView) } binding.viewModel!!.entry.set(getItem(position)) binding.executePendingBindings() return binding.root } interface Injector { fun entryListItemViewModel(): EntryListItemViewModel } }
apache-2.0
822584d0e62931d7d450715eaef535ec
35.183908
123
0.713151
4.843077
false
false
false
false
jwren/intellij-community
python/src/com/jetbrains/python/sdk/add/PyAddSdkDialog.kt
2
13723
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.sdk.add import com.intellij.CommonBundle import com.intellij.openapi.Disposable import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.Splitter import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.ui.popup.ListItemDescriptorAdapter import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.UserDataHolder import com.intellij.openapi.util.UserDataHolderBase import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.JBCardLayout import com.intellij.ui.components.JBList import com.intellij.ui.popup.list.GroupedItemsListRenderer import com.intellij.util.ExceptionUtil import com.intellij.util.PlatformUtils import com.intellij.util.ui.JBUI import com.jetbrains.python.PyBundle import com.jetbrains.python.packaging.PyExecutionException import com.jetbrains.python.sdk.* import com.jetbrains.python.sdk.add.PyAddSdkDialogFlowAction.* import com.jetbrains.python.sdk.conda.PyCondaSdkCustomizer import icons.PythonIcons import java.awt.CardLayout import java.awt.event.ActionEvent import java.util.function.Consumer import javax.swing.Action import javax.swing.JComponent import javax.swing.JPanel /** * The dialog may look like the normal dialog with OK, Cancel and Help buttons * or the wizard dialog with Next, Previous, Finish, Cancel and Help buttons. * * Use [show] to instantiate and show the dialog. * * @author vlan */ class PyAddSdkDialog private constructor(private val project: Project?, private val module: Module?, private val existingSdks: List<Sdk>) : DialogWrapper(project) { /** * This is the main panel that supplies sliding effect for the wizard states. */ private val mainPanel: JPanel = JPanel(JBCardLayout()) private var selectedPanel: PyAddSdkView? = null private val context = UserDataHolderBase() private var panels: List<PyAddSdkView> = emptyList() init { title = PyBundle.message("python.sdk.add.python.interpreter.title") } override fun createCenterPanel(): JComponent { val sdks = existingSdks .filter { it.sdkType is PythonSdkType && !PythonSdkUtil.isInvalid(it) } .sortedWith(PreferredSdkComparator()) val panels = createPanels(sdks).toMutableList() val extendedPanels = PyAddSdkProvider.EP_NAME.extensions .mapNotNull { it.safeCreateView(project = project, module = module, existingSdks = existingSdks, context=context) .registerIfDisposable() } panels.addAll(extendedPanels) mainPanel.add(SPLITTER_COMPONENT_CARD_PANE, createCardSplitter(panels)) return mainPanel } private fun createPanels(sdks: List<Sdk>): List<PyAddSdkView> { val venvPanel = createVirtualEnvPanel(project, module, sdks) val condaPanel = createAnacondaPanel(project, module) val systemWidePanel = PyAddSystemWideInterpreterPanel(project, module, existingSdks, context) return if (PyCondaSdkCustomizer.instance.preferCondaEnvironments) { listOf(condaPanel, venvPanel, systemWidePanel) } else { listOf(venvPanel, condaPanel, systemWidePanel) } } private fun <T> T.registerIfDisposable(): T = apply { (this as? Disposable)?.let { Disposer.register(disposable, it) } } private var navigationPanelCardLayout: CardLayout? = null private var southPanel: JPanel? = null override fun createSouthPanel(): JComponent { val regularDialogSouthPanel = super.createSouthPanel() val wizardDialogSouthPanel = createWizardSouthPanel() navigationPanelCardLayout = CardLayout() val result = JPanel(navigationPanelCardLayout).apply { add(regularDialogSouthPanel, REGULAR_CARD_PANE) add(wizardDialogSouthPanel, WIZARD_CARD_PANE) } southPanel = result return result } private fun createWizardSouthPanel(): JPanel { assert(value = style != DialogStyle.COMPACT, lazyMessage = { "${PyAddSdkDialog::class.java} is not ready for ${DialogStyle.COMPACT} dialog style" }) return doCreateSouthPanel(leftButtons = listOf(), rightButtons = listOf(previousButton.value, nextButton.value, cancelButton.value)) } @Suppress("SuspiciousPackagePrivateAccess") //todo: remove suppression when everyone update to IDEA where IDEA-210216 is fixed private val nextAction: Action = object : DialogWrapperAction(PyBundle.message("python.sdk.next")) { override fun doAction(e: ActionEvent) { selectedPanel?.let { if (it.actions.containsKey(NEXT)) onNext() else if (it.actions.containsKey(FINISH)) { onFinish() } } } } private val nextButton = lazy { createJButtonForAction(nextAction) } @Suppress("SuspiciousPackagePrivateAccess") private val previousAction = object : DialogWrapperAction(PyBundle.message("python.sdk.previous")) { override fun doAction(e: ActionEvent) = onPrevious() } private val previousButton = lazy { createJButtonForAction(previousAction) } private val cancelButton = lazy { createJButtonForAction(cancelAction) } override fun postponeValidation(): Boolean = false override fun doValidateAll(): List<ValidationInfo> = selectedPanel?.validateAll() ?: emptyList() fun getOrCreateSdk(): Sdk? = selectedPanel?.getOrCreateSdk() private fun createCardSplitter(panels: List<PyAddSdkView>): Splitter { this.panels = panels return Splitter(false, 0.25f).apply { val cardLayout = CardLayout() val cardPanel = JPanel(cardLayout).apply { preferredSize = JBUI.size(640, 480) for (panel in panels) { add(panel.component, panel.panelName) panel.addStateListener(object : PyAddSdkStateListener { override fun onComponentChanged() { show(mainPanel, panel.component) selectedPanel?.let { updateWizardActionButtons(it) } } override fun onActionsStateChanged() { selectedPanel?.let { updateWizardActionButtons(it) } } }) } } val cardsList = JBList(panels).apply { val descriptor = object : ListItemDescriptorAdapter<PyAddSdkView>() { override fun getTextFor(value: PyAddSdkView) = StringUtil.toTitleCase(value.panelName) override fun getIconFor(value: PyAddSdkView) = value.icon } cellRenderer = object : GroupedItemsListRenderer<PyAddSdkView>(descriptor) { override fun createItemComponent() = super.createItemComponent().apply { border = JBUI.Borders.empty(4, 4, 4, 10) } } addListSelectionListener { selectedPanel = selectedValue cardLayout.show(cardPanel, selectedValue.panelName) southPanel?.let { if (selectedValue.actions.containsKey(NEXT)) { navigationPanelCardLayout?.show(it, WIZARD_CARD_PANE) rootPane.defaultButton = nextButton.value updateWizardActionButtons(selectedValue) } else { navigationPanelCardLayout?.show(it, REGULAR_CARD_PANE) rootPane.defaultButton = getButton(okAction) } } selectedValue.onSelected() } selectedPanel = panels.getOrNull(0) selectedIndex = 0 } firstComponent = cardsList secondComponent = cardPanel } } private fun createVirtualEnvPanel(project: Project?, module: Module?, existingSdks: List<Sdk>): PyAddSdkPanel { val newVirtualEnvPanel = when { allowCreatingNewEnvironments(project) -> PyAddNewVirtualEnvPanel(project, module, existingSdks, null, context) else -> null } val existingVirtualEnvPanel = PyAddExistingVirtualEnvPanel(project, module, existingSdks, null, context) val panels = listOf(newVirtualEnvPanel, existingVirtualEnvPanel) .filterNotNull() val defaultPanel = when { detectVirtualEnvs(module, existingSdks, context).any { it.isAssociatedWithModule(module) } -> existingVirtualEnvPanel newVirtualEnvPanel != null -> newVirtualEnvPanel else -> existingVirtualEnvPanel } return PyAddSdkGroupPanel(PyBundle.messagePointer("python.add.sdk.panel.name.virtualenv.environment"), PythonIcons.Python.Virtualenv, panels, defaultPanel) } private fun createAnacondaPanel(project: Project?, module: Module?): PyAddSdkPanel { val newCondaEnvPanel = when { allowCreatingNewEnvironments(project) -> PyAddNewCondaEnvPanel(project, module, existingSdks, null) else -> null } val panels = listOf(newCondaEnvPanel, PyAddExistingCondaEnvPanel(project, module, existingSdks, null, context)) .filterNotNull() val defaultPanel = if (PyCondaSdkCustomizer.instance.preferExistingEnvironments) panels[1] else panels[0] return PyAddSdkGroupPanel(PyBundle.messagePointer("python.add.sdk.panel.name.conda.environment"), PythonIcons.Python.Anaconda, panels, defaultPanel) } /** * Navigates to the next step of the current wizard view. */ private fun onNext() { selectedPanel?.let { it.next() // sliding effect swipe(mainPanel, it.component, JBCardLayout.SwipeDirection.FORWARD) updateWizardActionButtons(it) } } /** * Navigates to the previous step of the current wizard view. */ private fun onPrevious() { selectedPanel?.let { it.previous() // sliding effect if (it.actions.containsKey(PREVIOUS)) { val stepContent = it.component val stepContentName = stepContent.hashCode().toString() (mainPanel.layout as JBCardLayout).swipe(mainPanel, stepContentName, JBCardLayout.SwipeDirection.BACKWARD) } else { // this is the first wizard step (mainPanel.layout as JBCardLayout).swipe(mainPanel, SPLITTER_COMPONENT_CARD_PANE, JBCardLayout.SwipeDirection.BACKWARD) } updateWizardActionButtons(it) } } /** * Tries to create the SDK and closes the dialog if the creation succeeded. * * @see [doOKAction] */ override fun doOKAction() { try { selectedPanel?.complete() } catch (e: CreateSdkInterrupted) { return } catch (e: Exception) { val cause = ExceptionUtil.findCause(e, PyExecutionException::class.java) if (cause == null) { Messages.showErrorDialog(e.localizedMessage, CommonBundle.message("title.error")) } else { showProcessExecutionErrorDialog(project, cause) } return } close(OK_EXIT_CODE) } private fun onFinish() { doOKAction() } private fun updateWizardActionButtons(it: PyAddSdkView) { previousButton.value.isEnabled = false it.actions.forEach { (action, isEnabled) -> val actionButton = when (action) { PREVIOUS -> previousButton.value NEXT -> nextButton.value.apply { text = PyBundle.message("python.sdk.next") } FINISH -> nextButton.value.apply { text = PyBundle.message("python.sdk.finish") } else -> null } actionButton?.isEnabled = isEnabled } } companion object { private val LOG: Logger = Logger.getInstance(PyAddSdkDialog::class.java) private fun allowCreatingNewEnvironments(project: Project?) = project != null || !PlatformUtils.isPyCharm() || PlatformUtils.isPyCharmEducational() private const val SPLITTER_COMPONENT_CARD_PANE = "Splitter" private const val REGULAR_CARD_PANE = "Regular" private const val WIZARD_CARD_PANE = "Wizard" @JvmStatic fun show(project: Project?, module: Module?, existingSdks: List<Sdk>, sdkAddedCallback: Consumer<Sdk?>) { val dialog = PyAddSdkDialog(project = project, module = module, existingSdks = existingSdks) dialog.init() val sdk = if (dialog.showAndGet()) dialog.getOrCreateSdk() else null sdkAddedCallback.accept(sdk) } /** * Fixes the problem when `PyAddDockerSdkProvider.createView` for Docker * and Docker Compose types throws [NoClassDefFoundError] exception when * `org.jetbrains.plugins.remote-run` plugin is disabled. */ private fun PyAddSdkProvider.safeCreateView(project: Project?, module: Module?, existingSdks: List<Sdk>, context:UserDataHolder): PyAddSdkView? { try { return createView(project, module, null, existingSdks, context) } catch (e: NoClassDefFoundError) { LOG.info(e) return null } } } } class CreateSdkInterrupted : Exception()
apache-2.0
328c0f5c515b2b1a909d1bc4114b7c8c
35.304233
128
0.684909
4.789878
false
false
false
false
ZhangQinglian/dcapp
src/main/kotlin/com/zqlite/android/diycode/device/utils/TokenStore.kt
1
2971
/* * Copyright 2017 zhangqinglian * * 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.zqlite.android.diycode.device.utils import android.content.Context import com.zqlite.android.ak47.getSPString import com.zqlite.android.ak47.save import com.zqlite.android.ak47.set import com.zqlite.android.dclib.entiry.Token /** * Created by scott on 2017/8/15. */ object TokenStore { val TOKEN = "tokenStore" val ACCESS_TOKEN_KEY = "access_token_key" val TOKEN_TYPE_KEY = "token_type_key" val EXPIRESIN = "expiresin_key" val FRESH_TOKEN_KEY = "fresh_token_key" val CREATE_AT = "createat_key" val CURRENT_LOGIN = "current_login" val CURRENT_AVATAR_URL = "current_avatar" fun saveToken(context: Context, token: Token) { context.getSharedPreferences(TOKEN, Context.MODE_PRIVATE).save { set(ACCESS_TOKEN_KEY to token.accessToken) set(TOKEN_TYPE_KEY to token.tokenType) set(EXPIRESIN to token.expiresIn) set(FRESH_TOKEN_KEY to token.refreshToken) set(CREATE_AT to token.createdAt) } } fun saveCurrentLogin(context: Context, login: String) { context.getSharedPreferences(TOKEN, Context.MODE_PRIVATE).save { set(CURRENT_LOGIN to login) } } fun getCurrentLogin(context: Context): String { return context.getSPString(TOKEN, CURRENT_LOGIN,"") } fun saveCurrentAvatarUrl(context: Context,avatarUrl:String){ context.getSharedPreferences(TOKEN, Context.MODE_PRIVATE).save { set(CURRENT_AVATAR_URL to avatarUrl) } } fun getCurrentAvatarUrl(context: Context): String { return context.getSPString(TOKEN, CURRENT_AVATAR_URL,"") } fun getAccessToken(context: Context): String { return context.getSPString(TOKEN, ACCESS_TOKEN_KEY,"") } fun shouldLogin(context: Context): Boolean { val accessToken = context.getSPString(TOKEN, ACCESS_TOKEN_KEY,"") return accessToken.isEmpty() } fun logout(context: Context){ context.getSharedPreferences(TOKEN, Context.MODE_PRIVATE).save { set(ACCESS_TOKEN_KEY to "") set(TOKEN_TYPE_KEY to "") set(EXPIRESIN to "") set(FRESH_TOKEN_KEY to "") set(CREATE_AT to "") set(CURRENT_LOGIN to "") set(CURRENT_AVATAR_URL to "") } } }
apache-2.0
1cd70746e573cb6e3a95a192ea057653
29.326531
78
0.655335
4.009447
false
false
false
false
dahlstrom-g/intellij-community
plugins/gradle/src/org/jetbrains/plugins/gradle/dependency/analyzer/GradleDependencyAnalyzerAction.kt
1
4096
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.dependency.analyzer import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformCoreDataKeys import com.intellij.openapi.externalSystem.dependency.analyzer.* import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys import com.intellij.openapi.externalSystem.model.project.ModuleData import com.intellij.openapi.externalSystem.model.project.ProjectData import com.intellij.openapi.externalSystem.model.project.dependencies.ArtifactDependencyNode import com.intellij.openapi.externalSystem.model.project.dependencies.DependencyScopeNode import com.intellij.openapi.externalSystem.model.project.dependencies.ProjectDependencyNode import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.externalSystem.view.ExternalSystemNode import com.intellij.openapi.externalSystem.view.ModuleNode import com.intellij.openapi.externalSystem.view.ProjectNode import com.intellij.openapi.module.Module import org.jetbrains.plugins.gradle.util.GradleConstants import org.jetbrains.plugins.gradle.util.GradleUtil class ViewDependencyAnalyzerAction : AbstractDependencyAnalyzerAction<ExternalSystemNode<*>>() { override fun getSystemId(e: AnActionEvent) = GradleConstants.SYSTEM_ID override fun getSelectedData(e: AnActionEvent): ExternalSystemNode<*>? { return e.getData(ExternalSystemDataKeys.SELECTED_NODES)?.firstOrNull() } override fun getModule(e: AnActionEvent, selectedData: ExternalSystemNode<*>): Module? { val project = e.project ?: return null return selectedData.findNode(ModuleNode::class.java)?.data ?.let { GradleUtil.findGradleModule(project, it) } ?: selectedData.findNode(ProjectNode::class.java)?.data ?.let { GradleUtil.findGradleModule(project, it) } } override fun getDependencyData(e: AnActionEvent, selectedData: ExternalSystemNode<*>): DependencyAnalyzerDependency.Data? { return when (val data = selectedData.data) { is ProjectData -> DAModule(data.internalName) is ModuleData -> DAModule(data.moduleName) else -> when (val node = selectedData.dependencyNode) { is ProjectDependencyNode -> DAModule(node.projectName) is ArtifactDependencyNode -> DAArtifact(node.group, node.module, node.version) else -> null } } } override fun getDependencyScope(e: AnActionEvent, selectedData: ExternalSystemNode<*>): String? { return selectedData.findDependencyNode(DependencyScopeNode::class.java)?.scope } } class ToolbarDependencyAnalyzerAction : DependencyAnalyzerAction() { private val viewAction = ViewDependencyAnalyzerAction() override fun getSystemId(e: AnActionEvent) = GradleConstants.SYSTEM_ID override fun isEnabledAndVisible(e: AnActionEvent) = true override fun setSelectedState(view: DependencyAnalyzerView, e: AnActionEvent) { viewAction.setSelectedState(view, e) } override fun getActionUpdateThread() = ActionUpdateThread.BGT } class ProjectViewDependencyAnalyzerAction : AbstractDependencyAnalyzerAction<Module>() { override fun getSystemId(e: AnActionEvent) = GradleConstants.SYSTEM_ID override fun getSelectedData(e: AnActionEvent): Module? { val module = e.getData(PlatformCoreDataKeys.MODULE) ?: return null if (ExternalSystemApiUtil.isExternalSystemAwareModule(GradleConstants.SYSTEM_ID, module)) { return module } return null } override fun getModule(e: AnActionEvent, selectedData: Module): Module { return selectedData } override fun getDependencyData(e: AnActionEvent, selectedData: Module): DependencyAnalyzerDependency.Data { return DAModule(selectedData.name) } override fun getDependencyScope(e: AnActionEvent, selectedData: Module) = null override fun getActionUpdateThread() = ActionUpdateThread.BGT }
apache-2.0
9057a13428c05e8975ece3ebc5c90cb2
43.043011
158
0.791504
4.864608
false
false
false
false
apollographql/apollo-android
apollo-ast/src/main/kotlin/com/apollographql/apollo3/ast/internal/InputValueValidationScope.kt
1
6568
package com.apollographql.apollo3.ast.internal import com.apollographql.apollo3.ast.GQLBooleanValue import com.apollographql.apollo3.ast.GQLEnumTypeDefinition import com.apollographql.apollo3.ast.GQLEnumValue import com.apollographql.apollo3.ast.GQLFloatValue import com.apollographql.apollo3.ast.GQLInputObjectTypeDefinition import com.apollographql.apollo3.ast.GQLIntValue import com.apollographql.apollo3.ast.GQLListType import com.apollographql.apollo3.ast.GQLListValue import com.apollographql.apollo3.ast.GQLNamedType import com.apollographql.apollo3.ast.GQLNonNullType import com.apollographql.apollo3.ast.GQLNullValue import com.apollographql.apollo3.ast.GQLObjectField import com.apollographql.apollo3.ast.GQLObjectValue import com.apollographql.apollo3.ast.GQLScalarTypeDefinition import com.apollographql.apollo3.ast.GQLStringValue import com.apollographql.apollo3.ast.GQLType import com.apollographql.apollo3.ast.GQLValue import com.apollographql.apollo3.ast.GQLVariableValue import com.apollographql.apollo3.ast.Issue import com.apollographql.apollo3.ast.VariableReference import com.apollographql.apollo3.ast.isDeprecated import com.apollographql.apollo3.ast.pretty import com.apollographql.apollo3.ast.toUtf8 internal fun ValidationScope.validateAndCoerceValue(value: GQLValue, expectedType: GQLType): GQLValue { if (value is GQLVariableValue) { if (this !is VariableReferencesScope) { registerIssue( "Variable '${value.name}' used in non-variable context", value.sourceLocation, ) } else { variableReferences.add(VariableReference(value, expectedType)) } return value } else if (value is GQLNullValue) { if (expectedType is GQLNonNullType) { registerIssue(value, expectedType) return value } // null is always valid in a nullable position return value } when (expectedType) { is GQLNonNullType -> { return validateAndCoerceValue(value, expectedType.type) } is GQLListType -> { val coercedValue = if (value !is GQLListValue) { GQLListValue(sourceLocation = value.sourceLocation, listOf(value)) } else { value } return GQLListValue( values = coercedValue.values.map { validateAndCoerceValue(it, expectedType.type) } ) } is GQLNamedType -> { when (val expectedTypeDefinition = typeDefinitions[expectedType.name]) { is GQLInputObjectTypeDefinition -> { return validateAndCoerceInputObject(value, expectedTypeDefinition) } is GQLScalarTypeDefinition -> { if (!expectedTypeDefinition.isBuiltIn()) { // custom scalar types are passed through return value } return validateAndCoerceScalar(value, expectedType) } is GQLEnumTypeDefinition -> { return validateAndCoerceEnum(value, expectedTypeDefinition) } else -> { registerIssue("Value cannot be of non-input type ${expectedType.pretty()}", value.sourceLocation) return value } } } } } private fun ValidationScope.registerIssue(value: GQLValue, expectedType: GQLType) { registerIssue(message = "Value `${value.toUtf8()}` cannot be used in position expecting `${expectedType.pretty()}`", sourceLocation = value.sourceLocation) } private fun ValidationScope.validateAndCoerceInputObject(value: GQLValue, expectedTypeDefinition: GQLInputObjectTypeDefinition): GQLValue { val expectedType = GQLNamedType(name = expectedTypeDefinition.name) if (value !is GQLObjectValue) { registerIssue(value, expectedType) return value } // 3.10 All required input fields must have a value expectedTypeDefinition.inputFields.forEach { inputValueDefinition -> if (inputValueDefinition.type is GQLNonNullType && inputValueDefinition.defaultValue == null && value.fields.firstOrNull { it.name == inputValueDefinition.name } == null ) { registerIssue(message = "No value passed for required inputField ${inputValueDefinition.name}", sourceLocation = value.sourceLocation) } } return GQLObjectValue(fields = value.fields.mapNotNull { field -> val inputField = expectedTypeDefinition.inputFields.firstOrNull { it.name == field.name } if (inputField == null) { // 3.10 Input values coercion: extra values are errors registerIssue(message = "Field ${field.name} is not defined by ${expectedType.pretty()}", sourceLocation = field.sourceLocation) return@mapNotNull null } GQLObjectField( name = field.name, value = validateAndCoerceValue(field.value, inputField.type) ) }) } private fun ValidationScope.validateAndCoerceEnum(value: GQLValue, enumTypeDefinition: GQLEnumTypeDefinition): GQLValue { val expectedType = GQLNamedType(name = enumTypeDefinition.name) if (value !is GQLEnumValue) { registerIssue(value, expectedType) return value } val enumValue = enumTypeDefinition.enumValues.firstOrNull { it.name == value.value } if (enumValue == null) { registerIssue( message = "Cannot find enum value `${value.value}` of type `${enumTypeDefinition.name}`", sourceLocation = value.sourceLocation ) } else if (enumValue.isDeprecated()) { issues.add(Issue.DeprecatedUsage( message = "Use of deprecated enum value `${value.value}` of type `${enumTypeDefinition.name}`", sourceLocation = value.sourceLocation )) } return value } private fun ValidationScope.validateAndCoerceScalar(value: GQLValue, expectedType: GQLNamedType): GQLValue { return when (expectedType.name) { "Int" -> { if (value !is GQLIntValue) { registerIssue(value, expectedType) } value } "Float" -> { when (value) { is GQLFloatValue -> value // Int get coerced to floats is GQLIntValue -> GQLFloatValue(value = value.value.toDouble()) else -> { registerIssue(value, expectedType) value } } } "String" -> { if (value !is GQLStringValue) { registerIssue(value, expectedType) } value } "Boolean" -> { if (value !is GQLBooleanValue) { registerIssue(value, expectedType) } value } "ID" -> { // 3.5.5 ID can be either string or int if (value !is GQLStringValue && value !is GQLIntValue) { registerIssue(value, expectedType) } value } else -> { registerIssue(value, expectedType) value } } }
mit
c132880b24fd4e4fb882fdaff1255e6a
34.122995
157
0.700974
4.443843
false
false
false
false
androidx/androidx
compose/integration-tests/demos/src/main/java/androidx/compose/integration/demos/DemoActivity.kt
3
10190
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.integration.demos import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.View import android.view.Window import androidx.activity.OnBackPressedCallback import androidx.activity.OnBackPressedDispatcher import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.integration.demos.common.ActivityDemo import androidx.compose.integration.demos.common.Demo import androidx.compose.integration.demos.common.DemoCategory import androidx.compose.integration.demos.settings.DecorFitsSystemWindowsEffect import androidx.compose.integration.demos.settings.DecorFitsSystemWindowsSetting import androidx.compose.integration.demos.settings.DynamicThemeSetting import androidx.compose.integration.demos.settings.SoftInputModeEffect import androidx.compose.integration.demos.settings.SoftInputModeSetting import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.Saver import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.focus.FocusManager import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat import androidx.fragment.app.FragmentActivity /** * Main [Activity] containing all Compose related demos. * * You can pass a specific demo's name as string extra "demoname" to launch this demo only. * Read this module's readme to learn more! */ @Suppress("DEPRECATION") class DemoActivity : FragmentActivity() { lateinit var hostView: View lateinit var focusManager: FocusManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val rootDemo = when (val demoName = intent.getStringExtra(DEMO_NAME)) { null -> AllDemosCategory else -> requireDemo(demoName, Navigator.findDemo(AllDemosCategory, demoName)) } ComposeView(this).also { setContentView(it) }.setContent { hostView = LocalView.current focusManager = LocalFocusManager.current val activityStarter = fun(demo: ActivityDemo<*>) { startActivity(Intent(this, demo.activityClass.java)) } val navigator = rememberSaveable( saver = Navigator.Saver(rootDemo, onBackPressedDispatcher, activityStarter) ) { Navigator(rootDemo, onBackPressedDispatcher, activityStarter) } SoftInputModeEffect(SoftInputModeSetting.asState().value, window) DecorFitsSystemWindowsEffect( DecorFitsSystemWindowsSetting.asState().value, hostView, window ) DemoTheme(DynamicThemeSetting.asState().value, this.hostView, window) { val filteringMode = rememberSaveable( saver = FilterMode.Saver(onBackPressedDispatcher) ) { FilterMode(onBackPressedDispatcher) } val onStartFiltering = { filteringMode.isFiltering = true } val onEndFiltering = { filteringMode.isFiltering = false } DemoApp( currentDemo = navigator.currentDemo, backStackTitle = navigator.backStackTitle, isFiltering = filteringMode.isFiltering, onStartFiltering = onStartFiltering, onEndFiltering = onEndFiltering, onNavigateToDemo = { demo -> if (filteringMode.isFiltering) { onEndFiltering() navigator.popAll() } navigator.navigateTo(demo) }, canNavigateUp = !navigator.isRoot, onNavigateUp = { onBackPressed() }, launchSettings = { startActivity(Intent(this, DemoSettingsActivity::class.java)) } ) } } } companion object { const val DEMO_NAME = "demoname" internal fun requireDemo(demoName: String, demo: Demo?) = requireNotNull(demo) { "No demo called \"$demoName\" could be found." } } } @Composable private fun DemoTheme( isDynamicThemeOn: Boolean, view: View, window: Window, content: @Composable () -> Unit ) { val isDarkMode = isSystemInDarkTheme() @Suppress("NewApi") val colorScheme = if (isDynamicThemeOn) { val context = LocalContext.current if (isDarkMode) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } else { if (isDarkMode) darkColorScheme() else lightColorScheme() } SideEffect { WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !isDarkMode WindowCompat.getInsetsController(window, view).isAppearanceLightNavigationBars = !isDarkMode window.statusBarColor = Color.Transparent.toArgb() window.navigationBarColor = Color.Transparent.toArgb() } MaterialTheme(colorScheme = colorScheme, content = content) } private class Navigator private constructor( private val backDispatcher: OnBackPressedDispatcher, private val launchActivityDemo: (ActivityDemo<*>) -> Unit, private val rootDemo: Demo, initialDemo: Demo, private val backStack: MutableList<Demo> ) { constructor( rootDemo: Demo, backDispatcher: OnBackPressedDispatcher, launchActivityDemo: (ActivityDemo<*>) -> Unit ) : this(backDispatcher, launchActivityDemo, rootDemo, rootDemo, mutableListOf<Demo>()) private val onBackPressed = object : OnBackPressedCallback(false) { override fun handleOnBackPressed() { popBackStack() } }.apply { isEnabled = !isRoot backDispatcher.addCallback(this) } private var _currentDemo by mutableStateOf(initialDemo) var currentDemo: Demo get() = _currentDemo private set(value) { _currentDemo = value onBackPressed.isEnabled = !isRoot } val isRoot: Boolean get() = backStack.isEmpty() val backStackTitle: String get() = (backStack.drop(1) + currentDemo).joinToString(separator = " > ") { it.title } fun navigateTo(demo: Demo) { if (demo is ActivityDemo<*>) { launchActivityDemo(demo) } else { backStack.add(currentDemo) currentDemo = demo } } fun popAll() { if (!isRoot) { backStack.clear() currentDemo = rootDemo } } private fun popBackStack() { currentDemo = backStack.removeAt(backStack.lastIndex) } companion object { fun Saver( rootDemo: Demo, backDispatcher: OnBackPressedDispatcher, launchActivityDemo: (ActivityDemo<*>) -> Unit ): Saver<Navigator, *> = listSaver<Navigator, String>( save = { navigator -> (navigator.backStack + navigator.currentDemo).map { it.title } }, restore = { restored -> require(restored.isNotEmpty()) val backStack = restored.mapTo(mutableListOf()) { requireNotNull(findDemo(rootDemo, it)) } val initial = backStack.removeAt(backStack.lastIndex) Navigator(backDispatcher, launchActivityDemo, rootDemo, initial, backStack) } ) fun findDemo(demo: Demo, title: String): Demo? { if (demo.title == title) { return demo } if (demo is DemoCategory) { demo.demos.forEach { child -> findDemo(child, title) ?.let { return it } } } return null } } } private class FilterMode(backDispatcher: OnBackPressedDispatcher, initialValue: Boolean = false) { private var _isFiltering by mutableStateOf(initialValue) private val onBackPressed = object : OnBackPressedCallback(false) { override fun handleOnBackPressed() { isFiltering = false } }.apply { isEnabled = initialValue backDispatcher.addCallback(this) } var isFiltering get() = _isFiltering set(value) { _isFiltering = value onBackPressed.isEnabled = value } companion object { fun Saver(backDispatcher: OnBackPressedDispatcher) = Saver<FilterMode, Boolean>( save = { it.isFiltering }, restore = { FilterMode(backDispatcher, it) } ) } }
apache-2.0
c70383d9d50586a927748577fb6c885f
35.007067
100
0.64524
5.228322
false
false
false
false
androidx/androidx
compose/ui/ui-text/src/test/java/androidx/compose/ui/text/style/LineHeightStyleTest.kt
3
3565
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:OptIn(ExperimentalTextApi::class) package androidx.compose.ui.text.style import androidx.compose.ui.text.ExperimentalTextApi import androidx.compose.ui.text.style.LineHeightStyle.Trim import androidx.compose.ui.text.style.LineHeightStyle.Alignment import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class LineHeightStyleTest { @Test fun equals_returns_false_for_different_alignment() { val lineHeightStyle = LineHeightStyle( alignment = Alignment.Center, trim = Trim.None ) val otherLineHeightStyle = LineHeightStyle( alignment = Alignment.Bottom, trim = Trim.None ) assertThat(lineHeightStyle.equals(otherLineHeightStyle)).isFalse() } @Test fun equals_returns_false_for_different_trim() { val lineHeightStyle = LineHeightStyle( alignment = Alignment.Center, trim = Trim.None ) val otherLineHeightStyle = LineHeightStyle( alignment = Alignment.Center, trim = Trim.Both ) assertThat(lineHeightStyle.equals(otherLineHeightStyle)).isFalse() } @Test fun equals_returns_true_for_same_attributes() { val lineHeightStyle = LineHeightStyle( alignment = Alignment.Center, trim = Trim.FirstLineTop ) val otherLineHeightStyle = LineHeightStyle( alignment = Alignment.Center, trim = Trim.FirstLineTop ) assertThat(lineHeightStyle.equals(otherLineHeightStyle)).isTrue() } @Test fun hashCode_is_different_for_different_alignment() { val lineHeightStyle = LineHeightStyle( alignment = Alignment.Center, trim = Trim.None ) val otherLineHeightStyle = LineHeightStyle( alignment = Alignment.Bottom, trim = Trim.Both ) assertThat(lineHeightStyle.hashCode()).isNotEqualTo(otherLineHeightStyle.hashCode()) } @Test fun hashCode_is_different_for_different_trim() { val lineHeightStyle = LineHeightStyle( alignment = Alignment.Center, trim = Trim.None ) val otherLineHeightStyle = LineHeightStyle( alignment = Alignment.Center, trim = Trim.Both ) assertThat(lineHeightStyle.hashCode()).isNotEqualTo(otherLineHeightStyle.hashCode()) } @Test fun hashCode_is_same_for_same_attributes() { val lineHeightStyle = LineHeightStyle( alignment = Alignment.Center, trim = Trim.Both ) val otherLineHeightStyle = LineHeightStyle( alignment = Alignment.Center, trim = Trim.Both ) assertThat(lineHeightStyle.hashCode()).isEqualTo(otherLineHeightStyle.hashCode()) } }
apache-2.0
7f973c7e5daed4861e64ceccfc92718b
32.018519
92
0.658626
4.944521
false
true
false
false
nimakro/tornadofx
src/main/java/tornadofx/Workspace.kt
1
17002
package tornadofx import javafx.beans.property.ObjectProperty import javafx.beans.property.SimpleBooleanProperty import javafx.beans.property.SimpleIntegerProperty import javafx.beans.property.SimpleObjectProperty import javafx.collections.FXCollections import javafx.geometry.Pos import javafx.geometry.Side import javafx.scene.Node import javafx.scene.Parent import javafx.scene.control.Button import javafx.scene.control.TabPane import javafx.scene.control.ToolBar import javafx.scene.input.KeyCombination import javafx.scene.layout.BorderPane import javafx.scene.layout.HBox import javafx.scene.layout.StackPane import tornadofx.Workspace.NavigationMode.Stack import kotlin.reflect.KClass import kotlin.reflect.full.isSubclassOf class HeadingContainer : HBox() { init { addClass("heading-container") } } class WorkspaceArea : BorderPane() { internal var dynamicComponentMode: Boolean = false internal val dynamicComponents = FXCollections.observableArrayList<Node>() var header: ToolBar by singleAssign() init { addClass("workspace") } } open class Workspace(title: String = "Workspace", navigationMode: NavigationMode = Stack) : View(title) { var refreshButton: Button by singleAssign() var saveButton: Button by singleAssign() var createButton: Button by singleAssign() var deleteButton: Button by singleAssign() var backButton: Button by singleAssign() var forwardButton: Button by singleAssign() enum class NavigationMode { Stack, Tabs } val navigationModeProperty: ObjectProperty<NavigationMode> = SimpleObjectProperty(navigationMode) var navigationMode by navigationModeProperty val viewStack = FXCollections.observableArrayList<UIComponent>() val maxViewStackDepthProperty = SimpleIntegerProperty(DefaultViewStackDepth) var maxViewStackDepth by maxViewStackDepthProperty val headingContainer = HeadingContainer() val tabContainer = TabPane().addClass("editor-container") val stackContainer = StackPane().addClass("editor-container") val contentContainerProperty = SimpleObjectProperty<Parent>(stackContainer) var contentContainer by contentContainerProperty val showHeadingLabelProperty = SimpleBooleanProperty(true) var showHeadingLabel by showHeadingLabelProperty val dockedComponentProperty: ObjectProperty<UIComponent> = SimpleObjectProperty() val dockedComponent: UIComponent? get() = dockedComponentProperty.value private val viewPos = integerBinding(viewStack, dockedComponentProperty) { viewStack.indexOf(dockedComponent) } val leftDrawer: Drawer get() = (root.left as? Drawer) ?: Drawer(Side.LEFT, false, false).also { root.left = it it.toFront() } val rightDrawer: Drawer get() = (root.right as? Drawer) ?: Drawer(Side.RIGHT, false, false).also { root.right = it it.toFront() } val bottomDrawer: Drawer get() = (root.bottom as? Drawer) ?: Drawer(Side.BOTTOM, false, false).also { root.bottom = it it.toFront() } companion object { val activeWorkspaces = FXCollections.observableArrayList<Workspace>() val DefaultViewStackDepth = 10 fun closeAll() { activeWorkspaces.forEach(Workspace::close) } var defaultSavable = true var defaultDeletable = true var defaultRefreshable = true var defaultCloseable = true var defaultComplete = true var defaultCreatable = true init { importStylesheet("/tornadofx/workspace.css") } } fun disableNavigation() { viewStack.clear() maxViewStackDepth = 0 } private fun registerWorkspaceAccelerators() { accelerators[KeyCombination.valueOf("Ctrl+S")] = { if (!saveButton.isDisable) onSave() } accelerators[KeyCombination.valueOf("Ctrl+N")] = { if (!createButton.isDisable) onSave() } accelerators[KeyCombination.valueOf("Ctrl+R")] = { if (!refreshButton.isDisable) onRefresh() } accelerators[KeyCombination.valueOf("F5")] = { if (!refreshButton.isDisable) onRefresh() } } override fun onDock() { activeWorkspaces += this } override fun onUndock() { activeWorkspaces -= this } override val root = WorkspaceArea().apply { top { vbox { header = toolbar { addClass("header") // Force the container to retain pos center even when it's resized (hack to make ToolBar behave) skinProperty().onChange { (lookup(".container") as? HBox)?.apply { alignment = Pos.CENTER_LEFT alignmentProperty().onChange { if (it != Pos.CENTER_LEFT) alignment = Pos.CENTER_LEFT } } } button { addClass("icon-only") backButton = this graphic = label { addClass("icon", "back") } action { if (dockedComponent?.onNavigateBack() ?: true) { navigateBack() } } disableProperty().bind(booleanBinding(viewPos, viewStack) { value < 1 }) } button { addClass("icon-only") forwardButton = this graphic = label { addClass("icon", "forward") } action { if (dockedComponent?.onNavigateForward() ?: true) { navigateForward() } } disableProperty().bind(booleanBinding(viewPos, viewStack) { value == viewStack.size - 1 }) } button { addClass("icon-only") refreshButton = this isDisable = true graphic = label { addClass("icon", "refresh") } action { onRefresh() } } button { addClass("icon-only") saveButton = this isDisable = true graphic = label { addClass("icon", "save") } action { onSave() } } button { addClass("icon-only") createButton = this isDisable = true graphic = label { addClass("icon", "create") } action { onCreate() } } button { addClass("icon-only") deleteButton = this isDisable = true graphic = label { addClass("icon", "delete") } action { onDelete() } } add(headingContainer) spacer() } } } } val header: ToolBar get() = root.header fun navigateForward(): Boolean { if (!forwardButton.isDisabled) { dock(viewStack[viewPos.get() + 1], false) return true } return false } fun navigateBack(): Boolean { if (!backButton.isDisabled) { dock(viewStack[viewPos.get() - 1], false) return true } return false } init { // @Suppress("LeakingThis") // if (!scope.hasActiveWorkspace) scope.workspaceInstance = this navigationModeProperty.addListener { _, ov, nv -> navigationModeChanged(ov, nv) } tabContainer.tabs.onChange { change -> while (change.next()) { if (change.wasRemoved()) { change.removed.forEach { if (it == dockedComponent) { titleProperty.unbind() refreshButton.disableProperty().unbind() saveButton.disableProperty().unbind() createButton.disableProperty().unbind() deleteButton.disableProperty().unbind() } } } if (change.wasAdded()) { change.addedSubList.forEach { it.content.properties["tornadofx.tab"] = it } } } } tabContainer.selectionModel.selectedItemProperty().addListener { observableValue, ov, nv -> val newCmp = nv?.content?.uiComponent<UIComponent>() val oldCmp = ov?.content?.uiComponent<UIComponent>() if (newCmp != null && newCmp != dockedComponent) { setAsCurrentlyDocked(newCmp) } if (oldCmp != newCmp) oldCmp?.callOnUndock() if (newCmp == null) { headingContainer.children.clear() clearDynamicComponents() dockedComponentProperty.value = null } } dockedComponentProperty.onChange { child -> if (child != null) { inDynamicComponentMode { if (contentContainer == stackContainer) { tabContainer.tabs.clear() stackContainer.clear() stackContainer += child } else { stackContainer.clear() var tab = tabContainer.tabs.find { it.content == child.root } if (tab == null) { tabContainer += child tab = tabContainer.tabs.last() } else { child.callOnDock() } tabContainer.selectionModel.select(tab) } } } } navigationModeChanged(null, navigationMode) registerWorkspaceAccelerators() } private fun navigationModeChanged(oldMode: NavigationMode?, newMode: NavigationMode?) { if (oldMode == null || oldMode != newMode) { contentContainer = if (navigationMode == Stack) stackContainer else tabContainer root.center = contentContainer if (contentContainer == stackContainer && tabContainer.tabs.isNotEmpty()) { tabContainer.tabs.clear() } dockedComponent?.also { dockedComponentProperty.value = null dock(it, true) } } if (newMode == Stack) { if (backButton !in root.header.items) { root.header.items.add(0, backButton) root.header.items.add(1, forwardButton) } } else { root.header.items -= backButton root.header.items -= forwardButton } } override fun onSave() { dockedComponentProperty.value ?.takeIf { it.savable.value } ?.onSave() } override fun onDelete() { dockedComponentProperty.value ?.takeIf { it.deletable.value } ?.onDelete() } override fun onCreate() { dockedComponentProperty.value ?.takeIf { it.creatable.value } ?.onCreate() } override fun onRefresh() { dockedComponentProperty.value ?.takeIf { it.refreshable.value } ?.onRefresh() } inline fun <reified T : UIComponent> dock(scope: Scope = [email protected], params: Map<*, Any?>? = null) = dock(find<T>(scope, params)) inline fun <reified T : UIComponent> dock(scope: Scope = [email protected], vararg params: Pair<*, Any?>) { dock<T>(scope, params.toMap()) } fun dock(child: UIComponent, forward: Boolean = true) { if (child == dockedComponent) return // Remove everything after viewpos if moving forward if (forward) while (viewPos.get() < viewStack.size -1) viewStack.removeAt(viewPos.get() + 1) val addToStack = contentContainer == stackContainer && maxViewStackDepth > 0 && child !in viewStack if (addToStack) viewStack += child setAsCurrentlyDocked(child) // Ensure max stack size while (viewStack.size >= maxViewStackDepth && viewStack.isNotEmpty()) viewStack.removeAt(0) } private fun setAsCurrentlyDocked(child: UIComponent) { titleProperty.bind(child.titleProperty) refreshButton.disableProperty().cleanBind(!child.refreshable) saveButton.disableProperty().cleanBind(!child.savable) createButton.disableProperty().cleanBind(!child.creatable) deleteButton.disableProperty().cleanBind(!child.deletable) headingContainer.children.clear() headingContainer.label(child.headingProperty) { graphicProperty().bind(child.iconProperty) removeWhen(!showHeadingLabelProperty) } clearDynamicComponents() dockedComponentProperty.value = child if (currentWindow?.isShowing != true && currentWindow?.aboutToBeShown != true) FX.log.warning("UIComponent $child docked in invisible workspace $workspace") } private fun clearDynamicComponents() { root.dynamicComponents.forEach(Node::removeFromParent) root.dynamicComponents.clear() } fun inDynamicComponentMode(function: () -> Unit) { root.dynamicComponentMode = true try { function() } finally { root.dynamicComponentMode = false } } /** * Create a new scope and associate it with this Workspace and optionally add one * or more ScopedInstance instances into the scope. The op block operates on the workspace and is passed the new scope. The following example * creates a new scope, injects a Customer Model into it and docks the CustomerEditor * into the Workspace: * * <pre> * workspace.withNewScope(CustomerModel(customer)) { newScope -> * dock<CustomerEditor>(newScope) * } * </pre> */ fun withNewScope(vararg setInScope: ScopedInstance, op: Workspace.(Scope) -> Unit) = op(this, Scope(this, *setInScope)) /** * Create a new scope and associate it with this Workspace and dock the given UIComponent type into * the scope, passing the given parameters on to the UIComponent and optionally injecting the given Injectables into the new scope. */ inline fun <reified T : UIComponent> dockInNewScope(params: Map<*, Any?>, vararg setInScope: ScopedInstance) { withNewScope(*setInScope) { newScope -> dock<T>(newScope, params) } } /** * Create a new scope and associate it with this Workspace and dock the given UIComponent type into * the scope, optionally injecting the given Injectables into the new scope. */ inline fun <reified T : UIComponent> dockInNewScope(vararg setInScope: ScopedInstance) { withNewScope(*setInScope) { newScope -> dock<T>(newScope) } } /** * Create a new scope and associate it with this Workspace and dock the given UIComponent type into * the scope and optionally injecting the given Injectables into the new scope. */ fun <T : UIComponent> dockInNewScope(uiComponent: T, vararg setInScope: ScopedInstance) { withNewScope(*setInScope) { dock(uiComponent) } } /** * Will automatically dock the given [UIComponent] if the [ListMenuItem] is selected. */ inline fun <reified T : UIComponent> ListMenuItem.dockOnSelect() { whenSelected { dock<T>() } } } open class WorkspaceApp(val initiallyDockedView: KClass<out UIComponent>, vararg stylesheet: KClass<out Stylesheet>) : App(Workspace::class, *stylesheet) { init { if (initiallyDockedView.isSubclassOf(Workspace::class)) log.warning("WorkspaceApp called with a Workspace as parameter! Change to App($initiallyDockedView::class) instead.") } override fun onBeforeShow(view: UIComponent) { workspace.dock(find(initiallyDockedView)) } }
apache-2.0
3a3eea0bbff5c8f0285be9b1421d5e5a
35.565591
155
0.559758
5.316448
false
false
false
false
GunoH/intellij-community
platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/util/ExternalSystemTestUtil.kt
1
3823
// 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.openapi.externalSystem.util import com.intellij.ide.actions.ImportProjectAction import com.intellij.ide.impl.OpenProjectTask import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.EDT import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys import com.intellij.openapi.externalSystem.model.ProjectSystemId import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.fileChooser.FileChooserDialog import com.intellij.openapi.fileChooser.FileChooserFactory import com.intellij.openapi.fileChooser.impl.FileChooserFactoryImpl import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ex.ProjectManagerEx import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.use import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.TestActionEvent import com.intellij.testFramework.closeOpenedProjectsIfFailAsync import com.intellij.testFramework.replaceService import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.awt.Component suspend fun openPlatformProjectAsync(projectDirectory: VirtualFile): Project { return closeOpenedProjectsIfFailAsync { ProjectManagerEx.getInstanceEx().openProjectAsync( projectStoreBaseDir = projectDirectory.toNioPath(), options = OpenProjectTask { forceOpenInNewFrame = true useDefaultProjectAsTemplate = false isRefreshVfsNeeded = false } )!! } } suspend fun importProjectAsync( projectFile: VirtualFile, systemId: ProjectSystemId? = null ): Project { return closeOpenedProjectsIfFailAsync { detectOpenedProject { performAction( action = ImportProjectAction(), systemId = systemId, selectedFile = projectFile ) } } } suspend fun performAction( action: AnAction, project: Project? = null, systemId: ProjectSystemId? = null, selectedFile: VirtualFile? = null ) { withSelectedFileIfNeeded(selectedFile) { withContext(Dispatchers.EDT) { action.actionPerformed(TestActionEvent { when { ExternalSystemDataKeys.EXTERNAL_SYSTEM_ID.`is`(it) -> systemId CommonDataKeys.PROJECT.`is`(it) -> project CommonDataKeys.VIRTUAL_FILE.`is`(it) -> selectedFile else -> null } }) } } } private inline fun <R> withSelectedFileIfNeeded(selectedFile: VirtualFile?, action: () -> R): R { if (selectedFile == null) { return action() } Disposer.newDisposable().use { ApplicationManager.getApplication().replaceService(FileChooserFactory::class.java, object : FileChooserFactoryImpl() { override fun createFileChooser(descriptor: FileChooserDescriptor, project: Project?, parent: Component?): FileChooserDialog { return object : FileChooserDialog { @Suppress("OVERRIDE_DEPRECATION") override fun choose(toSelect: VirtualFile?, project: Project?): Array<VirtualFile> { return choose(project, toSelect) } override fun choose(project: Project?, vararg toSelect: VirtualFile?): Array<VirtualFile> { return arrayOf(selectedFile) } } } }, it) return action() } } private inline fun detectOpenedProject(action: () -> Unit): Project { val projectManager = ProjectManager.getInstance() val openProjects = projectManager.openProjects.toHashSet() action() return projectManager.openProjects.first { it !in openProjects } }
apache-2.0
bb1e581640f9517e2fed0bd65bb7c59b
34.728972
131
0.751242
4.939276
false
false
false
false
GunoH/intellij-community
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/r/inlays/components/NotebookTabs.kt
2
2075
/* * Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package org.jetbrains.plugins.notebooks.visualization.r.inlays.components import com.intellij.openapi.fileEditor.FileEditor import com.intellij.util.ui.components.BorderLayoutPanel import org.jetbrains.annotations.Nls import org.jetbrains.plugins.notebooks.visualization.r.VisualizationBundle import java.awt.BorderLayout import java.awt.Component import javax.swing.JPanel import javax.swing.JToggleButton /** * This component "installs" into bottom area of given FileEditor and allows us to add tabs with custom components under editor. */ class NotebookTabs private constructor(private val editor: BorderLayoutPanel) : JPanel() { companion object { fun install(editor: FileEditor): NotebookTabs? { val component = editor.component if (component !is BorderLayoutPanel) return null val componentLayout = component.layout as? BorderLayout if (componentLayout == null) { return null } when (val bottomComponent = componentLayout.getLayoutComponent(BorderLayout.SOUTH)) { null -> return NotebookTabs(component) is NotebookTabs -> return bottomComponent else -> return null } } } private val tabs = HashMap<JToggleButton, Component>() init { editor.addToBottom(this) val center = (editor.layout as BorderLayout).getLayoutComponent(BorderLayout.CENTER) addTab(VisualizationBundle.message("notebook.tabs.code.title"), center) } private fun addTab(@Nls name: String, page: Component) { val tab = JToggleButton(name) val action = { val currentCenter = (editor.layout as BorderLayout).getLayoutComponent(BorderLayout.CENTER) if (currentCenter != page) { editor.remove(currentCenter) editor.add(page, BorderLayout.CENTER) editor.repaint() } } tab.addActionListener { action.invoke() } tabs[tab] = page action.invoke() add(tab) } }
apache-2.0
307f09ce9c9dc2ef702e9de7f4293e94
27.833333
140
0.718072
4.501085
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/AttachedEntityImpl.kt
2
8698
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToOneParent import com.intellij.workspaceModel.storage.impl.updateOneToOneParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class AttachedEntityImpl(val dataSource: AttachedEntityData) : AttachedEntity, WorkspaceEntityBase() { companion object { internal val REF_CONNECTION_ID: ConnectionId = ConnectionId.create(MainEntity::class.java, AttachedEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false) val connections = listOf<ConnectionId>( REF_CONNECTION_ID, ) } override val ref: MainEntity get() = snapshot.extractOneToOneParent(REF_CONNECTION_ID, this)!! override val data: String get() = dataSource.data override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: AttachedEntityData?) : ModifiableWorkspaceEntityBase<AttachedEntity, AttachedEntityData>( result), AttachedEntity.Builder { constructor() : this(AttachedEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity AttachedEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (_diff != null) { if (_diff.extractOneToOneParent<WorkspaceEntityBase>(REF_CONNECTION_ID, this) == null) { error("Field AttachedEntity#ref should be initialized") } } else { if (this.entityLinks[EntityLink(false, REF_CONNECTION_ID)] == null) { error("Field AttachedEntity#ref should be initialized") } } if (!getEntityData().isDataInitialized()) { error("Field AttachedEntity#data should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as AttachedEntity if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.data != dataSource.data) this.data = dataSource.data if (parents != null) { val refNew = parents.filterIsInstance<MainEntity>().single() if ((this.ref as WorkspaceEntityBase).id != (refNew as WorkspaceEntityBase).id) { this.ref = refNew } } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var ref: MainEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneParent(REF_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, REF_CONNECTION_ID)]!! as MainEntity } else { this.entityLinks[EntityLink(false, REF_CONNECTION_ID)]!! as MainEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*, *>) { value.entityLinks[EntityLink(true, REF_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) { _diff.updateOneToOneParentOfChild(REF_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*, *>) { value.entityLinks[EntityLink(true, REF_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, REF_CONNECTION_ID)] = value } changedProperty.add("ref") } override var data: String get() = getEntityData().data set(value) { checkModificationAllowed() getEntityData(true).data = value changedProperty.add("data") } override fun getEntityClass(): Class<AttachedEntity> = AttachedEntity::class.java } } class AttachedEntityData : WorkspaceEntityData<AttachedEntity>() { lateinit var data: String fun isDataInitialized(): Boolean = ::data.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<AttachedEntity> { val modifiable = AttachedEntityImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): AttachedEntity { return getCached(snapshot) { val entity = AttachedEntityImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return AttachedEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return AttachedEntity(data, entitySource) { this.ref = parents.filterIsInstance<MainEntity>().single() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(MainEntity::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as AttachedEntityData if (this.entitySource != other.entitySource) return false if (this.data != other.data) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as AttachedEntityData if (this.data != other.data) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + data.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + data.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
35ed97c8a8f118892c06a7247d377a7e
33.792
136
0.694872
5.146746
false
false
false
false
GunoH/intellij-community
platform/platform-tests/testSrc/com/intellij/openapi/roots/impl/indexing/ProjectStructureDsl.kt
5
11199
// 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.openapi.roots.impl.indexing import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.ModuleTypeId import com.intellij.openapi.module.ModuleTypeManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.ThrowableComputable import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.IoTestUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.PsiTestUtil import com.intellij.testFramework.rules.ProjectModelRule import org.jetbrains.jps.model.java.JavaResourceRootType import org.jetbrains.jps.model.java.JavaSourceRootType import org.jetbrains.jps.model.module.JpsModuleSourceRootType import java.io.File import java.nio.file.Path @DslMarker annotation class ProjectStructureDsl @ProjectStructureDsl interface DirectoryContentBuilder { fun dir(name: String, content: DirectoryContentBuilder.() -> Unit): DirectorySpec fun file(name: String, content: String): FileSpec fun symlink(name: String, target: ContentSpec): SymlinkSpec } @ProjectStructureDsl interface ModuleContentBuilder : DirectoryContentBuilder { fun content(name: String, content: ModuleContentBuilder.() -> Unit): ModuleRootSpec fun source(name: String, sourceRootType: JpsModuleSourceRootType<*>, content: ModuleContentBuilder.() -> Unit): ModuleRootSpec fun excluded(name: String, content: ModuleContentBuilder.() -> Unit): ModuleRootSpec /** Similar to [dir] but preserves [ModuleContentBuilder] receiver of the builder. */ fun moduleDir(name: String, content: ModuleContentBuilder.() -> Unit): DirectorySpec } fun ModuleContentBuilder.source(name: String, content: ModuleContentBuilder.() -> Unit) = source(name, JavaSourceRootType.SOURCE, content) fun ModuleContentBuilder.testSourceRoot(name: String, content: ModuleContentBuilder.() -> Unit) = source(name, JavaSourceRootType.TEST_SOURCE, content) fun ModuleContentBuilder.resourceRoot(name: String, content: ModuleContentBuilder.() -> Unit) = source(name, JavaResourceRootType.RESOURCE, content) fun ModuleContentBuilder.testResourceRoot(name: String, content: ModuleContentBuilder.() -> Unit) = source(name, JavaResourceRootType.TEST_RESOURCE, content) interface ContentSpecPath { companion object { const val SEPARATOR = '/' } val rootDirectory: VirtualFile val path: String val parentPath: ContentSpecPath fun resolve(child: String): ContentSpecPath } infix operator fun ContentSpecPath.div(child: String) = resolve(child) private class ContentSpecPathImpl(override val rootDirectory: VirtualFile, override val path: String) : ContentSpecPath { override fun resolve(child: String) = ContentSpecPathImpl( rootDirectory, if (path.isEmpty()) child else "$path${ContentSpecPath.SEPARATOR}$child" ) override val parentPath: ContentSpecPath get() { check(path.isNotEmpty()) { "This path is already the root path $rootDirectory" } return ContentSpecPathImpl(rootDirectory, path.substringBeforeLast(ContentSpecPath.SEPARATOR, "")) } } interface ContentSpec { val specPath: ContentSpecPath fun generateTo(target: VirtualFile) fun generate(parentDirectory: VirtualFile, name: String): VirtualFile } fun ContentSpec.resolveVirtualFile(): VirtualFile { val file = specPath.rootDirectory.findFileByRelativePath(specPath.path.replace(ContentSpecPath.SEPARATOR, '/')) checkNotNull(file) { "Content spec has not been created yet: ${specPath.path} against ${specPath.rootDirectory}" } file.refresh(false, true) return file } abstract class ContentWithChildrenSpec(override val specPath: ContentSpecPath) : ContentSpec { private val children = linkedMapOf<String, ContentSpec>() fun addChild(name: String, spec: ContentSpec) { check(!FileUtil.toSystemIndependentName(name).contains('/')) { "only simple child names are allowed: $name" } check(name !in children) { "'$name' was already added" } children[name] = spec } override fun generateTo(target: VirtualFile) { for ((childName, spec) in children) { spec.generate(target, childName) } } override fun generate(parentDirectory: VirtualFile, name: String): VirtualFile { val thisDirectory = runWriteAction { parentDirectory.createChildDirectory(null, name) } generateTo(thisDirectory) return thisDirectory } } abstract class ModuleRootSpec(specPath: ContentSpecPath, protected val module: Module) : DirectorySpec(specPath) class ContentRootSpec( specPath: ContentSpecPath, module: Module ) : ModuleRootSpec(specPath, module) { override fun generateTo(target: VirtualFile) { PsiTestUtil.addContentRoot(module, target) super.generateTo(target) } } class SourceRootSpec( specPath: ContentSpecPath, module: Module, private val sourceRootType: JpsModuleSourceRootType<*> ) : ModuleRootSpec(specPath, module) { override fun generateTo(target: VirtualFile) { PsiTestUtil.addSourceRoot(module, target, sourceRootType) super.generateTo(target) } } class ExcludedRootSpec( specPath: ContentSpecPath, module: Module ) : ModuleRootSpec(specPath, module) { override fun generateTo(target: VirtualFile) { PsiTestUtil.addExcludedRoot(module, target) super.generateTo(target) } } open class DirectorySpec(specPath: ContentSpecPath) : ContentWithChildrenSpec(specPath) class FileSpec(override val specPath: ContentSpecPath, private val content: ByteArray) : ContentSpec { override fun generateTo(target: VirtualFile) { runWriteAction { target.getOutputStream(null).buffered().use { it.write(content) } } } override fun generate(parentDirectory: VirtualFile, name: String): VirtualFile { val file = runWriteAction { parentDirectory.createChildData(null, name) } generateTo(file) return file } } class SymlinkSpec(override val specPath: ContentSpecPath, private val target: ContentSpec) : ContentSpec { override fun generateTo(target: VirtualFile) { throw UnsupportedOperationException("Cannot override symlink file $target") } private fun ContentSpecPath.getAbsolutePath(): String = rootDirectory.path.trimEnd('/').replace('/', ContentSpecPath.SEPARATOR) + (if (path.isEmpty()) "" else ContentSpecPath.SEPARATOR + path) override fun generate(parentDirectory: VirtualFile, name: String): VirtualFile { val targetRelativePathToSymlink = FileUtil.getRelativePath( specPath.parentPath.getAbsolutePath(), target.specPath.getAbsolutePath(), ContentSpecPath.SEPARATOR ) checkNotNull(targetRelativePathToSymlink) { "Path to symlink's target ${target.specPath.path} is not relative to ${specPath.path}" } val fullLinkPath = File(parentDirectory.path + '/' + name) check(!fullLinkPath.exists()) { "Link already exists: $fullLinkPath" } check(fullLinkPath.isAbsolute) { "Path to symlink must be absolute: $fullLinkPath" } val symlinkIoFile = IoTestUtil.createSymLink(targetRelativePathToSymlink, fullLinkPath.absolutePath) return checkNotNull(LocalFileSystem.getInstance().refreshAndFindFileByIoFile(symlinkIoFile)) } } class DirectoryContentBuilderImpl( private val result: ContentWithChildrenSpec ) : DirectoryContentBuilder { override fun dir(name: String, content: DirectoryContentBuilder.() -> Unit): DirectorySpec { val directorySpec = DirectorySpec(result.specPath / name) DirectoryContentBuilderImpl(directorySpec).content() result.addChild(name, directorySpec) return directorySpec } override fun file(name: String, content: String): FileSpec { val spec = FileSpec(result.specPath / name, content.toByteArray()) result.addChild(name, spec) return spec } override fun symlink(name: String, target: ContentSpec): SymlinkSpec { val spec = SymlinkSpec(result.specPath / name, target) result.addChild(name, spec) return spec } } class ModuleContentBuilderImpl( private val module: Module, private val result: ContentWithChildrenSpec ) : ModuleContentBuilder { private fun <S : ModuleRootSpec> addModuleContentChildSpec(name: String, spec: S, content: ModuleContentBuilder.() -> Unit): S { ModuleContentBuilderImpl(module, spec).content() result.addChild(name, spec) return spec } override fun content(name: String, content: ModuleContentBuilder.() -> Unit) = addModuleContentChildSpec( name, ContentRootSpec(result.specPath / name, module), content ) override fun source(name: String, sourceRootType: JpsModuleSourceRootType<*>, content: ModuleContentBuilder.() -> Unit) = addModuleContentChildSpec( name, SourceRootSpec(result.specPath / name, module, sourceRootType), content ) override fun excluded(name: String, content: ModuleContentBuilder.() -> Unit) = addModuleContentChildSpec( name, ExcludedRootSpec(result.specPath / name, module), content ) override fun dir(name: String, content: DirectoryContentBuilder.() -> Unit) = DirectoryContentBuilderImpl(result).dir(name, content) override fun moduleDir(name: String, content: ModuleContentBuilder.() -> Unit): DirectorySpec { val directorySpec = DirectorySpec(result.specPath / name) ModuleContentBuilderImpl(module, directorySpec).content() result.addChild(name, directorySpec) return directorySpec } override fun file(name: String, content: String) = DirectoryContentBuilderImpl(result).file(name, content) override fun symlink(name: String, target: ContentSpec) = DirectoryContentBuilderImpl(result).symlink(name, target) } fun buildDirectoryContent( directory: VirtualFile, content: DirectoryContentBuilder.() -> Unit ) { val directoryPath = ContentSpecPathImpl(directory, "") val directorySpec = DirectorySpec(directoryPath) DirectoryContentBuilderImpl(directorySpec).content() directorySpec.generateTo(directory) } fun ProjectModelRule.createJavaModule(moduleName: String, content: ModuleContentBuilder.() -> Unit): Module { val moduleRoot = baseProjectDir.newVirtualDirectory(moduleName) val module = createJavaModule(project, moduleName, moduleRoot.toNioPath()) val rootPath = ContentSpecPathImpl(moduleRoot, "") val directorySpec = DirectorySpec(rootPath) ModuleContentBuilderImpl(module, directorySpec).content() directorySpec.generateTo(moduleRoot) return module } private fun createJavaModule(project: Project, moduleName: String, moduleRootDirectory: Path): Module { val type = ModuleTypeManager.getInstance().findByID(ModuleTypeId.JAVA_MODULE) return WriteCommandAction.writeCommandAction(project).compute( ThrowableComputable<Module, RuntimeException> { val moduleModel = ModuleManager.getInstance(project).getModifiableModel() val module = moduleModel.newModule(moduleRootDirectory.resolve("$moduleName.iml"), type.id) moduleModel.commit() module } ) }
apache-2.0
1f560dbd16e100b3db03a30e5475c046
36.837838
136
0.766229
4.512087
false
false
false
false
jwren/intellij-community
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/script/dependencies/KotlinScriptDependenciesLibraryRootProvider.kt
1
2030
// 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.core.script.dependencies import com.intellij.navigation.ItemPresentation import com.intellij.openapi.project.Project import com.intellij.openapi.roots.AdditionalLibraryRootsProvider import com.intellij.openapi.roots.SyntheticLibrary import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager import javax.swing.Icon class KotlinScriptDependenciesLibraryRootProvider: AdditionalLibraryRootsProvider() { override fun getAdditionalProjectLibraries(project: Project): Collection<SyntheticLibrary> { val manager = ScriptConfigurationManager.getInstance(project) val classes = manager.getAllScriptsDependenciesClassFiles().filterValid() val sources = manager.getAllScriptDependenciesSources().filterValid() return if (classes.isEmpty() && sources.isEmpty()) { emptyList() } else { listOf(KotlinScriptDependenciesLibrary(classes = classes, sources = sources)) } } private fun Collection<VirtualFile>.filterValid() = this.filterTo(LinkedHashSet(), VirtualFile::isValid) override fun getRootsToWatch(project: Project): Collection<VirtualFile> = ScriptConfigurationManager.allExtraRoots(project).filterValid() private data class KotlinScriptDependenciesLibrary(val classes: Collection<VirtualFile>, val sources: Collection<VirtualFile>) : SyntheticLibrary(), ItemPresentation { override fun getBinaryRoots(): Collection<VirtualFile> = classes override fun getSourceRoots(): Collection<VirtualFile> = sources override fun getPresentableText(): String = KotlinBundle.message("script.name.kotlin.script.dependencies") override fun getIcon(unused: Boolean): Icon = KotlinIcons.SCRIPT } }
apache-2.0
3cc429d089e51d25f5216f173837c030
46.232558
132
0.772414
5.205128
false
true
false
false
GunoH/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/service/GHPRCreationServiceImpl.kt
3
3567
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.data.service import com.intellij.collaboration.async.CompletableFutureUtil.submitIOTask import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.util.text.nullize import git4idea.GitRemoteBranch import org.jetbrains.plugins.github.api.GHGQLRequests import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestShort import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.pullrequest.data.GHPRIdentifier import org.jetbrains.plugins.github.util.GHGitRepositoryMapping import java.util.concurrent.CompletableFuture class GHPRCreationServiceImpl(private val progressManager: ProgressManager, private val requestExecutor: GithubApiRequestExecutor, repositoryDataService: GHPRRepositoryDataService) : GHPRCreationService { private val baseRepo = repositoryDataService.repositoryMapping private val repositoryId = repositoryDataService.repositoryId override fun createPullRequest(progressIndicator: ProgressIndicator, baseBranch: GitRemoteBranch, headRepo: GHGitRepositoryMapping, headBranch: GitRemoteBranch, title: String, description: String, draft: Boolean): CompletableFuture<GHPullRequestShort> = progressManager.submitIOTask(progressIndicator) { it.text = GithubBundle.message("pull.request.create.process.title") val headRepositoryPrefix = getHeadRepoPrefix(headRepo) val actualTitle = title.takeIf(String::isNotBlank) ?: headBranch.nameForRemoteOperations val body = description.nullize(true) requestExecutor.execute(it, GHGQLRequests.PullRequest.create(baseRepo.repository, repositoryId, baseBranch.nameForRemoteOperations, headRepositoryPrefix + headBranch.nameForRemoteOperations, actualTitle, body, draft )) } override fun findPullRequest(progressIndicator: ProgressIndicator, baseBranch: GitRemoteBranch, headRepo: GHGitRepositoryMapping, headBranch: GitRemoteBranch): GHPRIdentifier? { progressIndicator.text = GithubBundle.message("pull.request.existing.process.title") return requestExecutor.execute(progressIndicator, GHGQLRequests.PullRequest.findByBranches(baseRepo.repository, baseBranch.nameForRemoteOperations, headBranch.nameForRemoteOperations )).nodes.firstOrNull { it.headRepository?.owner?.login == headRepo.repository.repositoryPath.owner } } private fun getHeadRepoPrefix(headRepo: GHGitRepositoryMapping) = if (baseRepo.repository == headRepo.repository) "" else headRepo.repository.repositoryPath.owner + ":" }
apache-2.0
b97a83fb4979a864883609266f4c9206
56.548387
140
0.650407
6.369643
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/fir-low-level-api/src/org/jetbrains/kotlin/idea/fir/low/level/api/providers/FirIdeProvider.kt
2
6787
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.fir.low.level.api.providers import com.intellij.openapi.project.Project import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.fir.FirSession import org.jetbrains.kotlin.fir.NoMutableState import org.jetbrains.kotlin.fir.ThreadSafeMutableState import org.jetbrains.kotlin.fir.builder.RawFirBuilder import org.jetbrains.kotlin.fir.declarations.* import org.jetbrains.kotlin.fir.declarations.synthetic.FirSyntheticProperty import org.jetbrains.kotlin.fir.originalForSubstitutionOverride import org.jetbrains.kotlin.fir.resolve.providers.FirProvider import org.jetbrains.kotlin.fir.resolve.providers.FirProviderInternals import org.jetbrains.kotlin.fir.resolve.providers.FirSymbolProvider import org.jetbrains.kotlin.fir.resolve.providers.FirSymbolProviderInternals import org.jetbrains.kotlin.fir.scopes.KotlinScopeProvider import org.jetbrains.kotlin.fir.symbols.impl.* import org.jetbrains.kotlin.idea.caches.project.ModuleSourceInfo import org.jetbrains.kotlin.idea.fir.low.level.api.IndexHelper import org.jetbrains.kotlin.idea.fir.low.level.api.PackageExistenceCheckerForSingleModule import org.jetbrains.kotlin.idea.fir.low.level.api.file.builder.FirFileBuilder import org.jetbrains.kotlin.idea.fir.low.level.api.file.builder.ModuleFileCache import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtProperty @ThreadSafeMutableState internal class FirIdeProvider( project: Project, val session: FirSession, moduleInfo: ModuleSourceInfo, val kotlinScopeProvider: KotlinScopeProvider, firFileBuilder: FirFileBuilder, val cache: ModuleFileCache, searchScope: GlobalSearchScope, ) : FirProvider() { override val symbolProvider: FirSymbolProvider = SymbolProvider() private val indexHelper = IndexHelper(project, searchScope) private val packageExistenceChecker = PackageExistenceCheckerForSingleModule(project, moduleInfo) private val providerHelper = FirProviderHelper( cache, firFileBuilder, indexHelper, packageExistenceChecker, ) override val isPhasedFirAllowed: Boolean get() = true override fun getFirClassifierByFqName(classId: ClassId): FirClassLikeDeclaration<*>? = providerHelper.getFirClassifierByFqName(classId) override fun getFirClassifierContainerFile(fqName: ClassId): FirFile { return getFirClassifierContainerFileIfAny(fqName) ?: error("Couldn't find container for ${fqName}") } override fun getFirClassifierContainerFileIfAny(fqName: ClassId): FirFile? { val fir = getFirClassifierByFqName(fqName) ?: return null // Necessary to ensure cacheProvider contains this classifier return cache.getContainerFirFile(fir) } override fun getFirClassifierContainerFile(symbol: FirClassLikeSymbol<*>): FirFile { return getFirClassifierContainerFileIfAny(symbol) ?: error("Couldn't find container for ${symbol.classId}") } override fun getFirClassifierContainerFileIfAny(symbol: FirClassLikeSymbol<*>): FirFile? = cache.getContainerFirFile(symbol.fir) override fun getFirCallableContainerFile(symbol: FirCallableSymbol<*>): FirFile? { symbol.fir.originalForSubstitutionOverride?.symbol?.let { return getFirCallableContainerFile(it) } if (symbol is FirAccessorSymbol) { val fir = symbol.fir if (fir is FirSyntheticProperty) { return getFirCallableContainerFile(fir.getter.delegate.symbol) } } return cache.getContainerFirFile(symbol.fir) } override fun getFirFilesByPackage(fqName: FqName): List<FirFile> = error("Should not be called in FIR IDE") // TODO move out of here // used only for completion fun buildFunctionWithBody(ktNamedFunction: KtNamedFunction, original: FirFunction<*>): FirFunction<*> { return RawFirBuilder(session, kotlinScopeProvider).buildFunctionWithBody(ktNamedFunction, original) } fun buildPropertyWithBody(ktNamedFunction: KtProperty, original: FirProperty): FirProperty { return RawFirBuilder(session, kotlinScopeProvider).buildPropertyWithBody(ktNamedFunction, original) } @FirProviderInternals override fun recordGeneratedClass(owner: FirAnnotatedDeclaration, klass: FirRegularClass) { TODO() } @FirProviderInternals override fun recordGeneratedMember(owner: FirAnnotatedDeclaration, klass: FirDeclaration) { TODO() } override fun getClassNamesInPackage(fqName: FqName): Set<Name> = indexHelper.getClassNamesInPackage(fqName) @NoMutableState private inner class SymbolProvider : FirSymbolProvider(session) { override fun getTopLevelCallableSymbols(packageFqName: FqName, name: Name): List<FirCallableSymbol<*>> = providerHelper.getTopLevelCallableSymbols(packageFqName, name) @FirSymbolProviderInternals override fun getTopLevelCallableSymbolsTo(destination: MutableList<FirCallableSymbol<*>>, packageFqName: FqName, name: Name) { destination += getTopLevelCallableSymbols(packageFqName, name) } override fun getTopLevelFunctionSymbols(packageFqName: FqName, name: Name): List<FirNamedFunctionSymbol> = providerHelper.getTopLevelFunctionSymbols(packageFqName, name) @FirSymbolProviderInternals override fun getTopLevelFunctionSymbolsTo(destination: MutableList<FirNamedFunctionSymbol>, packageFqName: FqName, name: Name) { destination += getTopLevelFunctionSymbols(packageFqName, name) } override fun getTopLevelPropertySymbols(packageFqName: FqName, name: Name): List<FirPropertySymbol> = providerHelper.getTopLevelPropertySymbols(packageFqName, name) @FirSymbolProviderInternals override fun getTopLevelPropertySymbolsTo(destination: MutableList<FirPropertySymbol>, packageFqName: FqName, name: Name) { destination += getTopLevelPropertySymbols(packageFqName, name) } override fun getPackage(fqName: FqName): FqName? = providerHelper.getPackage(fqName) override fun getClassLikeSymbolByFqName(classId: ClassId): FirClassLikeSymbol<*>? { return getFirClassifierByFqName(classId)?.symbol } } } internal val FirSession.firIdeProvider: FirIdeProvider by FirSession.sessionComponentAccessor()
apache-2.0
4ab68849b8cd8031415a1e5ad7aeac04
42.787097
136
0.760866
4.830605
false
false
false
false
smmribeiro/intellij-community
plugins/stats-collector/test/com/intellij/stats/completion/tracker/CompletionEventsLoggingTest.kt
12
4829
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.stats.completion.tracker import com.intellij.codeInsight.lookup.LookupElement import com.intellij.openapi.actionSystem.IdeActions import com.intellij.stats.completion.Action.* import com.intellij.stats.completion.events.ExplicitSelectEvent import com.intellij.stats.completion.events.LogEvent import com.intellij.stats.completion.events.TypedSelectEvent import org.assertj.core.api.Assertions.assertThat class CompletionEventsLoggingTest : CompletionLoggingTestBase() { fun `test item selected on just typing`() { myFixture.type('.') myFixture.completeBasic() val itemsOnStart = lookup.items myFixture.type("ru") trackedEvents.assertOrder( COMPLETION_STARTED, TYPE ) myFixture.type("n)") trackedEvents.assertOrder( COMPLETION_STARTED, TYPE, TYPE, TYPE, TYPED_SELECT ) checkLoggedAllElements(itemsOnStart) checkSelectedCorrectId(itemsOnStart, "run") } private fun checkLoggedAllElements(itemsOnStart: MutableList<LookupElement>) { assertThat(completionStartedEvent.newCompletionListItems).hasSize(itemsOnStart.size) assertThat(completionStartedEvent.completionListIds).hasSize(itemsOnStart.size) } private fun checkSelectedCorrectId(itemsOnStart: MutableList<LookupElement>, selectedString: String) { val selectedIndex = itemsOnStart.indexOfFirst { it.lookupString == selectedString } val selectedId = completionStartedEvent.completionListIds[selectedIndex] assertThat(trackedEvents.last().extractSelectedId()).isEqualTo(selectedId) } private fun LogEvent.extractSelectedId(): Int? { return when (this) { is ExplicitSelectEvent -> selectedId is TypedSelectEvent -> selectedId else -> null } } fun `test wrong typing`() { myFixture.type('.') myFixture.completeBasic() myFixture.type('r') myFixture.type('u') myFixture.type('x') lookup.hide() //figure out why needed here trackedEvents.assertOrder( COMPLETION_STARTED, TYPE, TYPE, TYPE, COMPLETION_CANCELED ) } fun `test down up buttons`() { myFixture.type('.') myFixture.completeBasic() val elementsOnStart = lookup.items myFixture.performEditorAction(IdeActions.ACTION_EDITOR_MOVE_CARET_DOWN) myFixture.performEditorAction(IdeActions.ACTION_EDITOR_MOVE_CARET_DOWN) myFixture.performEditorAction(IdeActions.ACTION_EDITOR_MOVE_CARET_DOWN) myFixture.performEditorAction(IdeActions.ACTION_EDITOR_MOVE_CARET_UP) myFixture.performEditorAction(IdeActions.ACTION_EDITOR_MOVE_CARET_UP) myFixture.performEditorAction(IdeActions.ACTION_EDITOR_MOVE_CARET_UP) myFixture.type('\n') trackedEvents.assertOrder( COMPLETION_STARTED, DOWN, DOWN, DOWN, UP, UP, UP, EXPLICIT_SELECT ) checkLoggedAllElements(elementsOnStart) checkSelectedCorrectId(elementsOnStart, elementsOnStart.first().lookupString) } fun `test backspace`() { myFixture.type('.') myFixture.completeBasic() val elementsOnStart = lookup.items myFixture.type("ru") myFixture.performEditorAction(IdeActions.ACTION_EDITOR_BACKSPACE) myFixture.type('u') myFixture.type('\n') trackedEvents.assertOrder( COMPLETION_STARTED, TYPE, TYPE, BACKSPACE, TYPE, EXPLICIT_SELECT ) checkSelectedCorrectId(elementsOnStart, "run") checkLoggedAllElements(elementsOnStart) } fun `test if typed prefix is correct completion variant, pressing dot will select it`() { myFixture.completeBasic() val elementsOnStart = lookup.items myFixture.type('.') trackedEvents.assertOrder( COMPLETION_STARTED, TYPED_SELECT ) checkSelectedCorrectId(elementsOnStart, "r") checkLoggedAllElements(elementsOnStart) } fun `test dot selection logs as explicit select`() { myFixture.completeBasic() val elementsOnStart = lookup.items myFixture.type('u') myFixture.type('.') trackedEvents.assertOrder( COMPLETION_STARTED, TYPE, EXPLICIT_SELECT ) checkSelectedCorrectId(elementsOnStart, "run") checkLoggedAllElements(elementsOnStart) } }
apache-2.0
4f4488accba406b2df1387b07ff36264
28.814815
140
0.652723
4.973223
false
false
false
false
smmribeiro/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/dsl/MavenDependencyModificator.kt
1
18200
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.dsl import com.intellij.buildsystem.model.DeclaredDependency import com.intellij.buildsystem.model.unified.UnifiedCoordinates import com.intellij.buildsystem.model.unified.UnifiedDependency import com.intellij.buildsystem.model.unified.UnifiedDependencyRepository import com.intellij.externalSystem.ExternalDependencyModificator import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.application.ReadAction import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDocumentManager import com.intellij.psi.util.childrenOfType import com.intellij.psi.xml.XmlFile import com.intellij.psi.xml.XmlTag import com.intellij.util.xml.DomUtil import com.intellij.util.xml.GenericDomValue import org.jetbrains.idea.maven.dom.MavenDomElement import org.jetbrains.idea.maven.dom.MavenDomProjectProcessorUtils import org.jetbrains.idea.maven.dom.MavenDomUtil import org.jetbrains.idea.maven.dom.converters.MavenDependencyCompletionUtil import org.jetbrains.idea.maven.dom.model.MavenDomDependency import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel import org.jetbrains.idea.maven.dom.model.MavenDomRepository import org.jetbrains.idea.maven.model.MavenId import org.jetbrains.idea.maven.project.MavenProject import org.jetbrains.idea.maven.project.MavenProjectBundle import org.jetbrains.idea.maven.project.MavenProjectsManager val mavenTopLevelElementsOrder = listOf( "modelVersion", "parent", "groupId", "artifactId", "version", "packaging", "properties", "name", "description", "url", "inceptionYear", "licenses", "organization", "developers", "contributors", "modules", "dependencyManagement", "dependencies", "build", "reporting", "issueManagement", "ciManagement", "mailingLists", "scm", "prerequisites", "repositories", "pluginRepositories", "distributionManagement", "profiles" ) val elementsBeforeDependencies = elementsBefore("dependencies") val elementsBeforeRepositories = elementsBefore("repositories") val elementsBeforeDependencyVersion = setOf("artifactId", "groupId") val elementsBeforeDependencyScope = elementsBeforeDependencyVersion + setOf("version", "classifier", "type") fun elementsBefore(s: String): Set<String> = mavenTopLevelElementsOrder.takeWhile { it != s } .toSet() class MavenDependencyModificator(private val myProject: Project) : ExternalDependencyModificator { private val myProjectsManager: MavenProjectsManager = MavenProjectsManager.getInstance(myProject) private val myDocumentManager: PsiDocumentManager = PsiDocumentManager.getInstance(myProject) private fun addDependenciesTagIfNotExists(psiFile: XmlFile, model: MavenDomProjectModel) { addTagIfNotExists(psiFile, model.dependencies, elementsBeforeDependencies) } private fun addRepositoriesTagIfNotExists(psiFile: XmlFile, model: MavenDomProjectModel) { addTagIfNotExists(psiFile, model.repositories, elementsBeforeRepositories) } private fun addTagIfNotExists(tagName: String, parentElement: MavenDomElement, siblingsBeforeTag: Set<String>) { val parentTag = checkNotNull(parentElement.xmlTag) { "Parent element ${parentElement.xmlElementName} must be an XML tag" } val xmlTagSiblings = parentTag.childrenOfType<XmlTag>() if (xmlTagSiblings.any { it.name == tagName }) return val siblingToInsertAfterOrNull = xmlTagSiblings.lastOrNull { siblingsBeforeTag.contains(it.name) } val child = parentTag.createChildTag(tagName, parentTag.namespace, null, false) parentTag.addAfter(child, siblingToInsertAfterOrNull) } private fun addTagIfNotExists(psiFile: XmlFile, element: MavenDomElement, elementsBefore: Set<String>) { if (element.exists()) { return } val rootTag = psiFile.rootTag if (rootTag == null) { element.ensureTagExists() return } val children = rootTag.children if (children.isEmpty()) { element.ensureTagExists() return } val lastOrNull = children .mapNotNull { it as? XmlTag } .lastOrNull { elementsBefore.contains(it.name) } val child = rootTag.createChildTag(element.xmlElementName, rootTag.namespace, null, false) rootTag.addAfter(child, lastOrNull) } private fun getDependenciesModel(module: Module, groupId: String, artifactId: String): Pair<MavenDomProjectModel, MavenDomDependency?> { val project: MavenProject = myProjectsManager.findProject(module) ?: throw IllegalArgumentException(MavenProjectBundle.message( "maven.project.not.found.for", module.name)) return ReadAction.compute<Pair<MavenDomProjectModel, MavenDomDependency?>, Throwable> { val model = MavenDomUtil.getMavenDomProjectModel(myProject, project.file) ?: throw IllegalStateException( MavenProjectBundle.message("maven.model.error", module.name)) val managedDependency = MavenDependencyCompletionUtil.findManagedDependency(model, myProject, groupId, artifactId) return@compute Pair(model, managedDependency) } } override fun supports(module: Module): Boolean { return myProjectsManager.isMavenizedModule(module) } override fun addDependency(module: Module, descriptor: UnifiedDependency) { requireNotNull(descriptor.coordinates.groupId) requireNotNull(descriptor.coordinates.version) requireNotNull(descriptor.coordinates.artifactId) val mavenId = descriptor.coordinates.toMavenId() val (model, managedDependency) = getDependenciesModel(module, mavenId.groupId!!, mavenId.artifactId!!) val psiFile = DomUtil.getFile(model) WriteCommandAction.writeCommandAction(myProject, psiFile).compute<Unit, Throwable> { addDependenciesTagIfNotExists(psiFile, model) val dependency = MavenDomUtil.createDomDependency(model, null) dependency.groupId.stringValue = mavenId.groupId dependency.artifactId.stringValue = mavenId.artifactId val scope = toMavenScope(descriptor.scope, managedDependency?.scope?.stringValue) scope?.let { dependency.scope.stringValue = it } if (managedDependency == null || managedDependency.version.stringValue != mavenId.version) { dependency.version.stringValue = mavenId.version } saveFile(psiFile) } } override fun updateDependency(module: Module, oldDescriptor: UnifiedDependency, newDescriptor: UnifiedDependency) { requireNotNull(newDescriptor.coordinates.groupId) requireNotNull(newDescriptor.coordinates.version) requireNotNull(newDescriptor.coordinates.artifactId) val oldMavenId = oldDescriptor.coordinates.toMavenId() val newMavenId = newDescriptor.coordinates.toMavenId() val (model, managedDependency) = ReadAction.compute<Pair<MavenDomProjectModel, MavenDomDependency?>, Throwable> { getDependenciesModel(module, oldMavenId.groupId!!, oldMavenId.artifactId!!) } val psiFile = DomUtil.getFile(model) WriteCommandAction.writeCommandAction(myProject, psiFile).compute<Unit, Throwable> { if (managedDependency != null) { updateManagedDependency(model, managedDependency, oldMavenId, newMavenId, oldDescriptor.scope, newDescriptor.scope) } else { updatePlainDependency(model, oldMavenId, newMavenId, oldDescriptor.scope, newDescriptor.scope) } saveFile(psiFile) } } private fun updateManagedDependency(model: MavenDomProjectModel, managedDependency: MavenDomDependency, oldMavenId: MavenId, newMavenId: MavenId, oldScope: String?, newScope: String?) { val domDependency = model.dependencies.dependencies.find { dep -> dep.artifactId.stringValue == oldMavenId.artifactId && dep.groupId.stringValue == oldMavenId.groupId && (!dep.version.exists() || dep.version.stringValue == oldMavenId.version) && (!dep.scope.exists() || dep.scope.stringValue == oldScope) } ?: return updateValueIfNeeded(model = model, domDependency = domDependency, domValue = domDependency.version, managedDomValue = managedDependency.version, newValue = newMavenId.version, siblingsBeforeTag = elementsBeforeDependencyVersion) updateValueIfNeeded(model = model, domDependency = domDependency, domValue = domDependency.scope, managedDomValue = managedDependency.scope, newValue = newScope, siblingsBeforeTag = elementsBeforeDependencyScope) } private fun updateValueIfNeeded(model: MavenDomProjectModel, domDependency: MavenDomDependency, domValue: GenericDomValue<String>, managedDomValue: GenericDomValue<String>, newValue: String?, siblingsBeforeTag: Set<String>) { when { newValue == null -> domValue.xmlTag?.delete() managedDomValue.stringValue != newValue -> { addTagIfNotExists(tagName = domValue.xmlElementName, parentElement = domDependency, siblingsBeforeTag = siblingsBeforeTag) updateVariableOrValue(model, domValue, newValue) } else -> domValue.xmlTag?.delete() } } private fun updatePlainDependency(model: MavenDomProjectModel, oldMavenId: MavenId, newMavenId: MavenId, oldScope: String?, newScope: String?) { val domDependency = model.dependencies.dependencies.find { dep -> dep.artifactId.stringValue == oldMavenId.artifactId && dep.groupId.stringValue == oldMavenId.groupId && dep.version.stringValue == oldMavenId.version && dep.scope.stringValue == oldScope } ?: return updateValueIfNeeded(model, domDependency, domDependency.artifactId, oldMavenId.artifactId, newMavenId.artifactId) updateValueIfNeeded(model, domDependency, domDependency.groupId, oldMavenId.groupId, newMavenId.groupId) updateValueIfNeeded(model, domDependency, domDependency.version, oldMavenId.version, newMavenId.version) updateValueIfNeeded(model, domDependency, domDependency.scope, oldScope, newScope) //if (oldMavenId.artifactId != newMavenId.artifactId) { // updateVariableOrValue(model, domDependency.artifactId, newMavenId.artifactId!!) //} //if (oldMavenId.groupId != newMavenId.groupId) { // updateVariableOrValue(model, domDependency.groupId, newMavenId.groupId!!) //} //if (oldMavenId.version != newMavenId.version) { // updateVariableOrValue(model, domDependency.version, newMavenId.version!!) //} } private fun updateValueIfNeeded(model: MavenDomProjectModel, domDependency: MavenDomDependency, domValue: GenericDomValue<String>, oldValue: String?, newValue: String?) { if (oldValue == newValue) return if (newValue != null) { addTagIfNotExists(domValue.xmlElementName, domDependency, elementsBeforeDependencyScope) updateVariableOrValue(model, domValue, newValue) } else { domDependency.scope.xmlTag?.delete() } } override fun removeDependency(module: Module, descriptor: UnifiedDependency) { requireNotNull(descriptor.coordinates.groupId) requireNotNull(descriptor.coordinates.version) val mavenId = descriptor.coordinates.toMavenId() val (model, _) = getDependenciesModel(module, mavenId.groupId!!, mavenId.artifactId!!) val psiFile = DomUtil.getFile(model) WriteCommandAction.writeCommandAction(myProject, psiFile).compute<Unit, Throwable> { for (dep in model.dependencies.dependencies) { if (dep.artifactId.stringValue == mavenId.artifactId && dep.groupId.stringValue == mavenId.groupId) { dep.xmlTag?.delete() } } if (model.dependencies.dependencies.isEmpty()) { model.dependencies.xmlTag?.delete() } saveFile(psiFile) } } override fun addRepository(module: Module, repository: UnifiedDependencyRepository) { val project: MavenProject = myProjectsManager.findProject(module) ?: throw IllegalArgumentException(MavenProjectBundle.message( "maven.project.not.found.for", module.name)) val model = ReadAction.compute<MavenDomProjectModel, Throwable> { MavenDomUtil.getMavenDomProjectModel(myProject, project.file) ?: throw IllegalStateException( MavenProjectBundle.message("maven.model.error", module.name)) } for (repo in model.repositories.repositories) { if (repo.url.stringValue?.trimLastSlash() == repository.url?.trimLastSlash()) { return } } val psiFile = DomUtil.getFile(model) WriteCommandAction.writeCommandAction(myProject, psiFile).compute<Unit, Throwable> { addRepositoriesTagIfNotExists(psiFile, model) val repoTag = model.repositories.addRepository() repository.id?.let { repoTag.id.stringValue = it } repository.name?.let { repoTag.name.stringValue = it } repository.url.let { repoTag.url.stringValue = it } saveFile(psiFile) } } override fun deleteRepository(module: Module, repository: UnifiedDependencyRepository) { val project: MavenProject = myProjectsManager.findProject(module) ?: throw IllegalArgumentException(MavenProjectBundle.message( "maven.project.not.found.for", module.name)) val (model, repo) = ReadAction.compute<Pair<MavenDomProjectModel, MavenDomRepository?>, Throwable> { val model = MavenDomUtil.getMavenDomProjectModel(myProject, project.file) ?: throw IllegalStateException( MavenProjectBundle.message("maven.model.error", module.name)) for (repo in model.repositories.repositories) { if (repo.url.stringValue?.trimLastSlash() == repository.url?.trimLastSlash()) { return@compute Pair(model, repo) } } return@compute null } if (repo == null) return val psiFile = DomUtil.getFile(repo) WriteCommandAction.writeCommandAction(myProject, psiFile).compute<Unit, Throwable> { repo.xmlTag?.delete() if (model.repositories.repositories.isEmpty()) { model.repositories.xmlTag?.delete() } saveFile(psiFile) } } private fun saveFile(psiFile: XmlFile) { val document = myDocumentManager.getDocument(psiFile) ?: throw IllegalStateException(MavenProjectBundle.message( "maven.model.error", psiFile)) myDocumentManager.doPostponedOperationsAndUnblockDocument(document) FileDocumentManager.getInstance().saveDocument(document) } private fun updateVariableOrValue(model: MavenDomProjectModel, domValue: GenericDomValue<String>, newValue: String) { val rawText = domValue.rawText?.trim() if (rawText != null && rawText.startsWith("${'$'}{") && rawText.endsWith("}")) { val propertyName = rawText.substring(2, rawText.length - 1) val subTags = model.properties.xmlTag?.subTags ?: emptyArray() for (subTag in subTags) { if (subTag.name == propertyName) { //TODO: recursive property declaration subTag.value.text = newValue return } } } else { domValue.stringValue = newValue } } private fun toMavenScope(scope: String?, managedScope: String?): String? { if (managedScope == null) { return scope } if (scope == managedScope) return null return scope } override fun declaredDependencies(module: Module): List<DeclaredDependency> { val project = MavenProjectsManager.getInstance(module.project).findProject(module) ?: return emptyList() return declaredDependencies(project.file) ?: emptyList() } //for faster testing fun declaredDependencies(file: VirtualFile): List<DeclaredDependency>? { return ReadAction.compute<List<DeclaredDependency>?, Throwable> { val model = MavenDomUtil.getMavenDomProjectModel(myProject, file) ?: return@compute null model.dependencies.dependencies.map { mavenDomDependency -> DeclaredDependency( groupId = mavenDomDependency.groupId.stringValue, artifactId = mavenDomDependency.artifactId.stringValue, version = retrieveDependencyVersion(myProject, mavenDomDependency), configuration = mavenDomDependency.scope.stringValue, dataContext = DataContext { if (CommonDataKeys.PSI_ELEMENT.`is`(it)) mavenDomDependency.xmlElement else null } ) } } } private fun retrieveDependencyVersion(project: Project, dependency: MavenDomDependency): String? { val directVersion = dependency.version.stringValue if (directVersion != null) return directVersion val managingDependency = MavenDomProjectProcessorUtils.searchManagingDependency(dependency, project) return managingDependency?.version?.stringValue } override fun declaredRepositories(module: Module): List<UnifiedDependencyRepository> { val project = MavenProjectsManager.getInstance(module.project).findProject(module) ?: return emptyList() return ReadAction.compute<List<UnifiedDependencyRepository>, Throwable> { val model = MavenDomUtil.getMavenDomProjectModel(myProject, project.file) ?: return@compute emptyList() model.repositories.repositories.map { UnifiedDependencyRepository(it.id.stringValue, it.name.stringValue, it.url.stringValue ?: "") } } } } private fun String.trimLastSlash() = trimEnd('/') private fun UnifiedCoordinates.toMavenId() = MavenId(groupId, artifactId, version)
apache-2.0
9ceda303db15336be08974e579355ae6
42.54067
140
0.718077
5.089485
false
false
false
false
anastr/SpeedView
speedviewlib/src/main/java/com/github/anastr/speedviewlib/components/note/TextNote.kt
1
2464
package com.github.anastr.speedviewlib.components.note import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.Typeface import android.text.Layout import android.text.StaticLayout import android.text.TextPaint import kotlin.math.max /** * this Library build By Anas Altair * see it on [GitHub](https://github.com/anastr/SpeedView) */ class TextNote /** * @param context you can use `getApplicationContext()` method. * @param noteText text to display, support SpannableString and multi-lines. */ (context: Context, private val noteText: CharSequence?) : Note<TextNote>(context) { private val notePaint = TextPaint(Paint.ANTI_ALIAS_FLAG) private var textSize = notePaint.textSize private var textLayout: StaticLayout? = null val textColor: Int get() = notePaint.color init { requireNotNull(noteText) { "noteText cannot be null." } notePaint.textAlign = Paint.Align.LEFT } override fun build(viewWidth: Int) { textLayout = StaticLayout(noteText, notePaint, viewWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, true) var w = 0 for (i in 0 until textLayout!!.lineCount) w = max(w.toFloat(), textLayout!!.getLineWidth(i)).toInt() noticeContainsSizeChange(w, textLayout!!.height) } override fun drawContains(canvas: Canvas, leftX: Float, topY: Float) { canvas.save() canvas.translate(leftX, topY) textLayout!!.draw(canvas) canvas.restore() } fun getTextSize(): Float { return textSize } /** * set Text size. * @param textSize in Pixel. * @return This Note object to allow for chaining of calls to set methods. */ fun setTextSize(textSize: Float): TextNote { this.textSize = textSize notePaint.textSize = textSize return this } /** * to change font or text style. * @param typeface new Typeface. * @return This Note object to allow for chaining of calls to set methods. */ fun setTextTypeFace(typeface: Typeface): TextNote { notePaint.typeface = typeface return this } /** * set text color. * @param textColor new color. * @return This Note object to allow for chaining of calls to set methods. */ fun setTextColor(textColor: Int): TextNote { notePaint.color = textColor return this } }
apache-2.0
f73e76deb824aee1a25d412ee8f43026
28.686747
114
0.664367
4.162162
false
false
false
false
aurae/PermissionsDispatcher
test/src/test/java/permissions/dispatcher/test/Extensions.kt
1
3309
package permissions.dispatcher.test import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.content.pm.PackageManager import android.os.Build import android.os.Process import android.support.v4.app.ActivityCompat import android.support.v4.app.AppOpsManagerCompat import android.support.v4.app.Fragment import android.support.v4.content.PermissionChecker import android.support.v7.app.AppCompatActivity import org.mockito.Matchers.* import org.powermock.api.mockito.PowerMockito import java.lang.reflect.Field import java.lang.reflect.Modifier fun mockShouldShowRequestPermissionRationaleActivity(result: Boolean) { PowerMockito.`when`(ActivityCompat.shouldShowRequestPermissionRationale(any(Activity::class.java), anyString())).thenReturn(result) } @SuppressLint("NewApi") fun mockShouldShowRequestPermissionRationaleFragment(fragment: Fragment, result: Boolean) { PowerMockito.`when`(fragment.shouldShowRequestPermissionRationale(anyString())).thenReturn(result) } fun mockActivityCompatShouldShowRequestPermissionRationale(result: Boolean) { PowerMockito.`when`(ActivityCompat.shouldShowRequestPermissionRationale(any(Activity::class.java), anyString())).thenReturn(result) } fun mockCheckSelfPermission(result: Boolean) { val value = if (result) PackageManager.PERMISSION_GRANTED else PackageManager.PERMISSION_DENIED PowerMockito.`when`(PermissionChecker.checkSelfPermission(any(Context::class.java), anyString())).thenReturn(value) } fun mockGetActivity(fragment: Fragment, result: AppCompatActivity) { PowerMockito.`when`(fragment.activity).thenReturn(result) } fun getRequestCameraConstant(clazz: Class<*>): Int { val field = clazz.getDeclaredField("REQUEST_SHOWCAMERA") field.isAccessible = true return field.getInt(null) } fun getPermissionRequestConstant(clazz: Class<*>): Array<String> { val field = clazz.getDeclaredField("PERMISSION_SHOWCAMERA") field.isAccessible = true return field.get(null) as Array<String> } fun overwriteCustomManufacture(manufactureText: String = "Xiaomi") { val modifiersField = Field::class.java.getDeclaredField("modifiers") modifiersField.isAccessible = true val manufacture = Build::class.java.getDeclaredField("MANUFACTURER") manufacture.isAccessible = true modifiersField.setInt(manufacture, manufacture.modifiers and Modifier.FINAL.inv()) manufacture.set(null, manufactureText) } fun overwriteCustomSdkInt(sdkInt: Int = 23) { val modifiersField = Field::class.java.getDeclaredField("modifiers") modifiersField.isAccessible = true val field = Build.VERSION::class.java.getDeclaredField("SDK_INT") field.isAccessible = true modifiersField.setInt(field, field.modifiers and Modifier.FINAL.inv()) field.set(null, sdkInt) } fun testForXiaomi() { overwriteCustomManufacture() overwriteCustomSdkInt() } fun mockPermissionToOp(result: String?) { PowerMockito.`when`(AppOpsManagerCompat.permissionToOp(anyString())).thenReturn(result) } fun mockMyUid() { PowerMockito.`when`(Process.myUid()).thenReturn(1) } fun mockNoteOp(result: Int) { mockMyUid() PowerMockito.`when`(AppOpsManagerCompat.noteOp(any(Context::class.java), anyString(), anyInt(), anyString())).thenReturn(result) }
apache-2.0
4e159459b3a5b9ba31567a93f22422a2
36.191011
135
0.788154
4.435657
false
false
false
false
dinosaurwithakatana/freight
freight-processor/src/main/kotlin/io/dwak/freight/processor/model/ClassBinding.kt
1
1859
package io.dwak.freight.processor.model import io.dwak.freight.annotation.ControllerBuilder import io.dwak.freight.annotation.Extra import io.dwak.freight.processor.extension.hasAnnotationWithName import io.dwak.freight.processor.extension.packageName import javax.lang.model.element.Element import javax.lang.model.element.ElementKind import javax.lang.model.element.TypeElement import javax.lang.model.type.MirroredTypeException import javax.lang.model.type.TypeMirror class ClassBinding(element: Element) : Binding { override val name: String override val type: TypeMirror override val kind: ElementKind val screenName: String val scopeName: String val enclosedExtras = arrayListOf<FieldBinding>() val popChangeHandler: TypeMirror? val pushChangeHandler: TypeMirror? init { name = element.simpleName.toString() kind = element.kind type = element.asType() val instance = element.getAnnotation(ControllerBuilder::class.java) screenName = instance.value scopeName = instance.scope popChangeHandler = getPopChangeHandler(instance) pushChangeHandler = getPushChangeHandler(instance) element.enclosedElements .filter { it.hasAnnotationWithName(Extra::class.java.simpleName) } .map(::FieldBinding) .forEach { enclosedExtras.add(it) } } companion object { fun getPopChangeHandler(annotation: ControllerBuilder): TypeMirror? { try { annotation.popChangeHandler // this should throw } catch (mte: MirroredTypeException) { return mte.typeMirror } return null } fun getPushChangeHandler(annotation: ControllerBuilder): TypeMirror? { try { annotation.pushChangeHandler // this should throw } catch (mte: MirroredTypeException) { return mte.typeMirror } return null } } }
apache-2.0
19e0adc9baa072f8f15b6cbe6c82bbd0
30.525424
78
0.734804
4.567568
false
false
false
false
koma-im/koma
src/main/kotlin/koma/gui/view/window/chatroom/messaging/reading/display/room_event/m_message/content/m_file.kt
1
2909
package koma.gui.view.window.chatroom.messaging.reading.display.room_event.m_message.content import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon import de.jensd.fx.glyphs.fontawesome.utils.FontAwesomeIconFactory import javafx.scene.control.MenuItem import javafx.scene.input.MouseButton import koma.Server import koma.gui.dialog.file.save.downloadFileAs import koma.gui.view.window.chatroom.messaging.reading.display.ViewNode import koma.koma_app.appState import koma.matrix.event.room_message.chat.FileMessage import koma.network.media.MHUrl import koma.network.media.parseMxc import koma.storage.persistence.settings.AppSettings import koma.util.onSuccess import link.continuum.desktop.gui.* private val settings: AppSettings = appState.store.settings class MFileViewNode(val content: FileMessage, private val server: Server): ViewNode { override val node = HBox(5.0) override val menuItems: List<MenuItem> private val url = content.url.parseMxc() init { val faicon = guessIconForMime(content.info?.mimetype) val s = settings.scale_em(2f) val icon_node = FontAwesomeIconFactory.get().createIcon(faicon, s) with(node) { add(icon_node) label(content.filename) setOnMouseClicked { e -> if (e.button == MouseButton.PRIMARY) save() } } menuItems = createMenuItems() } private fun createMenuItems(): List<MenuItem> { val mi = MenuItem("Save File") mi.isDisable = url == null mi.action { save() } val copyUrl = MenuItem("Copy File Address") copyUrl.isDisable = url == null copyUrl.action { clipboardPutString(url.toString()) } return listOf(mi, copyUrl) } private fun save() { url?.let { downloadFileAs(server.mxcToHttp(it), filename = content.filename, title = "Save File As", httpClient = server.httpClient) } } } private fun guessIconForMime(mime: String?): FontAwesomeIcon { mime?: return FontAwesomeIcon.FILE val keyword_icon = mapOf( Pair("zip", FontAwesomeIcon.FILE_ZIP_ALT), Pair("word", FontAwesomeIcon.FILE_WORD_ALT), Pair("video", FontAwesomeIcon.FILE_VIDEO_ALT), Pair("text", FontAwesomeIcon.FILE_TEXT), Pair("sound", FontAwesomeIcon.FILE_SOUND_ALT), Pair("powerpoint", FontAwesomeIcon.FILE_POWERPOINT_ALT), Pair("pdf", FontAwesomeIcon.FILE_PDF_ALT), Pair("image", FontAwesomeIcon.FILE_IMAGE_ALT), Pair("excel", FontAwesomeIcon.FILE_EXCEL_ALT), Pair("audio", FontAwesomeIcon.FILE_AUDIO_ALT), Pair("archive", FontAwesomeIcon.FILE_ARCHIVE_ALT) ) for ((k,i)in keyword_icon) { if (mime.contains(k)) return i } return FontAwesomeIcon.FILE }
gpl-3.0
153cd541e99df9cd22c8dca7a1e58ac4
33.630952
133
0.658302
4.040278
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/problem/httpws/service/HttpWsSampler.kt
1
3888
package org.evomaster.core.problem.httpws.service import org.evomaster.client.java.controller.api.dto.AuthenticationDto import org.evomaster.client.java.controller.api.dto.HeaderDto import org.evomaster.client.java.controller.api.dto.SutInfoDto import org.evomaster.core.problem.api.service.ApiWsSampler import org.evomaster.core.problem.httpws.service.auth.NoAuth import org.evomaster.core.problem.httpws.service.auth.* import org.evomaster.core.remote.SutProblemException import org.evomaster.core.search.Individual import org.slf4j.Logger import org.slf4j.LoggerFactory /** * Common code shared among sampler that rely on a RemoteController, and * that use HTTP, ie typically Web Services like REST and GraphQL */ abstract class HttpWsSampler<T> : ApiWsSampler<T>() where T : Individual{ companion object { private val log: Logger = LoggerFactory.getLogger(HttpWsSampler::class.java) } protected val authentications: MutableList<HttpWsAuthenticationInfo> = mutableListOf() /** * Given the current schema definition, create a random action among the available ones. * All the genes in such action will have their values initialized at random, but still within * their given constraints (if any, e.g., a day number being between 1 and 12). * * @param noAuthP the probability of having an HTTP call without any authentication header. */ fun sampleRandomAction(noAuthP: Double): HttpWsAction { val action = randomness.choose(actionCluster).copy() as HttpWsAction action.doInitialize(randomness) action.auth = getRandomAuth(noAuthP) return action } fun getRandomAuth(noAuthP: Double): HttpWsAuthenticationInfo { if (authentications.isEmpty() || randomness.nextBoolean(noAuthP)) { return NoAuth() } else { //if there is auth, should have high probability of using one, //as without auth we would do little. return randomness.choose(authentications) } } protected fun addAuthFromConfig(){ val headers = listOf(config.header0, config.header1, config.header2) .filter { it.isNotBlank() } if(headers.isEmpty()){ return //nothing to do } val dto = AuthenticationDto() headers.forEach { val k = it.indexOf(":") val name = it.substring(0, k) val content = it.substring(k+1) dto.headers.add(HeaderDto(name, content)) } dto.name = "Fixed Headers" handleAuthInfo(dto) } protected fun setupAuthentication(infoDto: SutInfoDto) { addAuthFromConfig() val info = infoDto.infoForAuthentication ?: return info.forEach { handleAuthInfo(it) } } private fun handleAuthInfo(i: AuthenticationDto) { if (i.name == null || i.name.isBlank()) { throw SutProblemException("Missing name in authentication info") } val headers: MutableList<AuthenticationHeader> = mutableListOf() i.headers.forEach loop@{ h -> val name = h.name?.trim() val value = h.value?.trim() if (name == null || value == null) { throw SutProblemException("Invalid header in ${i.name}, $name:$value") } headers.add(AuthenticationHeader(name, value)) } val cookieLogin = if (i.cookieLogin != null) { CookieLogin.fromDto(i.cookieLogin) } else { null } val jsonTokenPostLogin = if (i.jsonTokenPostLogin != null) { JsonTokenPostLogin.fromDto(i.jsonTokenPostLogin) } else { null } val auth = HttpWsAuthenticationInfo(i.name.trim(), headers, cookieLogin, jsonTokenPostLogin) authentications.add(auth) return } }
lgpl-3.0
56de6a61742e021604dba2f9c2bf5b4b
30.877049
100
0.651492
4.474108
false
false
false
false
atanana/si_counter
app/src/main/java/com/atanana/sicounter/usecases/SaveLogUseCase.kt
1
1809
package com.atanana.sicounter.usecases import android.content.Context import android.net.Uri import android.widget.Toast import androidx.annotation.StringRes import com.atanana.sicounter.R import com.atanana.sicounter.helpers.HistoryReportHelper import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.OutputStream class SaveLogUseCase( private val context: Context, private val historyReportHelper: HistoryReportHelper ) { suspend fun saveReport(uri: Uri?) { val result = trySaveReport(uri) val message = if (result) R.string.file_saved_message else R.string.file_save_error showToast(message) } private suspend fun trySaveReport(uri: Uri?): Boolean { return try { uri ?: return false val outputStream = openStream(uri) ?: return false outputStream.use { stream -> val report = createReport() writeReport(stream, report) } true } catch (e: Exception) { false } } private suspend fun writeReport(stream: OutputStream, report: String) { withContext(Dispatchers.IO) { val writer = stream.writer() writer.write(report) writer.flush() } } private suspend fun createReport(): String = withContext(Dispatchers.Default) { historyReportHelper.createReport().joinToString("\n") } private suspend fun openStream(uri: Uri) = withContext(Dispatchers.IO) { context.contentResolver.openOutputStream(uri) } private suspend fun showToast(@StringRes message: Int) { withContext(Dispatchers.Main) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show() } } }
mit
d8905c0edf8b1c9e1eeae8ef037eafac
29.166667
91
0.651189
4.674419
false
false
false
false