repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
kerubistan/kerub | src/main/kotlin/com/github/kerubistan/kerub/model/expectations/StoragePerformanceExpectation.kt | 2 | 295 | package com.github.kerubistan.kerub.model.expectations
import com.github.kerubistan.kerub.model.ExpectationLevel
import com.github.kerubistan.kerub.model.io.IoTune
interface StoragePerformanceExpectation : VirtualStorageExpectation {
override val level: ExpectationLevel
val speed: IoTune
}
| apache-2.0 |
chiken88/passnotes | app/src/main/kotlin/com/ivanovsky/passnotes/domain/interactor/note/NoteInteractor.kt | 1 | 1556 | package com.ivanovsky.passnotes.domain.interactor.note
import android.os.Handler
import android.os.Looper
import com.ivanovsky.passnotes.data.entity.Note
import com.ivanovsky.passnotes.data.entity.OperationResult
import com.ivanovsky.passnotes.data.repository.EncryptedDatabaseRepository
import com.ivanovsky.passnotes.data.repository.settings.Settings
import com.ivanovsky.passnotes.domain.ClipboardHelper
import com.ivanovsky.passnotes.domain.entity.DatabaseStatus
import com.ivanovsky.passnotes.domain.usecases.LockDatabaseUseCase
import com.ivanovsky.passnotes.domain.usecases.GetDatabaseStatusUseCase
import java.util.UUID
class NoteInteractor(
private val dbRepo: EncryptedDatabaseRepository,
private val clipboardHelper: ClipboardHelper,
private val lockUseCase: LockDatabaseUseCase,
private val getStatusUseCase: GetDatabaseStatusUseCase,
private val settings: Settings
) {
fun getNoteByUid(noteUid: UUID): OperationResult<Note> {
return dbRepo.noteRepository.getNoteByUid(noteUid)
}
fun copyToClipboardWithTimeout(text: String) {
clipboardHelper.copy(text)
val handler = Handler(Looper.getMainLooper())
handler.postDelayed({ clipboardHelper.clear() }, getTimeoutValueInMillis())
}
fun getTimeoutValueInMillis(): Long {
return settings.autoClearClipboardDelayInMs.toLong()
}
fun lockDatabase() {
lockUseCase.lockIfNeed()
}
suspend fun getDatabaseStatus(): OperationResult<DatabaseStatus> =
getStatusUseCase.getDatabaseStatus()
} | gpl-2.0 |
chiken88/passnotes | app/src/main/kotlin/com/ivanovsky/passnotes/util/IntentUtils.kt | 1 | 451 | package com.ivanovsky.passnotes.util
import android.content.Intent
import android.os.Build
object IntentUtils {
fun createFilePickerIntent(): Intent {
val action = if (Build.VERSION.SDK_INT >= 19) {
Intent.ACTION_OPEN_DOCUMENT
} else {
Intent.ACTION_GET_CONTENT
}
return Intent(action).apply {
type = "*/*";
addCategory(Intent.CATEGORY_OPENABLE)
}
}
} | gpl-2.0 |
breadwallet/breadwallet-android | ui/ui-staking/src/main/java/StakingInit.kt | 1 | 1632 | /**
* BreadWallet
*
* Created by Drew Carlson <[email protected]> on 10/30/20.
* Copyright (c) 2020 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.ui.uistaking
import com.breadwallet.ui.uistaking.Staking.F
import com.breadwallet.ui.uistaking.Staking.M
import com.spotify.mobius.First
import com.spotify.mobius.First.first
import com.spotify.mobius.Init
object StakingInit : Init<M, F> {
override fun init(model: M): First<M, F> =
first(model, setOf(
F.LoadAccount,
F.LoadAuthenticationSettings
))
}
| mit |
kerubistan/kerub | src/main/kotlin/com/github/kerubistan/kerub/host/distros/Gentoo.kt | 2 | 993 | package com.github.kerubistan.kerub.host.distros
import com.github.kerubistan.kerub.host.PackageManager
import com.github.kerubistan.kerub.host.execute
import com.github.kerubistan.kerub.host.packman.EmergePackageManager
import com.github.kerubistan.kerub.model.Host
import com.github.kerubistan.kerub.model.Version
import org.apache.sshd.client.session.ClientSession
class Gentoo : LsbDistribution("Gentoo") {
override fun getPackageManager(session: ClientSession): PackageManager = EmergePackageManager(session)
override fun getVersion(session: ClientSession): Version = Version.fromVersionString("0")
override fun handlesVersion(version: Version): Boolean = true // since gentoo does not really have releases
override fun installMonitorPackages(session: ClientSession, host: Host) {
//do nothing, at the moment it is not possible to install monitoring packages on gentoo
}
override fun detectHostCpuType(session: ClientSession): String = session.execute("uname -m").trim()
} | apache-2.0 |
AVnetWS/Hentoid | app/src/main/java/me/devsaki/hentoid/fragments/intro/ImportIntroFragment.kt | 1 | 10818 | package me.devsaki.hentoid.fragments.intro
import android.content.DialogInterface
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.BaseTransientBottomBar
import com.google.android.material.snackbar.Snackbar
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import me.devsaki.hentoid.R
import me.devsaki.hentoid.activities.IntroActivity
import me.devsaki.hentoid.databinding.IncludeImportStepsBinding
import me.devsaki.hentoid.databinding.IntroSlide04Binding
import me.devsaki.hentoid.events.ProcessEvent
import me.devsaki.hentoid.ui.BlinkAnimation
import me.devsaki.hentoid.util.FileHelper
import me.devsaki.hentoid.util.ImportHelper
import me.devsaki.hentoid.util.ImportHelper.setAndScanHentoidFolder
import me.devsaki.hentoid.util.Preferences
import me.devsaki.hentoid.workers.ImportWorker
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import timber.log.Timber
class ImportIntroFragment : Fragment(R.layout.intro_slide_04) {
private var _binding: IntroSlide04Binding? = null
private var _mergedBinding: IncludeImportStepsBinding? = null
private val binding get() = _binding!!
private val mergedBinding get() = _mergedBinding!!
private lateinit var importDisposable: Disposable
private val pickFolder = registerForActivityResult(ImportHelper.PickFolderContract()) { res ->
onFolderPickerResult(res.left, res.right)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
EventBus.getDefault().register(this)
}
override fun onDestroy() {
EventBus.getDefault().unregister(this)
super.onDestroy()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = IntroSlide04Binding.inflate(inflater, container, false)
// We need to manually bind the merged view - it won't work at runtime with the main view alone
_mergedBinding = IncludeImportStepsBinding.bind(binding.root)
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
mergedBinding.importStep1Button.setOnClickListener {
binding.skipBtn.visibility = View.INVISIBLE
pickFolder.launch(0)
}
mergedBinding.importStep1Button.visibility = View.VISIBLE
binding.skipBtn.setOnClickListener { askSkip() }
}
private fun onFolderPickerResult(resultCode: Int, treeUri: Uri?) {
when (resultCode) {
ImportHelper.PickerResult.OK -> {
if (null == treeUri) return
binding.waitTxt.visibility = View.VISIBLE
val animation = BlinkAnimation(750, 20)
binding.waitTxt.startAnimation(animation)
importDisposable = io.reactivex.Single.fromCallable {
setAndScanHentoidFolder(
requireContext(),
treeUri,
true,
null
)
}
.subscribeOn(io.reactivex.schedulers.Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ result: Int ->
run {
binding.waitTxt.clearAnimation()
binding.waitTxt.visibility = View.GONE
onScanHentoidFolderResult(result)
}
},
{ t: Throwable? -> Timber.w(t) }
)
}
ImportHelper.PickerResult.KO_CANCELED -> {
Snackbar.make(
binding.root,
R.string.import_canceled,
BaseTransientBottomBar.LENGTH_LONG
).show()
binding.skipBtn.visibility = View.VISIBLE
}
ImportHelper.PickerResult.KO_OTHER, ImportHelper.PickerResult.KO_NO_URI -> {
Snackbar.make(
binding.root,
R.string.import_other,
BaseTransientBottomBar.LENGTH_LONG
).show()
binding.skipBtn.visibility = View.VISIBLE
}
}
}
private fun onScanHentoidFolderResult(resultCode: Int) {
importDisposable.dispose()
when (resultCode) {
ImportHelper.ProcessFolderResult.OK_EMPTY_FOLDER -> nextStep()
ImportHelper.ProcessFolderResult.OK_LIBRARY_DETECTED -> { // Import service is already launched by the Helper; nothing else to do
updateOnSelectFolder()
return
}
ImportHelper.ProcessFolderResult.OK_LIBRARY_DETECTED_ASK -> {
updateOnSelectFolder()
ImportHelper.showExistingLibraryDialog(requireContext()) { onCancelExistingLibraryDialog() }
return
}
ImportHelper.ProcessFolderResult.KO_INVALID_FOLDER -> Snackbar.make(
binding.root,
R.string.import_invalid,
BaseTransientBottomBar.LENGTH_LONG
).show()
ImportHelper.ProcessFolderResult.KO_APP_FOLDER -> Snackbar.make(
binding.root,
R.string.import_invalid,
BaseTransientBottomBar.LENGTH_LONG
).show()
ImportHelper.ProcessFolderResult.KO_DOWNLOAD_FOLDER -> Snackbar.make(
binding.root,
R.string.import_download_folder,
BaseTransientBottomBar.LENGTH_LONG
).show()
ImportHelper.ProcessFolderResult.KO_CREATE_FAIL -> Snackbar.make(
binding.root,
R.string.import_create_fail,
BaseTransientBottomBar.LENGTH_LONG
).show()
ImportHelper.ProcessFolderResult.KO_OTHER -> Snackbar.make(
binding.root,
R.string.import_other,
BaseTransientBottomBar.LENGTH_LONG
).show()
}
binding.skipBtn.visibility = View.VISIBLE
}
private fun updateOnSelectFolder() {
mergedBinding.importStep1Button.visibility = View.INVISIBLE
mergedBinding.importStep1Folder.text = FileHelper.getFullPathFromTreeUri(
requireContext(),
Uri.parse(Preferences.getStorageUri())
)
mergedBinding.importStep1Check.visibility = View.VISIBLE
mergedBinding.importStep2.visibility = View.VISIBLE
mergedBinding.importStep2Bar.isIndeterminate = true
binding.skipBtn.visibility = View.INVISIBLE
}
private fun onCancelExistingLibraryDialog() {
// Revert back to initial state where only the "Select folder" button is visible
mergedBinding.importStep1Button.visibility = View.VISIBLE
mergedBinding.importStep1Folder.text = ""
mergedBinding.importStep1Check.visibility = View.INVISIBLE
mergedBinding.importStep2.visibility = View.INVISIBLE
binding.skipBtn.visibility = View.VISIBLE
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onMigrationEvent(event: ProcessEvent) {
val progressBar: ProgressBar = when (event.step) {
ImportWorker.STEP_2_BOOK_FOLDERS -> mergedBinding.importStep2Bar
ImportWorker.STEP_3_BOOKS -> mergedBinding.importStep3Bar
else -> mergedBinding.importStep4Bar
}
if (ProcessEvent.EventType.PROGRESS == event.eventType) {
if (event.elementsTotal > -1) {
progressBar.isIndeterminate = false
progressBar.max = event.elementsTotal
progressBar.progress = event.elementsOK + event.elementsKO
} else progressBar.isIndeterminate = true
if (ImportWorker.STEP_3_BOOKS == event.step) {
mergedBinding.importStep2Check.visibility = View.VISIBLE
mergedBinding.importStep3.visibility = View.VISIBLE
mergedBinding.importStep3Text.text = resources.getString(
R.string.api29_migration_step3,
event.elementsKO + event.elementsOK,
event.elementsTotal
)
} else if (ImportWorker.STEP_4_QUEUE_FINAL == event.step) {
mergedBinding.importStep3Check.visibility = View.VISIBLE
mergedBinding.importStep4.visibility = View.VISIBLE
}
} else if (ProcessEvent.EventType.COMPLETE == event.eventType) {
when {
ImportWorker.STEP_2_BOOK_FOLDERS == event.step -> {
mergedBinding.importStep2Check.visibility = View.VISIBLE
mergedBinding.importStep3.visibility = View.VISIBLE
}
ImportWorker.STEP_3_BOOKS == event.step -> {
mergedBinding.importStep3Text.text = resources.getString(
R.string.api29_migration_step3,
event.elementsTotal,
event.elementsTotal
)
mergedBinding.importStep3Check.visibility = View.VISIBLE
mergedBinding.importStep4.visibility = View.VISIBLE
}
ImportWorker.STEP_4_QUEUE_FINAL == event.step -> {
mergedBinding.importStep4Check.visibility = View.VISIBLE
nextStep()
}
}
}
}
private fun askSkip() {
val materialDialog: AlertDialog = MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.slide_04_skip_title)
.setMessage(R.string.slide_04_skip_msg)
.setCancelable(true)
.setPositiveButton(android.R.string.ok) { _: DialogInterface, _: Int -> nextStep() }
.setNegativeButton(android.R.string.cancel, null)
.create()
materialDialog.setIcon(R.drawable.ic_warning)
materialDialog.show()
}
private fun nextStep() {
val parentActivity = requireActivity() as IntroActivity
parentActivity.nextStep()
binding.skipBtn.visibility = View.VISIBLE
}
} | apache-2.0 |
yiyocx/YitLab | app/src/main/kotlin/yiyo/gitlabandroid/mvp/presenters/LoginPresenter.kt | 2 | 2570 | package yiyo.gitlabandroid.mvp.presenters
import android.text.TextUtils
import android.util.Log
import yiyo.gitlabandroid.R
import yiyo.gitlabandroid.domain.LoginUseCase
import yiyo.gitlabandroid.model.entities.Session
import yiyo.gitlabandroid.mvp.views.LoginView
import yiyo.gitlabandroid.utils.Configuration
import yiyo.gitlabandroid.utils.tag
/**
* Created by yiyo on 11/07/15.
*/
class LoginPresenter(private val loginView: LoginView) : Presenter {
override fun onResume() {
// Unused
}
override fun onPause() {
// Unused
}
fun login(username: String, password: String) {
loginView.showProgress()
if (valid(username, password)) {
LoginUseCase(username, password, loginView.getContext())
.execute()
.subscribe(
{ session: Session -> onSessionReceived(session) },
{ error: Throwable -> manageError(error) },
{ loginView.hideProgress() }
)
} else {
loginView.hideProgress()
}
}
fun valid(username: String, password: String): Boolean {
var valid = true
// Check for a valid password, if the user entered one.
if (TextUtils.isEmpty(password)) {
loginView.setupPasswordError(loginView.getContext().getString(R.string.error_field_required))
valid = false
} else {
loginView.setupPasswordError(null)
}
// Check for a valid username address.
if (TextUtils.isEmpty(username)) {
loginView.setupUsernameError(loginView.getContext().getString(R.string.error_field_required))
valid = false
} else {
loginView.setupUsernameError(null)
}
return valid
}
fun onSessionReceived(session: Session) {
val configuration = Configuration(loginView.getContext())
val sessionCreated = configuration.createSession(
session.name, session.username, session.email,
session.privateToken, session.id)
if (sessionCreated) {
loginView.navigateToHome()
Log.i(tag(), "The user has successfully logged")
} else {
Log.e(tag(), "There was a problem creating the session in the SharedPreferences")
}
}
fun manageError(error: Throwable) {
loginView.hideProgress()
// Log.e(tag(), error.getMessage(), error)
// loginView.showConnectionError(error as RetrofitError)
}
}
| gpl-2.0 |
siosio/nablarch-helper | src/main/java/siosio/repository/converter/ListPsiClassConverter.kt | 1 | 1921 | package siosio.repository.converter
import com.intellij.psi.*
import com.intellij.psi.impl.source.*
import com.intellij.psi.impl.source.resolve.reference.impl.providers.*
import com.intellij.psi.util.*
import com.intellij.util.xml.*
import inHandlerQueue
import parameterList
import siosio.repository.*
import siosio.repository.xml.*
class ListPsiClassConverter : RepositoryPsiClassConverter() {
override fun createClassReferenceProvider(value: GenericDomValue<PsiClass>,
context: ConvertContext,
extendClass: ExtendClass?): JavaClassReferenceProvider {
val provider = super.createClassReferenceProvider(value, context, extendClass)
val domElement = DomUtil.getDomElement(value.xmlElement) ?: return provider
val propertyTag = domElement.getParentOfType(Property::class.java, true)
val parameterType = propertyTag?.let { property ->
property.parameterList().firstOrNull()?.type
?.let { type ->
when (type) {
is PsiClassReferenceType -> type.reference.typeParameters.firstOrNull()
else -> null
}
}
} ?: run {
// プロパティ配下じゃない場合は、handlerQueue定義かどうかを探す
if (domElement.inHandlerQueue()) {
createHandlerInterfaceType(value.xmlElement!!.project)
} else {
null
}
} ?: return provider
when (parameterType) {
is PsiWildcardType -> PsiTypesUtil.getPsiClass(parameterType.bound)
else -> PsiTypesUtil.getPsiClass(parameterType)
}?.let {
provider.setOption(JavaClassReferenceProvider.EXTEND_CLASS_NAMES, arrayOf(it.qualifiedName))
}
return provider
}
}
| apache-2.0 |
like5188/Common | common/src/main/java/com/like/common/util/JSONObjectEx.kt | 1 | 221 | package com.like.common.util
import org.json.JSONObject
fun JSONObject.optStringForEmptyString(name: String) =
if (this.isNull(name)) {
""
} else {
this.optString(name)
}
| apache-2.0 |
Magneticraft-Team/ModelLoader | src/main/kotlin/com/cout970/modelloader/animation/ICompactModelData.kt | 1 | 636 | package com.cout970.modelloader.animation
import javax.vecmath.Vector2d
import javax.vecmath.Vector3d
/**
* Represents a model that uses a compact format when vertices are de-duped.
*/
interface ICompactModelData {
val indices: List<Int>?
val pos: List<Vector3d>
val tex: List<Vector2d>
val count: Int
val triangles: Boolean
}
/**
* Default implementation of ICompactModelData
*/
data class CompactModelData(
override val indices: List<Int>?,
override val pos: List<Vector3d>,
override val tex: List<Vector2d>,
override val count: Int,
override val triangles: Boolean
) : ICompactModelData | gpl-2.0 |
EMResearch/EvoMaster | core-it/src/test/kotlin/org/evomaster/core/mutatortest/OneMaxMutator.kt | 1 | 5125 | package org.evomaster.core.mutatortest
import com.google.inject.Injector
import com.google.inject.Key
import com.google.inject.TypeLiteral
import com.netflix.governator.guice.LifecycleInjector
import com.netflix.governator.lifecycle.LifecycleManager
import org.apache.commons.math3.stat.inference.MannWhitneyUTest
import org.evomaster.core.BaseModule
import org.evomaster.core.EMConfig
import org.evomaster.core.search.algorithms.MioAlgorithm
import org.evomaster.core.search.algorithms.onemax.ManipulatedOneMaxModule
import org.evomaster.core.search.algorithms.onemax.ManipulatedOneMaxMutator
import org.evomaster.core.search.algorithms.onemax.OneMaxIndividual
import org.evomaster.core.search.algorithms.onemax.OneMaxSampler
import org.evomaster.core.search.service.mutator.EvaluatedMutation
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.StandardOpenOption
import java.time.LocalDateTime
/**
* created by manzh on 2020-06-24
*/
class OneMaxMutator {
private val utest = MannWhitneyUTest()
fun mutatorExp(){
val targetsExp = listOf(50, 100, 500, 1000)
val first = listOf(true, false)
val improve = listOf(true, false)
val sample = 30
val path = Paths.get("target/mutatorWithOneMaxTest/summary.txt")
if (Files.exists(path))
Files.write(path, LocalDateTime.now().toString().toByteArray(), StandardOpenOption.APPEND)
else{
Files.createDirectories(path.parent)
Files.write(path, LocalDateTime.now().toString().toByteArray())
}
listOf(100, 500, 900).forEach {b->
targetsExp.forEach { n->
improve.forEach { i->
val map = mutableMapOf<String, MutableList<Pair<Double, Double>>>()
val content = mutableListOf<String>()
first.forEach { f->
(0 until sample).forEach {runs->
run(runs, n, i, f, b, map)
}
}
map.forEach { t, u ->
content.add("$t ,tp: ${u.map { it.first }.average()}, coverage: ${u.map { it.second }.average()}")
}
val keys = map.keys.toList()
assert(map.size == 2)
val pTP = utest.mannWhitneyUTest(map[keys.first()]!!.map { it.first }.toDoubleArray(), map[keys.last()]!!.map { it.first }.toDoubleArray())
val pCOV = utest.mannWhitneyUTest(map[keys.first()]!!.map { it.second }.toDoubleArray(), map[keys.last()]!!.map { it.second }.toDoubleArray())
content.add("${keys.first()} vs. ${keys.last()}, tp:$pTP, coverage: $pCOV")
Files.write(path, content, StandardOpenOption.APPEND)
}
}
}
}
private fun run(runs : Int, n : Int, improve: Boolean, first : Boolean, budget : Int, map: MutableMap<String, MutableList<Pair<Double, Double>>>){
val injector: Injector = LifecycleInjector.builder()
.withModules(ManipulatedOneMaxModule(), BaseModule())
.build().createInjector()
val mutator = injector.getInstance(Key.get(
object : TypeLiteral<ManipulatedOneMaxMutator>() {}))
val mio = injector.getInstance(Key.get(
object : TypeLiteral<MioAlgorithm<OneMaxIndividual>>() {}))
val config = injector.getInstance(EMConfig::class.java)
val sampler = injector.getInstance(OneMaxSampler::class.java)
config.stoppingCriterion = EMConfig.StoppingCriterion.FITNESS_EVALUATIONS
mutator.improve = improve
sampler.n = n
config.showProgress = false
config.mutationTargetsSelectionStrategy = if (first) EMConfig.MutationTargetsSelectionStrategy.FIRST_NOT_COVERED_TARGET else EMConfig.MutationTargetsSelectionStrategy.EXPANDED_UPDATED_NOT_COVERED_TARGET
config.maxActionEvaluations = budget
val expId = listOf("${config.mutationTargetsSelectionStrategy}", "budget-$budget","#targets-$n", "improvingMutator-$improve").joinToString("_")
config.mutatedGeneFile = "target/mutatorWithOneMaxTest/${expId}_runs$runs.csv"
Files.deleteIfExists(Paths.get(config.mutatedGeneFile))
val m = injector.getInstance(LifecycleManager::class.java)
m.start()
val solution = mio.search()
m.close()
val tp = reportFP(config.mutatedGeneFile, improve)
val covered = solution.overall.coveredTargets() * 1.0 /n
val result = Pair(tp, covered)
map.getOrPut(expId){ mutableListOf()}.add(result)
}
private fun reportFP(path : String, improve : Boolean) : Double{
val contents = Files.readAllLines(Paths.get(path))
val tp = contents.count {
val result = it.split(",")[1]
if (improve) result == EvaluatedMutation.WORSE_THAN.name else result != EvaluatedMutation.WORSE_THAN.name
}
return tp * 1.0 / contents.size
}
}
fun main(array: Array<String>){
OneMaxMutator().mutatorExp()
} | lgpl-3.0 |
oversecio/oversec_crypto | crypto/src/main/java/io/oversec/one/crypto/sym/ui/KeyDetailsActivity.kt | 1 | 12074 | package io.oversec.one.crypto.sym.ui
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Fragment
import android.content.Context
import android.content.Intent
import android.content.IntentSender
import android.graphics.Bitmap
import android.os.Bundle
import android.util.TypedValue
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.WindowManager
import com.afollestad.materialdialogs.MaterialDialog
import io.oversec.one.common.MainPreferences
import io.oversec.one.crypto.Help
import io.oversec.one.crypto.R
import io.oversec.one.crypto.TemporaryContentProvider
import io.oversec.one.crypto.sym.*
import io.oversec.one.crypto.symbase.KeyUtil
import io.oversec.one.crypto.symbase.OversecKeyCacheListener
import io.oversec.one.crypto.ui.NewPasswordInputDialog
import io.oversec.one.crypto.ui.NewPasswordInputDialogCallback
import io.oversec.one.crypto.ui.SecureBaseActivity
import io.oversec.one.crypto.ui.util.Util
import kotlinx.android.synthetic.main.sym_activity_key_details.*
import kotlinx.android.synthetic.main.sym_content_key_details.*
import roboguice.util.Ln
import java.text.SimpleDateFormat
class KeyDetailsActivity : SecureBaseActivity(), OversecKeyCacheListener {
private lateinit var mKeystore:OversecKeystore2
private var mId: Long = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mKeystore = OversecKeystore2.getInstance(this)
if (!MainPreferences.isAllowScreenshots(this)) {
window.setFlags(
WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE
)
}
mId = intent.getLongExtra(EXTRA_ID, 0)
val key = mKeystore.getSymmetricKeyEncrypted(mId)
if (key == null) {
Ln.w("couldn't find request key with id %s", mId)
finish()
return
}
setContentView(R.layout.sym_activity_key_details)
setSupportActionBar(toolbar)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
btRevealQr.setOnClickListener { showPlainKeyQR() }
tv_alias.text = key.name
tv_hash.text = SymUtil.longToPrettyHex(key.id)
val createdDate = key.createdDate
tv_date.text = SimpleDateFormat.getDateTimeInstance().format(
createdDate
)
setKeyImage(true)
fab.setOnClickListener { showConfirmDialog() }
refreshConfirm()
SymUtil.applyAvatar(tvAvatar, key.name!!)
mKeystore.addKeyCacheListener(this)
}
private fun showPlainKeyQR() {
val ok = setKeyImage(false)
if (!ok) {
UnlockKeyActivity.showForResult(this, mId, RQ_UNLOCK)
} else {
btRevealQr.visibility = View.GONE
}
}
private fun setKeyImage(blur: Boolean): Boolean {
val dimension =
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 240f, resources.displayMetrics)
.toInt()
try {
var bm: Bitmap?
if (blur) {
bm = SymUtil.getQrCode(KeyUtil.getRandomBytes(32), dimension)
val bmSmallTmp = Bitmap.createScaledBitmap(bm!!, 25, 25, true)
bm = Bitmap.createScaledBitmap(bmSmallTmp, dimension, dimension, true)
} else {
bm = SymUtil.getQrCode(mKeystore.getPlainKeyAsTransferBytes(mId), dimension)
}
ivQr.setImageBitmap(bm)
return true
} catch (ex: KeyNotCachedException) {
ex.printStackTrace()
} catch (ex: Exception) {
ex.printStackTrace()
}
return false
}
@SuppressLint("RestrictedApi")
private fun refreshConfirm() {
val confirmDate = mKeystore.getConfirmDate(mId)
fab.visibility = if (confirmDate == null) View.VISIBLE else View.GONE
tv_confirmed.text = if (confirmDate == null)
getString(R.string.label_key_unconfirmed)
else
SimpleDateFormat.getDateTimeInstance().format(
confirmDate
)
ivConfirmed.visibility = if (confirmDate == null) View.GONE else View.VISIBLE
ivUnConfirmed.visibility = if (confirmDate == null) View.VISIBLE else View.GONE
}
private fun showConfirmDialog() {
val fp = mId
//TODO: make custom dialog. highlight the fingerprint, monospace typeface
MaterialDialog.Builder(this)
.title(R.string.app_name)
.iconRes(R.drawable.ic_warning_black_24dp)
.cancelable(true)
.content(getString(R.string.dialog_confirm_key_text, SymUtil.longToPrettyHex(fp)))
.positiveText(R.string.common_ok)
.onPositive { dialog, which ->
try {
mKeystore.confirmKey(mId)
refreshConfirm()
} catch (e: Exception) {
e.printStackTrace()
showError(getString(R.string.common_error_body, e.message), null)
}
}
.negativeText(R.string.common_cancel)
.onNegative { dialog, which -> dialog.dismiss() }
.show()
}
private fun showDeleteDialog() {
MaterialDialog.Builder(this)
.title(R.string.app_name)
.iconRes(R.drawable.ic_warning_black_24dp)
.cancelable(true)
.content(getString(R.string.action_delete_key_confirm))
.positiveText(R.string.common_ok)
.onPositive { dialog, which ->
try {
mKeystore.deleteKey(mId)
setResult(Activity.RESULT_FIRST_USER)
finish()
} catch (e: Exception) {
e.printStackTrace()
showError(getString(R.string.common_error_body, e.message), null)
}
}
.negativeText(R.string.common_cancel)
.onNegative { dialog, which -> dialog.dismiss() }
.show()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_key_details, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
when (id) {
android.R.id.home -> finish()
R.id.action_delete_key -> {
showDeleteDialog()
return true
}
R.id.action_send_encrypted -> {
share(RQ_SEND_ENCRYPTED)
return true
}
R.id.action_view_encrypted -> {
share(RQ_VIEW_ENCRYPTED)
return true
}
R.id.help -> {
Help.open(this, Help.ANCHOR.symkey_details)
return true
}
}
return super.onOptionsItemSelected(item)
}
private fun share(rq: Int) {
try {
val plainKey = mKeystore.getPlainKey(mId)
share(plainKey, rq)
} catch (e: KeyNotCachedException) {
try {
startIntentSenderForResult(e.pendingIntent.intentSender, rq, null, 0, 0, 0)
} catch (e1: IntentSender.SendIntentException) {
e1.printStackTrace()
}
}
}
private fun share(plainKey: SymmetricKeyPlain, rq: Int) {
val cb = object : NewPasswordInputDialogCallback {
override fun positiveAction(pw: CharArray) {
share(pw, plainKey, rq)
}
override fun neutralAction() {
}
}
NewPasswordInputDialog.show(this, NewPasswordInputDialog.MODE.SHARE, cb)
}
private fun share(pw: CharArray, plainKey: SymmetricKeyPlain, rq: Int) {
val d = MaterialDialog.Builder(this)
.title(R.string.progress_encrypting)
.content(R.string.please_wait_encrypting)
.progress(true, 0)
.cancelable(false)
.show()
val t = Thread(Runnable {
try {
val encKey = mKeystore.encryptSymmetricKey(plainKey, pw)
d.dismiss()
runOnUiThread { share(encKey, rq) }
} catch (e: Exception) {
e.printStackTrace()
d.dismiss()
runOnUiThread {
showError(
getString(
R.string.common_error_body,
e.message
), null
)
}
} finally {
KeyUtil.erase(pw)
}
})
t.start()
}
private fun share(encKey: SymmetricKeyEncrypted, rq: Int) {
try {
val uri = TemporaryContentProvider.prepare(
this,
"image/png",
TemporaryContentProvider.TTL_1_HOUR,
null
)
val bm = SymUtil.getQrCode(
OversecKeystore2.getEncryptedKeyAsTransferBytes(encKey),
KEYSHARE_BITMAP_WIDTH_PX
)
val os = contentResolver.openOutputStream(uri)
?: //damnit
return
bm!!.compress(Bitmap.CompressFormat.PNG, 100, os)
os.close()
val intent = Intent()
var cid = 0
if (rq == RQ_SEND_ENCRYPTED) {
intent.action = Intent.ACTION_SEND
intent.putExtra(Intent.EXTRA_STREAM, uri)
intent.type = "image/png"
cid = R.string.intent_chooser_send_encryptedkey
} else if (rq == RQ_VIEW_ENCRYPTED) {
intent.action = Intent.ACTION_VIEW
intent.setDataAndType(uri, "image/png")
cid = R.string.intent_chooser_view_encryptedkey
}
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
Util.share(this, intent, null, getString(cid), true, null, false)
} catch (ex: Exception) {
ex.printStackTrace()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (RQ_UNLOCK == requestCode) {
if (resultCode == Activity.RESULT_OK) {
setKeyImage(false)
btRevealQr.visibility = View.GONE
}
} else if (RQ_SEND_ENCRYPTED == requestCode) {
if (resultCode == Activity.RESULT_OK) {
share(RQ_SEND_ENCRYPTED)
}
} else if (RQ_VIEW_ENCRYPTED == requestCode) {
if (resultCode == Activity.RESULT_OK) {
share(RQ_VIEW_ENCRYPTED)
}
}
}
override fun onDestroy() {
mKeystore.removeKeyCacheListener(this)
super.onDestroy()
}
override fun onFinishedCachingKey(keyId: Long) {
if (mId == keyId) {
finish()
}
}
override fun onStartedCachingKey(keyId: Long) {
}
companion object {
private const val EXTRA_ID = "id"
private const val RQ_UNLOCK = 1008
private const val RQ_SEND_ENCRYPTED = 1009
private const val RQ_VIEW_ENCRYPTED = 1010
private const val KEYSHARE_BITMAP_WIDTH_PX = 480
fun show(ctx: Context, keyId: Long?) {
val i = Intent()
i.setClass(ctx, KeyDetailsActivity::class.java)
if (ctx !is Activity) {
i.flags = Intent.FLAG_ACTIVITY_NEW_TASK
}
i.putExtra(EXTRA_ID, keyId)
ctx.startActivity(i)
}
fun showForResult(f: Fragment, rq: Int, id: Long) {
val i = Intent()
i.setClass(f.activity, KeyDetailsActivity::class.java)
i.putExtra(EXTRA_ID, id)
f.startActivityForResult(i, rq)
}
}
}
| gpl-3.0 |
ibinti/intellij-community | java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/inlays/JavaParameterNameHintsTest.kt | 1 | 20000 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.java.codeInsight.daemon.inlays
import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager
import com.intellij.codeInsight.hints.JavaInlayParameterHintsProvider
import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.lang.java.JavaLanguage
import com.intellij.openapi.editor.Inlay
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
import org.assertj.core.api.Assertions.assertThat
class JavaInlayParameterHintsTest : LightCodeInsightFixtureTestCase() {
override fun tearDown() {
val default = ParameterNameHintsSettings()
ParameterNameHintsSettings.getInstance().loadState(default.state)
super.tearDown()
}
fun check(text: String) {
myFixture.configureByText("A.java", text)
myFixture.testInlays()
}
fun `test insert literal arguments`() {
check("""
class Groo {
public void test(File file) {
boolean testNow = System.currentTimeMillis() > 34000;
int times = 1;
float pi = 4;
String title = "Testing...";
char ch = 'q';
configure(<hint text="testNow:"/>true, <hint text="times:"/>555, <hint text="pii:"/>3.141f, <hint text="title:"/>"Huge Title", <hint text="terminate:"/>'c', <hint text="file:"/>null);
configure(testNow, shouldIgnoreRoots(), fourteen, pi, title, c, file);
}
public void configure(boolean testNow, int times, float pii, String title, char terminate, File file) {
System.out.println();
System.out.println();
}
}""")
}
fun `test do not show for Exceptions`() {
check("""
class Fooo {
public void test() {
Throwable t = new IllegalStateException("crime");
}
}
""")
}
fun `test show hint for single string literal if there is multiple string params`() {
check("""class Groo {
public void test() {
String message = "sdfsdfdsf";
assertEquals(<hint text="expected:"/>"fooo", message);
String title = "TT";
show(title, <hint text="message:"/>"Hi");
}
public void assertEquals(String expected, String actual) {}
public void show(String title, String message) {}
}""")
}
fun `test no hints for generic builders`() {
check("""
class Foo {
void test() {
new IntStream().skip(10);
new Stream<Integer>().skip(10);
}
}
class IntStream {
public IntStream skip(int n) {}
}
class Stream<T> {
public Stream<T> skip(int n) {}
}
""")
JavaInlayParameterHintsProvider.getInstance().isDoNotShowForBuilderLikeMethods.set(false)
check("""
class Foo {
void test() {
new IntStream().skip(<hint text="n:"/>10);
new Stream<Integer>().skip(<hint text="n:"/>10);
}
}
class IntStream {
public IntStream skip(int n) {}
}
class Stream<T> {
public Stream<T> skip(int n) {}
}
""")
}
fun `test do not show hints on setters`() {
check("""class Groo {
public void test() {
setTestNow(false);
System.out.println("");
}
public void setTestNow(boolean testNow) {
System.out.println("");
System.out.println("");
}
}""")
}
fun `test single varargs hint`() {
check("""
public class VarArgTest {
public void main() {
System.out.println("AAA");
testBooleanVarargs(<hint text="test:"/>13, <hint text="...booleans:"/>false);
}
public boolean testBooleanVarargs(int test, Boolean... booleans) {
int temp = test;
return false;
}
}
""")
}
fun `test no hint if varargs null`() {
check("""
public class VarArgTest {
public void main() {
System.out.println("AAA");
testBooleanVarargs(<hint text="test:"/>13);
}
public boolean testBooleanVarargs(int test, Boolean... booleans) {
int temp = test;
return false;
}
}
""")
}
fun `test multiple vararg hint`() {
check("""
public class VarArgTest {
public void main() {
System.out.println("AAA");
testBooleanVarargs(<hint text="test:"/>13, <hint text="...booleans:"/>false, true, false);
}
public boolean testBooleanVarargs(int test, Boolean... booleans) {
int temp = test;
return false;
}
}
""")
}
fun `test do not inline known subsequent parameter names`() {
check("""
public class Test {
public void main() {
test1(1, 2);
test2(1, 2);
test3(1, 2);
doTest("first", "second");
}
public void test1(int first, int second) {
int start = first;
int end = second;
}
public void test2(int key, int value) {
int start = key;
int end = value;
}
public void test3(int key, int value) {
int start = key;
int end = value;
}
}
""")
}
fun `test show if can be assigned`() {
check("""
public class CharSymbol {
public void main() {
Object obj = new Object();
count(<hint text="test:"/>100, <hint text="boo:"/>false, <hint text="seq:"/>"Hi!");
}
public void count(Integer test, Boolean boo, CharSequence seq) {
int a = test;
Object obj = new Object();
}
}
""")
}
fun `test inline positive and negative numbers`() {
check("""
public class CharSymbol {
public void main() {
Object obj = new Object();
count(<hint text="test:"/>-1, obj);
count(<hint text="test:"/>+1, obj);
}
public void count(int test, Object obj) {
Object tmp = obj;
boolean isFast = false;
}
}
""")
}
fun `test inline literal arguments with crazy settings`() {
check("""
public class Test {
public void main(boolean isActive, boolean requestFocus, int xoo) {
System.out.println("AAA");
main(<hint text="isActive:"/>true,<hint text="requestFocus:"/>false, /*comment*/<hint text="xoo:"/>2);
}
}
""")
}
fun `test ignored methods`() {
check("""
public class Test {
List<String> list = new ArrayList<>();
StringBuilder builder = new StringBuilder();
public void main() {
System.out.println("A");
System.out.print("A");
list.add("sss");
list.get(1);
list.set(1, "sss");
setNewIndex(10);
"sss".contains("s");
builder.append("sdfsdf");
"sfsdf".startWith("s");
"sss".charAt(3);
clearStatus(<hint text="updatedRecently:"/>false);
}
void print(String s) {}
void println(String s) {}
void get(int index) {}
void set(int index, Object object) {}
void append(String s) {}
void clearStatus(boolean updatedRecently) {}
}
""")
}
fun `test hints for generic arguments`() {
check("""
class QList<E> {
void add(int query, E obj) {}
}
class QCmp<E> {
void cmpre(E o1, E o2) {}
}
public class Test {
public void main(QCmp<Integer> c, QList<String> l) {
c.cmpre(<hint text="o1:"/>0, /** ddd */<hint text="o2:"/>3);
l.add(<hint text="query:"/>1, <hint text="obj:"/>"uuu");
}
}
""")
}
fun `test inline constructor literal arguments names`() {
check("""
public class Test {
public void main() {
System.out.println("AAA");
Checker r = new Checker(<hint text="isActive:"/>true, <hint text="requestFocus:"/>false) {
@Override
void test() {
}
};
}
abstract class Checker {
Checker(boolean isActive, boolean requestFocus) {}
abstract void test();
}
}
""")
}
fun `test inline anonymous class constructor parameters`() {
check("""
public class Test {
Test(int counter, boolean shouldTest) {
System.out.println();
System.out.println();
}
public static void main() {
System.out.println();
Test t = new Test(<hint text="counter:"/>10, <hint text="shouldTest:"/>false);
}
}
""")
}
fun `test inline if one of vararg params is literal`() {
check("""
public class VarArgTest {
public void main() {
System.out.println("AAA");
int test = 13;
boolean isCheck = false;
boolean isOk = true;
testBooleanVarargs(test, <hint text="...booleans:"/>isCheck, true, isOk);
}
public boolean testBooleanVarargs(int test, Boolean... booleans) {
int temp = test;
return false;
}
}
""")
}
fun `test if any param matches inline all`() {
check("""
public class VarArgTest {
public void main() {
check(<hint text="x:"/>10, <hint text="paramNameLength:"/>1000);
}
public void check(int x, int paramNameLength) {
}
}
""")
}
fun `test inline common name pair if more that 2 args`() {
check("""
public class VarArgTest {
public void main() {
String s = "su";
check(<hint text="beginIndex:"/>10, <hint text="endIndex:"/>1000, s);
}
public void check(int beginIndex, int endIndex, String params) {
}
}
""")
}
fun `test ignore String methods`() {
check("""
class Test {
public void main() {
String.format("line", "eee", "www");
}
}
""")
}
fun `test inline common name pair if more that 2 args xxx`() {
check("""
public class VarArgTest {
public void main() {
check(<hint text="beginIndex:"/>10, <hint text="endIndex:"/>1000, <hint text="x:"/>"su");
}
public void check(int beginIndex, int endIndex, String x) {
}
}
""")
}
fun `test inline this`() {
check("""
public class VarArgTest {
public void main() {
check(<hint text="test:"/>this, <hint text="endIndex:"/>1000);
}
public void check(VarArgTest test, int endIndex) {
}
}
""")
}
fun `test inline strange methods`() {
check("""
public class Test {
void main() {
createContent(<hint text="manager:"/>null);
createNewContent(<hint text="test:"/>this);
}
Content createContent(DockManager manager) {}
Content createNewContent(Test test) {}
}
interface DockManager {}
interface Content {}
""")
}
fun `test do not inline builder pattern`() {
check("""
class Builder {
void await(boolean value) {}
Builder bwait(boolean xvalue) {}
Builder timeWait(int time) {}
}
class Test {
public void test() {
Builder builder = new Builder();
builder.await(<hint text="value:"/>true);
builder.bwait(false).timeWait(100);
}
}
""")
JavaInlayParameterHintsProvider.getInstance().isDoNotShowForBuilderLikeMethods.set(false)
check("""
class Builder {
void await(boolean value) {}
Builder bwait(boolean xvalue) {}
Builder timeWait(int millis) {}
}
class Test {
public void test() {
Builder builder = new Builder();
builder.await(<hint text="value:"/>true);
builder.bwait(<hint text="xvalue:"/>false).timeWait(<hint text="millis:"/>100);
}
}
""")
}
fun `test builder method only method with one param`() {
check("""
class Builder {
Builder qwit(boolean value, String sValue) {}
Builder trew(boolean value) {}
}
class Test {
public void test() {
Builder builder = new Builder();
builder
.trew(false)
.qwit(<hint text="value:"/>true, <hint text="sValue:"/>"value");
}
}
""")
JavaInlayParameterHintsProvider.getInstance().isDoNotShowForBuilderLikeMethods.set(false)
check("""
class Builder {
Builder qwit(boolean value, String sValue) {}
Builder trew(boolean value) {}
}
class Test {
public void test() {
Builder builder = new Builder();
builder
.trew(<hint text="value:"/>false)
.qwit(<hint text="value:"/>true, <hint text="sValue:"/>"value");
}
}
""")
}
fun `test do not show single parameter hint if it is string literal`() {
check("""
public class Test {
public void test() {
debug("Error message");
info("Error message", new Object());
}
void debug(String message) {}
void info(String message, Object error) {}
}
""")
}
fun `test show single`() {
check("""
class Test {
void main() {
blah(<hint text="a:"/>1, <hint text="b:"/>2);
int z = 2;
draw(<hint text="x:"/>10, <hint text="y:"/>20, z);
int x = 10;
int y = 12;
drawRect(x, y, <hint text="w:"/>10, <hint text="h:"/>12);
}
void blah(int a, int b) {}
void draw(int x, int y, int z) {}
void drawRect(int x, int y, int w, int h) {}
}
""")
}
fun `test do not show for setters`() {
check("""
class Test {
void main() {
set(10);
setWindow(100);
setWindow(<hint text="height:"/>100, <hint text="weight:">);
}
void set(int newValue) {}
void setWindow(int newValue) {}
void setWindow(int height, int weight) {}
}
""")
}
fun `test do not show for equals and min`() {
check("""
class Test {
void test() {
"xxx".equals(name);
Math.min(10, 20);
}
}
""")
}
fun `test more blacklisted items`() {
check("""
class Test {
void test() {
System.getProperty("aaa");
System.setProperty("aaa", "bbb");
new Key().create(10);
}
}
class Key {
void create(int a) {}
}
""")
}
fun `test poly and binary expressions`() {
check("""
class Test {
void test() {
xxx(<hint text="followTheSum:"/>100);
check(<hint text="isShow:"/>1 + 1);
check(<hint text="isShow:"/>1 + 1 + 1);
yyy(<hint text="followTheSum:"/>200);
}
void check(int isShow) {}
void xxx(int followTheSum) {}
void yyy(int followTheSum) {}
}
""")
}
fun `test incorrect pattern`() {
ParameterNameHintsSettings.getInstance().addIgnorePattern(JavaLanguage.INSTANCE, "")
check("""
class Test {
void test() {
check(<hint text="isShow:"/>1000);
}
void check(int isShow) {}
}
""")
}
fun `test do not show hint for name contained in method`() {
JavaInlayParameterHintsProvider.getInstance().isDoNotShowIfMethodNameContainsParameterName.set(true)
check("""
class Test {
void main() {
timeoutExecution(1000);
createSpace(true);
}
void timeoutExecution(int timeout) {}
void createSpace(boolean space) {}
}
""")
}
fun `test show if multiple params but name contained`() {
JavaInlayParameterHintsProvider.getInstance().isDoNotShowIfMethodNameContainsParameterName.set(true)
check("""
class Test {
void main() {
timeoutExecution(<hint text="timeout:"/>1000, <hint text="message:"/>"xxx");
createSpace(<hint text="space:"/>true, <hint text="a:"/>10);
}
void timeoutExecution(int timeout, String message) {}
void createSpace(boolean space, int a) {}
}
""")
}
fun `test show same params`() {
JavaInlayParameterHintsProvider.getInstance().isShowForParamsWithSameType.set(true)
check("""
class Test {
void main() {
String c = "c";
String d = "d";
test(<hint text="parent:"/>c, <hint text="child:"/>d);
}
void test(String parent, String child) {
}
}
""")
}
fun `test show triple`() {
JavaInlayParameterHintsProvider.getInstance().isShowForParamsWithSameType.set(true)
check("""
class Test {
void main() {
String c = "c";
test(<hint text="parent:"/>c, <hint text="child:"/>c, <hint text="grandParent:"/>c);
}
void test(String parent, String child, String grandParent) {
}
}
""")
}
fun `test show couple of doubles`() {
JavaInlayParameterHintsProvider.getInstance().isShowForParamsWithSameType.set(true)
check("""
class Test {
void main() {
String c = "c";
String d = "d";
int v = 10;
test(<hint text="parent:"/>c, <hint text="child:"/>d, <hint text="vx:"/>v, <hint text="vy:"/>v);
}
void test(String parent, String child, int vx, int vy) {
}
}
""")
}
fun `test show ambigous`() {
myFixture.configureByText(JavaFileType.INSTANCE, """
class Test {
void main() {
test(10<selection>, 100</selection>);
}
void test(int a, String bS) {}
void test(int a, int bI) {}
}
""")
myFixture.doHighlighting()
val hints = getHints()
assertThat(hints.size).isEqualTo(2)
assertThat(hints[0]).isEqualTo("a:")
assertThat(hints[1]).isEqualTo("bI:")
myFixture.type('\b')
myFixture.doHighlighting()
assertSingleInlayWithText("a:")
}
fun `test show ambiguous constructor`() {
myFixture.configureByText(JavaFileType.INSTANCE, """
class Test {
void main() {
new X(10<selection>, 100</selection>);
}
}
class X {
X(int a, int bI) {}
X(int a, String bS) {}
}
""")
myFixture.doHighlighting()
val hints = getHints()
assertThat(hints.size).isEqualTo(2)
assertThat(hints[0]).isEqualTo("a:")
assertThat(hints[1]).isEqualTo("bI:")
myFixture.type('\b')
myFixture.doHighlighting()
assertSingleInlayWithText("a:")
}
fun `test preserved inlays`() {
myFixture.configureByText(JavaFileType.INSTANCE,
"""
class Test {
void main() {
test(<caret>);
}
void test(int fooo) {}
}
""")
myFixture.type("100")
myFixture.doHighlighting()
assertSingleInlayWithText("fooo:")
myFixture.type("\b\b\b")
myFixture.doHighlighting()
assertSingleInlayWithText("fooo:")
myFixture.type("yyy")
myFixture.doHighlighting()
assertSingleInlayWithText("fooo:")
myFixture.checkResult(
"""
class Test {
void main() {
test(yyy);
}
void test(int fooo) {}
}
""")
}
fun `test do not show hints if method is unknown and one of them or both are blacklisted`() {
ParameterNameHintsSettings.getInstance().addIgnorePattern(JavaLanguage.INSTANCE, "*kee")
myFixture.configureByText(JavaFileType.INSTANCE, """
class Test {
void main() {
kee(100<caret>)
}
void kee(int a) {}
void kee(String a) {}
}
""")
myFixture.doHighlighting()
var hints = getHints()
assertThat(hints).hasSize(0)
myFixture.type('+')
myFixture.doHighlighting()
hints = getHints()
assertThat(hints).hasSize(0)
}
fun `test multiple hints on same offset lives without exception`() {
myFixture.configureByText(JavaFileType.INSTANCE,
"""
class Test {
void main() {
check(<selection>0, </selection>200);
}
void check(int qas, int b) {
}
}
""")
myFixture.doHighlighting()
var inlays = getHints()
assert(inlays.size == 2)
myFixture.type('\b')
myFixture.doHighlighting()
inlays = getHints()
assert(inlays.size == 1 && inlays.first() == "qas:", { "Real inlays ${inlays.size}" })
}
fun `test params with same type`() {
JavaInlayParameterHintsProvider.getInstance().isShowForParamsWithSameType.set(true)
check("""
class Test {
void test() {
String parent, child, element;
check(<hint text="a:"/>10, parent, child);
check(<hint text="a:"/>10, <hint text="parent:">element, child);
}
void check(int a, String parent, String child) {}
}
""")
}
fun `test if resolved but no hints just return no hints`() {
myFixture.configureByText(JavaFileType.INSTANCE, """
public class Test {
public void main() {
foo(1<caret>);
}
void foo(int a) {}
void foo() {}
}
""")
myFixture.doHighlighting()
var inlays = getHints()
assert(inlays.size == 1)
myFixture.type('\b')
myFixture.performEditorAction("EditorLeft")
myFixture.doHighlighting()
inlays = getHints()
assert(inlays.isEmpty())
}
fun getHints(): List<String> {
val document = myFixture.getDocument(myFixture.file)
val manager = ParameterHintsPresentationManager.getInstance()
return myFixture.editor
.inlayModel
.getInlineElementsInRange(0, document.textLength)
.mapNotNull { manager.getHintText(it) }
}
fun assertSingleInlayWithText(expectedText: String) {
val inlays = myFixture.editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength)
assertThat(inlays).hasSize(1)
val realText = getHintText(inlays[0])
assertThat(realText).isEqualTo(expectedText)
}
fun getHintText(inlay: Inlay): String {
return ParameterHintsPresentationManager.getInstance().getHintText(inlay)
}
} | apache-2.0 |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/fragments/QRCodeFragment.kt | 1 | 5173 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Authors: AmirHossein Naghshzan <[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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package cx.ring.fragments
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.StringRes
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import cx.ring.R
import cx.ring.databinding.FragQrcodeBinding
import cx.ring.share.ScanFragment
import cx.ring.share.ShareFragment
import cx.ring.utils.DeviceUtils.isTablet
class QRCodeFragment : BottomSheetDialogFragment() {
private var mBinding: FragQrcodeBinding? = null
private var mStartPageIndex = 0
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
super.onCreateView(inflater, container, savedInstanceState)
val args = requireArguments()
mStartPageIndex = args.getInt(ARG_START_PAGE_INDEX, 0)
return FragQrcodeBinding.inflate(inflater, container, false).apply {
viewPager.adapter = SectionsPagerAdapter(root.context, childFragmentManager)
tabs.setupWithViewPager(viewPager)
mBinding = this
}.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (mStartPageIndex != 0) {
mBinding?.tabs?.getTabAt(mStartPageIndex)?.select()
}
}
override fun onDestroyView() {
mBinding = null
super.onDestroyView()
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
dialog.setOnShowListener {
if (isTablet(requireContext())) {
dialog.window?.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)
}
}
return dialog
}
internal class SectionsPagerAdapter(private val mContext: Context, fm: FragmentManager) :
FragmentPagerAdapter(fm) {
@StringRes
private val TAB_TITLES = intArrayOf(R.string.tab_code, R.string.tab_scan)
override fun getItem(position: Int): Fragment {
return when (position) {
0 -> ShareFragment()
1 -> ScanFragment()
else -> throw IllegalArgumentException()
}
}
override fun getPageTitle(position: Int): CharSequence {
return mContext.resources.getString(TAB_TITLES[position])
}
override fun getCount(): Int {
return TAB_TITLES.size
}
}
override fun onResume() {
super.onResume()
addGlobalLayoutListener(requireView())
}
private fun addGlobalLayoutListener(view: View) {
view.addOnLayoutChangeListener(object : View.OnLayoutChangeListener {
override fun onLayoutChange(v: View, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) {
setPeekHeight(v.measuredHeight)
v.removeOnLayoutChangeListener(this)
}
})
}
fun setPeekHeight(peekHeight: Int) {
bottomSheetBehaviour?.peekHeight = peekHeight
}
private val bottomSheetBehaviour: BottomSheetBehavior<*>?
get() {
val layoutParams = (requireView().parent as View).layoutParams as CoordinatorLayout.LayoutParams
val behavior = layoutParams.behavior
return if (behavior is BottomSheetBehavior<*>) {
behavior
} else null
}
companion object {
val TAG = QRCodeFragment::class.simpleName!!
const val ARG_START_PAGE_INDEX = "start_page"
const val INDEX_CODE = 0
const val INDEX_SCAN = 1
fun newInstance(startPage: Int): QRCodeFragment {
val fragment = QRCodeFragment()
val args = Bundle()
args.putInt(ARG_START_PAGE_INDEX, startPage)
fragment.arguments = args
return fragment
}
}
} | gpl-3.0 |
bubelov/coins-android | app/src/main/java/com/bubelov/coins/logs/LogsFragment.kt | 1 | 2135 | package com.bubelov.coins.logs
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.bubelov.coins.R
import kotlinx.android.synthetic.main.fragment_logs.*
import kotlinx.coroutines.flow.collect
import org.koin.android.viewmodel.ext.android.viewModel
class LogsFragment : Fragment() {
private val model: LogsViewModel by viewModel()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_logs, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
toolbar.setNavigationOnClickListener { findNavController().popBackStack() }
list.layoutManager = LinearLayoutManager(requireContext())
val adapter = LogsAdapter()
list.adapter = adapter
lifecycleScope.launchWhenResumed {
model.getAll().collect {
adapter.swapItems(it)
}
}
}
override fun onResume() {
super.onResume()
requireActivity().window.apply {
clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
statusBarColor = ContextCompat.getColor(requireContext(), R.color.search_status_bar)
}
}
override fun onPause() {
requireActivity().window.apply {
clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
statusBarColor = ContextCompat.getColor(requireContext(), R.color.primary_dark)
}
super.onPause()
}
} | unlicense |
tonyofrancis/Fetch | fetch2core/src/main/java/com/tonyodev/fetch2core/FetchCoreDefaults.kt | 1 | 319 | @file:JvmName("FetchCoreDefaults")
package com.tonyodev.fetch2core
const val DEFAULT_TAG = "fetch2"
const val DEFAULT_LOGGING_ENABLED = false
const val DEFAULT_PROGRESS_REPORTING_INTERVAL_IN_MILLISECONDS = 2_000L
const val DEFAULT_BUFFER_SIZE = 8 * 1024
const val DEFAULT_PERSISTENT_TIME_OUT_IN_MILLISECONDS = 600000L | apache-2.0 |
slimaku/kondorcet | src/main/kotlin/kondorcet/model/DefaultBallot.kt | 1 | 1152 | package kondorcet.model
import kondorcet.Ballot
/**
* Vote ballot
*
* Contains all the candidates ordered by preferences.
*
* @property orderedCandidates Each element of this list is a set of candidate who are ex aequo.
*/
class DefaultBallot<out T : Any>(orderedCandidates: List<Set<T>> = emptyList()) : Ballot<T> {
override val orderedCandidates by lazy {
var winners = emptySet<T>()
orderedCandidates
.map { set -> set.filterNot { it in winners }.toSet().also { winners += it } }
.filterNot(Set<T>::isEmpty)
}
override val candidates by lazy { super.candidates }
override val winners by lazy { super.winners }
override val winner by lazy { super.winner }
constructor(vararg candidates: T) : this(candidates.map { setOf(it) })
constructor(vararg candidates: Collection<T>) : this(candidates.map { it.toSet() })
override fun equals(other: Any?) = other is Ballot<*> && other.orderedCandidates == orderedCandidates
override fun hashCode() = orderedCandidates.hashCode()
override fun toString() = "DefaultBallot(orderedCandidates=$orderedCandidates)"
} | lgpl-3.0 |
VerifAPS/verifaps-lib | geteta/src/test/kotlin/edu/kit/iti/formal/automation/testtables/monitor/monitor.kt | 1 | 734 | package edu.kit.iti.formal.automation.testtables.monitor
import edu.kit.iti.formal.automation.testtables.GetetaFacade
import org.junit.jupiter.api.Assumptions
import org.junit.jupiter.api.Test
import java.io.File
/**
*
* @author Alexander Weigl
* @version 1 (14.07.19)
*/
class MonitorTests {
@Test
fun testSimple() {
val file = File("examples/constantprogram/constantprogram.gtt")
Assumptions.assumeTrue(file.exists())
val gtt = GetetaFacade.parseTableDSL(file).first()
gtt.programRuns += ""
gtt.generateSmvExpression()
val automaton = GetetaFacade.constructTable(gtt).automaton
val mon = CppMonitorGenerator.generate(gtt, automaton)
println(mon)
}
} | gpl-3.0 |
RP-Kit/RPKit | bukkit/rpk-payment-lib-bukkit/src/main/kotlin/com/rpkit/payments/bukkit/RPKPaymentLibBukkit.kt | 1 | 1014 | /*
* Copyright 2022 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.payments.bukkit
import com.rpkit.core.plugin.RPKPlugin
import org.bstats.bukkit.Metrics
import org.bukkit.plugin.java.JavaPlugin
/**
* Class to allow payment lib to load as a plugin.
* This allows plugins requiring payment or implementing payment to depend on the plugin.
*/
class RPKPaymentLibBukkit : JavaPlugin(), RPKPlugin {
override fun onEnable() {
Metrics(this, 4405)
}
} | apache-2.0 |
manami-project/manami | manami-app/src/main/kotlin/io/github/manamiproject/manami/app/inconsistencies/animelist/deadentries/AnimeListDeadEntriesInconsistenciesResult.kt | 1 | 250 | package io.github.manamiproject.manami.app.inconsistencies.animelist.deadentries
import io.github.manamiproject.manami.app.lists.animelist.AnimeListEntry
data class AnimeListDeadEntriesInconsistenciesResult(
val entries: List<AnimeListEntry>
)
| agpl-3.0 |
industrial-data-space/trusted-connector | ids-api/src/main/java/de/fhg/aisec/ids/api/router/CounterExample.kt | 1 | 1150 | /*-
* ========================LICENSE_START=================================
* ids-api
* %%
* Copyright (C) 2019 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.api.router
abstract class CounterExample {
var explanation: String? = null
protected set
var steps: List<String>? = null
protected set
override fun toString(): String {
return """
Explanation: $explanation
${java.lang.String.join("\n|-- ", steps)}
""".trimIndent()
}
}
| apache-2.0 |
cketti/k-9 | app/ui/legacy/src/main/java/com/fsck/k9/ui/messageview/MessageViewContainerFragment.kt | 1 | 11026 | package com.fsck.k9.ui.messageview
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.DiffUtil
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.MarginPageTransformer
import androidx.viewpager2.widget.ViewPager2
import com.fsck.k9.controller.MessageReference
import com.fsck.k9.ui.R
import com.fsck.k9.ui.messagelist.MessageListItem
import com.fsck.k9.ui.messagelist.MessageListViewModel
import com.fsck.k9.ui.withArguments
/**
* A fragment that uses [ViewPager2] to allow the user to swipe between messages.
*
* Individual messages are displayed using a [MessageViewFragment].
*/
class MessageViewContainerFragment : Fragment() {
var isActive: Boolean = false
set(value) {
field = value
setMenuVisibility(value)
}
lateinit var messageReference: MessageReference
private set
private var activeMessageReference: MessageReference? = null
var lastDirection: Direction? = null
private set
private lateinit var fragmentListener: MessageViewContainerListener
private lateinit var viewPager: ViewPager2
private lateinit var adapter: MessageViewContainerAdapter
private var currentPosition: Int? = null
private val messageViewFragment: MessageViewFragment
get() {
check(isResumed)
return findMessageViewFragment()
}
private fun findMessageViewFragment(): MessageViewFragment {
val itemId = adapter.getItemId(messageReference)
// ViewPager2/FragmentStateAdapter don't provide an easy way to get hold of the Fragment for the active
// page. So we're using an implementation detail (the fragment tag) to find the fragment.
return childFragmentManager.findFragmentByTag("f$itemId") as MessageViewFragment
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
if (savedInstanceState == null) {
messageReference = MessageReference.parse(arguments?.getString(ARG_REFERENCE))
?: error("Missing argument $ARG_REFERENCE")
} else {
messageReference = MessageReference.parse(savedInstanceState.getString(STATE_MESSAGE_REFERENCE))
?: error("Missing state $STATE_MESSAGE_REFERENCE")
lastDirection = savedInstanceState.getSerializable(STATE_LAST_DIRECTION) as Direction?
}
adapter = MessageViewContainerAdapter(this)
}
override fun onAttach(context: Context) {
super.onAttach(context)
fragmentListener = try {
context as MessageViewContainerListener
} catch (e: ClassCastException) {
throw ClassCastException("This fragment must be attached to a MessageViewContainerListener")
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.message_view_container, container, false)
val resources = inflater.context.resources
val pageMargin = resources.getDimension(R.dimen.message_view_pager_page_margin).toInt()
viewPager = view.findViewById(R.id.message_viewpager)
viewPager.isUserInputEnabled = true
viewPager.offscreenPageLimit = ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT
viewPager.setPageTransformer(MarginPageTransformer(pageMargin))
viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
// The message list is updated each time the active message is changed. To avoid message list updates
// during the animation, we only set the active message after the animation has finished.
override fun onPageScrollStateChanged(state: Int) {
if (state == ViewPager2.SCROLL_STATE_IDLE) {
setActiveMessage(viewPager.currentItem)
}
}
override fun onPageSelected(position: Int) {
if (viewPager.scrollState == ViewPager2.SCROLL_STATE_IDLE) {
setActiveMessage(position)
}
}
})
return view
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(STATE_MESSAGE_REFERENCE, messageReference.toIdentityString())
outState.putSerializable(STATE_LAST_DIRECTION, lastDirection)
}
fun setViewModel(viewModel: MessageListViewModel) {
viewModel.getMessageListLiveData().observe(this) { messageListInfo ->
updateMessageList(messageListInfo.messageListItems)
}
}
private fun updateMessageList(messageListItems: List<MessageListItem>) {
if (messageListItems.isEmpty() || messageListItems.none { it.messageReference == messageReference }) {
fragmentListener.closeMessageView()
return
}
adapter.messageList = messageListItems
// We only set the adapter on ViewPager2 after the message list has been loaded. This way ViewPager2 can
// restore its saved state after a configuration change.
if (viewPager.adapter == null) {
viewPager.adapter = adapter
}
val position = adapter.getPosition(messageReference)
viewPager.setCurrentItem(position, false)
}
private fun setActiveMessage(position: Int) {
// If the position of current message changes (e.g. because messages were added or removed from the list), we
// keep track of the new position but otherwise ignore the event.
val newMessageReference = adapter.getMessageReference(position)
if (newMessageReference == activeMessageReference) {
currentPosition = position
return
}
rememberNavigationDirection(position)
messageReference = adapter.getMessageReference(position)
activeMessageReference = messageReference
fragmentListener.setActiveMessage(messageReference)
}
private fun rememberNavigationDirection(newPosition: Int) {
currentPosition?.let { currentPosition ->
lastDirection = if (newPosition < currentPosition) Direction.PREVIOUS else Direction.NEXT
}
currentPosition = newPosition
}
fun showPreviousMessage(): Boolean {
val newPosition = viewPager.currentItem - 1
return if (newPosition >= 0) {
setActiveMessage(newPosition)
val smoothScroll = true
viewPager.setCurrentItem(newPosition, smoothScroll)
true
} else {
false
}
}
fun showNextMessage(): Boolean {
val newPosition = viewPager.currentItem + 1
return if (newPosition < adapter.itemCount) {
setActiveMessage(newPosition)
val smoothScroll = true
viewPager.setCurrentItem(newPosition, smoothScroll)
true
} else {
false
}
}
fun onToggleFlagged() {
messageViewFragment.onToggleFlagged()
}
fun onMove() {
messageViewFragment.onMove()
}
fun onArchive() {
messageViewFragment.onArchive()
}
fun onCopy() {
messageViewFragment.onCopy()
}
fun onToggleRead() {
messageViewFragment.onToggleRead()
}
fun onForward() {
messageViewFragment.onForward()
}
fun onReplyAll() {
messageViewFragment.onReplyAll()
}
fun onReply() {
messageViewFragment.onReply()
}
fun onDelete() {
messageViewFragment.onDelete()
}
fun onPendingIntentResult(requestCode: Int, resultCode: Int, data: Intent?) {
findMessageViewFragment().onPendingIntentResult(requestCode, resultCode, data)
}
private class MessageViewContainerAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) {
var messageList: List<MessageListItem> = emptyList()
set(value) {
val diffResult = DiffUtil.calculateDiff(
MessageListDiffCallback(oldMessageList = messageList, newMessageList = value)
)
field = value
diffResult.dispatchUpdatesTo(this)
}
override fun getItemCount(): Int {
return messageList.size
}
override fun getItemId(position: Int): Long {
return messageList[position].uniqueId
}
override fun containsItem(itemId: Long): Boolean {
return messageList.any { it.uniqueId == itemId }
}
override fun createFragment(position: Int): Fragment {
check(position in messageList.indices)
val messageReference = messageList[position].messageReference
return MessageViewFragment.newInstance(messageReference)
}
fun getMessageReference(position: Int): MessageReference {
check(position in messageList.indices)
return messageList[position].messageReference
}
fun getPosition(messageReference: MessageReference): Int {
return messageList.indexOfFirst { it.messageReference == messageReference }
}
fun getItemId(messageReference: MessageReference): Long {
return messageList.first { it.messageReference == messageReference }.uniqueId
}
}
private class MessageListDiffCallback(
private val oldMessageList: List<MessageListItem>,
private val newMessageList: List<MessageListItem>
) : DiffUtil.Callback() {
override fun getOldListSize(): Int = oldMessageList.size
override fun getNewListSize(): Int = newMessageList.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldMessageList[oldItemPosition].uniqueId == newMessageList[newItemPosition].uniqueId
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
// Let MessageViewFragment deal with content changes
return areItemsTheSame(oldItemPosition, newItemPosition)
}
}
interface MessageViewContainerListener {
fun closeMessageView()
fun setActiveMessage(messageReference: MessageReference)
}
companion object {
private const val ARG_REFERENCE = "reference"
private const val STATE_MESSAGE_REFERENCE = "messageReference"
private const val STATE_LAST_DIRECTION = "lastDirection"
fun newInstance(reference: MessageReference): MessageViewContainerFragment {
return MessageViewContainerFragment().withArguments(
ARG_REFERENCE to reference.toIdentityString()
)
}
}
}
| apache-2.0 |
ethauvin/kobalt | modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/misc/Topological.kt | 2 | 1558 | package com.beust.kobalt.misc
import com.beust.kobalt.KobaltException
import com.google.common.collect.ArrayListMultimap
import com.google.common.collect.HashMultimap
import java.util.*
/**
* Sort items topologically. These items need to have overridden hashCode() and equals().
*/
class Topological<T> {
private val dependingOn = ArrayListMultimap.create<T, T>()
private val nodes = hashSetOf<T>()
fun addNode(t: T) = nodes.add(t)
fun addEdge(t: T, other: T) {
addNode(t)
addNode(other)
dependingOn.put(t, other)
}
/**
* @return the Ts sorted topologically.
*/
fun sort() : List<T> {
val all = ArrayList<T>(nodes)
val result = arrayListOf<T>()
var dependMap = HashMultimap.create<T, T>()
dependingOn.keySet().forEach { dependMap.putAll(it, dependingOn.get(it))}
nodes.forEach { dependMap.putAll(it, emptyList())}
while (all.size > 0) {
val freeNodes = all.filter {
dependMap.get(it).isEmpty()
}
if (freeNodes.isEmpty()) {
throw KobaltException("The dependency graph has a cycle: $all")
}
result.addAll(freeNodes)
all.removeAll(freeNodes)
val newMap = HashMultimap.create<T, T>()
dependMap.keySet().forEach {
val l = dependingOn.get(it)
l.removeAll(freeNodes)
newMap.putAll(it, l)
}
dependMap = newMap
}
return result
}
} | apache-2.0 |
kittinunf/ReactiveAndroid | sample/src/main/kotlin/com.github.kittinunf.reactiveandroid.sample/model/User.kt | 1 | 226 | package com.github.kittinunf.reactiveandroid.sample.model
data class User(val title: String = "",
val firstName: String = "",
val lastName: String = "",
val email: String = "")
| mit |
googlesamples/arcore-ml-sample | app/src/main/java/com/google/ar/core/examples/java/ml/MainActivityView.kt | 1 | 2386 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.ar.core.examples.java.ml
import android.opengl.GLSurfaceView
import android.view.View
import androidx.appcompat.widget.AppCompatButton
import androidx.appcompat.widget.SwitchCompat
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.google.ar.core.examples.java.common.helpers.SnackbarHelper
import com.google.ar.core.examples.java.common.samplerender.SampleRender
/**
* Wraps [R.layout.activity_main] and controls lifecycle operations for [GLSurfaceView].
*/
class MainActivityView(val activity: MainActivity, renderer: AppRenderer) : DefaultLifecycleObserver {
val root = View.inflate(activity, R.layout.activity_main, null)
val surfaceView = root.findViewById<GLSurfaceView>(R.id.surfaceview).apply {
SampleRender(this, renderer, activity.assets)
}
val useCloudMlSwitch = root.findViewById<SwitchCompat>(R.id.useCloudMlSwitch)
val scanButton = root.findViewById<AppCompatButton>(R.id.scanButton)
val resetButton = root.findViewById<AppCompatButton>(R.id.clearButton)
val snackbarHelper = SnackbarHelper().apply {
setParentView(root.findViewById(R.id.coordinatorLayout))
setMaxLines(6)
}
override fun onResume(owner: LifecycleOwner) {
surfaceView.onResume()
}
override fun onPause(owner: LifecycleOwner) {
surfaceView.onPause()
}
fun post(action: Runnable) = root.post(action)
/**
* Toggles the scan button depending on if scanning is in progress.
*/
fun setScanningActive(active: Boolean) = when(active) {
true -> {
scanButton.isEnabled = false
scanButton.setText(activity.getString(R.string.scan_busy))
}
false -> {
scanButton.isEnabled = true
scanButton.setText(activity.getString(R.string.scan_available))
}
}
} | apache-2.0 |
luxons/seven-wonders | sw-engine/src/test/kotlin/org/luxons/sevenwonders/engine/effects/ScienceProgressTest.kt | 1 | 1661 | package org.luxons.sevenwonders.engine.effects
import org.junit.experimental.theories.DataPoints
import org.junit.experimental.theories.Theories
import org.junit.experimental.theories.Theory
import org.junit.runner.RunWith
import org.luxons.sevenwonders.engine.boards.ScienceType
import org.luxons.sevenwonders.engine.test.createScience
import org.luxons.sevenwonders.engine.test.createScienceProgress
import org.luxons.sevenwonders.engine.test.testBoard
import org.luxons.sevenwonders.model.resources.ResourceType
import kotlin.test.assertEquals
@RunWith(Theories::class)
class ScienceProgressTest {
@Theory
fun apply_initContainsAddedScience(
initCompasses: Int,
initWheels: Int,
initTablets: Int,
initJokers: Int,
compasses: Int,
wheels: Int,
tablets: Int,
jokers: Int,
) {
val board = testBoard(ResourceType.ORE)
val initialScience = createScience(initCompasses, initWheels, initTablets, initJokers)
board.science.addAll(initialScience)
val effect = createScienceProgress(compasses, wheels, tablets, jokers)
effect.applyTo(board)
assertEquals(initCompasses + compasses, board.science.getQuantity(ScienceType.COMPASS))
assertEquals(initWheels + wheels, board.science.getQuantity(ScienceType.WHEEL))
assertEquals(initTablets + tablets, board.science.getQuantity(ScienceType.TABLET))
assertEquals(initJokers + jokers, board.science.jokers)
}
companion object {
@JvmStatic
@DataPoints
fun elementsCount(): IntArray {
return intArrayOf(0, 1, 2)
}
}
}
| mit |
jabbink/PokemonGoBot | src/main/kotlin/ink/abb/pogo/scraper/controllers/BotController.kt | 2 | 16388 | /**
* Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information)
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it under certain conditions.
*
* For more information, refer to the LICENSE file in this repositories root directory
*/
package ink.abb.pogo.scraper.controllers
import POGOProtos.Data.PokedexEntryOuterClass
import POGOProtos.Enums.PokemonIdOuterClass
import POGOProtos.Inventory.Item.ItemIdOuterClass
import POGOProtos.Networking.Responses.SetFavoritePokemonResponseOuterClass
import POGOProtos.Networking.Responses.UpgradePokemonResponseOuterClass
import com.google.common.geometry.S2LatLng
import ink.abb.pogo.api.cache.BagPokemon
import ink.abb.pogo.api.request.*
import ink.abb.pogo.scraper.Context
import ink.abb.pogo.scraper.Settings
import ink.abb.pogo.scraper.services.BotService
import ink.abb.pogo.scraper.util.ApiAuthProvider
import ink.abb.pogo.scraper.util.Log
import ink.abb.pogo.scraper.util.credentials.GoogleAutoCredentials
import ink.abb.pogo.scraper.util.data.*
import ink.abb.pogo.scraper.util.pokemon.candyCostsForPowerup
import ink.abb.pogo.scraper.util.pokemon.getStatsFormatted
import ink.abb.pogo.scraper.util.pokemon.meta
import ink.abb.pogo.scraper.util.pokemon.stardustCostsForPowerup
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import java.util.concurrent.atomic.AtomicInteger
import javax.servlet.http.HttpServletResponse
@RestController
@CrossOrigin
@RequestMapping("/api")
class BotController {
@Autowired
lateinit var service: BotService
@Autowired
lateinit var authProvider: ApiAuthProvider
@RequestMapping("/bots")
fun bots(): List<Settings> {
return service.getAllBotSettings()
}
@RequestMapping(value = "/bot/{name}/auth", method = arrayOf(RequestMethod.POST))
fun auth(
@PathVariable name: String,
@RequestBody pass: String,
httpResponse: HttpServletResponse
): String {
val ctx = service.getBotContext(name)
if (ctx.restApiPassword.equals("")) {
Log.red("REST API: There is no REST API password set in the configuration for bot $name, generating one now...")
authProvider.generateRestPassword(name)
return "REST API password generated for bot $name, check your console output!"
}
authProvider.generateAuthToken(name)
if (!pass.equals(ctx.restApiPassword)) {
httpResponse.status = HttpServletResponse.SC_UNAUTHORIZED
return "Your authentication request ($pass) does not match the REST API password from the bot $name configuration!"
}
return ctx.restApiToken
}
@RequestMapping(value = "/bot/{name}/load", method = arrayOf(RequestMethod.POST))
fun loadBot(@PathVariable name: String): Settings {
Log.magenta("REST API: Load bot $name")
return service.submitBot(name)
}
@RequestMapping(value = "/bot/{name}/unload", method = arrayOf(RequestMethod.POST))
fun unloadBot(@PathVariable name: String): String {
Log.magenta("REST API: Unload bot $name")
return service.doWithBot(name) {
it.stop()
service.removeBot(it)
}.toString()
}
@RequestMapping(value = "/bot/{name}/reload", method = arrayOf(RequestMethod.POST))
fun reloadBot(@PathVariable name: String): Settings {
Log.magenta("REST API: Reload bot $name")
if (unloadBot(name).equals("false")) // return default settings
return Settings(
credentials = GoogleAutoCredentials(),
latitude = 0.0,
longitude = 0.0
)
return loadBot(name)
}
@RequestMapping(value = "/bot/{name}/start", method = arrayOf(RequestMethod.POST))
fun startBot(@PathVariable name: String): String {
Log.magenta("REST API: Starting bot $name")
return service.doWithBot(name) { it.start() }.toString()
}
@RequestMapping(value = "/bot/{name}/stop", method = arrayOf(RequestMethod.POST))
fun stopBot(@PathVariable name: String): String {
Log.magenta("REST API: Stopping bot $name")
return service.doWithBot(name) { it.stop() }.toString()
}
@RequestMapping(value = "/bot/{name}/pokemons", method = arrayOf(RequestMethod.GET))
fun listPokemons(@PathVariable name: String): List<PokemonData> {
return service.getBotContext(name).api.inventory.pokemon.map { PokemonData().buildFromPokemon(it.value) }
}
@RequestMapping(value = "/bot/{name}/pokemon/{id}/transfer", method = arrayOf(RequestMethod.POST))
fun transferPokemon(
@PathVariable name: String,
@PathVariable id: Long
): String {
val pokemon: BagPokemon? = getPokemonById(service.getBotContext(name), id)
val release = ReleasePokemon().withPokemonId(pokemon!!.pokemonData.id)
Log.magenta("REST API: Transferring pokemon ${pokemon.pokemonData.pokemonId.name} with stats (${pokemon.pokemonData.getStatsFormatted()} CP: ${pokemon.pokemonData.cp})")
val result = service.getBotContext(name).api.queueRequest(release).toBlocking().first().response
// Update GUI
service.getBotContext(name).server.sendPokebank()
return result.result.toString()
}
@RequestMapping(value = "/bot/{name}/pokemon/{id}/evolve", method = arrayOf(RequestMethod.POST))
fun evolvePokemon(
@PathVariable name: String,
@PathVariable id: Long,
httpResponse: HttpServletResponse
): String {
val result: String
val pokemon: BagPokemon? = getPokemonById(service.getBotContext(name), id)
val requiredCandy = pokemon!!.pokemonData.meta.candyToEvolve
val candy = service.getBotContext(name).api.inventory.candies.getOrPut(pokemon.pokemonData.meta.family, { AtomicInteger(0) }).get()
if (requiredCandy > candy) {
httpResponse.status = HttpServletResponse.SC_BAD_REQUEST
result = "Not enough candies to evolve: ${candy}/${requiredCandy}"
} else {
val evolve = EvolvePokemon().withPokemonId(pokemon.pokemonData.id)
val evolutionResult = service.getBotContext(name).api.queueRequest(evolve).toBlocking().first().response
val evolved = evolutionResult.evolvedPokemonData
Log.magenta("REST API: Evolved pokemon ${pokemon.pokemonData.pokemonId.name} with stats (${pokemon.pokemonData.getStatsFormatted()} CP: ${pokemon.pokemonData.cp})"
+ " to pokemon ${evolved.pokemonId.name} with stats (${evolved.getStatsFormatted()} CP: ${evolved.cp})")
result = evolutionResult.result.toString()
}
// Update GUI
service.getBotContext(name).server.sendPokebank()
return result
}
@RequestMapping(value = "/bot/{name}/pokemon/{id}/powerup", method = arrayOf(RequestMethod.POST))
fun powerUpPokemon(
@PathVariable name: String,
@PathVariable id: Long,
httpResponse: HttpServletResponse
): String {
val pokemon = getPokemonById(service.getBotContext(name), id)
val candy = service.getBotContext(name).api.inventory.candies.getOrPut(pokemon!!.pokemonData.meta.family, { AtomicInteger(0) }).get()
val stardust = service.getBotContext(name).api.inventory.currencies.getOrPut("STARDUST", { AtomicInteger(0) }).get()
val result = if (pokemon.pokemonData.candyCostsForPowerup > candy) {
httpResponse.status = HttpServletResponse.SC_BAD_REQUEST
"Not enough candies to powerup: ${candy}/${pokemon.pokemonData.candyCostsForPowerup}"
} else if (pokemon.pokemonData.stardustCostsForPowerup > stardust) {
httpResponse.status = HttpServletResponse.SC_BAD_REQUEST
"Not enough stardust to powerup: ${stardust}/${pokemon.pokemonData.stardustCostsForPowerup}"
} else {
Log.magenta("REST API: Powering up pokemon ${pokemon.pokemonData.pokemonId.name} with stats (${pokemon.pokemonData.getStatsFormatted()} CP: ${pokemon.pokemonData.cp})")
val upgrade = UpgradePokemon().withPokemonId(pokemon.pokemonData.id)
Log.magenta("REST API : pokemon new CP " + pokemon.pokemonData.cp)
val response = service.getBotContext(name).api.queueRequest(upgrade).toBlocking().first()
if (response.response.result == UpgradePokemonResponseOuterClass.UpgradePokemonResponse.Result.SUCCESS) {
Log.magenta("REST API: Pokemon new CP ${response.response.upgradedPokemon.cp}")
}
response!!.response.result.toString()
}
// Update GUI
service.getBotContext(name).server.sendPokebank()
return result
}
@RequestMapping(value = "/bot/{name}/pokemon/{id}/favorite", method = arrayOf(RequestMethod.POST))
fun togglePokemonFavorite(
@PathVariable name: String,
@PathVariable id: Long
): String {
val pokemon = getPokemonById(service.getBotContext(name), id)
val setFav = SetFavoritePokemon().withIsFavorite(pokemon!!.pokemonData.favorite == 0).withPokemonId(pokemon.pokemonData.id)
val result = service.getBotContext(name).api.queueRequest(setFav).toBlocking().first().response.result
if (result == SetFavoritePokemonResponseOuterClass.SetFavoritePokemonResponse.Result.SUCCESS) {
when (pokemon.pokemonData.favorite > 0) {
false -> Log.magenta("REST API: Pokemon ${pokemon.pokemonData.pokemonId.name} with stats (${pokemon.pokemonData.getStatsFormatted()} CP: ${pokemon.pokemonData.cp}) is favorited")
true -> Log.magenta("REST API: Pokemon ${pokemon.pokemonData.pokemonId.name} with stats (${pokemon.pokemonData.getStatsFormatted()} CP: ${pokemon.pokemonData.cp}) is now unfavorited")
}
}
// Update GUI
service.getBotContext(name).server.sendPokebank()
return result.toString()
}
@RequestMapping(value = "/bot/{name}/pokemon/{id}/rename", method = arrayOf(RequestMethod.POST))
fun renamePokemon(
@PathVariable name: String,
@PathVariable id: Long,
@RequestBody newName: String
): String {
val pokemon = getPokemonById(service.getBotContext(name), id)
val rename = NicknamePokemon().withNickname(newName).withPokemonId(pokemon!!.pokemonData.id)
val result = service.getBotContext(name).api.queueRequest(rename).toBlocking().first().response.result.toString()
Log.magenta("REST API: Renamed pokemon ${pokemon.pokemonData.pokemonId.name} with stats (${pokemon.pokemonData.getStatsFormatted()} CP: ${pokemon.pokemonData.cp}) to $newName")
return result
}
@RequestMapping("/bot/{name}/items")
fun listItems(@PathVariable name: String): List<ItemData> {
return service.getBotContext(name).api.inventory.items.map { ItemData().buildFromItem(it.key, it.value.get()) }
}
@RequestMapping(value = "/bot/{name}/item/{id}/drop/{quantity}", method = arrayOf(RequestMethod.DELETE))
fun dropItem(
@PathVariable name: String,
@PathVariable id: Int,
@PathVariable quantity: Int,
httpResponse: HttpServletResponse
): String {
val itemBag = service.getBotContext(name).api.inventory.items
val itemId = ItemIdOuterClass.ItemId.forNumber(id)
val item = itemBag.getOrPut(itemId, { AtomicInteger(0) })
if (quantity > item.get()) {
httpResponse.status = HttpServletResponse.SC_BAD_REQUEST
return "Not enough items to drop ${item.get()}"
} else {
Log.magenta("REST API: Dropping ${quantity} ${itemId.name}")
val recycle = RecycleInventoryItem().withCount(quantity).withItemId(itemId)
val result = service.getBotContext(name).api.queueRequest(recycle).toBlocking().first().response.result.toString()
return result
}
}
@RequestMapping(value = "/bot/{name}/useIncense", method = arrayOf(RequestMethod.POST))
fun useIncense(
@PathVariable name: String,
httpResponse: HttpServletResponse
): String {
val itemBag = service.getBotContext(name).api.inventory.items
val count = itemBag.getOrPut(ItemIdOuterClass.ItemId.ITEM_INCENSE_ORDINARY, { AtomicInteger(0) }).get()
if (count == 0) {
httpResponse.status = HttpServletResponse.SC_BAD_REQUEST
return "Not enough incenses"
} else {
val useIncense = UseIncense().withIncenseType(ItemIdOuterClass.ItemId.ITEM_INCENSE_ORDINARY)
val result = service.getBotContext(name).api.queueRequest(useIncense).toBlocking().first().response.result.toString()
Log.magenta("REST API: Used incense")
return result
}
}
@RequestMapping(value = "/bot/{name}/useLuckyEgg", method = arrayOf(RequestMethod.POST))
fun useLuckyEgg(
@PathVariable name: String,
httpResponse: HttpServletResponse
): String {
val itemBag = service.getBotContext(name).api.inventory.items
val count = itemBag.getOrPut(ItemIdOuterClass.ItemId.ITEM_LUCKY_EGG, { AtomicInteger(0) }).get()
if (count == 0) {
httpResponse.status = HttpServletResponse.SC_BAD_REQUEST
return "Not enough lucky eggs"
} else {
val useEgg = UseItemXpBoost().withItemId(ItemIdOuterClass.ItemId.ITEM_LUCKY_EGG)
val result = service.getBotContext(name).api.queueRequest(useEgg).toBlocking().first().response.result.toString()
Log.magenta("REST API: Used lucky egg")
return result
}
}
@RequestMapping(value = "/bot/{name}/location", method = arrayOf(RequestMethod.GET))
fun getLocation(@PathVariable name: String): LocationData {
return LocationData(
service.getBotContext(name).api.latitude,
service.getBotContext(name).api.longitude
)
}
@RequestMapping(value = "/bot/{name}/location/{latitude}/{longitude}", method = arrayOf(RequestMethod.POST))
fun changeLocation(
@PathVariable name: String,
@PathVariable latitude: Double,
@PathVariable longitude: Double,
httpResponse: HttpServletResponse
): String {
val ctx: Context = service.getBotContext(name)
if (!latitude.isNaN() && !longitude.isNaN()) {
ctx.server.coordinatesToGoTo.add(S2LatLng.fromDegrees(latitude, longitude))
Log.magenta("REST API: Added ToGoTo coordinates $latitude $longitude")
return "SUCCESS"
} else {
httpResponse.status = HttpServletResponse.SC_BAD_REQUEST
return "FAIL"
}
}
@RequestMapping(value = "/bot/{name}/profile", method = arrayOf(RequestMethod.GET))
fun getProfile(@PathVariable name: String): ProfileData {
return ProfileData().buildFromApi(service.getBotContext(name).api)
}
@RequestMapping(value = "/bot/{name}/pokedex", method = arrayOf(RequestMethod.GET))
fun getPokedex(@PathVariable name: String): List<PokedexEntry> {
val pokedex = mutableListOf<PokedexEntry>()
val api = service.getBotContext(name).api
for (i in 0..151) {
val entry: PokedexEntryOuterClass.PokedexEntry? = api.inventory.pokedex.get(PokemonIdOuterClass.PokemonId.forNumber(i))
entry ?: continue
pokedex.add(PokedexEntry().buildFromEntry(entry))
}
return pokedex
}
@RequestMapping(value = "/bot/{name}/eggs", method = arrayOf(RequestMethod.GET))
fun getEggs(@PathVariable name: String): List<EggData> {
//service.getBotContext(name).api.inventories.updateInventories(true)
return service.getBotContext(name).api.inventory.eggs.map { EggData().buildFromEggPokemon(it.value) }
}
// FIXME! currently, the IDs returned by the API are not unique. It seems that only the last 6 digits change so we remove them
fun getPokemonById(ctx: Context, id: Long): BagPokemon? {
return ctx.api.inventory.pokemon[id]
}
}
| gpl-3.0 |
quarck/CalendarNotification | app/src/main/java/com/github/quarck/calnotify/calendareditor/CalendarChangeRequest.kt | 1 | 2024 | //
// Calendar Notifications Plus
// Copyright (C) 2017 Sergey Parshin ([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, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
package com.github.quarck.calnotify.calendareditor
import com.github.quarck.calnotify.calendar.CalendarEventDetails
enum class EventChangeStatus(val code: Int) {
Dirty(0),
Synced(1),
Failed(1000);
companion object {
@JvmStatic
fun fromInt(v: Int) = values()[v]
}
}
enum class EventChangeRequestType(val code: Int) {
AddNewEvent(0),
MoveExistingEvent(1),
EditExistingEvent(2);
companion object {
@JvmStatic
fun fromInt(v: Int) = values()[v]
}
}
data class CalendarChangeRequest(
var id: Long,
var type: EventChangeRequestType,
var eventId: Long,
val calendarId: Long,
val calendarOwnerAccount: String,
val details: CalendarEventDetails,
val oldDetails: CalendarEventDetails,
var status: EventChangeStatus = EventChangeStatus.Dirty,
var lastStatusUpdate: Long = 0,
var numRetries: Int = 0,
var lastRetryTime: Long = 0
) {
fun onValidated(success: Boolean) {
lastStatusUpdate = System.currentTimeMillis()
status = if (success) EventChangeStatus.Synced else EventChangeStatus.Dirty
}
}
| gpl-3.0 |
android/user-interface-samples | People/app/src/main/java/com/example/android/people/MainActivity.kt | 1 | 4633 | /*
* Copyright (C) 2019 The Android Open Source Project
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.people
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.transition.Transition
import android.transition.TransitionInflater
import android.transition.TransitionManager
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.commit
import androidx.fragment.app.commitNow
import com.example.android.people.data.Contact
import com.example.android.people.databinding.MainActivityBinding
import com.example.android.people.ui.chat.ChatFragment
import com.example.android.people.ui.main.MainFragment
import com.example.android.people.ui.photo.PhotoFragment
import com.example.android.people.ui.viewBindings
/**
* Entry point of the app when it is launched as a full app.
*/
class MainActivity : AppCompatActivity(R.layout.main_activity), NavigationController {
companion object {
private const val FRAGMENT_CHAT = "chat"
}
private val binding by viewBindings(MainActivityBinding::bind)
private lateinit var transition: Transition
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setSupportActionBar(binding.toolbar)
transition = TransitionInflater.from(this).inflateTransition(R.transition.app_bar)
if (savedInstanceState == null) {
supportFragmentManager.commitNow {
replace(R.id.container, MainFragment())
}
intent?.let(::handleIntent)
}
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
if (intent != null) {
handleIntent(intent)
}
}
private fun handleIntent(intent: Intent) {
when (intent.action) {
// Invoked when a dynamic shortcut is clicked.
Intent.ACTION_VIEW -> {
val id = intent.data?.lastPathSegment?.toLongOrNull()
if (id != null) {
openChat(id, null)
}
}
// Invoked when a text is shared through Direct Share.
Intent.ACTION_SEND -> {
val shortcutId = intent.getStringExtra(Intent.EXTRA_SHORTCUT_ID)
val text = intent.getStringExtra(Intent.EXTRA_TEXT)
val contact = Contact.CONTACTS.find { it.shortcutId == shortcutId }
if (contact != null) {
openChat(contact.id, text)
}
}
}
}
override fun updateAppBar(
showContact: Boolean,
hidden: Boolean,
body: (name: TextView, icon: ImageView) -> Unit
) {
if (hidden) {
binding.appBar.visibility = View.GONE
} else {
binding.appBar.visibility = View.VISIBLE
TransitionManager.beginDelayedTransition(binding.appBar, transition)
if (showContact) {
supportActionBar?.setDisplayShowTitleEnabled(false)
binding.name.visibility = View.VISIBLE
binding.icon.visibility = View.VISIBLE
} else {
supportActionBar?.setDisplayShowTitleEnabled(true)
binding.name.visibility = View.GONE
binding.icon.visibility = View.GONE
}
}
body(binding.name, binding.icon)
}
override fun openChat(id: Long, prepopulateText: String?) {
supportFragmentManager.popBackStack(FRAGMENT_CHAT, FragmentManager.POP_BACK_STACK_INCLUSIVE)
supportFragmentManager.commit {
addToBackStack(FRAGMENT_CHAT)
replace(R.id.container, ChatFragment.newInstance(id, true, prepopulateText))
}
}
override fun openPhoto(photo: Uri) {
supportFragmentManager.commit {
addToBackStack(null)
replace(R.id.container, PhotoFragment.newInstance(photo))
}
}
}
| apache-2.0 |
davidwhitman/deep-link-launcher | app/src/main/kotlin/com/thunderclouddev/deeplink/data/DeepLinkInfo.kt | 1 | 412 | package com.thunderclouddev.deeplink.data
data class DeepLinkInfo(val id: Long,
val deepLink: String,
val label: String?,
val updatedTime: Long,
val deepLinkHandlers: List<String>) : Comparable<DeepLinkInfo> {
override fun compareTo(other: DeepLinkInfo) = if (this.updatedTime < other.updatedTime) 1 else -1
}
| gpl-3.0 |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/utils/correios/EncomendaResponse.kt | 1 | 360 | package net.perfectdreams.loritta.morenitta.utils.correios
class EncomendaResponse {
var date = "???"
var time = "???"
var state = "???"
var error = "???"
var locations: List<PackageUpdate> = listOf()
class PackageUpdate {
var state = "???"
var reason = "???"
var location = "???"
var receiver = "???"
var date = "???"
var time = "???"
}
} | agpl-3.0 |
Quireg/AnotherMovieApp | app/src/main/java/com/anothermovieapp/view/DetailsActivity.kt | 1 | 9040 | /*
* Created by Arcturus Mengsk
* 2021.
*/
package com.anothermovieapp.view
import android.animation.ObjectAnimator
import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.palette.graphics.Palette
import com.anothermovieapp.R
import com.anothermovieapp.common.Constants
import com.anothermovieapp.viewmodel.ViewModelFavoriteMovies
import com.anothermovieapp.repository.EntityDBMovie
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.appbar.CollapsingToolbarLayout
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class DetailsActivity : AppCompatActivity(), OnFragmentInteractionListener {
private var mDetailsFragment: DetailsFragment? = null
private var mMovie: EntityDBMovie? = null
private lateinit var mToolbarLayout: CollapsingToolbarLayout
@Inject
lateinit var viewModel: ViewModelFavoriteMovies
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mMovie = intent.extras?.getSerializable(Constants.MOVIE) as EntityDBMovie
setContentView(R.layout.activity_movie_details_mine)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
val appBarLayout = findViewById<AppBarLayout>(R.id.appbar)
mToolbarLayout = appBarLayout.findViewById(R.id.collapsing_toolbar)
mDetailsFragment = DetailsFragment()
mDetailsFragment!!.arguments = intent.extras
supportFragmentManager.beginTransaction()
.replace(R.id.container, mDetailsFragment!!, DetailsFragment.TAG)
.commit()
if (mMovie?.title != null) {
val collapsingTBL = findViewById<CollapsingToolbarLayout>(R.id.collapsing_toolbar)
collapsingTBL.title = mMovie?.title
}
if (mMovie?.backdropPath != null) {
loadBackdropImage(mMovie?.backdropPath)
}
appBarLayout.setBackgroundColor(Color.parseColor("#8C000000"))
appBarLayout.setOnApplyWindowInsetsListener { v, insets ->
toolbar.setPadding(
v.paddingLeft,
insets.systemWindowInsetTop,
v.paddingRight,
v.paddingBottom
)
findViewById<View>(R.id.container).setPadding(
v.paddingLeft,
v.paddingTop,
v.paddingRight,
insets.systemWindowInsetBottom
)
val a = obtainStyledAttributes(intArrayOf(R.attr.actionBarSize))
val actionBarSize = a.getDimensionPixelSize(0, -1)
a.recycle()
mToolbarLayout.setScrimVisibleHeightTrigger(
insets.systemWindowInsetTop + actionBarSize + 1
)
insets
}
}
var heartMenu : MenuItem? = null
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.movie_menu, menu)
heartMenu = menu.findItem(R.id.favorite)
heartMenu?.icon = getDrawable(R.drawable.ic_favorite_black_24dp)
viewModel.isFavorite(mMovie!!.id).observe(this) {
heartMenu?.icon = if (it) {
getDrawable(R.drawable.ic_favorite_red_24dp)
} else {
getDrawable(R.drawable.ic_favorite_black_24dp)
}
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.favorite) {
viewModel.addOrRemove(mMovie!!.id)
return true
} else if (item.itemId == android.R.id.home) {
onBackPressed()
}
return super.onOptionsItemSelected(item)
}
override fun onFragmentMessage(tag: String?, data: Any?) {
}
private fun loadBackdropImage(path: String?) {
val imageUri = Uri.Builder()
.scheme("https")
.authority("image.tmdb.org")
.appendPath("t")
.appendPath("p")
.appendPath(Constants.IMAGE_SIZE_ORIGINAL)
.appendPath(path)
.build()
.normalizeScheme();
val headerImage = findViewById<ImageView>(R.id.toolbar_image)
Glide.with(this)
.asBitmap()
.load(imageUri)
.addListener(object : RequestListener<Bitmap?> {
override fun onLoadFailed(
e: GlideException?, model: Any,
target: Target<Bitmap?>,
isFirstResource: Boolean
): Boolean {
Handler(Looper.getMainLooper()).post {
if (mDetailsFragment != null) {
mDetailsFragment!!.readyShowContent()
}
}
return false
}
override fun onResourceReady(
resource: Bitmap?, model: Any,
target: Target<Bitmap?>,
dataSource: DataSource, isFirstResource: Boolean
): Boolean {
Handler(Looper.getMainLooper()).post {
if (mDetailsFragment != null) {
mDetailsFragment!!.readyShowContent()
}
headerImage.setImageBitmap(resource)
val animator = ObjectAnimator.ofFloat(
headerImage, View.ALPHA,
headerImage.alpha, 1f
)
animator.duration = 300
animator.start()
}
return true
}
})
.submit()
}
private fun playWithPalette(
resource: Bitmap, collapsingTBL: CollapsingToolbarLayout,
headerImage: ImageView
) {
Palette.from(Bitmap.createBitmap(resource))
.generate { palette -> // FloatingActionButton fab = findViewById(R.id.fab);
// Drawable drawable = getResources()
// .getDrawable(R.drawable.ic_action_star, getTheme());
//
// drawable.setTintMode(PorterDuff.Mode.SRC_IN);
// drawable.setTintList(new ColorStateList(
// new int[][]{
// new int[]{android.R.attr.state_selected},
// new int[]{-android.R.attr.state_selected}
// },
// new int[]{
// Color.RED,
// Color.WHITE
// }
// ));
// fab.setImageDrawable(drawable);
// fab.setBackgroundTintList(ColorStateList.valueOf(
// palette.getMutedColor(R.attr.colorSecondary)));
// fab.setRippleColor(ColorStateList.valueOf(
// palette.getDarkMutedColor(R.attr.colorSecondary)));
if (palette!!.dominantSwatch != null) {
collapsingTBL.setExpandedTitleColor(
palette.dominantSwatch!!.titleTextColor
)
}
if (palette.vibrantSwatch != null) {
collapsingTBL.setCollapsedTitleTextColor(
palette.vibrantSwatch!!.titleTextColor
)
collapsingTBL.setContentScrimColor(
palette.vibrantSwatch!!.rgb
)
}
val toolbar = findViewById<Toolbar>(R.id.toolbar)
if (toolbar.navigationIcon != null) {
toolbar.navigationIcon!!.setTint(
palette.getLightVibrantColor(R.attr.editTextColor)
)
}
collapsingTBL.setContentScrimColor(
palette.getMutedColor(R.attr.colorPrimary)
)
collapsingTBL.setStatusBarScrimColor(
palette.getDarkMutedColor(R.attr.colorPrimaryDark)
)
headerImage.setImageBitmap(resource)
headerImage.visibility = View.VISIBLE
}
}
} | mit |
darakeon/dfm | android/Lib/src/test/kotlin/com/darakeon/dfm/lib/api/entities/ComboItemTest.kt | 1 | 1510 | package com.darakeon.dfm.lib.api.entities
import android.app.Activity
import android.widget.AutoCompleteTextView
import android.widget.Button
import android.widget.TextView
import com.darakeon.dfm.testutils.BaseTest
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric.buildActivity
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class ComboItemTest: BaseTest() {
lateinit var activity: Activity
@Before
fun setup() {
activity = buildActivity(
Activity::class.java
).create().get()
}
@Test
fun setLabel() {
val list = arrayOf(
ComboItem("text1", "value1"),
ComboItem("text2", "value2"),
ComboItem("text3", "value3")
)
val field = TextView(activity)
list.setLabel(field, "value2")
assertThat(field.text.toString(), `is`("text2"))
}
var comboValue: String? = "value2"
@Test
fun setCombo() {
val list = arrayOf(
ComboItem("text1", "value1"),
ComboItem("text2", "value2"),
ComboItem("text3", "value3")
)
val field = AutoCompleteTextView(activity)
val button = Button(activity)
var opened = false
list.setCombo(field, button, this::comboValue) { opened = true }
assertThat(field.text.toString(), `is`("text2"))
button.performClick()
assertTrue(opened)
field.setText("text3")
assertThat(comboValue, `is`("value3"))
}
}
| gpl-3.0 |
Konstie/SightsGuru | app/src/main/java/com/sightsguru/app/sections/base/BaseActivity.kt | 1 | 2589 | package com.sightsguru.app.sections.base
import android.os.Build
import android.os.Handler
import android.support.v7.app.AppCompatActivity
abstract class BaseActivity : AppCompatActivity() {
protected var handler: Handler? = null
protected var handlerThread: android.os.HandlerThread? = null
@Synchronized protected fun runInBackground(r: Runnable) {
if (handler != null) {
handler!!.post(r)
}
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
PERMISSIONS_REQUEST -> {
if (grantResults.isNotEmpty()
&& grantResults[0] == android.content.pm.PackageManager.PERMISSION_GRANTED
&& grantResults[1] == android.content.pm.PackageManager.PERMISSION_GRANTED) {
onPermissionGranted()
} else {
requestPermission()
}
}
}
}
protected abstract fun onPermissionGranted()
protected fun allPermissionsGranted(): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return checkSelfPermission(PERMISSION_CAMERA) == android.content.pm.PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(PERMISSION_STORAGE) == android.content.pm.PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(PERMISSION_LOCATION) == android.content.pm.PackageManager.PERMISSION_GRANTED
} else {
return true
}
}
protected fun requestPermission() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(PERMISSION_CAMERA) || shouldShowRequestPermissionRationale(PERMISSION_STORAGE) || shouldShowRequestPermissionRationale(PERMISSION_LOCATION)) {
android.widget.Toast.makeText(this@BaseActivity, "Camera AND storage permission are required for this demo", android.widget.Toast.LENGTH_LONG).show()
}
requestPermissions(arrayOf(PERMISSION_CAMERA, PERMISSION_STORAGE, PERMISSION_LOCATION), PERMISSIONS_REQUEST)
}
}
companion object {
private val PERMISSIONS_REQUEST = 1
private val PERMISSION_CAMERA = android.Manifest.permission.CAMERA
private val PERMISSION_STORAGE = android.Manifest.permission.WRITE_EXTERNAL_STORAGE
private val PERMISSION_LOCATION = android.Manifest.permission.ACCESS_FINE_LOCATION
}
} | apache-2.0 |
luiqn2007/miaowo | app/src/main/java/org/miaowo/miaowo/ui/FloatView.kt | 1 | 7201 | package org.miaowo.miaowo.ui
import android.app.Activity
import android.content.Context
import android.graphics.PixelFormat
import android.graphics.Point
import android.os.IBinder
import android.support.annotation.LayoutRes
import android.util.AttributeSet
import android.view.*
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import org.miaowo.miaowo.R
import org.miaowo.miaowo.App
import org.miaowo.miaowo.base.ListHolder
import org.miaowo.miaowo.util.FormatUtil
import kotlin.collections.ArrayList
import kotlin.properties.Delegates
/**
* 悬浮窗
* Created by luqin on 17-1-21.
*/
class FloatView : LinearLayout {
private var mEndX = 0f
private var mEndY = 0f
private var mStartX = 0f
private var mStartY = 0f
private var mChangeX = 0f
private var mChangeY = 0f
private val mScreenSize = FormatUtil.screenSize
private var mGravity = Gravity.CENTER
private var mManager = App.i.getSystemService(Context.WINDOW_SERVICE) as WindowManager
private var mPosition = Point(0, 0)
private var mToken: IBinder? = null // View.applicationWindowToken
private var mSlop = ViewConfiguration.get(App.i).scaledTouchSlop
private var isShowing = false
var view by Delegates.notNull<View>()
var title: String? = null
var positionSave: ((position: Point, gravity: Int) -> Unit) = { _, _ -> }
constructor(title: String, @LayoutRes layout: Int, viewToken: IBinder) : super(App.i) {
init()
reset(title, layout, viewToken)
}
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init()
}
fun show(gravity: Int, position: Point): FloatView {
mPosition = position
mGravity = gravity
return show()
}
fun show(gravity: Int, xPos: Int, yPos: Int): FloatView {
mPosition.set(xPos, yPos)
mGravity = gravity
return show()
}
fun show(): FloatView {
if (isShowing) {
val index = shownWindows.indexOf(this)
if (index > 0) {
val bfViews = shownWindows.subList(0, index - 1)
shownWindows[0] = this
(0 until index).forEach {
shownWindows[it + 1] = bfViews[it]
}
}
return this
}
val params = buildLayoutParams()
shownWindows.add(this)
isShowing = true
mManager.addView(this, params)
return this
}
fun dismiss(clear: Boolean): FloatView {
if (isShowing) {
mManager.removeView(this)
shownWindows.remove(this)
isShowing = false
positionSave(mPosition, mGravity)
}
if (clear) {
findViewById<FrameLayout>(R.id.container).removeAllViews()
mPosition.set(0, 0)
mGravity = Gravity.CENTER
mToken = null
title = ""
}
return this
}
fun reset(title: String, @LayoutRes layout: Int, viewToken: IBinder) {
dismiss(true)
this.title = title
mToken = viewToken
setLayout(layout)
}
private fun buildLayoutParams(): WindowManager.LayoutParams {
return WindowManager.LayoutParams().apply {
gravity = mGravity
x = mPosition.x
y = mPosition.y
width = WindowManager.LayoutParams.WRAP_CONTENT
height = WindowManager.LayoutParams.WRAP_CONTENT
token = mToken
// 外部可点击
tag = // WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
// 变暗
WindowManager.LayoutParams.FLAG_DIM_BEHIND or
// 保持常亮
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or
// 无视其他修饰物
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or
WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR or
// 允许屏幕之外
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS or
// 防止脸误触
WindowManager.LayoutParams.FLAG_IGNORE_CHEEK_PRESSES
type = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL
format = PixelFormat.RGBA_8888
}
}
private fun init() = LayoutInflater.from(context).inflate(R.layout.ui_window_normal, this)
private fun setLayout(@LayoutRes layout: Int) {
val container = findViewById<FrameLayout>(R.id.container)
view = LayoutInflater.from(context).inflate(layout, container)
}
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
mStartX = event.x
mStartY = event.y
}
MotionEvent.ACTION_MOVE -> {
mEndX = event.x
mEndY = event.y
mChangeX = mEndX - mStartX
mChangeY = mEndY - mStartY
if (mChangeX * mChangeX + mChangeY * mChangeY >= mSlop * mSlop) {
val params = layoutParams as WindowManager.LayoutParams
val limitXR = mScreenSize.x + params.width / 5 * 4
val limitXL = -params.width / 5
val limitYB = mScreenSize.y + params.height / 5 * 4
val limitYT = -params.height / 5
val pX = params.x + mChangeX.toInt()
val pY = params.y - mChangeY.toInt()
when {
pX > limitXR -> params.x = limitXR
pX < limitXL -> params.x = limitXL
else -> params.x = pX
}
when {
pY > limitYB -> params.y = limitYB
pY < limitYT -> params.y = limitYT
else -> params.y = pY
}
mPosition.set(params.x, params.y)
mManager.updateViewLayout(this, params)
}
}
MotionEvent.ACTION_UP -> {
positionSave(mPosition, mGravity)
}
}
return true
}
fun defaultBar(): FloatView {
val holder = ListHolder(this)
holder.find(R.id.iv_close)?.setOnClickListener { dismiss(false) }
holder.find(R.id.pb_loading)?.visibility = View.GONE
holder.find<TextView>(R.id.tv_page)?.text = title ?: ""
return this
}
companion object {
var shownWindows = ArrayList<FloatView>(5)
fun setDimAmount(activity: Activity, dimAmount: Float) {
val window = activity.window
val lp = window.attributes
lp.dimAmount = dimAmount
window.attributes = lp
}
fun dismissFirst() = shownWindows.firstOrNull()?.dismiss(true)
}
} | apache-2.0 |
appnexus/mobile-sdk-android | tests/AppNexusSDKTestApp/app/src/androidTest/java/appnexus/com/appnexussdktestapp/functional/banner/BannerLazyLoadTest.kt | 1 | 8118 | /*
* Copyright 2012 APPNEXUS 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 appnexus.com.appnexussdktestapp.functional.banner
import android.content.Intent
import android.content.res.Resources
import android.view.View
import androidx.test.espresso.Espresso
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.IdlingPolicies
import androidx.test.espresso.IdlingRegistry
import androidx.test.espresso.ViewAction
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.assertion.ViewAssertions
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.intent.matcher.IntentMatchers
import androidx.test.espresso.intent.rule.IntentsTestRule
import androidx.test.espresso.matcher.ViewMatchers
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.runner.AndroidJUnit4
import androidx.test.rule.ActivityTestRule
import appnexus.com.appnexussdktestapp.BannerActivity
import appnexus.com.appnexussdktestapp.BannerLazyLoadActivity
import appnexus.com.appnexussdktestapp.R
import com.appnexus.opensdk.ANClickThroughAction
import com.appnexus.opensdk.AdActivity
import com.appnexus.opensdk.XandrAd
import com.appnexus.opensdk.utils.StringUtil
import com.appnexus.opensdk.utils.ViewUtil
import com.microsoft.appcenter.espresso.Factory
import org.hamcrest.CoreMatchers
import org.junit.*
import org.junit.runner.RunWith
import java.util.concurrent.TimeUnit
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class BannerLazyLoadTest {
val Int.dp: Int
get() = (this / Resources.getSystem().displayMetrics.density).toInt()
val Int.px: Int
get() = (this * Resources.getSystem().displayMetrics.density).toInt()
@get:Rule
var reportHelper = Factory.getReportHelper()
@Rule
@JvmField
var mActivityTestRule = IntentsTestRule(BannerLazyLoadActivity::class.java, false, false)
lateinit var bannerActivity: BannerLazyLoadActivity
@Before
fun setup() {
XandrAd.init(123, null, false, null)
IdlingPolicies.setMasterPolicyTimeout(1, TimeUnit.MINUTES)
IdlingPolicies.setIdlingResourceTimeout(1, TimeUnit.MINUTES)
var intent = Intent()
mActivityTestRule.launchActivity(intent)
bannerActivity = mActivityTestRule.activity
IdlingRegistry.getInstance().register(bannerActivity.idlingResource)
}
@After
fun destroy() {
IdlingRegistry.getInstance().unregister(bannerActivity.idlingResource)
reportHelper.label("Stopping App")
}
/*
* Test for the Invalid Renderer Url for Banner Native Ad (NativeAssemblyRenderer)
* */
@Test
fun bannerLazyLoad() {
Thread.sleep(2000)
Espresso.onView(ViewMatchers.withId(R.id.main_content))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
Espresso.onView(ViewMatchers.withId(R.id.main_content))
.check(ViewAssertions.matches(ViewMatchers.hasChildCount(2)))
// Espresso.onView(ViewMatchers.withId(bannerActivity.banner_id))
// .check(ViewAssertions.matches(CoreMatchers.not(ViewMatchers.isDisplayed())))
onView(withId(R.id.activateWebview)).perform(ViewActions.click())
Thread.sleep(5000)
Espresso.onView(ViewMatchers.withId(R.id.main_content))
.check(ViewAssertions.matches(ViewMatchers.hasChildCount(3)))
Espresso.onView(ViewMatchers.withId(bannerActivity.banner_id))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
Assert.assertTrue(
"Wrong Ad Width",
bannerActivity.banner.getChildAt(0).width.dp >= (bannerActivity.banner.adWidth - 1) ||
bannerActivity.banner.getChildAt(0).width.dp <= (bannerActivity.banner.adWidth + 1)
)
Assert.assertTrue(
"Wrong Ad Height",
bannerActivity.banner.getChildAt(0).height.dp >= (bannerActivity.banner.adHeight - 1) ||
bannerActivity.banner.getChildAt(0).height.dp <= (bannerActivity.banner.adHeight + 1)
)
println("LAZY LOAD: " + bannerActivity.logListener.logMsg)
}
/*
* Test for the Invalid Renderer Url for Banner Native Ad (NativeAssemblyRenderer)
* */
@Test
fun bannerLazyLoadReload() {
Thread.sleep(2000)
Espresso.onView(ViewMatchers.withId(R.id.main_content))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
Espresso.onView(ViewMatchers.withId(R.id.main_content))
.check(ViewAssertions.matches(ViewMatchers.hasChildCount(2)))
// Espresso.onView(ViewMatchers.withId(bannerActivity.banner_id))
// .check(ViewAssertions.matches(CoreMatchers.not(ViewMatchers.isDisplayed())))
onView(withId(R.id.activateWebview)).perform(ViewActions.click())
Thread.sleep(5000)
Espresso.onView(ViewMatchers.withId(R.id.main_content))
.check(ViewAssertions.matches(ViewMatchers.hasChildCount(3)))
Espresso.onView(ViewMatchers.withId(bannerActivity.banner_id))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
Assert.assertTrue(
"Wrong Ad Width",
bannerActivity.banner.getChildAt(0).width.dp >= (bannerActivity.banner.adWidth - 1) ||
bannerActivity.banner.getChildAt(0).width.dp <= (bannerActivity.banner.adWidth + 1)
)
Assert.assertTrue(
"Wrong Ad Height",
bannerActivity.banner.getChildAt(0).height.dp >= (bannerActivity.banner.adHeight - 1) ||
bannerActivity.banner.getChildAt(0).height.dp <= (bannerActivity.banner.adHeight + 1)
)
println("LAZY LOAD: " + bannerActivity.logListener.logMsg)
onView(withId(R.id.enableAndReload)).perform(ViewActions.click())
Thread.sleep(2000)
Espresso.onView(ViewMatchers.withId(R.id.main_content))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
Espresso.onView(ViewMatchers.withId(R.id.main_content))
.check(ViewAssertions.matches(ViewMatchers.hasChildCount(3)))
// Espresso.onView(ViewMatchers.withId(bannerActivity.banner_id))
// .check(ViewAssertions.matches(CoreMatchers.not(ViewMatchers.isDisplayed())))
// Assert.assertNull(
// "Webview must have been removed at this point",
// bannerActivity.banner.getChildAt(0))
onView(withId(R.id.activateWebview)).perform(ViewActions.click())
Thread.sleep(5000)
Espresso.onView(ViewMatchers.withId(R.id.main_content))
.check(ViewAssertions.matches(ViewMatchers.hasChildCount(3)))
Espresso.onView(ViewMatchers.withId(bannerActivity.banner_id))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
Assert.assertTrue(
"Wrong Ad Width",
bannerActivity.banner.getChildAt(0).width.dp >= (bannerActivity.banner.adWidth - 1) ||
bannerActivity.banner.getChildAt(0).width.dp <= (bannerActivity.banner.adWidth + 1)
)
Assert.assertTrue(
"Wrong Ad Height",
bannerActivity.banner.getChildAt(0).height.dp >= (bannerActivity.banner.adHeight - 1) ||
bannerActivity.banner.getChildAt(0).height.dp <= (bannerActivity.banner.adHeight + 1)
)
}
}
| apache-2.0 |
nidi3/emoji-art | src/main/kotlin/guru/nidi/emojiart/Eyer.kt | 1 | 2297 | /*
* Copyright © 2017 Stefan Niederhauser ([email protected])
*
* 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 guru.nidi.emojiart
class Eyer {
@Volatile private var running = false
fun start() {
if (!running) {
running = true
Thread {
while (running) {
eyes("(o)(o)", 800, 1200)
val r = Math.random()
when {
r < .2 -> bigEyes()
r < .4 -> oneEye()
else -> blink()
}
}
}.apply {
isDaemon = true
start()
}
}
}
fun stop() {
running = false
}
private fun bigEyes() {
eyes("(O)(O)", 300, 500)
eyes("(o)(o)", 100, 200)
eyes("(O)(O)", 300, 500)
}
private fun oneEye() {
val r = Math.random()
val s = when {
r < .5 -> "(-)(o)(_)(O)"
else -> "(o)(-)(O)(_)"
}
eyes(s.substring(0, 6), 50, 150)
eyes(s.substring(6, 12), 500, 800)
}
private fun blink() {
val r = Math.random()
val s = when {
r < .33 -> "(-)(-)(_)(_)"
r < .66 -> "(-)(o)(_)(o)"
else -> "(o)(-)(o)(_)"
}
eyes(s.substring(0, 6), 20, 50)
eyes(s.substring(6, 12), 20, 50)
}
private fun eyes(s: String, min: Int, max: Int) {
print(s + "\u001b[6D")
System.out.flush()
sleep(min, max)
}
private fun sleep(min: Int, max: Int) {
try {
Thread.sleep((Math.random() * (max - min) + min).toLong())
} catch (e: InterruptedException) {
//ignore
}
}
} | apache-2.0 |
shyiko/ktlint | ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/SpacingAroundKeywordRule.kt | 1 | 4126 | package com.pinterest.ktlint.ruleset.standard
import com.pinterest.ktlint.core.Rule
import com.pinterest.ktlint.core.ast.ElementType.CATCH_KEYWORD
import com.pinterest.ktlint.core.ast.ElementType.DO_KEYWORD
import com.pinterest.ktlint.core.ast.ElementType.ELSE_KEYWORD
import com.pinterest.ktlint.core.ast.ElementType.FINALLY_KEYWORD
import com.pinterest.ktlint.core.ast.ElementType.FOR_KEYWORD
import com.pinterest.ktlint.core.ast.ElementType.GET_KEYWORD
import com.pinterest.ktlint.core.ast.ElementType.IF_KEYWORD
import com.pinterest.ktlint.core.ast.ElementType.RBRACE
import com.pinterest.ktlint.core.ast.ElementType.SET_KEYWORD
import com.pinterest.ktlint.core.ast.ElementType.TRY_KEYWORD
import com.pinterest.ktlint.core.ast.ElementType.WHEN_KEYWORD
import com.pinterest.ktlint.core.ast.ElementType.WHILE_KEYWORD
import com.pinterest.ktlint.core.ast.ElementType.WHITE_SPACE
import com.pinterest.ktlint.core.ast.nextLeaf
import com.pinterest.ktlint.core.ast.prevLeaf
import com.pinterest.ktlint.core.ast.upsertWhitespaceAfterMe
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafElement
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.com.intellij.psi.tree.TokenSet.create
import org.jetbrains.kotlin.kdoc.psi.impl.KDocName
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtPropertyAccessor
import org.jetbrains.kotlin.psi.KtWhenEntry
class SpacingAroundKeywordRule : Rule("keyword-spacing") {
private val noLFBeforeSet = create(ELSE_KEYWORD, CATCH_KEYWORD, FINALLY_KEYWORD)
private val tokenSet = create(
FOR_KEYWORD, IF_KEYWORD, ELSE_KEYWORD, WHILE_KEYWORD, DO_KEYWORD,
TRY_KEYWORD, CATCH_KEYWORD, FINALLY_KEYWORD, WHEN_KEYWORD
)
private val keywordsWithoutSpaces = create(GET_KEYWORD, SET_KEYWORD)
override fun visit(
node: ASTNode,
autoCorrect: Boolean,
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit
) {
if (node is LeafPsiElement) {
if (tokenSet.contains(node.elementType) && node.parent !is KDocName && node.nextLeaf() !is PsiWhiteSpace) {
emit(node.startOffset + node.text.length, "Missing spacing after \"${node.text}\"", true)
if (autoCorrect) {
node.upsertWhitespaceAfterMe(" ")
}
} else if (keywordsWithoutSpaces.contains(node.elementType) && node.nextLeaf() is PsiWhiteSpace) {
val parent = node.parent
val nextLeaf = node.nextLeaf()
if (parent is KtPropertyAccessor && parent.hasBody() && nextLeaf != null) {
emit(node.startOffset, "Unexpected spacing after \"${node.text}\"", true)
if (autoCorrect) {
nextLeaf.treeParent.removeChild(nextLeaf)
}
}
}
if (noLFBeforeSet.contains(node.elementType)) {
val prevLeaf = node.prevLeaf()
val isElseKeyword = node.elementType == ELSE_KEYWORD
if (
prevLeaf?.elementType == WHITE_SPACE &&
prevLeaf.textContains('\n') &&
(!isElseKeyword || node.parent !is KtWhenEntry)
) {
val rBrace = prevLeaf.prevLeaf()?.takeIf { it.elementType == RBRACE }
val parentOfRBrace = rBrace?.treeParent
if (
parentOfRBrace is KtBlockExpression &&
(!isElseKeyword || parentOfRBrace.treeParent?.treeParent == node.treeParent)
) {
emit(node.startOffset, "Unexpected newline before \"${node.text}\"", true)
if (autoCorrect) {
(prevLeaf as LeafElement).rawReplaceWithText(" ")
}
}
}
}
}
}
}
| mit |
JayNewstrom/Concrete | concrete-sample/src/main/java/com/jaynewstrom/concretesample/details/DetailsListAdapter.kt | 1 | 713 | package com.jaynewstrom.concretesample.details
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
internal class DetailsListAdapter : BaseAdapter() {
override fun getCount(): Int = 50
override fun getItem(position: Int) = position
override fun getItemId(position: Int): Long = position.toLong()
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val listItemView: DetailsListItemView = if (convertView == null) {
DetailsListItemView(parent.context)
} else {
convertView as DetailsListItemView
}
listItemView.setPosition(position)
return listItemView
}
}
| apache-2.0 |
SerenityEnterprises/SerenityCE | src/main/java/host/serenity/serenity/event/internal/GameShutdown.kt | 1 | 156 | package host.serenity.serenity.event.internal
import java.util.*
class GameShutdown
class PostGameShutdown {
val tasks: List<Runnable> = ArrayList()
} | gpl-3.0 |
kmizu/kollection | src/main/kotlin/com/github/kmizu/kollection/tuples/Tuple42.kt | 1 | 920 | data class Tuple42<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42>(val item1: T1, val item2: T2, val item3: T3, val item4: T4, val item5: T5, val item6: T6, val item7: T7, val item8: T8, val item9: T9, val item10: T10, val item11: T11, val item12: T12, val item13: T13, val item14: T14, val item15: T15, val item16: T16, val item17: T17, val item18: T18, val item19: T19, val item20: T20, val item21: T21, val item22: T22, val item23: T23, val item24: T24, val item25: T25, val item26: T26, val item27: T27, val item28: T28, val item29: T29, val item30: T30, val item31: T31, val item32: T32, val item33: T33, val item34: T34, val item35: T35, val item36: T36, val item37: T37, val item38: T38, val item39: T39, val item40: T40, val item41: T41, val item42: T42) {
}
| mit |
nt-ca-aqe/library-app | library-service/src/test/kotlin/library/service/database/BookRecordToDocumentMapperTest.kt | 1 | 2743 | package library.service.database
import library.service.business.books.domain.BookRecord
import library.service.business.books.domain.states.Available
import library.service.business.books.domain.states.Borrowed
import library.service.business.books.domain.types.BookId
import library.service.business.books.domain.types.Borrower
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import utils.Books
import utils.classification.UnitTest
import java.time.OffsetDateTime
@UnitTest
internal class BookRecordToDocumentMapperTest {
val cut = BookRecordToDocumentMapper()
@Test fun `mapping uses the record's id as a UUID`() {
val bookId = BookId.generate()
val bookRecord = BookRecord(bookId, Books.THE_LORD_OF_THE_RINGS_1)
with(cut.map(bookRecord)) {
assertThat(id).isEqualTo(bookId.toUuid())
}
}
@Test fun `mapping uses string representations of the record's book data`() {
val bookId = BookId.generate()
val book = Books.THE_LORD_OF_THE_RINGS_2
with(cut.map(BookRecord(bookId, book))) {
assertThat(isbn).isEqualTo("9780261102361")
assertThat(title).isEqualTo("The Lord of the Rings 2. The Two Towers")
assertThat(authors).containsExactly("J.R.R. Tolkien")
}
}
@Nested inner class `handling of 'borrowed' state` {
@Test fun `mapping sets borrowed to null if record has 'available' state`() {
val bookId = BookId.generate()
val book = Books.THE_LORD_OF_THE_RINGS_3
with(cut.map(BookRecord(bookId, book, Available))) {
assertThat(borrowed).isNull()
}
}
@Test fun `mapping sets borrowed if record has 'borrowed' state`() {
val bookId = BookId.generate()
val book = Books.THE_LORD_OF_THE_RINGS_3
val state = Borrowed(Borrower("Frodo"), OffsetDateTime.parse("2017-12-16T12:34:56.789Z"))
with(cut.map(BookRecord(bookId, book, state))) {
assertThat(borrowed).isNotNull()
assertThat(borrowed?.by).isEqualTo("Frodo")
assertThat(borrowed?.on).isEqualTo("2017-12-16T12:34:56.789Z")
}
}
@Test fun `mapping converts borrowed timestamp to UTC timezone`() {
val bookId = BookId.generate()
val book = Books.THE_LORD_OF_THE_RINGS_3
val state = Borrowed(Borrower("Frodo"), OffsetDateTime.parse("2017-12-16T12:34:56.789+01:00"))
with(cut.map(BookRecord(bookId, book, state))) {
assertThat(borrowed?.on).isEqualTo("2017-12-16T11:34:56.789Z")
}
}
}
} | apache-2.0 |
eugeis/ee | ee-system/src-gen/main/kotlin/ee/system/SharedApiBase.kt | 1 | 18314 | package ee.system
import ee.lang.Composite
import java.nio.file.Path
import java.nio.file.Paths
enum class PackageState(var order: Int = 0) {
UNKNOWN(0), RESOLVED(1), PREPARED(2), INSTALLED(3), UNINSTALLED(-1);
fun isUnknown(): Boolean = this == UNKNOWN
fun isResolved(): Boolean = this == RESOLVED
fun isPrepared(): Boolean = this == PREPARED
fun isInstalled(): Boolean = this == INSTALLED
fun isUninstalled(): Boolean = this == UNINSTALLED
}
fun String?.toPackageState(): PackageState {
return if (this != null) {
PackageState.valueOf(this)
} else {
PackageState.UNKNOWN
}
}
data class PackageCoordinate(var classifier: String = "", var version: String = "", var group: String = "",
var artifact: String = "", var type: String = "", var packaging: String = "") {
companion object {
val EMPTY = PackageCoordinate()
}
}
fun PackageCoordinate?.orEmpty(): PackageCoordinate {
return if (this != null) this else PackageCoordinate.EMPTY
}
data class PackagePaths(var resolved: Path = Paths.get(""), var prepared: Path = Paths.get(""),
var installed: Path = Paths.get("")) {
companion object {
val EMPTY = PackagePaths()
}
}
fun PackagePaths?.orEmpty(): PackagePaths {
return if (this != null) this else PackagePaths.EMPTY
}
abstract class SystemBase : Composite {
constructor(elName: String = "") : super({ name(elName) }) {
}
}
open class System : SystemBase {
companion object {
val EMPTY = System()
}
var machines: MutableList<Machine> = arrayListOf()
constructor(elName: String = "", machines: MutableList<Machine> = arrayListOf()) : super(elName) {
this.machines = machines
}
}
fun System?.orEmpty(): System {
return if (this != null) this else System.EMPTY
}
open class Machine : SystemBase {
companion object {
val EMPTY = Machine()
}
var workspaces: MutableList<Workspace> = arrayListOf()
constructor(elName: String = "", workspaces: MutableList<Workspace> = arrayListOf()) : super(elName) {
this.workspaces = workspaces
}
}
fun Machine?.orEmpty(): Machine {
return if (this != null) this else Machine.EMPTY
}
open class Workspace : SystemBase {
companion object {
val EMPTY = Workspace()
}
var home: Path = Paths.get("")
var meta: Path = Paths.get("")
var prepared: Path = Paths.get("")
var services: MutableList<Service> = arrayListOf()
var tools: MutableList<Tool> = arrayListOf()
var packages: MutableList<Package> = arrayListOf()
constructor(elName: String = "", home: Path = Paths.get(""), meta: Path = Paths.get(""),
prepared: Path = Paths.get(""), services: MutableList<Service> = arrayListOf(),
tools: MutableList<Tool> = arrayListOf(), packages: MutableList<Package> = arrayListOf()) : super(elName) {
this.home = home
this.meta = meta
this.prepared = prepared
this.services = services
this.tools = tools
this.packages = packages
}
}
fun Workspace?.orEmpty(): Workspace {
return if (this != null) this else Workspace.EMPTY
}
open class Service : SystemBase {
companion object {
val EMPTY = Service()
}
var category: String = ""
var dependsOn: MutableList<Service> = arrayListOf()
var dependsOnMe: MutableList<Service> = arrayListOf()
constructor(elName: String = "", category: String = "", dependsOn: MutableList<Service> = arrayListOf(),
dependsOnMe: MutableList<Service> = arrayListOf()) : super(elName) {
this.category = category
this.dependsOn = dependsOn
this.dependsOnMe = dependsOnMe
}
}
fun Service?.orEmpty(): Service {
return if (this != null) this else Service.EMPTY
}
abstract class SocketServiceBase : Service {
companion object {
val EMPTY = SocketService()
}
var host: String = ""
var port: Int = 0
constructor(elName: String = "", category: String = "", dependsOn: MutableList<Service> = arrayListOf(),
dependsOnMe: MutableList<Service> = arrayListOf(), host: String = "", port: Int = 0) : super(elName, category,
dependsOn, dependsOnMe) {
this.host = host
this.port = port
}
}
fun SocketServiceBase?.orEmpty(): SocketService {
return if (this != null) this as SocketService else SocketServiceBase.EMPTY
}
open class JmxService : SocketService {
companion object {
val EMPTY = JmxService()
}
constructor(elName: String = "", category: String = "", dependsOn: MutableList<Service> = arrayListOf(),
dependsOnMe: MutableList<Service> = arrayListOf(), host: String = "", port: Int = 0) : super(elName, category,
dependsOn, dependsOnMe, host, port) {
}
}
fun JmxService?.orEmpty(): JmxService {
return if (this != null) this else JmxService.EMPTY
}
open class JavaService : SocketService {
companion object {
val EMPTY = JavaService()
}
var home: Path = Paths.get("")
var logs: Path = Paths.get("")
var configs: Path = Paths.get("")
var command: String = ""
constructor(elName: String = "", category: String = "", dependsOn: MutableList<Service> = arrayListOf(),
dependsOnMe: MutableList<Service> = arrayListOf(), host: String = "", port: Int = 0, home: Path = Paths.get(""),
logs: Path = Paths.get(""), configs: Path = Paths.get(""), command: String = "") : super(elName, category,
dependsOn, dependsOnMe, host, port) {
this.home = home
this.logs = logs
this.configs = configs
this.command = command
}
}
fun JavaService?.orEmpty(): JavaService {
return if (this != null) this else JavaService.EMPTY
}
open class Package : SystemBase {
companion object {
val EMPTY = Package()
}
var category: String = ""
var coordinate: PackageCoordinate = PackageCoordinate.EMPTY
var state: PackageState = PackageState.UNKNOWN
var dependsOn: MutableList<Package> = arrayListOf()
var dependsOnMe: MutableList<Package> = arrayListOf()
var paths: PackagePaths = PackagePaths.EMPTY
constructor(elName: String = "", category: String = "", coordinate: PackageCoordinate = PackageCoordinate.EMPTY,
state: PackageState = PackageState.UNKNOWN, dependsOn: MutableList<Package> = arrayListOf(),
dependsOnMe: MutableList<Package> = arrayListOf(), paths: PackagePaths = PackagePaths.EMPTY) : super(elName) {
this.category = category
this.coordinate = coordinate
this.state = state
this.dependsOn = dependsOn
this.dependsOnMe = dependsOnMe
this.paths = paths
}
}
fun Package?.orEmpty(): Package {
return if (this != null) this else Package.EMPTY
}
open class ContentPackage : Package {
companion object {
val EMPTY = ContentPackage()
}
var targetCoordinate: PackageCoordinate = PackageCoordinate.EMPTY
constructor(elName: String = "", category: String = "", coordinate: PackageCoordinate = PackageCoordinate.EMPTY,
state: PackageState = PackageState.UNKNOWN, dependsOn: MutableList<Package> = arrayListOf(),
dependsOnMe: MutableList<Package> = arrayListOf(), paths: PackagePaths = PackagePaths.EMPTY,
targetCoordinate: PackageCoordinate = PackageCoordinate.EMPTY) : super(elName, category, coordinate, state,
dependsOn, dependsOnMe, paths) {
this.targetCoordinate = targetCoordinate
}
}
fun ContentPackage?.orEmpty(): ContentPackage {
return if (this != null) this else ContentPackage.EMPTY
}
open class MetaPackage : Package {
companion object {
val EMPTY = MetaPackage()
}
var targetCoordinate: PackageCoordinate = PackageCoordinate.EMPTY
constructor(elName: String = "", category: String = "", coordinate: PackageCoordinate = PackageCoordinate.EMPTY,
state: PackageState = PackageState.UNKNOWN, dependsOn: MutableList<Package> = arrayListOf(),
dependsOnMe: MutableList<Package> = arrayListOf(), paths: PackagePaths = PackagePaths.EMPTY,
targetCoordinate: PackageCoordinate = PackageCoordinate.EMPTY) : super(elName, category, coordinate, state,
dependsOn, dependsOnMe, paths) {
this.targetCoordinate = targetCoordinate
}
}
fun MetaPackage?.orEmpty(): MetaPackage {
return if (this != null) this else MetaPackage.EMPTY
}
open class AddonPackage : MetaPackage {
companion object {
val EMPTY = AddonPackage()
}
var extract: Boolean = false
var includes: String = ""
var excludes: String = ""
var target: Path = Paths.get("")
constructor(elName: String = "", category: String = "", coordinate: PackageCoordinate = PackageCoordinate.EMPTY,
state: PackageState = PackageState.UNKNOWN, dependsOn: MutableList<Package> = arrayListOf(),
dependsOnMe: MutableList<Package> = arrayListOf(), paths: PackagePaths = PackagePaths.EMPTY,
targetCoordinate: PackageCoordinate = PackageCoordinate.EMPTY, extract: Boolean = false, includes: String = "",
excludes: String = "", target: Path = Paths.get("")) : super(elName, category, coordinate, state, dependsOn,
dependsOnMe, paths, targetCoordinate) {
this.extract = extract
this.includes = includes
this.excludes = excludes
this.target = target
}
}
fun AddonPackage?.orEmpty(): AddonPackage {
return if (this != null) this else AddonPackage.EMPTY
}
abstract class ToolBase : SystemBase {
companion object {
val EMPTY = Tool()
}
var home: Path = Paths.get("")
constructor(elName: String = "", home: Path = Paths.get("")) : super(elName) {
this.home = home
}
}
fun ToolBase?.orEmpty(): Tool {
return if (this != null) this as Tool else ToolBase.EMPTY
}
abstract class ServiceControllerBase<T : Service> {
companion object {
val EMPTY = ServiceController<Service>(Service.EMPTY)
}
var item: T
constructor(item: T) {
this.item = item
}
abstract fun start()
abstract fun stop()
abstract fun ping(): Boolean
abstract fun copyLogs(target: Path = Paths.get(""))
abstract fun copyConfigs(target: Path = Paths.get(""))
abstract fun deleteLogs()
abstract fun deleteOpsData()
}
fun ServiceControllerBase<*>?.orEmpty(): ServiceController<*> {
return if (this != null) this as ServiceController<*> else ServiceControllerBase.EMPTY
}
abstract class ServiceQueriesBase<T : Service> {
companion object {
val EMPTY = ServiceQueries<Service>()
}
constructor() {
}
}
fun ServiceQueriesBase<*>?.orEmpty(): ServiceQueries<*> {
return if (this != null) this as ServiceQueries<*> else ServiceQueriesBase.EMPTY
}
abstract class ServiceCommandsBase<T : Service> {
companion object {
val EMPTY = ServiceCommands<Service>(Service.EMPTY)
}
var item: T
constructor(item: T) {
this.item = item
}
}
fun ServiceCommandsBase<*>?.orEmpty(): ServiceCommands<*> {
return if (this != null) this as ServiceCommands<*> else ServiceCommandsBase.EMPTY
}
abstract class SocketServiceControllerBase<T : SocketService> : ServiceController<T> {
companion object {
val EMPTY = SocketServiceController<SocketService>(SocketService.EMPTY)
}
constructor(item: T) : super(item) {
}
}
fun SocketServiceControllerBase<*>?.orEmpty(): SocketServiceController<*> {
return if (this != null) this as SocketServiceController<*> else SocketServiceControllerBase.EMPTY
}
abstract class SocketServiceQueriesBase<T : SocketService> : ServiceQueries<T> {
companion object {
val EMPTY = SocketServiceQueries<SocketService>()
}
constructor() : super() {
}
}
fun SocketServiceQueriesBase<*>?.orEmpty(): SocketServiceQueries<*> {
return if (this != null) this as SocketServiceQueries<*> else SocketServiceQueriesBase.EMPTY
}
abstract class SocketServiceCommandsBase<T : SocketService> : ServiceCommands<T> {
companion object {
val EMPTY = SocketServiceCommands<SocketService>(SocketService.EMPTY)
}
constructor(item: T) : super(item) {
}
}
fun SocketServiceCommandsBase<*>?.orEmpty(): SocketServiceCommands<*> {
return if (this != null) this as SocketServiceCommands<*> else SocketServiceCommandsBase.EMPTY
}
abstract class JmxServiceControllerBase<T : JmxService> : SocketServiceController<T> {
companion object {
val EMPTY = JmxServiceController<JmxService>(JmxService.EMPTY)
}
constructor(item: T) : super(item) {
}
}
fun JmxServiceControllerBase<*>?.orEmpty(): JmxServiceController<*> {
return if (this != null) this as JmxServiceController<*> else JmxServiceControllerBase.EMPTY
}
abstract class JmxServiceQueriesBase<T : JmxService> : SocketServiceQueries<T> {
companion object {
val EMPTY = JmxServiceQueries<JmxService>()
}
constructor() : super() {
}
}
fun JmxServiceQueriesBase<*>?.orEmpty(): JmxServiceQueries<*> {
return if (this != null) this as JmxServiceQueries<*> else JmxServiceQueriesBase.EMPTY
}
abstract class JmxServiceCommandsBase<T : JmxService> : SocketServiceCommands<T> {
companion object {
val EMPTY = JmxServiceCommands<JmxService>(JmxService.EMPTY)
}
constructor(item: T) : super(item) {
}
}
fun JmxServiceCommandsBase<*>?.orEmpty(): JmxServiceCommands<*> {
return if (this != null) this as JmxServiceCommands<*> else JmxServiceCommandsBase.EMPTY
}
abstract class JavaServiceControllerBase<T : JavaService> : SocketServiceController<T> {
companion object {
val EMPTY = JavaServiceController<JavaService>(JavaService.EMPTY)
}
constructor(item: T) : super(item) {
}
}
fun JavaServiceControllerBase<*>?.orEmpty(): JavaServiceController<*> {
return if (this != null) this as JavaServiceController<*> else JavaServiceControllerBase.EMPTY
}
abstract class JavaServiceQueriesBase<T : JavaService> : SocketServiceQueries<T> {
companion object {
val EMPTY = JavaServiceQueries<JavaService>()
}
constructor() : super() {
}
}
fun JavaServiceQueriesBase<*>?.orEmpty(): JavaServiceQueries<*> {
return if (this != null) this as JavaServiceQueries<*> else JavaServiceQueriesBase.EMPTY
}
abstract class JavaServiceCommandsBase<T : JavaService> : SocketServiceCommands<T> {
companion object {
val EMPTY = JavaServiceCommands<JavaService>(JavaService.EMPTY)
}
constructor(item: T) : super(item) {
}
}
fun JavaServiceCommandsBase<*>?.orEmpty(): JavaServiceCommands<*> {
return if (this != null) this as JavaServiceCommands<*> else JavaServiceCommandsBase.EMPTY
}
abstract class PackageControllerBase<T : Package> {
companion object {
val EMPTY = PackageController<Package>(Package.EMPTY)
}
var item: T
constructor(item: T) {
this.item = item
}
abstract fun prepare(params: Map<String, String> = hashMapOf())
abstract fun configure(params: Map<String, String> = hashMapOf())
abstract fun install(params: Map<String, String> = hashMapOf())
abstract fun uninstall()
}
fun PackageControllerBase<*>?.orEmpty(): PackageController<*> {
return if (this != null) this as PackageController<*> else PackageControllerBase.EMPTY
}
abstract class PackageCommandsBase<T : Package> {
companion object {
val EMPTY = PackageCommands<Package>(Package.EMPTY)
}
var item: T
constructor(item: T) {
this.item = item
}
}
fun PackageCommandsBase<*>?.orEmpty(): PackageCommands<*> {
return if (this != null) this as PackageCommands<*> else PackageCommandsBase.EMPTY
}
abstract class ContentPackageControllerBase<T : ContentPackage> : PackageController<T> {
companion object {
val EMPTY = ContentPackageController<ContentPackage>(ContentPackage.EMPTY)
}
constructor(item: T) : super(item) {
}
}
fun ContentPackageControllerBase<*>?.orEmpty(): ContentPackageController<*> {
return if (this != null) this as ContentPackageController<*> else ContentPackageControllerBase.EMPTY
}
abstract class ContentPackageCommandsBase<T : ContentPackage> : PackageCommands<T> {
companion object {
val EMPTY = ContentPackageCommands<ContentPackage>(ContentPackage.EMPTY)
}
constructor(item: T) : super(item) {
}
}
fun ContentPackageCommandsBase<*>?.orEmpty(): ContentPackageCommands<*> {
return if (this != null) this as ContentPackageCommands<*> else ContentPackageCommandsBase.EMPTY
}
abstract class MetaPackageControllerBase<T : MetaPackage> : PackageController<T> {
companion object {
val EMPTY = MetaPackageController<MetaPackage>(MetaPackage.EMPTY)
}
constructor(item: T) : super(item) {
}
}
fun MetaPackageControllerBase<*>?.orEmpty(): MetaPackageController<*> {
return if (this != null) this as MetaPackageController<*> else MetaPackageControllerBase.EMPTY
}
abstract class MetaPackageCommandsBase<T : MetaPackage> : PackageCommands<T> {
companion object {
val EMPTY = MetaPackageCommands<MetaPackage>(MetaPackage.EMPTY)
}
constructor(item: T) : super(item) {
}
}
fun MetaPackageCommandsBase<*>?.orEmpty(): MetaPackageCommands<*> {
return if (this != null) this as MetaPackageCommands<*> else MetaPackageCommandsBase.EMPTY
}
abstract class AddonPackageControllerBase<T : AddonPackage> : MetaPackageController<T> {
companion object {
val EMPTY = AddonPackageController<AddonPackage>(AddonPackage.EMPTY)
}
constructor(item: T) : super(item) {
}
}
fun AddonPackageControllerBase<*>?.orEmpty(): AddonPackageController<*> {
return if (this != null) this as AddonPackageController<*> else AddonPackageControllerBase.EMPTY
}
abstract class AddonPackageCommandsBase<T : AddonPackage> : MetaPackageCommands<T> {
companion object {
val EMPTY = AddonPackageCommands<AddonPackage>(AddonPackage.EMPTY)
}
constructor(item: T) : super(item) {
}
}
fun AddonPackageCommandsBase<*>?.orEmpty(): AddonPackageCommands<*> {
return if (this != null) this as AddonPackageCommands<*> else AddonPackageCommandsBase.EMPTY
}
| apache-2.0 |
MeilCli/KLinq | src/main/kotlin/net/meilcli/klinq/internal/Lookup.kt | 1 | 1742 | package net.meilcli.klinq.internal
import net.meilcli.klinq.*
import java.util.*
internal class Lookup<TSource, TKey, TElement> : ILookup<TKey, TElement> {
private val enumerator: IEnumerator<IGrouping<TKey, TElement>>
private var list = ArrayList<IGrouping<TKey, TElement>>()
private var comparer: IEqualityComparer<TKey>
override var count: Int
constructor(
source: IEnumerable<TSource>,
keySelector: (TSource) -> TKey,
elementSelector: (TSource) -> TElement,
comparer: IEqualityComparer<TKey>) {
this.comparer = comparer
var map = HashMap<TKey, ArrayList<TElement>>()
var enumerator: IEnumerator<TSource> = source.getEnumerator()
while (enumerator.moveNext()) {
var key: TKey = keySelector(enumerator.current)
if (map.keys.toEnumerable().contains(key, comparer)) {
map[key]!!.add(elementSelector(enumerator.current))
} else {
map.put(key, ArrayList<TElement>())
map[key]!!.add(elementSelector(enumerator.current))
}
}
enumerator.reset()
for (key in map.keys) {
list.add(Grouping<TKey, TElement>(key, map[key]!!))
}
count = list.count()
this.enumerator = list.toEnumerable().getEnumerator()
}
override fun contains(key: TKey): Boolean {
return list.toEnumerable().any { x -> comparer.equals(x.key, key) }
}
override fun get(key: TKey): IEnumerable<TElement> {
return list.toEnumerable().single { x -> comparer.equals(x.key, key) }
}
override fun getEnumerator(): IEnumerator<IGrouping<TKey, TElement>> {
return enumerator
}
} | mit |
chRyNaN/GuitarChords | core/src/commonMain/kotlin/com.chrynan.chords/model/StringLabel.kt | 1 | 834 | package com.chrynan.chords.model
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* A model containing information about a label for a string in a chord diagram. This model
* contains the [string] the label should be displayed for and an optional [label] for that string.
* Chord diagrams may choose to either display this label, if it is not null, display the [string]
* number, or display no label indicator. Refer to [StringLabelState].
*
* @property [string] The [StringNumber] that this label should be displayed for.
* @property [label] The optional label that should be displayed for this string.
*
* @author chRyNaN
*/
@Serializable
data class StringLabel(
@SerialName(value = "string") val string: StringNumber,
@SerialName(value = "label") val label: String? = null
) | apache-2.0 |
suzp1984/Algorithms-Collection | kotlin/basics/src/main/kotlin/SortHelp.kt | 1 | 372 | package io.github.suzp1984.algorithms
inline fun <reified T> generateRandomArray(size: Int, start: T, end: T, noinline init: (Int) -> T) : Array<T> {
return Array<T>(size, init)
}
fun <T> Array<T>.printItSelf() {
print("[${this}]: ")
forEach { print("${it} ") }
}
//fun <T> generateNearlyOrderedIntArray(array: Array<T>, swapTimes: Int) : Array<T> {
//
//} | apache-2.0 |
shantstepanian/obevo | obevo-core/src/test/java/com/gs/obevo/impl/text/TextDependencyExtractorImplTest.kt | 1 | 5292 | /**
* Copyright 2017 Goldman Sachs.
* 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.gs.obevo.impl.text
import com.gs.obevo.api.appdata.CodeDependency
import com.gs.obevo.api.appdata.CodeDependencyType
import org.eclipse.collections.api.set.ImmutableSet
import org.eclipse.collections.impl.block.factory.Functions
import org.eclipse.collections.impl.factory.Lists
import org.eclipse.collections.impl.factory.Sets
import org.hamcrest.Matchers.containsInAnyOrder
import org.hamcrest.Matchers.empty
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThat
import org.junit.Test
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
class TextDependencyExtractorImplTest {
private val enricher = TextDependencyExtractorImpl(Functions.getStringPassThru()::valueOf)
@Test
fun testCalculateDependencies() {
val sp1 = newObject("sp1", "sp1 sp2('a')", Sets.immutable.empty(), Sets.immutable.with("manuallyAddedDependency"))
val sp2 = newObject("sp2", "sp2")
val sp3 = newObject("sp3", "sp3 sp1 ('a')sp2('a')")
val spA = newObject("spA", "spA sp1('a') ('a')sp2('a') sp3", Sets.immutable.with("sp1", "sp2"), Sets.immutable.empty())
val dependencies = enricher.calculateDependencies(Lists.mutable.with(sp1, sp2, sp3, spA))
assertThat(dependencies.get(sp1), containsInAnyOrder(CodeDependency("sp2", CodeDependencyType.DISCOVERED), CodeDependency("manuallyAddedDependency", CodeDependencyType.EXPLICIT)))
assertThat(dependencies.get(sp2), empty())
assertThat(dependencies.get(sp3), containsInAnyOrder(CodeDependency("sp2", CodeDependencyType.DISCOVERED), CodeDependency("sp1", CodeDependencyType.DISCOVERED)))
assertThat(dependencies.get(spA), containsInAnyOrder(CodeDependency("sp3", CodeDependencyType.DISCOVERED)))
}
@Test
fun testCalculateDependenciesAcrossSchemas() {
val sp1 = newObject(SCHEMA1, "sp1", "sp1 sp2", Sets.immutable.empty(), Sets.immutable.with("manuallyAddedDependency"))
val sp2 = newObject(SCHEMA2, "sp2", "sp2")
val sp3 = newObject(SCHEMA1, "sp3", "sp3 sp1 sp2")
val spA = newObject(SCHEMA2, "spA", "spA sp1 sp2 sp3", Sets.immutable.with("sp1", "sp2"), Sets.immutable.empty())
val dependencies = enricher.calculateDependencies(Lists.mutable.with(sp1, sp2, sp3, spA))
assertThat(dependencies.get(sp1), containsInAnyOrder(CodeDependency("sp2", CodeDependencyType.DISCOVERED), CodeDependency("manuallyAddedDependency", CodeDependencyType.EXPLICIT)))
assertThat(dependencies.get(sp2), empty())
assertThat(dependencies.get(sp3), containsInAnyOrder(CodeDependency("sp2", CodeDependencyType.DISCOVERED), CodeDependency("sp1", CodeDependencyType.DISCOVERED)))
assertThat(dependencies.get(spA), containsInAnyOrder(CodeDependency("sp3", CodeDependencyType.DISCOVERED)))
}
@Test
fun testCalculateDependenciesForChange() {
val dependencies = enricher.calculateDependencies("test1", "create procedure sp1\n" +
"// Comment sp2\n" +
"-- Comment sp2\n" +
"call sp_3(1234) -- end of line comment sp5\n" +
"/* Comment sp5 */\n" +
"/* Comment\n" +
"sp5\n" +
"\n" +
"sp5 */\n" +
"call sp4(1234)\n" +
"end\n" +
"", Sets.mutable.with("sp1", "sp2", "sp_3", "sp4", "sp5"))
assertEquals(Sets.mutable.with("sp1", "sp_3", "sp4"), dependencies)
}
private fun newObject(objectName: String, content: String): TextDependencyExtractable {
return newObject(SCHEMA1, objectName, content)
}
private fun newObject(objectName: String, content: String, excludeDependencies: ImmutableSet<String>, includeDependencies: ImmutableSet<String>): TextDependencyExtractable {
return newObject(SCHEMA1, objectName, content, excludeDependencies, includeDependencies)
}
private fun newObject(schema: String, objectName: String, content: String, excludeDependencies: ImmutableSet<String>? = null, includeDependencies: ImmutableSet<String>? = null): TextDependencyExtractable {
val item = mock(TextDependencyExtractable::class.java)
`when`(item.objectName).thenReturn(objectName)
`when`(item.contentForDependencyCalculation).thenReturn(content)
`when`(item.excludeDependencies).thenReturn(excludeDependencies ?: Sets.immutable.with())
`when`(item.includeDependencies).thenReturn(includeDependencies ?: Sets.immutable.with())
`when`(item.toString()).thenReturn(objectName)
return item
}
companion object {
private val SCHEMA1 = "schema1"
private val SCHEMA2 = "schema2"
}
}
| apache-2.0 |
danrien/projectBlue | projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/file/exoplayer/GivenAPlayingFile/WhenANormalProtocolExceptionOccurs.kt | 2 | 2426 | package com.lasthopesoftware.bluewater.client.playback.file.exoplayer.GivenAPlayingFile
import com.google.android.exoplayer2.ExoPlaybackException
import com.google.android.exoplayer2.PlaybackException
import com.google.android.exoplayer2.Player
import com.lasthopesoftware.bluewater.client.playback.exoplayer.PromisingExoPlayer
import com.lasthopesoftware.bluewater.client.playback.file.exoplayer.ExoPlayerPlaybackHandler
import com.lasthopesoftware.bluewater.client.playback.file.exoplayer.error.ExoPlayerException
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.AssertionsForClassTypes
import org.junit.BeforeClass
import org.junit.Test
import java.net.ProtocolException
import java.util.*
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeUnit
class WhenANormalProtocolExceptionOccurs {
companion object {
private var exoPlayerException: ExoPlayerException? = null
private val eventListener: MutableList<Player.Listener> = ArrayList()
@JvmStatic
@BeforeClass
fun context() {
val mockExoPlayer = mockk<PromisingExoPlayer>(relaxed = true)
every { mockExoPlayer.setPlayWhenReady(any()) } returns mockExoPlayer.toPromise()
every { mockExoPlayer.getPlayWhenReady() } returns true.toPromise()
every { mockExoPlayer.getCurrentPosition() } returns 50L.toPromise()
every { mockExoPlayer.getDuration() } returns 100L.toPromise()
every { mockExoPlayer.addListener(any()) } answers {
eventListener.add(firstArg())
mockExoPlayer.toPromise()
}
val exoPlayerPlaybackHandlerPlayerPlaybackHandler = ExoPlayerPlaybackHandler(mockExoPlayer)
val futurePlayedFile = exoPlayerPlaybackHandlerPlayerPlaybackHandler.promisePlayback()
.eventually { obj -> obj.promisePlayedFile() }
.toFuture()
eventListener.forEach { e ->
e.onPlayerError(ExoPlaybackException.createForSource(
ProtocolException(),
PlaybackException.ERROR_CODE_IO_UNSPECIFIED))
}
try {
futurePlayedFile[1, TimeUnit.SECONDS]
} catch (e: ExecutionException) {
exoPlayerException = e.cause as? ExoPlayerException
}
}
}
@Test
fun thenThePlaybackErrorIsCorrect() {
AssertionsForClassTypes.assertThat(exoPlayerException!!.cause).isInstanceOf(ExoPlaybackException::class.java)
}
}
| lgpl-3.0 |
android/app-bundle-samples | PlayCoreKtx/app/src/main/java/com/google/android/samples/dynamicfeatures/ui/MainFragment.kt | 1 | 13747 | /*
* 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 com.google.android.samples.dynamicfeatures.ui
import android.content.Context
import android.graphics.drawable.AnimatedVectorDrawable
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.annotation.Keep
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import com.google.android.material.snackbar.Snackbar
import com.google.android.play.core.appupdate.AppUpdateManager
import com.google.android.play.core.appupdate.AppUpdateManagerFactory
import com.google.android.play.core.install.model.AppUpdateType
import com.google.android.play.core.ktx.AppUpdateResult
import com.google.android.play.core.ktx.AppUpdateResult.Available
import com.google.android.play.core.ktx.AppUpdateResult.Downloaded
import com.google.android.play.core.ktx.AppUpdateResult.InProgress
import com.google.android.play.core.ktx.AppUpdateResult.NotAvailable
import com.google.android.play.core.ktx.bytesDownloaded
import com.google.android.play.core.ktx.launchReview
import com.google.android.play.core.ktx.startConfirmationDialogForResult
import com.google.android.play.core.ktx.startUpdateFlowForResult
import com.google.android.play.core.ktx.totalBytesToDownload
import com.google.android.play.core.review.ReviewManager
import com.google.android.play.core.review.ReviewManagerFactory
import com.google.android.play.core.splitcompat.SplitCompat
import com.google.android.play.core.splitinstall.SplitInstallManager
import com.google.android.play.core.splitinstall.SplitInstallManagerFactory
import com.google.android.samples.dynamicfeatures.R
import com.google.android.samples.dynamicfeatures.databinding.FragmentMainBinding
import com.google.android.samples.dynamicfeatures.state.ColorViewModel
import com.google.android.samples.dynamicfeatures.state.Event
import com.google.android.samples.dynamicfeatures.state.InstallViewModel
import com.google.android.samples.dynamicfeatures.state.InstallViewModelProviderFactory
import com.google.android.samples.dynamicfeatures.state.ModuleStatus
import com.google.android.samples.dynamicfeatures.state.ReviewViewModel
import com.google.android.samples.dynamicfeatures.state.ReviewViewModelProviderFactory
import com.google.android.samples.dynamicfeatures.state.UpdateViewModel
import com.google.android.samples.dynamicfeatures.state.UpdateViewModelProviderFactory
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
@OptIn(ExperimentalCoroutinesApi::class)
@Keep
class MainFragment : Fragment(R.layout.fragment_main) {
private var bindings: FragmentMainBinding? = null
private lateinit var splitInstallManager: SplitInstallManager
private val installViewModel by viewModels<InstallViewModel> {
InstallViewModelProviderFactory(splitInstallManager)
}
private var startModuleWhenReady: Boolean = false
private lateinit var appUpdateManager: AppUpdateManager
private val updateViewModel by viewModels<UpdateViewModel> {
UpdateViewModelProviderFactory(appUpdateManager)
}
private lateinit var reviewManager: ReviewManager
private val reviewViewModel by activityViewModels<ReviewViewModel> {
ReviewViewModelProviderFactory(reviewManager)
}
private val colorViewModel by activityViewModels<ColorViewModel>()
private lateinit var snackbar: Snackbar
override fun onAttach(context: Context) {
super.onAttach(context)
splitInstallManager = SplitInstallManagerFactory.create(context)
appUpdateManager = AppUpdateManagerFactory.create(context)
reviewManager = ReviewManagerFactory.create(context)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
bindings = FragmentMainBinding.bind(view).apply {
btnInvokePalette.setOnClickListener {
startModuleWhenReady = true
installViewModel.invokePictureSelection()
}
btnToggleLight.setOnClickListener {
startModuleWhenReady = false
colorViewModel.lightsOn.value = !colorViewModel.lightsOn.value
}
val colorBackgroundOff = ContextCompat.getColor(requireContext(), R.color.background)
val drawable = btnToggleLight.drawable as AnimatedVectorDrawable
viewLifecycleOwner.lifecycleScope.launchWhenResumed {
colorViewModel.lightsOn
.onEach { lightsOn: Boolean ->
if (lightsOn) {
// The user has turned on the flashlight.
drawable.start()
view.setBackgroundColor(colorViewModel.backgroundColor.value)
} else {
// The user has turned off the flashlight. Reset the icon and color:
drawable.reset()
view.setBackgroundColor(colorBackgroundOff)
}
}
.drop(1) // for launching the review ignore the starting value
.collect { lightsOn ->
// Check if the color was picked from a photo,
// and launch a review if yes:
if (!lightsOn && colorViewModel.colorWasPicked) {
colorViewModel.notifyPickedColorConsumed()
val reviewInfo = reviewViewModel.obtainReviewInfo()
if (reviewInfo != null) {
reviewManager.launchReview(requireActivity(), reviewInfo)
reviewViewModel.notifyAskedForReview()
}
}
}
}
}
snackbar = Snackbar.make(view, R.string.update_available, Snackbar.LENGTH_INDEFINITE)
addInstallViewModelObservers()
addUpdateViewModelObservers()
}
private fun addInstallViewModelObservers() {
with(installViewModel) {
events.onEach { event ->
when (event) {
is Event.ToastEvent -> toastAndLog(event.message)
is Event.NavigationEvent -> {
navigateToFragment(event.fragmentClass)
}
is Event.InstallConfirmationEvent -> splitInstallManager.startConfirmationDialogForResult(
event.status,
this@MainFragment,
INSTALL_CONFIRMATION_REQ_CODE
)
else -> throw IllegalStateException("Event type not handled: $event")
}
}.launchIn(viewLifecycleOwner.lifecycleScope)
pictureModuleStatus.observe(viewLifecycleOwner, Observer { status ->
bindings?.let {
updateModuleButton(status)
}
})
}
}
private fun navigateToFragment(fragmentClass: String) {
val fragment = parentFragmentManager.fragmentFactory.instantiate(
ClassLoader.getSystemClassLoader(),
fragmentClass)
parentFragmentManager.beginTransaction()
.replace(R.id.mycontainer, fragment)
.addToBackStack(null)
.commit()
}
private fun addUpdateViewModelObservers() {
with(updateViewModel) {
updateStatus.observe(
viewLifecycleOwner,
{ updateResult: AppUpdateResult ->
updateUpdateButton(updateResult)
// If it's an immediate update, launch it immediately and finish Activity
// to prevent the user from using the app until they update.
if (updateResult is Available) {
if (shouldLaunchImmediateUpdate(updateResult.updateInfo)) {
if (appUpdateManager.startUpdateFlowForResult(
updateResult.updateInfo,
AppUpdateType.IMMEDIATE,
this@MainFragment,
UPDATE_CONFIRMATION_REQ_CODE
)) {
// only exit if update flow really started
requireActivity().finish()
}
}
}
}
)
events.onEach { event ->
when (event) {
is Event.ToastEvent -> toastAndLog(event.message)
is Event.StartUpdateEvent -> {
val updateType = if (event.immediate) AppUpdateType.IMMEDIATE else AppUpdateType.FLEXIBLE
appUpdateManager.startUpdateFlowForResult(
event.updateInfo,
updateType,
this@MainFragment,
UPDATE_CONFIRMATION_REQ_CODE
)
}
else -> throw IllegalStateException("Event type not handled: $event")
}
}.launchIn(viewLifecycleOwner.lifecycleScope)
}
}
private fun updateModuleButton(status: ModuleStatus) {
bindings?.btnInvokePalette?.apply {
isEnabled = status !is ModuleStatus.Unavailable
when (status) {
ModuleStatus.Available -> {
text = getString(R.string.install)
shrink()
}
is ModuleStatus.Installing -> {
text = getString(
R.string.installing,
(status.progress * 100).toInt()
)
extend()
}
ModuleStatus.Unavailable -> {
text = getString(R.string.feature_not_available)
shrink()
}
ModuleStatus.Installed -> {
SplitCompat.installActivity(requireActivity())
shrink()
if (startModuleWhenReady) {
startModuleWhenReady = false
installViewModel.invokePictureSelection()
}
}
is ModuleStatus.NeedsConfirmation -> {
splitInstallManager.startConfirmationDialogForResult(
status.state,
this@MainFragment,
UPDATE_CONFIRMATION_REQ_CODE
)
}
}
}
}
private fun updateUpdateButton(updateResult: AppUpdateResult) {
when (updateResult) {
NotAvailable -> {
Log.d(TAG, "No update available")
snackbar.dismiss()
}
is Available -> with(snackbar) {
setText(R.string.update_available_snackbar)
setAction(R.string.update_now) {
updateViewModel.invokeUpdate()
}
show()
}
is InProgress -> {
with(snackbar) {
val updateProgress: Int = if (updateResult.installState.totalBytesToDownload == 0L) {
0
} else {
(updateResult.installState.bytesDownloaded * 100 /
updateResult.installState.totalBytesToDownload).toInt()
}
setText(context.getString(R.string.downloading_update, updateProgress))
setAction(null) {}
show()
}
}
is Downloaded -> {
with(snackbar) {
setText(R.string.update_downloaded)
setAction(R.string.complete_update) {
updateViewModel.invokeUpdate()
}
show()
}
}
}
}
override fun onDestroyView() {
bindings = null
super.onDestroyView()
}
}
fun MainFragment.toastAndLog(text: String) {
Toast.makeText(requireContext(), text, Toast.LENGTH_LONG).show()
Log.d(TAG, text)
}
private const val TAG = "DynamicFeatures"
const val INSTALL_CONFIRMATION_REQ_CODE = 1
const val UPDATE_CONFIRMATION_REQ_CODE = 2
| apache-2.0 |
edsilfer/presence-control | app/src/main/java/br/com/edsilfer/android/presence_control/main/presentation/view/IMainView.kt | 1 | 354 | package br.com.edsilfer.android.presence_control.main.presentation.view
import br.com.edsilfer.android.presence_control.core.presentation.BaseView
import br.com.edsilfer.android.presence_control.user.domain.entity.User
/**
* Created by ferna on 5/14/2017.
*/
interface IMainView : BaseView {
fun updateDrawerMenu(user: User)
fun finish()
} | apache-2.0 |
cypressious/learning-spaces | app/src/main/java/de/maxvogler/learningspaces/services/BusProvider.kt | 1 | 185 | package de.maxvogler.learningspaces.services
import com.squareup.otto.Bus
import com.squareup.otto.ThreadEnforcer
public object BusProvider {
public var instance: Bus = Bus()
} | gpl-2.0 |
looker-open-source/sdk-codegen | kotlin/src/main/com/looker/sdk/4.0/streams.kt | 1 | 384725 | /**
MIT License
Copyright (c) 2021 Looker Data Sciences, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* 459 API methods
*/
// NOTE: Do not edit this file generated by Looker SDK Codegen for API 4.0
package com.looker.sdk
import com.looker.rtl.*
import java.util.*
class LookerSDKStream(authSession: AuthSession) : APIMethods(authSession) {
//region Alert: Alert
/**
* Follow an alert.
*
* @param {String} alert_id ID of an alert
*
* POST /alerts/{alert_id}/follow -> ByteArray
*/
fun follow_alert(
alert_id: String
) : SDKResponse {
val path_alert_id = encodeParam(alert_id)
return this.post<ByteArray>("/alerts/${path_alert_id}/follow", mapOf())
}
/**
* Unfollow an alert.
*
* @param {String} alert_id ID of an alert
*
* DELETE /alerts/{alert_id}/follow -> ByteArray
*/
fun unfollow_alert(
alert_id: String
) : SDKResponse {
val path_alert_id = encodeParam(alert_id)
return this.delete<ByteArray>("/alerts/${path_alert_id}/follow", mapOf())
}
/**
* ### Search Alerts
*
* @param {Long} limit (Optional) Number of results to return (used with `offset`).
* @param {Long} offset (Optional) Number of results to skip before returning any (used with `limit`).
* @param {String} group_by (Optional) Dimension by which to order the results(`dashboard` | `owner`)
* @param {String} fields (Optional) Requested fields.
* @param {Boolean} disabled (Optional) Filter on returning only enabled or disabled alerts.
* @param {String} frequency (Optional) Filter on alert frequency, such as: monthly, weekly, daily, hourly, minutes
* @param {Boolean} condition_met (Optional) Filter on whether the alert has met its condition when it last executed
* @param {String} last_run_start (Optional) Filter on the start range of the last time the alerts were run. Example: 2021-01-01T01:01:01-08:00.
* @param {String} last_run_end (Optional) Filter on the start range of the last time the alerts were run. Example: 2021-01-01T01:01:01-08:00.
* @param {Boolean} all_owners (Admin only) (Optional) Filter for all owners.
*
* GET /alerts/search -> ByteArray
*/
@JvmOverloads fun search_alerts(
limit: Long? = null,
offset: Long? = null,
group_by: String? = null,
fields: String? = null,
disabled: Boolean? = null,
frequency: String? = null,
condition_met: Boolean? = null,
last_run_start: String? = null,
last_run_end: String? = null,
all_owners: Boolean? = null
) : SDKResponse {
return this.get<ByteArray>("/alerts/search",
mapOf("limit" to limit,
"offset" to offset,
"group_by" to group_by,
"fields" to fields,
"disabled" to disabled,
"frequency" to frequency,
"condition_met" to condition_met,
"last_run_start" to last_run_start,
"last_run_end" to last_run_end,
"all_owners" to all_owners))
}
/**
* ### Get an alert by a given alert ID
*
* @param {String} alert_id ID of an alert
*
* GET /alerts/{alert_id} -> ByteArray
*/
fun get_alert(
alert_id: String
) : SDKResponse {
val path_alert_id = encodeParam(alert_id)
return this.get<ByteArray>("/alerts/${path_alert_id}", mapOf())
}
/**
* ### Update an alert
* # Required fields: `owner_id`, `field`, `destinations`, `comparison_type`, `threshold`, `cron`
* #
*
* @param {String} alert_id ID of an alert
* @param {WriteAlert} body
*
* PUT /alerts/{alert_id} -> ByteArray
*/
fun update_alert(
alert_id: String,
body: WriteAlert
) : SDKResponse {
val path_alert_id = encodeParam(alert_id)
return this.put<ByteArray>("/alerts/${path_alert_id}", mapOf(), body)
}
/**
* ### Update select alert fields
* # Available fields: `owner_id`, `is_disabled`, `disabled_reason`, `is_public`, `threshold`
* #
*
* @param {String} alert_id ID of an alert
* @param {AlertPatch} body
*
* PATCH /alerts/{alert_id} -> ByteArray
*/
fun update_alert_field(
alert_id: String,
body: AlertPatch
) : SDKResponse {
val path_alert_id = encodeParam(alert_id)
return this.patch<ByteArray>("/alerts/${path_alert_id}", mapOf(), body)
}
/**
* ### Delete an alert by a given alert ID
*
* @param {String} alert_id ID of an alert
*
* DELETE /alerts/{alert_id} -> ByteArray
*/
fun delete_alert(
alert_id: String
) : SDKResponse {
val path_alert_id = encodeParam(alert_id)
return this.delete<ByteArray>("/alerts/${path_alert_id}", mapOf())
}
/**
* ### Create a new alert and return details of the newly created object
*
* Required fields: `field`, `destinations`, `comparison_type`, `threshold`, `cron`
*
* Example Request:
* Run alert on dashboard element '103' at 5am every day. Send an email to '[email protected]' if inventory for Los Angeles (using dashboard filter `Warehouse Name`) is lower than 1,000
* ```
* {
* "cron": "0 5 * * *",
* "custom_title": "Alert when LA inventory is low",
* "dashboard_element_id": 103,
* "applied_dashboard_filters": [
* {
* "filter_title": "Warehouse Name",
* "field_name": "distribution_centers.name",
* "filter_value": "Los Angeles CA",
* "filter_description": "is Los Angeles CA"
* }
* ],
* "comparison_type": "LESS_THAN",
* "destinations": [
* {
* "destination_type": "EMAIL",
* "email_address": "[email protected]"
* }
* ],
* "field": {
* "title": "Number on Hand",
* "name": "inventory_items.number_on_hand"
* },
* "is_disabled": false,
* "is_public": true,
* "threshold": 1000
* }
* ```
*
* @param {WriteAlert} body
*
* POST /alerts -> ByteArray
*/
fun create_alert(
body: WriteAlert
) : SDKResponse {
return this.post<ByteArray>("/alerts", mapOf(), body)
}
/**
* ### Enqueue an Alert by ID
*
* @param {String} alert_id ID of an alert
* @param {Boolean} force Whether to enqueue an alert again if its already running.
*
* POST /alerts/{alert_id}/enqueue -> ByteArray
*/
@JvmOverloads fun enqueue_alert(
alert_id: String,
force: Boolean? = null
) : SDKResponse {
val path_alert_id = encodeParam(alert_id)
return this.post<ByteArray>("/alerts/${path_alert_id}/enqueue",
mapOf("force" to force))
}
/**
* # Alert Notifications.
* The endpoint returns all the alert notifications received by the user on email in the past 7 days. It also returns whether the notifications have been read by the user.
*
* @param {Long} limit (Optional) Number of results to return (used with `offset`).
* @param {Long} offset (Optional) Number of results to skip before returning any (used with `limit`).
*
* GET /alert_notifications -> ByteArray
*/
@JvmOverloads fun alert_notifications(
limit: Long? = null,
offset: Long? = null
) : SDKResponse {
return this.get<ByteArray>("/alert_notifications",
mapOf("limit" to limit,
"offset" to offset))
}
/**
* # Reads a Notification
* The endpoint marks a given alert notification as read by the user, in case it wasn't already read. The AlertNotification model is updated for this purpose. It returns the notification as a response.
*
* @param {String} alert_notification_id ID of a notification
*
* PATCH /alert_notifications/{alert_notification_id} -> ByteArray
*/
fun read_alert_notification(
alert_notification_id: String
) : SDKResponse {
val path_alert_notification_id = encodeParam(alert_notification_id)
return this.patch<ByteArray>("/alert_notifications/${path_alert_notification_id}", mapOf())
}
//endregion Alert: Alert
//region ApiAuth: API Authentication
/**
* ### Present client credentials to obtain an authorization token
*
* Looker API implements the OAuth2 [Resource Owner Password Credentials Grant](https://docs.looker.com/r/api/outh2_resource_owner_pc) pattern.
* The client credentials required for this login must be obtained by creating an API3 key on a user account
* in the Looker Admin console. The API3 key consists of a public `client_id` and a private `client_secret`.
*
* The access token returned by `login` must be used in the HTTP Authorization header of subsequent
* API requests, like this:
* ```
* Authorization: token 4QDkCyCtZzYgj4C2p2cj3csJH7zqS5RzKs2kTnG4
* ```
* Replace "4QDkCy..." with the `access_token` value returned by `login`.
* The word `token` is a string literal and must be included exactly as shown.
*
* This function can accept `client_id` and `client_secret` parameters as URL query params or as www-form-urlencoded params in the body of the HTTP request. Since there is a small risk that URL parameters may be visible to intermediate nodes on the network route (proxies, routers, etc), passing credentials in the body of the request is considered more secure than URL params.
*
* Example of passing credentials in the HTTP request body:
* ````
* POST HTTP /login
* Content-Type: application/x-www-form-urlencoded
*
* client_id=CGc9B7v7J48dQSJvxxx&client_secret=nNVS9cSS3xNpSC9JdsBvvvvv
* ````
*
* ### Best Practice:
* Always pass credentials in body params. Pass credentials in URL query params **only** when you cannot pass body params due to application, tool, or other limitations.
*
* For more information and detailed examples of Looker API authorization, see [How to Authenticate to Looker API3](https://github.com/looker/looker-sdk-ruby/blob/master/authentication.md).
*
* @param {String} client_id client_id part of API3 Key.
* @param {String} client_secret client_secret part of API3 Key.
*
* POST /login -> ByteArray
*/
@JvmOverloads fun login(
client_id: String? = null,
client_secret: String? = null
) : SDKResponse {
return this.post<ByteArray>("/login",
mapOf("client_id" to client_id,
"client_secret" to client_secret))
}
/**
* ### Create an access token that runs as a given user.
*
* This can only be called by an authenticated admin user. It allows that admin to generate a new
* authentication token for the user with the given user id. That token can then be used for subsequent
* API calls - which are then performed *as* that target user.
*
* The target user does *not* need to have a pre-existing API client_id/client_secret pair. And, no such
* credentials are created by this call.
*
* This allows for building systems where api user authentication for an arbitrary number of users is done
* outside of Looker and funneled through a single 'service account' with admin permissions. Note that a
* new access token is generated on each call. If target users are going to be making numerous API
* calls in a short period then it is wise to cache this authentication token rather than call this before
* each of those API calls.
*
* See 'login' for more detail on the access token and how to use it.
*
* @param {String} user_id Id of user.
* @param {Boolean} associative When true (default), API calls using the returned access_token are attributed to the admin user who created the access_token. When false, API activity is attributed to the user the access_token runs as. False requires a looker license.
*
* POST /login/{user_id} -> ByteArray
*/
@JvmOverloads fun login_user(
user_id: String,
associative: Boolean? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.post<ByteArray>("/login/${path_user_id}",
mapOf("associative" to associative))
}
/**
* ### Logout of the API and invalidate the current access token.
*
* DELETE /logout -> ByteArray
*/
fun logout(
) : SDKResponse {
return this.delete<ByteArray>("/logout", mapOf())
}
//endregion ApiAuth: API Authentication
//region Artifact: Artifact Storage
/**
* Get the maximum configured size of the entire artifact store, and the currently used storage in bytes.
*
* **Note**: The artifact storage API can only be used by Looker-built extensions.
*
* @param {String} fields Comma-delimited names of fields to return in responses. Omit for all fields
*
* GET /artifact/usage -> ByteArray
*/
@JvmOverloads fun artifact_usage(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/artifact/usage",
mapOf("fields" to fields))
}
/**
* Get all artifact namespaces and the count of artifacts in each namespace
*
* **Note**: The artifact storage API can only be used by Looker-built extensions.
*
* @param {String} fields Comma-delimited names of fields to return in responses. Omit for all fields
* @param {Long} limit Number of results to return. (used with offset)
* @param {Long} offset Number of results to skip before returning any. (used with limit)
*
* GET /artifact/namespaces -> ByteArray
*/
@JvmOverloads fun artifact_namespaces(
fields: String? = null,
limit: Long? = null,
offset: Long? = null
) : SDKResponse {
return this.get<ByteArray>("/artifact/namespaces",
mapOf("fields" to fields,
"limit" to limit,
"offset" to offset))
}
/**
* ### Return the value of an artifact
*
* The MIME type for the API response is set to the `content_type` of the value
*
* **Note**: The artifact storage API can only be used by Looker-built extensions.
*
* @param {String} namespace Artifact storage namespace
* @param {String} key Artifact storage key. Namespace + Key must be unique
*
* GET /artifact/{namespace}/value -> ByteArray
*/
@JvmOverloads fun artifact_value(
namespace: String,
key: String? = null
) : SDKResponse {
val path_namespace = encodeParam(namespace)
return this.get<ByteArray>("/artifact/${path_namespace}/value",
mapOf("key" to key))
}
/**
* Remove *all* artifacts from a namespace. Purged artifacts are permanently deleted
*
* **Note**: The artifact storage API can only be used by Looker-built extensions.
*
* @param {String} namespace Artifact storage namespace
*
* DELETE /artifact/{namespace}/purge -> ByteArray
*/
fun purge_artifacts(
namespace: String
) : SDKResponse {
val path_namespace = encodeParam(namespace)
return this.delete<ByteArray>("/artifact/${path_namespace}/purge", mapOf())
}
/**
* ### Search all key/value pairs in a namespace for matching criteria.
*
* Returns an array of artifacts matching the specified search criteria.
*
* Key search patterns use case-insensitive matching and can contain `%` and `_` as SQL LIKE pattern match wildcard expressions.
*
* The parameters `min_size` and `max_size` can be used individually or together.
*
* - `min_size` finds artifacts with sizes greater than or equal to its value
* - `max_size` finds artifacts with sizes less than or equal to its value
* - using both parameters restricts the minimum and maximum size range for artifacts
*
* **NOTE**: Artifacts are always returned in alphanumeric order by key.
*
* Get a **single artifact** by namespace and key with [`artifact`](#!/Artifact/artifact)
*
* **Note**: The artifact storage API can only be used by Looker-built extensions.
*
* @param {String} namespace Artifact storage namespace
* @param {String} fields Comma-delimited names of fields to return in responses. Omit for all fields
* @param {String} key Key pattern to match
* @param {String} user_ids Ids of users who created or updated the artifact (comma-delimited list)
* @param {Long} min_size Minimum storage size of the artifact
* @param {Long} max_size Maximum storage size of the artifact
* @param {Long} limit Number of results to return. (used with offset)
* @param {Long} offset Number of results to skip before returning any. (used with limit)
*
* GET /artifact/{namespace}/search -> ByteArray
*/
@JvmOverloads fun search_artifacts(
namespace: String,
fields: String? = null,
key: String? = null,
user_ids: String? = null,
min_size: Long? = null,
max_size: Long? = null,
limit: Long? = null,
offset: Long? = null
) : SDKResponse {
val path_namespace = encodeParam(namespace)
return this.get<ByteArray>("/artifact/${path_namespace}/search",
mapOf("fields" to fields,
"key" to key,
"user_ids" to user_ids,
"min_size" to min_size,
"max_size" to max_size,
"limit" to limit,
"offset" to offset))
}
/**
* ### Get one or more artifacts
*
* Returns an array of artifacts matching the specified key value(s).
*
* **Note**: The artifact storage API can only be used by Looker-built extensions.
*
* @param {String} namespace Artifact storage namespace
* @param {String} key Comma-delimited list of keys. Wildcards not allowed.
* @param {String} fields Comma-delimited names of fields to return in responses. Omit for all fields
* @param {Long} limit Number of results to return. (used with offset)
* @param {Long} offset Number of results to skip before returning any. (used with limit)
*
* GET /artifact/{namespace} -> ByteArray
*/
@JvmOverloads fun artifact(
namespace: String,
key: String,
fields: String? = null,
limit: Long? = null,
offset: Long? = null
) : SDKResponse {
val path_namespace = encodeParam(namespace)
return this.get<ByteArray>("/artifact/${path_namespace}",
mapOf("key" to key,
"fields" to fields,
"limit" to limit,
"offset" to offset))
}
/**
* ### Delete one or more artifacts
*
* To avoid rate limiting on deletion requests, multiple artifacts can be deleted at the same time by using a comma-delimited list of artifact keys.
*
* **Note**: The artifact storage API can only be used by Looker-built extensions.
*
* @param {String} namespace Artifact storage namespace
* @param {String} key Comma-delimited list of keys. Wildcards not allowed.
*
* DELETE /artifact/{namespace} -> ByteArray
*/
fun delete_artifact(
namespace: String,
key: String
) : SDKResponse {
val path_namespace = encodeParam(namespace)
return this.delete<ByteArray>("/artifact/${path_namespace}",
mapOf("key" to key))
}
/**
* ### Create or update one or more artifacts
*
* Only `key` and `value` are required to _create_ an artifact.
* To _update_ an artifact, its current `version` value must be provided.
*
* In the following example `body` payload, `one` and `two` are existing artifacts, and `three` is new:
*
* ```json
* [
* { "key": "one", "value": "[ \"updating\", \"existing\", \"one\" ]", "version": 10, "content_type": "application/json" },
* { "key": "two", "value": "updating existing two", "version": 20 },
* { "key": "three", "value": "creating new three" },
* ]
* ```
*
* Notes for this body:
*
* - The `value` for `key` **one** is a JSON payload, so a `content_type` override is needed. This override must be done **every** time a JSON value is set.
* - The `version` values for **one** and **two** mean they have been saved 10 and 20 times, respectively.
* - If `version` is **not** provided for an existing artifact, the entire request will be refused and a `Bad Request` response will be sent.
* - If `version` is provided for an artifact, it is only used for helping to prevent inadvertent data overwrites. It cannot be used to **set** the version of an artifact. The Looker server controls `version`.
* - We suggest encoding binary values as base64. Because the MIME content type for base64 is detected as plain text, also provide `content_type` to correctly indicate the value's type for retrieval and client-side processing.
*
* Because artifacts are stored encrypted, the same value can be written multiple times (provided the correct `version` number is used). Looker does not examine any values stored in the artifact store, and only decrypts when sending artifacts back in an API response.
*
* **Note**: The artifact storage API can only be used by Looker-built extensions.
*
* @param {String} namespace Artifact storage namespace
* @param {Array<UpdateArtifact>} body
* @param {String} fields Comma-delimited names of fields to return in responses. Omit for all fields
*
* PUT /artifacts/{namespace} -> ByteArray
*/
@JvmOverloads fun update_artifacts(
namespace: String,
body: Array<UpdateArtifact>,
fields: String? = null
) : SDKResponse {
val path_namespace = encodeParam(namespace)
return this.put<ByteArray>("/artifacts/${path_namespace}",
mapOf("fields" to fields), body)
}
//endregion Artifact: Artifact Storage
//region Auth: Manage User Authentication Configuration
/**
* ### Create an embed secret using the specified information.
*
* The value of the `secret` field will be set by Looker and returned.
*
* @param {WriteEmbedSecret} body
*
* POST /embed_config/secrets -> ByteArray
*/
@JvmOverloads fun create_embed_secret(
body: WriteEmbedSecret? = null
) : SDKResponse {
return this.post<ByteArray>("/embed_config/secrets", mapOf(), body)
}
/**
* ### Delete an embed secret.
*
* @param {String} embed_secret_id Id of Embed Secret
*
* DELETE /embed_config/secrets/{embed_secret_id} -> ByteArray
*/
fun delete_embed_secret(
embed_secret_id: String
) : SDKResponse {
val path_embed_secret_id = encodeParam(embed_secret_id)
return this.delete<ByteArray>("/embed_config/secrets/${path_embed_secret_id}", mapOf())
}
/**
* ### Create SSO Embed URL
*
* Creates an SSO embed URL and cryptographically signs it with an embed secret.
* This signed URL can then be used to instantiate a Looker embed session in a PBL web application.
* Do not make any modifications to this URL - any change may invalidate the signature and
* cause the URL to fail to load a Looker embed session.
*
* A signed SSO embed URL can only be used once. After it has been used to request a page from the
* Looker server, the URL is invalid. Future requests using the same URL will fail. This is to prevent
* 'replay attacks'.
*
* The `target_url` property must be a complete URL of a Looker UI page - scheme, hostname, path and query params.
* To load a dashboard with id 56 and with a filter of `Date=1 years`, the looker URL would look like `https:/myname.looker.com/dashboards/56?Date=1%20years`.
* The best way to obtain this target_url is to navigate to the desired Looker page in your web browser,
* copy the URL shown in the browser address bar and paste it into the `target_url` property as a quoted string value in this API request.
*
* Permissions for the embed user are defined by the groups in which the embed user is a member (group_ids property)
* and the lists of models and permissions assigned to the embed user.
* At a minimum, you must provide values for either the group_ids property, or both the models and permissions properties.
* These properties are additive; an embed user can be a member of certain groups AND be granted access to models and permissions.
*
* The embed user's access is the union of permissions granted by the group_ids, models, and permissions properties.
*
* This function does not strictly require all group_ids, user attribute names, or model names to exist at the moment the
* SSO embed url is created. Unknown group_id, user attribute names or model names will be passed through to the output URL.
* To diagnose potential problems with an SSO embed URL, you can copy the signed URL into the Embed URI Validator text box in `<your looker instance>/admin/embed`.
*
* The `secret_id` parameter is optional. If specified, its value must be the id of an active secret defined in the Looker instance.
* if not specified, the URL will be signed using the newest active secret defined in the Looker instance.
*
* #### Security Note
* Protect this signed URL as you would an access token or password credentials - do not write
* it to disk, do not pass it to a third party, and only pass it through a secure HTTPS
* encrypted transport.
*
* @param {EmbedSsoParams} body
*
* POST /embed/sso_url -> ByteArray
*/
fun create_sso_embed_url(
body: EmbedSsoParams
) : SDKResponse {
return this.post<ByteArray>("/embed/sso_url", mapOf(), body)
}
/**
* ### Create an Embed URL
*
* Creates an embed URL that runs as the Looker user making this API call. ("Embed as me")
* This embed URL can then be used to instantiate a Looker embed session in a
* "Powered by Looker" (PBL) web application.
*
* This is similar to Private Embedding (https://docs.looker.com/r/admin/embed/private-embed). Instead of
* of logging into the Web UI to authenticate, the user has already authenticated against the API to be able to
* make this call. However, unlike Private Embed where the user has access to any other part of the Looker UI,
* the embed web session created by requesting the EmbedUrlResponse.url in a browser only has access to
* content visible under the `/embed` context.
*
* An embed URL can only be used once, and must be used within 5 minutes of being created. After it
* has been used to request a page from the Looker server, the URL is invalid. Future requests using
* the same URL will fail. This is to prevent 'replay attacks'.
*
* The `target_url` property must be a complete URL of a Looker Embedded UI page - scheme, hostname, path starting with "/embed" and query params.
* To load a dashboard with id 56 and with a filter of `Date=1 years`, the looker Embed URL would look like `https://myname.looker.com/embed/dashboards/56?Date=1%20years`.
* The best way to obtain this target_url is to navigate to the desired Looker page in your web browser,
* copy the URL shown in the browser address bar, insert "/embed" after the host/port, and paste it into the `target_url` property as a quoted string value in this API request.
*
* #### Security Note
* Protect this embed URL as you would an access token or password credentials - do not write
* it to disk, do not pass it to a third party, and only pass it through a secure HTTPS
* encrypted transport.
*
* @param {EmbedParams} body
*
* POST /embed/token_url/me -> ByteArray
*/
fun create_embed_url_as_me(
body: EmbedParams
) : SDKResponse {
return this.post<ByteArray>("/embed/token_url/me", mapOf(), body)
}
/**
* ### Acquire a cookieless embed session.
*
* The acquire session endpoint negates the need for signing the embed url and passing it as a parameter
* to the embed login. This endpoint accepts an embed user definition and creates it if it does not exist,
* otherwise it reuses it. Note that this endpoint will not update the user, user attributes or group
* attributes if the embed user already exists. This is the same behavior as the embed SSO login.
*
* The endpoint also accepts an optional `session_reference_token`. If present and the session has not expired
* and the credentials match the credentials for the embed session, a new authentication token will be
* generated. This allows the embed session to attach a new embedded IFRAME to the embed session. Note that
* the session will NOT be extended in this scenario, in other words the session_length parameter is ignored.
*
* If the session_reference_token has expired, it will be ignored and a new embed session will be created.
*
* If the credentials do not match the credentials associated with an exisiting session_reference_token, a
* 404 will be returned.
*
* The endpoint returns the following:
* - Authentication token - a token that is passed to `/embed/login` endpoint that creates or attaches to the
* embed session. This token can be used once and has a lifetime of 30 seconds.
* - Session reference token - a token that lives for the length of the session. This token is used to
* generate new api and navigation tokens OR create new embed IFRAMEs.
* - Api token - lives for 10 minutes. The Looker client will ask for this token once it is loaded into the
* iframe.
* - Navigation token - lives for 10 minutes. The Looker client will ask for this token once it is loaded into
* the iframe.
*
* @param {EmbedCookielessSessionAcquire} body
*
* POST /embed/cookieless_session/acquire -> ByteArray
*/
fun acquire_embed_cookieless_session(
body: EmbedCookielessSessionAcquire
) : SDKResponse {
return this.post<ByteArray>("/embed/cookieless_session/acquire", mapOf(), body)
}
/**
* ### Delete cookieless embed session
*
* This will delete the session associated with the given session reference token. Calling this endpoint will result
* in the session and session reference data being cleared from the system. This endpoint can be used to log an embed
* user out of the Looker instance.
*
* @param {String} session_reference_token Embed session reference token
*
* DELETE /embed/cookieless_session/{session_reference_token} -> ByteArray
*/
fun delete_embed_cookieless_session(
session_reference_token: String
) : SDKResponse {
val path_session_reference_token = encodeParam(session_reference_token)
return this.delete<ByteArray>("/embed/cookieless_session/${path_session_reference_token}", mapOf())
}
/**
* ### Generate api and navigation tokens for a cookieless embed session
*
* The generate tokens endpoint is used to create new tokens of type:
* - Api token.
* - Navigation token.
* The generate tokens endpoint should be called every time the Looker client asks for a token (except for the
* first time when the tokens returned by the acquire_session endpoint should be used).
*
* @param {EmbedCookielessSessionGenerateTokens} body
*
* PUT /embed/cookieless_session/generate_tokens -> ByteArray
*/
fun generate_tokens_for_cookieless_session(
body: EmbedCookielessSessionGenerateTokens
) : SDKResponse {
return this.put<ByteArray>("/embed/cookieless_session/generate_tokens", mapOf(), body)
}
/**
* ### Get the LDAP configuration.
*
* Looker can be optionally configured to authenticate users against an Active Directory or other LDAP directory server.
* LDAP setup requires coordination with an administrator of that directory server.
*
* Only Looker administrators can read and update the LDAP configuration.
*
* Configuring LDAP impacts authentication for all users. This configuration should be done carefully.
*
* Looker maintains a single LDAP configuration. It can be read and updated. Updates only succeed if the new state will be valid (in the sense that all required fields are populated); it is up to you to ensure that the configuration is appropriate and correct).
*
* LDAP is enabled or disabled for Looker using the **enabled** field.
*
* Looker will never return an **auth_password** field. That value can be set, but never retrieved.
*
* See the [Looker LDAP docs](https://docs.looker.com/r/api/ldap_setup) for additional information.
*
* GET /ldap_config -> ByteArray
*/
fun ldap_config(
) : SDKResponse {
return this.get<ByteArray>("/ldap_config", mapOf())
}
/**
* ### Update the LDAP configuration.
*
* Configuring LDAP impacts authentication for all users. This configuration should be done carefully.
*
* Only Looker administrators can read and update the LDAP configuration.
*
* LDAP is enabled or disabled for Looker using the **enabled** field.
*
* It is **highly** recommended that any LDAP setting changes be tested using the APIs below before being set globally.
*
* See the [Looker LDAP docs](https://docs.looker.com/r/api/ldap_setup) for additional information.
*
* @param {WriteLDAPConfig} body
*
* PATCH /ldap_config -> ByteArray
*/
fun update_ldap_config(
body: WriteLDAPConfig
) : SDKResponse {
return this.patch<ByteArray>("/ldap_config", mapOf(), body)
}
/**
* ### Test the connection settings for an LDAP configuration.
*
* This tests that the connection is possible given a connection_host and connection_port.
*
* **connection_host** and **connection_port** are required. **connection_tls** is optional.
*
* Example:
* ```json
* {
* "connection_host": "ldap.example.com",
* "connection_port": "636",
* "connection_tls": true
* }
* ```
*
* No authentication to the LDAP server is attempted.
*
* The active LDAP settings are not modified.
*
* @param {WriteLDAPConfig} body
*
* PUT /ldap_config/test_connection -> ByteArray
*/
fun test_ldap_config_connection(
body: WriteLDAPConfig
) : SDKResponse {
return this.put<ByteArray>("/ldap_config/test_connection", mapOf(), body)
}
/**
* ### Test the connection authentication settings for an LDAP configuration.
*
* This tests that the connection is possible and that a 'server' account to be used by Looker can authenticate to the LDAP server given connection and authentication information.
*
* **connection_host**, **connection_port**, and **auth_username**, are required. **connection_tls** and **auth_password** are optional.
*
* Example:
* ```json
* {
* "connection_host": "ldap.example.com",
* "connection_port": "636",
* "connection_tls": true,
* "auth_username": "cn=looker,dc=example,dc=com",
* "auth_password": "secret"
* }
* ```
*
* Looker will never return an **auth_password**. If this request omits the **auth_password** field, then the **auth_password** value from the active config (if present) will be used for the test.
*
* The active LDAP settings are not modified.
*
* @param {WriteLDAPConfig} body
*
* PUT /ldap_config/test_auth -> ByteArray
*/
fun test_ldap_config_auth(
body: WriteLDAPConfig
) : SDKResponse {
return this.put<ByteArray>("/ldap_config/test_auth", mapOf(), body)
}
/**
* ### Test the user authentication settings for an LDAP configuration without authenticating the user.
*
* This test will let you easily test the mapping for user properties and roles for any user without needing to authenticate as that user.
*
* This test accepts a full LDAP configuration along with a username and attempts to find the full info for the user from the LDAP server without actually authenticating the user. So, user password is not required.The configuration is validated before attempting to contact the server.
*
* **test_ldap_user** is required.
*
* The active LDAP settings are not modified.
*
* @param {WriteLDAPConfig} body
*
* PUT /ldap_config/test_user_info -> ByteArray
*/
fun test_ldap_config_user_info(
body: WriteLDAPConfig
) : SDKResponse {
return this.put<ByteArray>("/ldap_config/test_user_info", mapOf(), body)
}
/**
* ### Test the user authentication settings for an LDAP configuration.
*
* This test accepts a full LDAP configuration along with a username/password pair and attempts to authenticate the user with the LDAP server. The configuration is validated before attempting the authentication.
*
* Looker will never return an **auth_password**. If this request omits the **auth_password** field, then the **auth_password** value from the active config (if present) will be used for the test.
*
* **test_ldap_user** and **test_ldap_password** are required.
*
* The active LDAP settings are not modified.
*
* @param {WriteLDAPConfig} body
*
* PUT /ldap_config/test_user_auth -> ByteArray
*/
fun test_ldap_config_user_auth(
body: WriteLDAPConfig
) : SDKResponse {
return this.put<ByteArray>("/ldap_config/test_user_auth", mapOf(), body)
}
/**
* ### Registers a mobile device.
* # Required fields: [:device_token, :device_type]
*
* @param {WriteMobileToken} body
*
* POST /mobile/device -> ByteArray
*/
fun register_mobile_device(
body: WriteMobileToken
) : SDKResponse {
return this.post<ByteArray>("/mobile/device", mapOf(), body)
}
/**
* ### Updates the mobile device registration
*
* @param {String} device_id Unique id of the device.
*
* PATCH /mobile/device/{device_id} -> ByteArray
*/
fun update_mobile_device_registration(
device_id: String
) : SDKResponse {
val path_device_id = encodeParam(device_id)
return this.patch<ByteArray>("/mobile/device/${path_device_id}", mapOf())
}
/**
* ### Deregister a mobile device.
*
* @param {String} device_id Unique id of the device.
*
* DELETE /mobile/device/{device_id} -> ByteArray
*/
fun deregister_mobile_device(
device_id: String
) : SDKResponse {
val path_device_id = encodeParam(device_id)
return this.delete<ByteArray>("/mobile/device/${path_device_id}", mapOf())
}
/**
* ### List All OAuth Client Apps
*
* Lists all applications registered to use OAuth2 login with this Looker instance, including
* enabled and disabled apps.
*
* Results are filtered to include only the apps that the caller (current user)
* has permission to see.
*
* @param {String} fields Requested fields.
*
* GET /oauth_client_apps -> ByteArray
*/
@JvmOverloads fun all_oauth_client_apps(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/oauth_client_apps",
mapOf("fields" to fields))
}
/**
* ### Get Oauth Client App
*
* Returns the registered app client with matching client_guid.
*
* @param {String} client_guid The unique id of this application
* @param {String} fields Requested fields.
*
* GET /oauth_client_apps/{client_guid} -> ByteArray
*/
@JvmOverloads fun oauth_client_app(
client_guid: String,
fields: String? = null
) : SDKResponse {
val path_client_guid = encodeParam(client_guid)
return this.get<ByteArray>("/oauth_client_apps/${path_client_guid}",
mapOf("fields" to fields))
}
/**
* ### Register an OAuth2 Client App
*
* Registers details identifying an external web app or native app as an OAuth2 login client of the Looker instance.
* The app registration must provide a unique client_guid and redirect_uri that the app will present
* in OAuth login requests. If the client_guid and redirect_uri parameters in the login request do not match
* the app details registered with the Looker instance, the request is assumed to be a forgery and is rejected.
*
* @param {String} client_guid The unique id of this application
* @param {WriteOauthClientApp} body
* @param {String} fields Requested fields.
*
* POST /oauth_client_apps/{client_guid} -> ByteArray
*/
@JvmOverloads fun register_oauth_client_app(
client_guid: String,
body: WriteOauthClientApp,
fields: String? = null
) : SDKResponse {
val path_client_guid = encodeParam(client_guid)
return this.post<ByteArray>("/oauth_client_apps/${path_client_guid}",
mapOf("fields" to fields), body)
}
/**
* ### Update OAuth2 Client App Details
*
* Modifies the details a previously registered OAuth2 login client app.
*
* @param {String} client_guid The unique id of this application
* @param {WriteOauthClientApp} body
* @param {String} fields Requested fields.
*
* PATCH /oauth_client_apps/{client_guid} -> ByteArray
*/
@JvmOverloads fun update_oauth_client_app(
client_guid: String,
body: WriteOauthClientApp,
fields: String? = null
) : SDKResponse {
val path_client_guid = encodeParam(client_guid)
return this.patch<ByteArray>("/oauth_client_apps/${path_client_guid}",
mapOf("fields" to fields), body)
}
/**
* ### Delete OAuth Client App
*
* Deletes the registration info of the app with the matching client_guid.
* All active sessions and tokens issued for this app will immediately become invalid.
*
* As with most REST DELETE operations, this endpoint does not return an error if the
* indicated resource does not exist.
*
* ### Note: this deletion cannot be undone.
*
* @param {String} client_guid The unique id of this application
*
* DELETE /oauth_client_apps/{client_guid} -> ByteArray
*/
fun delete_oauth_client_app(
client_guid: String
) : SDKResponse {
val path_client_guid = encodeParam(client_guid)
return this.delete<ByteArray>("/oauth_client_apps/${path_client_guid}", mapOf())
}
/**
* ### Invalidate All Issued Tokens
*
* Immediately invalidates all auth codes, sessions, access tokens and refresh tokens issued for
* this app for ALL USERS of this app.
*
* @param {String} client_guid The unique id of the application
*
* DELETE /oauth_client_apps/{client_guid}/tokens -> ByteArray
*/
fun invalidate_tokens(
client_guid: String
) : SDKResponse {
val path_client_guid = encodeParam(client_guid)
return this.delete<ByteArray>("/oauth_client_apps/${path_client_guid}/tokens", mapOf())
}
/**
* ### Activate an app for a user
*
* Activates a user for a given oauth client app. This indicates the user has been informed that
* the app will have access to the user's looker data, and that the user has accepted and allowed
* the app to use their Looker account.
*
* Activating a user for an app that the user is already activated with returns a success response.
*
* @param {String} client_guid The unique id of this application
* @param {String} user_id The id of the user to enable use of this app
* @param {String} fields Requested fields.
*
* POST /oauth_client_apps/{client_guid}/users/{user_id} -> ByteArray
*/
@JvmOverloads fun activate_app_user(
client_guid: String,
user_id: String,
fields: String? = null
) : SDKResponse {
val path_client_guid = encodeParam(client_guid)
val path_user_id = encodeParam(user_id)
return this.post<ByteArray>("/oauth_client_apps/${path_client_guid}/users/${path_user_id}",
mapOf("fields" to fields))
}
/**
* ### Deactivate an app for a user
*
* Deactivate a user for a given oauth client app. All tokens issued to the app for
* this user will be invalid immediately. Before the user can use the app with their
* Looker account, the user will have to read and accept an account use disclosure statement for the app.
*
* Admin users can deactivate other users, but non-admin users can only deactivate themselves.
*
* As with most REST DELETE operations, this endpoint does not return an error if the indicated
* resource (app or user) does not exist or has already been deactivated.
*
* @param {String} client_guid The unique id of this application
* @param {String} user_id The id of the user to enable use of this app
* @param {String} fields Requested fields.
*
* DELETE /oauth_client_apps/{client_guid}/users/{user_id} -> ByteArray
*/
@JvmOverloads fun deactivate_app_user(
client_guid: String,
user_id: String,
fields: String? = null
) : SDKResponse {
val path_client_guid = encodeParam(client_guid)
val path_user_id = encodeParam(user_id)
return this.delete<ByteArray>("/oauth_client_apps/${path_client_guid}/users/${path_user_id}",
mapOf("fields" to fields))
}
/**
* ### Get the OIDC configuration.
*
* Looker can be optionally configured to authenticate users against an OpenID Connect (OIDC)
* authentication server. OIDC setup requires coordination with an administrator of that server.
*
* Only Looker administrators can read and update the OIDC configuration.
*
* Configuring OIDC impacts authentication for all users. This configuration should be done carefully.
*
* Looker maintains a single OIDC configuation. It can be read and updated. Updates only succeed if the new state will be valid (in the sense that all required fields are populated); it is up to you to ensure that the configuration is appropriate and correct).
*
* OIDC is enabled or disabled for Looker using the **enabled** field.
*
* GET /oidc_config -> ByteArray
*/
fun oidc_config(
) : SDKResponse {
return this.get<ByteArray>("/oidc_config", mapOf())
}
/**
* ### Update the OIDC configuration.
*
* Configuring OIDC impacts authentication for all users. This configuration should be done carefully.
*
* Only Looker administrators can read and update the OIDC configuration.
*
* OIDC is enabled or disabled for Looker using the **enabled** field.
*
* It is **highly** recommended that any OIDC setting changes be tested using the APIs below before being set globally.
*
* @param {WriteOIDCConfig} body
*
* PATCH /oidc_config -> ByteArray
*/
fun update_oidc_config(
body: WriteOIDCConfig
) : SDKResponse {
return this.patch<ByteArray>("/oidc_config", mapOf(), body)
}
/**
* ### Get a OIDC test configuration by test_slug.
*
* @param {String} test_slug Slug of test config
*
* GET /oidc_test_configs/{test_slug} -> ByteArray
*/
fun oidc_test_config(
test_slug: String
) : SDKResponse {
val path_test_slug = encodeParam(test_slug)
return this.get<ByteArray>("/oidc_test_configs/${path_test_slug}", mapOf())
}
/**
* ### Delete a OIDC test configuration.
*
* @param {String} test_slug Slug of test config
*
* DELETE /oidc_test_configs/{test_slug} -> ByteArray
*/
fun delete_oidc_test_config(
test_slug: String
) : SDKResponse {
val path_test_slug = encodeParam(test_slug)
return this.delete<ByteArray>("/oidc_test_configs/${path_test_slug}", mapOf())
}
/**
* ### Create a OIDC test configuration.
*
* @param {WriteOIDCConfig} body
*
* POST /oidc_test_configs -> ByteArray
*/
fun create_oidc_test_config(
body: WriteOIDCConfig
) : SDKResponse {
return this.post<ByteArray>("/oidc_test_configs", mapOf(), body)
}
/**
* ### Get password config.
*
* GET /password_config -> ByteArray
*/
fun password_config(
) : SDKResponse {
return this.get<ByteArray>("/password_config", mapOf())
}
/**
* ### Update password config.
*
* @param {WritePasswordConfig} body
*
* PATCH /password_config -> ByteArray
*/
fun update_password_config(
body: WritePasswordConfig
) : SDKResponse {
return this.patch<ByteArray>("/password_config", mapOf(), body)
}
/**
* ### Force all credentials_email users to reset their login passwords upon their next login.
*
* PUT /password_config/force_password_reset_at_next_login_for_all_users -> ByteArray
*/
fun force_password_reset_at_next_login_for_all_users(
) : SDKResponse {
return this.put<ByteArray>("/password_config/force_password_reset_at_next_login_for_all_users", mapOf())
}
/**
* ### Get the SAML configuration.
*
* Looker can be optionally configured to authenticate users against a SAML authentication server.
* SAML setup requires coordination with an administrator of that server.
*
* Only Looker administrators can read and update the SAML configuration.
*
* Configuring SAML impacts authentication for all users. This configuration should be done carefully.
*
* Looker maintains a single SAML configuation. It can be read and updated. Updates only succeed if the new state will be valid (in the sense that all required fields are populated); it is up to you to ensure that the configuration is appropriate and correct).
*
* SAML is enabled or disabled for Looker using the **enabled** field.
*
* GET /saml_config -> ByteArray
*/
fun saml_config(
) : SDKResponse {
return this.get<ByteArray>("/saml_config", mapOf())
}
/**
* ### Update the SAML configuration.
*
* Configuring SAML impacts authentication for all users. This configuration should be done carefully.
*
* Only Looker administrators can read and update the SAML configuration.
*
* SAML is enabled or disabled for Looker using the **enabled** field.
*
* It is **highly** recommended that any SAML setting changes be tested using the APIs below before being set globally.
*
* @param {WriteSamlConfig} body
*
* PATCH /saml_config -> ByteArray
*/
fun update_saml_config(
body: WriteSamlConfig
) : SDKResponse {
return this.patch<ByteArray>("/saml_config", mapOf(), body)
}
/**
* ### Get a SAML test configuration by test_slug.
*
* @param {String} test_slug Slug of test config
*
* GET /saml_test_configs/{test_slug} -> ByteArray
*/
fun saml_test_config(
test_slug: String
) : SDKResponse {
val path_test_slug = encodeParam(test_slug)
return this.get<ByteArray>("/saml_test_configs/${path_test_slug}", mapOf())
}
/**
* ### Delete a SAML test configuration.
*
* @param {String} test_slug Slug of test config
*
* DELETE /saml_test_configs/{test_slug} -> ByteArray
*/
fun delete_saml_test_config(
test_slug: String
) : SDKResponse {
val path_test_slug = encodeParam(test_slug)
return this.delete<ByteArray>("/saml_test_configs/${path_test_slug}", mapOf())
}
/**
* ### Create a SAML test configuration.
*
* @param {WriteSamlConfig} body
*
* POST /saml_test_configs -> ByteArray
*/
fun create_saml_test_config(
body: WriteSamlConfig
) : SDKResponse {
return this.post<ByteArray>("/saml_test_configs", mapOf(), body)
}
/**
* ### Parse the given xml as a SAML IdP metadata document and return the result.
*
* @param {String} body
*
* POST /parse_saml_idp_metadata -> ByteArray
*/
fun parse_saml_idp_metadata(
body: String
) : SDKResponse {
return this.post<ByteArray>("/parse_saml_idp_metadata", mapOf(), body)
}
/**
* ### Fetch the given url and parse it as a SAML IdP metadata document and return the result.
* Note that this requires that the url be public or at least at a location where the Looker instance
* can fetch it without requiring any special authentication.
*
* @param {String} body
*
* POST /fetch_and_parse_saml_idp_metadata -> ByteArray
*/
fun fetch_and_parse_saml_idp_metadata(
body: String
) : SDKResponse {
return this.post<ByteArray>("/fetch_and_parse_saml_idp_metadata", mapOf(), body)
}
/**
* ### Get session config.
*
* GET /session_config -> ByteArray
*/
fun session_config(
) : SDKResponse {
return this.get<ByteArray>("/session_config", mapOf())
}
/**
* ### Update session config.
*
* @param {WriteSessionConfig} body
*
* PATCH /session_config -> ByteArray
*/
fun update_session_config(
body: WriteSessionConfig
) : SDKResponse {
return this.patch<ByteArray>("/session_config", mapOf(), body)
}
/**
* ### Get Support Access Allowlist Users
*
* Returns the users that have been added to the Support Access Allowlist
*
* @param {String} fields Requested fields.
*
* GET /support_access/allowlist -> ByteArray
*/
@JvmOverloads fun get_support_access_allowlist_entries(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/support_access/allowlist",
mapOf("fields" to fields))
}
/**
* ### Add Support Access Allowlist Users
*
* Adds a list of emails to the Allowlist, using the provided reason
*
* @param {SupportAccessAddEntries} body
*
* POST /support_access/allowlist -> ByteArray
*/
fun add_support_access_allowlist_entries(
body: SupportAccessAddEntries
) : SDKResponse {
return this.post<ByteArray>("/support_access/allowlist", mapOf(), body)
}
/**
* ### Delete Support Access Allowlist User
*
* Deletes the specified Allowlist Entry Id
*
* @param {String} entry_id Id of Allowlist Entry
*
* DELETE /support_access/allowlist/{entry_id} -> ByteArray
*/
fun delete_support_access_allowlist_entry(
entry_id: String
) : SDKResponse {
val path_entry_id = encodeParam(entry_id)
return this.delete<ByteArray>("/support_access/allowlist/${path_entry_id}", mapOf())
}
/**
* ### Enable Support Access
*
* Enables Support Access for the provided duration
*
* @param {SupportAccessEnable} body
*
* PUT /support_access/enable -> ByteArray
*/
fun enable_support_access(
body: SupportAccessEnable
) : SDKResponse {
return this.put<ByteArray>("/support_access/enable", mapOf(), body)
}
/**
* ### Disable Support Access
*
* Disables Support Access immediately
*
* PUT /support_access/disable -> ByteArray
*/
fun disable_support_access(
) : SDKResponse {
return this.put<ByteArray>("/support_access/disable", mapOf())
}
/**
* ### Support Access Status
*
* Returns the current Support Access Status
*
* GET /support_access/status -> ByteArray
*/
fun support_access_status(
) : SDKResponse {
return this.get<ByteArray>("/support_access/status", mapOf())
}
/**
* ### Get currently locked-out users.
*
* @param {String} fields Include only these fields in the response
*
* GET /user_login_lockouts -> ByteArray
*/
@JvmOverloads fun all_user_login_lockouts(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/user_login_lockouts",
mapOf("fields" to fields))
}
/**
* ### Search currently locked-out users.
*
* @param {String} fields Include only these fields in the response
* @param {Long} page DEPRECATED. Use limit and offset instead. Return only page N of paginated results
* @param {Long} per_page DEPRECATED. Use limit and offset instead. Return N rows of data per page
* @param {Long} limit Number of results to return. (used with offset and takes priority over page and per_page)
* @param {Long} offset Number of results to skip before returning any. (used with limit and takes priority over page and per_page)
* @param {String} sorts Fields to sort by.
* @param {String} auth_type Auth type user is locked out for (email, ldap, totp, api)
* @param {String} full_name Match name
* @param {String} email Match email
* @param {String} remote_id Match remote LDAP ID
* @param {Boolean} filter_or Combine given search criteria in a boolean OR expression
*
* GET /user_login_lockouts/search -> ByteArray
*/
@JvmOverloads fun search_user_login_lockouts(
fields: String? = null,
page: Long? = null,
per_page: Long? = null,
limit: Long? = null,
offset: Long? = null,
sorts: String? = null,
auth_type: String? = null,
full_name: String? = null,
email: String? = null,
remote_id: String? = null,
filter_or: Boolean? = null
) : SDKResponse {
return this.get<ByteArray>("/user_login_lockouts/search",
mapOf("fields" to fields,
"page" to page,
"per_page" to per_page,
"limit" to limit,
"offset" to offset,
"sorts" to sorts,
"auth_type" to auth_type,
"full_name" to full_name,
"email" to email,
"remote_id" to remote_id,
"filter_or" to filter_or))
}
/**
* ### Removes login lockout for the associated user.
*
* @param {String} key The key associated with the locked user
*
* DELETE /user_login_lockout/{key} -> ByteArray
*/
fun delete_user_login_lockout(
key: String
) : SDKResponse {
val path_key = encodeParam(key)
return this.delete<ByteArray>("/user_login_lockout/${path_key}", mapOf())
}
//endregion Auth: Manage User Authentication Configuration
//region Board: Manage Boards
/**
* ### Get information about all boards.
*
* @param {String} fields Requested fields.
*
* GET /boards -> ByteArray
*/
@JvmOverloads fun all_boards(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/boards",
mapOf("fields" to fields))
}
/**
* ### Create a new board.
*
* @param {WriteBoard} body
* @param {String} fields Requested fields.
*
* POST /boards -> ByteArray
*/
@JvmOverloads fun create_board(
body: WriteBoard,
fields: String? = null
) : SDKResponse {
return this.post<ByteArray>("/boards",
mapOf("fields" to fields), body)
}
/**
* ### Search Boards
*
* If multiple search params are given and `filter_or` is FALSE or not specified,
* search params are combined in a logical AND operation.
* Only rows that match *all* search param criteria will be returned.
*
* If `filter_or` is TRUE, multiple search params are combined in a logical OR operation.
* Results will include rows that match **any** of the search criteria.
*
* String search params use case-insensitive matching.
* String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions.
* example="dan%" will match "danger" and "Danzig" but not "David"
* example="D_m%" will match "Damage" and "dump"
*
* Integer search params can accept a single value or a comma separated list of values. The multiple
* values will be combined under a logical OR operation - results will match at least one of
* the given values.
*
* Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match
* or exclude (respectively) rows where the column is null.
*
* Boolean search params accept only "true" and "false" as values.
*
* @param {String} title Matches board title.
* @param {String} created_at Matches the timestamp for when the board was created.
* @param {String} first_name The first name of the user who created this board.
* @param {String} last_name The last name of the user who created this board.
* @param {String} fields Requested fields.
* @param {Boolean} favorited Return favorited boards when true.
* @param {String} creator_id Filter on boards created by a particular user.
* @param {String} sorts The fields to sort the results by
* @param {Long} page The page to return. DEPRECATED. Use offset instead.
* @param {Long} per_page The number of items in the returned page. DEPRECATED. Use limit instead.
* @param {Long} offset The number of items to skip before returning any. (used with limit and takes priority over page and per_page)
* @param {Long} limit The maximum number of items to return. (used with offset and takes priority over page and per_page)
* @param {Boolean} filter_or Combine given search criteria in a boolean OR expression
* @param {String} permission Filter results based on permission, either show (default) or update
*
* GET /boards/search -> ByteArray
*/
@JvmOverloads fun search_boards(
title: String? = null,
created_at: String? = null,
first_name: String? = null,
last_name: String? = null,
fields: String? = null,
favorited: Boolean? = null,
creator_id: String? = null,
sorts: String? = null,
page: Long? = null,
per_page: Long? = null,
offset: Long? = null,
limit: Long? = null,
filter_or: Boolean? = null,
permission: String? = null
) : SDKResponse {
return this.get<ByteArray>("/boards/search",
mapOf("title" to title,
"created_at" to created_at,
"first_name" to first_name,
"last_name" to last_name,
"fields" to fields,
"favorited" to favorited,
"creator_id" to creator_id,
"sorts" to sorts,
"page" to page,
"per_page" to per_page,
"offset" to offset,
"limit" to limit,
"filter_or" to filter_or,
"permission" to permission))
}
/**
* ### Get information about a board.
*
* @param {String} board_id Id of board
* @param {String} fields Requested fields.
*
* GET /boards/{board_id} -> ByteArray
*/
@JvmOverloads fun board(
board_id: String,
fields: String? = null
) : SDKResponse {
val path_board_id = encodeParam(board_id)
return this.get<ByteArray>("/boards/${path_board_id}",
mapOf("fields" to fields))
}
/**
* ### Update a board definition.
*
* @param {String} board_id Id of board
* @param {WriteBoard} body
* @param {String} fields Requested fields.
*
* PATCH /boards/{board_id} -> ByteArray
*/
@JvmOverloads fun update_board(
board_id: String,
body: WriteBoard,
fields: String? = null
) : SDKResponse {
val path_board_id = encodeParam(board_id)
return this.patch<ByteArray>("/boards/${path_board_id}",
mapOf("fields" to fields), body)
}
/**
* ### Delete a board.
*
* @param {String} board_id Id of board
*
* DELETE /boards/{board_id} -> ByteArray
*/
fun delete_board(
board_id: String
) : SDKResponse {
val path_board_id = encodeParam(board_id)
return this.delete<ByteArray>("/boards/${path_board_id}", mapOf())
}
/**
* ### Get information about all board items.
*
* @param {String} fields Requested fields.
* @param {String} sorts Fields to sort by.
* @param {String} board_section_id Filter to a specific board section
*
* GET /board_items -> ByteArray
*/
@JvmOverloads fun all_board_items(
fields: String? = null,
sorts: String? = null,
board_section_id: String? = null
) : SDKResponse {
return this.get<ByteArray>("/board_items",
mapOf("fields" to fields,
"sorts" to sorts,
"board_section_id" to board_section_id))
}
/**
* ### Create a new board item.
*
* @param {WriteBoardItem} body
* @param {String} fields Requested fields.
*
* POST /board_items -> ByteArray
*/
@JvmOverloads fun create_board_item(
body: WriteBoardItem,
fields: String? = null
) : SDKResponse {
return this.post<ByteArray>("/board_items",
mapOf("fields" to fields), body)
}
/**
* ### Get information about a board item.
*
* @param {String} board_item_id Id of board item
* @param {String} fields Requested fields.
*
* GET /board_items/{board_item_id} -> ByteArray
*/
@JvmOverloads fun board_item(
board_item_id: String,
fields: String? = null
) : SDKResponse {
val path_board_item_id = encodeParam(board_item_id)
return this.get<ByteArray>("/board_items/${path_board_item_id}",
mapOf("fields" to fields))
}
/**
* ### Update a board item definition.
*
* @param {String} board_item_id Id of board item
* @param {WriteBoardItem} body
* @param {String} fields Requested fields.
*
* PATCH /board_items/{board_item_id} -> ByteArray
*/
@JvmOverloads fun update_board_item(
board_item_id: String,
body: WriteBoardItem,
fields: String? = null
) : SDKResponse {
val path_board_item_id = encodeParam(board_item_id)
return this.patch<ByteArray>("/board_items/${path_board_item_id}",
mapOf("fields" to fields), body)
}
/**
* ### Delete a board item.
*
* @param {String} board_item_id Id of board item
*
* DELETE /board_items/{board_item_id} -> ByteArray
*/
fun delete_board_item(
board_item_id: String
) : SDKResponse {
val path_board_item_id = encodeParam(board_item_id)
return this.delete<ByteArray>("/board_items/${path_board_item_id}", mapOf())
}
/**
* ### Get information about all board sections.
*
* @param {String} fields Requested fields.
* @param {String} sorts Fields to sort by.
*
* GET /board_sections -> ByteArray
*/
@JvmOverloads fun all_board_sections(
fields: String? = null,
sorts: String? = null
) : SDKResponse {
return this.get<ByteArray>("/board_sections",
mapOf("fields" to fields,
"sorts" to sorts))
}
/**
* ### Create a new board section.
*
* @param {WriteBoardSection} body
* @param {String} fields Requested fields.
*
* POST /board_sections -> ByteArray
*/
@JvmOverloads fun create_board_section(
body: WriteBoardSection,
fields: String? = null
) : SDKResponse {
return this.post<ByteArray>("/board_sections",
mapOf("fields" to fields), body)
}
/**
* ### Get information about a board section.
*
* @param {String} board_section_id Id of board section
* @param {String} fields Requested fields.
*
* GET /board_sections/{board_section_id} -> ByteArray
*/
@JvmOverloads fun board_section(
board_section_id: String,
fields: String? = null
) : SDKResponse {
val path_board_section_id = encodeParam(board_section_id)
return this.get<ByteArray>("/board_sections/${path_board_section_id}",
mapOf("fields" to fields))
}
/**
* ### Update a board section definition.
*
* @param {String} board_section_id Id of board section
* @param {WriteBoardSection} body
* @param {String} fields Requested fields.
*
* PATCH /board_sections/{board_section_id} -> ByteArray
*/
@JvmOverloads fun update_board_section(
board_section_id: String,
body: WriteBoardSection,
fields: String? = null
) : SDKResponse {
val path_board_section_id = encodeParam(board_section_id)
return this.patch<ByteArray>("/board_sections/${path_board_section_id}",
mapOf("fields" to fields), body)
}
/**
* ### Delete a board section.
*
* @param {String} board_section_id Id of board section
*
* DELETE /board_sections/{board_section_id} -> ByteArray
*/
fun delete_board_section(
board_section_id: String
) : SDKResponse {
val path_board_section_id = encodeParam(board_section_id)
return this.delete<ByteArray>("/board_sections/${path_board_section_id}", mapOf())
}
//endregion Board: Manage Boards
//region ColorCollection: Manage Color Collections
/**
* ### Get an array of all existing Color Collections
* Get a **single** color collection by id with [ColorCollection](#!/ColorCollection/color_collection)
*
* Get all **standard** color collections with [ColorCollection](#!/ColorCollection/color_collections_standard)
*
* Get all **custom** color collections with [ColorCollection](#!/ColorCollection/color_collections_custom)
*
* **Note**: Only an API user with the Admin role can call this endpoint. Unauthorized requests will return `Not Found` (404) errors.
*
* @param {String} fields Requested fields.
*
* GET /color_collections -> ByteArray
*/
@JvmOverloads fun all_color_collections(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/color_collections",
mapOf("fields" to fields))
}
/**
* ### Create a custom color collection with the specified information
*
* Creates a new custom color collection object, returning the details, including the created id.
*
* **Update** an existing color collection with [Update Color Collection](#!/ColorCollection/update_color_collection)
*
* **Permanently delete** an existing custom color collection with [Delete Color Collection](#!/ColorCollection/delete_color_collection)
*
* **Note**: Only an API user with the Admin role can call this endpoint. Unauthorized requests will return `Not Found` (404) errors.
*
* @param {WriteColorCollection} body
*
* POST /color_collections -> ByteArray
*/
fun create_color_collection(
body: WriteColorCollection
) : SDKResponse {
return this.post<ByteArray>("/color_collections", mapOf(), body)
}
/**
* ### Get an array of all existing **Custom** Color Collections
* Get a **single** color collection by id with [ColorCollection](#!/ColorCollection/color_collection)
*
* Get all **standard** color collections with [ColorCollection](#!/ColorCollection/color_collections_standard)
*
* **Note**: Only an API user with the Admin role can call this endpoint. Unauthorized requests will return `Not Found` (404) errors.
*
* @param {String} fields Requested fields.
*
* GET /color_collections/custom -> ByteArray
*/
@JvmOverloads fun color_collections_custom(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/color_collections/custom",
mapOf("fields" to fields))
}
/**
* ### Get an array of all existing **Standard** Color Collections
* Get a **single** color collection by id with [ColorCollection](#!/ColorCollection/color_collection)
*
* Get all **custom** color collections with [ColorCollection](#!/ColorCollection/color_collections_custom)
*
* **Note**: Only an API user with the Admin role can call this endpoint. Unauthorized requests will return `Not Found` (404) errors.
*
* @param {String} fields Requested fields.
*
* GET /color_collections/standard -> ByteArray
*/
@JvmOverloads fun color_collections_standard(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/color_collections/standard",
mapOf("fields" to fields))
}
/**
* ### Get the default color collection
*
* Use this to retrieve the default Color Collection.
*
* Set the default color collection with [ColorCollection](#!/ColorCollection/set_default_color_collection)
*
* GET /color_collections/default -> ByteArray
*/
fun default_color_collection(
) : SDKResponse {
return this.get<ByteArray>("/color_collections/default", mapOf())
}
/**
* ### Set the global default Color Collection by ID
*
* Returns the new specified default Color Collection object.
* **Note**: Only an API user with the Admin role can call this endpoint. Unauthorized requests will return `Not Found` (404) errors.
*
* @param {String} collection_id ID of color collection to set as default
*
* PUT /color_collections/default -> ByteArray
*/
fun set_default_color_collection(
collection_id: String
) : SDKResponse {
return this.put<ByteArray>("/color_collections/default",
mapOf("collection_id" to collection_id))
}
/**
* ### Get a Color Collection by ID
*
* Use this to retrieve a specific Color Collection.
* Get a **single** color collection by id with [ColorCollection](#!/ColorCollection/color_collection)
*
* Get all **standard** color collections with [ColorCollection](#!/ColorCollection/color_collections_standard)
*
* Get all **custom** color collections with [ColorCollection](#!/ColorCollection/color_collections_custom)
*
* **Note**: Only an API user with the Admin role can call this endpoint. Unauthorized requests will return `Not Found` (404) errors.
*
* @param {String} collection_id Id of Color Collection
* @param {String} fields Requested fields.
*
* GET /color_collections/{collection_id} -> ByteArray
*/
@JvmOverloads fun color_collection(
collection_id: String,
fields: String? = null
) : SDKResponse {
val path_collection_id = encodeParam(collection_id)
return this.get<ByteArray>("/color_collections/${path_collection_id}",
mapOf("fields" to fields))
}
/**
* ### Update a custom color collection by id.
* **Note**: Only an API user with the Admin role can call this endpoint. Unauthorized requests will return `Not Found` (404) errors.
*
* @param {String} collection_id Id of Custom Color Collection
* @param {WriteColorCollection} body
*
* PATCH /color_collections/{collection_id} -> ByteArray
*/
fun update_color_collection(
collection_id: String,
body: WriteColorCollection
) : SDKResponse {
val path_collection_id = encodeParam(collection_id)
return this.patch<ByteArray>("/color_collections/${path_collection_id}", mapOf(), body)
}
/**
* ### Delete a custom color collection by id
*
* This operation permanently deletes the identified **Custom** color collection.
*
* **Standard** color collections cannot be deleted
*
* Because multiple color collections can have the same label, they must be deleted by ID, not name.
* **Note**: Only an API user with the Admin role can call this endpoint. Unauthorized requests will return `Not Found` (404) errors.
*
* @param {String} collection_id Id of Color Collection
*
* DELETE /color_collections/{collection_id} -> ByteArray
*/
fun delete_color_collection(
collection_id: String
) : SDKResponse {
val path_collection_id = encodeParam(collection_id)
return this.delete<ByteArray>("/color_collections/${path_collection_id}", mapOf())
}
//endregion ColorCollection: Manage Color Collections
//region Config: Manage General Configuration
/**
* Get the current Cloud Storage Configuration.
*
* GET /cloud_storage -> ByteArray
*/
fun cloud_storage_configuration(
) : SDKResponse {
return this.get<ByteArray>("/cloud_storage", mapOf())
}
/**
* Update the current Cloud Storage Configuration.
*
* @param {WriteBackupConfiguration} body
*
* PATCH /cloud_storage -> ByteArray
*/
fun update_cloud_storage_configuration(
body: WriteBackupConfiguration
) : SDKResponse {
return this.patch<ByteArray>("/cloud_storage", mapOf(), body)
}
/**
* ### Looker Configuration Refresh
*
* This is an endpoint for manually calling refresh on Configuration manager.
*
* PUT /configuration_force_refresh -> ByteArray
*/
fun configuration_force_refresh(
) : SDKResponse {
return this.put<ByteArray>("/configuration_force_refresh", mapOf())
}
/**
* ### Get the current status and content of custom welcome emails
*
* GET /custom_welcome_email -> ByteArray
*/
@Deprecated(message = "Deprecated method")
fun custom_welcome_email(
) : SDKResponse {
return this.get<ByteArray>("/custom_welcome_email", mapOf())
}
/**
* Update custom welcome email setting and values. Optionally send a test email with the new content to the currently logged in user.
*
* @param {CustomWelcomeEmail} body
* @param {Boolean} send_test_welcome_email If true a test email with the content from the request will be sent to the current user after saving
*
* PATCH /custom_welcome_email -> ByteArray
*/
@Deprecated(message = "Deprecated method")
@JvmOverloads fun update_custom_welcome_email(
body: CustomWelcomeEmail,
send_test_welcome_email: Boolean? = null
) : SDKResponse {
return this.patch<ByteArray>("/custom_welcome_email",
mapOf("send_test_welcome_email" to send_test_welcome_email), body)
}
/**
* Requests to this endpoint will send a welcome email with the custom content provided in the body to the currently logged in user.
*
* @param {WelcomeEmailTest} body
*
* PUT /custom_welcome_email_test -> ByteArray
*/
fun update_custom_welcome_email_test(
body: WelcomeEmailTest
) : SDKResponse {
return this.put<ByteArray>("/custom_welcome_email_test", mapOf(), body)
}
/**
* ### Retrieve the value for whether or not digest emails is enabled
*
* GET /digest_emails_enabled -> ByteArray
*/
fun digest_emails_enabled(
) : SDKResponse {
return this.get<ByteArray>("/digest_emails_enabled", mapOf())
}
/**
* ### Update the setting for enabling/disabling digest emails
*
* @param {DigestEmails} body
*
* PATCH /digest_emails_enabled -> ByteArray
*/
fun update_digest_emails_enabled(
body: DigestEmails
) : SDKResponse {
return this.patch<ByteArray>("/digest_emails_enabled", mapOf(), body)
}
/**
* ### Trigger the generation of digest email records and send them to Looker's internal system. This does not send
* any actual emails, it generates records containing content which may be of interest for users who have become inactive.
* Emails will be sent at a later time from Looker's internal system if the Digest Emails feature is enabled in settings.
*
* POST /digest_email_send -> ByteArray
*/
fun create_digest_email_send(
) : SDKResponse {
return this.post<ByteArray>("/digest_email_send", mapOf())
}
/**
* ### Get Egress IP Addresses
*
* Returns the list of public egress IP Addresses for a hosted customer's instance
*
* GET /public_egress_ip_addresses -> ByteArray
*/
fun public_egress_ip_addresses(
) : SDKResponse {
return this.get<ByteArray>("/public_egress_ip_addresses", mapOf())
}
/**
* ### Set the menu item name and content for internal help resources
*
* GET /internal_help_resources_content -> ByteArray
*/
fun internal_help_resources_content(
) : SDKResponse {
return this.get<ByteArray>("/internal_help_resources_content", mapOf())
}
/**
* Update internal help resources content
*
* @param {WriteInternalHelpResourcesContent} body
*
* PATCH /internal_help_resources_content -> ByteArray
*/
fun update_internal_help_resources_content(
body: WriteInternalHelpResourcesContent
) : SDKResponse {
return this.patch<ByteArray>("/internal_help_resources_content", mapOf(), body)
}
/**
* ### Get and set the options for internal help resources
*
* GET /internal_help_resources_enabled -> ByteArray
*/
fun internal_help_resources(
) : SDKResponse {
return this.get<ByteArray>("/internal_help_resources_enabled", mapOf())
}
/**
* Update internal help resources settings
*
* @param {WriteInternalHelpResources} body
*
* PATCH /internal_help_resources -> ByteArray
*/
fun update_internal_help_resources(
body: WriteInternalHelpResources
) : SDKResponse {
return this.patch<ByteArray>("/internal_help_resources", mapOf(), body)
}
/**
* ### Get all legacy features.
*
* GET /legacy_features -> ByteArray
*/
fun all_legacy_features(
) : SDKResponse {
return this.get<ByteArray>("/legacy_features", mapOf())
}
/**
* ### Get information about the legacy feature with a specific id.
*
* @param {String} legacy_feature_id id of legacy feature
*
* GET /legacy_features/{legacy_feature_id} -> ByteArray
*/
fun legacy_feature(
legacy_feature_id: String
) : SDKResponse {
val path_legacy_feature_id = encodeParam(legacy_feature_id)
return this.get<ByteArray>("/legacy_features/${path_legacy_feature_id}", mapOf())
}
/**
* ### Update information about the legacy feature with a specific id.
*
* @param {String} legacy_feature_id id of legacy feature
* @param {WriteLegacyFeature} body
*
* PATCH /legacy_features/{legacy_feature_id} -> ByteArray
*/
fun update_legacy_feature(
legacy_feature_id: String,
body: WriteLegacyFeature
) : SDKResponse {
val path_legacy_feature_id = encodeParam(legacy_feature_id)
return this.patch<ByteArray>("/legacy_features/${path_legacy_feature_id}", mapOf(), body)
}
/**
* ### Get a list of locales that Looker supports.
*
* GET /locales -> ByteArray
*/
fun all_locales(
) : SDKResponse {
return this.get<ByteArray>("/locales", mapOf())
}
/**
* ### Get all mobile settings.
*
* GET /mobile/settings -> ByteArray
*/
fun mobile_settings(
) : SDKResponse {
return this.get<ByteArray>("/mobile/settings", mapOf())
}
/**
* ### Get Looker Settings
*
* Available settings are:
* - allow_user_timezones
* - custom_welcome_email
* - data_connector_default_enabled
* - extension_framework_enabled
* - extension_load_url_enabled
* - marketplace_auto_install_enabled
* - marketplace_enabled
* - onboarding_enabled
* - privatelabel_configuration
* - timezone
*
* @param {String} fields Requested fields
*
* GET /setting -> ByteArray
*/
@JvmOverloads fun get_setting(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/setting",
mapOf("fields" to fields))
}
/**
* ### Configure Looker Settings
*
* Available settings are:
* - allow_user_timezones
* - custom_welcome_email
* - data_connector_default_enabled
* - extension_framework_enabled
* - extension_load_url_enabled
* - marketplace_auto_install_enabled
* - marketplace_enabled
* - onboarding_enabled
* - privatelabel_configuration
* - timezone
*
* See the `Setting` type for more information on the specific values that can be configured.
*
* @param {WriteSetting} body
* @param {String} fields Requested fields
*
* PATCH /setting -> ByteArray
*/
@JvmOverloads fun set_setting(
body: WriteSetting,
fields: String? = null
) : SDKResponse {
return this.patch<ByteArray>("/setting",
mapOf("fields" to fields), body)
}
/**
* ### Configure SMTP Settings
* This API allows users to configure the SMTP settings on the Looker instance.
* This API is only supported in the OEM jar. Additionally, only admin users are authorised to call this API.
*
* @param {SmtpSettings} body
*
* POST /smtp_settings -> ByteArray
*/
fun set_smtp_settings(
body: SmtpSettings
) : SDKResponse {
return this.post<ByteArray>("/smtp_settings", mapOf(), body)
}
/**
* ### Get current SMTP status.
*
* @param {String} fields Include only these fields in the response
*
* GET /smtp_status -> ByteArray
*/
@JvmOverloads fun smtp_status(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/smtp_status",
mapOf("fields" to fields))
}
/**
* ### Get a list of timezones that Looker supports (e.g. useful for scheduling tasks).
*
* GET /timezones -> ByteArray
*/
fun all_timezones(
) : SDKResponse {
return this.get<ByteArray>("/timezones", mapOf())
}
/**
* ### Get information about all API versions supported by this Looker instance.
*
* @param {String} fields Requested fields.
*
* GET /versions -> ByteArray
*/
@JvmOverloads fun versions(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/versions",
mapOf("fields" to fields))
}
/**
* ### Get an API specification for this Looker instance.
*
* The specification is returned as a JSON document in Swagger 2.x format
*
* @param {String} api_version API version
* @param {String} specification Specification name. Typically, this is "swagger.json"
*
* GET /api_spec/{api_version}/{specification} -> ByteArray
*/
fun api_spec(
api_version: String,
specification: String
) : SDKResponse {
val path_api_version = encodeParam(api_version)
val path_specification = encodeParam(specification)
return this.get<ByteArray>("/api_spec/${path_api_version}/${path_specification}", mapOf())
}
/**
* ### This feature is enabled only by special license.
* ### Gets the whitelabel configuration, which includes hiding documentation links, custom favicon uploading, etc.
*
* @param {String} fields Requested fields.
*
* GET /whitelabel_configuration -> ByteArray
*/
@Deprecated(message = "Deprecated method")
@JvmOverloads fun whitelabel_configuration(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/whitelabel_configuration",
mapOf("fields" to fields))
}
/**
* ### Update the whitelabel configuration
*
* @param {WriteWhitelabelConfiguration} body
*
* PUT /whitelabel_configuration -> ByteArray
*/
@Deprecated(message = "Deprecated method")
fun update_whitelabel_configuration(
body: WriteWhitelabelConfiguration
) : SDKResponse {
return this.put<ByteArray>("/whitelabel_configuration", mapOf(), body)
}
//endregion Config: Manage General Configuration
//region Connection: Manage Database Connections
/**
* ### Get information about all connections.
*
* @param {String} fields Requested fields.
*
* GET /connections -> ByteArray
*/
@JvmOverloads fun all_connections(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/connections",
mapOf("fields" to fields))
}
/**
* ### Create a connection using the specified configuration.
*
* @param {WriteDBConnection} body
*
* POST /connections -> ByteArray
*/
fun create_connection(
body: WriteDBConnection
) : SDKResponse {
return this.post<ByteArray>("/connections", mapOf(), body)
}
/**
* ### Get information about a connection.
*
* @param {String} connection_name Name of connection
* @param {String} fields Requested fields.
*
* GET /connections/{connection_name} -> ByteArray
*/
@JvmOverloads fun connection(
connection_name: String,
fields: String? = null
) : SDKResponse {
val path_connection_name = encodeParam(connection_name)
return this.get<ByteArray>("/connections/${path_connection_name}",
mapOf("fields" to fields))
}
/**
* ### Update a connection using the specified configuration.
*
* @param {String} connection_name Name of connection
* @param {WriteDBConnection} body
*
* PATCH /connections/{connection_name} -> ByteArray
*/
fun update_connection(
connection_name: String,
body: WriteDBConnection
) : SDKResponse {
val path_connection_name = encodeParam(connection_name)
return this.patch<ByteArray>("/connections/${path_connection_name}", mapOf(), body)
}
/**
* ### Delete a connection.
*
* @param {String} connection_name Name of connection
*
* DELETE /connections/{connection_name} -> ByteArray
*/
fun delete_connection(
connection_name: String
) : SDKResponse {
val path_connection_name = encodeParam(connection_name)
return this.delete<ByteArray>("/connections/${path_connection_name}", mapOf())
}
/**
* ### Delete a connection override.
*
* @param {String} connection_name Name of connection
* @param {String} override_context Context of connection override
*
* DELETE /connections/{connection_name}/connection_override/{override_context} -> ByteArray
*/
fun delete_connection_override(
connection_name: String,
override_context: String
) : SDKResponse {
val path_connection_name = encodeParam(connection_name)
val path_override_context = encodeParam(override_context)
return this.delete<ByteArray>("/connections/${path_connection_name}/connection_override/${path_override_context}", mapOf())
}
/**
* ### Test an existing connection.
*
* Note that a connection's 'dialect' property has a 'connection_tests' property that lists the
* specific types of tests that the connection supports.
*
* This API is rate limited.
*
* Unsupported tests in the request will be ignored.
*
* @param {String} connection_name Name of connection
* @param {DelimArray<String>} tests Array of names of tests to run
*
* PUT /connections/{connection_name}/test -> ByteArray
*/
@JvmOverloads fun test_connection(
connection_name: String,
tests: DelimArray<String>? = null
) : SDKResponse {
val path_connection_name = encodeParam(connection_name)
return this.put<ByteArray>("/connections/${path_connection_name}/test",
mapOf("tests" to tests))
}
/**
* ### Test a connection configuration.
*
* Note that a connection's 'dialect' property has a 'connection_tests' property that lists the
* specific types of tests that the connection supports.
*
* This API is rate limited.
*
* Unsupported tests in the request will be ignored.
*
* @param {WriteDBConnection} body
* @param {DelimArray<String>} tests Array of names of tests to run
*
* PUT /connections/test -> ByteArray
*/
@JvmOverloads fun test_connection_config(
body: WriteDBConnection,
tests: DelimArray<String>? = null
) : SDKResponse {
return this.put<ByteArray>("/connections/test",
mapOf("tests" to tests), body)
}
/**
* ### Get information about all dialects.
*
* @param {String} fields Requested fields.
*
* GET /dialect_info -> ByteArray
*/
@JvmOverloads fun all_dialect_infos(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/dialect_info",
mapOf("fields" to fields))
}
/**
* ### Get all External OAuth Applications.
*
* This is an OAuth Application which Looker uses to access external systems.
*
* @param {String} name Application name
* @param {String} client_id Application Client ID
*
* GET /external_oauth_applications -> ByteArray
*/
@JvmOverloads fun all_external_oauth_applications(
name: String? = null,
client_id: String? = null
) : SDKResponse {
return this.get<ByteArray>("/external_oauth_applications",
mapOf("name" to name,
"client_id" to client_id))
}
/**
* ### Create an OAuth Application using the specified configuration.
*
* This is an OAuth Application which Looker uses to access external systems.
*
* @param {WriteExternalOauthApplication} body
*
* POST /external_oauth_applications -> ByteArray
*/
fun create_external_oauth_application(
body: WriteExternalOauthApplication
) : SDKResponse {
return this.post<ByteArray>("/external_oauth_applications", mapOf(), body)
}
/**
* ### Create OAuth User state.
*
* @param {CreateOAuthApplicationUserStateRequest} body
*
* POST /external_oauth_applications/user_state -> ByteArray
*/
fun create_oauth_application_user_state(
body: CreateOAuthApplicationUserStateRequest
) : SDKResponse {
return this.post<ByteArray>("/external_oauth_applications/user_state", mapOf(), body)
}
/**
* ### Get information about all SSH Servers.
*
* @param {String} fields Requested fields.
*
* GET /ssh_servers -> ByteArray
*/
@JvmOverloads fun all_ssh_servers(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/ssh_servers",
mapOf("fields" to fields))
}
/**
* ### Create an SSH Server.
*
* @param {WriteSshServer} body
*
* POST /ssh_servers -> ByteArray
*/
fun create_ssh_server(
body: WriteSshServer
) : SDKResponse {
return this.post<ByteArray>("/ssh_servers", mapOf(), body)
}
/**
* ### Get information about an SSH Server.
*
* @param {String} ssh_server_id Id of SSH Server
*
* GET /ssh_server/{ssh_server_id} -> ByteArray
*/
fun ssh_server(
ssh_server_id: String
) : SDKResponse {
val path_ssh_server_id = encodeParam(ssh_server_id)
return this.get<ByteArray>("/ssh_server/${path_ssh_server_id}", mapOf())
}
/**
* ### Update an SSH Server.
*
* @param {String} ssh_server_id Id of SSH Server
* @param {WriteSshServer} body
*
* PATCH /ssh_server/{ssh_server_id} -> ByteArray
*/
fun update_ssh_server(
ssh_server_id: String,
body: WriteSshServer
) : SDKResponse {
val path_ssh_server_id = encodeParam(ssh_server_id)
return this.patch<ByteArray>("/ssh_server/${path_ssh_server_id}", mapOf(), body)
}
/**
* ### Delete an SSH Server.
*
* @param {String} ssh_server_id Id of SSH Server
*
* DELETE /ssh_server/{ssh_server_id} -> ByteArray
*/
fun delete_ssh_server(
ssh_server_id: String
) : SDKResponse {
val path_ssh_server_id = encodeParam(ssh_server_id)
return this.delete<ByteArray>("/ssh_server/${path_ssh_server_id}", mapOf())
}
/**
* ### Test the SSH Server
*
* @param {String} ssh_server_id Id of SSH Server
*
* GET /ssh_server/{ssh_server_id}/test -> ByteArray
*/
fun test_ssh_server(
ssh_server_id: String
) : SDKResponse {
val path_ssh_server_id = encodeParam(ssh_server_id)
return this.get<ByteArray>("/ssh_server/${path_ssh_server_id}/test", mapOf())
}
/**
* ### Get information about all SSH Tunnels.
*
* @param {String} fields Requested fields.
*
* GET /ssh_tunnels -> ByteArray
*/
@JvmOverloads fun all_ssh_tunnels(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/ssh_tunnels",
mapOf("fields" to fields))
}
/**
* ### Create an SSH Tunnel
*
* @param {WriteSshTunnel} body
*
* POST /ssh_tunnels -> ByteArray
*/
fun create_ssh_tunnel(
body: WriteSshTunnel
) : SDKResponse {
return this.post<ByteArray>("/ssh_tunnels", mapOf(), body)
}
/**
* ### Get information about an SSH Tunnel.
*
* @param {String} ssh_tunnel_id Id of SSH Tunnel
*
* GET /ssh_tunnel/{ssh_tunnel_id} -> ByteArray
*/
fun ssh_tunnel(
ssh_tunnel_id: String
) : SDKResponse {
val path_ssh_tunnel_id = encodeParam(ssh_tunnel_id)
return this.get<ByteArray>("/ssh_tunnel/${path_ssh_tunnel_id}", mapOf())
}
/**
* ### Update an SSH Tunnel
*
* @param {String} ssh_tunnel_id Id of SSH Tunnel
* @param {WriteSshTunnel} body
*
* PATCH /ssh_tunnel/{ssh_tunnel_id} -> ByteArray
*/
fun update_ssh_tunnel(
ssh_tunnel_id: String,
body: WriteSshTunnel
) : SDKResponse {
val path_ssh_tunnel_id = encodeParam(ssh_tunnel_id)
return this.patch<ByteArray>("/ssh_tunnel/${path_ssh_tunnel_id}", mapOf(), body)
}
/**
* ### Delete an SSH Tunnel
*
* @param {String} ssh_tunnel_id Id of SSH Tunnel
*
* DELETE /ssh_tunnel/{ssh_tunnel_id} -> ByteArray
*/
fun delete_ssh_tunnel(
ssh_tunnel_id: String
) : SDKResponse {
val path_ssh_tunnel_id = encodeParam(ssh_tunnel_id)
return this.delete<ByteArray>("/ssh_tunnel/${path_ssh_tunnel_id}", mapOf())
}
/**
* ### Test the SSH Tunnel
*
* @param {String} ssh_tunnel_id Id of SSH Tunnel
*
* GET /ssh_tunnel/{ssh_tunnel_id}/test -> ByteArray
*/
fun test_ssh_tunnel(
ssh_tunnel_id: String
) : SDKResponse {
val path_ssh_tunnel_id = encodeParam(ssh_tunnel_id)
return this.get<ByteArray>("/ssh_tunnel/${path_ssh_tunnel_id}/test", mapOf())
}
/**
* ### Get the SSH public key
*
* Get the public key created for this instance to identify itself to a remote SSH server.
*
* GET /ssh_public_key -> ByteArray
*/
fun ssh_public_key(
) : SDKResponse {
return this.get<ByteArray>("/ssh_public_key", mapOf())
}
//endregion Connection: Manage Database Connections
//region Content: Manage Content
/**
* ### Search Favorite Content
*
* If multiple search params are given and `filter_or` is FALSE or not specified,
* search params are combined in a logical AND operation.
* Only rows that match *all* search param criteria will be returned.
*
* If `filter_or` is TRUE, multiple search params are combined in a logical OR operation.
* Results will include rows that match **any** of the search criteria.
*
* String search params use case-insensitive matching.
* String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions.
* example="dan%" will match "danger" and "Danzig" but not "David"
* example="D_m%" will match "Damage" and "dump"
*
* Integer search params can accept a single value or a comma separated list of values. The multiple
* values will be combined under a logical OR operation - results will match at least one of
* the given values.
*
* Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match
* or exclude (respectively) rows where the column is null.
*
* Boolean search params accept only "true" and "false" as values.
*
* @param {String} id Match content favorite id(s)
* @param {String} user_id Match user id(s).To create a list of multiple ids, use commas as separators
* @param {String} content_metadata_id Match content metadata id(s).To create a list of multiple ids, use commas as separators
* @param {String} dashboard_id Match dashboard id(s).To create a list of multiple ids, use commas as separators
* @param {String} look_id Match look id(s).To create a list of multiple ids, use commas as separators
* @param {String} board_id Match board id(s).To create a list of multiple ids, use commas as separators
* @param {Long} limit Number of results to return. (used with offset)
* @param {Long} offset Number of results to skip before returning any. (used with limit)
* @param {String} sorts Fields to sort by.
* @param {String} fields Requested fields.
* @param {Boolean} filter_or Combine given search criteria in a boolean OR expression
*
* GET /content_favorite/search -> ByteArray
*/
@JvmOverloads fun search_content_favorites(
id: String? = null,
user_id: String? = null,
content_metadata_id: String? = null,
dashboard_id: String? = null,
look_id: String? = null,
board_id: String? = null,
limit: Long? = null,
offset: Long? = null,
sorts: String? = null,
fields: String? = null,
filter_or: Boolean? = null
) : SDKResponse {
return this.get<ByteArray>("/content_favorite/search",
mapOf("id" to id,
"user_id" to user_id,
"content_metadata_id" to content_metadata_id,
"dashboard_id" to dashboard_id,
"look_id" to look_id,
"board_id" to board_id,
"limit" to limit,
"offset" to offset,
"sorts" to sorts,
"fields" to fields,
"filter_or" to filter_or))
}
/**
* ### Get favorite content by its id
*
* @param {String} content_favorite_id Id of favorite content
* @param {String} fields Requested fields.
*
* GET /content_favorite/{content_favorite_id} -> ByteArray
*/
@JvmOverloads fun content_favorite(
content_favorite_id: String,
fields: String? = null
) : SDKResponse {
val path_content_favorite_id = encodeParam(content_favorite_id)
return this.get<ByteArray>("/content_favorite/${path_content_favorite_id}",
mapOf("fields" to fields))
}
/**
* ### Delete favorite content
*
* @param {String} content_favorite_id Id of favorite content
*
* DELETE /content_favorite/{content_favorite_id} -> ByteArray
*/
fun delete_content_favorite(
content_favorite_id: String
) : SDKResponse {
val path_content_favorite_id = encodeParam(content_favorite_id)
return this.delete<ByteArray>("/content_favorite/${path_content_favorite_id}", mapOf())
}
/**
* ### Create favorite content
*
* @param {WriteContentFavorite} body
*
* POST /content_favorite -> ByteArray
*/
fun create_content_favorite(
body: WriteContentFavorite
) : SDKResponse {
return this.post<ByteArray>("/content_favorite", mapOf(), body)
}
/**
* ### Get information about all content metadata in a space.
*
* @param {String} parent_id Parent space of content.
* @param {String} fields Requested fields.
*
* GET /content_metadata -> ByteArray
*/
@JvmOverloads fun all_content_metadatas(
parent_id: String,
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/content_metadata",
mapOf("parent_id" to parent_id,
"fields" to fields))
}
/**
* ### Get information about an individual content metadata record.
*
* @param {String} content_metadata_id Id of content metadata
* @param {String} fields Requested fields.
*
* GET /content_metadata/{content_metadata_id} -> ByteArray
*/
@JvmOverloads fun content_metadata(
content_metadata_id: String,
fields: String? = null
) : SDKResponse {
val path_content_metadata_id = encodeParam(content_metadata_id)
return this.get<ByteArray>("/content_metadata/${path_content_metadata_id}",
mapOf("fields" to fields))
}
/**
* ### Move a piece of content.
*
* @param {String} content_metadata_id Id of content metadata
* @param {WriteContentMeta} body
*
* PATCH /content_metadata/{content_metadata_id} -> ByteArray
*/
fun update_content_metadata(
content_metadata_id: String,
body: WriteContentMeta
) : SDKResponse {
val path_content_metadata_id = encodeParam(content_metadata_id)
return this.patch<ByteArray>("/content_metadata/${path_content_metadata_id}", mapOf(), body)
}
/**
* ### All content metadata access records for a content metadata item.
*
* @param {String} content_metadata_id Id of content metadata
* @param {String} fields Requested fields.
*
* GET /content_metadata_access -> ByteArray
*/
@JvmOverloads fun all_content_metadata_accesses(
content_metadata_id: String,
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/content_metadata_access",
mapOf("content_metadata_id" to content_metadata_id,
"fields" to fields))
}
/**
* ### Create content metadata access.
*
* @param {ContentMetaGroupUser} body WARNING: no writeable properties found for POST, PUT, or PATCH
* @param {Boolean} send_boards_notification_email Optionally sends notification email when granting access to a board.
*
* POST /content_metadata_access -> ByteArray
*/
@JvmOverloads fun create_content_metadata_access(
body: ContentMetaGroupUser,
send_boards_notification_email: Boolean? = null
) : SDKResponse {
return this.post<ByteArray>("/content_metadata_access",
mapOf("send_boards_notification_email" to send_boards_notification_email), body)
}
/**
* ### Update type of access for content metadata.
*
* @param {String} content_metadata_access_id Id of content metadata access
* @param {ContentMetaGroupUser} body WARNING: no writeable properties found for POST, PUT, or PATCH
*
* PUT /content_metadata_access/{content_metadata_access_id} -> ByteArray
*/
fun update_content_metadata_access(
content_metadata_access_id: String,
body: ContentMetaGroupUser
) : SDKResponse {
val path_content_metadata_access_id = encodeParam(content_metadata_access_id)
return this.put<ByteArray>("/content_metadata_access/${path_content_metadata_access_id}", mapOf(), body)
}
/**
* ### Remove content metadata access.
*
* @param {String} content_metadata_access_id Id of content metadata access
*
* DELETE /content_metadata_access/{content_metadata_access_id} -> ByteArray
*/
fun delete_content_metadata_access(
content_metadata_access_id: String
) : SDKResponse {
val path_content_metadata_access_id = encodeParam(content_metadata_access_id)
return this.delete<ByteArray>("/content_metadata_access/${path_content_metadata_access_id}", mapOf())
}
/**
* ### Get an image representing the contents of a dashboard or look.
*
* The returned thumbnail is an abstract representation of the contents of a dashbord or look and does not
* reflect the actual data displayed in the respective visualizations.
*
* @param {String} type Either dashboard or look
* @param {String} resource_id ID of the dashboard or look to render
* @param {String} reload Whether or not to refresh the rendered image with the latest content
* @param {String} format A value of png produces a thumbnail in PNG format instead of SVG (default)
* @param {Long} width The width of the image if format is supplied
* @param {Long} height The height of the image if format is supplied
*
* GET /content_thumbnail/{type}/{resource_id} -> ByteArray
*
* **Note**: Binary content may be returned by this method.
*/
@JvmOverloads fun content_thumbnail(
type: String,
resource_id: String,
reload: String? = null,
format: String? = null,
width: Long? = null,
height: Long? = null
) : SDKResponse {
val path_type = encodeParam(type)
val path_resource_id = encodeParam(resource_id)
return this.get<ByteArray>("/content_thumbnail/${path_type}/${path_resource_id}",
mapOf("reload" to reload,
"format" to format,
"width" to width,
"height" to height))
}
/**
* ### Validate All Content
*
* Performs validation of all looks and dashboards
* Returns a list of errors found as well as metadata about the content validation run.
*
* @param {String} fields Requested fields.
*
* GET /content_validation -> ByteArray
*/
@JvmOverloads fun content_validation(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/content_validation",
mapOf("fields" to fields))
}
/**
* ### Search Content Views
*
* If multiple search params are given and `filter_or` is FALSE or not specified,
* search params are combined in a logical AND operation.
* Only rows that match *all* search param criteria will be returned.
*
* If `filter_or` is TRUE, multiple search params are combined in a logical OR operation.
* Results will include rows that match **any** of the search criteria.
*
* String search params use case-insensitive matching.
* String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions.
* example="dan%" will match "danger" and "Danzig" but not "David"
* example="D_m%" will match "Damage" and "dump"
*
* Integer search params can accept a single value or a comma separated list of values. The multiple
* values will be combined under a logical OR operation - results will match at least one of
* the given values.
*
* Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match
* or exclude (respectively) rows where the column is null.
*
* Boolean search params accept only "true" and "false" as values.
*
* @param {String} view_count Match view count
* @param {String} group_id Match Group Id
* @param {String} look_id Match look_id
* @param {String} dashboard_id Match dashboard_id
* @param {String} content_metadata_id Match content metadata id
* @param {String} start_of_week_date Match start of week date (format is "YYYY-MM-DD")
* @param {Boolean} all_time True if only all time view records should be returned
* @param {String} user_id Match user id
* @param {String} fields Requested fields
* @param {Long} limit Number of results to return. Use with `offset` to manage pagination of results
* @param {Long} offset Number of results to skip before returning data
* @param {String} sorts Fields to sort by
* @param {Boolean} filter_or Combine given search criteria in a boolean OR expression
*
* GET /content_view/search -> ByteArray
*/
@JvmOverloads fun search_content_views(
view_count: String? = null,
group_id: String? = null,
look_id: String? = null,
dashboard_id: String? = null,
content_metadata_id: String? = null,
start_of_week_date: String? = null,
all_time: Boolean? = null,
user_id: String? = null,
fields: String? = null,
limit: Long? = null,
offset: Long? = null,
sorts: String? = null,
filter_or: Boolean? = null
) : SDKResponse {
return this.get<ByteArray>("/content_view/search",
mapOf("view_count" to view_count,
"group_id" to group_id,
"look_id" to look_id,
"dashboard_id" to dashboard_id,
"content_metadata_id" to content_metadata_id,
"start_of_week_date" to start_of_week_date,
"all_time" to all_time,
"user_id" to user_id,
"fields" to fields,
"limit" to limit,
"offset" to offset,
"sorts" to sorts,
"filter_or" to filter_or))
}
/**
* ### Get a vector image representing the contents of a dashboard or look.
*
* # DEPRECATED: Use [content_thumbnail()](#!/Content/content_thumbnail)
*
* The returned thumbnail is an abstract representation of the contents of a dashbord or look and does not
* reflect the actual data displayed in the respective visualizations.
*
* @param {String} type Either dashboard or look
* @param {String} resource_id ID of the dashboard or look to render
* @param {String} reload Whether or not to refresh the rendered image with the latest content
*
* GET /vector_thumbnail/{type}/{resource_id} -> ByteArray
*/
@Deprecated(message = "Deprecated method")
@JvmOverloads fun vector_thumbnail(
type: String,
resource_id: String,
reload: String? = null
) : SDKResponse {
val path_type = encodeParam(type)
val path_resource_id = encodeParam(resource_id)
return this.get<ByteArray>("/vector_thumbnail/${path_type}/${path_resource_id}",
mapOf("reload" to reload))
}
//endregion Content: Manage Content
//region Dashboard: Manage Dashboards
/**
* ### Get information about all active dashboards.
*
* Returns an array of **abbreviated dashboard objects**. Dashboards marked as deleted are excluded from this list.
*
* Get the **full details** of a specific dashboard by id with [dashboard()](#!/Dashboard/dashboard)
*
* Find **deleted dashboards** with [search_dashboards()](#!/Dashboard/search_dashboards)
*
* @param {String} fields Requested fields.
*
* GET /dashboards -> ByteArray
*/
@JvmOverloads fun all_dashboards(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/dashboards",
mapOf("fields" to fields))
}
/**
* ### Create a new dashboard
*
* Creates a new dashboard object and returns the details of the newly created dashboard.
*
* `Title` and `space_id` are required fields.
* `Space_id` must contain the id of an existing space.
* A dashboard's `title` must be unique within the space in which it resides.
*
* If you receive a 422 error response when creating a dashboard, be sure to look at the
* response body for information about exactly which fields are missing or contain invalid data.
*
* You can **update** an existing dashboard with [update_dashboard()](#!/Dashboard/update_dashboard)
*
* You can **permanently delete** an existing dashboard with [delete_dashboard()](#!/Dashboard/delete_dashboard)
*
* @param {WriteDashboard} body
*
* POST /dashboards -> ByteArray
*/
fun create_dashboard(
body: WriteDashboard
) : SDKResponse {
return this.post<ByteArray>("/dashboards", mapOf(), body)
}
/**
* ### Search Dashboards
*
* Returns an **array of dashboard objects** that match the specified search criteria.
*
* If multiple search params are given and `filter_or` is FALSE or not specified,
* search params are combined in a logical AND operation.
* Only rows that match *all* search param criteria will be returned.
*
* If `filter_or` is TRUE, multiple search params are combined in a logical OR operation.
* Results will include rows that match **any** of the search criteria.
*
* String search params use case-insensitive matching.
* String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions.
* example="dan%" will match "danger" and "Danzig" but not "David"
* example="D_m%" will match "Damage" and "dump"
*
* Integer search params can accept a single value or a comma separated list of values. The multiple
* values will be combined under a logical OR operation - results will match at least one of
* the given values.
*
* Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match
* or exclude (respectively) rows where the column is null.
*
* Boolean search params accept only "true" and "false" as values.
*
*
* The parameters `limit`, and `offset` are recommended for fetching results in page-size chunks.
*
* Get a **single dashboard** by id with [dashboard()](#!/Dashboard/dashboard)
*
* @param {String} id Match dashboard id.
* @param {String} slug Match dashboard slug.
* @param {String} title Match Dashboard title.
* @param {String} description Match Dashboard description.
* @param {String} content_favorite_id Filter on a content favorite id.
* @param {String} folder_id Filter on a particular space.
* @param {String} deleted Filter on dashboards deleted status.
* @param {String} user_id Filter on dashboards created by a particular user.
* @param {String} view_count Filter on a particular value of view_count
* @param {String} content_metadata_id Filter on a content favorite id.
* @param {Boolean} curate Exclude items that exist only in personal spaces other than the users
* @param {String} last_viewed_at Select dashboards based on when they were last viewed
* @param {String} fields Requested fields.
* @param {Long} page DEPRECATED. Use limit and offset instead. Return only page N of paginated results
* @param {Long} per_page DEPRECATED. Use limit and offset instead. Return N rows of data per page
* @param {Long} limit Number of results to return. (used with offset and takes priority over page and per_page)
* @param {Long} offset Number of results to skip before returning any. (used with limit and takes priority over page and per_page)
* @param {String} sorts One or more fields to sort by. Sortable fields: [:title, :user_id, :id, :created_at, :space_id, :folder_id, :description, :view_count, :favorite_count, :slug, :content_favorite_id, :content_metadata_id, :deleted, :deleted_at, :last_viewed_at, :last_accessed_at]
* @param {Boolean} filter_or Combine given search criteria in a boolean OR expression
*
* GET /dashboards/search -> ByteArray
*/
@JvmOverloads fun search_dashboards(
id: String? = null,
slug: String? = null,
title: String? = null,
description: String? = null,
content_favorite_id: String? = null,
folder_id: String? = null,
deleted: String? = null,
user_id: String? = null,
view_count: String? = null,
content_metadata_id: String? = null,
curate: Boolean? = null,
last_viewed_at: String? = null,
fields: String? = null,
page: Long? = null,
per_page: Long? = null,
limit: Long? = null,
offset: Long? = null,
sorts: String? = null,
filter_or: Boolean? = null
) : SDKResponse {
return this.get<ByteArray>("/dashboards/search",
mapOf("id" to id,
"slug" to slug,
"title" to title,
"description" to description,
"content_favorite_id" to content_favorite_id,
"folder_id" to folder_id,
"deleted" to deleted,
"user_id" to user_id,
"view_count" to view_count,
"content_metadata_id" to content_metadata_id,
"curate" to curate,
"last_viewed_at" to last_viewed_at,
"fields" to fields,
"page" to page,
"per_page" to per_page,
"limit" to limit,
"offset" to offset,
"sorts" to sorts,
"filter_or" to filter_or))
}
/**
* ### Import a LookML dashboard to a space as a UDD
* Creates a UDD (a dashboard which exists in the Looker database rather than as a LookML file) from the LookML dashboard
* and places it in the space specified. The created UDD will have a lookml_link_id which links to the original LookML dashboard.
*
* To give the imported dashboard specify a (e.g. title: "my title") in the body of your request, otherwise the imported
* dashboard will have the same title as the original LookML dashboard.
*
* For this operation to succeed the user must have permission to see the LookML dashboard in question, and have permission to
* create content in the space the dashboard is being imported to.
*
* **Sync** a linked UDD with [sync_lookml_dashboard()](#!/Dashboard/sync_lookml_dashboard)
* **Unlink** a linked UDD by setting lookml_link_id to null with [update_dashboard()](#!/Dashboard/update_dashboard)
*
* @param {String} lookml_dashboard_id Id of LookML dashboard
* @param {String} space_id Id of space to import the dashboard to
* @param {WriteDashboard} body
* @param {Boolean} raw_locale If true, and this dashboard is localized, export it with the raw keys, not localized.
*
* POST /dashboards/{lookml_dashboard_id}/import/{space_id} -> ByteArray
*/
@JvmOverloads fun import_lookml_dashboard(
lookml_dashboard_id: String,
space_id: String,
body: WriteDashboard? = null,
raw_locale: Boolean? = null
) : SDKResponse {
val path_lookml_dashboard_id = encodeParam(lookml_dashboard_id)
val path_space_id = encodeParam(space_id)
return this.post<ByteArray>("/dashboards/${path_lookml_dashboard_id}/import/${path_space_id}",
mapOf("raw_locale" to raw_locale), body)
}
/**
* ### Update all linked dashboards to match the specified LookML dashboard.
*
* Any UDD (a dashboard which exists in the Looker database rather than as a LookML file) which has a `lookml_link_id`
* property value referring to a LookML dashboard's id (model::dashboardname) will be updated so that it matches the current state of the LookML dashboard.
*
* For this operation to succeed the user must have permission to view the LookML dashboard, and only linked dashboards
* that the user has permission to update will be synced.
*
* To **link** or **unlink** a UDD set the `lookml_link_id` property with [update_dashboard()](#!/Dashboard/update_dashboard)
*
* @param {String} lookml_dashboard_id Id of LookML dashboard, in the form 'model::dashboardname'
* @param {WriteDashboard} body
* @param {Boolean} raw_locale If true, and this dashboard is localized, export it with the raw keys, not localized.
*
* PATCH /dashboards/{lookml_dashboard_id}/sync -> ByteArray
*/
@JvmOverloads fun sync_lookml_dashboard(
lookml_dashboard_id: String,
body: WriteDashboard,
raw_locale: Boolean? = null
) : SDKResponse {
val path_lookml_dashboard_id = encodeParam(lookml_dashboard_id)
return this.patch<ByteArray>("/dashboards/${path_lookml_dashboard_id}/sync",
mapOf("raw_locale" to raw_locale), body)
}
/**
* ### Get information about a dashboard
*
* Returns the full details of the identified dashboard object
*
* Get a **summary list** of all active dashboards with [all_dashboards()](#!/Dashboard/all_dashboards)
*
* You can **Search** for dashboards with [search_dashboards()](#!/Dashboard/search_dashboards)
*
* @param {String} dashboard_id Id of dashboard
* @param {String} fields Requested fields.
*
* GET /dashboards/{dashboard_id} -> ByteArray
*/
@JvmOverloads fun dashboard(
dashboard_id: String,
fields: String? = null
) : SDKResponse {
val path_dashboard_id = encodeParam(dashboard_id)
return this.get<ByteArray>("/dashboards/${path_dashboard_id}",
mapOf("fields" to fields))
}
/**
* ### Update a dashboard
*
* You can use this function to change the string and integer properties of
* a dashboard. Nested objects such as filters, dashboard elements, or dashboard layout components
* cannot be modified by this function - use the update functions for the respective
* nested object types (like [update_dashboard_filter()](#!/3.1/Dashboard/update_dashboard_filter) to change a filter)
* to modify nested objects referenced by a dashboard.
*
* If you receive a 422 error response when updating a dashboard, be sure to look at the
* response body for information about exactly which fields are missing or contain invalid data.
*
* @param {String} dashboard_id Id of dashboard
* @param {WriteDashboard} body
*
* PATCH /dashboards/{dashboard_id} -> ByteArray
*/
fun update_dashboard(
dashboard_id: String,
body: WriteDashboard
) : SDKResponse {
val path_dashboard_id = encodeParam(dashboard_id)
return this.patch<ByteArray>("/dashboards/${path_dashboard_id}", mapOf(), body)
}
/**
* ### Delete the dashboard with the specified id
*
* Permanently **deletes** a dashboard. (The dashboard cannot be recovered after this operation.)
*
* "Soft" delete or hide a dashboard by setting its `deleted` status to `True` with [update_dashboard()](#!/Dashboard/update_dashboard).
*
* Note: When a dashboard is deleted in the UI, it is soft deleted. Use this API call to permanently remove it, if desired.
*
* @param {String} dashboard_id Id of dashboard
*
* DELETE /dashboards/{dashboard_id} -> ByteArray
*/
fun delete_dashboard(
dashboard_id: String
) : SDKResponse {
val path_dashboard_id = encodeParam(dashboard_id)
return this.delete<ByteArray>("/dashboards/${path_dashboard_id}", mapOf())
}
/**
* ### Get Aggregate Table LookML for Each Query on a Dahboard
*
* Returns a JSON object that contains the dashboard id and Aggregate Table lookml
*
* @param {String} dashboard_id Id of dashboard
*
* GET /dashboards/aggregate_table_lookml/{dashboard_id} -> ByteArray
*/
fun dashboard_aggregate_table_lookml(
dashboard_id: String
) : SDKResponse {
val path_dashboard_id = encodeParam(dashboard_id)
return this.get<ByteArray>("/dashboards/aggregate_table_lookml/${path_dashboard_id}", mapOf())
}
/**
* ### Get lookml of a UDD
*
* Returns a JSON object that contains the dashboard id and the full lookml
*
* @param {String} dashboard_id Id of dashboard
*
* GET /dashboards/lookml/{dashboard_id} -> ByteArray
*/
fun dashboard_lookml(
dashboard_id: String
) : SDKResponse {
val path_dashboard_id = encodeParam(dashboard_id)
return this.get<ByteArray>("/dashboards/lookml/${path_dashboard_id}", mapOf())
}
/**
* ### Move an existing dashboard
*
* Moves a dashboard to a specified folder, and returns the moved dashboard.
*
* `dashboard_id` and `folder_id` are required.
* `dashboard_id` and `folder_id` must already exist, and `folder_id` must be different from the current `folder_id` of the dashboard.
*
* @param {String} dashboard_id Dashboard id to move.
* @param {String} folder_id Folder id to move to.
*
* PATCH /dashboards/{dashboard_id}/move -> ByteArray
*/
fun move_dashboard(
dashboard_id: String,
folder_id: String
) : SDKResponse {
val path_dashboard_id = encodeParam(dashboard_id)
return this.patch<ByteArray>("/dashboards/${path_dashboard_id}/move",
mapOf("folder_id" to folder_id))
}
/**
* ### Creates a dashboard object based on LookML Dashboard YAML, and returns the details of the newly created dashboard.
*
* If a dashboard exists with the YAML-defined "preferred_slug", the new dashboard will overwrite it. Otherwise, a new
* dashboard will be created. Note that when a dashboard is overwritten, alerts will not be maintained.
*
* If a folder_id is specified: new dashboards will be placed in that folder, and overwritten dashboards will be moved to it
* If the folder_id isn't specified: new dashboards will be placed in the caller's personal folder, and overwritten dashboards
* will remain where they were
*
* LookML must contain valid LookML YAML code. It's recommended to use the LookML format returned
* from [dashboard_lookml()](#!/Dashboard/dashboard_lookml) as the input LookML (newlines replaced with
* ).
*
* Note that the created dashboard is not linked to any LookML Dashboard,
* i.e. [sync_lookml_dashboard()](#!/Dashboard/sync_lookml_dashboard) will not update dashboards created by this method.
*
* @param {WriteDashboardLookml} body
*
* POST /dashboards/lookml -> ByteArray
*/
fun import_dashboard_from_lookml(
body: WriteDashboardLookml
) : SDKResponse {
return this.post<ByteArray>("/dashboards/lookml", mapOf(), body)
}
/**
* # DEPRECATED: Use [import_dashboard_from_lookml()](#!/Dashboard/import_dashboard_from_lookml)
*
* @param {WriteDashboardLookml} body
*
* POST /dashboards/from_lookml -> ByteArray
*/
fun create_dashboard_from_lookml(
body: WriteDashboardLookml
) : SDKResponse {
return this.post<ByteArray>("/dashboards/from_lookml", mapOf(), body)
}
/**
* ### Copy an existing dashboard
*
* Creates a copy of an existing dashboard, in a specified folder, and returns the copied dashboard.
*
* `dashboard_id` is required, `dashboard_id` and `folder_id` must already exist if specified.
* `folder_id` will default to the existing folder.
*
* If a dashboard with the same title already exists in the target folder, the copy will have '(copy)'
* or '(copy <# of copies>)' appended.
*
* @param {String} dashboard_id Dashboard id to copy.
* @param {String} folder_id Folder id to copy to.
*
* POST /dashboards/{dashboard_id}/copy -> ByteArray
*/
@JvmOverloads fun copy_dashboard(
dashboard_id: String,
folder_id: String? = null
) : SDKResponse {
val path_dashboard_id = encodeParam(dashboard_id)
return this.post<ByteArray>("/dashboards/${path_dashboard_id}/copy",
mapOf("folder_id" to folder_id))
}
/**
* ### Search Dashboard Elements
*
* Returns an **array of DashboardElement objects** that match the specified search criteria.
*
* If multiple search params are given and `filter_or` is FALSE or not specified,
* search params are combined in a logical AND operation.
* Only rows that match *all* search param criteria will be returned.
*
* If `filter_or` is TRUE, multiple search params are combined in a logical OR operation.
* Results will include rows that match **any** of the search criteria.
*
* String search params use case-insensitive matching.
* String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions.
* example="dan%" will match "danger" and "Danzig" but not "David"
* example="D_m%" will match "Damage" and "dump"
*
* Integer search params can accept a single value or a comma separated list of values. The multiple
* values will be combined under a logical OR operation - results will match at least one of
* the given values.
*
* Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match
* or exclude (respectively) rows where the column is null.
*
* Boolean search params accept only "true" and "false" as values.
*
* @param {String} dashboard_id Select elements that refer to a given dashboard id
* @param {String} look_id Select elements that refer to a given look id
* @param {String} title Match the title of element
* @param {Boolean} deleted Select soft-deleted dashboard elements
* @param {String} fields Requested fields.
* @param {Boolean} filter_or Combine given search criteria in a boolean OR expression
* @param {String} sorts Fields to sort by. Sortable fields: [:look_id, :dashboard_id, :deleted, :title]
*
* GET /dashboard_elements/search -> ByteArray
*/
@JvmOverloads fun search_dashboard_elements(
dashboard_id: String? = null,
look_id: String? = null,
title: String? = null,
deleted: Boolean? = null,
fields: String? = null,
filter_or: Boolean? = null,
sorts: String? = null
) : SDKResponse {
return this.get<ByteArray>("/dashboard_elements/search",
mapOf("dashboard_id" to dashboard_id,
"look_id" to look_id,
"title" to title,
"deleted" to deleted,
"fields" to fields,
"filter_or" to filter_or,
"sorts" to sorts))
}
/**
* ### Get information about the dashboard element with a specific id.
*
* @param {String} dashboard_element_id Id of dashboard element
* @param {String} fields Requested fields.
*
* GET /dashboard_elements/{dashboard_element_id} -> ByteArray
*/
@JvmOverloads fun dashboard_element(
dashboard_element_id: String,
fields: String? = null
) : SDKResponse {
val path_dashboard_element_id = encodeParam(dashboard_element_id)
return this.get<ByteArray>("/dashboard_elements/${path_dashboard_element_id}",
mapOf("fields" to fields))
}
/**
* ### Update the dashboard element with a specific id.
*
* @param {String} dashboard_element_id Id of dashboard element
* @param {WriteDashboardElement} body
* @param {String} fields Requested fields.
*
* PATCH /dashboard_elements/{dashboard_element_id} -> ByteArray
*/
@JvmOverloads fun update_dashboard_element(
dashboard_element_id: String,
body: WriteDashboardElement,
fields: String? = null
) : SDKResponse {
val path_dashboard_element_id = encodeParam(dashboard_element_id)
return this.patch<ByteArray>("/dashboard_elements/${path_dashboard_element_id}",
mapOf("fields" to fields), body)
}
/**
* ### Delete a dashboard element with a specific id.
*
* @param {String} dashboard_element_id Id of dashboard element
*
* DELETE /dashboard_elements/{dashboard_element_id} -> ByteArray
*/
fun delete_dashboard_element(
dashboard_element_id: String
) : SDKResponse {
val path_dashboard_element_id = encodeParam(dashboard_element_id)
return this.delete<ByteArray>("/dashboard_elements/${path_dashboard_element_id}", mapOf())
}
/**
* ### Get information about all the dashboard elements on a dashboard with a specific id.
*
* @param {String} dashboard_id Id of dashboard
* @param {String} fields Requested fields.
*
* GET /dashboards/{dashboard_id}/dashboard_elements -> ByteArray
*/
@JvmOverloads fun dashboard_dashboard_elements(
dashboard_id: String,
fields: String? = null
) : SDKResponse {
val path_dashboard_id = encodeParam(dashboard_id)
return this.get<ByteArray>("/dashboards/${path_dashboard_id}/dashboard_elements",
mapOf("fields" to fields))
}
/**
* ### Create a dashboard element on the dashboard with a specific id.
*
* @param {WriteDashboardElement} body
* @param {String} fields Requested fields.
* @param {Boolean} apply_filters Apply relevant filters on dashboard to this tile
*
* POST /dashboard_elements -> ByteArray
*/
@JvmOverloads fun create_dashboard_element(
body: WriteDashboardElement,
fields: String? = null,
apply_filters: Boolean? = null
) : SDKResponse {
return this.post<ByteArray>("/dashboard_elements",
mapOf("fields" to fields,
"apply_filters" to apply_filters), body)
}
/**
* ### Get information about the dashboard filters with a specific id.
*
* @param {String} dashboard_filter_id Id of dashboard filters
* @param {String} fields Requested fields.
*
* GET /dashboard_filters/{dashboard_filter_id} -> ByteArray
*/
@JvmOverloads fun dashboard_filter(
dashboard_filter_id: String,
fields: String? = null
) : SDKResponse {
val path_dashboard_filter_id = encodeParam(dashboard_filter_id)
return this.get<ByteArray>("/dashboard_filters/${path_dashboard_filter_id}",
mapOf("fields" to fields))
}
/**
* ### Update the dashboard filter with a specific id.
*
* @param {String} dashboard_filter_id Id of dashboard filter
* @param {WriteDashboardFilter} body
* @param {String} fields Requested fields.
*
* PATCH /dashboard_filters/{dashboard_filter_id} -> ByteArray
*/
@JvmOverloads fun update_dashboard_filter(
dashboard_filter_id: String,
body: WriteDashboardFilter,
fields: String? = null
) : SDKResponse {
val path_dashboard_filter_id = encodeParam(dashboard_filter_id)
return this.patch<ByteArray>("/dashboard_filters/${path_dashboard_filter_id}",
mapOf("fields" to fields), body)
}
/**
* ### Delete a dashboard filter with a specific id.
*
* @param {String} dashboard_filter_id Id of dashboard filter
*
* DELETE /dashboard_filters/{dashboard_filter_id} -> ByteArray
*/
fun delete_dashboard_filter(
dashboard_filter_id: String
) : SDKResponse {
val path_dashboard_filter_id = encodeParam(dashboard_filter_id)
return this.delete<ByteArray>("/dashboard_filters/${path_dashboard_filter_id}", mapOf())
}
/**
* ### Get information about all the dashboard filters on a dashboard with a specific id.
*
* @param {String} dashboard_id Id of dashboard
* @param {String} fields Requested fields.
*
* GET /dashboards/{dashboard_id}/dashboard_filters -> ByteArray
*/
@JvmOverloads fun dashboard_dashboard_filters(
dashboard_id: String,
fields: String? = null
) : SDKResponse {
val path_dashboard_id = encodeParam(dashboard_id)
return this.get<ByteArray>("/dashboards/${path_dashboard_id}/dashboard_filters",
mapOf("fields" to fields))
}
/**
* ### Create a dashboard filter on the dashboard with a specific id.
*
* @param {WriteCreateDashboardFilter} body
* @param {String} fields Requested fields
*
* POST /dashboard_filters -> ByteArray
*/
@JvmOverloads fun create_dashboard_filter(
body: WriteCreateDashboardFilter,
fields: String? = null
) : SDKResponse {
return this.post<ByteArray>("/dashboard_filters",
mapOf("fields" to fields), body)
}
/**
* ### Get information about the dashboard elements with a specific id.
*
* @param {String} dashboard_layout_component_id Id of dashboard layout component
* @param {String} fields Requested fields.
*
* GET /dashboard_layout_components/{dashboard_layout_component_id} -> ByteArray
*/
@JvmOverloads fun dashboard_layout_component(
dashboard_layout_component_id: String,
fields: String? = null
) : SDKResponse {
val path_dashboard_layout_component_id = encodeParam(dashboard_layout_component_id)
return this.get<ByteArray>("/dashboard_layout_components/${path_dashboard_layout_component_id}",
mapOf("fields" to fields))
}
/**
* ### Update the dashboard element with a specific id.
*
* @param {String} dashboard_layout_component_id Id of dashboard layout component
* @param {WriteDashboardLayoutComponent} body
* @param {String} fields Requested fields.
*
* PATCH /dashboard_layout_components/{dashboard_layout_component_id} -> ByteArray
*/
@JvmOverloads fun update_dashboard_layout_component(
dashboard_layout_component_id: String,
body: WriteDashboardLayoutComponent,
fields: String? = null
) : SDKResponse {
val path_dashboard_layout_component_id = encodeParam(dashboard_layout_component_id)
return this.patch<ByteArray>("/dashboard_layout_components/${path_dashboard_layout_component_id}",
mapOf("fields" to fields), body)
}
/**
* ### Get information about all the dashboard layout components for a dashboard layout with a specific id.
*
* @param {String} dashboard_layout_id Id of dashboard layout component
* @param {String} fields Requested fields.
*
* GET /dashboard_layouts/{dashboard_layout_id}/dashboard_layout_components -> ByteArray
*/
@JvmOverloads fun dashboard_layout_dashboard_layout_components(
dashboard_layout_id: String,
fields: String? = null
) : SDKResponse {
val path_dashboard_layout_id = encodeParam(dashboard_layout_id)
return this.get<ByteArray>("/dashboard_layouts/${path_dashboard_layout_id}/dashboard_layout_components",
mapOf("fields" to fields))
}
/**
* ### Get information about the dashboard layouts with a specific id.
*
* @param {String} dashboard_layout_id Id of dashboard layouts
* @param {String} fields Requested fields.
*
* GET /dashboard_layouts/{dashboard_layout_id} -> ByteArray
*/
@JvmOverloads fun dashboard_layout(
dashboard_layout_id: String,
fields: String? = null
) : SDKResponse {
val path_dashboard_layout_id = encodeParam(dashboard_layout_id)
return this.get<ByteArray>("/dashboard_layouts/${path_dashboard_layout_id}",
mapOf("fields" to fields))
}
/**
* ### Update the dashboard layout with a specific id.
*
* @param {String} dashboard_layout_id Id of dashboard layout
* @param {WriteDashboardLayout} body
* @param {String} fields Requested fields.
*
* PATCH /dashboard_layouts/{dashboard_layout_id} -> ByteArray
*/
@JvmOverloads fun update_dashboard_layout(
dashboard_layout_id: String,
body: WriteDashboardLayout,
fields: String? = null
) : SDKResponse {
val path_dashboard_layout_id = encodeParam(dashboard_layout_id)
return this.patch<ByteArray>("/dashboard_layouts/${path_dashboard_layout_id}",
mapOf("fields" to fields), body)
}
/**
* ### Delete a dashboard layout with a specific id.
*
* @param {String} dashboard_layout_id Id of dashboard layout
*
* DELETE /dashboard_layouts/{dashboard_layout_id} -> ByteArray
*/
fun delete_dashboard_layout(
dashboard_layout_id: String
) : SDKResponse {
val path_dashboard_layout_id = encodeParam(dashboard_layout_id)
return this.delete<ByteArray>("/dashboard_layouts/${path_dashboard_layout_id}", mapOf())
}
/**
* ### Get information about all the dashboard elements on a dashboard with a specific id.
*
* @param {String} dashboard_id Id of dashboard
* @param {String} fields Requested fields.
*
* GET /dashboards/{dashboard_id}/dashboard_layouts -> ByteArray
*/
@JvmOverloads fun dashboard_dashboard_layouts(
dashboard_id: String,
fields: String? = null
) : SDKResponse {
val path_dashboard_id = encodeParam(dashboard_id)
return this.get<ByteArray>("/dashboards/${path_dashboard_id}/dashboard_layouts",
mapOf("fields" to fields))
}
/**
* ### Create a dashboard layout on the dashboard with a specific id.
*
* @param {WriteDashboardLayout} body
* @param {String} fields Requested fields.
*
* POST /dashboard_layouts -> ByteArray
*/
@JvmOverloads fun create_dashboard_layout(
body: WriteDashboardLayout,
fields: String? = null
) : SDKResponse {
return this.post<ByteArray>("/dashboard_layouts",
mapOf("fields" to fields), body)
}
//endregion Dashboard: Manage Dashboards
//region DataAction: Run Data Actions
/**
* Perform a data action. The data action object can be obtained from query results, and used to perform an arbitrary action.
*
* @param {DataActionRequest} body
*
* POST /data_actions -> ByteArray
*/
fun perform_data_action(
body: DataActionRequest
) : SDKResponse {
return this.post<ByteArray>("/data_actions", mapOf(), body)
}
/**
* For some data actions, the remote server may supply a form requesting further user input. This endpoint takes a data action, asks the remote server to generate a form for it, and returns that form to you for presentation to the user.
*
* @param {Map<String,Any>} body
*
* POST /data_actions/form -> ByteArray
*/
fun fetch_remote_data_action_form(
body: Map<String,Any>
) : SDKResponse {
return this.post<ByteArray>("/data_actions/form", mapOf(), body)
}
//endregion DataAction: Run Data Actions
//region Datagroup: Manage Datagroups
/**
* ### Get information about all datagroups.
*
* GET /datagroups -> ByteArray
*/
fun all_datagroups(
) : SDKResponse {
return this.get<ByteArray>("/datagroups", mapOf())
}
/**
* ### Get information about a datagroup.
*
* @param {String} datagroup_id ID of datagroup.
*
* GET /datagroups/{datagroup_id} -> ByteArray
*/
fun datagroup(
datagroup_id: String
) : SDKResponse {
val path_datagroup_id = encodeParam(datagroup_id)
return this.get<ByteArray>("/datagroups/${path_datagroup_id}", mapOf())
}
/**
* ### Update a datagroup using the specified params.
*
* @param {String} datagroup_id ID of datagroup.
* @param {WriteDatagroup} body
*
* PATCH /datagroups/{datagroup_id} -> ByteArray
*/
fun update_datagroup(
datagroup_id: String,
body: WriteDatagroup
) : SDKResponse {
val path_datagroup_id = encodeParam(datagroup_id)
return this.patch<ByteArray>("/datagroups/${path_datagroup_id}", mapOf(), body)
}
//endregion Datagroup: Manage Datagroups
//region DerivedTable: View Derived Table graphs
/**
* ### Discover information about derived tables
*
* @param {String} model The name of the Lookml model.
* @param {String} format The format of the graph. Valid values are [dot]. Default is `dot`
* @param {String} color Color denoting the build status of the graph. Grey = not built, green = built, yellow = building, red = error.
*
* GET /derived_table/graph/model/{model} -> ByteArray
*/
@JvmOverloads fun graph_derived_tables_for_model(
model: String,
format: String? = null,
color: String? = null
) : SDKResponse {
val path_model = encodeParam(model)
return this.get<ByteArray>("/derived_table/graph/model/${path_model}",
mapOf("format" to format,
"color" to color))
}
/**
* ### Get the subgraph representing this derived table and its dependencies.
*
* @param {String} view The derived table's view name.
* @param {String} models The models where this derived table is defined.
* @param {String} workspace The model directory to look in, either `dev` or `production`.
*
* GET /derived_table/graph/view/{view} -> ByteArray
*/
@JvmOverloads fun graph_derived_tables_for_view(
view: String,
models: String? = null,
workspace: String? = null
) : SDKResponse {
val path_view = encodeParam(view)
return this.get<ByteArray>("/derived_table/graph/view/${path_view}",
mapOf("models" to models,
"workspace" to workspace))
}
/**
* Enqueue materialization for a PDT with the given model name and view name
*
* @param {String} model_name The model of the PDT to start building.
* @param {String} view_name The view name of the PDT to start building.
* @param {String} force_rebuild Force rebuild of required dependent PDTs, even if they are already materialized.
* @param {String} force_full_incremental Force involved incremental PDTs to fully re-materialize.
* @param {String} workspace Workspace in which to materialize selected PDT ('dev' or default 'production').
* @param {String} source The source of this request.
*
* GET /derived_table/{model_name}/{view_name}/start -> ByteArray
*/
@JvmOverloads fun start_pdt_build(
model_name: String,
view_name: String,
force_rebuild: String? = null,
force_full_incremental: String? = null,
workspace: String? = null,
source: String? = null
) : SDKResponse {
val path_model_name = encodeParam(model_name)
val path_view_name = encodeParam(view_name)
return this.get<ByteArray>("/derived_table/${path_model_name}/${path_view_name}/start",
mapOf("force_rebuild" to force_rebuild,
"force_full_incremental" to force_full_incremental,
"workspace" to workspace,
"source" to source))
}
/**
* Check status of PDT materialization
*
* @param {String} materialization_id The materialization id to check status for.
*
* GET /derived_table/{materialization_id}/status -> ByteArray
*/
fun check_pdt_build(
materialization_id: String
) : SDKResponse {
val path_materialization_id = encodeParam(materialization_id)
return this.get<ByteArray>("/derived_table/${path_materialization_id}/status", mapOf())
}
/**
* Stop a PDT materialization
*
* @param {String} materialization_id The materialization id to stop.
* @param {String} source The source of this request.
*
* GET /derived_table/{materialization_id}/stop -> ByteArray
*/
@JvmOverloads fun stop_pdt_build(
materialization_id: String,
source: String? = null
) : SDKResponse {
val path_materialization_id = encodeParam(materialization_id)
return this.get<ByteArray>("/derived_table/${path_materialization_id}/stop",
mapOf("source" to source))
}
//endregion DerivedTable: View Derived Table graphs
//region Folder: Manage Folders
/**
* Search for folders by creator id, parent id, name, etc
*
* @param {String} fields Requested fields.
* @param {Long} page DEPRECATED. Use limit and offset instead. Return only page N of paginated results
* @param {Long} per_page DEPRECATED. Use limit and offset instead. Return N rows of data per page
* @param {Long} limit Number of results to return. (used with offset and takes priority over page and per_page)
* @param {Long} offset Number of results to skip before returning any. (used with limit and takes priority over page and per_page)
* @param {String} sorts Fields to sort by.
* @param {String} name Match Space title.
* @param {String} id Match Space id
* @param {String} parent_id Filter on a children of a particular folder.
* @param {String} creator_id Filter on folder created by a particular user.
* @param {Boolean} filter_or Combine given search criteria in a boolean OR expression
* @param {Boolean} is_shared_root Match is shared root
*
* GET /folders/search -> ByteArray
*/
@JvmOverloads fun search_folders(
fields: String? = null,
page: Long? = null,
per_page: Long? = null,
limit: Long? = null,
offset: Long? = null,
sorts: String? = null,
name: String? = null,
id: String? = null,
parent_id: String? = null,
creator_id: String? = null,
filter_or: Boolean? = null,
is_shared_root: Boolean? = null
) : SDKResponse {
return this.get<ByteArray>("/folders/search",
mapOf("fields" to fields,
"page" to page,
"per_page" to per_page,
"limit" to limit,
"offset" to offset,
"sorts" to sorts,
"name" to name,
"id" to id,
"parent_id" to parent_id,
"creator_id" to creator_id,
"filter_or" to filter_or,
"is_shared_root" to is_shared_root))
}
/**
* ### Get information about the folder with a specific id.
*
* @param {String} folder_id Id of folder
* @param {String} fields Requested fields.
*
* GET /folders/{folder_id} -> ByteArray
*/
@JvmOverloads fun folder(
folder_id: String,
fields: String? = null
) : SDKResponse {
val path_folder_id = encodeParam(folder_id)
return this.get<ByteArray>("/folders/${path_folder_id}",
mapOf("fields" to fields))
}
/**
* ### Update the folder with a specific id.
*
* @param {String} folder_id Id of folder
* @param {UpdateFolder} body
*
* PATCH /folders/{folder_id} -> ByteArray
*/
fun update_folder(
folder_id: String,
body: UpdateFolder
) : SDKResponse {
val path_folder_id = encodeParam(folder_id)
return this.patch<ByteArray>("/folders/${path_folder_id}", mapOf(), body)
}
/**
* ### Delete the folder with a specific id including any children folders.
* **DANGER** this will delete all looks and dashboards in the folder.
*
* @param {String} folder_id Id of folder
*
* DELETE /folders/{folder_id} -> ByteArray
*/
fun delete_folder(
folder_id: String
) : SDKResponse {
val path_folder_id = encodeParam(folder_id)
return this.delete<ByteArray>("/folders/${path_folder_id}", mapOf())
}
/**
* ### Get information about all folders.
*
* In API 3.x, this will not return empty personal folders, unless they belong to the calling user,
* or if they contain soft-deleted content.
*
* In API 4.0+, all personal folders will be returned.
*
* @param {String} fields Requested fields.
*
* GET /folders -> ByteArray
*/
@JvmOverloads fun all_folders(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/folders",
mapOf("fields" to fields))
}
/**
* ### Create a folder with specified information.
*
* Caller must have permission to edit the parent folder and to create folders, otherwise the request
* returns 404 Not Found.
*
* @param {CreateFolder} body
*
* POST /folders -> ByteArray
*/
fun create_folder(
body: CreateFolder
) : SDKResponse {
return this.post<ByteArray>("/folders", mapOf(), body)
}
/**
* ### Get the children of a folder.
*
* @param {String} folder_id Id of folder
* @param {String} fields Requested fields.
* @param {Long} page DEPRECATED. Use limit and offset instead. Return only page N of paginated results
* @param {Long} per_page DEPRECATED. Use limit and offset instead. Return N rows of data per page
* @param {Long} limit Number of results to return. (used with offset and takes priority over page and per_page)
* @param {Long} offset Number of results to skip before returning any. (used with limit and takes priority over page and per_page)
* @param {String} sorts Fields to sort by.
*
* GET /folders/{folder_id}/children -> ByteArray
*/
@JvmOverloads fun folder_children(
folder_id: String,
fields: String? = null,
page: Long? = null,
per_page: Long? = null,
limit: Long? = null,
offset: Long? = null,
sorts: String? = null
) : SDKResponse {
val path_folder_id = encodeParam(folder_id)
return this.get<ByteArray>("/folders/${path_folder_id}/children",
mapOf("fields" to fields,
"page" to page,
"per_page" to per_page,
"limit" to limit,
"offset" to offset,
"sorts" to sorts))
}
/**
* ### Search the children of a folder
*
* @param {String} folder_id Id of folder
* @param {String} fields Requested fields.
* @param {String} sorts Fields to sort by.
* @param {String} name Match folder name.
*
* GET /folders/{folder_id}/children/search -> ByteArray
*/
@JvmOverloads fun folder_children_search(
folder_id: String,
fields: String? = null,
sorts: String? = null,
name: String? = null
) : SDKResponse {
val path_folder_id = encodeParam(folder_id)
return this.get<ByteArray>("/folders/${path_folder_id}/children/search",
mapOf("fields" to fields,
"sorts" to sorts,
"name" to name))
}
/**
* ### Get the parent of a folder
*
* @param {String} folder_id Id of folder
* @param {String} fields Requested fields.
*
* GET /folders/{folder_id}/parent -> ByteArray
*/
@JvmOverloads fun folder_parent(
folder_id: String,
fields: String? = null
) : SDKResponse {
val path_folder_id = encodeParam(folder_id)
return this.get<ByteArray>("/folders/${path_folder_id}/parent",
mapOf("fields" to fields))
}
/**
* ### Get the ancestors of a folder
*
* @param {String} folder_id Id of folder
* @param {String} fields Requested fields.
*
* GET /folders/{folder_id}/ancestors -> ByteArray
*/
@JvmOverloads fun folder_ancestors(
folder_id: String,
fields: String? = null
) : SDKResponse {
val path_folder_id = encodeParam(folder_id)
return this.get<ByteArray>("/folders/${path_folder_id}/ancestors",
mapOf("fields" to fields))
}
/**
* ### Get all looks in a folder.
* In API 3.x, this will return all looks in a folder, including looks in the trash.
* In API 4.0+, all looks in a folder will be returned, excluding looks in the trash.
*
* @param {String} folder_id Id of folder
* @param {String} fields Requested fields.
*
* GET /folders/{folder_id}/looks -> ByteArray
*/
@JvmOverloads fun folder_looks(
folder_id: String,
fields: String? = null
) : SDKResponse {
val path_folder_id = encodeParam(folder_id)
return this.get<ByteArray>("/folders/${path_folder_id}/looks",
mapOf("fields" to fields))
}
/**
* ### Get the dashboards in a folder
*
* @param {String} folder_id Id of folder
* @param {String} fields Requested fields.
*
* GET /folders/{folder_id}/dashboards -> ByteArray
*/
@JvmOverloads fun folder_dashboards(
folder_id: String,
fields: String? = null
) : SDKResponse {
val path_folder_id = encodeParam(folder_id)
return this.get<ByteArray>("/folders/${path_folder_id}/dashboards",
mapOf("fields" to fields))
}
//endregion Folder: Manage Folders
//region Group: Manage Groups
/**
* ### Get information about all groups.
*
* @param {String} fields Requested fields.
* @param {Long} page DEPRECATED. Use limit and offset instead. Return only page N of paginated results
* @param {Long} per_page DEPRECATED. Use limit and offset instead. Return N rows of data per page
* @param {Long} limit Number of results to return. (used with offset and takes priority over page and per_page)
* @param {Long} offset Number of results to skip before returning any. (used with limit and takes priority over page and per_page)
* @param {String} sorts Fields to sort by.
* @param {DelimArray<String>} ids Optional of ids to get specific groups.
* @param {String} content_metadata_id Id of content metadata to which groups must have access.
* @param {Boolean} can_add_to_content_metadata Select only groups that either can/cannot be given access to content.
*
* GET /groups -> ByteArray
*/
@JvmOverloads fun all_groups(
fields: String? = null,
page: Long? = null,
per_page: Long? = null,
limit: Long? = null,
offset: Long? = null,
sorts: String? = null,
ids: DelimArray<String>? = null,
content_metadata_id: String? = null,
can_add_to_content_metadata: Boolean? = null
) : SDKResponse {
return this.get<ByteArray>("/groups",
mapOf("fields" to fields,
"page" to page,
"per_page" to per_page,
"limit" to limit,
"offset" to offset,
"sorts" to sorts,
"ids" to ids,
"content_metadata_id" to content_metadata_id,
"can_add_to_content_metadata" to can_add_to_content_metadata))
}
/**
* ### Creates a new group (admin only).
*
* @param {WriteGroup} body
* @param {String} fields Requested fields.
*
* POST /groups -> ByteArray
*/
@JvmOverloads fun create_group(
body: WriteGroup,
fields: String? = null
) : SDKResponse {
return this.post<ByteArray>("/groups",
mapOf("fields" to fields), body)
}
/**
* ### Search groups
*
* Returns all group records that match the given search criteria.
*
* If multiple search params are given and `filter_or` is FALSE or not specified,
* search params are combined in a logical AND operation.
* Only rows that match *all* search param criteria will be returned.
*
* If `filter_or` is TRUE, multiple search params are combined in a logical OR operation.
* Results will include rows that match **any** of the search criteria.
*
* String search params use case-insensitive matching.
* String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions.
* example="dan%" will match "danger" and "Danzig" but not "David"
* example="D_m%" will match "Damage" and "dump"
*
* Integer search params can accept a single value or a comma separated list of values. The multiple
* values will be combined under a logical OR operation - results will match at least one of
* the given values.
*
* Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match
* or exclude (respectively) rows where the column is null.
*
* Boolean search params accept only "true" and "false" as values.
*
* @param {String} fields Requested fields.
* @param {Long} limit Number of results to return (used with `offset`).
* @param {Long} offset Number of results to skip before returning any (used with `limit`).
* @param {String} sorts Fields to sort by.
* @param {Boolean} filter_or Combine given search criteria in a boolean OR expression
* @param {String} id Match group id.
* @param {String} name Match group name.
* @param {String} external_group_id Match group external_group_id.
* @param {Boolean} externally_managed Match group externally_managed.
* @param {Boolean} externally_orphaned Match group externally_orphaned.
*
* GET /groups/search -> ByteArray
*/
@JvmOverloads fun search_groups(
fields: String? = null,
limit: Long? = null,
offset: Long? = null,
sorts: String? = null,
filter_or: Boolean? = null,
id: String? = null,
name: String? = null,
external_group_id: String? = null,
externally_managed: Boolean? = null,
externally_orphaned: Boolean? = null
) : SDKResponse {
return this.get<ByteArray>("/groups/search",
mapOf("fields" to fields,
"limit" to limit,
"offset" to offset,
"sorts" to sorts,
"filter_or" to filter_or,
"id" to id,
"name" to name,
"external_group_id" to external_group_id,
"externally_managed" to externally_managed,
"externally_orphaned" to externally_orphaned))
}
/**
* ### Search groups include roles
*
* Returns all group records that match the given search criteria, and attaches any associated roles.
*
* If multiple search params are given and `filter_or` is FALSE or not specified,
* search params are combined in a logical AND operation.
* Only rows that match *all* search param criteria will be returned.
*
* If `filter_or` is TRUE, multiple search params are combined in a logical OR operation.
* Results will include rows that match **any** of the search criteria.
*
* String search params use case-insensitive matching.
* String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions.
* example="dan%" will match "danger" and "Danzig" but not "David"
* example="D_m%" will match "Damage" and "dump"
*
* Integer search params can accept a single value or a comma separated list of values. The multiple
* values will be combined under a logical OR operation - results will match at least one of
* the given values.
*
* Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match
* or exclude (respectively) rows where the column is null.
*
* Boolean search params accept only "true" and "false" as values.
*
* @param {String} fields Requested fields.
* @param {Long} limit Number of results to return (used with `offset`).
* @param {Long} offset Number of results to skip before returning any (used with `limit`).
* @param {String} sorts Fields to sort by.
* @param {Boolean} filter_or Combine given search criteria in a boolean OR expression
* @param {String} id Match group id.
* @param {String} name Match group name.
* @param {String} external_group_id Match group external_group_id.
* @param {Boolean} externally_managed Match group externally_managed.
* @param {Boolean} externally_orphaned Match group externally_orphaned.
*
* GET /groups/search/with_roles -> ByteArray
*/
@JvmOverloads fun search_groups_with_roles(
fields: String? = null,
limit: Long? = null,
offset: Long? = null,
sorts: String? = null,
filter_or: Boolean? = null,
id: String? = null,
name: String? = null,
external_group_id: String? = null,
externally_managed: Boolean? = null,
externally_orphaned: Boolean? = null
) : SDKResponse {
return this.get<ByteArray>("/groups/search/with_roles",
mapOf("fields" to fields,
"limit" to limit,
"offset" to offset,
"sorts" to sorts,
"filter_or" to filter_or,
"id" to id,
"name" to name,
"external_group_id" to external_group_id,
"externally_managed" to externally_managed,
"externally_orphaned" to externally_orphaned))
}
/**
* ### Search groups include hierarchy
*
* Returns all group records that match the given search criteria, and attaches
* associated role_ids and parent group_ids.
*
* If multiple search params are given and `filter_or` is FALSE or not specified,
* search params are combined in a logical AND operation.
* Only rows that match *all* search param criteria will be returned.
*
* If `filter_or` is TRUE, multiple search params are combined in a logical OR operation.
* Results will include rows that match **any** of the search criteria.
*
* String search params use case-insensitive matching.
* String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions.
* example="dan%" will match "danger" and "Danzig" but not "David"
* example="D_m%" will match "Damage" and "dump"
*
* Integer search params can accept a single value or a comma separated list of values. The multiple
* values will be combined under a logical OR operation - results will match at least one of
* the given values.
*
* Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match
* or exclude (respectively) rows where the column is null.
*
* Boolean search params accept only "true" and "false" as values.
*
* @param {String} fields Requested fields.
* @param {Long} limit Number of results to return (used with `offset`).
* @param {Long} offset Number of results to skip before returning any (used with `limit`).
* @param {String} sorts Fields to sort by.
* @param {Boolean} filter_or Combine given search criteria in a boolean OR expression
* @param {String} id Match group id.
* @param {String} name Match group name.
* @param {String} external_group_id Match group external_group_id.
* @param {Boolean} externally_managed Match group externally_managed.
* @param {Boolean} externally_orphaned Match group externally_orphaned.
*
* GET /groups/search/with_hierarchy -> ByteArray
*/
@JvmOverloads fun search_groups_with_hierarchy(
fields: String? = null,
limit: Long? = null,
offset: Long? = null,
sorts: String? = null,
filter_or: Boolean? = null,
id: String? = null,
name: String? = null,
external_group_id: String? = null,
externally_managed: Boolean? = null,
externally_orphaned: Boolean? = null
) : SDKResponse {
return this.get<ByteArray>("/groups/search/with_hierarchy",
mapOf("fields" to fields,
"limit" to limit,
"offset" to offset,
"sorts" to sorts,
"filter_or" to filter_or,
"id" to id,
"name" to name,
"external_group_id" to external_group_id,
"externally_managed" to externally_managed,
"externally_orphaned" to externally_orphaned))
}
/**
* ### Get information about a group.
*
* @param {String} group_id Id of group
* @param {String} fields Requested fields.
*
* GET /groups/{group_id} -> ByteArray
*/
@JvmOverloads fun group(
group_id: String,
fields: String? = null
) : SDKResponse {
val path_group_id = encodeParam(group_id)
return this.get<ByteArray>("/groups/${path_group_id}",
mapOf("fields" to fields))
}
/**
* ### Updates the a group (admin only).
*
* @param {String} group_id Id of group
* @param {WriteGroup} body
* @param {String} fields Requested fields.
*
* PATCH /groups/{group_id} -> ByteArray
*/
@JvmOverloads fun update_group(
group_id: String,
body: WriteGroup,
fields: String? = null
) : SDKResponse {
val path_group_id = encodeParam(group_id)
return this.patch<ByteArray>("/groups/${path_group_id}",
mapOf("fields" to fields), body)
}
/**
* ### Deletes a group (admin only).
*
* @param {String} group_id Id of group
*
* DELETE /groups/{group_id} -> ByteArray
*/
fun delete_group(
group_id: String
) : SDKResponse {
val path_group_id = encodeParam(group_id)
return this.delete<ByteArray>("/groups/${path_group_id}", mapOf())
}
/**
* ### Get information about all the groups in a group
*
* @param {String} group_id Id of group
* @param {String} fields Requested fields.
*
* GET /groups/{group_id}/groups -> ByteArray
*/
@JvmOverloads fun all_group_groups(
group_id: String,
fields: String? = null
) : SDKResponse {
val path_group_id = encodeParam(group_id)
return this.get<ByteArray>("/groups/${path_group_id}/groups",
mapOf("fields" to fields))
}
/**
* ### Adds a new group to a group.
*
* @param {String} group_id Id of group
* @param {GroupIdForGroupInclusion} body WARNING: no writeable properties found for POST, PUT, or PATCH
*
* POST /groups/{group_id}/groups -> ByteArray
*/
fun add_group_group(
group_id: String,
body: GroupIdForGroupInclusion
) : SDKResponse {
val path_group_id = encodeParam(group_id)
return this.post<ByteArray>("/groups/${path_group_id}/groups", mapOf(), body)
}
/**
* ### Get information about all the users directly included in a group.
*
* @param {String} group_id Id of group
* @param {String} fields Requested fields.
* @param {Long} page DEPRECATED. Use limit and offset instead. Return only page N of paginated results
* @param {Long} per_page DEPRECATED. Use limit and offset instead. Return N rows of data per page
* @param {Long} limit Number of results to return. (used with offset and takes priority over page and per_page)
* @param {Long} offset Number of results to skip before returning any. (used with limit and takes priority over page and per_page)
* @param {String} sorts Fields to sort by.
*
* GET /groups/{group_id}/users -> ByteArray
*/
@JvmOverloads fun all_group_users(
group_id: String,
fields: String? = null,
page: Long? = null,
per_page: Long? = null,
limit: Long? = null,
offset: Long? = null,
sorts: String? = null
) : SDKResponse {
val path_group_id = encodeParam(group_id)
return this.get<ByteArray>("/groups/${path_group_id}/users",
mapOf("fields" to fields,
"page" to page,
"per_page" to per_page,
"limit" to limit,
"offset" to offset,
"sorts" to sorts))
}
/**
* ### Adds a new user to a group.
*
* @param {String} group_id Id of group
* @param {GroupIdForGroupUserInclusion} body WARNING: no writeable properties found for POST, PUT, or PATCH
*
* POST /groups/{group_id}/users -> ByteArray
*/
fun add_group_user(
group_id: String,
body: GroupIdForGroupUserInclusion
) : SDKResponse {
val path_group_id = encodeParam(group_id)
return this.post<ByteArray>("/groups/${path_group_id}/users", mapOf(), body)
}
/**
* ### Removes a user from a group.
*
* @param {String} group_id Id of group
* @param {String} user_id Id of user to remove from group
*
* DELETE /groups/{group_id}/users/{user_id} -> ByteArray
*/
fun delete_group_user(
group_id: String,
user_id: String
) : SDKResponse {
val path_group_id = encodeParam(group_id)
val path_user_id = encodeParam(user_id)
return this.delete<ByteArray>("/groups/${path_group_id}/users/${path_user_id}", mapOf())
}
/**
* ### Removes a group from a group.
*
* @param {String} group_id Id of group
* @param {String} deleting_group_id Id of group to delete
*
* DELETE /groups/{group_id}/groups/{deleting_group_id} -> ByteArray
*/
fun delete_group_from_group(
group_id: String,
deleting_group_id: String
) : SDKResponse {
val path_group_id = encodeParam(group_id)
val path_deleting_group_id = encodeParam(deleting_group_id)
return this.delete<ByteArray>("/groups/${path_group_id}/groups/${path_deleting_group_id}", mapOf())
}
/**
* ### Set the value of a user attribute for a group.
*
* For information about how user attribute values are calculated, see [Set User Attribute Group Values](#!/UserAttribute/set_user_attribute_group_values).
*
* @param {String} group_id Id of group
* @param {String} user_attribute_id Id of user attribute
* @param {UserAttributeGroupValue} body WARNING: no writeable properties found for POST, PUT, or PATCH
*
* PATCH /groups/{group_id}/attribute_values/{user_attribute_id} -> ByteArray
*/
fun update_user_attribute_group_value(
group_id: String,
user_attribute_id: String,
body: UserAttributeGroupValue
) : SDKResponse {
val path_group_id = encodeParam(group_id)
val path_user_attribute_id = encodeParam(user_attribute_id)
return this.patch<ByteArray>("/groups/${path_group_id}/attribute_values/${path_user_attribute_id}", mapOf(), body)
}
/**
* ### Remove a user attribute value from a group.
*
* @param {String} group_id Id of group
* @param {String} user_attribute_id Id of user attribute
*
* DELETE /groups/{group_id}/attribute_values/{user_attribute_id} -> ByteArray
*/
fun delete_user_attribute_group_value(
group_id: String,
user_attribute_id: String
) : SDKResponse {
val path_group_id = encodeParam(group_id)
val path_user_attribute_id = encodeParam(user_attribute_id)
return this.delete<ByteArray>("/groups/${path_group_id}/attribute_values/${path_user_attribute_id}", mapOf())
}
//endregion Group: Manage Groups
//region Homepage: Manage Homepage
/**
* ### Get information about the primary homepage's sections.
*
* @param {String} fields Requested fields.
*
* GET /primary_homepage_sections -> ByteArray
*/
@JvmOverloads fun all_primary_homepage_sections(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/primary_homepage_sections",
mapOf("fields" to fields))
}
//endregion Homepage: Manage Homepage
//region Integration: Manage Integrations
/**
* ### Get information about all Integration Hubs.
*
* @param {String} fields Requested fields.
*
* GET /integration_hubs -> ByteArray
*/
@JvmOverloads fun all_integration_hubs(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/integration_hubs",
mapOf("fields" to fields))
}
/**
* ### Create a new Integration Hub.
*
* This API is rate limited to prevent it from being used for SSRF attacks
*
* @param {WriteIntegrationHub} body
* @param {String} fields Requested fields.
*
* POST /integration_hubs -> ByteArray
*/
@JvmOverloads fun create_integration_hub(
body: WriteIntegrationHub,
fields: String? = null
) : SDKResponse {
return this.post<ByteArray>("/integration_hubs",
mapOf("fields" to fields), body)
}
/**
* ### Get information about a Integration Hub.
*
* @param {String} integration_hub_id Id of integration_hub
* @param {String} fields Requested fields.
*
* GET /integration_hubs/{integration_hub_id} -> ByteArray
*/
@JvmOverloads fun integration_hub(
integration_hub_id: String,
fields: String? = null
) : SDKResponse {
val path_integration_hub_id = encodeParam(integration_hub_id)
return this.get<ByteArray>("/integration_hubs/${path_integration_hub_id}",
mapOf("fields" to fields))
}
/**
* ### Update a Integration Hub definition.
*
* This API is rate limited to prevent it from being used for SSRF attacks
*
* @param {String} integration_hub_id Id of integration_hub
* @param {WriteIntegrationHub} body
* @param {String} fields Requested fields.
*
* PATCH /integration_hubs/{integration_hub_id} -> ByteArray
*/
@JvmOverloads fun update_integration_hub(
integration_hub_id: String,
body: WriteIntegrationHub,
fields: String? = null
) : SDKResponse {
val path_integration_hub_id = encodeParam(integration_hub_id)
return this.patch<ByteArray>("/integration_hubs/${path_integration_hub_id}",
mapOf("fields" to fields), body)
}
/**
* ### Delete a Integration Hub.
*
* @param {String} integration_hub_id Id of integration_hub
*
* DELETE /integration_hubs/{integration_hub_id} -> ByteArray
*/
fun delete_integration_hub(
integration_hub_id: String
) : SDKResponse {
val path_integration_hub_id = encodeParam(integration_hub_id)
return this.delete<ByteArray>("/integration_hubs/${path_integration_hub_id}", mapOf())
}
/**
* Accepts the legal agreement for a given integration hub. This only works for integration hubs that have legal_agreement_required set to true and legal_agreement_signed set to false.
*
* @param {String} integration_hub_id Id of integration_hub
*
* POST /integration_hubs/{integration_hub_id}/accept_legal_agreement -> ByteArray
*/
fun accept_integration_hub_legal_agreement(
integration_hub_id: String
) : SDKResponse {
val path_integration_hub_id = encodeParam(integration_hub_id)
return this.post<ByteArray>("/integration_hubs/${path_integration_hub_id}/accept_legal_agreement", mapOf())
}
/**
* ### Get information about all Integrations.
*
* @param {String} fields Requested fields.
* @param {String} integration_hub_id Filter to a specific provider
*
* GET /integrations -> ByteArray
*/
@JvmOverloads fun all_integrations(
fields: String? = null,
integration_hub_id: String? = null
) : SDKResponse {
return this.get<ByteArray>("/integrations",
mapOf("fields" to fields,
"integration_hub_id" to integration_hub_id))
}
/**
* ### Get information about a Integration.
*
* @param {String} integration_id Id of integration
* @param {String} fields Requested fields.
*
* GET /integrations/{integration_id} -> ByteArray
*/
@JvmOverloads fun integration(
integration_id: String,
fields: String? = null
) : SDKResponse {
val path_integration_id = encodeParam(integration_id)
return this.get<ByteArray>("/integrations/${path_integration_id}",
mapOf("fields" to fields))
}
/**
* ### Update parameters on a Integration.
*
* @param {String} integration_id Id of integration
* @param {WriteIntegration} body
* @param {String} fields Requested fields.
*
* PATCH /integrations/{integration_id} -> ByteArray
*/
@JvmOverloads fun update_integration(
integration_id: String,
body: WriteIntegration,
fields: String? = null
) : SDKResponse {
val path_integration_id = encodeParam(integration_id)
return this.patch<ByteArray>("/integrations/${path_integration_id}",
mapOf("fields" to fields), body)
}
/**
* Returns the Integration form for presentation to the user.
*
* @param {String} integration_id Id of integration
* @param {Map<String,Any>} body
*
* POST /integrations/{integration_id}/form -> ByteArray
*/
@JvmOverloads fun fetch_integration_form(
integration_id: String,
body: Map<String,Any>? = null
) : SDKResponse {
val path_integration_id = encodeParam(integration_id)
return this.post<ByteArray>("/integrations/${path_integration_id}/form", mapOf(), body)
}
/**
* Tests the integration to make sure all the settings are working.
*
* @param {String} integration_id Id of integration
*
* POST /integrations/{integration_id}/test -> ByteArray
*/
fun test_integration(
integration_id: String
) : SDKResponse {
val path_integration_id = encodeParam(integration_id)
return this.post<ByteArray>("/integrations/${path_integration_id}/test", mapOf())
}
//endregion Integration: Manage Integrations
//region Look: Run and Manage Looks
/**
* ### Get information about all active Looks
*
* Returns an array of **abbreviated Look objects** describing all the looks that the caller has access to. Soft-deleted Looks are **not** included.
*
* Get the **full details** of a specific look by id with [look(id)](#!/Look/look)
*
* Find **soft-deleted looks** with [search_looks()](#!/Look/search_looks)
*
* @param {String} fields Requested fields.
*
* GET /looks -> ByteArray
*/
@JvmOverloads fun all_looks(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/looks",
mapOf("fields" to fields))
}
/**
* ### Create a Look
*
* To create a look to display query data, first create the query with [create_query()](#!/Query/create_query)
* then assign the query's id to the `query_id` property in the call to `create_look()`.
*
* To place the look into a particular space, assign the space's id to the `space_id` property
* in the call to `create_look()`.
*
* @param {WriteLookWithQuery} body
* @param {String} fields Requested fields.
*
* POST /looks -> ByteArray
*/
@JvmOverloads fun create_look(
body: WriteLookWithQuery,
fields: String? = null
) : SDKResponse {
return this.post<ByteArray>("/looks",
mapOf("fields" to fields), body)
}
/**
* ### Search Looks
*
* Returns an **array of Look objects** that match the specified search criteria.
*
* If multiple search params are given and `filter_or` is FALSE or not specified,
* search params are combined in a logical AND operation.
* Only rows that match *all* search param criteria will be returned.
*
* If `filter_or` is TRUE, multiple search params are combined in a logical OR operation.
* Results will include rows that match **any** of the search criteria.
*
* String search params use case-insensitive matching.
* String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions.
* example="dan%" will match "danger" and "Danzig" but not "David"
* example="D_m%" will match "Damage" and "dump"
*
* Integer search params can accept a single value or a comma separated list of values. The multiple
* values will be combined under a logical OR operation - results will match at least one of
* the given values.
*
* Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match
* or exclude (respectively) rows where the column is null.
*
* Boolean search params accept only "true" and "false" as values.
*
*
* Get a **single look** by id with [look(id)](#!/Look/look)
*
* @param {String} id Match look id.
* @param {String} title Match Look title.
* @param {String} description Match Look description.
* @param {String} content_favorite_id Select looks with a particular content favorite id
* @param {String} folder_id Select looks in a particular folder.
* @param {String} user_id Select looks created by a particular user.
* @param {String} view_count Select looks with particular view_count value
* @param {Boolean} deleted Select soft-deleted looks
* @param {String} query_id Select looks that reference a particular query by query_id
* @param {Boolean} curate Exclude items that exist only in personal spaces other than the users
* @param {String} last_viewed_at Select looks based on when they were last viewed
* @param {String} fields Requested fields.
* @param {Long} page DEPRECATED. Use limit and offset instead. Return only page N of paginated results
* @param {Long} per_page DEPRECATED. Use limit and offset instead. Return N rows of data per page
* @param {Long} limit Number of results to return. (used with offset and takes priority over page and per_page)
* @param {Long} offset Number of results to skip before returning any. (used with limit and takes priority over page and per_page)
* @param {String} sorts One or more fields to sort results by. Sortable fields: [:title, :user_id, :id, :created_at, :space_id, :folder_id, :description, :updated_at, :last_updater_id, :view_count, :favorite_count, :content_favorite_id, :deleted, :deleted_at, :last_viewed_at, :last_accessed_at, :query_id]
* @param {Boolean} filter_or Combine given search criteria in a boolean OR expression
*
* GET /looks/search -> ByteArray
*/
@JvmOverloads fun search_looks(
id: String? = null,
title: String? = null,
description: String? = null,
content_favorite_id: String? = null,
folder_id: String? = null,
user_id: String? = null,
view_count: String? = null,
deleted: Boolean? = null,
query_id: String? = null,
curate: Boolean? = null,
last_viewed_at: String? = null,
fields: String? = null,
page: Long? = null,
per_page: Long? = null,
limit: Long? = null,
offset: Long? = null,
sorts: String? = null,
filter_or: Boolean? = null
) : SDKResponse {
return this.get<ByteArray>("/looks/search",
mapOf("id" to id,
"title" to title,
"description" to description,
"content_favorite_id" to content_favorite_id,
"folder_id" to folder_id,
"user_id" to user_id,
"view_count" to view_count,
"deleted" to deleted,
"query_id" to query_id,
"curate" to curate,
"last_viewed_at" to last_viewed_at,
"fields" to fields,
"page" to page,
"per_page" to per_page,
"limit" to limit,
"offset" to offset,
"sorts" to sorts,
"filter_or" to filter_or))
}
/**
* ### Get a Look.
*
* Returns detailed information about a Look and its associated Query.
*
* @param {String} look_id Id of look
* @param {String} fields Requested fields.
*
* GET /looks/{look_id} -> ByteArray
*/
@JvmOverloads fun look(
look_id: String,
fields: String? = null
) : SDKResponse {
val path_look_id = encodeParam(look_id)
return this.get<ByteArray>("/looks/${path_look_id}",
mapOf("fields" to fields))
}
/**
* ### Modify a Look
*
* Use this function to modify parts of a look. Property values given in a call to `update_look` are
* applied to the existing look, so there's no need to include properties whose values are not changing.
* It's best to specify only the properties you want to change and leave everything else out
* of your `update_look` call. **Look properties marked 'read-only' will be ignored.**
*
* When a user deletes a look in the Looker UI, the look data remains in the database but is
* marked with a deleted flag ("soft-deleted"). Soft-deleted looks can be undeleted (by an admin)
* if the delete was in error.
*
* To soft-delete a look via the API, use [update_look()](#!/Look/update_look) to change the look's `deleted` property to `true`.
* You can undelete a look by calling `update_look` to change the look's `deleted` property to `false`.
*
* Soft-deleted looks are excluded from the results of [all_looks()](#!/Look/all_looks) and [search_looks()](#!/Look/search_looks), so they
* essentially disappear from view even though they still reside in the db.
* In API 3.1 and later, you can pass `deleted: true` as a parameter to [search_looks()](#!/3.1/Look/search_looks) to list soft-deleted looks.
*
* NOTE: [delete_look()](#!/Look/delete_look) performs a "hard delete" - the look data is removed from the Looker
* database and destroyed. There is no "undo" for `delete_look()`.
*
* @param {String} look_id Id of look
* @param {WriteLookWithQuery} body
* @param {String} fields Requested fields.
*
* PATCH /looks/{look_id} -> ByteArray
*/
@JvmOverloads fun update_look(
look_id: String,
body: WriteLookWithQuery,
fields: String? = null
) : SDKResponse {
val path_look_id = encodeParam(look_id)
return this.patch<ByteArray>("/looks/${path_look_id}",
mapOf("fields" to fields), body)
}
/**
* ### Permanently Delete a Look
*
* This operation **permanently** removes a look from the Looker database.
*
* NOTE: There is no "undo" for this kind of delete.
*
* For information about soft-delete (which can be undone) see [update_look()](#!/Look/update_look).
*
* @param {String} look_id Id of look
*
* DELETE /looks/{look_id} -> ByteArray
*/
fun delete_look(
look_id: String
) : SDKResponse {
val path_look_id = encodeParam(look_id)
return this.delete<ByteArray>("/looks/${path_look_id}", mapOf())
}
/**
* ### Run a Look
*
* Runs a given look's query and returns the results in the requested format.
*
* Supported formats:
*
* | result_format | Description
* | :-----------: | :--- |
* | json | Plain json
* | json_detail | Row data plus metadata describing the fields, pivots, table calcs, and other aspects of the query
* | csv | Comma separated values with a header
* | txt | Tab separated values with a header
* | html | Simple html
* | md | Simple markdown
* | xlsx | MS Excel spreadsheet
* | sql | Returns the generated SQL rather than running the query
* | png | A PNG image of the visualization of the query
* | jpg | A JPG image of the visualization of the query
*
* @param {String} look_id Id of look
* @param {String} result_format Format of result
* @param {Long} limit Row limit (may override the limit in the saved query).
* @param {Boolean} apply_formatting Apply model-specified formatting to each result.
* @param {Boolean} apply_vis Apply visualization options to results.
* @param {Boolean} cache Get results from cache if available.
* @param {Long} image_width Render width for image formats.
* @param {Long} image_height Render height for image formats.
* @param {Boolean} generate_drill_links Generate drill links (only applicable to 'json_detail' format.
* @param {Boolean} force_production Force use of production models even if the user is in development mode. Note that this flag being false does not guarantee development models will be used.
* @param {Boolean} cache_only Retrieve any results from cache even if the results have expired.
* @param {String} path_prefix Prefix to use for drill links (url encoded).
* @param {Boolean} rebuild_pdts Rebuild PDTS used in query.
* @param {Boolean} server_table_calcs Perform table calculations on query results
*
* GET /looks/{look_id}/run/{result_format} -> ByteArray
*
* **Note**: Binary content may be returned by this method.
*/
@JvmOverloads fun run_look(
look_id: String,
result_format: String,
limit: Long? = null,
apply_formatting: Boolean? = null,
apply_vis: Boolean? = null,
cache: Boolean? = null,
image_width: Long? = null,
image_height: Long? = null,
generate_drill_links: Boolean? = null,
force_production: Boolean? = null,
cache_only: Boolean? = null,
path_prefix: String? = null,
rebuild_pdts: Boolean? = null,
server_table_calcs: Boolean? = null
) : SDKResponse {
val path_look_id = encodeParam(look_id)
val path_result_format = encodeParam(result_format)
return this.get<ByteArray>("/looks/${path_look_id}/run/${path_result_format}",
mapOf("limit" to limit,
"apply_formatting" to apply_formatting,
"apply_vis" to apply_vis,
"cache" to cache,
"image_width" to image_width,
"image_height" to image_height,
"generate_drill_links" to generate_drill_links,
"force_production" to force_production,
"cache_only" to cache_only,
"path_prefix" to path_prefix,
"rebuild_pdts" to rebuild_pdts,
"server_table_calcs" to server_table_calcs))
}
/**
* ### Copy an existing look
*
* Creates a copy of an existing look, in a specified folder, and returns the copied look.
*
* `look_id` and `folder_id` are required.
*
* `look_id` and `folder_id` must already exist, and `folder_id` must be different from the current `folder_id` of the dashboard.
*
* @param {String} look_id Look id to copy.
* @param {String} folder_id Folder id to copy to.
*
* POST /looks/{look_id}/copy -> ByteArray
*/
@JvmOverloads fun copy_look(
look_id: String,
folder_id: String? = null
) : SDKResponse {
val path_look_id = encodeParam(look_id)
return this.post<ByteArray>("/looks/${path_look_id}/copy",
mapOf("folder_id" to folder_id))
}
/**
* ### Move an existing look
*
* Moves a look to a specified folder, and returns the moved look.
*
* `look_id` and `folder_id` are required.
* `look_id` and `folder_id` must already exist, and `folder_id` must be different from the current `folder_id` of the dashboard.
*
* @param {String} look_id Look id to move.
* @param {String} folder_id Folder id to move to.
*
* PATCH /looks/{look_id}/move -> ByteArray
*/
fun move_look(
look_id: String,
folder_id: String
) : SDKResponse {
val path_look_id = encodeParam(look_id)
return this.patch<ByteArray>("/looks/${path_look_id}/move",
mapOf("folder_id" to folder_id))
}
//endregion Look: Run and Manage Looks
//region LookmlModel: Manage LookML Models
/**
* ### Get information about all lookml models.
*
* @param {String} fields Requested fields.
* @param {Long} limit Number of results to return. (can be used with offset)
* @param {Long} offset Number of results to skip before returning any. (Defaults to 0 if not set when limit is used)
*
* GET /lookml_models -> ByteArray
*/
@JvmOverloads fun all_lookml_models(
fields: String? = null,
limit: Long? = null,
offset: Long? = null
) : SDKResponse {
return this.get<ByteArray>("/lookml_models",
mapOf("fields" to fields,
"limit" to limit,
"offset" to offset))
}
/**
* ### Create a lookml model using the specified configuration.
*
* @param {WriteLookmlModel} body
*
* POST /lookml_models -> ByteArray
*/
fun create_lookml_model(
body: WriteLookmlModel
) : SDKResponse {
return this.post<ByteArray>("/lookml_models", mapOf(), body)
}
/**
* ### Get information about a lookml model.
*
* @param {String} lookml_model_name Name of lookml model.
* @param {String} fields Requested fields.
*
* GET /lookml_models/{lookml_model_name} -> ByteArray
*/
@JvmOverloads fun lookml_model(
lookml_model_name: String,
fields: String? = null
) : SDKResponse {
val path_lookml_model_name = encodeParam(lookml_model_name)
return this.get<ByteArray>("/lookml_models/${path_lookml_model_name}",
mapOf("fields" to fields))
}
/**
* ### Update a lookml model using the specified configuration.
*
* @param {String} lookml_model_name Name of lookml model.
* @param {WriteLookmlModel} body
*
* PATCH /lookml_models/{lookml_model_name} -> ByteArray
*/
fun update_lookml_model(
lookml_model_name: String,
body: WriteLookmlModel
) : SDKResponse {
val path_lookml_model_name = encodeParam(lookml_model_name)
return this.patch<ByteArray>("/lookml_models/${path_lookml_model_name}", mapOf(), body)
}
/**
* ### Delete a lookml model.
*
* @param {String} lookml_model_name Name of lookml model.
*
* DELETE /lookml_models/{lookml_model_name} -> ByteArray
*/
fun delete_lookml_model(
lookml_model_name: String
) : SDKResponse {
val path_lookml_model_name = encodeParam(lookml_model_name)
return this.delete<ByteArray>("/lookml_models/${path_lookml_model_name}", mapOf())
}
/**
* ### Get information about a lookml model explore.
*
* @param {String} lookml_model_name Name of lookml model.
* @param {String} explore_name Name of explore.
* @param {String} fields Requested fields.
*
* GET /lookml_models/{lookml_model_name}/explores/{explore_name} -> ByteArray
*/
@JvmOverloads fun lookml_model_explore(
lookml_model_name: String,
explore_name: String,
fields: String? = null
) : SDKResponse {
val path_lookml_model_name = encodeParam(lookml_model_name)
val path_explore_name = encodeParam(explore_name)
return this.get<ByteArray>("/lookml_models/${path_lookml_model_name}/explores/${path_explore_name}",
mapOf("fields" to fields))
}
//endregion LookmlModel: Manage LookML Models
//region Metadata: Connection Metadata Features
/**
* ### Field name suggestions for a model and view
*
* `filters` is a string hash of values, with the key as the field name and the string value as the filter expression:
*
* ```ruby
* {'users.age': '>=60'}
* ```
*
* or
*
* ```ruby
* {'users.age': '<30'}
* ```
*
* or
*
* ```ruby
* {'users.age': '=50'}
* ```
*
* @param {String} model_name Name of model
* @param {String} view_name Name of view
* @param {String} field_name Name of field to use for suggestions
* @param {String} term Search term pattern (evaluated as as `%term%`)
* @param {Any} filters Suggestion filters with field name keys and comparison expressions
*
* GET /models/{model_name}/views/{view_name}/fields/{field_name}/suggestions -> ByteArray
*/
@JvmOverloads fun model_fieldname_suggestions(
model_name: String,
view_name: String,
field_name: String,
term: String? = null,
filters: Any? = null
) : SDKResponse {
val path_model_name = encodeParam(model_name)
val path_view_name = encodeParam(view_name)
val path_field_name = encodeParam(field_name)
return this.get<ByteArray>("/models/${path_model_name}/views/${path_view_name}/fields/${path_field_name}/suggestions",
mapOf("term" to term,
"filters" to filters))
}
/**
* ### Get a single model
*
* @param {String} model_name Name of model
*
* GET /models/{model_name} -> ByteArray
*/
fun get_model(
model_name: String
) : SDKResponse {
val path_model_name = encodeParam(model_name)
return this.get<ByteArray>("/models/${path_model_name}", mapOf())
}
/**
* ### List databases available to this connection
*
* Certain dialects can support multiple databases per single connection.
* If this connection supports multiple databases, the database names will be returned in an array.
*
* Connections using dialects that do not support multiple databases will return an empty array.
*
* **Note**: [Connection Features](#!/Metadata/connection_features) can be used to determine if a connection supports
* multiple databases.
*
* @param {String} connection_name Name of connection
*
* GET /connections/{connection_name}/databases -> ByteArray
*/
fun connection_databases(
connection_name: String
) : SDKResponse {
val path_connection_name = encodeParam(connection_name)
return this.get<ByteArray>("/connections/${path_connection_name}/databases", mapOf())
}
/**
* ### Retrieve metadata features for this connection
*
* Returns a list of feature names with `true` (available) or `false` (not available)
*
* @param {String} connection_name Name of connection
* @param {String} fields Requested fields.
*
* GET /connections/{connection_name}/features -> ByteArray
*/
@JvmOverloads fun connection_features(
connection_name: String,
fields: String? = null
) : SDKResponse {
val path_connection_name = encodeParam(connection_name)
return this.get<ByteArray>("/connections/${path_connection_name}/features",
mapOf("fields" to fields))
}
/**
* ### Get the list of schemas and tables for a connection
*
* @param {String} connection_name Name of connection
* @param {String} database For dialects that support multiple databases, optionally identify which to use
* @param {Boolean} cache True to use fetch from cache, false to load fresh
* @param {String} fields Requested fields.
*
* GET /connections/{connection_name}/schemas -> ByteArray
*/
@JvmOverloads fun connection_schemas(
connection_name: String,
database: String? = null,
cache: Boolean? = null,
fields: String? = null
) : SDKResponse {
val path_connection_name = encodeParam(connection_name)
return this.get<ByteArray>("/connections/${path_connection_name}/schemas",
mapOf("database" to database,
"cache" to cache,
"fields" to fields))
}
/**
* ### Get the list of tables for a schema
*
* For dialects that support multiple databases, optionally identify which to use. If not provided, the default
* database for the connection will be used.
*
* For dialects that do **not** support multiple databases, **do not use** the database parameter
*
* @param {String} connection_name Name of connection
* @param {String} database Optional. Name of database to use for the query, only if applicable
* @param {String} schema_name Optional. Return only tables for this schema
* @param {Boolean} cache True to fetch from cache, false to load fresh
* @param {String} fields Requested fields.
* @param {String} table_filter Optional. Return tables with names that contain this value
* @param {Long} table_limit Optional. Return tables up to the table_limit
*
* GET /connections/{connection_name}/tables -> ByteArray
*/
@JvmOverloads fun connection_tables(
connection_name: String,
database: String? = null,
schema_name: String? = null,
cache: Boolean? = null,
fields: String? = null,
table_filter: String? = null,
table_limit: Long? = null
) : SDKResponse {
val path_connection_name = encodeParam(connection_name)
return this.get<ByteArray>("/connections/${path_connection_name}/tables",
mapOf("database" to database,
"schema_name" to schema_name,
"cache" to cache,
"fields" to fields,
"table_filter" to table_filter,
"table_limit" to table_limit))
}
/**
* ### Get the columns (and therefore also the tables) in a specific schema
*
* @param {String} connection_name Name of connection
* @param {String} database For dialects that support multiple databases, optionally identify which to use
* @param {String} schema_name Name of schema to use.
* @param {Boolean} cache True to fetch from cache, false to load fresh
* @param {Long} table_limit limits the tables per schema returned
* @param {String} table_names only fetch columns for a given (comma-separated) list of tables
* @param {String} fields Requested fields.
*
* GET /connections/{connection_name}/columns -> ByteArray
*/
@JvmOverloads fun connection_columns(
connection_name: String,
database: String? = null,
schema_name: String? = null,
cache: Boolean? = null,
table_limit: Long? = null,
table_names: String? = null,
fields: String? = null
) : SDKResponse {
val path_connection_name = encodeParam(connection_name)
return this.get<ByteArray>("/connections/${path_connection_name}/columns",
mapOf("database" to database,
"schema_name" to schema_name,
"cache" to cache,
"table_limit" to table_limit,
"table_names" to table_names,
"fields" to fields))
}
/**
* ### Search a connection for columns matching the specified name
*
* **Note**: `column_name` must be a valid column name. It is not a search pattern.
*
* @param {String} connection_name Name of connection
* @param {String} column_name Column name to find
* @param {String} fields Requested fields.
*
* GET /connections/{connection_name}/search_columns -> ByteArray
*/
@JvmOverloads fun connection_search_columns(
connection_name: String,
column_name: String? = null,
fields: String? = null
) : SDKResponse {
val path_connection_name = encodeParam(connection_name)
return this.get<ByteArray>("/connections/${path_connection_name}/search_columns",
mapOf("column_name" to column_name,
"fields" to fields))
}
/**
* ### Connection cost estimating
*
* Assign a `sql` statement to the body of the request. e.g., for Ruby, `{sql: 'select * from users'}`
*
* **Note**: If the connection's dialect has no support for cost estimates, an error will be returned
*
* @param {String} connection_name Name of connection
* @param {CreateCostEstimate} body WARNING: no writeable properties found for POST, PUT, or PATCH
* @param {String} fields Requested fields.
*
* POST /connections/{connection_name}/cost_estimate -> ByteArray
*/
@JvmOverloads fun connection_cost_estimate(
connection_name: String,
body: CreateCostEstimate,
fields: String? = null
) : SDKResponse {
val path_connection_name = encodeParam(connection_name)
return this.post<ByteArray>("/connections/${path_connection_name}/cost_estimate",
mapOf("fields" to fields), body)
}
//endregion Metadata: Connection Metadata Features
//region Project: Manage Projects
/**
* ### Generate Lockfile for All LookML Dependencies
*
* Git must have been configured, must be in dev mode and deploy permission required
*
* Install_all is a two step process
* 1. For each remote_dependency in a project the dependency manager will resolve any ambiguous ref.
* 2. The project will then write out a lockfile including each remote_dependency with its resolved ref.
*
* @param {String} project_id Id of project
* @param {String} fields Requested fields
*
* POST /projects/{project_id}/manifest/lock_all -> ByteArray
*/
@JvmOverloads fun lock_all(
project_id: String,
fields: String? = null
) : SDKResponse {
val path_project_id = encodeParam(project_id)
return this.post<ByteArray>("/projects/${path_project_id}/manifest/lock_all",
mapOf("fields" to fields))
}
/**
* ### Get All Git Branches
*
* Returns a list of git branches in the project repository
*
* @param {String} project_id Project Id
*
* GET /projects/{project_id}/git_branches -> ByteArray
*/
fun all_git_branches(
project_id: String
) : SDKResponse {
val path_project_id = encodeParam(project_id)
return this.get<ByteArray>("/projects/${path_project_id}/git_branches", mapOf())
}
/**
* ### Get the Current Git Branch
*
* Returns the git branch currently checked out in the given project repository
*
* @param {String} project_id Project Id
*
* GET /projects/{project_id}/git_branch -> ByteArray
*/
fun git_branch(
project_id: String
) : SDKResponse {
val path_project_id = encodeParam(project_id)
return this.get<ByteArray>("/projects/${path_project_id}/git_branch", mapOf())
}
/**
* ### Checkout and/or reset --hard an existing Git Branch
*
* Only allowed in development mode
* - Call `update_session` to select the 'dev' workspace.
*
* Checkout an existing branch if name field is different from the name of the currently checked out branch.
*
* Optionally specify a branch name, tag name or commit SHA to which the branch should be reset.
* **DANGER** hard reset will be force pushed to the remote. Unsaved changes and commits may be permanently lost.
*
* @param {String} project_id Project Id
* @param {WriteGitBranch} body
*
* PUT /projects/{project_id}/git_branch -> ByteArray
*/
fun update_git_branch(
project_id: String,
body: WriteGitBranch
) : SDKResponse {
val path_project_id = encodeParam(project_id)
return this.put<ByteArray>("/projects/${path_project_id}/git_branch", mapOf(), body)
}
/**
* ### Create and Checkout a Git Branch
*
* Creates and checks out a new branch in the given project repository
* Only allowed in development mode
* - Call `update_session` to select the 'dev' workspace.
*
* Optionally specify a branch name, tag name or commit SHA as the start point in the ref field.
* If no ref is specified, HEAD of the current branch will be used as the start point for the new branch.
*
* @param {String} project_id Project Id
* @param {WriteGitBranch} body
*
* POST /projects/{project_id}/git_branch -> ByteArray
*/
fun create_git_branch(
project_id: String,
body: WriteGitBranch
) : SDKResponse {
val path_project_id = encodeParam(project_id)
return this.post<ByteArray>("/projects/${path_project_id}/git_branch", mapOf(), body)
}
/**
* ### Get the specified Git Branch
*
* Returns the git branch specified in branch_name path param if it exists in the given project repository
*
* @param {String} project_id Project Id
* @param {String} branch_name Branch Name
*
* GET /projects/{project_id}/git_branch/{branch_name} -> ByteArray
*/
fun find_git_branch(
project_id: String,
branch_name: String
) : SDKResponse {
val path_project_id = encodeParam(project_id)
val path_branch_name = encodeParam(branch_name)
return this.get<ByteArray>("/projects/${path_project_id}/git_branch/${path_branch_name}", mapOf())
}
/**
* ### Delete the specified Git Branch
*
* Delete git branch specified in branch_name path param from local and remote of specified project repository
*
* @param {String} project_id Project Id
* @param {String} branch_name Branch Name
*
* DELETE /projects/{project_id}/git_branch/{branch_name} -> ByteArray
*/
fun delete_git_branch(
project_id: String,
branch_name: String
) : SDKResponse {
val path_project_id = encodeParam(project_id)
val path_branch_name = encodeParam(branch_name)
return this.delete<ByteArray>("/projects/${path_project_id}/git_branch/${path_branch_name}", mapOf())
}
/**
* ### Deploy a Remote Branch or Ref to Production
*
* Git must have been configured and deploy permission required.
*
* Deploy is a one/two step process
* 1. If this is the first deploy of this project, create the production project with git repository.
* 2. Pull the branch or ref into the production project.
*
* Can only specify either a branch or a ref.
*
* @param {String} project_id Id of project
* @param {String} branch Branch to deploy to production
* @param {String} ref Ref to deploy to production
*
* POST /projects/{project_id}/deploy_ref_to_production -> ByteArray
*/
@JvmOverloads fun deploy_ref_to_production(
project_id: String,
branch: String? = null,
ref: String? = null
) : SDKResponse {
val path_project_id = encodeParam(project_id)
return this.post<ByteArray>("/projects/${path_project_id}/deploy_ref_to_production",
mapOf("branch" to branch,
"ref" to ref))
}
/**
* ### Deploy LookML from this Development Mode Project to Production
*
* Git must have been configured, must be in dev mode and deploy permission required
*
* Deploy is a two / three step process:
*
* 1. Push commits in current branch of dev mode project to the production branch (origin/master).
* Note a. This step is skipped in read-only projects.
* Note b. If this step is unsuccessful for any reason (e.g. rejected non-fastforward because production branch has
* commits not in current branch), subsequent steps will be skipped.
* 2. If this is the first deploy of this project, create the production project with git repository.
* 3. Pull the production branch into the production project.
*
* @param {String} project_id Id of project
*
* POST /projects/{project_id}/deploy_to_production -> ByteArray
*/
fun deploy_to_production(
project_id: String
) : SDKResponse {
val path_project_id = encodeParam(project_id)
return this.post<ByteArray>("/projects/${path_project_id}/deploy_to_production", mapOf())
}
/**
* ### Reset a project to the revision of the project that is in production.
*
* **DANGER** this will delete any changes that have not been pushed to a remote repository.
*
* @param {String} project_id Id of project
*
* POST /projects/{project_id}/reset_to_production -> ByteArray
*/
fun reset_project_to_production(
project_id: String
) : SDKResponse {
val path_project_id = encodeParam(project_id)
return this.post<ByteArray>("/projects/${path_project_id}/reset_to_production", mapOf())
}
/**
* ### Reset a project development branch to the revision of the project that is on the remote.
*
* **DANGER** this will delete any changes that have not been pushed to a remote repository.
*
* @param {String} project_id Id of project
*
* POST /projects/{project_id}/reset_to_remote -> ByteArray
*/
fun reset_project_to_remote(
project_id: String
) : SDKResponse {
val path_project_id = encodeParam(project_id)
return this.post<ByteArray>("/projects/${path_project_id}/reset_to_remote", mapOf())
}
/**
* ### Get All Projects
*
* Returns all projects visible to the current user
*
* @param {String} fields Requested fields
*
* GET /projects -> ByteArray
*/
@JvmOverloads fun all_projects(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/projects",
mapOf("fields" to fields))
}
/**
* ### Create A Project
*
* dev mode required.
* - Call `update_session` to select the 'dev' workspace.
*
* `name` is required.
* `git_remote_url` is not allowed. To configure Git for the newly created project, follow the instructions in `update_project`.
*
* @param {WriteProject} body
*
* POST /projects -> ByteArray
*/
fun create_project(
body: WriteProject
) : SDKResponse {
return this.post<ByteArray>("/projects", mapOf(), body)
}
/**
* ### Get A Project
*
* Returns the project with the given project id
*
* @param {String} project_id Project Id
* @param {String} fields Requested fields
*
* GET /projects/{project_id} -> ByteArray
*/
@JvmOverloads fun project(
project_id: String,
fields: String? = null
) : SDKResponse {
val path_project_id = encodeParam(project_id)
return this.get<ByteArray>("/projects/${path_project_id}",
mapOf("fields" to fields))
}
/**
* ### Update Project Configuration
*
* Apply changes to a project's configuration.
*
*
* #### Configuring Git for a Project
*
* To set up a Looker project with a remote git repository, follow these steps:
*
* 1. Call `update_session` to select the 'dev' workspace.
* 1. Call `create_git_deploy_key` to create a new deploy key for the project
* 1. Copy the deploy key text into the remote git repository's ssh key configuration
* 1. Call `update_project` to set project's `git_remote_url` ()and `git_service_name`, if necessary).
*
* When you modify a project's `git_remote_url`, Looker connects to the remote repository to fetch
* metadata. The remote git repository MUST be configured with the Looker-generated deploy
* key for this project prior to setting the project's `git_remote_url`.
*
* To set up a Looker project with a git repository residing on the Looker server (a 'bare' git repo):
*
* 1. Call `update_session` to select the 'dev' workspace.
* 1. Call `update_project` setting `git_remote_url` to null and `git_service_name` to "bare".
*
* @param {String} project_id Project Id
* @param {WriteProject} body
* @param {String} fields Requested fields
*
* PATCH /projects/{project_id} -> ByteArray
*/
@JvmOverloads fun update_project(
project_id: String,
body: WriteProject,
fields: String? = null
) : SDKResponse {
val path_project_id = encodeParam(project_id)
return this.patch<ByteArray>("/projects/${path_project_id}",
mapOf("fields" to fields), body)
}
/**
* ### Get A Projects Manifest object
*
* Returns the project with the given project id
*
* @param {String} project_id Project Id
*
* GET /projects/{project_id}/manifest -> ByteArray
*/
fun manifest(
project_id: String
) : SDKResponse {
val path_project_id = encodeParam(project_id)
return this.get<ByteArray>("/projects/${path_project_id}/manifest", mapOf())
}
/**
* ### Git Deploy Key
*
* Returns the ssh public key previously created for a project's git repository.
*
* @param {String} project_id Project Id
*
* GET /projects/{project_id}/git/deploy_key -> ByteArray
*/
fun git_deploy_key(
project_id: String
) : SDKResponse {
val path_project_id = encodeParam(project_id)
return this.get<ByteArray>("/projects/${path_project_id}/git/deploy_key", mapOf())
}
/**
* ### Create Git Deploy Key
*
* Create a public/private key pair for authenticating ssh git requests from Looker to a remote git repository
* for a particular Looker project.
*
* Returns the public key of the generated ssh key pair.
*
* Copy this public key to your remote git repository's ssh keys configuration so that the remote git service can
* validate and accept git requests from the Looker server.
*
* @param {String} project_id Project Id
*
* POST /projects/{project_id}/git/deploy_key -> ByteArray
*/
fun create_git_deploy_key(
project_id: String
) : SDKResponse {
val path_project_id = encodeParam(project_id)
return this.post<ByteArray>("/projects/${path_project_id}/git/deploy_key", mapOf())
}
/**
* ### Get Cached Project Validation Results
*
* Returns the cached results of a previous project validation calculation, if any.
* Returns http status 204 No Content if no validation results exist.
*
* Validating the content of all the files in a project can be computationally intensive
* for large projects. Use this API to simply fetch the results of the most recent
* project validation rather than revalidating the entire project from scratch.
*
* A value of `"stale": true` in the response indicates that the project has changed since
* the cached validation results were computed. The cached validation results may no longer
* reflect the current state of the project.
*
* @param {String} project_id Project Id
* @param {String} fields Requested fields
*
* GET /projects/{project_id}/validate -> ByteArray
*/
@JvmOverloads fun project_validation_results(
project_id: String,
fields: String? = null
) : SDKResponse {
val path_project_id = encodeParam(project_id)
return this.get<ByteArray>("/projects/${path_project_id}/validate",
mapOf("fields" to fields))
}
/**
* ### Validate Project
*
* Performs lint validation of all lookml files in the project.
* Returns a list of errors found, if any.
*
* Validating the content of all the files in a project can be computationally intensive
* for large projects. For best performance, call `validate_project(project_id)` only
* when you really want to recompute project validation. To quickly display the results of
* the most recent project validation (without recomputing), use `project_validation_results(project_id)`
*
* @param {String} project_id Project Id
* @param {String} fields Requested fields
*
* POST /projects/{project_id}/validate -> ByteArray
*/
@JvmOverloads fun validate_project(
project_id: String,
fields: String? = null
) : SDKResponse {
val path_project_id = encodeParam(project_id)
return this.post<ByteArray>("/projects/${path_project_id}/validate",
mapOf("fields" to fields))
}
/**
* ### Get Project Workspace
*
* Returns information about the state of the project files in the currently selected workspace
*
* @param {String} project_id Project Id
* @param {String} fields Requested fields
*
* GET /projects/{project_id}/current_workspace -> ByteArray
*/
@JvmOverloads fun project_workspace(
project_id: String,
fields: String? = null
) : SDKResponse {
val path_project_id = encodeParam(project_id)
return this.get<ByteArray>("/projects/${path_project_id}/current_workspace",
mapOf("fields" to fields))
}
/**
* ### Get All Project Files
*
* Returns a list of the files in the project
*
* @param {String} project_id Project Id
* @param {String} fields Requested fields
*
* GET /projects/{project_id}/files -> ByteArray
*/
@JvmOverloads fun all_project_files(
project_id: String,
fields: String? = null
) : SDKResponse {
val path_project_id = encodeParam(project_id)
return this.get<ByteArray>("/projects/${path_project_id}/files",
mapOf("fields" to fields))
}
/**
* ### Get Project File Info
*
* Returns information about a file in the project
*
* @param {String} project_id Project Id
* @param {String} file_id File Id
* @param {String} fields Requested fields
*
* GET /projects/{project_id}/files/file -> ByteArray
*/
@JvmOverloads fun project_file(
project_id: String,
file_id: String,
fields: String? = null
) : SDKResponse {
val path_project_id = encodeParam(project_id)
return this.get<ByteArray>("/projects/${path_project_id}/files/file",
mapOf("file_id" to file_id,
"fields" to fields))
}
/**
* ### Get All Git Connection Tests
*
* dev mode required.
* - Call `update_session` to select the 'dev' workspace.
*
* Returns a list of tests which can be run against a project's (or the dependency project for the provided remote_url) git connection. Call [Run Git Connection Test](#!/Project/run_git_connection_test) to execute each test in sequence.
*
* Tests are ordered by increasing specificity. Tests should be run in the order returned because later tests require functionality tested by tests earlier in the test list.
*
* For example, a late-stage test for write access is meaningless if connecting to the git server (an early test) is failing.
*
* @param {String} project_id Project Id
* @param {String} remote_url (Optional: leave blank for root project) The remote url for remote dependency to test.
*
* GET /projects/{project_id}/git_connection_tests -> ByteArray
*/
@JvmOverloads fun all_git_connection_tests(
project_id: String,
remote_url: String? = null
) : SDKResponse {
val path_project_id = encodeParam(project_id)
return this.get<ByteArray>("/projects/${path_project_id}/git_connection_tests",
mapOf("remote_url" to remote_url))
}
/**
* ### Run a git connection test
*
* Run the named test on the git service used by this project (or the dependency project for the provided remote_url) and return the result. This
* is intended to help debug git connections when things do not work properly, to give
* more helpful information about why a git url is not working with Looker.
*
* Tests should be run in the order they are returned by [Get All Git Connection Tests](#!/Project/all_git_connection_tests).
*
* @param {String} project_id Project Id
* @param {String} test_id Test Id
* @param {String} remote_url (Optional: leave blank for root project) The remote url for remote dependency to test.
* @param {String} use_production (Optional: leave blank for dev credentials) Whether to use git production credentials.
*
* GET /projects/{project_id}/git_connection_tests/{test_id} -> ByteArray
*/
@JvmOverloads fun run_git_connection_test(
project_id: String,
test_id: String,
remote_url: String? = null,
use_production: String? = null
) : SDKResponse {
val path_project_id = encodeParam(project_id)
val path_test_id = encodeParam(test_id)
return this.get<ByteArray>("/projects/${path_project_id}/git_connection_tests/${path_test_id}",
mapOf("remote_url" to remote_url,
"use_production" to use_production))
}
/**
* ### Get All LookML Tests
*
* Returns a list of tests which can be run to validate a project's LookML code and/or the underlying data,
* optionally filtered by the file id.
* Call [Run LookML Test](#!/Project/run_lookml_test) to execute tests.
*
* @param {String} project_id Project Id
* @param {String} file_id File Id
*
* GET /projects/{project_id}/lookml_tests -> ByteArray
*/
@JvmOverloads fun all_lookml_tests(
project_id: String,
file_id: String? = null
) : SDKResponse {
val path_project_id = encodeParam(project_id)
return this.get<ByteArray>("/projects/${path_project_id}/lookml_tests",
mapOf("file_id" to file_id))
}
/**
* ### Run LookML Tests
*
* Runs all tests in the project, optionally filtered by file, test, and/or model.
*
* @param {String} project_id Project Id
* @param {String} file_id File Name
* @param {String} test Test Name
* @param {String} model Model Name
*
* GET /projects/{project_id}/lookml_tests/run -> ByteArray
*/
@JvmOverloads fun run_lookml_test(
project_id: String,
file_id: String? = null,
test: String? = null,
model: String? = null
) : SDKResponse {
val path_project_id = encodeParam(project_id)
return this.get<ByteArray>("/projects/${path_project_id}/lookml_tests/run",
mapOf("file_id" to file_id,
"test" to test,
"model" to model))
}
/**
* ### Creates a tag for the most recent commit, or a specific ref is a SHA is provided
*
* This is an internal-only, undocumented route.
*
* @param {String} project_id Project Id
* @param {WriteProject} body
* @param {String} commit_sha (Optional): Commit Sha to Tag
* @param {String} tag_name Tag Name
* @param {String} tag_message (Optional): Tag Message
*
* POST /projects/{project_id}/tag -> ByteArray
*/
@JvmOverloads fun tag_ref(
project_id: String,
body: WriteProject,
commit_sha: String? = null,
tag_name: String? = null,
tag_message: String? = null
) : SDKResponse {
val path_project_id = encodeParam(project_id)
return this.post<ByteArray>("/projects/${path_project_id}/tag",
mapOf("commit_sha" to commit_sha,
"tag_name" to tag_name,
"tag_message" to tag_message), body)
}
/**
* ### Configure Repository Credential for a remote dependency
*
* Admin required.
*
* `root_project_id` is required.
* `credential_id` is required.
*
* @param {String} root_project_id Root Project Id
* @param {String} credential_id Credential Id
* @param {WriteRepositoryCredential} body
*
* PUT /projects/{root_project_id}/credential/{credential_id} -> ByteArray
*/
fun update_repository_credential(
root_project_id: String,
credential_id: String,
body: WriteRepositoryCredential
) : SDKResponse {
val path_root_project_id = encodeParam(root_project_id)
val path_credential_id = encodeParam(credential_id)
return this.put<ByteArray>("/projects/${path_root_project_id}/credential/${path_credential_id}", mapOf(), body)
}
/**
* ### Repository Credential for a remote dependency
*
* Admin required.
*
* `root_project_id` is required.
* `credential_id` is required.
*
* @param {String} root_project_id Root Project Id
* @param {String} credential_id Credential Id
*
* DELETE /projects/{root_project_id}/credential/{credential_id} -> ByteArray
*/
fun delete_repository_credential(
root_project_id: String,
credential_id: String
) : SDKResponse {
val path_root_project_id = encodeParam(root_project_id)
val path_credential_id = encodeParam(credential_id)
return this.delete<ByteArray>("/projects/${path_root_project_id}/credential/${path_credential_id}", mapOf())
}
/**
* ### Get all Repository Credentials for a project
*
* `root_project_id` is required.
*
* @param {String} root_project_id Root Project Id
*
* GET /projects/{root_project_id}/credentials -> ByteArray
*/
fun get_all_repository_credentials(
root_project_id: String
) : SDKResponse {
val path_root_project_id = encodeParam(root_project_id)
return this.get<ByteArray>("/projects/${path_root_project_id}/credentials", mapOf())
}
//endregion Project: Manage Projects
//region Query: Run and Manage Queries
/**
* ### Create an async query task
*
* Creates a query task (job) to run a previously created query asynchronously. Returns a Query Task ID.
*
* Use [query_task(query_task_id)](#!/Query/query_task) to check the execution status of the query task.
* After the query task status reaches "Complete", use [query_task_results(query_task_id)](#!/Query/query_task_results) to fetch the results of the query.
*
* @param {WriteCreateQueryTask} body
* @param {Long} limit Row limit (may override the limit in the saved query).
* @param {Boolean} apply_formatting Apply model-specified formatting to each result.
* @param {Boolean} apply_vis Apply visualization options to results.
* @param {Boolean} cache Get results from cache if available.
* @param {Boolean} generate_drill_links Generate drill links (only applicable to 'json_detail' format.
* @param {Boolean} force_production Force use of production models even if the user is in development mode. Note that this flag being false does not guarantee development models will be used.
* @param {Boolean} cache_only Retrieve any results from cache even if the results have expired.
* @param {String} path_prefix Prefix to use for drill links (url encoded).
* @param {Boolean} rebuild_pdts Rebuild PDTS used in query.
* @param {Boolean} server_table_calcs Perform table calculations on query results
* @param {Long} image_width DEPRECATED. Render width for image formats. Note that this parameter is always ignored by this method.
* @param {Long} image_height DEPRECATED. Render height for image formats. Note that this parameter is always ignored by this method.
* @param {String} fields Requested fields
*
* POST /query_tasks -> ByteArray
*/
@JvmOverloads fun create_query_task(
body: WriteCreateQueryTask,
limit: Long? = null,
apply_formatting: Boolean? = null,
apply_vis: Boolean? = null,
cache: Boolean? = null,
generate_drill_links: Boolean? = null,
force_production: Boolean? = null,
cache_only: Boolean? = null,
path_prefix: String? = null,
rebuild_pdts: Boolean? = null,
server_table_calcs: Boolean? = null,
image_width: Long? = null,
image_height: Long? = null,
fields: String? = null
) : SDKResponse {
return this.post<ByteArray>("/query_tasks",
mapOf("limit" to limit,
"apply_formatting" to apply_formatting,
"apply_vis" to apply_vis,
"cache" to cache,
"generate_drill_links" to generate_drill_links,
"force_production" to force_production,
"cache_only" to cache_only,
"path_prefix" to path_prefix,
"rebuild_pdts" to rebuild_pdts,
"server_table_calcs" to server_table_calcs,
"image_width" to image_width,
"image_height" to image_height,
"fields" to fields), body)
}
/**
* ### Fetch results of multiple async queries
*
* Returns the results of multiple async queries in one request.
*
* For Query Tasks that are not completed, the response will include the execution status of the Query Task but will not include query results.
* Query Tasks whose results have expired will have a status of 'expired'.
* If the user making the API request does not have sufficient privileges to view a Query Task result, the result will have a status of 'missing'
*
* @param {DelimArray<String>} query_task_ids List of Query Task IDs
*
* GET /query_tasks/multi_results -> ByteArray
*/
fun query_task_multi_results(
query_task_ids: DelimArray<String>
) : SDKResponse {
return this.get<ByteArray>("/query_tasks/multi_results",
mapOf("query_task_ids" to query_task_ids))
}
/**
* ### Get Query Task details
*
* Use this function to check the status of an async query task. After the status
* reaches "Complete", you can call [query_task_results(query_task_id)](#!/Query/query_task_results) to
* retrieve the results of the query.
*
* Use [create_query_task()](#!/Query/create_query_task) to create an async query task.
*
* @param {String} query_task_id ID of the Query Task
* @param {String} fields Requested fields.
*
* GET /query_tasks/{query_task_id} -> ByteArray
*/
@JvmOverloads fun query_task(
query_task_id: String,
fields: String? = null
) : SDKResponse {
val path_query_task_id = encodeParam(query_task_id)
return this.get<ByteArray>("/query_tasks/${path_query_task_id}",
mapOf("fields" to fields))
}
/**
* ### Get Async Query Results
*
* Returns the results of an async query task if the query has completed.
*
* If the query task is still running or waiting to run, this function returns 204 No Content.
*
* If the query task ID is invalid or the cached results of the query task have expired, this function returns 404 Not Found.
*
* Use [query_task(query_task_id)](#!/Query/query_task) to check the execution status of the query task
* Call query_task_results only after the query task status reaches "Complete".
*
* You can also use [query_task_multi_results()](#!/Query/query_task_multi_results) retrieve the
* results of multiple async query tasks at the same time.
*
* #### SQL Error Handling:
* If the query fails due to a SQL db error, how this is communicated depends on the result_format you requested in `create_query_task()`.
*
* For `json_detail` result_format: `query_task_results()` will respond with HTTP status '200 OK' and db SQL error info
* will be in the `errors` property of the response object. The 'data' property will be empty.
*
* For all other result formats: `query_task_results()` will respond with HTTP status `400 Bad Request` and some db SQL error info
* will be in the message of the 400 error response, but not as detailed as expressed in `json_detail.errors`.
* These data formats can only carry row data, and error info is not row data.
*
* @param {String} query_task_id ID of the Query Task
*
* GET /query_tasks/{query_task_id}/results -> ByteArray
*/
fun query_task_results(
query_task_id: String
) : SDKResponse {
val path_query_task_id = encodeParam(query_task_id)
return this.get<ByteArray>("/query_tasks/${path_query_task_id}/results", mapOf())
}
/**
* ### Get a previously created query by id.
*
* A Looker query object includes the various parameters that define a database query that has been run or
* could be run in the future. These parameters include: model, view, fields, filters, pivots, etc.
* Query *results* are not part of the query object.
*
* Query objects are unique and immutable. Query objects are created automatically in Looker as users explore data.
* Looker does not delete them; they become part of the query history. When asked to create a query for
* any given set of parameters, Looker will first try to find an existing query object with matching
* parameters and will only create a new object when an appropriate object can not be found.
*
* This 'get' method is used to get the details about a query for a given id. See the other methods here
* to 'create' and 'run' queries.
*
* Note that some fields like 'filter_config' and 'vis_config' etc are specific to how the Looker UI
* builds queries and visualizations and are not generally useful for API use. They are not required when
* creating new queries and can usually just be ignored.
*
* @param {String} query_id Id of query
* @param {String} fields Requested fields.
*
* GET /queries/{query_id} -> ByteArray
*/
@JvmOverloads fun query(
query_id: String,
fields: String? = null
) : SDKResponse {
val path_query_id = encodeParam(query_id)
return this.get<ByteArray>("/queries/${path_query_id}",
mapOf("fields" to fields))
}
/**
* ### Get the query for a given query slug.
*
* This returns the query for the 'slug' in a query share URL.
*
* The 'slug' is a randomly chosen short string that is used as an alternative to the query's id value
* for use in URLs etc. This method exists as a convenience to help you use the API to 'find' queries that
* have been created using the Looker UI.
*
* You can use the Looker explore page to build a query and then choose the 'Share' option to
* show the share url for the query. Share urls generally look something like 'https://looker.yourcompany/x/vwGSbfc'.
* The trailing 'vwGSbfc' is the share slug. You can pass that string to this api method to get details about the query.
* Those details include the 'id' that you can use to run the query. Or, you can copy the query body
* (perhaps with your own modification) and use that as the basis to make/run new queries.
*
* This will also work with slugs from Looker explore urls like
* 'https://looker.yourcompany/explore/ecommerce/orders?qid=aogBgL6o3cKK1jN3RoZl5s'. In this case
* 'aogBgL6o3cKK1jN3RoZl5s' is the slug.
*
* @param {String} slug Slug of query
* @param {String} fields Requested fields.
*
* GET /queries/slug/{slug} -> ByteArray
*/
@JvmOverloads fun query_for_slug(
slug: String,
fields: String? = null
) : SDKResponse {
val path_slug = encodeParam(slug)
return this.get<ByteArray>("/queries/slug/${path_slug}",
mapOf("fields" to fields))
}
/**
* ### Create a query.
*
* This allows you to create a new query that you can later run. Looker queries are immutable once created
* and are not deleted. If you create a query that is exactly like an existing query then the existing query
* will be returned and no new query will be created. Whether a new query is created or not, you can use
* the 'id' in the returned query with the 'run' method.
*
* The query parameters are passed as json in the body of the request.
*
* @param {WriteQuery} body
* @param {String} fields Requested fields.
*
* POST /queries -> ByteArray
*/
@JvmOverloads fun create_query(
body: WriteQuery,
fields: String? = null
) : SDKResponse {
return this.post<ByteArray>("/queries",
mapOf("fields" to fields), body)
}
/**
* ### Run a saved query.
*
* This runs a previously saved query. You can use this on a query that was generated in the Looker UI
* or one that you have explicitly created using the API. You can also use a query 'id' from a saved 'Look'.
*
* The 'result_format' parameter specifies the desired structure and format of the response.
*
* Supported formats:
*
* | result_format | Description
* | :-----------: | :--- |
* | json | Plain json
* | json_detail | Row data plus metadata describing the fields, pivots, table calcs, and other aspects of the query
* | csv | Comma separated values with a header
* | txt | Tab separated values with a header
* | html | Simple html
* | md | Simple markdown
* | xlsx | MS Excel spreadsheet
* | sql | Returns the generated SQL rather than running the query
* | png | A PNG image of the visualization of the query
* | jpg | A JPG image of the visualization of the query
*
* @param {String} query_id Id of query
* @param {String} result_format Format of result
* @param {Long} limit Row limit (may override the limit in the saved query).
* @param {Boolean} apply_formatting Apply model-specified formatting to each result.
* @param {Boolean} apply_vis Apply visualization options to results.
* @param {Boolean} cache Get results from cache if available.
* @param {Long} image_width Render width for image formats.
* @param {Long} image_height Render height for image formats.
* @param {Boolean} generate_drill_links Generate drill links (only applicable to 'json_detail' format.
* @param {Boolean} force_production Force use of production models even if the user is in development mode. Note that this flag being false does not guarantee development models will be used.
* @param {Boolean} cache_only Retrieve any results from cache even if the results have expired.
* @param {String} path_prefix Prefix to use for drill links (url encoded).
* @param {Boolean} rebuild_pdts Rebuild PDTS used in query.
* @param {Boolean} server_table_calcs Perform table calculations on query results
* @param {String} source Specifies the source of this call.
*
* GET /queries/{query_id}/run/{result_format} -> ByteArray
*
* **Note**: Binary content may be returned by this method.
*/
@JvmOverloads fun run_query(
query_id: String,
result_format: String,
limit: Long? = null,
apply_formatting: Boolean? = null,
apply_vis: Boolean? = null,
cache: Boolean? = null,
image_width: Long? = null,
image_height: Long? = null,
generate_drill_links: Boolean? = null,
force_production: Boolean? = null,
cache_only: Boolean? = null,
path_prefix: String? = null,
rebuild_pdts: Boolean? = null,
server_table_calcs: Boolean? = null,
source: String? = null
) : SDKResponse {
val path_query_id = encodeParam(query_id)
val path_result_format = encodeParam(result_format)
return this.get<ByteArray>("/queries/${path_query_id}/run/${path_result_format}",
mapOf("limit" to limit,
"apply_formatting" to apply_formatting,
"apply_vis" to apply_vis,
"cache" to cache,
"image_width" to image_width,
"image_height" to image_height,
"generate_drill_links" to generate_drill_links,
"force_production" to force_production,
"cache_only" to cache_only,
"path_prefix" to path_prefix,
"rebuild_pdts" to rebuild_pdts,
"server_table_calcs" to server_table_calcs,
"source" to source))
}
/**
* ### Run the query that is specified inline in the posted body.
*
* This allows running a query as defined in json in the posted body. This combines
* the two actions of posting & running a query into one step.
*
* Here is an example body in json:
* ```
* {
* "model":"thelook",
* "view":"inventory_items",
* "fields":["category.name","inventory_items.days_in_inventory_tier","products.count"],
* "filters":{"category.name":"socks"},
* "sorts":["products.count desc 0"],
* "limit":"500",
* "query_timezone":"America/Los_Angeles"
* }
* ```
*
* When using the Ruby SDK this would be passed as a Ruby hash like:
* ```
* {
* :model=>"thelook",
* :view=>"inventory_items",
* :fields=>
* ["category.name",
* "inventory_items.days_in_inventory_tier",
* "products.count"],
* :filters=>{:"category.name"=>"socks"},
* :sorts=>["products.count desc 0"],
* :limit=>"500",
* :query_timezone=>"America/Los_Angeles",
* }
* ```
*
* This will return the result of running the query in the format specified by the 'result_format' parameter.
*
* Supported formats:
*
* | result_format | Description
* | :-----------: | :--- |
* | json | Plain json
* | json_detail | Row data plus metadata describing the fields, pivots, table calcs, and other aspects of the query
* | csv | Comma separated values with a header
* | txt | Tab separated values with a header
* | html | Simple html
* | md | Simple markdown
* | xlsx | MS Excel spreadsheet
* | sql | Returns the generated SQL rather than running the query
* | png | A PNG image of the visualization of the query
* | jpg | A JPG image of the visualization of the query
*
* @param {String} result_format Format of result
* @param {WriteQuery} body
* @param {Long} limit Row limit (may override the limit in the saved query).
* @param {Boolean} apply_formatting Apply model-specified formatting to each result.
* @param {Boolean} apply_vis Apply visualization options to results.
* @param {Boolean} cache Get results from cache if available.
* @param {Long} image_width Render width for image formats.
* @param {Long} image_height Render height for image formats.
* @param {Boolean} generate_drill_links Generate drill links (only applicable to 'json_detail' format.
* @param {Boolean} force_production Force use of production models even if the user is in development mode. Note that this flag being false does not guarantee development models will be used.
* @param {Boolean} cache_only Retrieve any results from cache even if the results have expired.
* @param {String} path_prefix Prefix to use for drill links (url encoded).
* @param {Boolean} rebuild_pdts Rebuild PDTS used in query.
* @param {Boolean} server_table_calcs Perform table calculations on query results
*
* POST /queries/run/{result_format} -> ByteArray
*
* **Note**: Binary content may be returned by this method.
*/
@JvmOverloads fun run_inline_query(
result_format: String,
body: WriteQuery,
limit: Long? = null,
apply_formatting: Boolean? = null,
apply_vis: Boolean? = null,
cache: Boolean? = null,
image_width: Long? = null,
image_height: Long? = null,
generate_drill_links: Boolean? = null,
force_production: Boolean? = null,
cache_only: Boolean? = null,
path_prefix: String? = null,
rebuild_pdts: Boolean? = null,
server_table_calcs: Boolean? = null
) : SDKResponse {
val path_result_format = encodeParam(result_format)
return this.post<ByteArray>("/queries/run/${path_result_format}",
mapOf("limit" to limit,
"apply_formatting" to apply_formatting,
"apply_vis" to apply_vis,
"cache" to cache,
"image_width" to image_width,
"image_height" to image_height,
"generate_drill_links" to generate_drill_links,
"force_production" to force_production,
"cache_only" to cache_only,
"path_prefix" to path_prefix,
"rebuild_pdts" to rebuild_pdts,
"server_table_calcs" to server_table_calcs), body)
}
/**
* ### Run an URL encoded query.
*
* This requires the caller to encode the specifiers for the query into the URL query part using
* Looker-specific syntax as explained below.
*
* Generally, you would want to use one of the methods that takes the parameters as json in the POST body
* for creating and/or running queries. This method exists for cases where one really needs to encode the
* parameters into the URL of a single 'GET' request. This matches the way that the Looker UI formats
* 'explore' URLs etc.
*
* The parameters here are very similar to the json body formatting except that the filter syntax is
* tricky. Unfortunately, this format makes this method not currently callable via the 'Try it out!' button
* in this documentation page. But, this is callable when creating URLs manually or when using the Looker SDK.
*
* Here is an example inline query URL:
*
* ```
* https://looker.mycompany.com:19999/api/3.0/queries/models/thelook/views/inventory_items/run/json?fields=category.name,inventory_items.days_in_inventory_tier,products.count&f[category.name]=socks&sorts=products.count+desc+0&limit=500&query_timezone=America/Los_Angeles
* ```
*
* When invoking this endpoint with the Ruby SDK, pass the query parameter parts as a hash. The hash to match the above would look like:
*
* ```ruby
* query_params =
* {
* fields: "category.name,inventory_items.days_in_inventory_tier,products.count",
* :"f[category.name]" => "socks",
* sorts: "products.count desc 0",
* limit: "500",
* query_timezone: "America/Los_Angeles"
* }
* response = ruby_sdk.run_url_encoded_query('thelook','inventory_items','json', query_params)
*
* ```
*
* Again, it is generally easier to use the variant of this method that passes the full query in the POST body.
* This method is available for cases where other alternatives won't fit the need.
*
* Supported formats:
*
* | result_format | Description
* | :-----------: | :--- |
* | json | Plain json
* | json_detail | Row data plus metadata describing the fields, pivots, table calcs, and other aspects of the query
* | csv | Comma separated values with a header
* | txt | Tab separated values with a header
* | html | Simple html
* | md | Simple markdown
* | xlsx | MS Excel spreadsheet
* | sql | Returns the generated SQL rather than running the query
* | png | A PNG image of the visualization of the query
* | jpg | A JPG image of the visualization of the query
*
* @param {String} model_name Model name
* @param {String} view_name View name
* @param {String} result_format Format of result
*
* GET /queries/models/{model_name}/views/{view_name}/run/{result_format} -> ByteArray
*
* **Note**: Binary content may be returned by this method.
*/
fun run_url_encoded_query(
model_name: String,
view_name: String,
result_format: String
) : SDKResponse {
val path_model_name = encodeParam(model_name)
val path_view_name = encodeParam(view_name)
val path_result_format = encodeParam(result_format)
return this.get<ByteArray>("/queries/models/${path_model_name}/views/${path_view_name}/run/${path_result_format}", mapOf())
}
/**
* ### Get Merge Query
*
* Returns a merge query object given its id.
*
* @param {String} merge_query_id Merge Query Id
* @param {String} fields Requested fields
*
* GET /merge_queries/{merge_query_id} -> ByteArray
*/
@JvmOverloads fun merge_query(
merge_query_id: String,
fields: String? = null
) : SDKResponse {
val path_merge_query_id = encodeParam(merge_query_id)
return this.get<ByteArray>("/merge_queries/${path_merge_query_id}",
mapOf("fields" to fields))
}
/**
* ### Create Merge Query
*
* Creates a new merge query object.
*
* A merge query takes the results of one or more queries and combines (merges) the results
* according to field mapping definitions. The result is similar to a SQL left outer join.
*
* A merge query can merge results of queries from different SQL databases.
*
* The order that queries are defined in the source_queries array property is significant. The
* first query in the array defines the primary key into which the results of subsequent
* queries will be merged.
*
* Like model/view query objects, merge queries are immutable and have structural identity - if
* you make a request to create a new merge query that is identical to an existing merge query,
* the existing merge query will be returned instead of creating a duplicate. Conversely, any
* change to the contents of a merge query will produce a new object with a new id.
*
* @param {WriteMergeQuery} body
* @param {String} fields Requested fields
*
* POST /merge_queries -> ByteArray
*/
@JvmOverloads fun create_merge_query(
body: WriteMergeQuery? = null,
fields: String? = null
) : SDKResponse {
return this.post<ByteArray>("/merge_queries",
mapOf("fields" to fields), body)
}
/**
* Get information about all running queries.
*
* GET /running_queries -> ByteArray
*/
fun all_running_queries(
) : SDKResponse {
return this.get<ByteArray>("/running_queries", mapOf())
}
/**
* Kill a query with a specific query_task_id.
*
* @param {String} query_task_id Query task id.
*
* DELETE /running_queries/{query_task_id} -> ByteArray
*/
fun kill_query(
query_task_id: String
) : SDKResponse {
val path_query_task_id = encodeParam(query_task_id)
return this.delete<ByteArray>("/running_queries/${path_query_task_id}", mapOf())
}
/**
* Get a SQL Runner query.
*
* @param {String} slug slug of query
*
* GET /sql_queries/{slug} -> ByteArray
*/
fun sql_query(
slug: String
) : SDKResponse {
val path_slug = encodeParam(slug)
return this.get<ByteArray>("/sql_queries/${path_slug}", mapOf())
}
/**
* ### Create a SQL Runner Query
*
* Either the `connection_name` or `model_name` parameter MUST be provided.
*
* @param {SqlQueryCreate} body
*
* POST /sql_queries -> ByteArray
*/
fun create_sql_query(
body: SqlQueryCreate
) : SDKResponse {
return this.post<ByteArray>("/sql_queries", mapOf(), body)
}
/**
* Execute a SQL Runner query in a given result_format.
*
* @param {String} slug slug of query
* @param {String} result_format Format of result, options are: ["inline_json", "json", "json_detail", "json_fe", "csv", "html", "md", "txt", "xlsx", "gsxml", "json_label"]
* @param {String} download Defaults to false. If set to true, the HTTP response will have content-disposition and other headers set to make the HTTP response behave as a downloadable attachment instead of as inline content.
*
* POST /sql_queries/{slug}/run/{result_format} -> ByteArray
*
* **Note**: Binary content may be returned by this method.
*/
@JvmOverloads fun run_sql_query(
slug: String,
result_format: String,
download: String? = null
) : SDKResponse {
val path_slug = encodeParam(slug)
val path_result_format = encodeParam(result_format)
return this.post<ByteArray>("/sql_queries/${path_slug}/run/${path_result_format}",
mapOf("download" to download))
}
//endregion Query: Run and Manage Queries
//region RenderTask: Manage Render Tasks
/**
* ### Create a new task to render a look to an image.
*
* Returns a render task object.
* To check the status of a render task, pass the render_task.id to [Get Render Task](#!/RenderTask/get_render_task).
* Once the render task is complete, you can download the resulting document or image using [Get Render Task Results](#!/RenderTask/get_render_task_results).
*
* @param {String} look_id Id of look to render
* @param {String} result_format Output type: png, or jpg
* @param {Long} width Output width in pixels
* @param {Long} height Output height in pixels
* @param {String} fields Requested fields.
*
* POST /render_tasks/looks/{look_id}/{result_format} -> ByteArray
*/
@JvmOverloads fun create_look_render_task(
look_id: String,
result_format: String,
width: Long,
height: Long,
fields: String? = null
) : SDKResponse {
val path_look_id = encodeParam(look_id)
val path_result_format = encodeParam(result_format)
return this.post<ByteArray>("/render_tasks/looks/${path_look_id}/${path_result_format}",
mapOf("width" to width,
"height" to height,
"fields" to fields))
}
/**
* ### Create a new task to render an existing query to an image.
*
* Returns a render task object.
* To check the status of a render task, pass the render_task.id to [Get Render Task](#!/RenderTask/get_render_task).
* Once the render task is complete, you can download the resulting document or image using [Get Render Task Results](#!/RenderTask/get_render_task_results).
*
* @param {String} query_id Id of the query to render
* @param {String} result_format Output type: png or jpg
* @param {Long} width Output width in pixels
* @param {Long} height Output height in pixels
* @param {String} fields Requested fields.
*
* POST /render_tasks/queries/{query_id}/{result_format} -> ByteArray
*/
@JvmOverloads fun create_query_render_task(
query_id: String,
result_format: String,
width: Long,
height: Long,
fields: String? = null
) : SDKResponse {
val path_query_id = encodeParam(query_id)
val path_result_format = encodeParam(result_format)
return this.post<ByteArray>("/render_tasks/queries/${path_query_id}/${path_result_format}",
mapOf("width" to width,
"height" to height,
"fields" to fields))
}
/**
* ### Create a new task to render a dashboard to a document or image.
*
* Returns a render task object.
* To check the status of a render task, pass the render_task.id to [Get Render Task](#!/RenderTask/get_render_task).
* Once the render task is complete, you can download the resulting document or image using [Get Render Task Results](#!/RenderTask/get_render_task_results).
*
* @param {String} dashboard_id Id of dashboard to render. The ID can be a LookML dashboard also.
* @param {String} result_format Output type: pdf, png, or jpg
* @param {CreateDashboardRenderTask} body
* @param {Long} width Output width in pixels
* @param {Long} height Output height in pixels
* @param {String} fields Requested fields.
* @param {String} pdf_paper_size Paper size for pdf. Value can be one of: ["letter","legal","tabloid","a0","a1","a2","a3","a4","a5"]
* @param {Boolean} pdf_landscape Whether to render pdf in landscape paper orientation
* @param {Boolean} long_tables Whether or not to expand table vis to full length
*
* POST /render_tasks/dashboards/{dashboard_id}/{result_format} -> ByteArray
*/
@JvmOverloads fun create_dashboard_render_task(
dashboard_id: String,
result_format: String,
body: CreateDashboardRenderTask,
width: Long,
height: Long,
fields: String? = null,
pdf_paper_size: String? = null,
pdf_landscape: Boolean? = null,
long_tables: Boolean? = null
) : SDKResponse {
val path_dashboard_id = encodeParam(dashboard_id)
val path_result_format = encodeParam(result_format)
return this.post<ByteArray>("/render_tasks/dashboards/${path_dashboard_id}/${path_result_format}",
mapOf("width" to width,
"height" to height,
"fields" to fields,
"pdf_paper_size" to pdf_paper_size,
"pdf_landscape" to pdf_landscape,
"long_tables" to long_tables), body)
}
/**
* ### Get information about a render task.
*
* Returns a render task object.
* To check the status of a render task, pass the render_task.id to [Get Render Task](#!/RenderTask/get_render_task).
* Once the render task is complete, you can download the resulting document or image using [Get Render Task Results](#!/RenderTask/get_render_task_results).
*
* @param {String} render_task_id Id of render task
* @param {String} fields Requested fields.
*
* GET /render_tasks/{render_task_id} -> ByteArray
*/
@JvmOverloads fun render_task(
render_task_id: String,
fields: String? = null
) : SDKResponse {
val path_render_task_id = encodeParam(render_task_id)
return this.get<ByteArray>("/render_tasks/${path_render_task_id}",
mapOf("fields" to fields))
}
/**
* ### Get the document or image produced by a completed render task.
*
* Note that the PDF or image result will be a binary blob in the HTTP response, as indicated by the
* Content-Type in the response headers. This may require specialized (or at least different) handling than text
* responses such as JSON. You may need to tell your HTTP client that the response is binary so that it does not
* attempt to parse the binary data as text.
*
* If the render task exists but has not finished rendering the results, the response HTTP status will be
* **202 Accepted**, the response body will be empty, and the response will have a Retry-After header indicating
* that the caller should repeat the request at a later time.
*
* Returns 404 if the render task cannot be found, if the cached result has expired, or if the caller
* does not have permission to view the results.
*
* For detailed information about the status of the render task, use [Render Task](#!/RenderTask/render_task).
* Polling loops waiting for completion of a render task would be better served by polling **render_task(id)** until
* the task status reaches completion (or error) instead of polling **render_task_results(id)** alone.
*
* @param {String} render_task_id Id of render task
*
* GET /render_tasks/{render_task_id}/results -> ByteArray
*
* **Note**: Binary content is returned by this method.
*/
fun render_task_results(
render_task_id: String
) : SDKResponse {
val path_render_task_id = encodeParam(render_task_id)
return this.get<ByteArray>("/render_tasks/${path_render_task_id}/results", mapOf())
}
/**
* ### Create a new task to render a dashboard element to an image.
*
* Returns a render task object.
* To check the status of a render task, pass the render_task.id to [Get Render Task](#!/RenderTask/get_render_task).
* Once the render task is complete, you can download the resulting document or image using [Get Render Task Results](#!/RenderTask/get_render_task_results).
*
* @param {String} dashboard_element_id Id of dashboard element to render: UDD dashboard element would be numeric and LookML dashboard element would be model_name::dashboard_title::lookml_link_id
* @param {String} result_format Output type: png or jpg
* @param {Long} width Output width in pixels
* @param {Long} height Output height in pixels
* @param {String} fields Requested fields.
*
* POST /render_tasks/dashboard_elements/{dashboard_element_id}/{result_format} -> ByteArray
*/
@JvmOverloads fun create_dashboard_element_render_task(
dashboard_element_id: String,
result_format: String,
width: Long,
height: Long,
fields: String? = null
) : SDKResponse {
val path_dashboard_element_id = encodeParam(dashboard_element_id)
val path_result_format = encodeParam(result_format)
return this.post<ByteArray>("/render_tasks/dashboard_elements/${path_dashboard_element_id}/${path_result_format}",
mapOf("width" to width,
"height" to height,
"fields" to fields))
}
//endregion RenderTask: Manage Render Tasks
//region Role: Manage Roles
/**
* ### Search model sets
* Returns all model set records that match the given search criteria.
* If multiple search params are given and `filter_or` is FALSE or not specified,
* search params are combined in a logical AND operation.
* Only rows that match *all* search param criteria will be returned.
*
* If `filter_or` is TRUE, multiple search params are combined in a logical OR operation.
* Results will include rows that match **any** of the search criteria.
*
* String search params use case-insensitive matching.
* String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions.
* example="dan%" will match "danger" and "Danzig" but not "David"
* example="D_m%" will match "Damage" and "dump"
*
* Integer search params can accept a single value or a comma separated list of values. The multiple
* values will be combined under a logical OR operation - results will match at least one of
* the given values.
*
* Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match
* or exclude (respectively) rows where the column is null.
*
* Boolean search params accept only "true" and "false" as values.
*
* @param {String} fields Requested fields.
* @param {Long} limit Number of results to return (used with `offset`).
* @param {Long} offset Number of results to skip before returning any (used with `limit`).
* @param {String} sorts Fields to sort by.
* @param {String} id Match model set id.
* @param {String} name Match model set name.
* @param {Boolean} all_access Match model sets by all_access status.
* @param {Boolean} built_in Match model sets by built_in status.
* @param {Boolean} filter_or Combine given search criteria in a boolean OR expression.
*
* GET /model_sets/search -> ByteArray
*/
@JvmOverloads fun search_model_sets(
fields: String? = null,
limit: Long? = null,
offset: Long? = null,
sorts: String? = null,
id: String? = null,
name: String? = null,
all_access: Boolean? = null,
built_in: Boolean? = null,
filter_or: Boolean? = null
) : SDKResponse {
return this.get<ByteArray>("/model_sets/search",
mapOf("fields" to fields,
"limit" to limit,
"offset" to offset,
"sorts" to sorts,
"id" to id,
"name" to name,
"all_access" to all_access,
"built_in" to built_in,
"filter_or" to filter_or))
}
/**
* ### Get information about the model set with a specific id.
*
* @param {String} model_set_id Id of model set
* @param {String} fields Requested fields.
*
* GET /model_sets/{model_set_id} -> ByteArray
*/
@JvmOverloads fun model_set(
model_set_id: String,
fields: String? = null
) : SDKResponse {
val path_model_set_id = encodeParam(model_set_id)
return this.get<ByteArray>("/model_sets/${path_model_set_id}",
mapOf("fields" to fields))
}
/**
* ### Update information about the model set with a specific id.
*
* @param {String} model_set_id id of model set
* @param {WriteModelSet} body
*
* PATCH /model_sets/{model_set_id} -> ByteArray
*/
fun update_model_set(
model_set_id: String,
body: WriteModelSet
) : SDKResponse {
val path_model_set_id = encodeParam(model_set_id)
return this.patch<ByteArray>("/model_sets/${path_model_set_id}", mapOf(), body)
}
/**
* ### Delete the model set with a specific id.
*
* @param {String} model_set_id id of model set
*
* DELETE /model_sets/{model_set_id} -> ByteArray
*/
fun delete_model_set(
model_set_id: String
) : SDKResponse {
val path_model_set_id = encodeParam(model_set_id)
return this.delete<ByteArray>("/model_sets/${path_model_set_id}", mapOf())
}
/**
* ### Get information about all model sets.
*
* @param {String} fields Requested fields.
*
* GET /model_sets -> ByteArray
*/
@JvmOverloads fun all_model_sets(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/model_sets",
mapOf("fields" to fields))
}
/**
* ### Create a model set with the specified information. Model sets are used by Roles.
*
* @param {WriteModelSet} body
*
* POST /model_sets -> ByteArray
*/
fun create_model_set(
body: WriteModelSet
) : SDKResponse {
return this.post<ByteArray>("/model_sets", mapOf(), body)
}
/**
* ### Get all supported permissions.
*
* GET /permissions -> ByteArray
*/
fun all_permissions(
) : SDKResponse {
return this.get<ByteArray>("/permissions", mapOf())
}
/**
* ### Search permission sets
* Returns all permission set records that match the given search criteria.
* If multiple search params are given and `filter_or` is FALSE or not specified,
* search params are combined in a logical AND operation.
* Only rows that match *all* search param criteria will be returned.
*
* If `filter_or` is TRUE, multiple search params are combined in a logical OR operation.
* Results will include rows that match **any** of the search criteria.
*
* String search params use case-insensitive matching.
* String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions.
* example="dan%" will match "danger" and "Danzig" but not "David"
* example="D_m%" will match "Damage" and "dump"
*
* Integer search params can accept a single value or a comma separated list of values. The multiple
* values will be combined under a logical OR operation - results will match at least one of
* the given values.
*
* Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match
* or exclude (respectively) rows where the column is null.
*
* Boolean search params accept only "true" and "false" as values.
*
* @param {String} fields Requested fields.
* @param {Long} limit Number of results to return (used with `offset`).
* @param {Long} offset Number of results to skip before returning any (used with `limit`).
* @param {String} sorts Fields to sort by.
* @param {String} id Match permission set id.
* @param {String} name Match permission set name.
* @param {Boolean} all_access Match permission sets by all_access status.
* @param {Boolean} built_in Match permission sets by built_in status.
* @param {Boolean} filter_or Combine given search criteria in a boolean OR expression.
*
* GET /permission_sets/search -> ByteArray
*/
@JvmOverloads fun search_permission_sets(
fields: String? = null,
limit: Long? = null,
offset: Long? = null,
sorts: String? = null,
id: String? = null,
name: String? = null,
all_access: Boolean? = null,
built_in: Boolean? = null,
filter_or: Boolean? = null
) : SDKResponse {
return this.get<ByteArray>("/permission_sets/search",
mapOf("fields" to fields,
"limit" to limit,
"offset" to offset,
"sorts" to sorts,
"id" to id,
"name" to name,
"all_access" to all_access,
"built_in" to built_in,
"filter_or" to filter_or))
}
/**
* ### Get information about the permission set with a specific id.
*
* @param {String} permission_set_id Id of permission set
* @param {String} fields Requested fields.
*
* GET /permission_sets/{permission_set_id} -> ByteArray
*/
@JvmOverloads fun permission_set(
permission_set_id: String,
fields: String? = null
) : SDKResponse {
val path_permission_set_id = encodeParam(permission_set_id)
return this.get<ByteArray>("/permission_sets/${path_permission_set_id}",
mapOf("fields" to fields))
}
/**
* ### Update information about the permission set with a specific id.
*
* @param {String} permission_set_id Id of permission set
* @param {WritePermissionSet} body
*
* PATCH /permission_sets/{permission_set_id} -> ByteArray
*/
fun update_permission_set(
permission_set_id: String,
body: WritePermissionSet
) : SDKResponse {
val path_permission_set_id = encodeParam(permission_set_id)
return this.patch<ByteArray>("/permission_sets/${path_permission_set_id}", mapOf(), body)
}
/**
* ### Delete the permission set with a specific id.
*
* @param {String} permission_set_id Id of permission set
*
* DELETE /permission_sets/{permission_set_id} -> ByteArray
*/
fun delete_permission_set(
permission_set_id: String
) : SDKResponse {
val path_permission_set_id = encodeParam(permission_set_id)
return this.delete<ByteArray>("/permission_sets/${path_permission_set_id}", mapOf())
}
/**
* ### Get information about all permission sets.
*
* @param {String} fields Requested fields.
*
* GET /permission_sets -> ByteArray
*/
@JvmOverloads fun all_permission_sets(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/permission_sets",
mapOf("fields" to fields))
}
/**
* ### Create a permission set with the specified information. Permission sets are used by Roles.
*
* @param {WritePermissionSet} body
*
* POST /permission_sets -> ByteArray
*/
fun create_permission_set(
body: WritePermissionSet
) : SDKResponse {
return this.post<ByteArray>("/permission_sets", mapOf(), body)
}
/**
* ### Get information about all roles.
*
* @param {String} fields Requested fields.
* @param {DelimArray<String>} ids Optional list of ids to get specific roles.
*
* GET /roles -> ByteArray
*/
@JvmOverloads fun all_roles(
fields: String? = null,
ids: DelimArray<String>? = null
) : SDKResponse {
return this.get<ByteArray>("/roles",
mapOf("fields" to fields,
"ids" to ids))
}
/**
* ### Create a role with the specified information.
*
* @param {WriteRole} body
*
* POST /roles -> ByteArray
*/
fun create_role(
body: WriteRole
) : SDKResponse {
return this.post<ByteArray>("/roles", mapOf(), body)
}
/**
* ### Search roles
*
* Returns all role records that match the given search criteria.
*
* If multiple search params are given and `filter_or` is FALSE or not specified,
* search params are combined in a logical AND operation.
* Only rows that match *all* search param criteria will be returned.
*
* If `filter_or` is TRUE, multiple search params are combined in a logical OR operation.
* Results will include rows that match **any** of the search criteria.
*
* String search params use case-insensitive matching.
* String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions.
* example="dan%" will match "danger" and "Danzig" but not "David"
* example="D_m%" will match "Damage" and "dump"
*
* Integer search params can accept a single value or a comma separated list of values. The multiple
* values will be combined under a logical OR operation - results will match at least one of
* the given values.
*
* Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match
* or exclude (respectively) rows where the column is null.
*
* Boolean search params accept only "true" and "false" as values.
*
* @param {String} fields Requested fields.
* @param {Long} limit Number of results to return (used with `offset`).
* @param {Long} offset Number of results to skip before returning any (used with `limit`).
* @param {String} sorts Fields to sort by.
* @param {String} id Match role id.
* @param {String} name Match role name.
* @param {Boolean} built_in Match roles by built_in status.
* @param {Boolean} filter_or Combine given search criteria in a boolean OR expression.
*
* GET /roles/search -> ByteArray
*/
@JvmOverloads fun search_roles(
fields: String? = null,
limit: Long? = null,
offset: Long? = null,
sorts: String? = null,
id: String? = null,
name: String? = null,
built_in: Boolean? = null,
filter_or: Boolean? = null
) : SDKResponse {
return this.get<ByteArray>("/roles/search",
mapOf("fields" to fields,
"limit" to limit,
"offset" to offset,
"sorts" to sorts,
"id" to id,
"name" to name,
"built_in" to built_in,
"filter_or" to filter_or))
}
/**
* ### Search roles include user count
*
* Returns all role records that match the given search criteria, and attaches
* associated user counts.
*
* If multiple search params are given and `filter_or` is FALSE or not specified,
* search params are combined in a logical AND operation.
* Only rows that match *all* search param criteria will be returned.
*
* If `filter_or` is TRUE, multiple search params are combined in a logical OR operation.
* Results will include rows that match **any** of the search criteria.
*
* String search params use case-insensitive matching.
* String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions.
* example="dan%" will match "danger" and "Danzig" but not "David"
* example="D_m%" will match "Damage" and "dump"
*
* Integer search params can accept a single value or a comma separated list of values. The multiple
* values will be combined under a logical OR operation - results will match at least one of
* the given values.
*
* Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match
* or exclude (respectively) rows where the column is null.
*
* Boolean search params accept only "true" and "false" as values.
*
* @param {String} fields Requested fields.
* @param {Long} limit Number of results to return (used with `offset`).
* @param {Long} offset Number of results to skip before returning any (used with `limit`).
* @param {String} sorts Fields to sort by.
* @param {String} id Match role id.
* @param {String} name Match role name.
* @param {Boolean} built_in Match roles by built_in status.
* @param {Boolean} filter_or Combine given search criteria in a boolean OR expression.
*
* GET /roles/search/with_user_count -> ByteArray
*/
@JvmOverloads fun search_roles_with_user_count(
fields: String? = null,
limit: Long? = null,
offset: Long? = null,
sorts: String? = null,
id: String? = null,
name: String? = null,
built_in: Boolean? = null,
filter_or: Boolean? = null
) : SDKResponse {
return this.get<ByteArray>("/roles/search/with_user_count",
mapOf("fields" to fields,
"limit" to limit,
"offset" to offset,
"sorts" to sorts,
"id" to id,
"name" to name,
"built_in" to built_in,
"filter_or" to filter_or))
}
/**
* ### Get information about the role with a specific id.
*
* @param {String} role_id id of role
*
* GET /roles/{role_id} -> ByteArray
*/
fun role(
role_id: String
) : SDKResponse {
val path_role_id = encodeParam(role_id)
return this.get<ByteArray>("/roles/${path_role_id}", mapOf())
}
/**
* ### Update information about the role with a specific id.
*
* @param {String} role_id id of role
* @param {WriteRole} body
*
* PATCH /roles/{role_id} -> ByteArray
*/
fun update_role(
role_id: String,
body: WriteRole
) : SDKResponse {
val path_role_id = encodeParam(role_id)
return this.patch<ByteArray>("/roles/${path_role_id}", mapOf(), body)
}
/**
* ### Delete the role with a specific id.
*
* @param {String} role_id id of role
*
* DELETE /roles/{role_id} -> ByteArray
*/
fun delete_role(
role_id: String
) : SDKResponse {
val path_role_id = encodeParam(role_id)
return this.delete<ByteArray>("/roles/${path_role_id}", mapOf())
}
/**
* ### Get information about all the groups with the role that has a specific id.
*
* @param {String} role_id id of role
* @param {String} fields Requested fields.
*
* GET /roles/{role_id}/groups -> ByteArray
*/
@JvmOverloads fun role_groups(
role_id: String,
fields: String? = null
) : SDKResponse {
val path_role_id = encodeParam(role_id)
return this.get<ByteArray>("/roles/${path_role_id}/groups",
mapOf("fields" to fields))
}
/**
* ### Set all groups for a role, removing all existing group associations from that role.
*
* @param {String} role_id id of role
* @param {Array<String>} body
*
* PUT /roles/{role_id}/groups -> ByteArray
*/
fun set_role_groups(
role_id: String,
body: Array<String>
) : SDKResponse {
val path_role_id = encodeParam(role_id)
return this.put<ByteArray>("/roles/${path_role_id}/groups", mapOf(), body)
}
/**
* ### Get information about all the users with the role that has a specific id.
*
* @param {String} role_id id of role
* @param {String} fields Requested fields.
* @param {Boolean} direct_association_only Get only users associated directly with the role: exclude those only associated through groups.
*
* GET /roles/{role_id}/users -> ByteArray
*/
@JvmOverloads fun role_users(
role_id: String,
fields: String? = null,
direct_association_only: Boolean? = null
) : SDKResponse {
val path_role_id = encodeParam(role_id)
return this.get<ByteArray>("/roles/${path_role_id}/users",
mapOf("fields" to fields,
"direct_association_only" to direct_association_only))
}
/**
* ### Set all the users of the role with a specific id.
*
* @param {String} role_id id of role
* @param {Array<String>} body
*
* PUT /roles/{role_id}/users -> ByteArray
*/
fun set_role_users(
role_id: String,
body: Array<String>
) : SDKResponse {
val path_role_id = encodeParam(role_id)
return this.put<ByteArray>("/roles/${path_role_id}/users", mapOf(), body)
}
//endregion Role: Manage Roles
//region ScheduledPlan: Manage Scheduled Plans
/**
* ### Get Scheduled Plans for a Space
*
* Returns scheduled plans owned by the caller for a given space id.
*
* @param {String} space_id Space Id
* @param {String} fields Requested fields.
*
* GET /scheduled_plans/space/{space_id} -> ByteArray
*/
@JvmOverloads fun scheduled_plans_for_space(
space_id: String,
fields: String? = null
) : SDKResponse {
val path_space_id = encodeParam(space_id)
return this.get<ByteArray>("/scheduled_plans/space/${path_space_id}",
mapOf("fields" to fields))
}
/**
* ### Get Information About a Scheduled Plan
*
* Admins can fetch information about other users' Scheduled Plans.
*
* @param {String} scheduled_plan_id Scheduled Plan Id
* @param {String} fields Requested fields.
*
* GET /scheduled_plans/{scheduled_plan_id} -> ByteArray
*/
@JvmOverloads fun scheduled_plan(
scheduled_plan_id: String,
fields: String? = null
) : SDKResponse {
val path_scheduled_plan_id = encodeParam(scheduled_plan_id)
return this.get<ByteArray>("/scheduled_plans/${path_scheduled_plan_id}",
mapOf("fields" to fields))
}
/**
* ### Update a Scheduled Plan
*
* Admins can update other users' Scheduled Plans.
*
* Note: Any scheduled plan destinations specified in an update will **replace** all scheduled plan destinations
* currently defined for the scheduled plan.
*
* For Example: If a scheduled plan has destinations A, B, and C, and you call update on this scheduled plan
* specifying only B in the destinations, then destinations A and C will be deleted by the update.
*
* Updating a scheduled plan to assign null or an empty array to the scheduled_plan_destinations property is an error, as a scheduled plan must always have at least one destination.
*
* If you omit the scheduled_plan_destinations property from the object passed to update, then the destinations
* defined on the original scheduled plan will remain unchanged.
*
* #### Email Permissions:
*
* For details about permissions required to schedule delivery to email and the safeguards
* Looker offers to protect against sending to unauthorized email destinations, see [Email Domain Whitelist for Scheduled Looks](https://docs.looker.com/r/api/embed-permissions).
*
*
* #### Scheduled Plan Destination Formats
*
* Scheduled plan destinations must specify the data format to produce and send to the destination.
*
* Formats:
*
* | format | Description
* | :-----------: | :--- |
* | json | A JSON object containing a `data` property which contains an array of JSON objects, one per row. No metadata.
* | json_detail | Row data plus metadata describing the fields, pivots, table calcs, and other aspects of the query
* | inline_json | Same as the JSON format, except that the `data` property is a string containing JSON-escaped row data. Additional properties describe the data operation. This format is primarily used to send data to web hooks so that the web hook doesn't have to re-encode the JSON row data in order to pass it on to its ultimate destination.
* | csv | Comma separated values with a header
* | txt | Tab separated values with a header
* | html | Simple html
* | xlsx | MS Excel spreadsheet
* | wysiwyg_pdf | Dashboard rendered in a tiled layout to produce a PDF document
* | assembled_pdf | Dashboard rendered in a single column layout to produce a PDF document
* | wysiwyg_png | Dashboard rendered in a tiled layout to produce a PNG image
* ||
*
* Valid formats vary by destination type and source object. `wysiwyg_pdf` is only valid for dashboards, for example.
*
* @param {String} scheduled_plan_id Scheduled Plan Id
* @param {WriteScheduledPlan} body
*
* PATCH /scheduled_plans/{scheduled_plan_id} -> ByteArray
*/
fun update_scheduled_plan(
scheduled_plan_id: String,
body: WriteScheduledPlan
) : SDKResponse {
val path_scheduled_plan_id = encodeParam(scheduled_plan_id)
return this.patch<ByteArray>("/scheduled_plans/${path_scheduled_plan_id}", mapOf(), body)
}
/**
* ### Delete a Scheduled Plan
*
* Normal users can only delete their own scheduled plans.
* Admins can delete other users' scheduled plans.
* This delete cannot be undone.
*
* @param {String} scheduled_plan_id Scheduled Plan Id
*
* DELETE /scheduled_plans/{scheduled_plan_id} -> ByteArray
*/
fun delete_scheduled_plan(
scheduled_plan_id: String
) : SDKResponse {
val path_scheduled_plan_id = encodeParam(scheduled_plan_id)
return this.delete<ByteArray>("/scheduled_plans/${path_scheduled_plan_id}", mapOf())
}
/**
* ### List All Scheduled Plans
*
* Returns all scheduled plans which belong to the caller or given user.
*
* If no user_id is provided, this function returns the scheduled plans owned by the caller.
*
*
* To list all schedules for all users, pass `all_users=true`.
*
*
* The caller must have `see_schedules` permission to see other users' scheduled plans.
*
* @param {String} user_id Return scheduled plans belonging to this user_id. If not provided, returns scheduled plans owned by the caller.
* @param {String} fields Comma delimited list of field names. If provided, only the fields specified will be included in the response
* @param {Boolean} all_users Return scheduled plans belonging to all users (caller needs see_schedules permission)
*
* GET /scheduled_plans -> ByteArray
*/
@JvmOverloads fun all_scheduled_plans(
user_id: String? = null,
fields: String? = null,
all_users: Boolean? = null
) : SDKResponse {
return this.get<ByteArray>("/scheduled_plans",
mapOf("user_id" to user_id,
"fields" to fields,
"all_users" to all_users))
}
/**
* ### Create a Scheduled Plan
*
* Create a scheduled plan to render a Look or Dashboard on a recurring schedule.
*
* To create a scheduled plan, you MUST provide values for the following fields:
* `name`
* and
* `look_id`, `dashboard_id`, `lookml_dashboard_id`, or `query_id`
* and
* `cron_tab` or `datagroup`
* and
* at least one scheduled_plan_destination
*
* A scheduled plan MUST have at least one scheduled_plan_destination defined.
*
* When `look_id` is set, `require_no_results`, `require_results`, and `require_change` are all required.
*
* If `create_scheduled_plan` fails with a 422 error, be sure to look at the error messages in the response which will explain exactly what fields are missing or values that are incompatible.
*
* The queries that provide the data for the look or dashboard are run in the context of user account that owns the scheduled plan.
*
* When `run_as_recipient` is `false` or not specified, the queries that provide the data for the
* look or dashboard are run in the context of user account that owns the scheduled plan.
*
* When `run_as_recipient` is `true` and all the email recipients are Looker user accounts, the
* queries are run in the context of each recipient, so different recipients may see different
* data from the same scheduled render of a look or dashboard. For more details, see [Run As Recipient](https://docs.looker.com/r/admin/run-as-recipient).
*
* Admins can create and modify scheduled plans on behalf of other users by specifying a user id.
* Non-admin users may not create or modify scheduled plans by or for other users.
*
* #### Email Permissions:
*
* For details about permissions required to schedule delivery to email and the safeguards
* Looker offers to protect against sending to unauthorized email destinations, see [Email Domain Whitelist for Scheduled Looks](https://docs.looker.com/r/api/embed-permissions).
*
*
* #### Scheduled Plan Destination Formats
*
* Scheduled plan destinations must specify the data format to produce and send to the destination.
*
* Formats:
*
* | format | Description
* | :-----------: | :--- |
* | json | A JSON object containing a `data` property which contains an array of JSON objects, one per row. No metadata.
* | json_detail | Row data plus metadata describing the fields, pivots, table calcs, and other aspects of the query
* | inline_json | Same as the JSON format, except that the `data` property is a string containing JSON-escaped row data. Additional properties describe the data operation. This format is primarily used to send data to web hooks so that the web hook doesn't have to re-encode the JSON row data in order to pass it on to its ultimate destination.
* | csv | Comma separated values with a header
* | txt | Tab separated values with a header
* | html | Simple html
* | xlsx | MS Excel spreadsheet
* | wysiwyg_pdf | Dashboard rendered in a tiled layout to produce a PDF document
* | assembled_pdf | Dashboard rendered in a single column layout to produce a PDF document
* | wysiwyg_png | Dashboard rendered in a tiled layout to produce a PNG image
* ||
*
* Valid formats vary by destination type and source object. `wysiwyg_pdf` is only valid for dashboards, for example.
*
* @param {WriteScheduledPlan} body
*
* POST /scheduled_plans -> ByteArray
*/
fun create_scheduled_plan(
body: WriteScheduledPlan
) : SDKResponse {
return this.post<ByteArray>("/scheduled_plans", mapOf(), body)
}
/**
* ### Run a Scheduled Plan Immediately
*
* Create a scheduled plan that runs only once, and immediately.
*
* This can be useful for testing a Scheduled Plan before committing to a production schedule.
*
* Admins can create scheduled plans on behalf of other users by specifying a user id.
*
* This API is rate limited to prevent it from being used for relay spam or DoS attacks
*
* #### Email Permissions:
*
* For details about permissions required to schedule delivery to email and the safeguards
* Looker offers to protect against sending to unauthorized email destinations, see [Email Domain Whitelist for Scheduled Looks](https://docs.looker.com/r/api/embed-permissions).
*
*
* #### Scheduled Plan Destination Formats
*
* Scheduled plan destinations must specify the data format to produce and send to the destination.
*
* Formats:
*
* | format | Description
* | :-----------: | :--- |
* | json | A JSON object containing a `data` property which contains an array of JSON objects, one per row. No metadata.
* | json_detail | Row data plus metadata describing the fields, pivots, table calcs, and other aspects of the query
* | inline_json | Same as the JSON format, except that the `data` property is a string containing JSON-escaped row data. Additional properties describe the data operation. This format is primarily used to send data to web hooks so that the web hook doesn't have to re-encode the JSON row data in order to pass it on to its ultimate destination.
* | csv | Comma separated values with a header
* | txt | Tab separated values with a header
* | html | Simple html
* | xlsx | MS Excel spreadsheet
* | wysiwyg_pdf | Dashboard rendered in a tiled layout to produce a PDF document
* | assembled_pdf | Dashboard rendered in a single column layout to produce a PDF document
* | wysiwyg_png | Dashboard rendered in a tiled layout to produce a PNG image
* ||
*
* Valid formats vary by destination type and source object. `wysiwyg_pdf` is only valid for dashboards, for example.
*
* @param {WriteScheduledPlan} body
*
* POST /scheduled_plans/run_once -> ByteArray
*/
fun scheduled_plan_run_once(
body: WriteScheduledPlan
) : SDKResponse {
return this.post<ByteArray>("/scheduled_plans/run_once", mapOf(), body)
}
/**
* ### Get Scheduled Plans for a Look
*
* Returns all scheduled plans for a look which belong to the caller or given user.
*
* If no user_id is provided, this function returns the scheduled plans owned by the caller.
*
*
* To list all schedules for all users, pass `all_users=true`.
*
*
* The caller must have `see_schedules` permission to see other users' scheduled plans.
*
* @param {String} look_id Look Id
* @param {String} user_id User Id (default is requesting user if not specified)
* @param {String} fields Requested fields.
* @param {Boolean} all_users Return scheduled plans belonging to all users for the look
*
* GET /scheduled_plans/look/{look_id} -> ByteArray
*/
@JvmOverloads fun scheduled_plans_for_look(
look_id: String,
user_id: String? = null,
fields: String? = null,
all_users: Boolean? = null
) : SDKResponse {
val path_look_id = encodeParam(look_id)
return this.get<ByteArray>("/scheduled_plans/look/${path_look_id}",
mapOf("user_id" to user_id,
"fields" to fields,
"all_users" to all_users))
}
/**
* ### Get Scheduled Plans for a Dashboard
*
* Returns all scheduled plans for a dashboard which belong to the caller or given user.
*
* If no user_id is provided, this function returns the scheduled plans owned by the caller.
*
*
* To list all schedules for all users, pass `all_users=true`.
*
*
* The caller must have `see_schedules` permission to see other users' scheduled plans.
*
* @param {String} dashboard_id Dashboard Id
* @param {String} user_id User Id (default is requesting user if not specified)
* @param {Boolean} all_users Return scheduled plans belonging to all users for the dashboard
* @param {String} fields Requested fields.
*
* GET /scheduled_plans/dashboard/{dashboard_id} -> ByteArray
*/
@JvmOverloads fun scheduled_plans_for_dashboard(
dashboard_id: String,
user_id: String? = null,
all_users: Boolean? = null,
fields: String? = null
) : SDKResponse {
val path_dashboard_id = encodeParam(dashboard_id)
return this.get<ByteArray>("/scheduled_plans/dashboard/${path_dashboard_id}",
mapOf("user_id" to user_id,
"all_users" to all_users,
"fields" to fields))
}
/**
* ### Get Scheduled Plans for a LookML Dashboard
*
* Returns all scheduled plans for a LookML Dashboard which belong to the caller or given user.
*
* If no user_id is provided, this function returns the scheduled plans owned by the caller.
*
*
* To list all schedules for all users, pass `all_users=true`.
*
*
* The caller must have `see_schedules` permission to see other users' scheduled plans.
*
* @param {String} lookml_dashboard_id LookML Dashboard Id
* @param {String} user_id User Id (default is requesting user if not specified)
* @param {String} fields Requested fields.
* @param {Boolean} all_users Return scheduled plans belonging to all users for the dashboard
*
* GET /scheduled_plans/lookml_dashboard/{lookml_dashboard_id} -> ByteArray
*/
@JvmOverloads fun scheduled_plans_for_lookml_dashboard(
lookml_dashboard_id: String,
user_id: String? = null,
fields: String? = null,
all_users: Boolean? = null
) : SDKResponse {
val path_lookml_dashboard_id = encodeParam(lookml_dashboard_id)
return this.get<ByteArray>("/scheduled_plans/lookml_dashboard/${path_lookml_dashboard_id}",
mapOf("user_id" to user_id,
"fields" to fields,
"all_users" to all_users))
}
/**
* ### Run a Scheduled Plan By Id Immediately
* This function creates a run-once schedule plan based on an existing scheduled plan,
* applies modifications (if any) to the new scheduled plan, and runs the new schedule plan immediately.
* This can be useful for testing modifications to an existing scheduled plan before committing to a production schedule.
*
* This function internally performs the following operations:
*
* 1. Copies the properties of the existing scheduled plan into a new scheduled plan
* 2. Copies any properties passed in the JSON body of this request into the new scheduled plan (replacing the original values)
* 3. Creates the new scheduled plan
* 4. Runs the new scheduled plan
*
* The original scheduled plan is not modified by this operation.
* Admins can create, modify, and run scheduled plans on behalf of other users by specifying a user id.
* Non-admins can only create, modify, and run their own scheduled plans.
*
* #### Email Permissions:
*
* For details about permissions required to schedule delivery to email and the safeguards
* Looker offers to protect against sending to unauthorized email destinations, see [Email Domain Whitelist for Scheduled Looks](https://docs.looker.com/r/api/embed-permissions).
*
*
* #### Scheduled Plan Destination Formats
*
* Scheduled plan destinations must specify the data format to produce and send to the destination.
*
* Formats:
*
* | format | Description
* | :-----------: | :--- |
* | json | A JSON object containing a `data` property which contains an array of JSON objects, one per row. No metadata.
* | json_detail | Row data plus metadata describing the fields, pivots, table calcs, and other aspects of the query
* | inline_json | Same as the JSON format, except that the `data` property is a string containing JSON-escaped row data. Additional properties describe the data operation. This format is primarily used to send data to web hooks so that the web hook doesn't have to re-encode the JSON row data in order to pass it on to its ultimate destination.
* | csv | Comma separated values with a header
* | txt | Tab separated values with a header
* | html | Simple html
* | xlsx | MS Excel spreadsheet
* | wysiwyg_pdf | Dashboard rendered in a tiled layout to produce a PDF document
* | assembled_pdf | Dashboard rendered in a single column layout to produce a PDF document
* | wysiwyg_png | Dashboard rendered in a tiled layout to produce a PNG image
* ||
*
* Valid formats vary by destination type and source object. `wysiwyg_pdf` is only valid for dashboards, for example.
*
*
*
* This API is rate limited to prevent it from being used for relay spam or DoS attacks
*
* @param {String} scheduled_plan_id Id of schedule plan to copy and run
* @param {WriteScheduledPlan} body
*
* POST /scheduled_plans/{scheduled_plan_id}/run_once -> ByteArray
*/
@JvmOverloads fun scheduled_plan_run_once_by_id(
scheduled_plan_id: String,
body: WriteScheduledPlan? = null
) : SDKResponse {
val path_scheduled_plan_id = encodeParam(scheduled_plan_id)
return this.post<ByteArray>("/scheduled_plans/${path_scheduled_plan_id}/run_once", mapOf(), body)
}
//endregion ScheduledPlan: Manage Scheduled Plans
//region Session: Session Information
/**
* ### Get API Session
*
* Returns information about the current API session, such as which workspace is selected for the session.
*
* GET /session -> ByteArray
*/
fun session(
) : SDKResponse {
return this.get<ByteArray>("/session", mapOf())
}
/**
* ### Update API Session
*
* #### API Session Workspace
*
* You can use this endpoint to change the active workspace for the current API session.
*
* Only one workspace can be active in a session. The active workspace can be changed
* any number of times in a session.
*
* The default workspace for API sessions is the "production" workspace.
*
* All Looker APIs that use projects or lookml models (such as running queries) will
* use the version of project and model files defined by this workspace for the lifetime of the
* current API session or until the session workspace is changed again.
*
* An API session has the same lifetime as the access_token used to authenticate API requests. Each successful
* API login generates a new access_token and a new API session.
*
* If your Looker API client application needs to work in a dev workspace across multiple
* API sessions, be sure to select the dev workspace after each login.
*
* @param {WriteApiSession} body
*
* PATCH /session -> ByteArray
*/
fun update_session(
body: WriteApiSession
) : SDKResponse {
return this.patch<ByteArray>("/session", mapOf(), body)
}
//endregion Session: Session Information
//region Theme: Manage Themes
/**
* ### Get an array of all existing themes
*
* Get a **single theme** by id with [Theme](#!/Theme/theme)
*
* This method returns an array of all existing themes. The active time for the theme is not considered.
*
* **Note**: Custom themes needs to be enabled by Looker. Unless custom themes are enabled, only the automatically generated default theme can be used. Please contact your Account Manager or help.looker.com to update your license for this feature.
*
* @param {String} fields Requested fields.
*
* GET /themes -> ByteArray
*/
@JvmOverloads fun all_themes(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/themes",
mapOf("fields" to fields))
}
/**
* ### Create a theme
*
* Creates a new theme object, returning the theme details, including the created id.
*
* If `settings` are not specified, the default theme settings will be copied into the new theme.
*
* The theme `name` can only contain alphanumeric characters or underscores. Theme names should not contain any confidential information, such as customer names.
*
* **Update** an existing theme with [Update Theme](#!/Theme/update_theme)
*
* **Permanently delete** an existing theme with [Delete Theme](#!/Theme/delete_theme)
*
* For more information, see [Creating and Applying Themes](https://docs.looker.com/r/admin/themes).
*
* **Note**: Custom themes needs to be enabled by Looker. Unless custom themes are enabled, only the automatically generated default theme can be used. Please contact your Account Manager or help.looker.com to update your license for this feature.
*
* @param {WriteTheme} body
*
* POST /themes -> ByteArray
*/
fun create_theme(
body: WriteTheme
) : SDKResponse {
return this.post<ByteArray>("/themes", mapOf(), body)
}
/**
* ### Search all themes for matching criteria.
*
* Returns an **array of theme objects** that match the specified search criteria.
*
* | Search Parameters | Description
* | :-------------------: | :------ |
* | `begin_at` only | Find themes active at or after `begin_at`
* | `end_at` only | Find themes active at or before `end_at`
* | both set | Find themes with an active inclusive period between `begin_at` and `end_at`
*
* Note: Range matching requires boolean AND logic.
* When using `begin_at` and `end_at` together, do not use `filter_or`=TRUE
*
* If multiple search params are given and `filter_or` is FALSE or not specified,
* search params are combined in a logical AND operation.
* Only rows that match *all* search param criteria will be returned.
*
* If `filter_or` is TRUE, multiple search params are combined in a logical OR operation.
* Results will include rows that match **any** of the search criteria.
*
* String search params use case-insensitive matching.
* String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions.
* example="dan%" will match "danger" and "Danzig" but not "David"
* example="D_m%" will match "Damage" and "dump"
*
* Integer search params can accept a single value or a comma separated list of values. The multiple
* values will be combined under a logical OR operation - results will match at least one of
* the given values.
*
* Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match
* or exclude (respectively) rows where the column is null.
*
* Boolean search params accept only "true" and "false" as values.
*
*
* Get a **single theme** by id with [Theme](#!/Theme/theme)
*
* **Note**: Custom themes needs to be enabled by Looker. Unless custom themes are enabled, only the automatically generated default theme can be used. Please contact your Account Manager or help.looker.com to update your license for this feature.
*
* @param {String} id Match theme id.
* @param {String} name Match theme name.
* @param {Date} begin_at Timestamp for activation.
* @param {Date} end_at Timestamp for expiration.
* @param {Long} limit Number of results to return (used with `offset`).
* @param {Long} offset Number of results to skip before returning any (used with `limit`).
* @param {String} sorts Fields to sort by.
* @param {String} fields Requested fields.
* @param {Boolean} filter_or Combine given search criteria in a boolean OR expression
*
* GET /themes/search -> ByteArray
*/
@JvmOverloads fun search_themes(
id: String? = null,
name: String? = null,
begin_at: Date? = null,
end_at: Date? = null,
limit: Long? = null,
offset: Long? = null,
sorts: String? = null,
fields: String? = null,
filter_or: Boolean? = null
) : SDKResponse {
return this.get<ByteArray>("/themes/search",
mapOf("id" to id,
"name" to name,
"begin_at" to begin_at,
"end_at" to end_at,
"limit" to limit,
"offset" to offset,
"sorts" to sorts,
"fields" to fields,
"filter_or" to filter_or))
}
/**
* ### Get the default theme
*
* Returns the active theme object set as the default.
*
* The **default** theme name can be set in the UI on the Admin|Theme UI page
*
* The optional `ts` parameter can specify a different timestamp than "now." If specified, it returns the default theme at the time indicated.
*
* @param {Date} ts Timestamp representing the target datetime for the active period. Defaults to 'now'
*
* GET /themes/default -> ByteArray
*/
@JvmOverloads fun default_theme(
ts: Date? = null
) : SDKResponse {
return this.get<ByteArray>("/themes/default",
mapOf("ts" to ts))
}
/**
* ### Set the global default theme by theme name
*
* Only Admin users can call this function.
*
* Only an active theme with no expiration (`end_at` not set) can be assigned as the default theme. As long as a theme has an active record with no expiration, it can be set as the default.
*
* [Create Theme](#!/Theme/create) has detailed information on rules for default and active themes
*
* Returns the new specified default theme object.
*
* **Note**: Custom themes needs to be enabled by Looker. Unless custom themes are enabled, only the automatically generated default theme can be used. Please contact your Account Manager or help.looker.com to update your license for this feature.
*
* @param {String} name Name of theme to set as default
*
* PUT /themes/default -> ByteArray
*/
fun set_default_theme(
name: String
) : SDKResponse {
return this.put<ByteArray>("/themes/default",
mapOf("name" to name))
}
/**
* ### Get active themes
*
* Returns an array of active themes.
*
* If the `name` parameter is specified, it will return an array with one theme if it's active and found.
*
* The optional `ts` parameter can specify a different timestamp than "now."
*
* **Note**: Custom themes needs to be enabled by Looker. Unless custom themes are enabled, only the automatically generated default theme can be used. Please contact your Account Manager or help.looker.com to update your license for this feature.
*
* @param {String} name Name of theme
* @param {Date} ts Timestamp representing the target datetime for the active period. Defaults to 'now'
* @param {String} fields Requested fields.
*
* GET /themes/active -> ByteArray
*/
@JvmOverloads fun active_themes(
name: String? = null,
ts: Date? = null,
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/themes/active",
mapOf("name" to name,
"ts" to ts,
"fields" to fields))
}
/**
* ### Get the named theme if it's active. Otherwise, return the default theme
*
* The optional `ts` parameter can specify a different timestamp than "now."
* Note: API users with `show` ability can call this function
*
* **Note**: Custom themes needs to be enabled by Looker. Unless custom themes are enabled, only the automatically generated default theme can be used. Please contact your Account Manager or help.looker.com to update your license for this feature.
*
* @param {String} name Name of theme
* @param {Date} ts Timestamp representing the target datetime for the active period. Defaults to 'now'
*
* GET /themes/theme_or_default -> ByteArray
*/
@JvmOverloads fun theme_or_default(
name: String,
ts: Date? = null
) : SDKResponse {
return this.get<ByteArray>("/themes/theme_or_default",
mapOf("name" to name,
"ts" to ts))
}
/**
* ### Validate a theme with the specified information
*
* Validates all values set for the theme, returning any errors encountered, or 200 OK if valid
*
* See [Create Theme](#!/Theme/create_theme) for constraints
*
* **Note**: Custom themes needs to be enabled by Looker. Unless custom themes are enabled, only the automatically generated default theme can be used. Please contact your Account Manager or help.looker.com to update your license for this feature.
*
* @param {WriteTheme} body
*
* POST /themes/validate -> ByteArray
*/
fun validate_theme(
body: WriteTheme
) : SDKResponse {
return this.post<ByteArray>("/themes/validate", mapOf(), body)
}
/**
* ### Get a theme by ID
*
* Use this to retrieve a specific theme, whether or not it's currently active.
*
* **Note**: Custom themes needs to be enabled by Looker. Unless custom themes are enabled, only the automatically generated default theme can be used. Please contact your Account Manager or help.looker.com to update your license for this feature.
*
* @param {String} theme_id Id of theme
* @param {String} fields Requested fields.
*
* GET /themes/{theme_id} -> ByteArray
*/
@JvmOverloads fun theme(
theme_id: String,
fields: String? = null
) : SDKResponse {
val path_theme_id = encodeParam(theme_id)
return this.get<ByteArray>("/themes/${path_theme_id}",
mapOf("fields" to fields))
}
/**
* ### Update the theme by id.
*
* **Note**: Custom themes needs to be enabled by Looker. Unless custom themes are enabled, only the automatically generated default theme can be used. Please contact your Account Manager or help.looker.com to update your license for this feature.
*
* @param {String} theme_id Id of theme
* @param {WriteTheme} body
*
* PATCH /themes/{theme_id} -> ByteArray
*/
fun update_theme(
theme_id: String,
body: WriteTheme
) : SDKResponse {
val path_theme_id = encodeParam(theme_id)
return this.patch<ByteArray>("/themes/${path_theme_id}", mapOf(), body)
}
/**
* ### Delete a specific theme by id
*
* This operation permanently deletes the identified theme from the database.
*
* Because multiple themes can have the same name (with different activation time spans) themes can only be deleted by ID.
*
* All IDs associated with a theme name can be retrieved by searching for the theme name with [Theme Search](#!/Theme/search).
*
* **Note**: Custom themes needs to be enabled by Looker. Unless custom themes are enabled, only the automatically generated default theme can be used. Please contact your Account Manager or help.looker.com to update your license for this feature.
*
* @param {String} theme_id Id of theme
*
* DELETE /themes/{theme_id} -> ByteArray
*/
fun delete_theme(
theme_id: String
) : SDKResponse {
val path_theme_id = encodeParam(theme_id)
return this.delete<ByteArray>("/themes/${path_theme_id}", mapOf())
}
//endregion Theme: Manage Themes
//region User: Manage Users
/**
* ### Search email credentials
*
* Returns all credentials_email records that match the given search criteria.
*
* If multiple search params are given and `filter_or` is FALSE or not specified,
* search params are combined in a logical AND operation.
* Only rows that match *all* search param criteria will be returned.
*
* If `filter_or` is TRUE, multiple search params are combined in a logical OR operation.
* Results will include rows that match **any** of the search criteria.
*
* String search params use case-insensitive matching.
* String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions.
* example="dan%" will match "danger" and "Danzig" but not "David"
* example="D_m%" will match "Damage" and "dump"
*
* Integer search params can accept a single value or a comma separated list of values. The multiple
* values will be combined under a logical OR operation - results will match at least one of
* the given values.
*
* Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match
* or exclude (respectively) rows where the column is null.
*
* Boolean search params accept only "true" and "false" as values.
*
* @param {String} fields Requested fields.
* @param {Long} limit Number of results to return (used with `offset`).
* @param {Long} offset Number of results to skip before returning any (used with `limit`).
* @param {String} sorts Fields to sort by.
* @param {String} id Match credentials_email id.
* @param {String} email Match credentials_email email.
* @param {String} emails Find credentials_email that match given emails.
* @param {Boolean} filter_or Combine given search criteria in a boolean OR expression.
*
* GET /credentials_email/search -> ByteArray
*/
@JvmOverloads fun search_credentials_email(
fields: String? = null,
limit: Long? = null,
offset: Long? = null,
sorts: String? = null,
id: String? = null,
email: String? = null,
emails: String? = null,
filter_or: Boolean? = null
) : SDKResponse {
return this.get<ByteArray>("/credentials_email/search",
mapOf("fields" to fields,
"limit" to limit,
"offset" to offset,
"sorts" to sorts,
"id" to id,
"email" to email,
"emails" to emails,
"filter_or" to filter_or))
}
/**
* ### Get information about the current user; i.e. the user account currently calling the API.
*
* @param {String} fields Requested fields.
*
* GET /user -> ByteArray
*/
@JvmOverloads fun me(
fields: String? = null
) : SDKResponse {
return this.get<ByteArray>("/user",
mapOf("fields" to fields))
}
/**
* ### Get information about all users.
*
* @param {String} fields Requested fields.
* @param {Long} page DEPRECATED. Use limit and offset instead. Return only page N of paginated results
* @param {Long} per_page DEPRECATED. Use limit and offset instead. Return N rows of data per page
* @param {Long} limit Number of results to return. (used with offset and takes priority over page and per_page)
* @param {Long} offset Number of results to skip before returning any. (used with limit and takes priority over page and per_page)
* @param {String} sorts Fields to sort by.
* @param {DelimArray<String>} ids Optional list of ids to get specific users.
*
* GET /users -> ByteArray
*/
@JvmOverloads fun all_users(
fields: String? = null,
page: Long? = null,
per_page: Long? = null,
limit: Long? = null,
offset: Long? = null,
sorts: String? = null,
ids: DelimArray<String>? = null
) : SDKResponse {
return this.get<ByteArray>("/users",
mapOf("fields" to fields,
"page" to page,
"per_page" to per_page,
"limit" to limit,
"offset" to offset,
"sorts" to sorts,
"ids" to ids))
}
/**
* ### Create a user with the specified information.
*
* @param {WriteUser} body
* @param {String} fields Requested fields.
*
* POST /users -> ByteArray
*/
@JvmOverloads fun create_user(
body: WriteUser? = null,
fields: String? = null
) : SDKResponse {
return this.post<ByteArray>("/users",
mapOf("fields" to fields), body)
}
/**
* ### Search users
*
* Returns all<sup>*</sup> user records that match the given search criteria.
*
* If multiple search params are given and `filter_or` is FALSE or not specified,
* search params are combined in a logical AND operation.
* Only rows that match *all* search param criteria will be returned.
*
* If `filter_or` is TRUE, multiple search params are combined in a logical OR operation.
* Results will include rows that match **any** of the search criteria.
*
* String search params use case-insensitive matching.
* String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions.
* example="dan%" will match "danger" and "Danzig" but not "David"
* example="D_m%" will match "Damage" and "dump"
*
* Integer search params can accept a single value or a comma separated list of values. The multiple
* values will be combined under a logical OR operation - results will match at least one of
* the given values.
*
* Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match
* or exclude (respectively) rows where the column is null.
*
* Boolean search params accept only "true" and "false" as values.
*
*
* (<sup>*</sup>) Results are always filtered to the level of information the caller is permitted to view.
* Looker admins can see all user details; normal users in an open system can see
* names of other users but no details; normal users in a closed system can only see
* names of other users who are members of the same group as the user.
*
* @param {String} fields Include only these fields in the response
* @param {Long} page DEPRECATED. Use limit and offset instead. Return only page N of paginated results
* @param {Long} per_page DEPRECATED. Use limit and offset instead. Return N rows of data per page
* @param {Long} limit Number of results to return. (used with offset and takes priority over page and per_page)
* @param {Long} offset Number of results to skip before returning any. (used with limit and takes priority over page and per_page)
* @param {String} sorts Fields to sort by.
* @param {String} id Match User Id.
* @param {String} first_name Match First name.
* @param {String} last_name Match Last name.
* @param {Boolean} verified_looker_employee Search for user accounts associated with Looker employees
* @param {Boolean} embed_user Search for only embed users
* @param {String} email Search for the user with this email address
* @param {Boolean} is_disabled Search for disabled user accounts
* @param {Boolean} filter_or Combine given search criteria in a boolean OR expression
* @param {String} content_metadata_id Search for users who have access to this content_metadata item
* @param {String} group_id Search for users who are direct members of this group
*
* GET /users/search -> ByteArray
*/
@JvmOverloads fun search_users(
fields: String? = null,
page: Long? = null,
per_page: Long? = null,
limit: Long? = null,
offset: Long? = null,
sorts: String? = null,
id: String? = null,
first_name: String? = null,
last_name: String? = null,
verified_looker_employee: Boolean? = null,
embed_user: Boolean? = null,
email: String? = null,
is_disabled: Boolean? = null,
filter_or: Boolean? = null,
content_metadata_id: String? = null,
group_id: String? = null
) : SDKResponse {
return this.get<ByteArray>("/users/search",
mapOf("fields" to fields,
"page" to page,
"per_page" to per_page,
"limit" to limit,
"offset" to offset,
"sorts" to sorts,
"id" to id,
"first_name" to first_name,
"last_name" to last_name,
"verified_looker_employee" to verified_looker_employee,
"embed_user" to embed_user,
"email" to email,
"is_disabled" to is_disabled,
"filter_or" to filter_or,
"content_metadata_id" to content_metadata_id,
"group_id" to group_id))
}
/**
* ### Search for user accounts by name
*
* Returns all user accounts where `first_name` OR `last_name` OR `email` field values match a pattern.
* The pattern can contain `%` and `_` wildcards as in SQL LIKE expressions.
*
* Any additional search params will be combined into a logical AND expression.
*
* @param {String} pattern Pattern to match
* @param {String} fields Include only these fields in the response
* @param {Long} page DEPRECATED. Use limit and offset instead. Return only page N of paginated results
* @param {Long} per_page DEPRECATED. Use limit and offset instead. Return N rows of data per page
* @param {Long} limit Number of results to return. (used with offset and takes priority over page and per_page)
* @param {Long} offset Number of results to skip before returning any. (used with limit and takes priority over page and per_page)
* @param {String} sorts Fields to sort by
* @param {String} id Match User Id
* @param {String} first_name Match First name
* @param {String} last_name Match Last name
* @param {Boolean} verified_looker_employee Match Verified Looker employee
* @param {String} email Match Email Address
* @param {Boolean} is_disabled Include or exclude disabled accounts in the results
*
* GET /users/search/names/{pattern} -> ByteArray
*/
@JvmOverloads fun search_users_names(
pattern: String,
fields: String? = null,
page: Long? = null,
per_page: Long? = null,
limit: Long? = null,
offset: Long? = null,
sorts: String? = null,
id: String? = null,
first_name: String? = null,
last_name: String? = null,
verified_looker_employee: Boolean? = null,
email: String? = null,
is_disabled: Boolean? = null
) : SDKResponse {
val path_pattern = encodeParam(pattern)
return this.get<ByteArray>("/users/search/names/${path_pattern}",
mapOf("fields" to fields,
"page" to page,
"per_page" to per_page,
"limit" to limit,
"offset" to offset,
"sorts" to sorts,
"id" to id,
"first_name" to first_name,
"last_name" to last_name,
"verified_looker_employee" to verified_looker_employee,
"email" to email,
"is_disabled" to is_disabled))
}
/**
* ### Get information about the user with a specific id.
*
* If the caller is an admin or the caller is the user being specified, then full user information will
* be returned. Otherwise, a minimal 'public' variant of the user information will be returned. This contains
* The user name and avatar url, but no sensitive information.
*
* @param {String} user_id Id of user
* @param {String} fields Requested fields.
*
* GET /users/{user_id} -> ByteArray
*/
@JvmOverloads fun user(
user_id: String,
fields: String? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.get<ByteArray>("/users/${path_user_id}",
mapOf("fields" to fields))
}
/**
* ### Update information about the user with a specific id.
*
* @param {String} user_id Id of user
* @param {WriteUser} body
* @param {String} fields Requested fields.
*
* PATCH /users/{user_id} -> ByteArray
*/
@JvmOverloads fun update_user(
user_id: String,
body: WriteUser,
fields: String? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.patch<ByteArray>("/users/${path_user_id}",
mapOf("fields" to fields), body)
}
/**
* ### Delete the user with a specific id.
*
* **DANGER** this will delete the user and all looks and other information owned by the user.
*
* @param {String} user_id Id of user
*
* DELETE /users/{user_id} -> ByteArray
*/
fun delete_user(
user_id: String
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.delete<ByteArray>("/users/${path_user_id}", mapOf())
}
/**
* ### Get information about the user with a credential of given type with specific id.
*
* This is used to do things like find users by their embed external_user_id. Or, find the user with
* a given api3 client_id, etc. The 'credential_type' matches the 'type' name of the various credential
* types. It must be one of the values listed in the table below. The 'credential_id' is your unique Id
* for the user and is specific to each type of credential.
*
* An example using the Ruby sdk might look like:
*
* `sdk.user_for_credential('embed', 'customer-4959425')`
*
* This table shows the supported 'Credential Type' strings. The right column is for reference; it shows
* which field in the given credential type is actually searched when finding a user with the supplied
* 'credential_id'.
*
* | Credential Types | Id Field Matched |
* | ---------------- | ---------------- |
* | email | email |
* | google | google_user_id |
* | saml | saml_user_id |
* | oidc | oidc_user_id |
* | ldap | ldap_id |
* | api | token |
* | api3 | client_id |
* | embed | external_user_id |
* | looker_openid | email |
*
* **NOTE**: The 'api' credential type was only used with the legacy Looker query API and is no longer supported. The credential type for API you are currently looking at is 'api3'.
*
* @param {String} credential_type Type name of credential
* @param {String} credential_id Id of credential
* @param {String} fields Requested fields.
*
* GET /users/credential/{credential_type}/{credential_id} -> ByteArray
*/
@JvmOverloads fun user_for_credential(
credential_type: String,
credential_id: String,
fields: String? = null
) : SDKResponse {
val path_credential_type = encodeParam(credential_type)
val path_credential_id = encodeParam(credential_id)
return this.get<ByteArray>("/users/credential/${path_credential_type}/${path_credential_id}",
mapOf("fields" to fields))
}
/**
* ### Email/password login information for the specified user.
*
* @param {String} user_id Id of user
* @param {String} fields Requested fields.
*
* GET /users/{user_id}/credentials_email -> ByteArray
*/
@JvmOverloads fun user_credentials_email(
user_id: String,
fields: String? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.get<ByteArray>("/users/${path_user_id}/credentials_email",
mapOf("fields" to fields))
}
/**
* ### Email/password login information for the specified user.
*
* @param {String} user_id Id of user
* @param {WriteCredentialsEmail} body
* @param {String} fields Requested fields.
*
* POST /users/{user_id}/credentials_email -> ByteArray
*/
@JvmOverloads fun create_user_credentials_email(
user_id: String,
body: WriteCredentialsEmail,
fields: String? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.post<ByteArray>("/users/${path_user_id}/credentials_email",
mapOf("fields" to fields), body)
}
/**
* ### Email/password login information for the specified user.
*
* @param {String} user_id Id of user
* @param {WriteCredentialsEmail} body
* @param {String} fields Requested fields.
*
* PATCH /users/{user_id}/credentials_email -> ByteArray
*/
@JvmOverloads fun update_user_credentials_email(
user_id: String,
body: WriteCredentialsEmail,
fields: String? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.patch<ByteArray>("/users/${path_user_id}/credentials_email",
mapOf("fields" to fields), body)
}
/**
* ### Email/password login information for the specified user.
*
* @param {String} user_id Id of user
*
* DELETE /users/{user_id}/credentials_email -> ByteArray
*/
fun delete_user_credentials_email(
user_id: String
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.delete<ByteArray>("/users/${path_user_id}/credentials_email", mapOf())
}
/**
* ### Two-factor login information for the specified user.
*
* @param {String} user_id Id of user
* @param {String} fields Requested fields.
*
* GET /users/{user_id}/credentials_totp -> ByteArray
*/
@JvmOverloads fun user_credentials_totp(
user_id: String,
fields: String? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.get<ByteArray>("/users/${path_user_id}/credentials_totp",
mapOf("fields" to fields))
}
/**
* ### Two-factor login information for the specified user.
*
* @param {String} user_id Id of user
* @param {CredentialsTotp} body WARNING: no writeable properties found for POST, PUT, or PATCH
* @param {String} fields Requested fields.
*
* POST /users/{user_id}/credentials_totp -> ByteArray
*/
@JvmOverloads fun create_user_credentials_totp(
user_id: String,
body: CredentialsTotp? = null,
fields: String? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.post<ByteArray>("/users/${path_user_id}/credentials_totp",
mapOf("fields" to fields), body)
}
/**
* ### Two-factor login information for the specified user.
*
* @param {String} user_id Id of user
*
* DELETE /users/{user_id}/credentials_totp -> ByteArray
*/
fun delete_user_credentials_totp(
user_id: String
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.delete<ByteArray>("/users/${path_user_id}/credentials_totp", mapOf())
}
/**
* ### LDAP login information for the specified user.
*
* @param {String} user_id Id of user
* @param {String} fields Requested fields.
*
* GET /users/{user_id}/credentials_ldap -> ByteArray
*/
@JvmOverloads fun user_credentials_ldap(
user_id: String,
fields: String? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.get<ByteArray>("/users/${path_user_id}/credentials_ldap",
mapOf("fields" to fields))
}
/**
* ### LDAP login information for the specified user.
*
* @param {String} user_id Id of user
*
* DELETE /users/{user_id}/credentials_ldap -> ByteArray
*/
fun delete_user_credentials_ldap(
user_id: String
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.delete<ByteArray>("/users/${path_user_id}/credentials_ldap", mapOf())
}
/**
* ### Google authentication login information for the specified user.
*
* @param {String} user_id Id of user
* @param {String} fields Requested fields.
*
* GET /users/{user_id}/credentials_google -> ByteArray
*/
@JvmOverloads fun user_credentials_google(
user_id: String,
fields: String? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.get<ByteArray>("/users/${path_user_id}/credentials_google",
mapOf("fields" to fields))
}
/**
* ### Google authentication login information for the specified user.
*
* @param {String} user_id Id of user
*
* DELETE /users/{user_id}/credentials_google -> ByteArray
*/
fun delete_user_credentials_google(
user_id: String
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.delete<ByteArray>("/users/${path_user_id}/credentials_google", mapOf())
}
/**
* ### Saml authentication login information for the specified user.
*
* @param {String} user_id Id of user
* @param {String} fields Requested fields.
*
* GET /users/{user_id}/credentials_saml -> ByteArray
*/
@JvmOverloads fun user_credentials_saml(
user_id: String,
fields: String? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.get<ByteArray>("/users/${path_user_id}/credentials_saml",
mapOf("fields" to fields))
}
/**
* ### Saml authentication login information for the specified user.
*
* @param {String} user_id Id of user
*
* DELETE /users/{user_id}/credentials_saml -> ByteArray
*/
fun delete_user_credentials_saml(
user_id: String
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.delete<ByteArray>("/users/${path_user_id}/credentials_saml", mapOf())
}
/**
* ### OpenID Connect (OIDC) authentication login information for the specified user.
*
* @param {String} user_id Id of user
* @param {String} fields Requested fields.
*
* GET /users/{user_id}/credentials_oidc -> ByteArray
*/
@JvmOverloads fun user_credentials_oidc(
user_id: String,
fields: String? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.get<ByteArray>("/users/${path_user_id}/credentials_oidc",
mapOf("fields" to fields))
}
/**
* ### OpenID Connect (OIDC) authentication login information for the specified user.
*
* @param {String} user_id Id of user
*
* DELETE /users/{user_id}/credentials_oidc -> ByteArray
*/
fun delete_user_credentials_oidc(
user_id: String
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.delete<ByteArray>("/users/${path_user_id}/credentials_oidc", mapOf())
}
/**
* ### API 3 login information for the specified user. This is for the newer API keys that can be added for any user.
*
* @param {String} user_id Id of user
* @param {String} credentials_api3_id Id of API 3 Credential
* @param {String} fields Requested fields.
*
* GET /users/{user_id}/credentials_api3/{credentials_api3_id} -> ByteArray
*/
@JvmOverloads fun user_credentials_api3(
user_id: String,
credentials_api3_id: String,
fields: String? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
val path_credentials_api3_id = encodeParam(credentials_api3_id)
return this.get<ByteArray>("/users/${path_user_id}/credentials_api3/${path_credentials_api3_id}",
mapOf("fields" to fields))
}
/**
* ### API 3 login information for the specified user. This is for the newer API keys that can be added for any user.
*
* @param {String} user_id Id of user
* @param {String} credentials_api3_id Id of API 3 Credential
*
* DELETE /users/{user_id}/credentials_api3/{credentials_api3_id} -> ByteArray
*/
fun delete_user_credentials_api3(
user_id: String,
credentials_api3_id: String
) : SDKResponse {
val path_user_id = encodeParam(user_id)
val path_credentials_api3_id = encodeParam(credentials_api3_id)
return this.delete<ByteArray>("/users/${path_user_id}/credentials_api3/${path_credentials_api3_id}", mapOf())
}
/**
* ### API 3 login information for the specified user. This is for the newer API keys that can be added for any user.
*
* @param {String} user_id Id of user
* @param {String} fields Requested fields.
*
* GET /users/{user_id}/credentials_api3 -> ByteArray
*/
@JvmOverloads fun all_user_credentials_api3s(
user_id: String,
fields: String? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.get<ByteArray>("/users/${path_user_id}/credentials_api3",
mapOf("fields" to fields))
}
/**
* ### API 3 login information for the specified user. This is for the newer API keys that can be added for any user.
*
* @param {String} user_id Id of user
* @param {String} fields Requested fields.
*
* POST /users/{user_id}/credentials_api3 -> ByteArray
*/
@JvmOverloads fun create_user_credentials_api3(
user_id: String,
fields: String? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.post<ByteArray>("/users/${path_user_id}/credentials_api3",
mapOf("fields" to fields))
}
/**
* ### Embed login information for the specified user.
*
* @param {String} user_id Id of user
* @param {String} credentials_embed_id Id of Embedding Credential
* @param {String} fields Requested fields.
*
* GET /users/{user_id}/credentials_embed/{credentials_embed_id} -> ByteArray
*/
@JvmOverloads fun user_credentials_embed(
user_id: String,
credentials_embed_id: String,
fields: String? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
val path_credentials_embed_id = encodeParam(credentials_embed_id)
return this.get<ByteArray>("/users/${path_user_id}/credentials_embed/${path_credentials_embed_id}",
mapOf("fields" to fields))
}
/**
* ### Embed login information for the specified user.
*
* @param {String} user_id Id of user
* @param {String} credentials_embed_id Id of Embedding Credential
*
* DELETE /users/{user_id}/credentials_embed/{credentials_embed_id} -> ByteArray
*/
fun delete_user_credentials_embed(
user_id: String,
credentials_embed_id: String
) : SDKResponse {
val path_user_id = encodeParam(user_id)
val path_credentials_embed_id = encodeParam(credentials_embed_id)
return this.delete<ByteArray>("/users/${path_user_id}/credentials_embed/${path_credentials_embed_id}", mapOf())
}
/**
* ### Embed login information for the specified user.
*
* @param {String} user_id Id of user
* @param {String} fields Requested fields.
*
* GET /users/{user_id}/credentials_embed -> ByteArray
*/
@JvmOverloads fun all_user_credentials_embeds(
user_id: String,
fields: String? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.get<ByteArray>("/users/${path_user_id}/credentials_embed",
mapOf("fields" to fields))
}
/**
* ### Looker Openid login information for the specified user. Used by Looker Analysts.
*
* @param {String} user_id Id of user
* @param {String} fields Requested fields.
*
* GET /users/{user_id}/credentials_looker_openid -> ByteArray
*/
@JvmOverloads fun user_credentials_looker_openid(
user_id: String,
fields: String? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.get<ByteArray>("/users/${path_user_id}/credentials_looker_openid",
mapOf("fields" to fields))
}
/**
* ### Looker Openid login information for the specified user. Used by Looker Analysts.
*
* @param {String} user_id Id of user
*
* DELETE /users/{user_id}/credentials_looker_openid -> ByteArray
*/
fun delete_user_credentials_looker_openid(
user_id: String
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.delete<ByteArray>("/users/${path_user_id}/credentials_looker_openid", mapOf())
}
/**
* ### Web login session for the specified user.
*
* @param {String} user_id Id of user
* @param {String} session_id Id of Web Login Session
* @param {String} fields Requested fields.
*
* GET /users/{user_id}/sessions/{session_id} -> ByteArray
*/
@JvmOverloads fun user_session(
user_id: String,
session_id: String,
fields: String? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
val path_session_id = encodeParam(session_id)
return this.get<ByteArray>("/users/${path_user_id}/sessions/${path_session_id}",
mapOf("fields" to fields))
}
/**
* ### Web login session for the specified user.
*
* @param {String} user_id Id of user
* @param {String} session_id Id of Web Login Session
*
* DELETE /users/{user_id}/sessions/{session_id} -> ByteArray
*/
fun delete_user_session(
user_id: String,
session_id: String
) : SDKResponse {
val path_user_id = encodeParam(user_id)
val path_session_id = encodeParam(session_id)
return this.delete<ByteArray>("/users/${path_user_id}/sessions/${path_session_id}", mapOf())
}
/**
* ### Web login session for the specified user.
*
* @param {String} user_id Id of user
* @param {String} fields Requested fields.
*
* GET /users/{user_id}/sessions -> ByteArray
*/
@JvmOverloads fun all_user_sessions(
user_id: String,
fields: String? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.get<ByteArray>("/users/${path_user_id}/sessions",
mapOf("fields" to fields))
}
/**
* ### Create a password reset token.
* This will create a cryptographically secure random password reset token for the user.
* If the user already has a password reset token then this invalidates the old token and creates a new one.
* The token is expressed as the 'password_reset_url' of the user's email/password credential object.
* This takes an optional 'expires' param to indicate if the new token should be an expiring token.
* Tokens that expire are typically used for self-service password resets for existing users.
* Invitation emails for new users typically are not set to expire.
* The expire period is always 60 minutes when expires is enabled.
* This method can be called with an empty body.
*
* @param {String} user_id Id of user
* @param {Boolean} expires Expiring token.
* @param {String} fields Requested fields.
*
* POST /users/{user_id}/credentials_email/password_reset -> ByteArray
*/
@JvmOverloads fun create_user_credentials_email_password_reset(
user_id: String,
expires: Boolean? = null,
fields: String? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.post<ByteArray>("/users/${path_user_id}/credentials_email/password_reset",
mapOf("expires" to expires,
"fields" to fields))
}
/**
* ### Get information about roles of a given user
*
* @param {String} user_id Id of user
* @param {String} fields Requested fields.
* @param {Boolean} direct_association_only Get only roles associated directly with the user: exclude those only associated through groups.
*
* GET /users/{user_id}/roles -> ByteArray
*/
@JvmOverloads fun user_roles(
user_id: String,
fields: String? = null,
direct_association_only: Boolean? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.get<ByteArray>("/users/${path_user_id}/roles",
mapOf("fields" to fields,
"direct_association_only" to direct_association_only))
}
/**
* ### Set roles of the user with a specific id.
*
* @param {String} user_id Id of user
* @param {Array<String>} body
* @param {String} fields Requested fields.
*
* PUT /users/{user_id}/roles -> ByteArray
*/
@JvmOverloads fun set_user_roles(
user_id: String,
body: Array<String>,
fields: String? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.put<ByteArray>("/users/${path_user_id}/roles",
mapOf("fields" to fields), body)
}
/**
* ### Get user attribute values for a given user.
*
* Returns the values of specified user attributes (or all user attributes) for a certain user.
*
* A value for each user attribute is searched for in the following locations, in this order:
*
* 1. in the user's account information
* 1. in groups that the user is a member of
* 1. the default value of the user attribute
*
* If more than one group has a value defined for a user attribute, the group with the lowest rank wins.
*
* The response will only include user attributes for which values were found. Use `include_unset=true` to include
* empty records for user attributes with no value.
*
* The value of all hidden user attributes will be blank.
*
* @param {String} user_id Id of user
* @param {String} fields Requested fields.
* @param {DelimArray<String>} user_attribute_ids Specific user attributes to request. Omit or leave blank to request all user attributes.
* @param {Boolean} all_values If true, returns all values in the search path instead of just the first value found. Useful for debugging group precedence.
* @param {Boolean} include_unset If true, returns an empty record for each requested attribute that has no user, group, or default value.
*
* GET /users/{user_id}/attribute_values -> ByteArray
*/
@JvmOverloads fun user_attribute_user_values(
user_id: String,
fields: String? = null,
user_attribute_ids: DelimArray<String>? = null,
all_values: Boolean? = null,
include_unset: Boolean? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.get<ByteArray>("/users/${path_user_id}/attribute_values",
mapOf("fields" to fields,
"user_attribute_ids" to user_attribute_ids,
"all_values" to all_values,
"include_unset" to include_unset))
}
/**
* ### Store a custom value for a user attribute in a user's account settings.
*
* Per-user user attribute values take precedence over group or default values.
*
* @param {String} user_id Id of user
* @param {String} user_attribute_id Id of user attribute
* @param {WriteUserAttributeWithValue} body
*
* PATCH /users/{user_id}/attribute_values/{user_attribute_id} -> ByteArray
*/
fun set_user_attribute_user_value(
user_id: String,
user_attribute_id: String,
body: WriteUserAttributeWithValue
) : SDKResponse {
val path_user_id = encodeParam(user_id)
val path_user_attribute_id = encodeParam(user_attribute_id)
return this.patch<ByteArray>("/users/${path_user_id}/attribute_values/${path_user_attribute_id}", mapOf(), body)
}
/**
* ### Delete a user attribute value from a user's account settings.
*
* After the user attribute value is deleted from the user's account settings, subsequent requests
* for the user attribute value for this user will draw from the user's groups or the default
* value of the user attribute. See [Get User Attribute Values](#!/User/user_attribute_user_values) for more
* information about how user attribute values are resolved.
*
* @param {String} user_id Id of user
* @param {String} user_attribute_id Id of user attribute
*
* DELETE /users/{user_id}/attribute_values/{user_attribute_id} -> ByteArray
*/
fun delete_user_attribute_user_value(
user_id: String,
user_attribute_id: String
) : SDKResponse {
val path_user_id = encodeParam(user_id)
val path_user_attribute_id = encodeParam(user_attribute_id)
return this.delete<ByteArray>("/users/${path_user_id}/attribute_values/${path_user_attribute_id}", mapOf())
}
/**
* ### Send a password reset token.
* This will send a password reset email to the user. If a password reset token does not already exist
* for this user, it will create one and then send it.
* If the user has not yet set up their account, it will send a setup email to the user.
* The URL sent in the email is expressed as the 'password_reset_url' of the user's email/password credential object.
* Password reset URLs will expire in 60 minutes.
* This method can be called with an empty body.
*
* @param {String} user_id Id of user
* @param {String} fields Requested fields.
*
* POST /users/{user_id}/credentials_email/send_password_reset -> ByteArray
*/
@JvmOverloads fun send_user_credentials_email_password_reset(
user_id: String,
fields: String? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.post<ByteArray>("/users/${path_user_id}/credentials_email/send_password_reset",
mapOf("fields" to fields))
}
/**
* ### Change a disabled user's email addresses
*
* Allows the admin to change the email addresses for all the user's
* associated credentials. Will overwrite all associated email addresses with
* the value supplied in the 'email' body param.
* The user's 'is_disabled' status must be true.
*
* @param {String} user_id Id of user
* @param {UserEmailOnly} body
* @param {String} fields Requested fields.
*
* POST /users/{user_id}/update_emails -> ByteArray
*/
@JvmOverloads fun wipeout_user_emails(
user_id: String,
body: UserEmailOnly,
fields: String? = null
) : SDKResponse {
val path_user_id = encodeParam(user_id)
return this.post<ByteArray>("/users/${path_user_id}/update_emails",
mapOf("fields" to fields), body)
}
/**
* Create an embed user from an external user ID
*
* @param {CreateEmbedUserRequest} body
*
* POST /users/embed_user -> ByteArray
*/
fun create_embed_user(
body: CreateEmbedUserRequest
) : SDKResponse {
return this.post<ByteArray>("/users/embed_user", mapOf(), body)
}
//endregion User: Manage Users
//region UserAttribute: Manage User Attributes
/**
* ### Get information about all user attributes.
*
* @param {String} fields Requested fields.
* @param {String} sorts Fields to order the results by. Sortable fields include: name, label
*
* GET /user_attributes -> ByteArray
*/
@JvmOverloads fun all_user_attributes(
fields: String? = null,
sorts: String? = null
) : SDKResponse {
return this.get<ByteArray>("/user_attributes",
mapOf("fields" to fields,
"sorts" to sorts))
}
/**
* ### Create a new user attribute
*
* Permission information for a user attribute is conveyed through the `can` and `user_can_edit` fields.
* The `user_can_edit` field indicates whether an attribute is user-editable _anywhere_ in the application.
* The `can` field gives more granular access information, with the `set_value` child field indicating whether
* an attribute's value can be set by [Setting the User Attribute User Value](#!/User/set_user_attribute_user_value).
*
* Note: `name` and `label` fields must be unique across all user attributes in the Looker instance.
* Attempting to create a new user attribute with a name or label that duplicates an existing
* user attribute will fail with a 422 error.
*
* @param {WriteUserAttribute} body
* @param {String} fields Requested fields.
*
* POST /user_attributes -> ByteArray
*/
@JvmOverloads fun create_user_attribute(
body: WriteUserAttribute,
fields: String? = null
) : SDKResponse {
return this.post<ByteArray>("/user_attributes",
mapOf("fields" to fields), body)
}
/**
* ### Get information about a user attribute.
*
* @param {String} user_attribute_id Id of user attribute
* @param {String} fields Requested fields.
*
* GET /user_attributes/{user_attribute_id} -> ByteArray
*/
@JvmOverloads fun user_attribute(
user_attribute_id: String,
fields: String? = null
) : SDKResponse {
val path_user_attribute_id = encodeParam(user_attribute_id)
return this.get<ByteArray>("/user_attributes/${path_user_attribute_id}",
mapOf("fields" to fields))
}
/**
* ### Update a user attribute definition.
*
* @param {String} user_attribute_id Id of user attribute
* @param {WriteUserAttribute} body
* @param {String} fields Requested fields.
*
* PATCH /user_attributes/{user_attribute_id} -> ByteArray
*/
@JvmOverloads fun update_user_attribute(
user_attribute_id: String,
body: WriteUserAttribute,
fields: String? = null
) : SDKResponse {
val path_user_attribute_id = encodeParam(user_attribute_id)
return this.patch<ByteArray>("/user_attributes/${path_user_attribute_id}",
mapOf("fields" to fields), body)
}
/**
* ### Delete a user attribute (admin only).
*
* @param {String} user_attribute_id Id of user attribute
*
* DELETE /user_attributes/{user_attribute_id} -> ByteArray
*/
fun delete_user_attribute(
user_attribute_id: String
) : SDKResponse {
val path_user_attribute_id = encodeParam(user_attribute_id)
return this.delete<ByteArray>("/user_attributes/${path_user_attribute_id}", mapOf())
}
/**
* ### Returns all values of a user attribute defined by user groups, in precedence order.
*
* A user may be a member of multiple groups which define different values for a given user attribute.
* The order of group-values in the response determines precedence for selecting which group-value applies
* to a given user. For more information, see [Set User Attribute Group Values](#!/UserAttribute/set_user_attribute_group_values).
*
* Results will only include groups that the caller's user account has permission to see.
*
* @param {String} user_attribute_id Id of user attribute
* @param {String} fields Requested fields.
*
* GET /user_attributes/{user_attribute_id}/group_values -> ByteArray
*/
@JvmOverloads fun all_user_attribute_group_values(
user_attribute_id: String,
fields: String? = null
) : SDKResponse {
val path_user_attribute_id = encodeParam(user_attribute_id)
return this.get<ByteArray>("/user_attributes/${path_user_attribute_id}/group_values",
mapOf("fields" to fields))
}
/**
* ### Define values for a user attribute across a set of groups, in priority order.
*
* This function defines all values for a user attribute defined by user groups. This is a global setting, potentially affecting
* all users in the system. This function replaces any existing group value definitions for the indicated user attribute.
*
* The value of a user attribute for a given user is determined by searching the following locations, in this order:
*
* 1. the user's account settings
* 2. the groups that the user is a member of
* 3. the default value of the user attribute, if any
*
* The user may be a member of multiple groups which define different values for that user attribute. The order of items in the group_values parameter
* determines which group takes priority for that user. Lowest array index wins.
*
* An alternate method to indicate the selection precedence of group-values is to assign numbers to the 'rank' property of each
* group-value object in the array. Lowest 'rank' value wins. If you use this technique, you must assign a
* rank value to every group-value object in the array.
*
* To set a user attribute value for a single user, see [Set User Attribute User Value](#!/User/set_user_attribute_user_value).
* To set a user attribute value for all members of a group, see [Set User Attribute Group Value](#!/Group/update_user_attribute_group_value).
*
* @param {String} user_attribute_id Id of user attribute
* @param {Array<UserAttributeGroupValue>} body
*
* POST /user_attributes/{user_attribute_id}/group_values -> ByteArray
*/
fun set_user_attribute_group_values(
user_attribute_id: String,
body: Array<UserAttributeGroupValue>
) : SDKResponse {
val path_user_attribute_id = encodeParam(user_attribute_id)
return this.post<ByteArray>("/user_attributes/${path_user_attribute_id}/group_values", mapOf(), body)
}
//endregion UserAttribute: Manage User Attributes
//region Workspace: Manage Workspaces
/**
* ### Get All Workspaces
*
* Returns all workspaces available to the calling user.
*
* GET /workspaces -> ByteArray
*/
fun all_workspaces(
) : SDKResponse {
return this.get<ByteArray>("/workspaces", mapOf())
}
/**
* ### Get A Workspace
*
* Returns information about a workspace such as the git status and selected branches
* of all projects available to the caller's user account.
*
* A workspace defines which versions of project files will be used to evaluate expressions
* and operations that use model definitions - operations such as running queries or rendering dashboards.
* Each project has its own git repository, and each project in a workspace may be configured to reference
* particular branch or revision within their respective repositories.
*
* There are two predefined workspaces available: "production" and "dev".
*
* The production workspace is shared across all Looker users. Models in the production workspace are read-only.
* Changing files in production is accomplished by modifying files in a git branch and using Pull Requests
* to merge the changes from the dev branch into the production branch, and then telling
* Looker to sync with production.
*
* The dev workspace is local to each Looker user. Changes made to project/model files in the dev workspace only affect
* that user, and only when the dev workspace is selected as the active workspace for the API session.
* (See set_session_workspace()).
*
* The dev workspace is NOT unique to an API session. Two applications accessing the Looker API using
* the same user account will see the same files in the dev workspace. To avoid collisions between
* API clients it's best to have each client login with API3 credentials for a different user account.
*
* Changes made to files in a dev workspace are persistent across API sessions. It's a good
* idea to commit any changes you've made to the git repository, but not strictly required. Your modified files
* reside in a special user-specific directory on the Looker server and will still be there when you login in again
* later and use update_session(workspace_id: "dev") to select the dev workspace for the new API session.
*
* @param {String} workspace_id Id of the workspace
*
* GET /workspaces/{workspace_id} -> ByteArray
*/
fun workspace(
workspace_id: String
) : SDKResponse {
val path_workspace_id = encodeParam(workspace_id)
return this.get<ByteArray>("/workspaces/${path_workspace_id}", mapOf())
}
//endregion Workspace: Manage Workspaces
} | mit |
WillFK/fuckoffer | app/src/main/java/com/fk/fuckoffer/ui/field/FieldFormPresenter.kt | 1 | 1565 | package com.fk.fuckoffer.ui.field
import android.util.Log
import com.fk.fuckoffer.domain.interactor.IFieldInteractor
import com.fk.fuckoffer.domain.model.Field
import com.fk.fuckoffer.domain.repository.FoaasRepository
import com.fk.fuckoffer.ui.BasePresenter
import io.reactivex.android.schedulers.AndroidSchedulers
import javax.inject.Inject
/**
* Awful presenter. Refactor it. This list of fields is nasty and whoever made it should feel bad. TODO
* Created by fk on 23.10.17.
*/
class FieldFormPresenter @Inject constructor(
private val foaasRepository: FoaasRepository,
private val fieldInteractor: IFieldInteractor) : BasePresenter<FieldFormView>() {
fun getOperation(operationName: String, fieldIndex: Int) {
foaasRepository.getOperationByName(operationName)
.observeOn(AndroidSchedulers.mainThread())
.doOnSuccess { view?.displayFieldInfo(it.fields[fieldIndex], it.fields.size == fieldIndex+1) }
.flatMap { fieldInteractor.getPreviousValues(it.fields[fieldIndex]) }
.subscribe(
{ view?.displaySuggestions(it) },
{ Log.e("Field", it.message, it) })
}
fun inputField(field: Field, value: String, last: Boolean) {
fieldInteractor.registerValue(field, value)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ if (last) view?.gotoPreview() else view?.gotoNextField() },
{ Log.e("Field", it.message, it) })
}
} | mit |
kysersozelee/KotlinStudy | JsonParser/bin/main.kt | 1 | 1165 | fun main(args: Array<String>) {
var writer: JsonWriter = JsonWriter()
var jobj = JsonObject()
jobj.add("õÁ¤ÇÊ", 29)
jobj.add("½ÉÇö¿ì", 30)
jobj.write(writer)
println("json array serialize ==> ${writer.string}")
var jobj3 = JsonObject()
jobj3.add("À̵¿¿ì", 99)
var writer2: JsonWriter = JsonWriter()
var jobj2 = JsonObject()
jobj2.add("idiots", jobj)
jobj2.add("genius", jobj3)
jobj2.add("null test", null)
jobj2.write(writer2)
println("nested json object serialize ==> ${writer2.string}")
var writer4: JsonWriter = JsonWriter()
var jarr = JsonArray()
jarr.add(123)
jarr.add("asd")
jarr.add(0.323)
jarr.add(true)
jarr.write(writer4)
println("json array serialize ==> ${writer4.string}")
var parser: JsonParser = JsonParser()
var parsedJobj: JsonObject = parser.parse(writer2.string).asObject()
var genius: JsonObject? = parsedJobj.get("genius")?.asObject()
var writer5: JsonWriter = JsonWriter()
var writer6: JsonWriter = JsonWriter()
println("json object deserialize jsonstr : ${writer2.string} parsedJobj : ${parsedJobj.write(writer6)} genius : ==> ${genius?.write(writer5)}")
} | bsd-2-clause |
spark/photon-tinker-android | devicesetup/src/main/java/io/particle/android/sdk/devicesetup/apconnector/ApConnector.kt | 1 | 1832 | package io.particle.android.sdk.devicesetup.apconnector
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiConfiguration.KeyMgmt
import io.particle.android.sdk.devicesetup.apconnector.ApConnector.Client
import io.particle.android.sdk.utils.SSID
import java.util.concurrent.TimeUnit.SECONDS
interface ApConnector {
interface Client {
fun onApConnectionSuccessful(config: WifiConfiguration)
fun onApConnectionFailed(config: WifiConfiguration)
}
/**
* Connect this Android device to the specified AP.
*
* @param config the WifiConfiguration defining which AP to connect to
*/
fun connectToAP(config: WifiConfiguration, client: Client)
/**
* Stop attempting to connect
*/
fun stop()
companion object {
@JvmStatic
fun buildUnsecuredConfig(ssid: SSID): WifiConfiguration {
val config = WifiConfiguration()
config.SSID = ssid.inQuotes()
config.hiddenSSID = false
config.allowedKeyManagement.set(KeyMgmt.NONE)
// have to set a very high number in order to ensure that Android doesn't
// immediately drop this connection and reconnect to the a different AP
config.priority = 999999
return config
}
@JvmField
val CONNECT_TO_DEVICE_TIMEOUT_MILLIS = SECONDS.toMillis(20)
}
}
class DecoratingClient(
private val onClearState: () -> Unit
) : Client {
var wrappedClient: Client? = null
override fun onApConnectionSuccessful(config: WifiConfiguration) {
onClearState()
wrappedClient?.onApConnectionSuccessful(config)
}
override fun onApConnectionFailed(config: WifiConfiguration) {
onClearState()
wrappedClient?.onApConnectionFailed(config)
}
}
| apache-2.0 |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/RsMacroDefinition.kt | 2 | 1125 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.IStubElementType
import org.rust.ide.icons.RsIcons
import org.rust.lang.core.psi.RsElementTypes
import org.rust.lang.core.psi.RsMacroDefinition
import org.rust.lang.core.stubs.RsMacroDefinitionStub
import javax.swing.Icon
abstract class RsMacroDefinitionImplMixin : RsStubbedNamedElementImpl<RsMacroDefinitionStub>,
RsMacroDefinition {
constructor(node: ASTNode) : super(node)
constructor(stub: RsMacroDefinitionStub, elementType: IStubElementType<*, *>) : super(stub, elementType)
override fun getNameIdentifier(): PsiElement? =
findChildrenByType<PsiElement>(RsElementTypes.IDENTIFIER)
.getOrNull(1) // Zeroth is `macro_rules` itself
override fun getIcon(flags: Int): Icon? = RsIcons.MACRO
}
val RsMacroDefinition.hasMacroExport: Boolean
get() = queryAttributes.hasAttribute("macro_export")
| mit |
albertoruibal/karballo | karballo-jvm/src/test/kotlin/karballo/EvaluatorOpeningEndgameTest.kt | 1 | 2043 | package karballo
import karballo.evaluation.Evaluator
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Test Opening/Ending two short values in the same integer arithmetic
*/
class EvaluatorOpeningEndgameTest {
@Test
fun conversionA() {
val value = Evaluator.oe(-89, 54)
assertEquals("Conversion O", -89, Evaluator.o(value))
assertEquals("Conversion E", 54, Evaluator.e(value))
}
@Test
fun conversionB() {
val value = Evaluator.oe(54, -89)
assertEquals("Conversion O", 54, Evaluator.o(value))
assertEquals("Conversion E", -89, Evaluator.e(value))
}
@Test
fun add() {
val value = Evaluator.oe(12, 38) + Evaluator.oe(9, 67)
assertEquals("Add O", 21, Evaluator.o(value))
assertEquals("Add E", 105, Evaluator.e(value))
}
@Test
fun subFromNegative() {
val value = Evaluator.oe(-8, -8) - Evaluator.oe(8, 8)
assertEquals("Sub O", -16, Evaluator.o(value))
assertEquals("Sub E", -16, Evaluator.e(value))
}
@Test
fun subThreeNegatives() {
val value = Evaluator.oe(-8, -8) - Evaluator.oe(8, 8) - Evaluator.oe(8, 8)
assertEquals("Sub O", -24, Evaluator.o(value))
assertEquals("Sub E", -24, Evaluator.e(value))
}
@Test
fun subSwitchToNegativeA() {
val value = Evaluator.oe(10, 10) - Evaluator.oe(12, 12)
assertEquals("Sub O", -2, Evaluator.o(value))
assertEquals("Sub E", -2, Evaluator.e(value))
}
@Test
fun mutiplyPositive() {
val value = 5 * Evaluator.oe(4, 50)
assertEquals("Multiply O", 20, Evaluator.o(value))
assertEquals("Multiply E", 250, Evaluator.e(value))
}
@Test
fun openingValueMustBeZero() {
val value = Evaluator.oe(0, -5)
assertEquals("O must be zero", 0, Evaluator.o(value))
}
@Test
fun endgameValueMustBeZero() {
val value = Evaluator.oe(-5, 0)
assertEquals("E must be zero", 0, Evaluator.e(value))
}
} | mit |
google/horologist | media-ui/src/debug/java/com/google/android/horologist/media/ui/components/controls/SeekToNextButtonPreview.kt | 1 | 1298 | /*
* 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.
*/
@file:OptIn(ExperimentalHorologistMediaUiApi::class)
package com.google.android.horologist.media.ui.components.controls
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi
@Preview(
name = "Enabled",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun SeekToNextButtonPreviewEnabled() {
SeekToNextButton(onClick = {})
}
@Preview(
name = "Disabled",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun SeekToNextButtonPreviewDisabled() {
SeekToNextButton(onClick = {}, enabled = false)
}
| apache-2.0 |
wasabeef/recyclerview-animators | example/src/main/java/jp/wasabeef/example/recyclerview/AdapterSampleActivity.kt | 1 | 3624 | package jp.wasabeef.example.recyclerview
import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.animation.OvershootInterpolator
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import jp.wasabeef.recyclerview.adapters.AlphaInAnimationAdapter
import jp.wasabeef.recyclerview.adapters.AnimationAdapter
import jp.wasabeef.recyclerview.adapters.ScaleInAnimationAdapter
import jp.wasabeef.recyclerview.adapters.SlideInBottomAnimationAdapter
import jp.wasabeef.recyclerview.adapters.SlideInLeftAnimationAdapter
import jp.wasabeef.recyclerview.adapters.SlideInRightAnimationAdapter
import jp.wasabeef.recyclerview.animators.FadeInAnimator
/**
* Created by Daichi Furiya / Wasabeef on 2020/08/26.
*/
class AdapterSampleActivity : AppCompatActivity() {
internal enum class Type {
AlphaIn {
override operator fun get(context: Context): AnimationAdapter {
return AlphaInAnimationAdapter(MainAdapter(context, SampleData.LIST.toMutableList()))
}
},
ScaleIn {
override operator fun get(context: Context): AnimationAdapter {
return ScaleInAnimationAdapter(MainAdapter(context, SampleData.LIST.toMutableList()))
}
},
SlideInBottom {
override operator fun get(context: Context): AnimationAdapter {
return SlideInBottomAnimationAdapter(MainAdapter(context, SampleData.LIST.toMutableList()))
}
},
SlideInLeft {
override operator fun get(context: Context): AnimationAdapter {
return SlideInLeftAnimationAdapter(MainAdapter(context, SampleData.LIST.toMutableList()))
}
},
SlideInRight {
override operator fun get(context: Context): AnimationAdapter {
return SlideInRightAnimationAdapter(MainAdapter(context, SampleData.LIST.toMutableList()))
}
};
abstract operator fun get(context: Context): AnimationAdapter
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_adapter_sample)
setSupportActionBar(findViewById(R.id.tool_bar))
supportActionBar?.setDisplayShowTitleEnabled(false)
val recyclerView = findViewById<RecyclerView>(R.id.list)
recyclerView.layoutManager = if (intent.getBooleanExtra(MainActivity.KEY_GRID, true)) {
GridLayoutManager(this, 2)
} else {
LinearLayoutManager(this)
}
val spinner = findViewById<Spinner>(R.id.spinner)
spinner.adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1).apply {
for (type in Type.values()) add(type.name)
}
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
recyclerView.adapter = Type.values()[position][view.context].apply {
setFirstOnly(true)
setDuration(500)
setInterpolator(OvershootInterpolator(.5f))
}
}
override fun onNothingSelected(parent: AdapterView<*>) {
// no-op
}
}
recyclerView.itemAnimator = FadeInAnimator()
val adapter = MainAdapter(this, SampleData.LIST.toMutableList())
recyclerView.adapter = AlphaInAnimationAdapter(adapter).apply {
setFirstOnly(true)
setDuration(500)
setInterpolator(OvershootInterpolator(.5f))
}
}
}
| apache-2.0 |
siosio/DomaSupport | src/main/java/siosio/doma/inspection/dao/quickfix/DirectoryChooser.kt | 1 | 673 | package siosio.doma.inspection.dao.quickfix
import com.intellij.ide.util.*
import com.intellij.openapi.module.*
import com.intellij.openapi.project.*
import com.intellij.openapi.roots.*
import com.intellij.psi.*
open class DirectoryChooser {
open fun chooseDirectory(project: Project, module: Module, isInTest: Boolean): PsiDirectory? {
val roots = ModuleRootManager.getInstance(module).getSourceRoots(isInTest)
val psiDirectories = roots.map { PsiManager.getInstance(project).findDirectory(it) }.toTypedArray()
return DirectoryChooserUtil.chooseDirectory(
psiDirectories, null, project, HashMap())
}
}
| mit |
JavaEden/OrchidCore | plugins/OrchidPosts/src/main/kotlin/com/eden/orchid/posts/components/DisqusComponent.kt | 1 | 743 | package com.eden.orchid.posts.components
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.theme.components.OrchidComponent
import javax.inject.Inject
@Description("Easily add comments to any page with Disqus.", name = "Disqus")
class DisqusComponent
@Inject
constructor(
context: OrchidContext
) : OrchidComponent(context, "disqus", 100) {
@Option
@Description("Your disqus shortname.")
lateinit var shortname: String
@Option
@Description("A site-wide unique identifier for the comment section on this page. Defaults to the page's URL.")
lateinit var identifier: String
}
| mit |
Kotlin/dokka | core/testdata/links/linkToExternalSite.kt | 1 | 69 | /**
* This is link to [http://example.com/#example]
*/
class Foo {} | apache-2.0 |
vase4kin/TeamCityApp | app/src/test/java/com/github/vase4kin/teamcityapp/tests/extractor/TestsValueExtractorImplTest.kt | 1 | 2117 | /*
* Copyright 2019 Andrey Tolpeev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.vase4kin.teamcityapp.tests.extractor
import android.os.Bundle
import com.github.vase4kin.teamcityapp.base.extractor.BundleExtractorValues
import org.hamcrest.core.Is.`is`
import org.hamcrest.core.IsEqual.equalTo
import org.junit.Assert.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.runners.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class TestsValueExtractorImplTest {
@Mock
private lateinit var bundle: Bundle
private lateinit var valueExtractor: TestsValueExtractorImpl
@Before
fun setUp() {
valueExtractor = TestsValueExtractorImpl(bundle)
}
@Test
fun testGetUrl() {
`when`(bundle.getString(BundleExtractorValues.URL)).thenReturn("url")
assertThat(valueExtractor.url, `is`(equalTo("url")))
}
@Test
fun testGetPassedCount() {
`when`(bundle.getInt(BundleExtractorValues.PASSED_COUNT_PARAM)).thenReturn(45)
assertThat(valueExtractor.passedCount, `is`(equalTo(45)))
}
@Test
fun testGetFailedCount() {
`when`(bundle.getInt(BundleExtractorValues.FAILED_COUNT_PARAM)).thenReturn(14)
assertThat(valueExtractor.failedCount, `is`(equalTo(14)))
}
@Test
fun testGetIgnoredCount() {
`when`(bundle.getInt(BundleExtractorValues.IGNORED_COUNT_PARAM)).thenReturn(89)
assertThat(valueExtractor.ignoredCount, `is`(equalTo(89)))
}
}
| apache-2.0 |
Kotlin/dokka | plugins/javadoc/src/test/kotlin/org/jetbrains/dokka/javadoc/JavadocPackageTemplateMapTest.kt | 1 | 7048 | package org.jetbrains.dokka.javadoc
import org.jetbrains.dokka.javadoc.pages.JavadocContentKind
import org.jetbrains.dokka.javadoc.pages.JavadocPackagePageNode
import org.jetbrains.dokka.javadoc.pages.RowJavadocListEntry
import org.jetbrains.dokka.links.DRI
import org.jetbrains.dokka.test.assertIsInstance
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import java.io.File
internal class JavadocPackageTemplateMapTest : AbstractJavadocTemplateMapTest() {
@Test
@Suppress("UNCHECKED_CAST")
fun `single class`() {
dualTestTemplateMapInline(
kotlin =
"""
/src/source.kt
package com.test.package0
class Test
""",
java =
"""
/src/com/test/package0/Test.java
package com.test.package0;
public class Test {}
"""
) {
val map = singlePageOfType<JavadocPackagePageNode>().templateMap
assertEquals("Class Summary", ((map["lists"] as List<*>).first() as Map<String, *>)["tabTitle"])
assertEquals("Class", ((map["lists"] as List<*>).first() as Map<String, *>)["colTitle"])
assertEquals("Package com.test.package0", map["title"])
assertEquals("", map["subtitle"])
assertEquals("package", map["kind"])
val list = assertIsInstance<List<*>>(((map["lists"] as List<*>).first() as Map<String, *>)["list"])
val entry = assertIsInstance<RowJavadocListEntry>(list.single())
assertEquals("Test", entry.link.name)
assertEquals(JavadocContentKind.Class, entry.link.kind)
assertEquals(DRI("com.test.package0", "Test"), entry.link.dri.single())
}
}
@Test
@Suppress("UNCHECKED_CAST")
fun `multiple packages`() {
dualTestTemplateMapInline(
kotlin =
"""
/src/source0.kt
package com.test.package0
class Test0
/src/source1.kt
package com.test.package1
class Test1
""",
java =
"""
/src/com/test/package0/Test0.java
package com.test.package0;
public class Test0 {}
/src/com/test/package1/Test1.java
package com.test.package1;
public class Test1 {}
"""
) {
val packagePages = allPagesOfType<JavadocPackagePageNode>()
packagePages.forEach { page ->
val map = page.templateMap
assertEquals("Class Summary", ((map["lists"] as List<*>).first() as Map<String, *>)["tabTitle"])
assertEquals("Class", ((map["lists"] as List<*>).first() as Map<String, *>)["colTitle"])
assertEquals("", map["subtitle"])
assertEquals("package", map["kind"])
}
assertEquals(2, packagePages.size, "Expected two package pages")
}
}
@Test
fun `single class with package documentation (java)`() {
testTemplateMapInline(
query =
"""
/src/com/test/package0/package-info.java
/**
* ABC
*/
package com.test.package0;
/src/com/test/package0/Test.java
package com.test.package0;
public class Test{}
"""
) {
val packagePage = singlePageOfType<JavadocPackagePageNode>()
val map = packagePage.templateMap
assertEquals("<p>ABC</p>", map["subtitle"].toString().trim())
}
}
@Test
fun `single class with package documentation (kotlin)`() {
testTemplateMapInline(
query =
"""
/src/packages.md
# Package com.test.package0
ABC
/src/source0.kt
package com.test.package0
class Test
""",
configuration = config.copy(
sourceSets = config.sourceSets.map { sourceSet ->
sourceSet.copy(
includes = setOf(File("src/packages.md"))
)
}
)
) {
val packagePage = singlePageOfType<JavadocPackagePageNode>()
val map = packagePage.templateMap
assertEquals("<p>ABC</p>", map["subtitle"].toString().trim())
}
}
@Test
fun `single class with long package documentation (java)`() {
testTemplateMapInline(
query =
"""
/src/com/test/package0/package-info.java
/**
* Aliquam rerum est vel. Molestiae eos expedita animi repudiandae sed commodi.
* Omnis qui ducimus ut et perspiciatis sint.
*
* Veritatis nam eaque sequi laborum voluptas voluptate aut.
*/
package com.test.package0;
/src/com/test/package0/Test.java
package com.test.package0;
public class Test{}
"""
) {
val packagePage = singlePageOfType<JavadocPackagePageNode>()
val map = packagePage.templateMap
val expectedText = """
<p>Aliquam rerum est vel. Molestiae eos expedita animi repudiandae sed commodi.
Omnis qui ducimus ut et perspiciatis sint.
Veritatis nam eaque sequi laborum voluptas voluptate aut.</p>
""".trimIndent().replace("\n", "")
assertEquals(expectedText, map["subtitle"].toString().trim())
}
}
@Test
fun `single class with long package documentation (kotlin)`() {
testTemplateMapInline(
query =
"""
/src/packages.md
# Package com.test.package0
Aliquam rerum est vel. Molestiae eos expedita animi repudiandae sed commodi.
Omnis qui ducimus ut et perspiciatis sint.
Veritatis nam eaque sequi laborum voluptas voluptate aut.
/src/source0.kt
package com.test.package0
class Test
""",
configuration = config.copy(
sourceSets = config.sourceSets.map { sourceSet ->
sourceSet.copy(
includes = setOf(File("src/packages.md"))
)
}
)
) {
val packagePage = singlePageOfType<JavadocPackagePageNode>()
val map = packagePage.templateMap
val expectedText = """
<p>Aliquam rerum est vel. Molestiae eos expedita animi repudiandae sed commodi.
Omnis qui ducimus ut et perspiciatis sint.</p>
<p>Veritatis nam eaque sequi laborum voluptas voluptate aut.</p>
""".trimIndent().replace("\n", "")
assertEquals(expectedText, map["subtitle"].toString().trim())
}
}
}
| apache-2.0 |
Riccorl/kotlin-koans | src/i_introduction/_4_Lambdas/n04Lambdas.kt | 1 | 722 | package i_introduction._4_Lambdas
import util.TODO
import util.doc4
fun example() {
val sum = { x: Int, y: Int -> x + y }
val square: (Int) -> Int = { x -> x * x }
sum(1, square(2)) == 5
}
fun todoTask4(collection: Collection<Int>): Nothing = TODO(
"""
Task 4.
Rewrite 'JavaCode4.task4()' in Kotlin using lambdas:
return true if the collection contains an even number.
You can find the appropriate function to call on 'Collection' by using code completion.
Don't use the class 'Iterables'.
""",
documentation = doc4(),
references = { JavaCode4().task4(collection) })
fun task4(collection: Collection<Int>): Boolean = collection.any { it % 2 == 0 }
| mit |
Shynixn/BlockBall | blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/business/commandexecutor/ArenaCommandExecutor.kt | 1 | 9755 | package com.github.shynixn.blockball.core.logic.business.commandexecutor
import com.github.shynixn.blockball.api.business.enumeration.ChatClickAction
import com.github.shynixn.blockball.api.business.enumeration.ChatColor
import com.github.shynixn.blockball.api.business.enumeration.MenuCommand
import com.github.shynixn.blockball.api.business.enumeration.MenuCommandResult
import com.github.shynixn.blockball.api.business.executor.CommandExecutor
import com.github.shynixn.blockball.api.business.service.ConfigurationService
import com.github.shynixn.blockball.api.business.service.LoggingService
import com.github.shynixn.blockball.api.business.service.ProxyService
import com.github.shynixn.blockball.core.logic.business.commandmenu.*
import com.github.shynixn.blockball.core.logic.persistence.entity.ChatBuilderEntity
import com.google.inject.Inject
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
class ArenaCommandExecutor @Inject constructor(
private val configurationService: ConfigurationService,
private val proxyService: ProxyService,
private val loggingService: LoggingService,
openPage: OpenPage,
mainConfigurationPage: MainConfigurationPage,
spectatePage: SpectatePage,
mainSettingsPage: MainSettingsPage,
ballSettingsPage: BallSettingsPage,
ballModifierPage: BallModifierSettingsPage,
listablePage: ListablePage,
teamSettingsPage: TeamSettingsPage,
effectsSettingsPage: EffectsSettingsPage,
multipleLinesPage: MultipleLinesPage,
hologramsPage: HologramPage,
scoreboardPage: ScoreboardPage,
bossbarPage: BossbarPage,
templatePage: TemplateSettingsPage,
signSettingsPage: SignSettingsPage,
rewardsPage: RewardsPage,
particlesPage: ParticleEffectPage,
soundsPage: SoundEffectPage,
abilitiesPage: AbilitiesSettingsPage,
doubleJumpPage: DoubleJumpPage,
miscPage: MiscSettingsPage,
gamePropertiesPage: GamePropertiesPage,
areaProtectionPage: AreaProtectionPage,
teamTextBookPage: TeamTextBookPage,
gameSettingsPage: GameSettingsPage,
spectatingSettingsPage: SpectatingSettingsPage,
notificationPage: NotificationPage,
matchtimesPage : MatchTimesPage
) : CommandExecutor {
companion object {
private val HEADER_STANDARD =
ChatColor.WHITE.toString() + "" + ChatColor.BOLD + "" + ChatColor.UNDERLINE + " BlockBall "
private val FOOTER_STANDARD =
ChatColor.WHITE.toString() + "" + ChatColor.BOLD + "" + ChatColor.UNDERLINE + " ┌1/1┐ "
}
private val cache = HashMap<Any, Array<Any?>>()
private var pageCache: MutableList<Page> = arrayListOf(
openPage, mainConfigurationPage, spectatePage, mainSettingsPage, ballSettingsPage
, ballModifierPage, listablePage, teamSettingsPage, effectsSettingsPage, multipleLinesPage, hologramsPage, scoreboardPage, bossbarPage
, templatePage, signSettingsPage, rewardsPage, particlesPage, soundsPage, abilitiesPage, doubleJumpPage, miscPage, gamePropertiesPage
, areaProtectionPage, teamTextBookPage, gameSettingsPage, spectatingSettingsPage, notificationPage, matchtimesPage
)
/**
* Gets called when the given [source] executes the defined command with the given [args].
*/
override fun <S> onExecuteCommand(source: S, args: Array<out String>): Boolean {
try {
if (source !is Any) {
return false
}
for (i in 0..19) {
proxyService.sendMessage(source, "")
}
proxyService.sendMessage(source, HEADER_STANDARD)
proxyService.sendMessage(source, "\n")
if (!this.cache.containsKey(source)) {
val anyArray = arrayOfNulls<Any>(8)
this.cache[source] = anyArray
}
val cache: Array<Any?>? = this.cache[source]
val command = MenuCommand.from(args)
?: throw IllegalArgumentException("Command is not registered!")
var usedPage: Page? = null
for (page in this.pageCache) {
if (page.getCommandKey() === command.key) {
usedPage = page
if (command == MenuCommand.BACK) {
val newPage = this.getPageById(Integer.parseInt(args[2]))
val b = newPage.buildPage(cache!!)!!
proxyService.sendMessage(source, b)
} else if (command == MenuCommand.CLOSE) {
this.cache.remove(source)
for (i in 0..19) {
proxyService.sendMessage(source, "")
}
return true
} else {
@Suppress("UNCHECKED_CAST") val result = page.execute(source, command, cache!!, args as Array<String>)
if (result == MenuCommandResult.BACK) {
proxyService.performPlayerCommand(source, "blockball open back " + usedPage.getPreviousIdFrom(cache))
return true
}
if (result != MenuCommandResult.SUCCESS && result != MenuCommandResult.CANCEL_MESSAGE) {
val b = ChatBuilderEntity()
.component(ChatColor.WHITE.toString() + "" + ChatColor.BOLD + "[" + ChatColor.RED + ChatColor.BOLD + "!" + ChatColor.WHITE + ChatColor.BOLD + "] " + ChatColor.RED + "Error (Hover me)")
.setHoverText(result.message!!).builder()
proxyService.sendMessage(source, b)
}
if (result != MenuCommandResult.CANCEL_MESSAGE) {
val b = page.buildPage(cache)!!
proxyService.sendMessage(source, b)
}
}
break
}
}
if (usedPage == null)
throw IllegalArgumentException("Cannot find page with key " + command.key)
val builder = ChatBuilderEntity()
.text(ChatColor.STRIKETHROUGH.toString() + "----------------------------------------------------").nextLine()
.component(" >>Save<< ")
.setColor(ChatColor.GREEN)
.setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.ARENA_SAVE.command)
.setHoverText("Saves the current arena if possible.")
.builder()
if (usedPage is ListablePage) {
builder.component(">>Back<<")
.setColor(ChatColor.RED)
.setClickAction(ChatClickAction.RUN_COMMAND, (cache!![3] as MenuCommand).command)
.setHoverText("Goes back to the previous page.")
.builder()
} else {
builder.component(">>Back<<")
.setColor(ChatColor.RED)
.setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.BACK.command + usedPage.getPreviousIdFrom(cache!!))
.setHoverText("Goes back to the previous page.")
.builder()
}
val b = builder.component(" >>Save and reload<<")
.setColor(ChatColor.BLUE)
.setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.ARENA_RELOAD.command)
.setHoverText("Saves the current arena and reloads all games on the server.")
.builder()
proxyService.sendMessage(source, b)
proxyService.sendMessage(source, FOOTER_STANDARD)
} catch (e: Exception) {
loggingService.debug("Command completion failed.", e)
val prefix = configurationService.findValue<String>("messages.prefix")
proxyService.sendMessage(source, prefix + "Cannot find command.")
val data = StringBuilder()
args.map { d -> data.append(d).append(" ") }
loggingService.info("Cannot find command for args $data.")
}
return true
}
/**
* Returns the [Page] with the given [id] and throws
* a [RuntimeException] if the page is not found.
*/
private fun getPageById(id: Int): Page {
for (page in this.pageCache) {
if (page.id == id) {
return page
}
}
throw RuntimeException("Page does not exist!")
}
}
| apache-2.0 |
chrisbanes/tivi | data/src/main/java/app/tivi/data/repositories/episodes/EpisodeWatchStore.kt | 1 | 3523 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.tivi.data.repositories.episodes
import app.tivi.data.DatabaseTransactionRunner
import app.tivi.data.daos.EpisodeWatchEntryDao
import app.tivi.data.entities.EpisodeWatchEntry
import app.tivi.data.entities.PendingAction
import app.tivi.data.syncers.syncerForEntity
import app.tivi.util.Logger
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class EpisodeWatchStore @Inject constructor(
private val transactionRunner: DatabaseTransactionRunner,
private val episodeWatchEntryDao: EpisodeWatchEntryDao,
logger: Logger
) {
private val episodeWatchSyncer = syncerForEntity(
episodeWatchEntryDao,
{ it.traktId },
{ entity, id -> entity.copy(id = id ?: 0) },
logger
)
fun observeEpisodeWatches(episodeId: Long): Flow<List<EpisodeWatchEntry>> {
return episodeWatchEntryDao.watchesForEpisodeObservable(episodeId)
}
suspend fun save(watch: EpisodeWatchEntry) = episodeWatchEntryDao.insertOrUpdate(watch)
suspend fun save(watches: List<EpisodeWatchEntry>) = episodeWatchEntryDao.insertOrUpdate(watches)
suspend fun getEpisodeWatchesForShow(showId: Long) = episodeWatchEntryDao.entriesForShowId(showId)
suspend fun getWatchesForEpisode(episodeId: Long) = episodeWatchEntryDao.watchesForEpisode(episodeId)
suspend fun getEpisodeWatch(watchId: Long) = episodeWatchEntryDao.entryWithId(watchId)
suspend fun hasEpisodeBeenWatched(episodeId: Long) = episodeWatchEntryDao.watchCountForEpisode(episodeId) > 0
suspend fun getEntriesWithAddAction(showId: Long) = episodeWatchEntryDao.entriesForShowIdWithSendPendingActions(showId)
suspend fun getEntriesWithDeleteAction(showId: Long) = episodeWatchEntryDao.entriesForShowIdWithDeletePendingActions(showId)
suspend fun deleteEntriesWithIds(ids: List<Long>) = episodeWatchEntryDao.deleteWithIds(ids)
suspend fun updateEntriesWithAction(ids: List<Long>, action: PendingAction): Int {
return episodeWatchEntryDao.updateEntriesToPendingAction(ids, action.value)
}
suspend fun addNewShowWatchEntries(
showId: Long,
watches: List<EpisodeWatchEntry>
) = transactionRunner {
val currentWatches = episodeWatchEntryDao.entriesForShowIdWithNoPendingAction(showId)
episodeWatchSyncer.sync(currentWatches, watches, removeNotMatched = false)
}
suspend fun syncShowWatchEntries(
showId: Long,
watches: List<EpisodeWatchEntry>
) = transactionRunner {
val currentWatches = episodeWatchEntryDao.entriesForShowIdWithNoPendingAction(showId)
episodeWatchSyncer.sync(currentWatches, watches)
}
suspend fun syncEpisodeWatchEntries(
episodeId: Long,
watches: List<EpisodeWatchEntry>
) = transactionRunner {
val currentWatches = episodeWatchEntryDao.watchesForEpisode(episodeId)
episodeWatchSyncer.sync(currentWatches, watches)
}
}
| apache-2.0 |
Fitbit/MvRx | sample/src/main/java/com/airbnb/mvrx/sample/features/flow/FlowIntroFragment.kt | 1 | 1567 | package com.airbnb.mvrx.sample.features.flow
import android.os.Bundle
import android.view.View
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.setupWithNavController
import com.airbnb.mvrx.activityViewModel
import com.airbnb.mvrx.sample.R
import com.airbnb.mvrx.sample.core.BaseFragment
import com.airbnb.mvrx.sample.databinding.FlowIntroFragmentBinding
import com.airbnb.mvrx.sample.utils.viewBinding
import com.airbnb.mvrx.sample.views.basicRow
import com.airbnb.mvrx.sample.views.marquee
class FlowIntroFragment : BaseFragment(R.layout.flow_intro_fragment) {
private val binding: FlowIntroFragmentBinding by viewBinding()
private val viewModel: FlowViewModel by activityViewModel()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding.toolbar.setupWithNavController(findNavController())
binding.recyclerView.withModels {
marquee {
id("marquee")
title("Intro")
subtitle("Set the initial counter value")
}
arrayOf(0, 10, 50, 100, 1_000, 10_000).forEach { count ->
basicRow {
id(count)
title("$count")
clickListener { _ ->
viewModel.setCount(count)
findNavController().navigate(R.id.action_flowIntroFragment_to_flowCounterFragment)
}
}
}
}
}
override fun invalidate() {
// Do nothing.
}
}
| apache-2.0 |
jtransc/jtransc | jtransc-core/src/com/jtransc/ast/feature/method/OptimizeFeature.kt | 2 | 739 | /*
* Copyright 2016 Carlos Ballesteros Velasco
*
* 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.jtransc.ast.feature.method
import com.jtransc.ast.AstMethodFeature
class OptimizeFeature : AstMethodFeature() {
} | apache-2.0 |
dataloom/conductor-client | src/main/kotlin/com/openlattice/organizations/ExternalDatabaseManagementService.kt | 1 | 36412 | package com.openlattice.organizations
import com.google.common.base.Preconditions.checkState
import com.hazelcast.core.HazelcastInstance
import com.hazelcast.query.Predicate
import com.hazelcast.query.Predicates
import com.hazelcast.query.QueryConstants
import com.openlattice.assembler.AssemblerConnectionManager.Companion.OPENLATTICE_SCHEMA
import com.openlattice.assembler.AssemblerConnectionManager.Companion.STAGING_SCHEMA
import com.openlattice.assembler.PostgresRoles.Companion.getSecurablePrincipalIdFromUserName
import com.openlattice.assembler.PostgresRoles.Companion.isPostgresUserName
import com.openlattice.assembler.dropAllConnectionsToDatabaseSql
import com.openlattice.authorization.*
import com.openlattice.authorization.processors.PermissionMerger
import com.openlattice.authorization.securable.SecurableObjectType
import com.openlattice.edm.processors.GetEntityTypeFromEntitySetEntryProcessor
import com.openlattice.edm.processors.GetFqnFromPropertyTypeEntryProcessor
import com.openlattice.edm.requests.MetadataUpdate
import com.openlattice.hazelcast.HazelcastMap
import com.openlattice.hazelcast.processors.GetMembersOfOrganizationEntryProcessor
import com.openlattice.hazelcast.processors.organizations.UpdateOrganizationExternalDatabaseColumnEntryProcessor
import com.openlattice.hazelcast.processors.organizations.UpdateOrganizationExternalDatabaseTableEntryProcessor
import com.openlattice.organization.OrganizationExternalDatabaseColumn
import com.openlattice.organization.OrganizationExternalDatabaseTable
import com.openlattice.organization.OrganizationExternalDatabaseTableColumnsPair
import com.openlattice.organizations.mapstores.ORGANIZATION_ID_INDEX
import com.openlattice.organizations.mapstores.TABLE_ID_INDEX
import com.openlattice.organizations.roles.SecurePrincipalsManager
import com.openlattice.postgres.*
import com.openlattice.postgres.DataTables.quote
import com.openlattice.postgres.ResultSetAdapters.*
import com.openlattice.postgres.external.ExternalDatabaseConnectionManager
import com.openlattice.postgres.streams.BasePostgresIterable
import com.openlattice.postgres.streams.StatementHolderSupplier
import com.openlattice.transporter.processors.DestroyTransportedEntitySetEntryProcessor
import com.openlattice.transporter.processors.GetPropertyTypesFromTransporterColumnSetEntryProcessor
import com.openlattice.transporter.processors.TransportEntitySetEntryProcessor
import com.openlattice.transporter.types.TransporterDatastore
import com.zaxxer.hikari.HikariDataSource
import org.apache.olingo.commons.api.edm.FullQualifiedName
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import java.io.BufferedOutputStream
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.StandardCopyOption
import java.nio.file.StandardOpenOption
import java.time.OffsetDateTime
import java.util.*
import kotlin.collections.HashMap
import kotlin.streams.toList
@Service
class ExternalDatabaseManagementService(
hazelcastInstance: HazelcastInstance,
private val externalDbManager: ExternalDatabaseConnectionManager,
private val securePrincipalsManager: SecurePrincipalsManager,
private val aclKeyReservations: HazelcastAclKeyReservationService,
private val authorizationManager: AuthorizationManager,
private val organizationExternalDatabaseConfiguration: OrganizationExternalDatabaseConfiguration,
private val transporterDatastore: TransporterDatastore,
private val dbCredentialService: DbCredentialService,
private val hds: HikariDataSource
) {
private val organizationExternalDatabaseColumns = HazelcastMap.ORGANIZATION_EXTERNAL_DATABASE_COLUMN.getMap(hazelcastInstance)
private val organizationExternalDatabaseTables = HazelcastMap.ORGANIZATION_EXTERNAL_DATABASE_TABLE.getMap(hazelcastInstance)
private val securableObjectTypes = HazelcastMap.SECURABLE_OBJECT_TYPES.getMap(hazelcastInstance)
private val aces = HazelcastMap.PERMISSIONS.getMap(hazelcastInstance)
private val logger = LoggerFactory.getLogger(ExternalDatabaseManagementService::class.java)
private val primaryKeyConstraint = "PRIMARY KEY"
private val FETCH_SIZE = 100_000
/**
* Only needed for materialize entity set, which should move elsewhere eventually
*/
private val entitySets = HazelcastMap.ENTITY_SETS.getMap(hazelcastInstance)
private val entityTypes = HazelcastMap.ENTITY_TYPES.getMap(hazelcastInstance)
private val propertyTypes = HazelcastMap.PROPERTY_TYPES.getMap(hazelcastInstance)
private val organizations = HazelcastMap.ORGANIZATIONS.getMap(hazelcastInstance)
private val transporterState = HazelcastMap.TRANSPORTER_DB_COLUMNS.getMap(hazelcastInstance)
/*CREATE*/
fun createOrganizationExternalDatabaseTable(orgId: UUID, table: OrganizationExternalDatabaseTable): UUID {
val tableFQN = FullQualifiedName(orgId.toString(), table.name)
checkState(organizationExternalDatabaseTables.putIfAbsent(table.id, table) == null,
"OrganizationExternalDatabaseTable ${tableFQN.fullQualifiedNameAsString} already exists")
aclKeyReservations.reserveIdAndValidateType(table, tableFQN::getFullQualifiedNameAsString)
val tableAclKey = AclKey(table.id)
authorizationManager.setSecurableObjectType(tableAclKey, SecurableObjectType.OrganizationExternalDatabaseTable)
return table.id
}
fun createOrganizationExternalDatabaseColumn(orgId: UUID, column: OrganizationExternalDatabaseColumn): UUID {
checkState(organizationExternalDatabaseTables[column.tableId] != null,
"OrganizationExternalDatabaseColumn ${column.name} belongs to " +
"a table with id ${column.tableId} that does not exist")
val columnFQN = FullQualifiedName(column.tableId.toString(), column.name)
checkState(organizationExternalDatabaseColumns.putIfAbsent(column.id, column) == null,
"OrganizationExternalDatabaseColumn $columnFQN already exists")
aclKeyReservations.reserveIdAndValidateType(column, columnFQN::getFullQualifiedNameAsString)
val columnAclKey = AclKey(column.tableId, column.id)
authorizationManager.setSecurableObjectType(columnAclKey, SecurableObjectType.OrganizationExternalDatabaseColumn)
return column.id
}
fun getColumnMetadata(tableName: String, tableId: UUID, orgId: UUID, columnName: Optional<String>): BasePostgresIterable<
OrganizationExternalDatabaseColumn> {
var columnCondition = ""
columnName.ifPresent { columnCondition = "AND information_schema.columns.column_name = '$it'" }
val sql = getColumnMetadataSql(tableName, columnCondition)
return BasePostgresIterable(
StatementHolderSupplier(externalDbManager.connectToOrg(orgId), sql)
) { rs ->
val storedColumnName = columnName(rs)
val dataType = sqlDataType(rs)
val position = ordinalPosition(rs)
val isPrimaryKey = constraintType(rs) == primaryKeyConstraint
OrganizationExternalDatabaseColumn(
Optional.empty(),
storedColumnName,
storedColumnName,
Optional.empty(),
tableId,
orgId,
dataType,
isPrimaryKey,
position)
}
}
fun destroyTransportedEntitySet(entitySetId: UUID) {
entitySets.executeOnKey(entitySetId, DestroyTransportedEntitySetEntryProcessor().init(transporterDatastore))
}
fun transportEntitySet(organizationId: UUID, entitySetId: UUID) {
val userToPrincipalsCompletion = organizations.submitToKey(
organizationId,
GetMembersOfOrganizationEntryProcessor()
).thenApplyAsync { members ->
securePrincipalsManager.bulkGetUnderlyingPrincipals(
securePrincipalsManager.getSecurablePrincipals(members).toSet()
).mapKeys {
dbCredentialService.getDbUsername(it.key)
}
}
val entityTypeId = entitySets.submitToKey(
entitySetId,
GetEntityTypeFromEntitySetEntryProcessor()
)
val accessCheckCompletion = entityTypeId.thenCompose { etid ->
entityTypes.getAsync(etid!!)
}.thenApplyAsync { entityType ->
entityType.properties.mapTo(mutableSetOf()) { ptid ->
AccessCheck(AclKey(entitySetId, ptid), EnumSet.of(Permission.READ))
}
}
val transporterColumnsCompletion = entityTypeId.thenCompose { etid ->
requireNotNull(etid) {
"Entity set $entitySetId has no entity type"
}
transporterState.submitToKey(etid, GetPropertyTypesFromTransporterColumnSetEntryProcessor())
}.thenCompose { transporterPtIds ->
propertyTypes.submitToKeys(transporterPtIds, GetFqnFromPropertyTypeEntryProcessor())
}
val userToPermissionsCompletion = userToPrincipalsCompletion.thenCombine(accessCheckCompletion) { userToPrincipals, accessChecks ->
userToPrincipals.mapValues { (_, principals) ->
authorizationManager.accessChecksForPrincipals(accessChecks, principals).filter {
it.permissions[Permission.READ]!!
}.map {
it.aclKey[1]
}.toList()
}
}
userToPermissionsCompletion.thenCombine(transporterColumnsCompletion) { userToPtCols, transporterColumns ->
val userToEntitySetColumnNames = userToPtCols.mapValues { (_, columns) ->
columns.map {
transporterColumns.get(it).toString()
}
}
entitySets.submitToKey(entitySetId,
TransportEntitySetEntryProcessor(transporterColumns, organizationId, userToEntitySetColumnNames)
.init(transporterDatastore)
)
}.toCompletableFuture().get().toCompletableFuture().get()
}
/*GET*/
fun getExternalDatabaseTables(orgId: UUID): Set<Map.Entry<UUID, OrganizationExternalDatabaseTable>> {
return organizationExternalDatabaseTables.entrySet(belongsToOrganization(orgId))
}
fun getExternalDatabaseTablesWithColumns(orgId: UUID): Map<Pair<UUID, OrganizationExternalDatabaseTable>, Set<Map.Entry<UUID, OrganizationExternalDatabaseColumn>>> {
val tables = getExternalDatabaseTables(orgId)
return tables.map {
Pair(it.key, it.value) to (organizationExternalDatabaseColumns.entrySet(belongsToTable(it.key)))
}.toMap()
}
fun getExternalDatabaseTableWithColumns(tableId: UUID): OrganizationExternalDatabaseTableColumnsPair {
val table = getOrganizationExternalDatabaseTable(tableId)
return OrganizationExternalDatabaseTableColumnsPair(table, organizationExternalDatabaseColumns.values(belongsToTable(tableId)).toSet())
}
fun getExternalDatabaseTableData(
orgId: UUID,
tableId: UUID,
authorizedColumns: Set<OrganizationExternalDatabaseColumn>,
rowCount: Int): Map<UUID, List<Any?>> {
val tableName = organizationExternalDatabaseTables.getValue(tableId).name
val columnNamesSql = authorizedColumns.joinToString(", ") { it.name }
val dataByColumnId = mutableMapOf<UUID, MutableList<Any?>>()
val sql = "SELECT $columnNamesSql FROM $tableName LIMIT $rowCount"
BasePostgresIterable(
StatementHolderSupplier(externalDbManager.connectToOrg(orgId), sql)
) { rs ->
val pairsList = mutableListOf<Pair<UUID, Any?>>()
authorizedColumns.forEach {
pairsList.add(it.id to rs.getObject(it.name))
}
return@BasePostgresIterable pairsList
}.forEach { pairsList ->
pairsList.forEach {
dataByColumnId.getOrPut(it.first) { mutableListOf() }.add(it.second)
}
}
return dataByColumnId
}
fun getOrganizationExternalDatabaseTable(tableId: UUID): OrganizationExternalDatabaseTable {
return organizationExternalDatabaseTables.getValue(tableId)
}
fun getOrganizationExternalDatabaseColumn(columnId: UUID): OrganizationExternalDatabaseColumn {
return organizationExternalDatabaseColumns.getValue(columnId)
}
fun getColumnNamesByTableName(dbName: String): Map<String, TableSchemaInfo> {
val columnNamesByTableName = mutableMapOf<String, TableSchemaInfo>()
val sql = getCurrentTableAndColumnNamesSql()
BasePostgresIterable(
StatementHolderSupplier(externalDbManager.connect(dbName), sql, FETCH_SIZE)
) { rs -> TableInfo(oid(rs), name(rs) , columnName(rs)) }
.forEach {
columnNamesByTableName
.getOrPut(it.tableName) {
TableSchemaInfo(it.oid, mutableSetOf())
}.columnNames.add(it.columnName)
}
return columnNamesByTableName
}
/*UPDATE*/
fun updateOrganizationExternalDatabaseTable(orgId: UUID, tableFqnToId: Pair<String, UUID>, update: MetadataUpdate) {
update.name.ifPresent {
val newTableFqn = FullQualifiedName(orgId.toString(), it)
val oldTableName = getNameFromFqnString(tableFqnToId.first)
externalDbManager.connectToOrg(orgId).connection.use { conn ->
val stmt = conn.createStatement()
stmt.execute("ALTER TABLE $oldTableName RENAME TO $it")
}
aclKeyReservations.renameReservation(tableFqnToId.second, newTableFqn.fullQualifiedNameAsString)
}
organizationExternalDatabaseTables.submitToKey(tableFqnToId.second, UpdateOrganizationExternalDatabaseTableEntryProcessor(update))
}
fun updateOrganizationExternalDatabaseColumn(orgId: UUID, tableFqnToId: Pair<String, UUID>, columnFqnToId: Pair<String, UUID>, update: MetadataUpdate) {
update.name.ifPresent {
val tableName = getNameFromFqnString(tableFqnToId.first)
val newColumnFqn = FullQualifiedName(tableFqnToId.second.toString(), it)
val oldColumnName = getNameFromFqnString(columnFqnToId.first)
externalDbManager.connectToOrg(orgId).connection.use { conn ->
val stmt = conn.createStatement()
stmt.execute("ALTER TABLE $tableName RENAME COLUMN $oldColumnName to $it")
}
aclKeyReservations.renameReservation(columnFqnToId.second, newColumnFqn.fullQualifiedNameAsString)
}
organizationExternalDatabaseColumns.submitToKey(columnFqnToId.second, UpdateOrganizationExternalDatabaseColumnEntryProcessor(update))
}
/*DELETE*/
fun deleteOrganizationExternalDatabaseTables(orgId: UUID, tableIdByFqn: Map<String, UUID>) {
tableIdByFqn.forEach { (tableFqn, tableId) ->
val tableName = getNameFromFqnString(tableFqn)
//delete columns from tables
val tableFqnToId = Pair(tableFqn, tableId)
val columnIdByFqn = organizationExternalDatabaseColumns
.entrySet(belongsToTable(tableId))
.map { FullQualifiedName(tableId.toString(), it.value.name).toString() to it.key }
.toMap()
val columnsByTable = mapOf(tableFqnToId to columnIdByFqn)
deleteOrganizationExternalDatabaseColumns(orgId, columnsByTable)
//delete tables from postgres
externalDbManager.connectToOrg(orgId).connection.use { conn ->
val stmt = conn.createStatement()
stmt.execute("DROP TABLE $tableName")
}
}
//delete securable object
val tableIds = tableIdByFqn.values.toSet()
deleteOrganizationExternalDatabaseTableObjects(tableIds)
}
fun deleteOrganizationExternalDatabaseTableObjects(tableIds: Set<UUID>) {
tableIds.forEach {
val aclKey = AclKey(it)
authorizationManager.deletePermissions(aclKey)
securableObjectTypes.remove(aclKey)
aclKeyReservations.release(it)
}
organizationExternalDatabaseTables.removeAll(idsPredicate(tableIds))
}
fun deleteOrganizationExternalDatabaseColumns(orgId: UUID, columnsByTable: Map<Pair<String, UUID>, Map<String, UUID>>) {
columnsByTable.forEach { (tableFqnToId, columnIdsByFqn) ->
if (columnIdsByFqn.isEmpty()) return@forEach
val tableName = getNameFromFqnString(tableFqnToId.first)
val tableId = tableFqnToId.second
val columnNames = columnIdsByFqn.keys.map { getNameFromFqnString(it) }.toSet()
val columnIds = columnIdsByFqn.values.toSet()
//delete columns from postgres
val dropColumnsSql = createDropColumnSql(columnNames)
externalDbManager.connectToOrg(orgId).connection.use { conn ->
val stmt = conn.createStatement()
stmt.execute("ALTER TABLE $tableName $dropColumnsSql")
}
deleteOrganizationExternalDatabaseColumnObjects(mapOf(tableId to columnIds))
}
}
fun deleteOrganizationExternalDatabaseColumnObjects(columnIdsByTableId: Map<UUID, Set<UUID>>) {
columnIdsByTableId.forEach { (tableId, columnIds) ->
columnIds.forEach { columnId ->
val aclKey = AclKey(tableId, columnId)
authorizationManager.deletePermissions(aclKey)
securableObjectTypes.remove(aclKey)
aclKeyReservations.release(columnId)
}
organizationExternalDatabaseColumns.removeAll(idsPredicate(columnIds))
}
}
/**
* Deletes an organization's entire database.
* Is called when an organization is deleted.
*/
fun deleteOrganizationExternalDatabase(orgId: UUID) {
//remove all tables/columns within org
val tableIdByFqn = organizationExternalDatabaseTables
.entrySet(belongsToOrganization(orgId))
.map { FullQualifiedName(orgId.toString(), it.value.name).toString() to it.key }
.toMap()
deleteOrganizationExternalDatabaseTables(orgId, tableIdByFqn)
//drop db from schema
val dbName = externalDbManager.getOrganizationDatabaseName(orgId)
externalDbManager.connect(dbName).connection.use { conn ->
val stmt = conn.createStatement()
stmt.execute(dropAllConnectionsToDatabaseSql(dbName))
stmt.execute("DROP DATABASE $dbName")
}
}
/*PERMISSIONS*/
fun addHBARecord(orgId: UUID, userPrincipal: Principal, connectionType: PostgresConnectionType, ipAddress: String) {
val dbName = externalDbManager.getOrganizationDatabaseName(orgId)
val username = getDBUser(userPrincipal.id)
val record = PostgresAuthenticationRecord(
connectionType,
dbName,
username,
ipAddress,
organizationExternalDatabaseConfiguration.authMethod)
hds.connection.use { connection ->
connection.createStatement().use { stmt ->
val hbaTable = PostgresTable.HBA_AUTHENTICATION_RECORDS
val columns = hbaTable.columns.joinToString(", ", "(", ")") { it.name }
val pkey = hbaTable.primaryKey.joinToString(", ", "(", ")") { it.name }
val insertRecordSql = getInsertRecordSql(hbaTable, columns, pkey, record)
stmt.executeUpdate(insertRecordSql)
}
}
updateHBARecords(dbName)
}
fun removeHBARecord(orgId: UUID, userPrincipal: Principal, connectionType: PostgresConnectionType, ipAddress: String) {
val dbName = externalDbManager.getOrganizationDatabaseName(orgId)
val username = getDBUser(userPrincipal.id)
val record = PostgresAuthenticationRecord(
connectionType,
dbName,
username,
ipAddress,
organizationExternalDatabaseConfiguration.authMethod)
hds.connection.use {
val stmt = it.createStatement()
val hbaTable = PostgresTable.HBA_AUTHENTICATION_RECORDS
val deleteRecordSql = getDeleteRecordSql(hbaTable, record)
stmt.executeUpdate(deleteRecordSql)
}
updateHBARecords(dbName)
}
fun getOrganizationOwners(orgId: UUID): Set<SecurablePrincipal> {
val principals = securePrincipalsManager.getAuthorizedPrincipalsOnSecurableObject(AclKey(orgId), EnumSet.of(Permission.OWNER))
return securePrincipalsManager.getSecurablePrincipals(principals).toSet()
}
/**
* Sets privileges for a user on an organization's column
*/
fun executePrivilegesUpdate(action: Action, columnAcls: List<Acl>) {
val columnIds = columnAcls.map { it.aclKey[1] }.toSet()
val columnsById = organizationExternalDatabaseColumns.getAll(columnIds)
val columnAclsByOrg = columnAcls.groupBy {
columnsById.getValue(it.aclKey[1]).organizationId
}
columnAclsByOrg.forEach { (orgId, columnAcls) ->
externalDbManager.connectToOrg(orgId).connection.use { conn ->
conn.autoCommit = false
val stmt = conn.createStatement()
columnAcls.forEach {
val tableAndColumnNames = getTableAndColumnNames(AclKey(it.aclKey))
val tableName = tableAndColumnNames.first
val columnName = tableAndColumnNames.second
it.aces.forEach { ace ->
if (!areValidPermissions(ace.permissions)) {
throw IllegalStateException("Permissions ${ace.permissions} are not valid")
}
val dbUser = getDBUser(ace.principal.id)
//revoke any previous privileges before setting specified ones
if (action == Action.SET) {
val revokeSql = createPrivilegesUpdateSql(Action.REMOVE, listOf("ALL"), tableName, columnName, dbUser)
stmt.addBatch(revokeSql)
}
val privileges = getPrivilegesFromPermissions(ace.permissions)
val grantSql = createPrivilegesUpdateSql(action, privileges, tableName, columnName, dbUser)
stmt.addBatch(grantSql)
}
stmt.executeBatch()
conn.commit()
}
}
}
}
/**
* Revokes all privileges for a user on an organization's database
* when that user is removed from an organization.
*/
fun revokeAllPrivilegesFromMember(orgId: UUID, userId: String) {
val dbName = externalDbManager.getOrganizationDatabaseName(orgId)
val userName = getDBUser(userId)
externalDbManager.connect(dbName).connection.use { conn ->
val stmt = conn.createStatement()
stmt.execute("REVOKE ALL ON DATABASE $dbName FROM $userName")
}
}
fun syncPermissions(
orgOwnerIds: List<UUID>,
orgId: UUID,
tableId: UUID,
tableName: String,
maybeColumnId: Optional<UUID>,
maybeColumnName: Optional<String>
): List<Acl> {
val privilegesByUser = HashMap<UUID, MutableSet<PostgresPrivileges>>()
val aclKeyUUIDs = mutableListOf(tableId)
var objectType = SecurableObjectType.OrganizationExternalDatabaseTable
var aclKey = AclKey(aclKeyUUIDs)
val ownerPrivileges = PostgresPrivileges.values().toMutableSet()
ownerPrivileges.remove(PostgresPrivileges.ALL)
//if column objects, sync postgres privileges
maybeColumnId.ifPresent { columnId ->
aclKeyUUIDs.add(columnId)
aclKey = AclKey(aclKeyUUIDs)
val privilegesFields = getPrivilegesFields(tableName, maybeColumnName)
val sql = privilegesFields.first
objectType = privilegesFields.second
BasePostgresIterable(
StatementHolderSupplier(externalDbManager.connectToOrg(orgId), sql)
) { rs ->
user(rs) to PostgresPrivileges.valueOf(privilegeType(rs).toUpperCase())
}
.filter { isPostgresUserName(it.first) }
.forEach {
val securablePrincipalId = getSecurablePrincipalIdFromUserName(it.first)
privilegesByUser.getOrPut(securablePrincipalId) { mutableSetOf() }.add(it.second)
}
}
//give organization owners all privileges
orgOwnerIds.forEach { orgOwnerId ->
privilegesByUser.getOrPut(orgOwnerId) { mutableSetOf() }.addAll(ownerPrivileges)
}
return privilegesByUser.map { (securablePrincipalId, privileges) ->
val principal = securePrincipalsManager.getSecurablePrincipalById(securablePrincipalId).principal
val aceKey = AceKey(aclKey, principal)
val permissions = EnumSet.noneOf(Permission::class.java)
if (privileges == ownerPrivileges) {
permissions.addAll(setOf(Permission.OWNER, Permission.READ, Permission.WRITE))
} else {
if (privileges.contains(PostgresPrivileges.SELECT)) {
permissions.add(Permission.READ)
}
if (privileges.contains(PostgresPrivileges.INSERT) || privileges.contains(PostgresPrivileges.UPDATE))
permissions.add(Permission.WRITE)
}
aces.executeOnKey(aceKey, PermissionMerger(permissions, objectType, OffsetDateTime.MAX))
return@map Acl(aclKeyUUIDs, setOf(Ace(principal, permissions, Optional.empty())))
}
}
/*PRIVATE FUNCTIONS*/
private fun getNameFromFqnString(fqnString: String): String {
return FullQualifiedName(fqnString).name
}
private fun createDropColumnSql(columnNames: Set<String>): String {
return columnNames.joinToString(", ") { "DROP COLUMN ${quote(it)}" }
}
private fun createPrivilegesUpdateSql(action: Action, privileges: List<String>, tableName: String, columnName: String, dbUser: String): String {
val privilegesAsString = privileges.joinToString(separator = ", ")
checkState(action == Action.REMOVE || action == Action.ADD || action == Action.SET,
"Invalid action $action specified")
return if (action == Action.REMOVE) {
"REVOKE $privilegesAsString (${quote(columnName)}) ON $tableName FROM $dbUser"
} else {
"GRANT $privilegesAsString (${quote(columnName)}) ON $tableName TO $dbUser"
}
}
private fun getTableAndColumnNames(aclKey: AclKey): Pair<String, String> {
val securableObjectId = aclKey[1]
val organizationAtlasColumn = organizationExternalDatabaseColumns.getValue(securableObjectId)
val tableName = organizationExternalDatabaseTables.getValue(organizationAtlasColumn.tableId).name
val columnName = organizationAtlasColumn.name
return Pair(tableName, columnName)
}
private fun getDBUser(principalId: String): String {
val securePrincipal = securePrincipalsManager.getPrincipal(principalId)
checkState(securePrincipal.principalType == PrincipalType.USER, "Principal must be of type USER")
return dbCredentialService.getDbUsername(securePrincipal)
}
private fun areValidPermissions(permissions: Set<Permission>): Boolean {
if (!(permissions.contains(Permission.OWNER) || permissions.contains(Permission.READ) || permissions.contains(Permission.WRITE))) {
return false
} else if (permissions.isEmpty()) {
return false
}
return true
}
private fun getPrivilegesFromPermissions(permissions: Set<Permission>): List<String> {
val privileges = mutableListOf<String>()
if (permissions.contains(Permission.OWNER)) {
privileges.add(PostgresPrivileges.ALL.toString())
} else {
if (permissions.contains(Permission.WRITE)) {
privileges.addAll(listOf(
PostgresPrivileges.INSERT.toString(),
PostgresPrivileges.UPDATE.toString()))
}
if (permissions.contains(Permission.READ)) {
privileges.add(PostgresPrivileges.SELECT.toString())
}
}
return privileges
}
private fun getPrivilegesFields(tableName: String, maybeColumnName: Optional<String>): Pair<String, SecurableObjectType> {
var columnCondition = ""
var grantsTableName = "information_schema.role_table_grants"
var objectType = SecurableObjectType.OrganizationExternalDatabaseTable
if (maybeColumnName.isPresent) {
val columnName = maybeColumnName.get()
columnCondition = "AND column_name = '$columnName'"
grantsTableName = "information_schema.role_column_grants"
objectType = SecurableObjectType.OrganizationExternalDatabaseColumn
}
val sql = getCurrentUsersPrivilegesSql(tableName, grantsTableName, columnCondition)
return Pair(sql, objectType)
}
private fun updateHBARecords(dbName: String) {
val originalHBAPath = Paths.get(organizationExternalDatabaseConfiguration.path + organizationExternalDatabaseConfiguration.fileName)
val tempHBAPath = Paths.get(organizationExternalDatabaseConfiguration.path + "/temp_hba.conf")
//create hba file with new records
val records = getHBARecords(PostgresTable.HBA_AUTHENTICATION_RECORDS.name)
.map {
it.buildHBAConfRecord()
}.toSet()
try {
val out = BufferedOutputStream(
Files.newOutputStream(tempHBAPath, StandardOpenOption.WRITE, StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING)
)
records.forEach {
val recordAsByteArray = it.toByteArray()
out.write(recordAsByteArray)
}
out.close()
//reload config
externalDbManager.connect(dbName).connection.use { conn ->
val stmt = conn.createStatement()
stmt.executeQuery(getReloadConfigSql())
}
} catch (ex: IOException) {
logger.info("IO exception while creating new hba config")
}
//replace old hba with new hba
try {
Files.move(tempHBAPath, originalHBAPath, StandardCopyOption.REPLACE_EXISTING)
} catch (ex: IOException) {
logger.info("IO exception while updating hba config")
}
}
private fun getHBARecords(tableName: String): BasePostgresIterable<PostgresAuthenticationRecord> {
return BasePostgresIterable(
StatementHolderSupplier(hds, getSelectRecordsSql(tableName))
) { rs ->
postgresAuthenticationRecord(rs)
}
}
/**
* Moves a table from the [OPENLATTICE_SCHEMA] schema to the [STAGING_SCHEMA] schema
*/
fun promoteStagingTable(organizationId: UUID, tableName: String) {
externalDbManager.connectToOrg(organizationId).use { hds ->
hds.connection.use { conn ->
conn.createStatement().use { stmt ->
stmt.execute(publishStagingTableSql(tableName))
}
}
}
}
/*INTERNAL SQL QUERIES*/
private fun getCurrentTableAndColumnNamesSql(): String {
return selectExpression + fromExpression + leftJoinColumnsExpression +
"WHERE information_schema.tables.table_schema=ANY('{$OPENLATTICE_SCHEMA,$STAGING_SCHEMA}') " +
"AND table_type='BASE TABLE'"
}
private fun getColumnMetadataSql(tableName: String, columnCondition: String): String {
return selectExpression + ", information_schema.columns.data_type AS datatype, " +
"information_schema.columns.ordinal_position, " +
"information_schema.table_constraints.constraint_type " +
fromExpression + leftJoinColumnsExpression +
"LEFT OUTER JOIN information_schema.constraint_column_usage ON " +
"information_schema.columns.column_name = information_schema.constraint_column_usage.column_name " +
"AND information_schema.columns.table_name = information_schema.constraint_column_usage.table_name " +
"LEFT OUTER JOIN information_schema.table_constraints " +
"ON information_schema.constraint_column_usage.constraint_name = " +
"information_schema.table_constraints.constraint_name " +
"WHERE information_schema.columns.table_name = '$tableName' " +
"AND (information_schema.table_constraints.constraint_type = 'PRIMARY KEY' " +
"OR information_schema.table_constraints.constraint_type IS NULL)" +
columnCondition
}
private fun getCurrentUsersPrivilegesSql(tableName: String, grantsTableName: String, columnCondition: String): String {
return "SELECT grantee AS user, privilege_type " +
"FROM $grantsTableName " +
"WHERE table_name = '$tableName' " +
columnCondition
}
private fun getReloadConfigSql(): String {
return "SELECT pg_reload_conf()"
}
private val selectExpression = "SELECT oid, information_schema.tables.table_name AS name, information_schema.columns.column_name "
private val fromExpression = "FROM information_schema.tables "
private val leftJoinColumnsExpression0 = "LEFT JOIN pg_class ON relname = information_schema.tables.table_name "
private val leftJoinColumnsExpression = "LEFT JOIN information_schema.columns ON information_schema.tables.table_name = information_schema.columns.table_name $leftJoinColumnsExpression0"
private fun getInsertRecordSql(table: PostgresTableDefinition, columns: String, pkey: String, record: PostgresAuthenticationRecord): String {
return "INSERT INTO ${table.name} $columns VALUES(${record.buildPostgresRecord()}) " +
"ON CONFLICT $pkey DO UPDATE SET ${PostgresColumn.AUTHENTICATION_METHOD.name}=EXCLUDED.${PostgresColumn.AUTHENTICATION_METHOD.name}"
}
private fun getDeleteRecordSql(table: PostgresTableDefinition, record: PostgresAuthenticationRecord): String {
return "DELETE FROM ${table.name} WHERE ${PostgresColumn.USERNAME.name} = '${record.username}' " +
"AND ${PostgresColumn.DATABASE.name} = '${record.database}' " +
"AND ${PostgresColumn.CONNECTION_TYPE.name} = '${record.connectionType}' " +
"AND ${PostgresColumn.IP_ADDRESS.name} = '${record.ipAddress}'"
}
private fun getSelectRecordsSql(tableName: String): String {
return "SELECT * FROM $tableName"
}
/*PREDICATES*/
private fun <T> idsPredicate(ids: Set<UUID>): Predicate<UUID, T> {
return Predicates.`in`(QueryConstants.KEY_ATTRIBUTE_NAME.value(), *ids.toTypedArray())
}
private fun belongsToOrganization(orgId: UUID): Predicate<UUID, OrganizationExternalDatabaseTable> {
return Predicates.equal(ORGANIZATION_ID_INDEX, orgId)
}
private fun belongsToTable(tableId: UUID): Predicate<UUID, OrganizationExternalDatabaseColumn> {
return Predicates.equal(TABLE_ID_INDEX, tableId)
}
private fun publishStagingTableSql(tableName: String): String {
return "ALTER TABLE ${quote(tableName)} SET SCHEMA $OPENLATTICE_SCHEMA"
}
}
data class TableSchemaInfo(
val oid: Int,
val columnNames: MutableSet<String>
)
data class TableInfo(
val oid : Int,
val tableName: String,
val columnName: String
) | gpl-3.0 |
MyDogTom/detekt | detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/naming/VariableMinLength.kt | 1 | 1208 | package io.gitlab.arturbosch.detekt.rules.style.naming
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.rules.SubRule
import org.jetbrains.kotlin.psi.KtVariableDeclaration
class VariableMinLength(config: Config = Config.empty) : SubRule<KtVariableDeclaration>(config) {
override val issue = Issue(javaClass.simpleName,
Severity.Style,
debt = Debt.FIVE_MINS)
private val minimumVariableNameLength
= valueOrDefault(MINIMUM_VARIABLE_NAME_LENGTH, DEFAULT_MINIMUM_VARIABLE_NAME_LENGTH)
override fun apply(element: KtVariableDeclaration) {
if (element.identifierName().length < minimumVariableNameLength) {
report(CodeSmell(
issue.copy(description = "Variable names should be at least $minimumVariableNameLength characters long."),
Entity.from(element)))
}
}
companion object {
const val MINIMUM_VARIABLE_NAME_LENGTH = "minimumVariableNameLength"
private const val DEFAULT_MINIMUM_VARIABLE_NAME_LENGTH = 3
}
}
| apache-2.0 |
Vakosta/Chapper | app/src/main/java/org/chapper/chapper/presentation/screen/intro/ImagePickSlide.kt | 1 | 2801 | package org.chapper.chapper.presentation.screen.intro
import agency.tango.materialintroscreen.SlideFragment
import android.Manifest
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import com.mvc.imagepicker.ImagePicker
import de.hdodenhof.circleimageview.CircleImageView
import org.chapper.chapper.R
import org.chapper.chapper.data.Constants
import org.chapper.chapper.data.repository.SettingsRepository
import kotlin.properties.Delegates
class ImagePickSlide : SlideFragment() {
private var mPhoto: CircleImageView by Delegates.notNull()
private var mPickButton: Button by Delegates.notNull()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_image_pick_slide, container, false)
mPhoto = view.findViewById(R.id.selectedPhotoImageView)
mPickButton = view.findViewById(R.id.pickButton)
mPickButton.setOnClickListener {
pick()
}
return view
}
override fun backgroundColor(): Int = R.color.colorPrimary
override fun buttonsColor(): Int = R.color.colorAccent
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == RESULT_OK && data != null) {
val bitmap: Bitmap = ImagePicker.getImageFromResult(activity!!.applicationContext, requestCode, resultCode, data)!!
mPhoto.setImageBitmap(bitmap)
SettingsRepository.setProfilePhoto(activity!!.applicationContext, bitmap)
}
}
private fun pick() {
val permissionCheck = ContextCompat.checkSelfPermission(activity!!.applicationContext, Manifest.permission.WRITE_EXTERNAL_STORAGE)
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity!!,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
Constants.WRITE_EXTERNAL_STORAGE_PERMISSIONS)
return
}
ImagePicker.pickImage(this)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when (requestCode) {
Constants.WRITE_EXTERNAL_STORAGE_PERMISSIONS -> {
if ((grantResults.isNotEmpty()) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
pick()
}
}
}
}
} | gpl-2.0 |
sangcomz/FishBun | FishBun/src/main/java/com/sangcomz/fishbun/permission/PermissionCheck.kt | 1 | 3229 | package com.sangcomz.fishbun.permission
import android.Manifest.permission.*
import android.annotation.TargetApi
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.sangcomz.fishbun.R
/**
* Created by sangc on 2015-10-12.
*/
class PermissionCheck(private val context: Context) {
private fun checkPermission(permissionList: List<String>, requestCode: Int): Boolean {
if (context !is Activity) return false
val needRequestPermissionList = permissionList
.map { it to ContextCompat.checkSelfPermission(context, it) }
.filter { it.second != PackageManager.PERMISSION_GRANTED }
.map { it.first }
.toTypedArray()
return if (needRequestPermissionList.isEmpty()) {
true
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(
context,
needRequestPermissionList.first()
)
) {
ActivityCompat.requestPermissions(context, needRequestPermissionList, requestCode)
} else {
ActivityCompat.requestPermissions(context, needRequestPermissionList, requestCode)
}
false
}
}
fun checkStoragePermission(requestCode: Int): Boolean {
return when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU -> {
checkStoragePermissionUnderAPI33(requestCode)
}
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU -> {
checkStoragePermissionOrHigherAPI33(requestCode)
}
else -> true
}
}
@TargetApi(Build.VERSION_CODES.M)
fun checkStoragePermissionUnderAPI33(requestCode: Int): Boolean {
return checkPermission(
arrayListOf(READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE),
requestCode
)
}
@TargetApi(Build.VERSION_CODES.TIRAMISU)
fun checkStoragePermissionOrHigherAPI33(requestCode: Int): Boolean {
return checkPermission(
arrayListOf(READ_MEDIA_IMAGES),
requestCode
)
}
@TargetApi(Build.VERSION_CODES.M)
fun checkCameraPermission(requestCode: Int): Boolean {
try {
val info = context.packageManager.getPackageInfo(
context.packageName,
PackageManager.GET_PERMISSIONS
)
//This array contains the requested permissions.
val permissions = info.requestedPermissions
return if (permissions?.contains(CAMERA) == true) {
checkPermission(listOf(CAMERA), requestCode)
} else {
false
}
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
return false
}
}
fun showPermissionDialog() {
Toast.makeText(context, R.string.msg_permission, Toast.LENGTH_SHORT).show()
}
} | apache-2.0 |
laurencegw/jenjin | jenjin-core/src/main/kotlin/com/binarymonks/jj/core/api/TasksAPI.kt | 1 | 1166 | package com.binarymonks.jj.core.api
import com.binarymonks.jj.core.async.FunctionClosureBuilder
import com.binarymonks.jj.core.async.Task
import kotlin.reflect.KFunction
/**
* Lets you add [com.binarymonks.jj.core.async.Task]s to parts of the game loop.
*/
interface TasksAPI {
fun addPreLoopTask(task: Task)
fun addPostPhysicsTask(task: Task)
fun doOnceAfterPhysics(fn: () -> Unit)
/**
* Often you need to do something that involves modifying something in the physics world during the
* physics step. With box2d this is not allowed, so you need to schedule something to happen after the
* step. But, what if you need to have access to the context that you have now to pass into the function?
*
* This lets you capture a closure around the function that you want to call, but the closure will automatically
* be recycled into a pool. No object creation to make GC sad.
*
* The function will then be called with the arguments in the closure.
*/
fun doOnceAfterPhysicsCapture(function: KFunction<*>, build: (FunctionClosureBuilder.() -> Unit)? = null)
fun addPrePhysicsTask(task: Task)
}
| apache-2.0 |
msebire/intellij-community | community-guitests/testSrc/com/intellij/ide/projectWizard/kotlin/createProject/CreateGradleProjectWithKotlinGuiTest.kt | 1 | 3406 | // 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.ide.projectWizard.kotlin.createProject
import com.intellij.ide.projectWizard.kotlin.model.*
import com.intellij.testGuiFramework.framework.param.GuiTestSuiteParam
import com.intellij.testGuiFramework.impl.ScreenshotOnFailure
import com.intellij.testGuiFramework.util.currentTimeInHumanString
import com.intellij.testGuiFramework.util.scenarios.NewProjectDialogModel
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import java.io.Serializable
@RunWith(GuiTestSuiteParam::class)
class CreateGradleProjectWithKotlinGuiTest(private val testParameters: TestParameters) : KotlinGuiTestCase() {
data class TestParameters(
val projectName: String,
val project: ProjectProperties,
val gradleModuleGroup: NewProjectDialogModel.GradleGroupModules,
val expectedFacet: FacetStructure) : Serializable {
override fun toString() = projectName
}
@Before
fun beforeTest(){
ScreenshotOnFailure.takeScreenshot("${currentTimeInHumanString}_before_${testMethod.methodName}")
}
@After
fun afterTest(){
ScreenshotOnFailure.takeScreenshot("${currentTimeInHumanString}_after_${testMethod.methodName}")
}
@Test
fun createGradleWithKotlin() {
testGradleProjectWithKotlin(
kotlinVersion = KotlinTestProperties.kotlin_artifact_version,
project = testParameters.project,
expectedFacet = testParameters.expectedFacet,
gradleOptions = NewProjectDialogModel.GradleProjectOptions(
artifact = testParameters.projectName,
framework = testParameters.project.frameworkName,
useKotlinDsl = testParameters.project.isKotlinDsl,
groupModules = testParameters.gradleModuleGroup
)
)
}
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{0}")
fun data(): Collection<TestParameters> {
return listOf(
TestParameters(
projectName = "gradle_with_jvm_explicit",
project = kotlinProjects.getValue(Projects.GradleGProjectJvm),
expectedFacet = defaultFacetSettings.getValue(TargetPlatform.JVM18),
gradleModuleGroup = NewProjectDialogModel.GradleGroupModules.ExplicitModuleGroups
),
TestParameters(
projectName = "gradle_with_jvm_qualified",
project = kotlinProjects.getValue(Projects.GradleGProjectJvm),
expectedFacet = defaultFacetSettings.getValue(TargetPlatform.JVM18),
gradleModuleGroup = NewProjectDialogModel.GradleGroupModules.QualifiedNames
),
TestParameters(
projectName = "gradle_with_js_explicit",
project = kotlinProjects.getValue(Projects.GradleGProjectJs),
expectedFacet = defaultFacetSettings.getValue(TargetPlatform.JavaScript),
gradleModuleGroup = NewProjectDialogModel.GradleGroupModules.ExplicitModuleGroups
),
TestParameters(
projectName = "gradle_with_js_qualified",
project = kotlinProjects.getValue(Projects.GradleGProjectJs),
expectedFacet = defaultFacetSettings.getValue(TargetPlatform.JavaScript),
gradleModuleGroup = NewProjectDialogModel.GradleGroupModules.QualifiedNames
)
)
}
}
} | apache-2.0 |
jjoller/foxinabox | src/jjoller/foxinabox/FiveCardValue.kt | 1 | 16337 | package jjoller.foxinabox
import java.util.Arrays
import java.util.EnumSet
import jjoller.foxinabox.Card.CardValue
/**
* Try all combinations of five cards and find out which has the highest
* value.
* @param hand
* * A Hand of at least five cards.
* *
* *
* @param flush
* * If set to false do not look at the suit of the cards.
*/
public class FiveCardValue(hand: EnumSet<Card>, flush: Boolean = true) : Comparable<FiveCardValue> {
// private EnumSet<Card> hand;
val hand: EnumSet<Card>
val rank: Int
init {
// precondition
if (hand.size < 5)
throw IllegalArgumentException(
"the Hand contains less than five Cards.")
var bestRank = Integer.MIN_VALUE
var bestCombination: EnumSet<Card>? = null;
val numCards = hand.size
var iter = hand.iterator();
val cards = Array(numCards, { iter.next() })
//var cards = hand.toArray()
// array elements are sorted by index, starting with the lowest index.
// Card[] cards = hand.toArray(new Card[numCards]);
for (p in 0..numCards - 4 - 1) {
for (o in p + 1..numCards - 3 - 1) {
for (k in o + 1..numCards - 2 - 1) {
for (e in k + 1..numCards - 1 - 1) {
for (r in e + 1..numCards - 1) {
val c0 = cards[p]
val c1 = cards[o]
val c2 = cards[k]
val c3 = cards[e]
val c4 = cards[r]
val v0: Int
val v1: Int
val v2: Int
val v3: Int
val v4: Int
v0 = c0.value.ordinal
v1 = c1.value.ordinal
v2 = c2.value.ordinal
v3 = c3.value.ordinal
v4 = c4.value.ordinal
var rank = RANKING.rank[v0][v1][v2][v3][v4]
if (flush) {
if (isFlush(c0, c1, c2, c3, c4)) {
if (RANKING.isStraight(v0, v1, v2, v3, v4)) {
// straight flush
rank = rank - RANKING.straightRank + RANKING.straightFlushRank
} else {
// normal flush
rank = RANKING.flushRank + (rank - RANKING.minRank)
}
}
}
if (rank > bestRank) {
bestRank = rank
bestCombination = EnumSet.of(c0, c1, c2, c3, c4)
}
}
}
}
}
}
this.hand = bestCombination!!
this.rank = bestRank
}
val handValue: HandValueType
get() {
var iter = hand.iterator();
return getHandValueType(iter.next(), iter.next(), iter.next(), iter.next(), iter.next())
}
/**
* returns a positive number if this Value is better than the given
* FiveCardValue. Returns 0 if the given value is equal this value.
*/
override fun compareTo(o: FiveCardValue): Int {
return rank - o.rank
}
fun isBetterThan(o: FiveCardValue): Boolean {
return rank > o.rank
}
fun isEqual(o: FiveCardValue): Boolean {
return rank == o.rank
}
override fun toString(): String {
var s = ""
val v = handValue
val fiveCardValues = arrayOfNulls<CardValue>(5)
var i = 0
for (c in hand!!) {
fiveCardValues[i++] = c.value
}
s += v
when (v) {
FiveCardValue.HandValueType.HIGH_CARD -> s += " " + fiveCardValues[0] + " " + fiveCardValues[1] + " " + fiveCardValues[2] + " " + fiveCardValues[3] + " " + fiveCardValues[4]
FiveCardValue.HandValueType.PAIR -> s += " " + fiveCardValues[0] + " " + fiveCardValues[1] + " " + fiveCardValues[2] + " " + fiveCardValues[3] + " " + fiveCardValues[4]
FiveCardValue.HandValueType.TWO_PAIR -> s += " " + fiveCardValues[0] + " " + fiveCardValues[1] + " " + fiveCardValues[2] + " " + fiveCardValues[3] + " " + fiveCardValues[4]
FiveCardValue.HandValueType.THREE_OF_A_KIND -> s += " " + fiveCardValues[0] + " " + fiveCardValues[1] + " " + fiveCardValues[2] + " " + fiveCardValues[3] + " " + fiveCardValues[4]
FiveCardValue.HandValueType.STRAIGHT -> if (fiveCardValues[0] === CardValue.ACE && fiveCardValues[1] === CardValue.FIVE) {
s += " " + fiveCardValues[1] + " high"
} else {
s += " " + fiveCardValues[0] + " high"
}
FiveCardValue.HandValueType.FLUSH -> s += " " + fiveCardValues[0] + " " + fiveCardValues[1] + " " + fiveCardValues[2] + " " + fiveCardValues[3] + " " + fiveCardValues[4]
FiveCardValue.HandValueType.FULL_HOUSE ->
if (fiveCardValues[0] === fiveCardValues[2]) {
s += " " + fiveCardValues[0] + "s, full of " + fiveCardValues[3] + "s"
} else {
s += " " + fiveCardValues[3] + "s, full of " + fiveCardValues[0] + "s"
}
FiveCardValue.HandValueType.FOUR_OF_A_KIND ->
if (fiveCardValues[0] === fiveCardValues[1]) {
s += " " + fiveCardValues[0] + "s, " + fiveCardValues[4] + " kicker"
} else {
s += " " + fiveCardValues[1] + "s, " + fiveCardValues[0] + " kicker"
}
FiveCardValue.HandValueType.STRAIGHT_FLUSH ->
if (fiveCardValues[0] === CardValue.ACE && fiveCardValues[1] === CardValue.FIVE) {
s += " " + fiveCardValues[1] + " high"
} else {
s += " " + fiveCardValues[0] + " high"
}
}
return s
}
internal class HandValueRanking constructor() {
val rank = Array(13) { Array(13) { Array(13) { Array(13) { IntArray(13) } } } }
private var count: Int = 0
var flushRank: Int = 0
var straightRank: Int = 0
var fullHouseRank: Int = 0
var fourOfAKindRank: Int = 0
var straightFlushRank: Int = 0
var maxRank: Int = 0
var minRank: Int = 0
init {
count = Integer.MAX_VALUE / 2
maxRank = count + 9 // the number of different straight flushs
straightFlushRank = count
putFourOfAKind()
fourOfAKindRank = count
putFullHouse()
fullHouseRank = count
count -= 13 * 12 * 11 * 10 * 9
flushRank = count
count--
putStraight()
straightRank = count
putThreeOfAKind()
putTwoPair()
putPair()
putHighCard()
minRank = count
}
// private void fill() {
//
//
//
// }
private fun putFourOfAKind() {
for (p in 0..12) {
for (o in 0..12) {
if (areDifferent(p, o)) {
put(p, p, p, p, o, count--)
}
}
}
}
private fun putFullHouse() {
for (p in 0..12) {
for (o in 0..12) {
if (areDifferent(p, o)) {
put(p, p, p, o, o, count--)
}
}
}
}
private fun putStraight() {
// straight five high
for (p in 0..8) {
rank[p][p + 1][p + 2][p + 3][p + 4] = count--
}
rank[0][9][10][11][12] = count--
}
private fun putThreeOfAKind() {
for (p in 0..12) {
for (o in 0..12) {
for (k in o..12) {
if (areDifferent(p, o, k)) {
put(p, p, p, o, k, count--)
}
}
}
}
}
private fun putTwoPair() {
for (p in 0..12) {
for (o in p..12) {
for (k in 0..12) {
if (areDifferent(p, o, k)) {
put(p, p, o, o, k, count--)
}
}
}
}
}
private fun putPair() {
for (p in 0..12) {
for (o in 0..12) {
for (k in o..12) {
for (e in k..12) {
if (areDifferent(p, o, k, e)) {
put(p, p, o, k, e, count--)
}
}
}
}
}
}
private fun putHighCard() {
for (p in 0..12) {
for (o in p + 1..12) {
for (k in o + 1..12) {
for (e in k + 1..12) {
for (r in e + 1..12) {
if (areDifferent(p, o, k, e, r) && !isStraight(p, o, k, e, r)) {
put(p, o, k, e, r, count--)
}
}
}
}
}
}
}
private fun put(p: Int, o: Int, k: Int, e: Int, r: Int, count: Int) {
val i = IntArray(5)
i[0] = p
i[1] = o
i[2] = k
i[3] = e
i[4] = r
Arrays.sort(i)
rank[i[0]][i[1]][i[2]][i[3]][i[4]] = count
}
private fun areDifferent(vararg a: Int): Boolean {
val n = a.size
for (i in 0..n - 1) {
for (j in 0..n - 1) {
if (i != j) {
if (a[i] == a[j]) {
return false
}
}
}
}
return true
}
fun isPair(p: Int, o: Int, k: Int, e: Int, r: Int): Boolean {
val pairs = BooleanArray(10)
pairs[0] = p == o
pairs[1] = p == k
pairs[2] = p == e
pairs[3] = p == r
pairs[4] = o == k
pairs[5] = o == e
pairs[6] = o == r
pairs[7] = k == e
pairs[8] = k == r
pairs[9] = e == r
var result = false
for (b in pairs) {
if (b) {
result = true
break
}
}
return result
}
fun isTwoPair(p: Int, o: Int, k: Int, e: Int, r: Int): Boolean {
val pairs = BooleanArray(10)
pairs[0] = p == o
pairs[1] = p == k
pairs[2] = p == e
pairs[3] = p == r
pairs[4] = o == k
pairs[5] = o == e
pairs[6] = o == r
pairs[7] = k == e
pairs[8] = k == r
pairs[9] = e == r
var numPairs = 0
for (b in pairs) {
if (b) {
numPairs++
}
}
var result = false
if (numPairs == 2) {
result = true
}
return result
}
fun isThreeOfAKind(p: Int, o: Int, k: Int, e: Int, r: Int): Boolean {
var result = false
for (i in 0..12) {
var count = 0
if (p == i) {
count++
}
if (o == i) {
count++
}
if (k == i) {
count++
}
if (e == i) {
count++
}
if (r == i) {
count++
}
if (count == 3) {
result = true
break
}
}
return result
}
fun isFourOfAKind(p: Int, o: Int, k: Int, e: Int, r: Int): Boolean {
var result = false
for (i in 0..12) {
var count = 0
if (p == i) {
count++
}
if (o == i) {
count++
}
if (k == i) {
count++
}
if (e == i) {
count++
}
if (r == i) {
count++
}
if (count == 4) {
result = true
break
}
}
return result
}
fun isFullHouse(p: Int, o: Int, k: Int, e: Int, r: Int): Boolean {
var result: Boolean
result = p == o && o == k && k != e && e == r
result = result or (p == o) && o != k && k == e && e == r
return result
}
fun isStraight(p: Int, o: Int, k: Int, e: Int, r: Int): Boolean {
var isStraight = false
if (o - p == 1 && k - o == 1 && e - k == 1 && r - e == 1) {
isStraight = true
} else if (p == 0 && o == 9 && k == 10 && e == 11 && r == 12) {
isStraight = true
}
//
// int[] a = new int[5];
// a[0] = p;
// a[1] = o;
// a[2] = k;
// a[3] = e;
// a[4] = r;
// Arrays.sort(a);
// boolean isStraight = true;
// for (int i = 1; i < 5; i++) {
// if (a[i] - a[i - 1] != 1) {
// isStraight = false;
// break;
// }
// }
// straight ace to 5
// if (isStraight)
// log.info("is straight: " + p + " " + o + " " + k + " " + e
// + " " + r + " " + isStraight);
return isStraight
}
}
enum class HandValueType {
HIGH_CARD, PAIR, TWO_PAIR, THREE_OF_A_KIND, STRAIGHT, FLUSH, FULL_HOUSE, FOUR_OF_A_KIND, STRAIGHT_FLUSH
}
companion object {
private val RANKING = HandValueRanking()
private fun getHandValueType(c0: Card, c1: Card, c2: Card,
c3: Card, c4: Card): HandValueType {
val p: Int
val o: Int
val k: Int
val e: Int
val r: Int
p = c0.value.ordinal
o = c1.value.ordinal
k = c2.value.ordinal
e = c3.value.ordinal
r = c4.value.ordinal
val flush = isFlush(c0, c1, c2, c3, c4)
val isStraight = RANKING.isStraight(p, o, k, e, r)
if (flush && isStraight)
return HandValueType.STRAIGHT_FLUSH
if (RANKING.isFourOfAKind(p, o, k, e, r))
return HandValueType.FOUR_OF_A_KIND
if (RANKING.isFullHouse(p, o, k, e, r))
return HandValueType.FULL_HOUSE
if (flush)
return HandValueType.FLUSH
if (isStraight)
return HandValueType.STRAIGHT
if (RANKING.isThreeOfAKind(p, o, k, e, r))
return HandValueType.THREE_OF_A_KIND
if (RANKING.isTwoPair(p, o, k, e, r))
return HandValueType.TWO_PAIR
if (RANKING.isPair(p, o, k, e, r))
return HandValueType.PAIR
return HandValueType.HIGH_CARD
}
private fun isFlush(c1: Card, c2: Card, c3: Card, c4: Card, c5: Card): Boolean {
return c1.suit == c2.suit && c2.suit == c3.suit && c3.suit == c4.suit && c4.suit == c5.suit
}
}
}
| mit |
ReepicheepRed/PhotoMark-official | app/src/main/java/me/jessyan/mvparms/photomark/mvp/contract/PosterMainContract.kt | 1 | 1856 | package me.jessyan.mvparms.photomark.mvp.contract
import com.jess.arms.base.DefaultAdapter
import com.jess.arms.mvp.BaseView
import com.jess.arms.mvp.IModel
import me.jessyan.mvparms.photomark.mvp.model.entity.Banner
import me.jessyan.mvparms.photomark.mvp.model.entity.BaseJson
import me.jessyan.mvparms.photomark.mvp.model.entity.PAtt
import me.jessyan.mvparms.photomark.mvp.model.entity.PList
import rx.Observable
/**
* 通过Template生成对应页面的MVP和Dagger代码,请注意输入框中输入的名字必须相同
* 由于每个项目包结构都不一定相同,所以每生成一个文件需要自己导入import包名,可以在设置中设置自动导入包名
* 请在对应包下按以下顺序生成对应代码,Contract->Model->Presenter->Activity->Module->Component
* 因为生成Activity时,Module和Component还没生成,但是Activity中有它们的引用,所以会报错,但是不用理会
* 继续将Module和Component生成完后,编译一下项目再回到Activity,按提示修改一个方法名即可
* 如果想生成Fragment的相关文件,则将上面构建顺序中的Activity换为Fragment,并将Component中inject方法的参数改为此Fragment
*/
/**
* Created by zhiPeng.S on 2017/5/31.
*/
interface PosterMainContract {
//对于经常使用的关于UI的方法可以定义到BaseView中,如显示隐藏进度条,和显示文字消息
interface View : BaseView{
fun setAdapter(adapter: DefaultAdapter<*>)
}
//Model层定义接口,外部只需关心model返回的数据,无需关心内部细节,及是否使用缓存
interface Model : IModel{
fun obtainBanner() : Observable<BaseJson<List<Banner>>>
fun getPoster(pid: Int, update: Boolean): Observable<BaseJson<List<PList>>>
fun getPAtt(pid: Int, update: Boolean): Observable<BaseJson<List<PAtt>>>
}
} | apache-2.0 |
LordAkkarin/Beacon | core/src/main/kotlin/tv/dotstart/beacon/core/upnp/ActionExtensions.kt | 1 | 4149 | /*
* Copyright 2020 Johannes Donath <[email protected]>
* and other copyright owners as documented in the project's IP log.
*
* 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 tv.dotstart.beacon.core.upnp
import kotlinx.coroutines.future.await
import net.mm2d.upnp.Action
import tv.dotstart.beacon.core.upnp.error.*
import java.util.concurrent.CancellationException
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletionException
/**
* Provides functions which simplify the interaction with devices.
*
* @author [Johannes Donath](mailto:[email protected])
* @date 02/12/2020
*/
private const val errorCodeFieldName = "UPnPError/errorCode"
private const val errorDescriptionFieldName = "UPnPError/errorDescription"
/**
* Invokes a given UPnP operation with a given set of parameters and synchronously returns a
* converted response.
*
* @throws ActionFailedException when the action failed to execute as desired.
* @throws DeviceOutOfMemoryException when the device ran out of memory while processing the action.
* @throws HumanInterventionRequiredException when the action requires human intervention.
* @throws InvalidActionArgumentException when the given set of arguments has been rejected.
* @throws UnknownActionErrorException when an unknown error occurs.
* @throws CancellationException when the thread is interrupted while awaiting the action result.
*/
suspend operator fun <T> Action.invoke(parameters: Map<String, String?> = emptyMap(),
converter: (Map<String, String>) -> T): T {
val future = CompletableFuture<T>()
try {
this.invoke(
parameters,
onResult = actionInvocation@{
if (errorCodeFieldName in it) {
val errorDescription = it[errorDescriptionFieldName]
?.takeIf(String::isNotBlank)
?: "No additional information given"
val errorCodeStr = it[errorCodeFieldName]
val errorCode = errorCodeStr
?.toIntOrNull()
?: throw UnknownActionErrorException(
"Device responded with malformed error code \"$errorCodeStr\": $errorDescription")
val ex = when (errorCode) {
401, 602 -> InvalidActionException("Device rejected action: $errorDescription")
402, 600, 601, 605 -> InvalidActionArgumentException(
"Device rejected arguments: $errorDescription")
501 -> ActionFailedException("Device failed to perform action: $errorDescription")
603 -> DeviceOutOfMemoryException("Device ran out of memory: $errorDescription")
604 -> HumanInterventionRequiredException(
"Device requested human intervention: $errorDescription")
else -> UnknownActionErrorException(
"Device responded with unknown error code $errorCode: $errorDescription")
}
future.completeExceptionally(ex)
return@actionInvocation
}
val result = converter(it)
future.complete(result)
},
onError = future::completeExceptionally,
returnErrorResponse = true,
)
} catch (ex: Exception) {
throw UnknownActionErrorException("Unknown error occurred while invoking device action", ex)
}
return try {
future.await()
} catch (ex: CompletionException) {
val cause = ex.cause
if (cause is ActionException) {
throw cause
}
throw UnknownActionErrorException(
"Unknown error occurred while invoking device action", cause ?: ex)
}
}
| apache-2.0 |
infinum/android_dbinspector | dbinspector/src/main/kotlin/com/infinum/dbinspector/ui/databases/DatabaseInteractions.kt | 1 | 352 | package com.infinum.dbinspector.ui.databases
import com.infinum.dbinspector.domain.database.models.DatabaseDescriptor
internal data class DatabaseInteractions(
val onDelete: (DatabaseDescriptor) -> Unit,
val onRename: (DatabaseDescriptor) -> Unit,
val onCopy: (DatabaseDescriptor) -> Unit,
val onShare: (DatabaseDescriptor) -> Unit
)
| apache-2.0 |
JetBrains/anko | anko/library/static/commons/src/main/java/dialogs/AlertDialogBuilder.kt | 4 | 9394 | /*
* Copyright 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.
*/
@file:Suppress("unused")
package org.jetbrains.anko
import android.R
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.database.Cursor
import android.graphics.drawable.Drawable
import android.view.KeyEvent
import android.view.View
import android.view.ViewManager
import android.widget.ListAdapter
@Deprecated("Use AlertBuilder class instead.")
class AlertDialogBuilder(val ctx: Context) {
private var builder: AlertDialog.Builder? = AlertDialog.Builder(ctx)
/**
* Returns the [AlertDialog] instance if created.
* Returns null until the [show] function is called.
*/
var dialog: AlertDialog? = null
private set
constructor(ankoContext: AnkoContext<*>) : this(ankoContext.ctx)
fun dismiss() {
dialog?.dismiss()
}
private fun checkBuilder() {
if (builder == null) {
throw IllegalStateException("show() was already called for this AlertDialogBuilder")
}
}
/**
* Create the [AlertDialog] and display it on screen.
*
*/
fun show(): AlertDialogBuilder {
checkBuilder()
dialog = builder!!.create()
builder = null
dialog!!.show()
return this
}
/**
* Set the [title] displayed in the dialog.
*/
fun title(title: CharSequence) {
checkBuilder()
builder!!.setTitle(title)
}
/**
* Set the title using the given [title] resource id.
*/
fun title(title: Int) {
checkBuilder()
builder!!.setTitle(title)
}
/**
* Set the [message] to display.
*/
fun message(message: CharSequence) {
checkBuilder()
builder!!.setMessage(message)
}
/**
* Set the message to display using the given [message] resource id.
*/
fun message(message: Int) {
checkBuilder()
builder!!.setMessage(message)
}
/**
* Set the resource id of the [Drawable] to be used in the title.
*/
fun icon(icon: Int) {
checkBuilder()
builder!!.setIcon(icon)
}
/**
* Set the [icon] Drawable to be used in the title.
*/
fun icon(icon: Drawable) {
checkBuilder()
builder!!.setIcon(icon)
}
/**
* Set the title using the custom [view].
*/
fun customTitle(view: View) {
checkBuilder()
builder!!.setCustomTitle(view)
}
/**
* Set the title using the custom DSL view.
*/
fun customTitle(dsl: ViewManager.() -> Unit) {
checkBuilder()
val view = ctx.UI(dsl).view
builder!!.setCustomTitle(view)
}
/**
* Set a custom [view] to be the contents of the Dialog.
*/
fun customView(view: View) {
checkBuilder()
builder!!.setView(view)
}
/**
* Set a custom DSL view to be the contents of the Dialog.
*/
fun customView(dsl: ViewManager.() -> Unit) {
checkBuilder()
val view = ctx.UI(dsl).view
builder!!.setView(view)
}
/**
* Set if the dialog is cancellable.
*
* @param cancellable if true, the created dialog will be cancellable.
*/
fun cancellable(cancellable: Boolean = true) {
checkBuilder()
builder!!.setCancelable(cancellable)
}
/**
* Sets the [callback] that will be called if the dialog is canceled.
*/
fun onCancel(callback: () -> Unit) {
checkBuilder()
builder!!.setOnCancelListener { callback() }
}
/**
* Sets the [callback] that will be called if a key is dispatched to the dialog.
*/
fun onKey(callback: (keyCode: Int, e: KeyEvent) -> Boolean) {
checkBuilder()
builder!!.setOnKeyListener({ dialog, keyCode, event -> callback(keyCode, event) })
}
/**
* Set a listener to be invoked when the neutral button of the dialog is pressed.
*
* @param neutralText the text resource to display in the neutral button.
* @param callback the callback that will be called if the neutral button is pressed.
*/
fun neutralButton(neutralText: Int = R.string.ok, callback: DialogInterface.() -> Unit = { dismiss() }) {
neutralButton(ctx.getString(neutralText), callback)
}
/**
* Set a listener to be invoked when the neutral button of the dialog is pressed.
*
* @param neutralText the text to display in the neutral button.
* @param callback the callback that will be called if the neutral button is pressed.
*/
fun neutralButton(neutralText: CharSequence, callback: DialogInterface.() -> Unit = { dismiss() }) {
checkBuilder()
builder!!.setNeutralButton(neutralText, { dialog, which -> dialog.callback() })
}
/**
* Set a listener to be invoked when the positive button of the dialog is pressed.
*
* @param positiveText the text to display in the positive button.
* @param callback the callback that will be called if the positive button is pressed.
*/
fun positiveButton(positiveText: Int, callback: DialogInterface.() -> Unit) {
positiveButton(ctx.getString(positiveText), callback)
}
/**
* Set a listener to be invoked when the positive button of the dialog is pressed.
*
* @param callback the callback that will be called if the positive button is pressed.
*/
fun okButton(callback: DialogInterface.() -> Unit) {
positiveButton(ctx.getString(R.string.ok), callback)
}
/**
* Set a listener to be invoked when the positive button of the dialog is pressed.
*
* @param callback the callback that will be called if the positive button is pressed.
*/
fun yesButton(callback: DialogInterface.() -> Unit) {
positiveButton(ctx.getString(R.string.yes), callback)
}
/**
* Set a listener to be invoked when the positive button of the dialog is pressed.
*
* @param positiveText the text to display in the positive button.
* @param callback the callback that will be called if the positive button is pressed.
*/
fun positiveButton(positiveText: CharSequence, callback: DialogInterface.() -> Unit) {
checkBuilder()
builder!!.setPositiveButton(positiveText, { dialog, which -> dialog.callback() })
}
/**
* Set a listener to be invoked when the negative button of the dialog is pressed.
*
* @param negativeText the text to display in the negative button.
* @param callback the callback that will be called if the negative button is pressed.
*/
fun negativeButton(negativeText: Int, callback: DialogInterface.() -> Unit = { dismiss() }) {
negativeButton(ctx.getString(negativeText), callback)
}
/**
* Set a listener to be invoked when the negative button of the dialog is pressed.
*
* @param callback the callback that will be called if the negative button is pressed.
*/
fun cancelButton(callback: DialogInterface.() -> Unit = { dismiss() }) {
negativeButton(ctx.getString(R.string.cancel), callback)
}
/**
* Set a listener to be invoked when the negative button of the dialog is pressed.
*
* @param callback the callback that will be called if the negative button is pressed.
*/
fun noButton(callback: DialogInterface.() -> Unit = { dismiss() }) {
negativeButton(ctx.getString(R.string.no), callback)
}
/**
* Set a listener to be invoked when the negative button of the dialog is pressed.
*
* @param negativeText the text to display in the negative button.
* @param callback the callback that will be called if the negative button is pressed.
*/
fun negativeButton(negativeText: CharSequence, callback: DialogInterface.() -> Unit = { dismiss() }) {
checkBuilder()
builder!!.setNegativeButton(negativeText, { dialog, which -> dialog.callback() })
}
fun items(itemsId: Int, callback: (which: Int) -> Unit) {
items(ctx.resources!!.getTextArray(itemsId), callback)
}
fun items(items: List<CharSequence>, callback: (which: Int) -> Unit) {
items(items.toTypedArray(), callback)
}
fun items(items: Array<CharSequence>, callback: (which: Int) -> Unit) {
checkBuilder()
builder!!.setItems(items, { dialog, which -> callback(which) })
}
fun adapter(adapter: ListAdapter, callback: (which: Int) -> Unit) {
checkBuilder()
builder!!.setAdapter(adapter, { dialog, which -> callback(which) })
}
fun adapter(cursor: Cursor, labelColumn: String, callback: (which: Int) -> Unit) {
checkBuilder()
builder!!.setCursor(cursor, { dialog, which -> callback(which) }, labelColumn)
}
}
| apache-2.0 |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/camera_type/AddCameraType.kt | 1 | 1101 | package de.westnordost.streetcomplete.quests.camera_type
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.CITIZEN
class AddCameraType : OsmFilterQuestType<CameraType>() {
override val elementFilter = """
nodes with
surveillance:type = camera
and surveillance ~ public|outdoor|traffic
and !camera:type
"""
override val commitMessage = "Add camera type"
override val wikiLink = "Tag:surveillance:type"
override val icon = R.drawable.ic_quest_surveillance_camera
override val questTypeAchievements = listOf(CITIZEN)
override fun getTitle(tags: Map<String, String>) = R.string.quest_camera_type_title
override fun createForm() = AddCameraTypeForm()
override fun applyAnswerTo(answer: CameraType, changes: StringMapChangesBuilder) {
changes.add("camera:type", answer.osmValue)
}
}
| gpl-3.0 |
sybila/biodivine-ctl | src/main/java/com/github/sybila/biodivine/YamlHelper.kt | 1 | 1549 | package com.github.sybila.biodivine
/*
fun File.toYamlMap(): YamlMap {
return YamlMap(Yaml().load(this.inputStream()) as Map<*,*>)
}
fun String.toYamlMap(): YamlMap {
return YamlMap(Yaml().load(this) as Map<*, *>)
}
class YamlMap internal constructor(private val data: Map<*,*>) {
fun getString(key: String, default: String): String {
return data[key] as String? ?: default
}
fun getAny(key: String): Any? {
return data[key]
}
fun getString(key: String): String? {
return data[key] as String?
}
fun getInt(key: String, default: Int): Int {
return data[key] as Int? ?: default
}
fun getBoolean(key: String, default: Boolean): Boolean {
return data[key] as Boolean? ?: default
}
fun getMap(key: String): YamlMap {
return YamlMap(data[key] as Map<*,*>? ?: mapOf<Any,Any>())
}
fun getFile(key: String): File? {
return data[key]?.run { File(this as String) }
}
fun getMapList(key: String): List<YamlMap> {
val list = data[key] as List<*>? ?: listOf<Any>()
return list.map { YamlMap(it as Map<*, *>) }
}
fun getStringList(key: String): List<String> {
val list = data[key] as List<*>? ?: listOf<Any>()
return list.map { it.toString() }
}
fun getLogLevel(key: String, default: Level): Level {
val level = data[key] as String?
return level?.toLogLevel() ?: default
}
override fun toString(): String {
return Yaml().dump(this.data)
}
}*/ | gpl-3.0 |
shkschneider/android_Skeleton | core/src/main/kotlin/me/shkschneider/skeleton/ui/widget/AutoImageViewHeight.kt | 1 | 947 | package me.shkschneider.skeleton.ui.widget
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.appcompat.widget.AppCompatImageView
// <http://stackoverflow.com/a/12283909>
class AutoImageViewHeight : AppCompatImageView {
var ratio = 1.1.toFloat()
constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : super(context, attrs, defStyleAttr)
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
drawable?.let { drawable ->
val height = View.MeasureSpec.getSize(heightMeasureSpec)
val width = Math.ceil((height.toFloat() * drawable.intrinsicHeight.toFloat() / drawable.intrinsicWidth.toFloat()).toDouble()).toInt()
setMeasuredDimension((ratio * width).toInt(), (ratio * height).toInt())
} ?: run {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
}
}
| apache-2.0 |
wordpress-mobile/WordPress-Stores-Android | fluxc/src/main/java/org/wordpress/android/fluxc/action/EditorThemeAction.kt | 2 | 437 | package org.wordpress.android.fluxc.action
import org.wordpress.android.fluxc.annotations.Action
import org.wordpress.android.fluxc.annotations.ActionEnum
import org.wordpress.android.fluxc.annotations.action.IAction
import org.wordpress.android.fluxc.store.EditorThemeStore.FetchEditorThemePayload
@ActionEnum
enum class EditorThemeAction : IAction {
@Action(payloadType = FetchEditorThemePayload::class)
FETCH_EDITOR_THEME
}
| gpl-2.0 |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/extensions/FloatingActionButton.kt | 1 | 1020 | package com.boardgamegeek.extensions
import android.annotation.TargetApi
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Build
import com.google.android.material.floatingactionbutton.FloatingActionButton
fun FloatingActionButton.colorize(color: Int): Boolean {
val colorStateList = ColorStateList.valueOf(color)
if (color != Color.TRANSPARENT && backgroundTintList != colorStateList) {
backgroundTintList = colorStateList
colorImageTint(color)
return true
}
return false
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private fun FloatingActionButton.colorImageTint(backgroundColor: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
imageTintList = ColorStateList.valueOf(
if (backgroundColor.isColorDark()) {
Color.WHITE
} else {
Color.BLACK
}
)
}
}
fun FloatingActionButton.ensureShown() {
postDelayed({ show() }, 2000)
}
| gpl-3.0 |
perseacado/feedback-ui | feedback-ui-slack/src/main/java/com/github/perseacado/feedbackui/slack/SlackConfigurationProperties.kt | 1 | 362 | package com.github.perseacado.feedbackui.slack
import org.springframework.boot.context.properties.ConfigurationProperties
/**
* @author Marco Eigletsberger, 24.06.16.
*/
@ConfigurationProperties(prefix = "feedback-ui.slack")
class SlackConfigurationProperties {
var token: String? = null
var username: String? = null
var channel: String? = null
} | mit |
Kotlin/kotlinx.serialization | formats/json-tests/commonTest/src/kotlinx/serialization/features/SealedPolymorphismTest.kt | 1 | 1671 | /*
* Copyright 2017-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.features
import kotlinx.serialization.*
import kotlinx.serialization.json.Json
import kotlinx.serialization.modules.*
import kotlinx.serialization.test.assertStringFormAndRestored
import kotlin.test.Test
class SealedPolymorphismTest {
@Serializable
data class FooHolder(
val someMetadata: Int,
val payload: List<@Polymorphic Foo>
)
@Serializable
@SerialName("Foo")
sealed class Foo {
@Serializable
@SerialName("Bar")
data class Bar(val bar: Int) : Foo()
@Serializable
@SerialName("Baz")
data class Baz(val baz: String) : Foo()
}
val sealedModule = SerializersModule {
polymorphic(Foo::class) {
subclass(Foo.Bar.serializer())
subclass(Foo.Baz.serializer())
}
}
val json = Json { serializersModule = sealedModule }
@Test
fun testSaveSealedClassesList() {
assertStringFormAndRestored(
"""{"someMetadata":42,"payload":[
|{"type":"Bar","bar":1},
|{"type":"Baz","baz":"2"}]}""".trimMargin().replace("\n", ""),
FooHolder(42, listOf(Foo.Bar(1), Foo.Baz("2"))),
FooHolder.serializer(),
json,
printResult = true
)
}
@Test
fun testCanSerializeSealedClassPolymorphicallyOnTopLevel() {
assertStringFormAndRestored(
"""{"type":"Bar","bar":1}""",
Foo.Bar(1),
PolymorphicSerializer(Foo::class),
json
)
}
}
| apache-2.0 |
Nearsoft/nearbooks-android | app/src/main/java/com/nearsoft/nearbooks/util/ViewUtil.kt | 2 | 9449 | package com.nearsoft.nearbooks.util
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.databinding.ViewDataBinding
import android.graphics.Bitmap
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.os.Build
import android.support.design.widget.Snackbar
import android.support.v4.content.ContextCompat
import android.support.v7.graphics.Palette
import android.support.v7.view.menu.ActionMenuItemView
import android.support.v7.widget.ActionMenuView
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.Toast
import com.nearsoft.nearbooks.R
import com.nearsoft.nearbooks.view.helpers.ColorsWrapper
import com.squareup.picasso.Callback
import com.squareup.picasso.Picasso
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.io.IOException
import java.util.*
/**
* Utilities related with views.
* Created by epool on 1/8/16.
*/
object ViewUtil {
fun loadBitmapFromUrlImage(context: Context,
url: String): Observable<Bitmap> {
return Observable.create { subscriber ->
try {
val bitmap = Picasso.with(context).load(url).get()
subscriber.onNext(bitmap)
subscriber.onCompleted()
} catch (e: IOException) {
e.printStackTrace()
subscriber.onError(e)
}
}
}
fun getPaletteFromUrlImage(context: Context, url: String): Observable<Palette> {
return loadBitmapFromUrlImage(context, url).map { Palette.from(it).generate() }
}
fun getColorsWrapperFromUrlImage(context: Context, url: String): Observable<ColorsWrapper> {
return getPaletteFromUrlImage(context, url).map {
val defaultColor = ContextCompat.getColor(context, R.color.colorPrimary)
ViewUtil.getVibrantPriorityColorSwatchPair(it, defaultColor)
}
}
fun loadImageFromUrl(imageView: ImageView,
url: String): Observable<ColorsWrapper> {
val context = imageView.context
return Observable.create { subscriber ->
val requestCreator = Picasso.with(context).load(url)
requestCreator.placeholder(R.drawable.ic_launcher)
requestCreator.error(R.drawable.ic_launcher)
requestCreator.into(imageView, object : Callback {
override fun onSuccess() {
if (subscriber.isUnsubscribed) return
ViewUtil.getColorsWrapperFromUrlImage(context, url).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe { colorsWrapper ->
subscriber.onNext(colorsWrapper)
subscriber.onCompleted()
}
}
override fun onError() {
subscriber.onCompleted()
}
})
}
}
fun getVibrantPriorityColorSwatchPair(
palette: Palette?, defaultColor: Int): ColorsWrapper? {
if (palette == null) return null
if (palette.vibrantSwatch != null) {
return ColorsWrapper(palette.getVibrantColor(defaultColor),
palette.vibrantSwatch!!)
} else if (palette.lightVibrantSwatch != null) {
return ColorsWrapper(palette.getLightVibrantColor(defaultColor),
palette.lightVibrantSwatch!!)
} else if (palette.darkVibrantSwatch != null) {
return ColorsWrapper(palette.getDarkVibrantColor(defaultColor),
palette.darkVibrantSwatch!!)
} else if (palette.mutedSwatch != null) {
return ColorsWrapper(palette.getMutedColor(defaultColor),
palette.mutedSwatch!!)
} else if (palette.lightMutedSwatch != null) {
return ColorsWrapper(palette.getLightMutedColor(defaultColor),
palette.lightMutedSwatch!!)
} else if (palette.darkMutedSwatch != null) {
return ColorsWrapper(palette.getDarkMutedColor(defaultColor),
palette.darkMutedSwatch!!)
}
return null
}
fun showSnackbarMessage(viewDataBinding: ViewDataBinding, message: String): Snackbar {
val snackbar = Snackbar.make(viewDataBinding.root, message, Snackbar.LENGTH_LONG)
snackbar.show()
return snackbar
}
fun showToastMessage(context: Context, message: String): Toast {
val toast = Toast.makeText(context, message, Toast.LENGTH_LONG)
toast.show()
return toast
}
fun showToastMessage(context: Context, messageRes: Int, vararg formatArgs: Any): Toast {
val toast = Toast.makeText(context, context.getString(messageRes, *formatArgs), Toast.LENGTH_LONG)
toast.show()
return toast
}
object Toolbar {
/**
* Use this method to colorize toolbar icons to the desired target color
* @param toolbarView toolbar view being colored
* *
* @param toolbarIconsColor the target color of toolbar icons
* *
* @param activity reference to activity needed to register observers
*/
fun colorizeToolbar(toolbarView: android.support.v7.widget.Toolbar,
toolbarIconsColor: Int, activity: Activity) {
val colorFilter = PorterDuffColorFilter(toolbarIconsColor, PorterDuff.Mode.MULTIPLY)
for (i in 0..toolbarView.childCount - 1) {
val v = toolbarView.getChildAt(i)
//Step 1 : Changing the color of back button (or open drawer button).
if (v is ImageButton) {
//Action Bar back button
v.drawable.colorFilter = colorFilter
}
if (v is ActionMenuView) {
for (j in 0..v.childCount - 1) {
//Step 2: Changing the color of any ActionMenuViews - icons that
//are not back button, nor text, nor overflow menu icon.
val innerView = v.getChildAt(j)
if (innerView is ActionMenuItemView) {
val drawablesCount = innerView.compoundDrawables.size
for (k in 0..drawablesCount - 1) {
if (innerView.compoundDrawables[k] != null) {
val finalK = k
//Important to set the color filter in seperate thread,
//by adding it to the message queue
//Won't work otherwise.
innerView.post { innerView.compoundDrawables[finalK].colorFilter = colorFilter }
}
}
}
}
}
//Step 3: Changing the color of title and subtitle.
toolbarView.setTitleTextColor(toolbarIconsColor)
toolbarView.setSubtitleTextColor(toolbarIconsColor)
//Step 4: Changing the color of the Overflow Menu icon.
setOverflowButtonColor(activity, colorFilter)
}
}
/**
* It's important to set overflowDescription attribute in styles, so we can grab the
* reference to the overflow icon. Check: res/values/styles.xml
* @param activity Activity where is called.
* *
* @param colorFilter Color to be set.
*/
private fun setOverflowButtonColor(activity: Activity,
colorFilter: PorterDuffColorFilter) {
@SuppressLint("PrivateResource")
val overflowDescription = activity.getString(R.string.abc_action_menu_overflow_description)
val decorView = activity.window.decorView as ViewGroup
val viewTreeObserver = decorView.viewTreeObserver
viewTreeObserver.addOnGlobalLayoutListener(
object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
val outViews = ArrayList<View>()
decorView.findViewsWithText(outViews, overflowDescription,
View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION)
if (outViews.isEmpty()) return
val overflow = outViews[0] as ImageView
overflow.colorFilter = colorFilter
removeOnGlobalLayoutListener(decorView, this)
}
})
}
@SuppressWarnings("deprecation")
private fun removeOnGlobalLayoutListener(v: View,
listener: ViewTreeObserver.OnGlobalLayoutListener) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
v.viewTreeObserver.removeGlobalOnLayoutListener(listener)
} else {
v.viewTreeObserver.removeOnGlobalLayoutListener(listener)
}
}
}
}
| mit |
Kotlin/kotlinx.serialization | formats/json/jvmMain/src/kotlinx/serialization/json/internal/JvmJsonStreams.kt | 1 | 9388 | package kotlinx.serialization.json.internal
import java.io.InputStream
import java.io.OutputStream
import java.nio.charset.Charset
internal class JsonToJavaStreamWriter(private val stream: OutputStream) : JsonWriter {
private val buffer = ByteArrayPool.take()
private var charArray = CharArrayPool.take()
private var indexInBuffer: Int = 0
override fun writeLong(value: Long) {
write(value.toString())
}
override fun writeChar(char: Char) {
writeUtf8CodePoint(char.code)
}
override fun write(text: String) {
val length = text.length
ensureTotalCapacity(0, length)
text.toCharArray(charArray, 0, 0, length)
writeUtf8(charArray, length)
}
override fun writeQuoted(text: String) {
ensureTotalCapacity(0, text.length + 2)
val arr = charArray
arr[0] = '"'
val length = text.length
text.toCharArray(arr, 1, 0, length)
for (i in 1 until 1 + length) {
val ch = arr[i].code
// Do we have unescaped symbols?
if (ch < ESCAPE_MARKERS.size && ESCAPE_MARKERS[ch] != 0.toByte()) {
// Go to slow path
return appendStringSlowPath(i, text)
}
}
// Update the state
// Capacity is not ensured because we didn't hit the slow path and thus guessed it properly in the beginning
arr[length + 1] = '"'
writeUtf8(arr, length + 2)
flush()
}
private fun appendStringSlowPath(currentSize: Int, string: String) {
var sz = currentSize
for (i in currentSize - 1 until string.length) {
/*
* We ar already on slow path and haven't guessed the capacity properly.
* Reserve +2 for backslash-escaped symbols on each iteration
*/
sz = ensureTotalCapacity(sz, 2)
val ch = string[i].code
// Do we have unescaped symbols?
if (ch < ESCAPE_MARKERS.size) {
/*
* Escape markers are populated for backslash-escaped symbols.
* E.g. ESCAPE_MARKERS['\b'] == 'b'.toByte()
* Everything else is populated with either zeros (no escapes)
* or ones (unicode escape)
*/
when (val marker = ESCAPE_MARKERS[ch]) {
0.toByte() -> {
charArray[sz++] = ch.toChar()
}
1.toByte() -> {
val escapedString = ESCAPE_STRINGS[ch]!!
sz = ensureTotalCapacity(sz, escapedString.length)
escapedString.toCharArray(charArray, sz, 0, escapedString.length)
sz += escapedString.length
}
else -> {
charArray[sz] = '\\'
charArray[sz + 1] = marker.toInt().toChar()
sz += 2
}
}
} else {
charArray[sz++] = ch.toChar()
}
}
ensureTotalCapacity(sz, 1)
charArray[sz++] = '"'
writeUtf8(charArray, sz)
flush()
}
private fun ensureTotalCapacity(oldSize: Int, additional: Int): Int {
val newSize = oldSize + additional
if (charArray.size <= newSize) {
charArray = charArray.copyOf(newSize.coerceAtLeast(oldSize * 2))
}
return oldSize
}
override fun release() {
flush()
CharArrayPool.release(charArray)
ByteArrayPool.release(buffer)
}
private fun flush() {
stream.write(buffer, 0, indexInBuffer)
indexInBuffer = 0
}
@Suppress("NOTHING_TO_INLINE")
// ! you should never ask for more than the buffer size
private inline fun ensure(bytesCount: Int) {
if (rest() < bytesCount) {
flush()
}
}
@Suppress("NOTHING_TO_INLINE")
// ! you should never ask for more than the buffer size
private inline fun write(byte: Int) {
buffer[indexInBuffer++] = byte.toByte()
}
@Suppress("NOTHING_TO_INLINE")
private inline fun rest(): Int {
return buffer.size - indexInBuffer
}
/*
Sources taken from okio library with minor changes, see https://github.com/square/okio
*/
private fun writeUtf8(string: CharArray, count: Int) {
require(count >= 0) { "count < 0" }
require(count <= string.size) { "count > string.length: $count > ${string.size}" }
// Transcode a UTF-16 Java String to UTF-8 bytes.
var i = 0
while (i < count) {
var c = string[i].code
when {
c < 0x80 -> {
// Emit a 7-bit character with 1 byte.
ensure(1)
write(c) // 0xxxxxxx
i++
val runLimit = minOf(count, i + rest())
// Fast-path contiguous runs of ASCII characters. This is ugly, but yields a ~4x performance
// improvement over independent calls to writeByte().
while (i < runLimit) {
c = string[i].code
if (c >= 0x80) break
write(c) // 0xxxxxxx
i++
}
}
c < 0x800 -> {
// Emit a 11-bit character with 2 bytes.
ensure(2)
write(c shr 6 or 0xc0) // 110xxxxx
write(c and 0x3f or 0x80) // 10xxxxxx
i++
}
c < 0xd800 || c > 0xdfff -> {
// Emit a 16-bit character with 3 bytes.
ensure(3)
write(c shr 12 or 0xe0) // 1110xxxx
write(c shr 6 and 0x3f or 0x80) // 10xxxxxx
write(c and 0x3f or 0x80) // 10xxxxxx
i++
}
else -> {
// c is a surrogate. Make sure it is a high surrogate & that its successor is a low
// surrogate. If not, the UTF-16 is invalid, in which case we emit a replacement
// character.
val low = (if (i + 1 < count) string[i + 1].code else 0)
if (c > 0xdbff || low !in 0xdc00..0xdfff) {
ensure(1)
write('?'.code)
i++
} else {
// UTF-16 high surrogate: 110110xxxxxxxxxx (10 bits)
// UTF-16 low surrogate: 110111yyyyyyyyyy (10 bits)
// Unicode code point: 00010000000000000000 + xxxxxxxxxxyyyyyyyyyy (21 bits)
val codePoint = 0x010000 + (c and 0x03ff shl 10 or (low and 0x03ff))
// Emit a 21-bit character with 4 bytes.
ensure(4)
write(codePoint shr 18 or 0xf0) // 11110xxx
write(codePoint shr 12 and 0x3f or 0x80) // 10xxxxxx
write(codePoint shr 6 and 0x3f or 0x80) // 10xxyyyy
write(codePoint and 0x3f or 0x80) // 10yyyyyy
i += 2
}
}
}
}
}
/*
Sources taken from okio library with minor changes, see https://github.com/square/okio
*/
private fun writeUtf8CodePoint(codePoint: Int) {
when {
codePoint < 0x80 -> {
// Emit a 7-bit code point with 1 byte.
ensure(1)
write(codePoint)
}
codePoint < 0x800 -> {
// Emit a 11-bit code point with 2 bytes.
ensure(2)
write(codePoint shr 6 or 0xc0) // 110xxxxx
write(codePoint and 0x3f or 0x80) // 10xxxxxx
}
codePoint in 0xd800..0xdfff -> {
// Emit a replacement character for a partial surrogate.
ensure(1)
write('?'.code)
}
codePoint < 0x10000 -> {
// Emit a 16-bit code point with 3 bytes.
ensure(3)
write(codePoint shr 12 or 0xe0) // 1110xxxx
write(codePoint shr 6 and 0x3f or 0x80) // 10xxxxxx
write(codePoint and 0x3f or 0x80) // 10xxxxxx
}
codePoint <= 0x10ffff -> {
// Emit a 21-bit code point with 4 bytes.
ensure(4)
write(codePoint shr 18 or 0xf0) // 11110xxx
write(codePoint shr 12 and 0x3f or 0x80) // 10xxxxxx
write(codePoint shr 6 and 0x3f or 0x80) // 10xxyyyy
write(codePoint and 0x3f or 0x80) // 10yyyyyy
}
else -> {
throw JsonEncodingException("Unexpected code point: $codePoint")
}
}
}
}
internal class JavaStreamSerialReader(
stream: InputStream,
charset: Charset = Charsets.UTF_8
) : SerialReader {
private val reader = stream.reader(charset)
override fun read(buffer: CharArray, bufferOffset: Int, count: Int): Int {
return reader.read(buffer, bufferOffset, count)
}
}
| apache-2.0 |
davidwhitman/changelogs | app/src/main/java/com/thunderclouddev/changelogs/ui/comparator/SizeComparator.kt | 1 | 956 | /*
* Copyright (c) 2017.
* Distributed under the GNU GPLv3 by David Whitman.
* https://www.gnu.org/licenses/gpl-3.0.en.html
*
* This source code is made available to help others learn. Please don't clone my app.
*/
package com.thunderclouddev.changelogs.ui.comparator
import java.util.*
/**
* @author Thundercloud Dev on 6/9/2016.
*/
//class SizeComparator : Comparator<AppInfo> {
// companion object {
// // Performance, yo
// private val recentlyUpdatedComparator = RecentlyUpdatedComparator()
// }
//
// override fun compare(lhs: AppInfo?, rhs: AppInfo?): Int {
// val leftMC = MostCorrectAppInfo(lhs!!)
// val rightMC = MostCorrectAppInfo(rhs!!)
// val updateResult = rightMC.installSize.compareTo(leftMC.installSize)
//
// if (updateResult != 0) {
// return updateResult
// } else {
// return recentlyUpdatedComparator.compare(lhs, rhs)
// }
// }
//} | gpl-3.0 |
minjaesong/terran-basic-java-vm | src/net/torvald/terranvm/runtime/compiler/cflat/NewCompiler.kt | 1 | 22890 | package net.torvald.terranvm.runtime.compiler.cflat
import net.torvald.terranvm.runtime.*
import net.torvald.terranvm.runtime.compiler.cflat.Cflat.ExpressionType.*
import net.torvald.terrarum.virtualcomputer.terranvmadapter.printASM
import java.lang.StringBuilder
import kotlin.UnsupportedOperationException
import kotlin.collections.HashMap
/**
* Compilation step:
*
* User Input -> Tree Representation -> IR1 (preorder?) -> IR2 (postorder) -> ASM => Fed into Assembler
*
* Reference:
* - *Compiler Design: Virtual Machines*, Reinhard Wilhelm and Helmut Seidi, 2011, ISBN 3642149081
*/
object NewCompiler {
val testProgram = """
int c;
int d;
int shit;
int plac;
int e_ho;
int lder;
int r;
//c = (3 + 4) * (7 - 2);
c = -3;
if (c > 42) {
c = 0;
}
else {
c = 1;
}
void newfunction(int k) {
dosomething(k, -k);
}
//d = "Hello, world!";
float dd;
""".trimIndent()
// TODO add issues here
// lexer and parser goes here //
/*
/**
* An example of (3 + 4) * (7 - 2).
*
* This is also precisely what **IR1** is supposed to be.
* Invoke this "Function" and you will get a string, which is **IR2**.
* IR2 is
*/
val TEST_CODE: () -> CodeR = { { MUL(0, { ADD(0, { LIT(0, 3) }, { LIT(0, 4) }) }, { SUB(0, { LIT(0, 7) }, { LIT(0, 2) }) }) } }
/**
* If (3) 7200 Else 5415; 3 + 4; 7 * 2
*/
val TEST_CODE2 = {
{
IFELSE(1,
{ LIT(1, 3) }, // cond
{ LIT(2, 7200) }, // true
{ LIT(4, 5415) } // false
)
} bind { // AM I >>=ing right ?
ADD(6, { LIT(6, 3) }, { LIT(6, 4) })
} bind {
MUL(7, { LIT(7, 7) }, { LIT(7, 2) })
}
}
/**
* var a = (b + (b * c)); // a |> 5; b |> 6; c |> 7
*
* Expected output: loadc 6; load; loadc 6; load; ... -- as per our reference book
*/
val TEST_VARS = {
// function for variable address
val aTable = hashMapOf("a" to 5, "b" to 6, "c" to 7)
val aenv: Rho = { name -> aTable[name]!! }
// the actual code
{
ASSIGN(1, {
VAR_L(1, "a", aenv)
}, {
ADD(1, {
VAR_R(1, "b", aenv)
}, {
MUL(1, {
VAR_R(1, "b", aenv)
}, {
VAR_R(1, "c", aenv)
})
})
}, aenv
)
}
}*/
/** Shitty >>= (toilet plunger) */
private infix fun (CodeR).bind(other: CodeR) = sequenceOf(this, other)
private infix fun (Sequence<CodeR>).bind(other: CodeR) = this + other
// TREE TO IR1
fun toIR1(tree: Cflat.SyntaxTreeNode): Pair<CodeR, Rho> {
//val parentCode: Sequence<CodeR> = sequenceOf( { "" } )
val variableAddr = HashMap<String, Int>()
var varCnt = 0
fun String.toVarName() = "$$this"
val aenv: Rho = { name ->
if (!variableAddr.containsKey(name.toVarName()))
throw UnresolvedReference("No such variable defined: $name")
//println("Fetch var ${name.toVarName()} -> ${variableAddr[name.toVarName()]}")
variableAddr[name.toVarName()]!!
}
fun addvar(name: String, ln: Int) {
if (!variableAddr.containsKey(name.toVarName())) {
variableAddr[name.toVarName()] = varCnt + 256 // index starts at 100h
varCnt++
}
//println("Add var ${name.toVarName()} -> ${variableAddr[name.toVarName()]}")
}
// TODO recursion is a key
// SyntaxTreeNode has its own traverse function, but our traverse is nothing trivial
// so let's just leave it this way.
// Traverse order: Self -> Arguments (e1, e2, ...) -> Statements (s)
fun traverse1(node: Cflat.SyntaxTreeNode) : CodeR {
val l = node.lineNumber
// termination conditions //
if (node.expressionType == LITERAL_LEAF) {
return when (node.returnType!!) {
Cflat.ReturnType.INT -> { CodeR { LIT(l, node.literalValue as Int) }}
Cflat.ReturnType.FLOAT -> { CodeR { LIT(l, node.literalValue as Float) }}
Cflat.ReturnType.DATABASE -> { CodeR { LIT(l, node.literalValue as String) }}
else -> { CodeR { _REM(l, "Unsupported literal with type: ${node.returnType}") }}
}
}
else if (node.expressionType == VARIABLE_READ) {
addvar(node.name!!, l)
return CodeR { VAR_R(l, node.name!!, aenv) }
}
else if (node.expressionType == VARIABLE_WRITE) {
if (!variableAddr.containsKey(node.name!!)) {
throw UnresolvedReference("No such variable defined: ${node.name!!}")
}
return CodeR { VAR_L(l, node.name!!, aenv) }
}
// recursion conditions //
else {
return if (node.expressionType == FUNCTION_CALL) {
when (node.name) {
"+" -> { CodeR { ADD(l, traverse1(node.arguments[0]), traverse1(node.arguments[1])) }}
"-" -> { CodeR { SUB(l, traverse1(node.arguments[0]), traverse1(node.arguments[1])) }}
"*" -> { CodeR { MUL(l, traverse1(node.arguments[0]), traverse1(node.arguments[1])) }}
"/" -> { CodeR { DIV(l, traverse1(node.arguments[0]), traverse1(node.arguments[1])) }}
"=" -> { CodeR { ASSIGN(l, CodeL { VAR_L(l, node.arguments[0].name!!, aenv) }, traverse1(node.arguments[1]), aenv) }}
"==" -> { CodeR { EQU(l, traverse1(node.arguments[0]), traverse1(node.arguments[1])) }}
"!=" -> { CodeR { NEQ(l, traverse1(node.arguments[0]), traverse1(node.arguments[1])) }}
">=" -> { CodeR { GEQ(l, traverse1(node.arguments[0]), traverse1(node.arguments[1])) }}
"<=" -> { CodeR { LEQ(l, traverse1(node.arguments[0]), traverse1(node.arguments[1])) }}
">" -> { CodeR { GT(l, traverse1(node.arguments[0]), traverse1(node.arguments[1])) }}
"<" -> { CodeR { LS(l, traverse1(node.arguments[0]), traverse1(node.arguments[1])) }}
"if" -> { CodeR { IF(l, traverse1(node.arguments[0]), traverse1(node.statements[0])) }}
"ifelse" -> { CodeR { IFELSE(l, traverse1(node.arguments[0]), traverse1(node.statements[0]), traverse1(node.statements[1])) }}
"#_unaryminus" -> { CodeR { NEG(l, traverse1(node.arguments[0])) } }
// calling arbitrary function
else -> {
// see p.42 ?
val finalCmd = StringBuilder()
finalCmd.append(ALLOCATSTACK(node.arguments.size))
// push CodeR args passing into the stack, reversed order
node.arguments.reversed().map { traverse1(it) }.forEach {
finalCmd.append(PUSH(it))
}
finalCmd.append(MARKFUNCCALL())
finalCmd.append(CALLFUNC(node.arguments.size))
// TODO slide
CodeR { finalCmd.toString() } // we're doing this because I couldn't build func composition
}
}
}
else if (node.expressionType == INTERNAL_FUNCTION_CALL) {
when (node.name) {
"#_declarevar" -> {
addvar(node.arguments[0].literalValue as String, l)
return CodeR { NEWVAR(l, node.arguments[1].literalValue as String, node.arguments[0].literalValue as String) }
}
else -> { return CodeR { _REM(l, "Unknown internal function: ${node.name}") }}
}
}
else if (node.name == Cflat.rootNodeName) {
return CodeR { _PARSE_HEAD(node.statements.map { traverse1(it) }) }
}
/*else if (node.expressionType == FUNCTION_DEF) {
}*/
else {
throw UnsupportedOperationException("Unsupported node:\n[NODE START]\n$node\n[NODE END]")
}
}
}
return traverse1(tree) to aenv
}
// These are the definition of IR1. Invoke this "function" and string will come out, which is IR2.
// l: Int means Line Number
// EXPRESSIONS
// Think these as:
// Proper impl of the func "CodeR" requires "Operation" and "E"s; it'd be easier if we're on Haskell, but to
// make proper impl in the Kotlin, the code gets too long.
// Think of these as "spilled" version of the proper one.
// Function "CodeR" returns IR2, and so does these spilled versions.
private fun _REM(l: Int, message: String): IR2 = "\nREM Ln$l : ${message.replace('\n', '$')};\n"
private fun _PARSE_HEAD(e: List<CodeR>): IR2 = e.fold("") { acc, it -> acc + it.invoke() } + "HALT;\n"
/** e1 ; e2 ; add ; */
fun ADD(l: Int, e1: CodeR, e2: CodeR): IR2 = e1() + e2() + "ADD;\n"
fun SUB(l: Int, e1: CodeR, e2: CodeR) = e1() + e2() + "SUB;\n"
fun MUL(l: Int, e1: CodeR, e2: CodeR) = e1() + e2() + "MUL;\n"
fun DIV(l: Int, e1: CodeR, e2: CodeR) = e1() + e2() + "DIV;\n"
fun NEG(l: Int, e: CodeR) = e() + "NEG;\n"
/** loadconst ; literal ; */
fun LIT(l: Int, e: Int) = "LOADCONST ${e.toHexString()};-_-_-_ Literal\n" // always ends with 'h'
fun LIT(l: Int, e: Float) = "LOADCONST ${e}f;-_-_-_ Literal\n" // always ends with 'f'
fun LIT(l: Int, e: String) = LIT(l, e.toByteArray(Charsets.UTF_8))
fun LIT(l: Int, e: ByteArray) = "LOADDATA ${e.fold("") { acc, byte -> acc + "${byte.to2Hex()} " }};"
/** address(int) ; value(word) ; store ; */
fun ASSIGN(l: Int, e1: CodeL, e2: CodeR, aenv: Rho) = e2() + e1(aenv) + "STORE;\n"
/** ( address -- value stored in that address ) */ // this is Forth stack notation
fun VAR_R(l: Int, varname: String, aenv: Rho) = "LOADCONST ${aenv(varname).toHexString()}; LOAD;-_-_-_ Read from variable\n" // NOT using 8hexstring is deliberate
/** ( address -- ); memory gets changed */
fun VAR_L(l: Int, varname: String, aenv: Rho) = "LOADCONST ${aenv(varname).toHexString()};-_-_-_ Write to variable, if following command is STORE\n" // NOT using 8hexstring is deliberate; no need for extra store; handled by ASSIGN
fun NEWVAR(l: Int, type: String, varname: String) = "NEWVAR ${type.toUpperCase()} $varname;\n"
fun JUMP(l: Int, newPC: CodeR) = "JUMP $newPC;\n"
// FOR NON-COMPARISON OPS
fun JUMPZ(l: Int, newPC: CodeR) = "JUMPZ $newPC;\n"
fun JUMPNZ(l: Int, newPC: CodeR) = "JUMPNZ $newPC;\n"
// FOR COMPARISON OPS ONLY !!
fun JUMPFALSE(l: Int, newPC: CodeR) = "JUMPFALSE $newPC;\n" // zero means false
fun IF(l: Int, cond: CodeR, invokeTrue: CodeR) =
cond() + "JUMPFALSE ${labelFalse(l, cond)};\n" + invokeTrue() + "LABEL ${labelFalse(l, cond)};\n"
fun IFELSE(l: Int, cond: CodeR, invokeTrue: CodeR, invokeFalse: CodeR) =
cond() + "JUMPFALSE ${labelFalse(l, cond)};\n" + invokeTrue() + "JUMP ${labelThen(l, cond)};\n" +
"LABEL ${labelFalse(l, cond)};\n" + invokeFalse() + "LABEL ${labelThen(l, cond)};\n"
fun WHILE(l: Int, cond: CodeR, invokeWhile: CodeR) =
"LABEL ${labelWhile(l, cond)};\n" +
cond() + "JUMPFALSE ${labelThen(l, cond)};\n" +
invokeWhile() + "JUMP ${labelWhile(l, cond)};\n" +
"LABEL ${labelThen(l, cond)};\n"
fun EQU(l: Int, e1: CodeR, e2: CodeR) = e1() + e2() + "ISEQUAL;\n"
fun NEQ(l: Int, e1: CodeR, e2: CodeR) = e1() + e2() + "ISNOTEQUAL;\n"
fun LEQ(l: Int, e1: CodeR, e2: CodeR) = e1() + e2() + "ISLESSEQUAL;\n"
fun GEQ(l: Int, e1: CodeR, e2: CodeR) = e1() + e2() + "ISGREATEQUAL;\n"
fun GT(l: Int, e1: CodeR, e2: CodeR) = e1() + e2() + "ISGREATER;\n"
fun LS(l: Int, e1: CodeR, e2: CodeR) = e1() + e2() + "ISLESSER;\n"
// TODO NEWFUNC -- how do I deal with the function arguments?
//fun FOR
// TODO for ( e1 ; e2 ; e3 ) s' === e1 ; while ( e2 ) { s' ; e3 ; }
fun NOP() = ""
fun PUSH() = "PUSH;-_-_-_ Inline ASM\n"
fun PUSHEP() = "PUSHEP;\n"
fun PUSHFP() = "PUSHFP;\n"
fun PUSH(e: CodeR) = e() + "PUSH;\n"
fun MARKFUNCCALL() = PUSHEP() + PUSHFP()
fun CALLFUNC(m: Int) = "CALLFUNC $m;\n"
fun ALLOCATSTACK(m: Int) = "ALLOCATSTACK $m;\n"
// STATEMENTS
// also "spilled" version of function "Code"
// SEXP stands for Statements-to-EXPression; my wild guess from my compiler prof's sense of naming, who is sexually
// attracted to the language Haskell
/** @params codeR an any function that takes nothing and returns IR2 (like LIT, ADD, VAR_R, JUMP) */
fun SEXP(l: Int, codeR: CodeR, rho: Rho): IR2 = codeR() + "POP;\n"
/** @params codeR an any function that takes Rho and returns IR2 (like ASSIGN, VAR_L) */
fun SEXP(l: Int, codeL: CodeL, rho: Rho): IR2 = codeL(rho) + "POP;\n"
fun SSEQ(l: Int, s: List<CodeR>, rho: Rho): IR2 =
if (s.isEmpty()) "" else s.first().invoke() + SSEQ(l, s.drop(1), rho)
private fun labelUnit(lineNum: Int, code: CodeR): IR2 {
return "\$LN${lineNum}_${code.hashCode().toHexString().dropLast(1)}" // hopefully there'll be no hash collision...
}
private fun labelFalse(lineNum: Int, code: CodeR) = labelUnit(lineNum, code) + "_FALSE"
private fun labelThen(lineNum: Int, code: CodeR) = labelUnit(lineNum, code) + "_THEN"
private fun labelWhile(lineNum: Int, code: CodeR) = "\$WHILE_" + labelUnit(lineNum, code).drop(1)
// IR2 to ASM
private const val IR1_COMMENT_MARKER = "-_-_-_"
private const val EP = "r14"
private const val FP = "r15"
private const val PC = "r0"
private const val SP = "r1" // special register
/**
- IR2 conditional:
```
IS-Comp
JUMPFALSE Lfalse
λ. code s_true rho
JUMP Lthen
LABEL Lfalse
λ. code s_false rho
LABEL Lthen
...
```
- ASM conditional:
```
λ. <comparison> rho
CMP;
JZ/JNZ/... Lfalse
(do.)
```
IR2's JUMPFALSE needs to be converted equivalent ASM according to the IS-Comp,
for example, ISEQUAL; JUMPZ false === CMP; JNZ false.
If you do the calculation, ALL THE RETURNING LABEL TAKE FALSE-LABELS. (easy coding wohoo!)
*/
private fun IR2toFalseJumps(compFun: IR2): Array<String> {
return when(compFun) {
"ISEQUAL" -> arrayOf("JNZ")
"ISNOTEQUAL" -> arrayOf("JZ")
"ISGREATER" -> arrayOf("JLS", "JZ")
"ISLESSER" -> arrayOf("JGT, JZ")
"ISGREATEQUAL" -> arrayOf("JLS")
"ISLESSEQUAL" -> arrayOf("JGT")
else -> throw UnsupportedOperationException("Unacceptable comparison operator: $compFun")
}
}
fun toASM(ir2: IR2, addDebugComments: Boolean = true): String {
val irList1 = ir2.replace(Regex("""$IR1_COMMENT_MARKER[^\n]*\n"""), "") // get rid of debug comment
.replace(Regex("""; *"""), "\n") // get rid of traling spaces after semicolon
.replace(Regex("""\n+"""), "\n") // get rid of empty lines
.split('\n') // CAPTCHA Sarah Connor
// put all the newvar into the top of the list
fun filterNewvar(s: IR2) = s.startsWith("NEWVAR")
val irList = listOf("SECT DATA") + irList1.filter { filterNewvar(it) } + listOf("SECT CODE") + irList1.filterNot { filterNewvar(it) }
val asm = StringBuilder()
var prevCompFun = ""
println("[START irList]")
println(irList.joinToString("\n")) // test return irList as one string
println("[END irList]\n")
for (c in 0..irList.lastIndex) {
val it = irList[c]
val tokens = it.split(Regex(" +"))
val head = tokens[0]
val arg1 = tokens.getOrNull(1)
val arg2 = tokens.getOrNull(2)
val arg3 = tokens.getOrNull(3)
if (it.isEmpty())
continue
val stmt: List<String>? = when (head) {
"HALT" -> { listOf("HALT;") }
"LOADCONST" -> { // ( -- immediate )
val l = listOf(
"LOADWORDIHI r1, ${arg1!!.dropLast(5)}h;",
"LOADWORDILO r1, ${arg1.takeLast(5)};",
"PUSH r1;"
)
if (arg1.length >= 5) l else l.drop(1)
}
"LOAD" -> { // ( address -- value in the addr )
listOf("POP r1;",
"LOADWORD r1, r1, r0;"
)
}
"STORE" -> { // ( value, address -- )
// TODO 'address' is virtual one
listOf("POP r2;",
"POP r1;",
"STOREWORD r1, r2, r0;"
)
}
"LABEL" -> {
listOf(":$arg1;")
}
"JUMP" -> {
listOf("JMP @$arg1;")
}
"ISEQUAL", "ISNOTEQUAL", "ISGREATER", "ISLESSER", "ISGREATEQUAL", "ISLESSEQUAL" -> {
prevCompFun = head // it's guaranteed compfunction is followed by JUMPFALSE (see IF/IFELSE/WHILE)
listOf("POP r2;",
"POP r1;",
"CMP r1, r2;"
)
}
"JUMPFALSE" -> {
IR2toFalseJumps(prevCompFun).map { "$it @$arg1;" }
}
"NEG" -> {
listOf("POP r1;",
"SUB r1, r0, r1;",
"PUSH r1;"
)
}
"SECT" -> { listOf(".$arg1;") }
"NEWVAR" -> { listOf("$arg1 $arg2;") }
"PUSH" -> { listOf("PUSH r1;") }
"PUSHEP" -> { listOf("PUSH $EP;") }
"PUSHFP" -> { listOf("PUSH $FP;") }
"CALLFUNC" -> {
// instruction CALL (fig 2.27)
listOf("SRR $FP, $SP;", // set FP
"SRR r1, $PC;", // swap(p, q); put PC into r1 (= p)
"POP r2;", // swap(p, q); pop into r2 (= q)
"PUSH r1;", // swap(p, q); push p
// instruction ENTER(m) part here (fig 2.28)
"LOADWORDILO r1, ${arg1!!.toInt()}", // EP = SP + m
"ADDINT $EP, r1, $FP", // EP = SP + m; FP still holds SP
// the last of CALL (jump)
"SRW r2, $PC;" // set PC as q (will do unconditional jump as PC is being overwritten)
)
}
"ALLOCATSTACK" -> {
val list = mutableListOf<String>()
repeat(arg1!!.toInt()) { list.add("PUSH r0;") } // we can just increment SP, but the stack will remain 0xFFFFFFFF which makes debugging trickier
/*return*/ list.toList()
}
"JSR" -> { listOf("JSR;") }
else -> {
listOf("# Unknown IR2: $it")
}
}
// keep this as is; it puts \n and original IR2 as formatted comments
val tabLen = 50
if (addDebugComments) {
stmt?.forEachIndexed { index, s ->
if (index == 0)
if (head == "JUMPFALSE")
asm.append(s.tabulate(tabLen) + "# ($prevCompFun) -> $it\n")
else
asm.append(s.tabulate(tabLen) + "# $it\n")
else if (index == stmt.lastIndex)
asm.append(s.tabulate(tabLen) + "#\n")
else
asm.append(s.tabulate(tabLen) + "#\n")
}
}
else {
stmt?.forEach { asm.append("$it ") } // ASMs grouped as their semantic meaning won't get \n'd
}
stmt?.let { asm.append("\n") }
}
return asm.toString()
}
private fun Byte.to2Hex() = this.toUint().toString(16).toUpperCase().padStart(2, '0') + 'h'
private fun String.tabulate(columnSize: Int = 56) = this + " ".repeat(maxOf(1, columnSize - this.length))
}
// IR1 is the bunch of functions above
typealias IR2 = String
/**
* Address Environment; a function to map a variable name to its memory address.
*
* The address is usually virtual. Can be converted to real address at either (IR2 -> ASM) or (ASM -> Machine) stage.
*/
typealias Rho = (String) -> Int
//typealias CodeL = (Rho) -> IR2
//typealias CodeR = () -> IR2
inline class CodeL(val function: (Rho) -> IR2) {
operator fun invoke(rho: Rho): IR2 { return function(rho) }
}
inline class CodeR(val function: () -> IR2) {
operator fun invoke(): IR2 { return function() }
}
inline class Code(val function: (Rho) -> IR2) {
operator fun invoke(rho: Rho): IR2 { return function(rho) }
}
// due to my laziness, CodeR is also a Stmt; after all, "e;" is a statement
/*inline class Stmt(val function: (Rho?) -> IR2) {
operator fun invoke(rho: Rho?): IR2 { return function(rho) }
}*/
fun main(args: Array<String>) {
val testProg = NewCompiler.testProgram
val tree = Cflat.buildTree(Cflat.tokenise(testProg))
val vm = TerranVM(4096)
val assembler = Assembler(vm)
println(tree)
//val code = NewCompiler.TEST_VARS
val (ir1, aenv) = NewCompiler.toIR1(tree)
val ir2 = ir1.invoke()
//code.invoke().forEach { println(it.invoke()) } // this is probably not the best sequence comprehension
println("## IR2: ##")
println(ir2)
val asm = NewCompiler.toASM(ir2)
println("## ASM: ##")
println(asm)
val vmImage = assembler(asm)
println("## OPCODE: ##")
vmImage.bytes.printASM()
} | mit |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/highlighting/LatexAnnotator.kt | 1 | 8244 | package nl.hannahsten.texifyidea.highlighting
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import nl.hannahsten.texifyidea.lang.Environment
import nl.hannahsten.texifyidea.psi.*
import nl.hannahsten.texifyidea.util.*
import nl.hannahsten.texifyidea.util.labels.getLabelDefinitionCommands
import nl.hannahsten.texifyidea.util.magic.CommandMagic
/**
* Provide syntax highlighting.
*
* @author Hannah Schellekens
*/
open class LatexAnnotator : Annotator {
override fun annotate(psiElement: PsiElement, annotationHolder: AnnotationHolder) {
// Math display
if (psiElement is LatexInlineMath) {
annotateInlineMath(psiElement, annotationHolder)
}
else if (psiElement is LatexDisplayMath ||
(psiElement is LatexEnvironment && psiElement.isContext(Environment.Context.MATH))
) {
annotateDisplayMath(psiElement, annotationHolder)
// Begin/End commands
if (psiElement is LatexEnvironment) {
annotationHolder.newAnnotation(HighlightSeverity.INFORMATION, "")
.range(TextRange.from(psiElement.beginCommand.textOffset, 6))
.textAttributes(LatexSyntaxHighlighter.COMMAND_MATH_DISPLAY)
.create()
annotationHolder.newAnnotation(HighlightSeverity.INFORMATION, "")
.range(TextRange.from(psiElement.endCommand?.textOffset ?: psiElement.textOffset, 4))
.textAttributes(LatexSyntaxHighlighter.COMMAND_MATH_DISPLAY)
.create()
}
}
// Optional parameters
else if (psiElement is LatexOptionalParam) {
annotateOptionalParameters(psiElement, annotationHolder)
}
// Commands
else if (psiElement is LatexCommands) {
annotateCommands(psiElement, annotationHolder)
}
}
/**
* Annotates an inline math element and its children.
*
* All elements will be coloured accoding to [LatexSyntaxHighlighter.INLINE_MATH] and
* all commands that are contained in the math environment get styled with
* [LatexSyntaxHighlighter.COMMAND_MATH_INLINE].
*/
private fun annotateInlineMath(
inlineMathElement: LatexInlineMath,
annotationHolder: AnnotationHolder
) {
annotationHolder.newSilentAnnotation(HighlightSeverity.INFORMATION)
.range(inlineMathElement)
.textAttributes(LatexSyntaxHighlighter.INLINE_MATH)
.create()
annotateMathCommands(
inlineMathElement.childrenOfType(LatexCommands::class), annotationHolder,
LatexSyntaxHighlighter.COMMAND_MATH_INLINE
)
}
/**
* Annotates a display math element and its children.
*
* All elements will be coloured accoding to [LatexSyntaxHighlighter.DISPLAY_MATH] and
* all commands that are contained in the math environment get styled with
* [LatexSyntaxHighlighter.COMMAND_MATH_DISPLAY].
*/
private fun annotateDisplayMath(
displayMathElement: PsiElement,
annotationHolder: AnnotationHolder
) {
annotationHolder.newSilentAnnotation(HighlightSeverity.INFORMATION)
.range(displayMathElement)
.textAttributes(LatexSyntaxHighlighter.DISPLAY_MATH)
.create()
annotateMathCommands(
displayMathElement.childrenOfType(LatexCommands::class), annotationHolder,
LatexSyntaxHighlighter.COMMAND_MATH_DISPLAY
)
}
/**
* Annotates all command tokens of the commands that are included in the `elements`.
*
* @param elements
* All elements to handle. Only elements that are [LatexCommands] are considered.
* @param highlighter
* The attributes to apply to all command tokens.
*/
private fun annotateMathCommands(
elements: Collection<PsiElement>,
annotationHolder: AnnotationHolder,
highlighter: TextAttributesKey
) {
for (element in elements) {
if (element !is LatexCommands) {
continue
}
val token = element.commandToken
annotationHolder.newSilentAnnotation(HighlightSeverity.INFORMATION)
.range(token)
.textAttributes(highlighter)
.create()
if (element.name == "\\text" || element.name == "\\intertext") {
annotationHolder.newSilentAnnotation(HighlightSeverity.INFORMATION)
.range(element.requiredParameters().firstOrNull() ?: continue)
.textAttributes(LatexSyntaxHighlighter.MATH_NESTED_TEXT)
.create()
}
}
}
/**
* Annotates the given optional parameters of commands.
*/
private fun annotateOptionalParameters(
optionalParamElement: LatexOptionalParam,
annotationHolder: AnnotationHolder
) {
for (
element in optionalParamElement.optionalParamContentList
) {
if (element !is LatexOptionalParamContent) {
continue
}
val toStyle = element.parameterText ?: continue
annotationHolder.newSilentAnnotation(HighlightSeverity.INFORMATION)
.range(toStyle)
.textAttributes(LatexSyntaxHighlighter.OPTIONAL_PARAM)
.create()
}
}
/**
* Annotates the given required parameters of commands.
*/
private fun annotateCommands(command: LatexCommands, annotationHolder: AnnotationHolder) {
annotateStyle(command, annotationHolder)
// Label references.
val style = when (command.name) {
in CommandMagic.labelReferenceWithoutCustomCommands -> {
LatexSyntaxHighlighter.LABEL_REFERENCE
}
// Label definitions.
in getLabelDefinitionCommands() -> {
LatexSyntaxHighlighter.LABEL_DEFINITION
}
// Bibliography references (citations).
in CommandMagic.bibliographyReference -> {
LatexSyntaxHighlighter.BIBLIOGRAPHY_REFERENCE
}
// Label definitions.
in CommandMagic.bibliographyItems -> {
LatexSyntaxHighlighter.BIBLIOGRAPHY_DEFINITION
}
else -> return
}
command.requiredParameters().firstOrNull()?.let {
annotationHolder.annotateRequiredParameter(it, style)
}
}
/**
* Annotates the command according to its font style, i.e. \textbf{} gets annotated with the `STYLE_BOLD` style.
*/
private fun annotateStyle(command: LatexCommands, annotationHolder: AnnotationHolder) {
val style = when (command.name) {
"\\textbf" -> LatexSyntaxHighlighter.STYLE_BOLD
"\\textit" -> LatexSyntaxHighlighter.STYLE_ITALIC
"\\underline" -> LatexSyntaxHighlighter.STYLE_UNDERLINE
"\\sout" -> LatexSyntaxHighlighter.STYLE_STRIKETHROUGH
"\\textsc" -> LatexSyntaxHighlighter.STYLE_SMALL_CAPITALS
"\\overline" -> LatexSyntaxHighlighter.STYLE_OVERLINE
"\\texttt" -> LatexSyntaxHighlighter.STYLE_TYPEWRITER
"\\textsl" -> LatexSyntaxHighlighter.STYLE_SLANTED
else -> return
}
command.requiredParameters().firstOrNull()?.let {
annotationHolder.annotateRequiredParameter(it, style)
}
}
/**
* Annotates the contents of the given parameter with the given style.
*/
private fun AnnotationHolder.annotateRequiredParameter(parameter: LatexRequiredParam, style: TextAttributesKey) {
val content = parameter.firstChildOfType(LatexContent::class) ?: return
this.newSilentAnnotation(HighlightSeverity.INFORMATION)
.range(content)
.textAttributes(style)
.create()
}
}
| mit |
ziggy42/Blum | app/src/main/java/com/andreapivetta/blu/data/twitter/TweetsQueue.kt | 1 | 2353 | package com.andreapivetta.blu.data.twitter
import android.content.Context
import com.andreapivetta.blu.R
import com.andreapivetta.blu.common.notifications.AppNotifications
import com.andreapivetta.blu.common.notifications.AppNotificationsFactory
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import timber.log.Timber
import java.io.InputStream
import java.util.*
/**
* Created by andrea on 13/10/16.
*/
object TweetsQueue {
data class StatusUpdate(val text: String, val streams: List<InputStream>, val reply: Long = -1) {
companion object {
fun valueOf(text: String) = StatusUpdate(text, listOf())
fun valueOf(text: String, reply: Long) = StatusUpdate(text, listOf(), reply)
fun valueOf(text: String, files: List<InputStream>) = StatusUpdate(text, files)
fun valueOf(text: String, files: List<InputStream>, reply: Long) =
StatusUpdate(text, files, reply)
}
}
private val queue: Queue<StatusUpdate> = LinkedList<StatusUpdate>()
private lateinit var appNotifications: AppNotifications
private lateinit var context: Context
private var sending = false
fun init(context: Context) {
this.context = context
this.appNotifications = AppNotificationsFactory.getAppNotifications(context)
}
fun add(update: StatusUpdate) {
queue.add(update)
tick()
}
@Synchronized private fun tick() {
if (!sending && queue.isNotEmpty()) {
sending = true
val id = appNotifications.sendLongRunning(
context.getString(R.string.sending_tweet_title),
context.getString(R.string.sending_tweet_content), R.drawable.ic_publish)
TwitterAPI.updateStatus(queue.poll())
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({
sending = false
appNotifications.stopLongRunning(id)
tick()
}, {
Timber.e(it)
sending = false
appNotifications.stopLongRunning(id)
tick()
})
}
}
} | apache-2.0 |
TWiStErRob/TWiStErRob | JFixturePlayground/src/test/java/net/twisterrob/test/jfixture/examples/journey/JourneyBuilder.kt | 1 | 1048 | package net.twisterrob.test.jfixture.examples.journey
import java.time.Clock
import java.time.LocalDateTime
import java.time.ZoneOffset
class JourneyBuilder(
private var id: String = "",
private val legs: MutableList<Leg> = mutableListOf()
) {
fun build() = Journey(id, legs, emptyList())
fun setId(id: String): JourneyBuilder = this.apply { this.id = id }
fun addLeg(leg: Leg): JourneyBuilder = this.apply { legs.add(leg) }
}
class LegBuilder(
private var origin: Stop = Stop("", ""),
private var departure: LocalDateTime = LocalDateTime.now(clock),
private var mode: TransportMode = TransportMode.WALK,
private var destination: Stop = Stop("", ""),
private var arrival: LocalDateTime = LocalDateTime.now(clock)
) {
fun build() = Leg(origin, departure, mode, destination, arrival)
fun setOrigin(origin: Stop): LegBuilder = this.apply { this.origin = origin }
fun setMode(mode: TransportMode): LegBuilder = this.apply { this.mode = mode }
// ...
companion object {
private val clock = Clock.tickMillis(ZoneOffset.UTC)
}
}
| unlicense |
AcapellaSoft/Aconite | aconite-core/src/io/aconite/serializers/AnyOfBodySerializerFactory.kt | 1 | 539 | package io.aconite.serializers
import io.aconite.BodySerializer
import kotlin.reflect.KAnnotatedElement
import kotlin.reflect.KType
class AnyOfBodySerializerFactory(vararg val serializers: BodySerializer.Factory): BodySerializer.Factory {
override fun create(annotations: KAnnotatedElement, type: KType) = serializers
.asSequence()
.map { it.create(annotations, type) }
.firstOrNull { it != null }
}
fun oneOf(vararg serializers: BodySerializer.Factory) = AnyOfBodySerializerFactory(*serializers) | mit |
schaal/ocreader | app/src/main/java/email/schaal/ocreader/view/ProgressFloatingActionButton.kt | 1 | 1500 | package email.schaal.ocreader.view
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import androidx.annotation.Keep
import com.google.android.material.floatingactionbutton.FloatingActionButton
import email.schaal.ocreader.R
/**
* FloatingActionButton with ability to show progress
*/
class ProgressFloatingActionButton(context: Context, attrs: AttributeSet?) : FloatingActionButton(context, attrs) {
private val circlePaint = Paint()
var progress = 0f
@Keep
set(value) {
field = value
invalidate()
}
private val diameter: Float = resources.getDimensionPixelSize(R.dimen.fab_size_normal).toFloat()
@Keep
fun setFabBackgroundColor(color: Int) {
backgroundTintList = ColorStateList.valueOf(color)
}
override fun onDraw(canvas: Canvas) {
val radius = diameter / 2
val count = canvas.save()
// draw progress circle fraction
canvas.clipRect(0f, diameter * (1 - progress), diameter, diameter)
canvas.drawCircle(radius, radius, radius, circlePaint)
canvas.restoreToCount(count)
super.onDraw(canvas)
}
init {
context.obtainStyledAttributes(attrs, R.styleable.ProgressFloatingActionButton).also {
circlePaint.color = it.getColor(R.styleable.ProgressFloatingActionButton_progressColor, 0)
}.recycle()
}
} | gpl-3.0 |
bravelocation/yeltzland-android | app/src/main/java/com/bravelocation/yeltzlandnew/tweet/VideoInfo.kt | 1 | 246 | package com.bravelocation.yeltzlandnew.tweet
import com.google.gson.annotations.SerializedName
import com.google.gson.annotations.Expose
class VideoInfo {
@SerializedName("aspect_ratio")
@Expose
var aspectRatios: List<Int>? = null
} | mit |
misaochan/apps-android-commons | app/src/main/java/fr/free/nrw/commons/wikidata/model/DepictSearchItem.kt | 8 | 569 | package fr.free.nrw.commons.wikidata.model
/**
* Model class for Depiction item returned from API after calling searchForDepicts
"search": [
{
"repository": "local",
"id": "Q23444",
"concepturi": "http://www.wikidata.org/entity/Q23444",
"title": "Q23444",
"pageid": 26835,
"url": "//www.wikidata.org/wiki/Q23444",
"label": "white",
"description": "color",
"match": {
"type": "label",
"language": "en",
"text": "white"
}
}*/
class DepictSearchItem(
val id: String,
val pageid: String,
val url: String,
val label: String,
val description: String?
)
| apache-2.0 |
d3xter/bo-android | app/src/main/java/org/blitzortung/android/data/provider/blitzortung/TimestampIterator.kt | 1 | 1570 | /*
Copyright 2015 Andreas Würl
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.blitzortung.android.data.provider.blitzortung
class TimestampIterator(
private val intervalLength: Long,
startTime: Long,
private val endTime: Long = System.currentTimeMillis()
) : Iterator<Long> {
private var currentTime: Long = roundTime(startTime)
fun roundTime(time: Long): Long {
return time / intervalLength * intervalLength
}
override fun hasNext(): Boolean {
return currentTime <= endTime
}
override fun next(): Long {
val currentTimeCopy = currentTime
currentTime += intervalLength
return currentTimeCopy
}
}
/**
* Values of the Timestamp-Sequence are lazy generated, so we provide a Sequence for it
* @param intervalLength Interval length
* @param startTime Start time of the sequence
*/
internal fun createTimestampSequence(intervalLength: Long, startTime: Long): Sequence<Long> {
return Sequence { TimestampIterator(intervalLength, startTime) }
}
| apache-2.0 |
tasks/tasks | app/src/googleplay/java/org/tasks/injection/FlavorModule.kt | 1 | 1189 | package org.tasks.injection
import dagger.Lazy
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import org.tasks.location.Geocoder
import org.tasks.location.GeocoderMapbox
import org.tasks.location.GoogleMapFragment
import org.tasks.location.LocationService
import org.tasks.location.LocationServiceAndroid
import org.tasks.location.LocationServiceGooglePlay
import org.tasks.location.MapFragment
import org.tasks.location.OsmMapFragment
import org.tasks.play.PlayServices
@Module
@InstallIn(SingletonComponent::class)
class FlavorModule {
@Provides
fun getLocationService(
google: Lazy<LocationServiceGooglePlay>,
android: Lazy<LocationServiceAndroid>,
playServices: PlayServices,
): LocationService = if (playServices.isAvailable()) google.get() else android.get()
@Provides
fun getMapFragment(
osm: Lazy<OsmMapFragment>,
google: Lazy<GoogleMapFragment>,
playServices: PlayServices,
): MapFragment = if (playServices.isAvailable()) google.get() else osm.get()
@Provides
fun getGeocoder(mapbox: GeocoderMapbox): Geocoder = mapbox
} | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.