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 |
---|---|---|---|---|---|
mp911de/lettuce | src/main/kotlin/io/lettuce/core/api/coroutines/RedisServerCoroutinesCommands.kt | 1 | 11544 | /*
* Copyright 2020-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.lettuce.core.api.coroutines
import io.lettuce.core.ExperimentalLettuceCoroutinesApi
import io.lettuce.core.KillArgs
import io.lettuce.core.TrackingArgs
import io.lettuce.core.UnblockType
import io.lettuce.core.protocol.CommandType
import java.util.*
/**
* Coroutine executed commands for Server Control.
*
* @param <K> Key type.
* @param <V> Value type.
* @author Mikhael Sokolov
* @since 6.0
* @generated by io.lettuce.apigenerator.CreateKotlinCoroutinesApi
*/
@ExperimentalLettuceCoroutinesApi
interface RedisServerCoroutinesCommands<K : Any, V : Any> {
/**
* Asynchronously rewrite the append-only file.
*
* @return String simple-string-reply always `OK`.
*/
suspend fun bgrewriteaof(): String?
/**
* Asynchronously save the dataset to disk.
*
* @return String simple-string-reply.
*/
suspend fun bgsave(): String?
/**
* Control tracking of keys in the context of server-assisted client cache invalidation.
*
* @param enabled @code true} to enable key tracking.
* @return String simple-string-reply `OK`.
* @since 6.0
*/
suspend fun clientCaching(enabled: Boolean): String?
/**
* Get the current connection name.
*
* @return K bulk-string-reply The connection name, or a null bulk reply if no name is set.
*/
suspend fun clientGetname(): K?
/**
* Returns the client ID we are redirecting our tracking notifications to.
*
* @return the ID of the client we are redirecting the notifications to. The command returns -1 if client tracking is not
* enabled, or 0 if client tracking is enabled but we are not redirecting the notifications to any client.
* @since 6.0
*/
suspend fun clientGetredir(): Long?
/**
* Get the id of the current connection.
*
* @return Long The command just returns the ID of the current connection.
* @since 5.3
*/
suspend fun clientId(): Long?
/**
* Kill the connection of a client identified by ip:port.
*
* @param addr ip:port.
* @return String simple-string-reply `OK` if the connection exists and has been closed.
*/
suspend fun clientKill(addr: String): String?
/**
* Kill connections of clients which are filtered by `killArgs`.
*
* @param killArgs args for the kill operation.
* @return Long integer-reply number of killed connections.
*/
suspend fun clientKill(killArgs: KillArgs): Long?
/**
* Get the list of client connections.
*
* @return String bulk-string-reply a unique string, formatted as follows: One client connection per line (separated by LF),
* each line is composed of a succession of property=value fields separated by a space character.
*/
suspend fun clientList(): String?
/**
* Stop processing commands from clients for some time.
*
* @param timeout the timeout value in milliseconds.
* @return String simple-string-reply The command returns OK or an error if the timeout is invalid.
*/
suspend fun clientPause(timeout: Long): String?
/**
* Set the current connection name.
*
* @param name the client name.
* @return simple-string-reply `OK` if the connection name was successfully set.
*/
suspend fun clientSetname(name: K): String?
/**
* Enables the tracking feature of the Redis server, that is used for server assisted client side caching. Tracking messages
* are either available when using the RESP3 protocol or through Pub/Sub notification when using RESP2.
*
* @param args for the CLIENT TRACKING operation.
* @return String simple-string-reply `OK`.
* @since 6.0
*/
suspend fun clientTracking(args: TrackingArgs): String?
/**
* Unblock the specified blocked client.
*
* @param id the client id.
* @param type unblock type.
* @return Long integer-reply number of unblocked connections.
* @since 5.1
*/
suspend fun clientUnblock(id: Long, type: UnblockType): Long?
/**
* Returns an array reply of details about all Redis commands.
*
* @return List<Any> array-reply.
*/
suspend fun command(): List<Any>
/**
* Get total number of Redis commands.
*
* @return Long integer-reply of number of total commands in this Redis server.
*/
suspend fun commandCount(): Long?
/**
* Returns an array reply of details about the requested commands.
*
* @param commands the commands to query for.
* @return List<Any> array-reply.
*/
suspend fun commandInfo(vararg commands: String): List<Any>
/**
* Returns an array reply of details about the requested commands.
*
* @param commands the commands to query for.
* @return List<Any> array-reply.
*/
suspend fun commandInfo(vararg commands: CommandType): List<Any>
/**
* Get the value of a configuration parameter.
*
* @param parameter name of the parameter.
* @return Map<String, String> bulk-string-reply.
*/
suspend fun configGet(parameter: String): Map<String, String>?
/**
* Reset the stats returned by INFO.
*
* @return String simple-string-reply always `OK`.
*/
suspend fun configResetstat(): String?
/**
* Rewrite the configuration file with the in memory configuration.
*
* @return String simple-string-reply `OK` when the configuration was rewritten properly. Otherwise an error is
* returned.
*/
suspend fun configRewrite(): String?
/**
* Set a configuration parameter to the given value.
*
* @param parameter the parameter name.
* @param value the parameter value.
* @return String simple-string-reply: `OK` when the configuration was set properly. Otherwise an error is returned.
*/
suspend fun configSet(parameter: String, value: String): String?
/**
* Return the number of keys in the selected database.
*
* @return Long integer-reply.
*/
suspend fun dbsize(): Long?
/**
* Crash and recover.
*
* @param delay optional delay in milliseconds.
* @return String simple-string-reply.
*/
suspend fun debugCrashAndRecover(delay: Long): String?
/**
* Get debugging information about the internal hash-table state.
*
* @param db the database number.
* @return String simple-string-reply.
*/
suspend fun debugHtstats(db: Int): String?
/**
* Get debugging information about a key.
*
* @param key the key.
* @return String simple-string-reply.
*/
suspend fun debugObject(key: K): String?
/**
* Make the server crash: Out of memory.
*
* @return nothing, because the server crashes before returning.
*/
suspend fun debugOom()
/**
* Save RDB, clear the database and reload RDB.
*
* @return String simple-string-reply The commands returns OK on success.
*/
suspend fun debugReload(): String?
/**
* Restart the server gracefully.
*
* @param delay optional delay in milliseconds.
* @return String simple-string-reply.
*/
suspend fun debugRestart(delay: Long): String?
/**
* Get debugging information about the internal SDS length.
*
* @param key the key.
* @return String simple-string-reply.
*/
suspend fun debugSdslen(key: K): String?
/**
* Make the server crash: Invalid pointer access.
*
* @return nothing, because the server crashes before returning.
*/
suspend fun debugSegfault()
/**
* Remove all keys from all databases.
*
* @return String simple-string-reply.
*/
suspend fun flushall(): String?
/**
* Remove all keys asynchronously from all databases.
*
* @return String simple-string-reply.
*/
suspend fun flushallAsync(): String?
/**
* Remove all keys from the current database.
*
* @return String simple-string-reply.
*/
suspend fun flushdb(): String?
/**
* Remove all keys asynchronously from the current database.
*
* @return String simple-string-reply.
*/
suspend fun flushdbAsync(): String?
/**
* Get information and statistics about the server.
*
* @return String bulk-string-reply as a collection of text lines.
*/
suspend fun info(): String?
/**
* Get information and statistics about the server.
*
* @param section the section type: string.
* @return String bulk-string-reply as a collection of text lines.
*/
suspend fun info(section: String): String?
/**
* Get the UNIX time stamp of the last successful save to disk.
*
* @return Date integer-reply an UNIX time stamp.
*/
suspend fun lastsave(): Date?
/**
* Reports the number of bytes that a key and its value require to be stored in RAM.
*
* @return memory usage in bytes.
* @since 5.2
*/
suspend fun memoryUsage(key: K): Long?
/**
* Synchronously save the dataset to disk.
*
* @return String simple-string-reply The commands returns OK on success.
*/
suspend fun save(): String?
/**
* Synchronously save the dataset to disk and then shut down the server.
*
* @param save @code true} force save operation.
*/
suspend fun shutdown(save: Boolean)
/**
* Make the server a replica of another instance, or promote it as master.
*
* @param host the host type: string.
* @param port the port type: string.
* @return String simple-string-reply.
*/
suspend fun slaveof(host: String, port: Int): String?
/**
* Promote server as master.
*
* @return String simple-string-reply.
*/
suspend fun slaveofNoOne(): String?
/**
* Read the slow log.
*
* @return List<Any> deeply nested multi bulk replies.
*/
suspend fun slowlogGet(): List<Any>
/**
* Read the slow log.
*
* @param count the count.
* @return List<Any> deeply nested multi bulk replies.
*/
suspend fun slowlogGet(count: Int): List<Any>
/**
* Obtaining the current length of the slow log.
*
* @return Long length of the slow log.
*/
suspend fun slowlogLen(): Long?
/**
* Resetting the slow log.
*
* @return String simple-string-reply The commands returns OK on success.
*/
suspend fun slowlogReset(): String?
/**
* Return the current server time.
*
* @return List<V> array-reply specifically:
*
* A multi bulk reply containing two elements:
*
* unix time in seconds. microseconds.
*/
suspend fun time(): List<V>
}
| apache-2.0 |
Demidong/ClockView | app/src/main/java/com/xd/demi/activity/InviteCodeActivity.kt | 1 | 999 | package com.xd.demi.activity
import android.app.Activity
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import com.xd.demi.R
import com.xd.demi.view.InviteCodeView
import kotlinx.android.synthetic.main.activity_invite.*
/**
* Created by demi on 2019/3/1 下午4:07.
*/
class InviteCodeActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_invite)
btn_control.setOnClickListener {
if (et_in.isDrawNumber) {
et_in.hideNumberText()
btn_control.text = "显示邀请码"
} else {
et_in.showNumberText()
btn_control.text = "隐藏邀请码"
}
}
et_in.setOnFinishInputCodeListener {
Toast.makeText(this, "输入完毕:$it", Toast.LENGTH_SHORT).show()
finish()
}
}
} | apache-2.0 |
toastkidjp/Jitte | loan/src/main/java/jp/toastkid/loan/model/Factor.kt | 1 | 513 | /*
* Copyright (c) 2021 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.loan.model
class Factor(
val amount: Int,
val term: Int,
val interestRate: Double,
val downPayment: Int,
val managementFee: Int,
val renovationReserves: Int
) | epl-1.0 |
proxer/ProxerLibJava | library/src/main/kotlin/me/proxer/library/internal/adapter/EpisodeInfoAdapter.kt | 1 | 3369 | package me.proxer.library.internal.adapter
import com.squareup.moshi.FromJson
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.squareup.moshi.ToJson
import me.proxer.library.entity.info.AnimeEpisode
import me.proxer.library.entity.info.EpisodeInfo
import me.proxer.library.entity.info.MangaEpisode
import me.proxer.library.enums.Category
import me.proxer.library.enums.MediaLanguage
import me.proxer.library.internal.adapter.EpisodeInfoAdapter.IntermediateEpisodeInfo.IntermediateEpisode
/**
* @author Ruben Gees
*/
internal class EpisodeInfoAdapter {
private companion object {
private const val DELIMITER = ","
}
@FromJson
fun fromJson(json: IntermediateEpisodeInfo): EpisodeInfo {
val episodes = when (json.category) {
Category.ANIME -> json.episodes.map { episode ->
val hosters = requireNotNull(episode.hosters).split(DELIMITER).toSet()
val hosterImages = requireNotNull(episode.hosterImages).split(DELIMITER)
AnimeEpisode(episode.number, episode.language, hosters, hosterImages)
}
Category.MANGA, Category.NOVEL -> json.episodes.map { episode ->
val title = requireNotNull(episode.title)
MangaEpisode(episode.number, episode.language, title)
}
}
return EpisodeInfo(
json.firstEpisode,
json.lastEpisode,
json.category,
json.availableLanguages,
json.userProgress,
episodes
)
}
@ToJson
fun toJson(value: EpisodeInfo?): IntermediateEpisodeInfo? {
if (value == null) return null
val episodes = value.episodes.map {
when (it) {
is AnimeEpisode -> {
val joinedHosters = it.hosters.joinToString(DELIMITER)
val joinedHosterImages = it.hosterImages.joinToString(DELIMITER)
IntermediateEpisode(it.number, it.language, null, joinedHosters, joinedHosterImages)
}
is MangaEpisode -> IntermediateEpisode(it.number, it.language, it.title, null, null)
else -> error("Unknown Episode type: ${it.javaClass.name}")
}
}
return IntermediateEpisodeInfo(
value.firstEpisode,
value.lastEpisode,
value.category,
value.availableLanguages,
value.userProgress,
episodes
)
}
@JsonClass(generateAdapter = true)
internal data class IntermediateEpisodeInfo(
@Json(name = "start") val firstEpisode: Int,
@Json(name = "end") val lastEpisode: Int,
@Json(name = "kat") val category: Category,
@Json(name = "lang") val availableLanguages: Set<MediaLanguage>,
@Json(name = "state") val userProgress: Int?,
@Json(name = "episodes") val episodes: List<IntermediateEpisode>
) {
@JsonClass(generateAdapter = true)
internal data class IntermediateEpisode(
@Json(name = "no") val number: Int,
@Json(name = "typ") val language: MediaLanguage,
@Json(name = "title") val title: String?,
@Json(name = "types") val hosters: String?,
@Json(name = "typeimg") val hosterImages: String?
)
}
}
| mit |
iZettle/wrench | wrench-app/src/main/java/com/izettle/wrench/database/WrenchConfigurationValue.kt | 1 | 1122 | package com.izettle.wrench.database
import androidx.room.*
import androidx.room.ForeignKey.CASCADE
import com.izettle.wrench.database.tables.ConfigurationTable
import com.izettle.wrench.database.tables.ConfigurationValueTable
@Entity(tableName = ConfigurationValueTable.TABLE_NAME,
indices = [Index(value = arrayOf(ConfigurationValueTable.COL_CONFIG_ID, ConfigurationValueTable.COL_VALUE, ConfigurationValueTable.COL_SCOPE), unique = true)],
foreignKeys = [ForeignKey(entity = WrenchConfiguration::class, parentColumns = arrayOf(ConfigurationTable.COL_ID), childColumns = arrayOf(ConfigurationValueTable.COL_CONFIG_ID), onDelete = CASCADE)])
data class WrenchConfigurationValue(
@field:PrimaryKey(autoGenerate = true) @field:ColumnInfo(name = ConfigurationValueTable.COL_ID)
var id: Long,
@field:ColumnInfo(name = ConfigurationValueTable.COL_CONFIG_ID)
var configurationId: Long,
@field:ColumnInfo(name = ConfigurationValueTable.COL_VALUE)
var value: String?,
@field:ColumnInfo(name = ConfigurationValueTable.COL_SCOPE)
var scope: Long)
| mit |
cuebyte/rendition | src/test/kotlin/moe/cuebyte/rendition/mock/BookInt.kt | 1 | 449 | package moe.cuebyte.rendition.mock
import moe.cuebyte.rendition.Model
import moe.cuebyte.rendition.type.int
import moe.cuebyte.rendition.type.long
import moe.cuebyte.rendition.type.string
object BookInt : Model("book_int", mapOf(
"id" to int().primaryKey(),
"author" to string().index(),
"publish" to string().index(),
"words" to long().index(),
"sales" to long().index(),
"introduce" to string(),
"date" to string()
)) | lgpl-3.0 |
chat-sdk/chat-sdk-android | chat-sdk-vendor/src/main/java/smartadapter/viewevent/swipe/BasicSwipeEventBinder.kt | 1 | 3413 | package smartadapter.viewevent.swipe
/*
* Created by Manne Öhlund on 2019-08-15.
* Copyright (c) All rights reserved.
*/
import android.graphics.Canvas
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import smartadapter.SmartRecyclerAdapter
import smartadapter.SmartViewHolderType
import smartadapter.viewevent.model.ViewEvent
import smartadapter.viewevent.viewholder.OnItemSwipedListener
import smartadapter.viewholder.SmartViewHolder
import kotlin.math.abs
/**
* The basic implementation of [SwipeEventBinder].
*
* @see SwipeEventBinder
*/
open class BasicSwipeEventBinder(
override val identifier: Any = BasicSwipeEventBinder::class,
override var longPressDragEnabled: Boolean = false,
override var swipeFlags: SwipeFlags = ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT,
override var viewHolderTypes: List<SmartViewHolderType> = listOf(SmartViewHolder::class),
override var eventListener: (ViewEvent.OnItemSwiped) -> Unit
) : SwipeEventBinder() {
override lateinit var smartRecyclerAdapter: SmartRecyclerAdapter
override fun getMovementFlags(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder
): Int {
var swipeFlags = 0
for (viewHolderType in viewHolderTypes) {
if (viewHolderType.java.isAssignableFrom(viewHolder.javaClass)) {
swipeFlags = this.swipeFlags
break
}
}
return makeMovementFlags(0, swipeFlags)
}
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
if (viewHolder is OnItemSwipedListener) {
viewHolder.onItemSwiped(
ViewEvent.OnItemSwiped(
smartRecyclerAdapter,
viewHolder as SmartViewHolder<*>,
viewHolder.adapterPosition,
viewHolder.itemView,
direction
)
)
}
eventListener.invoke(
ViewEvent.OnItemSwiped(
smartRecyclerAdapter,
viewHolder as SmartViewHolder<*>,
viewHolder.adapterPosition,
viewHolder.itemView,
direction
)
)
}
override fun isLongPressDragEnabled(): Boolean = longPressDragEnabled
override fun onChildDraw(
canvas: Canvas,
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
dX: Float,
dY: Float,
actionState: Int,
isCurrentlyActive: Boolean
) {
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
val alpha = 1 - abs(dX) / recyclerView.width
viewHolder.itemView.alpha = alpha
}
super.onChildDraw(canvas, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
}
override fun bind(
smartRecyclerAdapter: SmartRecyclerAdapter,
recyclerView: RecyclerView
): BasicSwipeEventBinder {
this.smartRecyclerAdapter = smartRecyclerAdapter
val touchHelper = ItemTouchHelper(this)
touchHelper.attachToRecyclerView(recyclerView)
return this
}
}
| apache-2.0 |
consp1racy/android-commons | commons-dimen/src/main/java/net/xpece/android/content/res/Dimen.kt | 1 | 1718 | package net.xpece.android.content.res
import android.content.Context
/**
* Created by pechanecjr on 4. 1. 2015.
*/
data class Dimen internal constructor(val value: Float) : Comparable<Dimen> {
override fun compareTo(other: Dimen): Int = this.value.compareTo(other.value)
operator fun plus(that: Dimen): Dimen = Dimen(
this.value + that.value)
operator fun minus(that: Dimen): Dimen = Dimen(
this.value - that.value)
operator fun plus(that: Number): Dimen = Dimen(
this.value + that.toFloat())
operator fun minus(that: Number): Dimen = Dimen(
this.value - that.toFloat())
operator fun unaryMinus() = Dimen(-this.value)
operator fun unaryPlus() = Dimen(this.value)
operator fun times(q: Number) = Dimen(this.value * q.toFloat())
operator fun div(d: Number) = Dimen(this.value / d.toFloat())
operator fun div(d: Dimen) = this.value / d.value
val pixelSize: Int
get() {
val res = (value + 0.5F).toInt()
if (res != 0) return res
if (value == 0F) return 0
if (value > 0) return 1
return -1
}
val pixelOffset: Int
get() = value.toInt()
override fun toString(): String = "Dimen(${value}px)"
/**
* Along px prints also dp and sp values according to provided context.
*/
fun toString(context: Context): String {
val density = context.resources.displayMetrics.density
val dp = Math.round(value / density)
val scaledDensity = context.resources.displayMetrics.scaledDensity
val sp = Math.round(value / scaledDensity)
return "Dimen(${value}px ~ ${dp}dp ~ ${sp}sp)"
}
}
| apache-2.0 |
Shashi-Bhushan/General | cp-trials/src/test/kotlin/in/shabhushan/cp_trials/RgbToHexConversionTest.kt | 1 | 455 | package `in`.shabhushan.cp_trials
import `in`.shabhushan.cp_trials.RgbToHexConversion.rgb
import kotlin.test.assertEquals
import org.junit.Test
class RgbToHexConversionTest {
@Test
fun testFixed() {
assertEquals("000000", rgb(0, 0, 0))
assertEquals("000000", rgb(0, 0, -20))
assertEquals("FFFFFF", rgb(300,255,255))
assertEquals("ADFF2F", rgb(173,255,47))
assertEquals("9400D3", rgb(148, 0, 211))
}
}
| gpl-2.0 |
icarumbas/bagel | core/src/ru/icarumbas/bagel/engine/entities/factories/EntityFactory.kt | 1 | 44718 | package ru.icarumbas.bagel.engine.entities.factories
import com.badlogic.ashley.core.Entity
import com.badlogic.ashley.utils.ImmutableArray
import com.badlogic.gdx.graphics.g2d.Animation
import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.badlogic.gdx.maps.MapObject
import com.badlogic.gdx.maps.objects.PolylineMapObject
import com.badlogic.gdx.maps.objects.RectangleMapObject
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.math.Rectangle
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.physics.box2d.Body
import com.badlogic.gdx.physics.box2d.BodyDef
import com.badlogic.gdx.utils.Array
import ru.icarumbas.bagel.engine.components.other.*
import ru.icarumbas.bagel.engine.components.physics.BodyComponent
import ru.icarumbas.bagel.engine.components.physics.InactiveMarkerComponent
import ru.icarumbas.bagel.engine.components.physics.StaticComponent
import ru.icarumbas.bagel.engine.components.physics.WeaponComponent
import ru.icarumbas.bagel.engine.components.velocity.FlyComponent
import ru.icarumbas.bagel.engine.components.velocity.JumpComponent
import ru.icarumbas.bagel.engine.components.velocity.RunComponent
import ru.icarumbas.bagel.engine.components.velocity.TeleportComponent
import ru.icarumbas.bagel.engine.entities.EntityState
import ru.icarumbas.bagel.engine.resources.ResourceManager
import ru.icarumbas.bagel.engine.systems.physics.WeaponSystem
import ru.icarumbas.bagel.engine.world.PIX_PER_M
import ru.icarumbas.bagel.utils.*
import ru.icarumbas.bagel.view.renderer.components.*
import kotlin.experimental.or
class EntityFactory(
private val bodyFactory: BodyFactory,
private val animationFactory: AnimationFactory,
private val assets: ResourceManager
) {
fun swingWeaponEntity(width: Int,
height: Int,
mainBody: Body,
anchorA: Vector2,
anchorB: Vector2,
speed: Float,
maxSpeed: Float): Entity {
return Entity().apply {
add(BodyComponent(bodyFactory.swordWeapon(
categoryBit = WEAPON_BIT,
maskBit = AI_BIT or BREAKABLE_BIT or PLAYER_BIT,
size = Vector2(width / PIX_PER_M, height / PIX_PER_M))
.createRevoluteJoint(mainBody, anchorA, anchorB, maxSpeed, speed)))
add(InactiveMarkerComponent())
}.also {
body[it].body.userData = it
}
}
fun playerEntity(): Entity {
val playerBody = bodyFactory.playerBody()
val weaponAtlas = assets.getTextureAtlas("Packs/weapons.pack")
val playerAtlas = assets.getTextureAtlas("Packs/GuyKnight.pack")
return Entity()
.add(TextureComponent())
.add(PlayerComponent(0))
.add(RunComponent(acceleration = .4f, maxSpeed = 6f))
.add(SizeComponent(Vector2(50 / PIX_PER_M, 105 / PIX_PER_M), .425f))
.add(JumpComponent(jumpVelocity = 1.5f, maxJumps = 5))
.add(HealthComponent(
HP = 100,
canBeDamagedTime = 1f))
.add(BodyComponent(playerBody))
.add(EquipmentComponent())
.add(WeaponComponent(
type = WeaponSystem.WeaponType.SWING,
entityLeft = swingWeaponEntity(
width = 30,
height = 100,
mainBody = playerBody,
anchorA = Vector2(0f, -.2f),
anchorB = Vector2(0f, -1f),
speed = 5f,
maxSpeed = 3f)
.add(AlwaysRenderingMarkerComponent())
.add(TextureComponent(weaponAtlas.findRegion("eyes_sword")))
.add((TranslateComponent()))
.add(SizeComponent(Vector2(30 / PIX_PER_M, 150 / PIX_PER_M), .1f)),
entityRight = swingWeaponEntity(
width = 30,
height = 100,
mainBody = playerBody,
anchorA = Vector2(0f, -.2f),
anchorB = Vector2(0f, -.8f),
speed = -5f,
maxSpeed = 3f)
.add(AlwaysRenderingMarkerComponent())
.add((TranslateComponent()))
.add(TextureComponent(weaponAtlas.findRegion("eyes_sword")))
.add(SizeComponent(Vector2(30 / PIX_PER_M, 150 / PIX_PER_M), .1f))))
.add(StateComponent(ImmutableArray(Array.with(
EntityState.RUNNING,
EntityState.JUMPING,
EntityState.STANDING,
EntityState.ATTACKING,
EntityState.DEAD,
EntityState.WALKING,
EntityState.JUMP_ATTACKING
))))
.add(AnimationComponent(hashMapOf(
EntityState.RUNNING to animationFactory.create("Run", 10, .075f, playerAtlas),
EntityState.JUMPING to animationFactory.create("Jump", 10, .15f, playerAtlas),
EntityState.STANDING to animationFactory.create("Idle", 10, .1f, playerAtlas),
EntityState.DEAD to animationFactory.create("Dead", 10, .1f, playerAtlas, Animation.PlayMode.NORMAL),
EntityState.ATTACKING to animationFactory.create("Attack", 7, .075f, playerAtlas),
EntityState.WALKING to animationFactory.create("Walk", 10, .075f, playerAtlas),
EntityState.JUMP_ATTACKING to animationFactory.create("JumpAttack", 10, .075f, playerAtlas)
)))
.add(AlwaysRenderingMarkerComponent())
.add(AttackComponent(strength = 15, knockback = Vector2(1.5f, 1f)))
.add((TranslateComponent()))
.also {
body[it].body.userData = it
}
}
fun groundEntity(obj: MapObject, bit: Short): Entity{
return Entity()
.add(when (obj) {
is RectangleMapObject -> {
BodyComponent(bodyFactory.rectangleMapObjectBody(
obj.rectangle,
BodyDef.BodyType.StaticBody,
obj.rectangle.width / PIX_PER_M,
obj.rectangle.height / PIX_PER_M,
bit))
}
is PolylineMapObject -> {
BodyComponent(bodyFactory.polylineMapObjectBody(
obj,
BodyDef.BodyType.StaticBody,
bit))
}
else -> throw IllegalArgumentException("Cant create ${obj.name} object")
})
}
fun lootEntity(r: Int,
point: Pair<Float,Float>,
roomId: Int,
playerEntity: Entity): Entity{
val atlas = assets.getTextureAtlas("weapons.pack")
val loot = Entity()
.add(SizeComponent(Vector2(30 / PIX_PER_M, 100 / PIX_PER_M), 1.5f))
.add(TextureComponent(atlas.findRegion("sword1")))
.add((TranslateComponent(point.first - 15 / PIX_PER_M, point.second)))
.add(LootComponent(arrayListOf(
WeaponComponent(
type = WeaponSystem.WeaponType.SWING,
entityLeft = swingWeaponEntity(
width = 30,
height = 100,
mainBody = body[playerEntity].body,
anchorA = Vector2(0f, -.2f),
anchorB = Vector2(0f, -1f),
speed = 5f,
maxSpeed = 3f)
.add(AlwaysRenderingMarkerComponent())
.add((TranslateComponent()))
.add(SizeComponent(Vector2(5 / PIX_PER_M, 100 / PIX_PER_M), 2f))
.add(TextureComponent(atlas.findRegion("sword1"))),
entityRight = swingWeaponEntity(
width = 30,
height = 100,
mainBody = body[playerEntity].body,
anchorA = Vector2(0f, -.2f),
anchorB = Vector2(0f, -.8f),
speed = -5f,
maxSpeed = 3f)
.add(AlwaysRenderingMarkerComponent())
.add((TranslateComponent()))
.add(TextureComponent(atlas.findRegion("sword1")))
.add(SizeComponent(Vector2(5 / PIX_PER_M, 100 / PIX_PER_M), 2f))
),
AttackComponent(strength = 30, knockback = Vector2(2f, 2f))
)))
loot.add(RoomIdComponent(roomId))
// loot.add(ShaderComponent(ShaderProgram(FileHandle("Shaders/bleak.vert"), FileHandle("Shaders/bleak.frag"))))
return loot
}
fun idMapObjectEntity(roomId: Int,
rect: Rectangle,
objectPath: String,
r: Int,
playerEntity: Entity): Entity? {
val atlas = assets.getTextureAtlas("Packs/items.pack")
return when(objectPath){
"vase" -> {
val size = when (r) {
1 -> Pair(132, 171)
2 -> Pair(65, 106)
3 -> Pair(120, 162)
4 -> Pair(98, 72)
else -> return null
}
Entity()
.add(BodyComponent(bodyFactory.rectangleMapObjectBody(
rect,
BodyDef.BodyType.StaticBody,
size.first / PIX_PER_M,
size.second / PIX_PER_M,
BREAKABLE_BIT,
WEAPON_BIT)))
.add(HealthComponent(5))
.add(SizeComponent(Vector2(size.first / PIX_PER_M, size.second / PIX_PER_M)))
.add(TextureComponent(atlas.findRegion("Vase ($r)")))
}
"window" -> {
Entity()
.add(BodyComponent(bodyFactory.rectangleMapObjectBody(
rect,
BodyDef.BodyType.StaticBody,
86 / PIX_PER_M,
169 / PIX_PER_M,
STATIC_BIT,
WEAPON_BIT)))
.add(SizeComponent(Vector2(86 / PIX_PER_M, 169 / PIX_PER_M)))
.add(TextureComponent(atlas.findRegion("Window Small ($r)")))
}
"chair1" -> {
if (r == 2) return null
Entity()
.add(BodyComponent(bodyFactory.rectangleMapObjectBody(
rect,
BodyDef.BodyType.StaticBody,
70 / PIX_PER_M,
128 / PIX_PER_M,
BREAKABLE_BIT,
WEAPON_BIT)))
.add(HealthComponent(5))
.add(SizeComponent(Vector2(70 / PIX_PER_M, 128 / PIX_PER_M)))
.add(TextureComponent(atlas.findRegion("Chair (1)")))
}
"chair2" -> {
if (r == 2) return null
Entity()
.add(BodyComponent(bodyFactory.rectangleMapObjectBody(
rect,
BodyDef.BodyType.StaticBody,
70 / PIX_PER_M,
128 / PIX_PER_M,
BREAKABLE_BIT,
WEAPON_BIT)))
.add(HealthComponent(5))
.add(SizeComponent(Vector2(70 / PIX_PER_M, 128 / PIX_PER_M)))
.add(TextureComponent(atlas.findRegion("Chair (2)")))
}
"table" -> {
if (r == 2) return null
Entity()
.add(BodyComponent(bodyFactory.rectangleMapObjectBody(
rect,
BodyDef.BodyType.StaticBody,
137 / PIX_PER_M,
69 / PIX_PER_M,
BREAKABLE_BIT,
WEAPON_BIT)))
.add(HealthComponent(5))
.add(SizeComponent(Vector2(137 / PIX_PER_M, 69 / PIX_PER_M)))
.add(TextureComponent(atlas.findRegion("Table")))
}
"chandelier" -> {
Entity()
.add(BodyComponent(bodyFactory.rectangleMapObjectBody(
rect,
BodyDef.BodyType.StaticBody,
243 / PIX_PER_M,
120 / PIX_PER_M,
BREAKABLE_BIT,
WEAPON_BIT)))
.add(HealthComponent(5))
.add(AnimationComponent(hashMapOf(EntityState.STANDING to
animationFactory.create("Chandelier", 4, .125f, atlas))))
.add(StateComponent(
ImmutableArray(Array.with(EntityState.STANDING)),
MathUtils.random()
))
.add(SizeComponent(Vector2(243 / PIX_PER_M, 120 / PIX_PER_M)))
.add(TextureComponent())
}
"candle" -> {
Entity()
.add(BodyComponent(bodyFactory.rectangleMapObjectBody(
rect,
BodyDef.BodyType.StaticBody,
178 / PIX_PER_M,
208 / PIX_PER_M,
BREAKABLE_BIT,
WEAPON_BIT)))
.add(HealthComponent(5))
.add(AnimationComponent(hashMapOf(EntityState.STANDING to
animationFactory.create("Candle", 4, .125f, atlas))))
.add(StateComponent(
ImmutableArray(Array.with(EntityState.STANDING)),
MathUtils.random()
))
.add(SizeComponent(Vector2(178 / PIX_PER_M, 208 / PIX_PER_M)))
.add(TextureComponent())
}
"smallBanner" -> {
Entity()
.add(BodyComponent(bodyFactory.rectangleMapObjectBody(
rect,
BodyDef.BodyType.StaticBody,
126 / PIX_PER_M,
180 / PIX_PER_M,
BREAKABLE_BIT,
WEAPON_BIT)))
.add(SizeComponent(Vector2(126 / PIX_PER_M, 180 / PIX_PER_M)))
.add(HealthComponent(5))
.add(TextureComponent(atlas.findRegion("Banner ($r)")))
}
"chest" -> {
if (r == 2) return null
Entity()
.add(BodyComponent(bodyFactory.rectangleMapObjectBody(
rect,
BodyDef.BodyType.StaticBody,
96 / PIX_PER_M,
96 / PIX_PER_M,
KEY_OPEN_BIT,
PLAYER_BIT)))
.add(SizeComponent(Vector2(96 / PIX_PER_M, 96 / PIX_PER_M)))
.add(AnimationComponent(hashMapOf(
EntityState.STANDING to
animationFactory.create("Chest", 1, .125f, atlas),
EntityState.OPENING to
animationFactory.create("Chest", 4, .125f, atlas))))
.add(StateComponent(
ImmutableArray(Array.with(EntityState.STANDING, EntityState.OPENING)),
0f
))
.add(TextureComponent(atlas.findRegion("Chest (1)")))
.add(OpenComponent())
}
"door" -> {
Entity()
.add(BodyComponent(bodyFactory.rectangleMapObjectBody(
rect,
BodyDef.BodyType.StaticBody,
170 / PIX_PER_M,
244 / PIX_PER_M,
KEY_OPEN_BIT,
PLAYER_BIT)))
.add(SizeComponent(Vector2(170 / PIX_PER_M, 244 / PIX_PER_M)))
.add(AnimationComponent(
if (r == 1) {
hashMapOf(
EntityState.STANDING to
animationFactory.create("IronDoor", 1, .125f, atlas),
EntityState.OPENING to
animationFactory.create("IronDoor", 4, .125f, atlas)
)
} else {
hashMapOf(
EntityState.STANDING to
animationFactory.create("Wood Door", 1, .125f, atlas),
EntityState.OPENING to
animationFactory.create("Wood Door", 4, .125f, atlas)
)
}
))
.add(StateComponent(
ImmutableArray(Array.with(EntityState.STANDING, EntityState.OPENING)),
0f
))
.add(TextureComponent())
.add(OpenComponent())
.add(DoorComponent())
}
"crateBarrel" -> {
if (r == 3) return null
Entity()
.add(BodyComponent(bodyFactory.rectangleMapObjectBody(
rect,
BodyDef.BodyType.StaticBody,
if (r == 1) 106 / PIX_PER_M else 119 / PIX_PER_M,
if (r == 1) 106 / PIX_PER_M else 133 / PIX_PER_M,
BREAKABLE_BIT,
WEAPON_BIT)))
.add(HealthComponent(5))
.add(SizeComponent(Vector2(
if (r == 1) 106 / PIX_PER_M else 119 / PIX_PER_M,
if (r == 1) 106 / PIX_PER_M else 133 / PIX_PER_M)))
.add(TextureComponent(atlas.findRegion(if (r == 1) "Crate" else "Barrel")))
}
"flyingEnemy" -> {
when (r) {
1 -> {
Entity()
.add(BodyComponent(bodyFactory.rectangleMapObjectBody(
rect,
BodyDef.BodyType.DynamicBody,
64 / PIX_PER_M,
64 / PIX_PER_M,
AI_BIT,
PLAYER_BIT or WEAPON_BIT,
true,
0f)))
.add(HealthComponent(roomId + 20))
.add(AnimationComponent(hashMapOf(
EntityState.STANDING to Animation(
.1f,
assets.getTextureAtlas("Packs/Enemies/MiniDragon.pack")
.findRegions("miniDragon"),
Animation.PlayMode.LOOP)
)))
.add(StateComponent(ImmutableArray(Array.with(EntityState.STANDING))))
.add(AIComponent(refreshSpeed = MathUtils.random(.2f, .3f), attackDistance = 1f, entityTarget = playerEntity))
.add(SizeComponent(Vector2(64 / PIX_PER_M, 64 / PIX_PER_M), .15f))
.add(AttackComponent(strength = roomId + 15, knockback = Vector2(2f, 2f)))
.add(TextureComponent())
.add(FlyComponent(.005f))
}
else -> return null
}
}
"groundEnemy" -> {
when (r) {
1 -> {
val skeletonAtlas = assets.getTextureAtlas("Packs/Enemies/Skeleton.pack")
val body = bodyFactory.rectangleMapObjectBody(
rect,
BodyDef.BodyType.DynamicBody,
85 / PIX_PER_M,
192 / PIX_PER_M,
AI_BIT,
WEAPON_BIT or GROUND_BIT or PLATFORM_BIT)
Entity()
.add(BodyComponent(body))
.add(HealthComponent(roomId + 40))
.add(AnimationComponent(hashMapOf(
EntityState.STANDING to Animation(
.125f,
skeletonAtlas.findRegions("idle"),
Animation.PlayMode.LOOP),
EntityState.ATTACKING to Animation(
.125f,
skeletonAtlas.findRegions("hit"),
Animation.PlayMode.LOOP),
EntityState.DEAD to Animation(
.125f,
skeletonAtlas.findRegions("die"),
Animation.PlayMode.NORMAL),
EntityState.APPEARING to Animation(
.1f,
skeletonAtlas.findRegions("appear"),
Animation.PlayMode.LOOP),
EntityState.WALKING to Animation(
.125f,
skeletonAtlas.findRegions("go"),
Animation.PlayMode.LOOP))
))
.add(StateComponent(
ImmutableArray(Array.with(
EntityState.STANDING,
EntityState.ATTACKING,
EntityState.DEAD,
EntityState.APPEARING,
EntityState.WALKING))
))
.add(RunComponent(.25f, 1f))
.add(AIComponent(refreshSpeed = MathUtils.random(.2f, .3f), attackDistance = 1f, entityTarget = playerEntity))
.add(SizeComponent(Vector2(180 / PIX_PER_M, 230 / PIX_PER_M), 1f))
.add(WeaponComponent(
type = WeaponSystem.WeaponType.SWING,
entityLeft = swingWeaponEntity(
35,
135,
body,
Vector2(0f, -.3f),
Vector2(0f, -.5f),
speed = 4f,
maxSpeed = 2f)
.add(RoomIdComponent(roomId)),
entityRight = swingWeaponEntity(
35,
135,
body,
Vector2(0f, -.3f),
Vector2(0f, -.5f),
speed = -4f,
maxSpeed = 2f)
.add(RoomIdComponent(roomId))))
.add(AttackComponent(strength = roomId + 15, knockback = Vector2(2.5f, 2.5f)))
.add(TextureComponent())
}
2 -> {
val golemAtlas = assets.getTextureAtlas("Packs/Enemies/Golem.pack")
val body = bodyFactory.rectangleMapObjectBody(
rect,
BodyDef.BodyType.DynamicBody,
230 / PIX_PER_M,
230 / PIX_PER_M,
AI_BIT,
WEAPON_BIT or GROUND_BIT or PLATFORM_BIT)
Entity()
.add(BodyComponent(body))
.add(HealthComponent(roomId + 80))
.add(AnimationComponent(hashMapOf(
EntityState.STANDING to Animation(
.125f,
golemAtlas.findRegions("idle"),
Animation.PlayMode.LOOP),
EntityState.ATTACKING to Animation(
.125f,
golemAtlas.findRegions("hit"),
Animation.PlayMode.LOOP),
EntityState.DEAD to Animation(
.15f,
golemAtlas.findRegions("die"),
Animation.PlayMode.NORMAL),
EntityState.APPEARING to Animation(
.1f,
golemAtlas.findRegions("appear"),
Animation.PlayMode.LOOP),
EntityState.WALKING to Animation(
.1f,
golemAtlas.findRegions("idle"),
Animation.PlayMode.LOOP))
))
.add(StateComponent(
ImmutableArray(Array.with(
EntityState.STANDING,
EntityState.ATTACKING,
EntityState.DEAD,
EntityState.APPEARING,
EntityState.WALKING))
))
.add(RunComponent(.5f, .5f))
.add(AIComponent(refreshSpeed = MathUtils.random(.45f, .55f), attackDistance = 2f, entityTarget = playerEntity))
.add(SizeComponent(Vector2(230 / PIX_PER_M, 230 / PIX_PER_M), 1f))
.add(WeaponComponent(
type = WeaponSystem.WeaponType.SWING,
entityLeft = swingWeaponEntity(
50,
215,
body,
Vector2(0f, -.3f),
Vector2(0f, -1f),
speed = 4f,
maxSpeed = 2f)
.add(RoomIdComponent(roomId)),
entityRight = swingWeaponEntity(
50,
215,
body,
Vector2(0f, -.3f),
Vector2(0f, -1f),
speed = -4f,
maxSpeed = 2f)
.add(RoomIdComponent(roomId))))
.add(AttackComponent(strength = roomId + 25, knockback = Vector2(3.5f, 3.5f)))
.add(TextureComponent())
}
3 -> {
val zombieAtlas = assets.getTextureAtlas("Packs/Enemies/Zombie.pack")
val body = bodyFactory.rectangleMapObjectBody(
rect,
BodyDef.BodyType.DynamicBody,
85 / PIX_PER_M,
192 / PIX_PER_M,
AI_BIT,
WEAPON_BIT or GROUND_BIT or PLATFORM_BIT or SHARP_BIT)
Entity()
.add(BodyComponent(body))
.add(HealthComponent(roomId + 30))
.add(AnimationComponent(hashMapOf(
EntityState.STANDING to Animation(
.125f,
zombieAtlas.findRegions("idle"),
Animation.PlayMode.LOOP),
EntityState.ATTACKING to Animation(
.125f,
zombieAtlas.findRegions("hit"),
Animation.PlayMode.LOOP),
EntityState.DEAD to Animation(
.125f,
zombieAtlas.findRegions("die"),
Animation.PlayMode.NORMAL),
EntityState.APPEARING to Animation(
.1f,
zombieAtlas.findRegions("appear"),
Animation.PlayMode.LOOP),
EntityState.WALKING to Animation(
.075f,
zombieAtlas.findRegions("go"),
Animation.PlayMode.LOOP))
))
.add(StateComponent(
ImmutableArray(Array.with(
EntityState.STANDING,
EntityState.ATTACKING,
EntityState.DEAD,
EntityState.APPEARING,
EntityState.WALKING))
))
.add(RunComponent(.25f, 2f))
.add(AIComponent(refreshSpeed = MathUtils.random(.1f, .2f), attackDistance = 1f, entityTarget = playerEntity))
.add(SizeComponent(Vector2(125 / PIX_PER_M, 202 / PIX_PER_M), 1f))
.add(WeaponComponent(
type = WeaponSystem.WeaponType.SWING,
entityLeft = swingWeaponEntity(
35,
110,
body,
Vector2(0f, -.3f),
Vector2(0f, -.5f),
speed = 4f,
maxSpeed = 2f)
.add(RoomIdComponent(roomId)),
entityRight = swingWeaponEntity(
35,
110,
body,
Vector2(0f, -.3f),
Vector2(0f, -.5f),
speed = -4f,
maxSpeed = 2f)
.add(RoomIdComponent(roomId))))
.add(AttackComponent(strength = roomId + 10, knockback = Vector2(2.5f, 2.5f)))
.add(TextureComponent())
}
4 -> {
val vampAtlas = assets.getTextureAtlas("Packs/Enemies/Vamp.pack")
val body = bodyFactory.rectangleMapObjectBody(
rect,
BodyDef.BodyType.DynamicBody,
85 / PIX_PER_M,
192 / PIX_PER_M,
AI_BIT,
WEAPON_BIT or GROUND_BIT or PLATFORM_BIT or SHARP_BIT)
Entity()
.add(BodyComponent(body))
.add(HealthComponent(roomId + 20))
.add(AnimationComponent(hashMapOf(
EntityState.STANDING to Animation(
.125f,
vampAtlas.findRegions("go"),
Animation.PlayMode.LOOP),
EntityState.ATTACKING to Animation(
.125f,
vampAtlas.findRegions("hit"),
Animation.PlayMode.LOOP),
EntityState.DEAD to Animation(
.125f,
vampAtlas.findRegions("appear"),
Animation.PlayMode.NORMAL),
EntityState.APPEARING to Animation(
.1f,
vampAtlas.findRegions("appear").apply { reverse() },
Animation.PlayMode.LOOP),
EntityState.WALKING to Animation(
.1f,
vampAtlas.findRegions("go"),
Animation.PlayMode.LOOP),
EntityState.DISAPPEARING to Animation(
.1f,
vampAtlas.findRegions("appear"),
Animation.PlayMode.LOOP))
))
.add(StateComponent(
ImmutableArray(Array.with(
EntityState.STANDING,
EntityState.ATTACKING,
EntityState.DEAD,
EntityState.APPEARING,
EntityState.WALKING,
EntityState.DISAPPEARING))
))
.add(RunComponent(.225f, .75f))
.add(AIComponent(refreshSpeed = MathUtils.random(.7f, 1f), attackDistance = 2f, entityTarget = playerEntity))
.add(SizeComponent(Vector2(85 / PIX_PER_M, 202 / PIX_PER_M), 1f))
.add(WeaponComponent(
type = WeaponSystem.WeaponType.SWING,
entityLeft = swingWeaponEntity(
35,
220,
body,
Vector2(0f, -.3f),
Vector2(0f, -1f),
speed = 4f,
maxSpeed = 2f)
.add(RoomIdComponent(roomId)),
entityRight = swingWeaponEntity(
35,
220,
body,
Vector2(0f, -.3f),
Vector2(0f, -1f),
speed = -4f,
maxSpeed = 2f)
.add(RoomIdComponent(roomId))))
.add(TeleportComponent())
.add(AttackComponent(strength = roomId + 15, knockback = Vector2(1.5f, 1.5f)))
.add(TextureComponent())
}
else -> return null
}
}
else -> throw IllegalArgumentException("Cant create object with objectPath = $objectPath")
}.apply {
add(TranslateComponent())
add(RoomIdComponent(roomId))
}.also {
body[it].body.userData = it
}
}
fun staticMapObjectEntity(roomPath: String,
objectPath: String,
atlas: TextureAtlas,
obj: MapObject): Entity{
return when(objectPath){
"spikes" -> {
Entity()
.add(BodyComponent(bodyFactory.rectangleMapObjectBody(
(obj as RectangleMapObject).rectangle,
BodyDef.BodyType.StaticBody,
64 / PIX_PER_M,
64 / PIX_PER_M,
SHARP_BIT,
PLAYER_BIT or AI_BIT)))
.add(SizeComponent(Vector2(64 / PIX_PER_M, 64 / PIX_PER_M), .5f))
.add(AttackComponent(15, Vector2(0f, .05f)))
.add(TextureComponent(atlas.findRegion("Spike")))
.add((TranslateComponent()))
}
"lighting" -> {
Entity()
.add(BodyComponent(bodyFactory.rectangleMapObjectBody(
(obj as RectangleMapObject).rectangle,
BodyDef.BodyType.StaticBody,
98 / PIX_PER_M,
154 / PIX_PER_M,
STATIC_BIT,
-1)))
.add(AnimationComponent(hashMapOf(EntityState.STANDING to
animationFactory.create("Lighting", 4, .125f, atlas))))
.add(StateComponent(ImmutableArray(Array.with(EntityState.STANDING)),
MathUtils.random()))
.add(SizeComponent(Vector2(98 / PIX_PER_M, 154 / PIX_PER_M)))
.add(TextureComponent())
.add((TranslateComponent()))
}
"torch" -> {
Entity()
.add(BodyComponent(bodyFactory.rectangleMapObjectBody(
(obj as RectangleMapObject).rectangle,
BodyDef.BodyType.StaticBody,
178 / PIX_PER_M,
116 / PIX_PER_M,
STATIC_BIT,
-1)))
.add(AnimationComponent(hashMapOf(EntityState.STANDING to
animationFactory.create("Torch", 4, .125f, atlas))))
.add(StateComponent(ImmutableArray(Array.with(EntityState.STANDING)),
MathUtils.random()))
.add(SizeComponent(Vector2(178 / PIX_PER_M, 116 / PIX_PER_M)))
.add(TextureComponent())
.add((TranslateComponent()))
}
"ground" -> groundEntity(obj, GROUND_BIT)
"platform" -> {
groundEntity(obj, PLATFORM_BIT)
.add(SizeComponent(Vector2(
(obj as RectangleMapObject).rectangle.width / PIX_PER_M,
obj.rectangle.height / PIX_PER_M)))
.add((TranslateComponent()))
}
else -> throw IllegalArgumentException("Cant create object with objectPath = $objectPath")
}
.add(StaticComponent(roomPath))
.also {
body[it].body.userData = it
}
}
}
| apache-2.0 |
tommykw/capture | auto-permanent-compiler/src/main/java/com/github/tommykw/auto_permanent_compiler/model/AutoPermanentClassSpec.kt | 1 | 403 | package com.github.tommykw.auto_permanent_compiler.model
import kotlin.reflect.KClass
internal sealed class AutoPermanentClassSpec(val clazz: KClass) {
class Object(clazz: KClass, val name: String) : AutoPermanentClassSpec(clazz)
class Data(clazz: KClass, val properties: List<AutoPermanentClassSpec>)
}
internal data class AutoPermanentPropertySpec(
val name: String,
val type: Int
) | apache-2.0 |
rowysock/codecov2discord | src/main/kotlin/com/wabadaba/codecov2discord/MainController.kt | 1 | 3792 | package com.wabadaba.codecov2discord
import com.fasterxml.jackson.databind.ObjectMapper
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.client.RestTemplate
import java.math.BigDecimal
import java.math.RoundingMode
@Suppress("unused")
@RestController
class MainController {
@Autowired
lateinit var mapper: ObjectMapper
val logger = LoggerFactory.getLogger(this::class.java)
private val iconUrl = "https://chocolatey.org/content/packageimages/codecov.1.0.1.png"
@RequestMapping("/discord-webhook/{id}/{token}")
fun test(
@PathVariable id: String,
@PathVariable token: String,
@RequestBody bodyString: String
) {
logger.info(bodyString)
val body = mapper.readValue(bodyString, CodecovWebhook::class.java)
val template = RestTemplate(HttpComponentsClientHttpRequestFactory())
val author = DiscordWebhook.Embed.Author(body.head.author.username)
val commitIdShort = body.head.commitid.substring(0, 6)
val description = "[`$commitIdShort`](${body.head.service_url}) ${body.head.message}"
val embed = DiscordWebhook.Embed(
"[${body.repo.name}:${body.head.branch}]",
description,
body.repo.url,
author,
color = 0xF70557)
val webhook = DiscordWebhook("""
Coverage: **${body.head.totals.c.setScale(2, RoundingMode.HALF_UP)}%**
[Change: **${body.compare.coverage.setScale(2, RoundingMode.HALF_UP)}%**](${body.compare.url})
""".trimIndent(),
"Codecov",
iconUrl,
listOf(embed))
template.postForEntity("https://discordapp.com/api/webhooks/$id/$token", webhook, String::class.java)
}
}
data class DiscordWebhook(
val content: String,
val username: String,
val avatar_url: String,
val embeds: List<Embed>) {
data class Embed(
val title: String,
val description: String,
val url: String,
val author: Author,
val fields: List<Field>? = null,
val provider: Provider? = null,
val thumbnail: Thumbnail? = null,
val color: Int) {
data class Author(
val name: String
)
data class Field(
val name: String,
val value: String
)
data class Provider(
val name: String
)
data class Thumbnail(
val url: String,
val height: Int,
val width: Int
)
}
}
data class CodecovWebhook(
val repo: Repo,
val head: Head,
val compare: Compare) {
data class Head(
val url: String,
val message: String,
val author: Author,
val totals: Totals,
val branch: String,
val commitid: String,
val service_url: String) {
data class Totals(
val c: BigDecimal
)
data class Author(
val username: String,
val name: String
)
}
data class Repo(
val name: String,
val url: String
)
data class Compare(
val coverage: BigDecimal,
val url: String
)
}
| mit |
polson/MetroTripper | app/src/main/java/com/philsoft/metrotripper/utils/ui/Ui.kt | 1 | 1288 | package com.philsoft.metrotripper.utils.ui
import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Point
import android.graphics.drawable.BitmapDrawable
import android.view.WindowManager
import com.philsoft.metrotripper.utils.createBitmap
object Ui {
fun createBitmapFromDrawableResource(context: Context, widthOffset: Int, heightOffset: Int, drawableResource: Int): Bitmap {
val d = context.resources.getDrawable(drawableResource)
val bd = d.current as BitmapDrawable
val b = bd.bitmap
return Bitmap.createScaledBitmap(b, b.width + widthOffset, b.height + heightOffset, false)
}
fun createBitmapFromLayoutResource(activity: Activity, layoutResource: Int): Bitmap {
val view = activity.layoutInflater.inflate(layoutResource, null, false)
return view.createBitmap()
}
fun getCurrentScreenHeight(context: Context): Int {
val size = getDisplaySize(context)
return size.y
}
private fun getDisplaySize(context: Context): Point {
val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val display = wm.defaultDisplay
val size = Point()
display.getSize(size)
return size
}
}
| apache-2.0 |
uber/RIBs | android/libraries/rib-coroutines/src/main/kotlin/com/uber/rib/core/RibCoroutineScopes.kt | 1 | 2811 | /*
* Copyright (C) 2022. Uber Technologies
*
* 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.uber.rib.core
import android.app.Application
import com.uber.autodispose.ScopeProvider
import com.uber.autodispose.coroutinesinterop.asCoroutineScope
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import java.util.WeakHashMap
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.reflect.KProperty
/**
* [CoroutineScope] tied to this [ScopeProvider].
* This scope will be canceled when ScopeProvider is completed
*
* This scope is bound to
* [RibDispatchers.Main.immediate][kotlinx.coroutines.MainCoroutineDispatcher.immediate]
*/
public val ScopeProvider.coroutineScope: CoroutineScope by LazyCoroutineScope<ScopeProvider> {
val context: CoroutineContext = SupervisorJob() +
RibDispatchers.Main.immediate +
CoroutineName("${this::class.simpleName}:coroutineScope") +
(RibCoroutinesConfig.exceptionHandler ?: EmptyCoroutineContext)
asCoroutineScope(context)
}
/**
* [CoroutineScope] tied to this [Application].
* This scope will not be cancelled, it lives for the full application process.
*
* This scope is bound to
* [RibDispatchers.Main.immediate][kotlinx.coroutines.MainCoroutineDispatcher.immediate]
*/
public val Application.coroutineScope: CoroutineScope by LazyCoroutineScope<Application> {
val context: CoroutineContext = SupervisorJob() +
RibDispatchers.Main.immediate +
CoroutineName("${this::class.simpleName}:coroutineScope") +
(RibCoroutinesConfig.exceptionHandler ?: EmptyCoroutineContext)
CoroutineScope(context)
}
internal class LazyCoroutineScope<This : Any>(val initializer: This.() -> CoroutineScope) {
companion object {
private val values = WeakHashMap<Any, CoroutineScope>()
// Used to get and set Test overrides from rib-coroutines-test utils
operator fun get(provider: Any) = values[provider]
operator fun set(provider: Any, scope: CoroutineScope?) {
values[provider] = scope
}
}
operator fun getValue(thisRef: This, property: KProperty<*>): CoroutineScope = synchronized(LazyCoroutineScope) {
return values.getOrPut(thisRef) { thisRef.initializer() }
}
}
| apache-2.0 |
charlesmadere/smash-ranks-android | smash-ranks-android/app/src/test/java/com/garpr/android/data/models/SimpleDateTest.kt | 1 | 2001 | package com.garpr.android.data.models
import com.garpr.android.test.BaseTest
import org.junit.Assert.assertEquals
import org.junit.Test
import java.util.Calendar
import java.util.Collections
import java.util.Date
class SimpleDateTest : BaseTest() {
@Test
fun testChronologicalOrder() {
val list = listOf(SimpleDate(Date(2)), SimpleDate(Date(0)),
SimpleDate(Date(1)), SimpleDate(Date(5)), SimpleDate(Date(20)))
Collections.sort(list, SimpleDate.CHRONOLOGICAL_ORDER)
assertEquals(0, list[0].date.time)
assertEquals(1, list[1].date.time)
assertEquals(2, list[2].date.time)
assertEquals(5, list[3].date.time)
assertEquals(20, list[4].date.time)
}
@Test
fun testHashCodeWithChristmas() {
val date = with(Calendar.getInstance()) {
clear()
set(Calendar.YEAR, 2017)
set(Calendar.MONTH, Calendar.DECEMBER)
set(Calendar.DAY_OF_MONTH, 25)
time
}
val simpleDate = SimpleDate(date)
assertEquals(date.hashCode(), simpleDate.hashCode())
}
@Test
fun testHashCodeWithGenesis7() {
val date = with(Calendar.getInstance()) {
clear()
set(Calendar.YEAR, 2020)
set(Calendar.MONTH, Calendar.JANUARY)
set(Calendar.DAY_OF_MONTH, 24)
time
}
val simpleDate = SimpleDate(date)
assertEquals(date.hashCode(), simpleDate.hashCode())
}
@Test
fun testReverseChronologicalOrder() {
val list = listOf(SimpleDate(Date(2)), SimpleDate(Date(0)),
SimpleDate(Date(1)), SimpleDate(Date(5)), SimpleDate(Date(20)))
Collections.sort(list, SimpleDate.REVERSE_CHRONOLOGICAL_ORDER)
assertEquals(20, list[0].date.time)
assertEquals(5, list[1].date.time)
assertEquals(2, list[2].date.time)
assertEquals(1, list[3].date.time)
assertEquals(0, list[4].date.time)
}
}
| unlicense |
alexpensato/spring-boot-repositories-samples | spring-data-apache-cassandra-sample/src/main/java/net/pensato/data/cassandra/sample/App.kt | 1 | 1208 | /*
* Copyright 2017 twitter.com/PensatoAlex
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.pensato.data.cassandra.sample
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.builder.SpringApplicationBuilder
import org.springframework.boot.web.support.SpringBootServletInitializer
@SpringBootApplication
open class App : SpringBootServletInitializer() {
override fun configure(application: SpringApplicationBuilder): SpringApplicationBuilder {
return application.sources(App::class.java)
}
}
fun main(args: Array<String>) {
SpringApplication.run(App::class.java, *args)
}
| apache-2.0 |
CaelumF/Cbot | src/com/gmail/caelum119/Cbot2/events/UserWelcomeEvent.kt | 1 | 293 | package com.gmail.caelum119.Cbot2.events
import com.gmail.caelum119.Cbot2.message_structure.Identity
import com.gmail.caelum119.utils.event.Event
/**
* First created 10/16/2016 in Cbot
*/
class UserWelcomeEvent(val login: String, val identity: Identity, val channelJoined: String): Event() | mit |
jtransc/jtransc | jtransc-utils/src/com/jtransc/text/token.kt | 2 | 3279 | /*
* 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.text
import com.jtransc.error.InvalidOperationException
import java.io.Reader
class TokenReader<T>(val list: List<T>) {
var position = 0
val size = list.size
val hasMore: Boolean get() = position < size
fun peek(): T = list[position]
fun read(): T {
val result = peek()
skip()
return result
}
fun tryRead(vararg expected: T): Boolean {
val value = peek()
if (value in expected) {
skip(1)
return true
} else {
return false
}
}
fun expect(expected: T): T {
val value = read()
if (value != expected) {
throw InvalidOperationException("Expected $expected but found $value")
}
return value
}
fun expect(expected: Set<T>): T {
val value = read()
if (value !in expected) throw InvalidOperationException("Expected $expected but found $value")
return value
}
fun unread() {
position--
}
fun skip(count: Int = 1): TokenReader<T> {
position += count
return this
}
}
fun Char.isLetterOrUnderscore(): Boolean = this.isLetter() || this == '_' || this == '$'
fun Char.isLetterDigitOrUnderscore(): Boolean = this.isLetterOrDigit() || this == '_' || this == '$'
fun Char.isLetterOrDigitOrDollar(): Boolean = this.isLetterOrDigit() || this == '$'
// @TODO: Make a proper table
// 0x20, 0x7e
//return this.isLetterDigitOrUnderscore() || this == '.' || this == '/' || this == '\'' || this == '"' || this == '(' || this == ')' || this == '[' || this == ']' || this == '+' || this == '-' || this == '*' || this == '/'
fun Char.isPrintable(): Boolean = when (this) {
in '\u0020'..'\u007e', in '\u00a1'..'\u00ff' -> true
else -> false
}
fun GenericTokenize(sr: Reader): List<String> {
val symbols = setOf("...")
val tokens = arrayListOf<String>()
while (sr.hasMore) {
val char = sr.peekch()
if (char.isLetterOrUnderscore()) {
var token = ""
while (sr.hasMore) {
val c = sr.peekch()
if (!c.isLetterDigitOrUnderscore()) break
token += c
sr.skip(1)
}
tokens.add(token)
} else if (char.isWhitespace()) {
sr.skip(1)
} else if (char.isDigit()) {
var token = ""
while (sr.hasMore) {
val c = sr.peekch()
if (!c.isLetterOrDigit() && c != '.') break
token += c
sr.skip(1)
}
tokens.add(token)
} else if (char == '"') {
var token = "\""
sr.skip(1)
while (sr.hasMore) {
val c = sr.peekch()
token += c
sr.skip(1)
if (c == '"') break
}
tokens.add(token)
} else {
//val peek = sr.peek(3)
if (sr.peek(3) in symbols) {
tokens.add(sr.read(3))
} else if (sr.peek(2) in symbols) {
tokens.add(sr.read(2))
} else {
tokens.add("$char")
sr.skip(1)
}
}
}
return tokens.toList()
} | apache-2.0 |
dataloom/conductor-client | src/test/kotlin/com/openlattice/hazelcast/serializers/RemoveMembersFromOrganizationAssemblyProcessorStreamSerializerTest.kt | 1 | 2269 | /*
* Copyright (C) 2019. OpenLattice, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* You can contact the owner of the copyright at [email protected]
*
*
*/
package com.openlattice.hazelcast.serializers
import com.kryptnostic.rhizome.hazelcast.serializers.AbstractStreamSerializerTest
import com.openlattice.assembler.AssemblerConnectionManager
import com.openlattice.assembler.processors.RemoveMembersFromOrganizationAssemblyProcessor
import com.openlattice.mapstores.TestDataFactory
import com.openlattice.organizations.SecurablePrincipalList
import org.mockito.Mockito
class RemoveMembersFromOrganizationAssemblyProcessorStreamSerializerTest
: AbstractStreamSerializerTest<RemoveMembersFromOrganizationAssemblyProcessorStreamSerializer,
RemoveMembersFromOrganizationAssemblyProcessor>() {
override fun createSerializer(): RemoveMembersFromOrganizationAssemblyProcessorStreamSerializer {
val processorSerializer = RemoveMembersFromOrganizationAssemblyProcessorStreamSerializer()
processorSerializer.init(Mockito.mock(AssemblerConnectionManager::class.java))
processorSerializer.initSplss(SecurablePrincipalListStreamSerializer())
return processorSerializer
}
override fun createInput(): RemoveMembersFromOrganizationAssemblyProcessor {
return RemoveMembersFromOrganizationAssemblyProcessor(
SecurablePrincipalList(
mutableListOf(
TestDataFactory.securableUserPrincipal(),
TestDataFactory.securableUserPrincipal()
)
)
)
}
} | gpl-3.0 |
jpmoreto/play-with-robots | android/app/src/main/java/jpm/android/ui/ConfigureFragment.kt | 1 | 985 | package jpm.android.ui
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import jpm.android.R
import jpm.android.ui.common.BaseFragment
class ConfigureFragment : BaseFragment() {
override fun getName(context: Context): String = context.getString(R.string.section_configure)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.fragment_configure, container, false)
val textDirection = rootView.findViewById(R.id.section_label_direction) as TextView
textDirection.setTextColor(Color.BLACK)
val textVelocity = rootView.findViewById(R.id.section_label_velocity) as TextView
textVelocity.setTextColor(Color.BLACK)
return rootView
}
}
| mit |
blackbbc/Tucao | app/src/main/kotlin/me/sweetll/tucao/business/home/viewmodel/MessageDetailViewModel.kt | 1 | 3650 | package me.sweetll.tucao.business.home.viewmodel
import androidx.databinding.ObservableField
import android.view.View
import com.trello.rxlifecycle2.kotlin.bindToLifecycle
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import me.sweetll.tucao.base.BaseViewModel
import me.sweetll.tucao.business.home.MessageDetailActivity
import me.sweetll.tucao.business.home.model.MessageDetail
import me.sweetll.tucao.di.service.ApiConfig
import me.sweetll.tucao.extension.NonNullObservableField
import me.sweetll.tucao.extension.toast
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import java.text.SimpleDateFormat
import java.util.*
class MessageDetailViewModel(val activity: MessageDetailActivity, val id: String, val _username: String, val _avatar: String): BaseViewModel() {
val message = NonNullObservableField<String>("")
fun loadData() {
rawApiService.readMessageDetail(id)
.bindToLifecycle(activity)
.subscribeOn(Schedulers.io())
.retryWhen(ApiConfig.RetryWithDelay())
.map {
parseMessageDetail(Jsoup.parse(it.string()))
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
activity.onLoadData(it)
}, {
error ->
error.printStackTrace()
})
}
fun parseMessageDetail(doc: Document): MutableList<MessageDetail> {
val table_right = doc.selectFirst("td.tableright")
val divs = table_right.child(3).children()
val res = mutableListOf<MessageDetail>()
for (index in 0 until divs.size / 3) {
val div1 = divs[3 * index]
val div2 = divs[3 * index + 1]
val class_name = div1.className()
val type = if ("userpicr" in class_name) MessageDetail.TYPE_RIGHT else MessageDetail.TYPE_LEFT
val message = div2.ownText().trim()
val time = div2.selectFirst("div.time").text()
val avatar = if (type == MessageDetail.TYPE_LEFT) _avatar else user.avatar
res.add(MessageDetail(avatar, message, time, type))
}
return res
}
fun onClickSendMessage(view: View) {
val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
activity.addMessage(MessageDetail(user.avatar, message.get(), sdf.format(Date()), MessageDetail.TYPE_RIGHT))
rawApiService.replyMessage(message.get(), id, user.name)
.bindToLifecycle(activity)
.doOnNext {
message.set("")
}
.subscribeOn(Schedulers.io())
.retryWhen(ApiConfig.RetryWithDelay())
.map { parseSendResult(Jsoup.parse(it.string())) }
.flatMap {
(code, msg) ->
if (code == 0) {
Observable.just(Object())
} else {
Observable.error(Error(msg))
}
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
//
}, {
error ->
error.printStackTrace()
error.localizedMessage.toast()
})
}
fun parseSendResult(doc: Document): Pair<Int, String> {
val content = doc.body().text()
return if ("成功" in content) {
Pair(0, "")
} else {
Pair(1, content)
}
}
} | mit |
strooooke/quickfit | app/src/main/java/com/lambdasoup/quickfit/alarm/AlarmService.kt | 1 | 8576 | /*
* Copyright 2016-2019 Juliane Lehmann <[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 com.lambdasoup.quickfit.alarm
import android.app.*
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.os.PowerManager
import androidx.core.app.NotificationCompat
import com.lambdasoup.quickfit.Constants
import com.lambdasoup.quickfit.Constants.PENDING_INTENT_WORKOUT_LIST
import com.lambdasoup.quickfit.R
import com.lambdasoup.quickfit.persist.QuickFitContentProvider
import com.lambdasoup.quickfit.ui.WorkoutListActivity
import com.lambdasoup.quickfit.util.WakefulIntents
import timber.log.Timber
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
/**
* ForegroundService, handling alarm-related background I/O work. Could also have been solved as a [androidx.core.app.JobIntentService],
* or as a collection of jobs for [androidx.work.WorkManager], but (a) reading the documentation says that JobScheduler is for _deferrable_
* I/O work, which this is not - and also no promises are given as to the timeliness of the execution of JobScheduler jobs that are free
* of restrictions. Although it seems to be fine in practice (on non-background crippling devices). Also (b) - just for trying it out.
* Currently, this project serves as an exhibition of different ways of performing background work.
*/
class AlarmService : Service() {
private val alarms by lazy { Alarms(this.applicationContext) }
private val runWakeLock by lazy {
(getSystemService(Context.POWER_SERVICE) as PowerManager)
.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, AlarmService::class.java.canonicalName)
}
private lateinit var executor: ExecutorService
override fun onCreate() {
super.onCreate()
executor = Executors.newFixedThreadPool(2)
}
override fun onDestroy() {
executor.shutdownNow()
super.onDestroy()
}
override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
@Suppress("ReplaceGuardClauseWithFunctionCall") // IDE fails then, demands wrong type. New type inference at fault?
if (intent == null) throw IllegalArgumentException("Should never receive null intents because of START_REDELIVER_INTENT")
startForeground(Constants.NOTIFICATION_ALARM_BG_IO_WORK, buildForegroundNotification())
runWakeLock.acquire(TimeUnit.SECONDS.toMillis(30))
WakefulIntents.completeWakefulIntent(intent)
Timber.d("Done with wakelock handover and foreground start, about to enqueue intent processing. intent=$intent")
executor.submit {
try {
fun getScheduleId() = QuickFitContentProvider.getScheduleIdFromUriOrThrow(intent.data!!)
when (intent.action) {
ACTION_SNOOZE -> alarms.onSnoozed(getScheduleId())
ACTION_DIDIT -> {
val workoutId = QuickFitContentProvider.getWorkoutIdFromUriOrThrow(intent.data!!)
alarms.onDidIt(getScheduleId(), workoutId)
}
ACTION_ON_NOTIFICATION_SHOWN -> alarms.onNotificationShown(getScheduleId())
ACTION_ON_NOTIFICATION_DISMISSED -> alarms.onNotificationDismissed(getScheduleId())
ACTION_ON_SCHEDULE_CHANGED -> alarms.onScheduleChanged(getScheduleId())
ACTION_ON_SCHEDULE_DELETED -> alarms.onScheduleDeleted(getScheduleId())
ACTION_TIME_DISCONTINUITY -> alarms.resetAlarms()
else -> throw IllegalArgumentException("Unknown action: ${intent.action}")
}
} catch (e: Throwable) {
Timber.e(e, "Failed to execute $intent")
} finally {
runWakeLock.release()
stopSelf(startId)
}
}
return START_REDELIVER_INTENT
}
private fun buildForegroundNotification(): Notification =
NotificationCompat.Builder(this, Constants.NOTIFICATION_CHANNEL_ID_BG_IO)
.setContentTitle(getString(R.string.notification_alarm_bg_io_title))
.setContentText(getString(R.string.notification_alarm_bg_io_content))
.setContentIntent(
PendingIntent.getActivity(
this,
PENDING_INTENT_WORKOUT_LIST,
Intent(this, WorkoutListActivity::class.java),
PendingIntent.FLAG_UPDATE_CURRENT)
)
.build()
companion object {
private const val ACTION_SNOOZE = "com.lambdasoup.quickfit.alarm.ACTION_SNOOZE"
private const val ACTION_DIDIT = "com.lambdasoup.quickfit.alarm.ACTION_DIDIT"
private const val ACTION_ON_NOTIFICATION_SHOWN = "com.lambdasoup.quickfit.alarm.ACTION_ON_NOTIFICATION_SHOWN"
private const val ACTION_ON_NOTIFICATION_DISMISSED = "com.lambdasoup.quickfit.alarm.ACTION_ON_NOTIFICATION_DISMISSED"
private const val ACTION_ON_SCHEDULE_CHANGED = "com.lambdasoup.quickfit.alarm.ACTION_ON_SCHEDULE_CHANGED"
private const val ACTION_ON_SCHEDULE_DELETED = "com.lambdasoup.quickfit.alarm.ACTION_ON_SCHEDULE_DELETED"
private const val ACTION_TIME_DISCONTINUITY = "com.lambdasoup.quickfit.alarm.ACTION_TIME_DISCONTINUITY"
fun getSnoozeIntent(context: Context, scheduleId: Long) =
Intent(context, AlarmService::class.java)
.setData(QuickFitContentProvider.getUriSchedulesId(scheduleId))
.setAction(ACTION_SNOOZE)
fun getDidItIntent(context: Context, workoutId: Long, scheduleId: Long) =
Intent(context, AlarmService::class.java)
.setData(QuickFitContentProvider.getUriWorkoutsIdSchedulesId(workoutId, scheduleId))
.setAction(ACTION_DIDIT)
fun getOnNotificationShownIntent(context: Context, scheduleId: Long) =
Intent(context, AlarmService::class.java)
.setData(QuickFitContentProvider.getUriSchedulesId(scheduleId))
.setAction(ACTION_ON_NOTIFICATION_SHOWN)
fun getOnNotificationDismissedIntent(context: Context, scheduleId: Long) =
Intent(context, AlarmService::class.java)
.setData(QuickFitContentProvider.getUriSchedulesId(scheduleId))
.setAction(ACTION_ON_NOTIFICATION_DISMISSED)
fun getOnScheduleChangedIntent(context: Context, scheduleId: Long) =
Intent(context, AlarmService::class.java)
.setData(QuickFitContentProvider.getUriSchedulesId(scheduleId))
.setAction(ACTION_ON_SCHEDULE_CHANGED)
fun getOnScheduleDeletedIntent(context: Context, scheduleId: Long) =
Intent(context, AlarmService::class.java)
.setData(QuickFitContentProvider.getUriSchedulesId(scheduleId))
.setAction(ACTION_ON_SCHEDULE_DELETED)
fun getOnBootCompletedIntent(context: Context) =
Intent(context, AlarmService::class.java)
.setAction(ACTION_TIME_DISCONTINUITY)
fun initNotificationChannels(context: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val bgIoChannel = NotificationChannel(
Constants.NOTIFICATION_CHANNEL_ID_BG_IO,
context.getString(R.string.notification_channel_bg_io_name),
NotificationManager.IMPORTANCE_LOW
)
context.getSystemService(NotificationManager::class.java)!!.createNotificationChannel(bgIoChannel)
}
}
}
}
| apache-2.0 |
Bodo1981/swapi.co | app/src/main/java/com/christianbahl/swapico/list/rx/AddLoadMore.kt | 1 | 319 | package com.christianbahl.swapico.list.rx
import com.christianbahl.swapico.list.model.ILoadMoreList
import rx.functions.Func1
/**
* @author Christian Bahl
*/
class AddLoadMore<M: ILoadMoreList> : Func1<M, M> {
override fun call(t: M): M {
if (t.loadMore) {
t.addLoadMoreRow()
}
return t
}
} | apache-2.0 |
joan-domingo/Podcasts-RAC1-Android | app/src/main/java/cat/xojan/random1/domain/model/MediaDescriptionCompatJson.kt | 1 | 434 | package cat.xojan.random1.domain.model
import java.util.*
class MediaDescriptionCompatJson(
val id: String?,
val title: String,
val mediaUrl: String?,
val iconUrl: String?,
val state: PodcastState,
val downloadReference: Long?,
val mediaFilePath: String?,
val programId: String?,
val bigImageUrl: String?,
val duration: Long?,
val date: Date?
) | mit |
afollestad/material-dialogs | sample/src/debug/java/com/afollestad/materialdialogssample/SampleApp.kt | 2 | 943 | /**
* Designed and developed by Aidan Follestad (@afollestad)
*
* 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.afollestad.materialdialogssample
import android.app.Application
import leakcanary.LeakCanary
/** @author Aidan Follestad (afollestad) */
class SampleApp : Application() {
override fun onCreate() {
super.onCreate()
LeakCanary.config = LeakCanary.config.copy(retainedVisibleThreshold = 3)
}
}
| apache-2.0 |
yuyashuai/SurfaceViewFrameAnimation | frameanimation/src/main/java/com/yuyashuai/frameanimation/FrameAnimationSurfaceView.kt | 1 | 2028 | package com.yuyashuai.frameanimation
import android.content.Context
import android.util.AttributeSet
import android.view.SurfaceView
import android.view.View
/**
* the frame animation view to handle the animation life circle
* @see SurfaceView
* @author yuyashuai 2019-05-16.
*/
class FrameAnimationSurfaceView private constructor(context: Context, attributeSet: AttributeSet?, defStyle: Int, val animation: FrameAnimation)
: SurfaceView(context, attributeSet, defStyle), AnimationController by animation {
constructor(context: Context, attributeSet: AttributeSet?, defStyle: Int)
: this(context, attributeSet, defStyle, FrameAnimation(context))
constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0)
constructor(context: Context) : this(context, null)
private var lastStopIndex = 0
private var lastStopPaths: MutableList<FrameAnimation.PathData>? = null
/**
* whether to resume playback
*/
var restoreEnable = true
init {
animation.bindView(this)
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
saveAndStop()
}
/**
* stop the animation, save the index when the animation stops playing
*/
private fun saveAndStop() {
lastStopPaths = animation.mPaths
lastStopIndex = stopAnimation()
}
/**
* resume animation
*/
private fun restoreAndStart() {
if (lastStopPaths != null && restoreEnable) {
playAnimation(lastStopPaths!!, lastStopIndex)
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
restoreAndStart()
}
override fun onVisibilityChanged(changedView: View, visibility: Int) {
super.onVisibilityChanged(changedView, visibility)
if (visibility == View.GONE || visibility == View.INVISIBLE) {
saveAndStop()
} else if (visibility == View.VISIBLE) {
restoreAndStart()
}
}
} | apache-2.0 |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/libanki/importer/BackendCsvImportV16.kt | 1 | 1730 | /***************************************************************************************
* Copyright (c) 2022 Ankitects Pty Ltd <http://apps.ankiweb.net> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.libanki.importer
import com.ichi2.libanki.CollectionV16
// These take and return bytes that the frontend TypeScript code will encode/decode.
fun CollectionV16.getCsvMetadataRaw(input: ByteArray): ByteArray {
return backend.getCsvMetadataRaw(input)
}
fun CollectionV16.importCsvRaw(input: ByteArray): ByteArray {
return backend.importCsvRaw(input)
}
| gpl-3.0 |
rock3r/detekt | detekt-sample-extensions/src/main/kotlin/io/gitlab/arturbosch/detekt/sample/extensions/rules/TooManyFunctions.kt | 1 | 1275 | package io.gitlab.arturbosch.detekt.sample.extensions.rules
import io.gitlab.arturbosch.detekt.api.CodeSmell
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.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedFunction
/**
* This is a sample rule reporting too many functions inside a file.
*/
class TooManyFunctions : Rule() {
override val issue = Issue(
javaClass.simpleName,
Severity.CodeSmell,
"This rule reports a file with an excessive function count.",
Debt.TWENTY_MINS
)
private var amount: Int = 0
override fun visitKtFile(file: KtFile) {
super.visitKtFile(file)
if (amount > THRESHOLD) {
report(CodeSmell(issue, Entity.from(file),
message = "The file ${file.name} has $amount function declarations. " +
"Threshold is specified with $THRESHOLD."))
}
amount = 0
}
override fun visitNamedFunction(function: KtNamedFunction) {
super.visitNamedFunction(function)
amount++
}
}
const val THRESHOLD = 10
| apache-2.0 |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/osm/edits/update_tags/StringMapEntryChange.kt | 1 | 1806 | package de.westnordost.streetcomplete.data.osm.edits.update_tags
import kotlinx.serialization.Serializable
@Serializable
sealed class StringMapEntryChange {
abstract override fun toString(): String
abstract override fun equals(other: Any?): Boolean
abstract override fun hashCode(): Int
abstract fun conflictsWith(map: Map<String, String>): Boolean
abstract fun applyTo(map: MutableMap<String, String>)
abstract fun reversed(): StringMapEntryChange
}
@Serializable
data class StringMapEntryAdd(val key: String, val value: String) : StringMapEntryChange() {
override fun toString() = "ADD \"$key\"=\"$value\""
override fun conflictsWith(map: Map<String, String>) = map.containsKey(key) && map[key] != value
override fun applyTo(map: MutableMap<String, String>) { map[key] = value }
override fun reversed() = StringMapEntryDelete(key, value)
}
@Serializable
data class StringMapEntryModify(val key: String, val valueBefore: String, val value: String) : StringMapEntryChange() {
override fun toString() = "MODIFY \"$key\"=\"$valueBefore\" -> \"$key\"=\"$value\""
override fun conflictsWith(map: Map<String, String>) = map[key] != valueBefore && map[key] != value
override fun applyTo(map: MutableMap<String, String>) { map[key] = value }
override fun reversed() = StringMapEntryModify(key, value, valueBefore)
}
@Serializable
data class StringMapEntryDelete(val key: String, val valueBefore: String) : StringMapEntryChange() {
override fun toString() = "DELETE \"$key\"=\"$valueBefore\""
override fun conflictsWith(map: Map<String, String>) = map.containsKey(key) && map[key] != valueBefore
override fun applyTo(map: MutableMap<String, String>) { map.remove(key) }
override fun reversed() = StringMapEntryAdd(key, valueBefore)
}
| gpl-3.0 |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/viewmodel/HotnessViewModel.kt | 1 | 1217 | package com.boardgamegeek.ui.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import com.boardgamegeek.entities.HotGameEntity
import com.boardgamegeek.entities.RefreshableResource
import com.boardgamegeek.repository.HotnessRepository
import com.boardgamegeek.repository.PlayRepository
import kotlinx.coroutines.launch
class HotnessViewModel(application: Application) : AndroidViewModel(application) {
private val repository = HotnessRepository(getApplication())
private val playRepository = PlayRepository(getApplication())
val hotness: LiveData<RefreshableResource<List<HotGameEntity>>> = liveData {
try {
emit(RefreshableResource.refreshing(latestValue?.data))
val games = repository.getHotness()
emit(RefreshableResource.success(games))
} catch (e: Exception) {
emit(RefreshableResource.error(e, application))
}
}
fun logQuickPlay(gameId: Int, gameName: String) {
viewModelScope.launch {
playRepository.logQuickPlay(gameId, gameName)
}
}
}
| gpl-3.0 |
wzhxyz/ACManager | src/main/java/com/zzkun/util/prob/PbDiffCalcer.kt | 1 | 1208 | package com.zzkun.util.prob
import com.zzkun.dao.ExtOjPbInfoRepo
import com.zzkun.dao.UserACPbRepo
import com.zzkun.model.OJType
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.util.*
/**
* Created by Administrator on 2017/2/26 0026.
*/
@Component
open class PbDiffCalcer(
@Autowired private val extOjPbInfoRepo: ExtOjPbInfoRepo,
@Autowired private val userACPbRepo: UserACPbRepo) {
fun calcPbDiff(ojName: OJType, pbId: String, pbNum: String): Double {
// val info = extOjPbInfoRepo.findByOjNameAndPid(ojName, pbId)
// val weAC = userACPbRepo.countByOjNameAndOjPbId(ojName, pbNum)
// val res = (DEFAULT_MAX - log(1.0 + info.dacu)) / log(1.7 + weAC)
// println("${ojName},${pbId},${pbNum},${info.dacu},${info.ac},${weAC}")
// return res
return 1.0;
}
fun allPbDiff(): HashMap<String, Double> {
val res = HashMap<String, Double>()
val list = extOjPbInfoRepo.findAll()
list.forEach {
res["${it.num}@${it.ojName}"] = calcPbDiff(it.ojName, it.pid, it.num)
}
return res
}
} | gpl-3.0 |
devmil/PaperLaunch | app/src/main/java/de/devmil/paperlaunch/view/LauncherView.kt | 1 | 17351 | /*
* Copyright 2015 Devmil Solutions
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.devmil.paperlaunch.view
import android.animation.Animator
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Rect
import android.support.v4.content.ContextCompat
import android.util.AttributeSet
import android.util.Log
import android.util.TypedValue
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import java.io.InvalidClassException
import java.util.ArrayList
import de.devmil.paperlaunch.R
import de.devmil.paperlaunch.model.IEntry
import de.devmil.paperlaunch.model.IFolder
import de.devmil.paperlaunch.config.LaunchConfig
import de.devmil.paperlaunch.model.Launch
import de.devmil.paperlaunch.utils.PositionAndSizeEvaluator
import de.devmil.paperlaunch.view.utils.ViewUtils
import de.devmil.paperlaunch.view.utils.ColorUtils
import de.devmil.paperlaunch.view.widgets.VerticalTextView
class LauncherView : RelativeLayout {
private var viewModel: LauncherViewModel? = null
private val laneViews = ArrayList<LaunchLaneView>()
private var background: RelativeLayout? = null
private var neutralZone: LinearLayout? = null
private var neutralZoneBackground: LinearLayout? = null
private var neutralZoneBackgroundImage: ImageView? = null
private var neutralZoneBackgroundAppNameText: VerticalTextView? = null
private var listener: ILauncherViewListener? = null
private var autoStartMotionEvent: MotionEvent? = null
private var currentlySelectedItem: IEntry? = null
interface ILauncherViewListener {
fun onFinished()
}
constructor(context: Context) : super(context) {
construct()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
construct()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
construct()
}
fun doInitialize(config: LaunchConfig) {
buildViewModel(config)
}
private fun start() {
buildViews()
transitToState(LauncherViewModel.State.Init)
transitToState(LauncherViewModel.State.Initializing)
}
fun setListener(listener: ILauncherViewListener) {
this.listener = listener
}
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
super.onLayout(changed, l, t, r, b)
autoStartMotionEvent?.let {
start()
onTouchEvent(it)
autoStartMotionEvent = null
}
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
return super.onTouchEvent(event) || handleTouchEvent(event.action, event.x, event.y)
}
fun handleTouchEvent(action: Int, x: Float, y: Float): Boolean {
return laneViews.fold(false) { currentResult, laneView ->
sendIfMatches(laneView, action, x, y) || currentResult
}
}
fun doAutoStart(firstMotionEvent: MotionEvent) {
autoStartMotionEvent = firstMotionEvent
}
private fun construct() {
ViewUtils.disableClipping(this)
}
private fun buildViewModel(config: LaunchConfig) {
viewModel = LauncherViewModel(config)
}
private val laneIds: IntArray
get() = intArrayOf(
R.id.id_launchview_lane1,
R.id.id_launchview_lane2,
R.id.id_launchview_lane3,
R.id.id_launchview_lane4,
R.id.id_launchview_lane5,
R.id.id_launchview_lane6,
R.id.id_launchview_lane7,
R.id.id_launchview_lane8,
R.id.id_launchview_lane9,
R.id.id_launchview_lane10,
R.id.id_launchview_lane11,
R.id.id_launchview_lane12,
R.id.id_launchview_lane13)
private fun buildViews() {
removeAllViews()
laneViews.clear()
addBackground()
addNeutralZone()
val laneIds = laneIds
val localNeutralZone = neutralZone!!
val localNeutralZoneBackground = neutralZoneBackground!!
val localViewModel = viewModel!!
laneIds.indices.fold(localNeutralZone.id) { current, i ->
addLaneView(i, current).id
}
setEntriesToLane(laneViews[0], localViewModel.entries)
laneViews.indices.reversed().forEach { i ->
laneViews[i].bringToFront()
}
localNeutralZone.bringToFront()
localNeutralZoneBackground.bringToFront()
}
private fun addLaneView(laneIndex: Int, anchorId: Int): LaunchLaneView {
val laneIds = laneIds
val id = laneIds[laneIndex]
val llv = LaunchLaneView(context)
llv.id = id
val localViewModel = viewModel!!
val params = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
params.addRule(RelativeLayout.ALIGN_PARENT_TOP)
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
if (localViewModel.isOnRightSide)
params.addRule(RelativeLayout.LEFT_OF, anchorId)
else
params.addRule(RelativeLayout.RIGHT_OF, anchorId)
addView(llv, params)
laneViews.add(llv)
llv.setLaneListener(object : LaunchLaneView.ILaneListener {
override fun onItemSelected(selectedItem: IEntry?) {
currentlySelectedItem = selectedItem
if (selectedItem == null) {
return
}
if (selectedItem.isFolder) {
val f = selectedItem as IFolder
if (laneViews.size <= laneIndex + 1) {
return
}
val nextLaneView = laneViews[laneIndex + 1]
setEntriesToLane(nextLaneView, f.subEntries.orEmpty())
nextLaneView.start()
}
}
override fun onItemSelecting(selectedItem: IEntry?) {
currentlySelectedItem = selectedItem
}
override fun onStateChanged(oldState: LaunchLaneViewModel.State, newState: LaunchLaneViewModel.State) {
if (newState === LaunchLaneViewModel.State.Focusing) {
for (idx in laneIndex + 1 until laneViews.size) {
laneViews[idx].stop()
}
}
}
})
return llv
}
private fun setEntriesToLane(laneView: LaunchLaneView, entries: List<IEntry>) {
val localViewModel = viewModel!!
val entryModels = entries.map { LaunchEntryViewModel.createFrom(context, it, viewModel!!.entryConfig) }
val vm = LaunchLaneViewModel(entryModels, localViewModel.laneConfig)
laneView.doInitializeData(vm)
}
private fun addBackground() {
val localViewModel = viewModel!!
val localBackground = RelativeLayout(context)
localBackground.setBackgroundColor(localViewModel.backgroundColor)
localBackground.alpha = 0f
background = localBackground
val params = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
params.addRule(RelativeLayout.ALIGN_PARENT_TOP)
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT)
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
addView(localBackground, params)
}
private fun addNeutralZone() {
val localViewModel = viewModel!!
val localNeutralZone = LinearLayout(context)
localNeutralZone.id = R.id.id_launchview_neutralzone
localNeutralZone.minimumWidth = ViewUtils.getPxFromDip(context, localViewModel.neutralZoneWidthDip).toInt()
localNeutralZone.isClickable = false
val params = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
params.addRule(RelativeLayout.ALIGN_PARENT_TOP)
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
if (localViewModel.isOnRightSide) {
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
}
else {
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT)
}
addView(localNeutralZone, params)
val localNeutralZoneBackground = LinearLayout(context)
localNeutralZoneBackground.setBackgroundColor(localViewModel.designConfig.frameDefaultColor)
localNeutralZoneBackground.elevation = ViewUtils.getPxFromDip(context, localViewModel.highElevationDip)
localNeutralZoneBackground.isClickable = false
localNeutralZoneBackground.orientation = LinearLayout.VERTICAL
localNeutralZoneBackground.gravity = Gravity.CENTER_HORIZONTAL
val backParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
)
localNeutralZone.addView(localNeutralZoneBackground, backParams)
if(localViewModel.laneConfig.showLogo) {
val localNeutralZoneBackgroundImage = ImageView(context)
localNeutralZoneBackgroundImage.setImageResource(R.mipmap.ic_launcher)
localNeutralZoneBackgroundImage.isClickable = false
localNeutralZoneBackgroundImage.visibility = View.GONE
val backImageParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
backImageParams.setMargins(0, ViewUtils.getPxFromDip(context, localViewModel.laneConfig.laneIconTopMarginDip).toInt(), 0, 0)
localNeutralZoneBackground.addView(localNeutralZoneBackgroundImage, backImageParams)
val localNeutralZoneBackgroundAppNameText = VerticalTextView(context)
localNeutralZoneBackgroundAppNameText.visibility = View.GONE
localNeutralZoneBackgroundAppNameText.setTextSize(TypedValue.COMPLEX_UNIT_SP, localViewModel.itemNameTextSizeSP)
//this is needed because the parts in the system run with another theme than the application parts
localNeutralZoneBackgroundAppNameText.setTextColor(ContextCompat.getColor(context, R.color.name_label))
localNeutralZoneBackgroundAppNameText.setText(R.string.app_name)
localNeutralZoneBackgroundAppNameText.visibility = View.GONE
val backTextParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
backTextParams.setMargins(0, ViewUtils.getPxFromDip(context, localViewModel.laneConfig.laneTextTopMarginDip).toInt(), 0, 0)
localNeutralZoneBackground.addView(localNeutralZoneBackgroundAppNameText, backTextParams)
localNeutralZoneBackground.setBackgroundColor(
ColorUtils.getBackgroundColorFromImage(
resources.getDrawable(
R.mipmap.ic_launcher,
context.theme
),
localViewModel.frameDefaultColor))
neutralZoneBackgroundImage = localNeutralZoneBackgroundImage
neutralZoneBackgroundAppNameText = localNeutralZoneBackgroundAppNameText
} else {
neutralZoneBackgroundImage = null
neutralZoneBackgroundAppNameText = null
}
neutralZone = localNeutralZone
neutralZoneBackground = localNeutralZoneBackground
}
private fun sendIfMatches(laneView: LaunchLaneView, action: Int, x: Float, y: Float): Boolean {
val laneX = (x - laneView.x).toInt()
val laneY = (y - laneView.y).toInt()
laneView.doHandleTouch(action, laneX, laneY)
if (action == MotionEvent.ACTION_UP) {
launchAppIfSelected()
listener?.onFinished()
}
return true
}
private fun launchAppIfSelected() {
if (currentlySelectedItem?.isFolder != false) {
return
}
val l = currentlySelectedItem as Launch?
val intent = l?.launchIntent
intent?.let {
it.flags = it.flags or Intent.FLAG_ACTIVITY_NEW_TASK
}
try {
context.startActivity(intent)
} catch (e: Exception) {
Log.e(TAG, "Error while launching app", e)
}
}
private fun transitToState(newState: LauncherViewModel.State) {
when (newState) {
LauncherViewModel.State.Init -> {
hideBackground()
hideNeutralZone()
}
LauncherViewModel.State.Initializing -> {
animateBackground()
animateNeutralZone()
}
LauncherViewModel.State.Ready -> startLane()
}
viewModel!!.state = newState
}
private fun startLane() {
laneViews[0].start()
}
private fun hideBackground() {
background?.alpha = 0f
}
private fun hideNeutralZone() {
neutralZoneBackground?.visibility = View.INVISIBLE
}
private fun animateBackground() {
if (viewModel?.showBackground == true) {
val localBackground = background!!
val localViewModel = viewModel!!
localBackground.visibility = View.VISIBLE
localBackground
.animate()
.alpha(localViewModel.backgroundAlpha)
.setDuration(localViewModel.backgroundAnimationDurationMS.toLong())
.start()
} else {
background?.visibility = View.GONE
}
}
private fun animateNeutralZone() {
val localViewModel = viewModel!!
val size = localViewModel.neutralZoneWidthDip
val fromLeft = if (localViewModel.isOnRightSide) width - size.toInt() else 0
var fromTop = (height - size.toInt()) / 2
if (autoStartMotionEvent != null) {
fromTop = Math.min(
height - size.toInt(),
autoStartMotionEvent!!.y.toInt()
)
}
val fromRight = fromLeft + size.toInt()
val fromBottom = fromTop + size.toInt()
val fromRect = Rect(
fromLeft,
fromTop,
fromRight,
fromBottom
)
val toRect = Rect(
fromLeft,
0,
fromRight,
height
)
val anim: ObjectAnimator?
try {
anim = ObjectAnimator.ofObject(
neutralZoneBackground,
"margins",
PositionAndSizeEvaluator(neutralZoneBackground!!),
fromRect,
toRect)
anim.addListener(object : Animator.AnimatorListener {
override fun onAnimationStart(animation: Animator) {
neutralZoneBackground?.visibility = View.VISIBLE
}
override fun onAnimationEnd(animation: Animator) {
Thread(Runnable {
try {
Thread.sleep(100)
} catch (e: InterruptedException) {
}
neutralZoneBackground?.post { transitToState(LauncherViewModel.State.Ready) }
}).start()
}
override fun onAnimationCancel(animation: Animator) {}
override fun onAnimationRepeat(animation: Animator) {}
})
anim.duration = localViewModel.launcherInitAnimationDurationMS.toLong()
anim.start()
Thread(Runnable {
try {
Thread.sleep((localViewModel.launcherInitAnimationDurationMS / 2).toLong())
neutralZoneBackgroundImage?.post {
neutralZoneBackgroundImage!!.visibility = View.VISIBLE
neutralZoneBackgroundAppNameText!!.visibility = View.VISIBLE
}
} catch (e: InterruptedException) {
}
}).start()
} catch (e: InvalidClassException) {
e.printStackTrace()
}
}
companion object {
private val TAG = LauncherView::class.java.simpleName
}
}
| apache-2.0 |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/lang/commands/Argument.kt | 1 | 1356 | package nl.hannahsten.texifyidea.lang.commands
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionProvider
import nl.hannahsten.texifyidea.completion.LatexBibliographyStyleProvider
import nl.hannahsten.texifyidea.completion.LatexListTypeProvider
/**
* @author Sten Wessel
*/
abstract class Argument @JvmOverloads protected constructor(val name: String, val type: Type = Type.NORMAL) {
abstract override fun toString(): String
/**
* @author Hannah Schellekens, Sten Wessel
*/
enum class Type(
/**
* Provides the autocomplete options for the argument of this type.
* `null` for no autocomplete options.
*/
val completionProvider: CompletionProvider<CompletionParameters>? = null
) {
/**
* Can contain any kind of argument content.
*/
NORMAL,
/**
* Contains a path/reference to a file.
*/
FILE,
/**
* Text contents.
*/
TEXT,
/**
* Contains a bibliography style.
*/
BIBLIOGRAPHY_STYLE(completionProvider = LatexBibliographyStyleProvider),
/**
* enumerate, itemize, etc.
*/
LIST_ENVIRONMENT(completionProvider = LatexListTypeProvider),
}
}
| mit |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/templates/BibtexContext.kt | 1 | 416 | package nl.hannahsten.texifyidea.templates
import com.intellij.codeInsight.template.TemplateActionContext
import com.intellij.codeInsight.template.TemplateContextType
import nl.hannahsten.texifyidea.file.BibtexFile
/**
* @author Hannah Schellekens
*/
open class BibtexContext : TemplateContextType("BIBTEX", "BibTeX") {
override fun isInContext(context: TemplateActionContext) = context.file is BibtexFile
} | mit |
jeffersonvenancio/BarzingaNow | android/app/src/main/java/com/barzinga/util/ImageExtensions.kt | 1 | 454 | package com.barzinga.util
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import jp.wasabeef.glide.transformations.CropCircleTransformation
/**
* Created by rafaela.araujo on 08/11/17.
*/
fun ImageView.loadUrl(photoUrl: String?){
Glide.with(this)
.load(photoUrl)
.apply(RequestOptions.bitmapTransform(CropCircleTransformation()))
.into(this)
}
| apache-2.0 |
i7c/cfm | server/recorder/src/main/kotlin/org/rliz/cfm/recorder/common/security/CfmAuthProvider.kt | 1 | 2134 | package org.rliz.cfm.recorder.common.security
import org.rliz.cfm.recorder.user.boundary.UserBoundary
import org.rliz.cfm.recorder.user.data.User
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.authentication.AuthenticationProvider
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.stereotype.Component
import org.springframework.transaction.annotation.Transactional
@Component
class CfmAuthProvider : AuthenticationProvider {
@Autowired
private lateinit var userBoundary: UserBoundary
private val encoder = BCryptPasswordEncoder()
@Transactional
override fun authenticate(authentication: Authentication?): Authentication {
if (authentication == null) throw BadCredentialsException("Internal error")
val name = authentication.name
val password = authentication.credentials.toString()
if (name.isEmpty()) throw BadCredentialsException("Provide a username")
if (password.isEmpty()) throw BadCredentialsException("Provide a password")
return regularUserLogin(name, password)
}
private fun regularUserLogin(name: String, password: String): Authentication {
userBoundary.findUserByName(name)?.let {
if (encoder.matches(password, it.password)) {
return UsernamePasswordAuthenticationToken(it, "removed", determineRoles(it))
}
}
throw BadCredentialsException("Bad credentials")
}
override fun supports(authentication: Class<*>?): Boolean =
authentication!!.isAssignableFrom(UsernamePasswordAuthenticationToken::class.java)
}
fun determineRoles(u: User) = (if (u.systemUser) listOf(SimpleGrantedAuthority("ROLE_ADMIN")) else emptyList())
.plus(SimpleGrantedAuthority("ROLE_USER"))
| gpl-3.0 |
danrien/projectBlueWater | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/browsing/remote/NowPlayingMediaItemLookup.kt | 1 | 809 | package com.lasthopesoftware.bluewater.client.browsing.remote
import android.support.v4.media.MediaBrowserCompat
import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.storage.INowPlayingRepository
import com.namehillsoftware.handoff.promises.Promise
class NowPlayingMediaItemLookup(
private val nowPlayingRepository: INowPlayingRepository,
private val mediaItemServiceFileLookup: GetMediaItemsFromServiceFiles,
) : GetNowPlayingMediaItem {
override fun promiseNowPlayingItem(): Promise<MediaBrowserCompat.MediaItem?> =
nowPlayingRepository
.nowPlaying
.eventually { np ->
if (np.playlist.isEmpty() || np.playlistPosition < 0) Promise.empty<MediaBrowserCompat.MediaItem?>()
else mediaItemServiceFileLookup.promiseMediaItemWithImage(np.playlist[np.playlistPosition])
}
}
| lgpl-3.0 |
die-tageszeitung/tazapp-android | tazapp/src/main/java/de/thecode/android/tazreader/audio/AudioPlayerService.kt | 1 | 11066 | package de.thecode.android.tazreader.audio
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.IBinder
import android.os.Parcelable
import android.os.PowerManager
import android.widget.Toast
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import androidx.core.graphics.drawable.toBitmap
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.github.ajalt.timberkt.Timber.d
import com.github.ajalt.timberkt.Timber.e
import com.github.ajalt.timberkt.Timber.i
import de.thecode.android.tazreader.R
import de.thecode.android.tazreader.notifications.NotificationUtils
import de.thecode.android.tazreader.start.StartActivity
import kotlinx.android.parcel.Parcelize
import java.io.IOException
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
import kotlin.math.max
class AudioPlayerService : Service(), MediaPlayer.OnCompletionListener, MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnInfoListener, AudioManager.OnAudioFocusChangeListener {
enum class State {
LOADING, PLAYING, PAUSED
}
companion object {
const val EXTRA_AUDIO_ITEM = "audioExtra"
const val ACTION_STATE_CHANGED = "serviceAudioStateChanged"
const val ACTION_POSITION_UPDATE = "serviceAudioPositionChanged"
var instance: AudioPlayerService? = null
}
private var mediaPlayer: MediaPlayer? = null
private var audioManager: AudioManager? = null
private var executor:ScheduledExecutorService? = null
var audioItem: AudioItem? = null
var state: State = State.LOADING
set(value) {
d {"setState $value"}
field = value
val serviceIntent = Intent()
serviceIntent.action = ACTION_STATE_CHANGED
LocalBroadcastManager.getInstance(this)
.sendBroadcast(serviceIntent)
when(value) {
State.PLAYING -> {
if (executor == null) {
executor = Executors.newSingleThreadScheduledExecutor()
executor?.scheduleAtFixedRate({
updatePlayerPosition()
}, 0, 500, TimeUnit.MILLISECONDS)
}
}
else -> {
executor?.shutdown()
executor = null
}
}
}
override fun onBind(intent: Intent?): IBinder? {
TODO("not implemented")
}
override fun onCreate() {
super.onCreate()
instance = this
d {
"XXX SERVICE CREATED"
}
}
override fun onDestroy() {
instance = null
removeAudioFocus()
state = State.LOADING
super.onDestroy()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
d { "onStartCommand $intent" }
intent?.let { onStartIntent ->
val audioItemExtra = onStartIntent.getParcelableExtra<AudioItem>(EXTRA_AUDIO_ITEM)
audioItemExtra?.let {
audioItem = it
if (isPlaying()) {
mediaPlayer?.stop()
mediaPlayer?.release()
mediaPlayer = null
}
initForeground()
//Request audio focus
if (requestAudioFocus()) {
initMediaPlayer()
} else {
Toast.makeText(this, R.string.audio_service_error_gain_focus, Toast.LENGTH_LONG)
.show()
//Could not gain focus
stopSelf()
}
}
}
return super.onStartCommand(intent, flags, startId)
}
private fun initForeground() {
val builder = NotificationCompat.Builder(this, NotificationUtils.AUDIO_CHANNEL_ID)
val title = StringBuilder()
title.append(audioItem!!.title)
builder.setContentTitle(title.toString())
.setContentText(audioItem!!.source)
builder.setWhen(System.currentTimeMillis())
builder.setSmallIcon(R.drawable.ic_audio_notification)
val drawableRes = if (isPlaying()) R.drawable.ic_record_voice_over_black_32dp else R.drawable.ic_pause_black_24dp
val drawable = AppCompatResources.getDrawable(this, drawableRes)
drawable?.let {
var wrappedDrawable = DrawableCompat.wrap(it)
wrappedDrawable = wrappedDrawable.mutate()
DrawableCompat.setTint(wrappedDrawable, ContextCompat.getColor(this, R.color.color_accent))
builder.setLargeIcon(wrappedDrawable.toBitmap())
}
builder.priority = NotificationCompat.PRIORITY_DEFAULT
val intent = Intent(this, StartActivity::class.java)
intent.putExtra(NotificationUtils.NOTIFICATION_EXTRA_BOOKID, audioItem!!.sourceId)
intent.putExtra(NotificationUtils.NOTIFICATION_EXTRA_TYPE_ID, NotificationUtils.AUDIOSERVICE_NOTIFICATION_ID)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
val uniqueInt = (System.currentTimeMillis() and 0xfffffff).toInt()
val contentIntent = PendingIntent.getActivity(this, uniqueInt, intent, PendingIntent.FLAG_UPDATE_CURRENT)
builder.setContentIntent(contentIntent)
val notification = builder.build()
// Start foreground service.
startForeground(1, notification)
}
fun isPlaying(): Boolean {
return try {
mediaPlayer?.isPlaying ?: throw IllegalStateException() //mediaPlayer.isPlaying also throws IllegalstateException
} catch (ex: IllegalStateException) {
false
}
}
private fun initMediaPlayer() {
val mp = MediaPlayer()
mp.setOnBufferingUpdateListener(this)
mp.setOnCompletionListener(this)
mp.setOnErrorListener(this)
mp.setOnPreparedListener(this)
mp.setOnInfoListener(this)
mp.reset()
mp.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK)
mp.setAudioStreamType(AudioManager.STREAM_MUSIC)
try {
mp.setDataSource(audioItem!!.uri)
} catch (ex: IOException) {
e(ex)
stopSelf()
}
state = State.LOADING
mp.prepareAsync()
mediaPlayer = mp
}
fun stopPlaying() {
mediaPlayer?.let {
if (it.isPlaying) {
it.stop()
}
it.release()
}
stopSelf()
}
fun pauseOrResumePlaying() {
d { "pauseOrResumePlaying" }
mediaPlayer?.let { mp ->
if (mp.isPlaying) {
mp.pause()
state = State.PAUSED
audioItem?.let {
it.resumePosition = mp.currentPosition
}
} else {
audioItem?.let {
mp.seekTo(it.resumePosition)
}
mp.start()
state= State.PLAYING
}
initForeground()
}
}
fun seekToPosition(position:Int) {
mediaPlayer?.seekTo(position)
updatePlayerPosition()
}
fun rewind30Seconds() {
mediaPlayer?.let {
val newPos = it.currentPosition - TimeUnit.SECONDS.toMillis(30).toInt()
it.seekTo(max(newPos,0))
updatePlayerPosition()
}
}
private fun updatePlayerPosition() {
mediaPlayer?.let {
audioItem?.resumePosition = it.currentPosition
val timeIntent = Intent()
timeIntent.action = ACTION_POSITION_UPDATE
LocalBroadcastManager.getInstance(this)
.sendBroadcast(timeIntent)
}
}
private fun requestAudioFocus(): Boolean {
val audioManagerService = getSystemService(Context.AUDIO_SERVICE) as AudioManager
audioManager = audioManagerService
val result = audioManagerService.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN)
d { "requestAudioFocus $result" }
return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED
}
private fun removeAudioFocus(): Boolean {
d { "removeAudioFocus" }
audioManager?.let {
return AudioManager.AUDIOFOCUS_REQUEST_GRANTED == it.abandonAudioFocus(this)
} ?: return false
}
override fun onBufferingUpdate(mp: MediaPlayer?, percent: Int) {
d {
"onBufferingUpdate $percent"
}
}
override fun onPrepared(mp: MediaPlayer?) {
d {
"onPrepared duration ${mp?.duration}"
}
mp?.let { audioItem?.duration = mp.duration }
pauseOrResumePlaying()
}
override fun onCompletion(mp: MediaPlayer?) {
d {
"onCompletion"
}
stopPlaying()
}
override fun onError(mp: MediaPlayer?, what: Int, extra: Int): Boolean {
e {
"onError what: $what extra: $extra"
}
return false
}
override fun onInfo(mp: MediaPlayer?, what: Int, extra: Int): Boolean {
i {
"onInfo what: $what extra: $extra"
}
return false
}
override fun onAudioFocusChange(focusChange: Int) {
d { "onAudioFocusChange $focusChange" }
when (focusChange) {
AudioManager.AUDIOFOCUS_GAIN -> {
if (mediaPlayer == null) {
initMediaPlayer()
} else if (!isPlaying()) {
pauseOrResumePlaying()
}
mediaPlayer?.setVolume(1F, 1F)
// resume or start playback
}
AudioManager.AUDIOFOCUS_LOSS -> {
// Lost focus for an unbounded amount of time: stop playback and release media player
stopPlaying()
}
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
// Lost focus for a short time, but we have to stop
// playback. We don't release the media player because playback
// is likely to resume
if (isPlaying()) pauseOrResumePlaying()
}
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {
// Lost focus for a short time, but it's ok to keep playing
if (isPlaying()) mediaPlayer?.setVolume(0.1F, 0.1F)
}
}
}
}
@Parcelize
data class AudioItem(val uri: String, val title: String, val source: String, val sourceId: String, var resumePosition: Int = 0, var duration: Int = 0) : Parcelable | agpl-3.0 |
QuickBlox/quickblox-android-sdk | sample-chat-kotlin/app/src/main/java/com/quickblox/sample/chat/kotlin/ui/dialog/ProgressDialogFragment.kt | 1 | 2496 | package com.quickblox.sample.chat.kotlin.ui.dialog
import android.app.Dialog
import android.app.ProgressDialog
import android.content.DialogInterface
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.quickblox.sample.chat.kotlin.R
private const val ARG_MESSAGE_ID = "message_id"
class ProgressDialogFragment : DialogFragment() {
companion object {
private val TAG = ProgressDialogFragment::class.java.simpleName
fun show(fragmentManager: FragmentManager) {
// We're not using dialogFragment.show() method because we may call this DialogFragment
// in onActivityResult() method and there will be a state loss exception
if (fragmentManager.findFragmentByTag(TAG) == null) {
Log.d(TAG, "fragmentManager.findFragmentByTag(TAG) == null")
val args = Bundle()
args.putInt(ARG_MESSAGE_ID, R.string.dlg_loading)
val dialog = ProgressDialogFragment()
dialog.arguments = args
Log.d(TAG, "newInstance = $dialog")
fragmentManager.beginTransaction().add(dialog, TAG).commitAllowingStateLoss()
}
Log.d(TAG, "backstack = " + fragmentManager.fragments)
}
fun hide(fragmentManager: FragmentManager) {
val fragment = fragmentManager.findFragmentByTag(TAG)
fragment?.let {
fragmentManager.beginTransaction().remove(it).commitAllowingStateLoss()
Log.d(TAG, "fragmentManager.beginTransaction().remove(fragment)$fragment")
}
Log.d(TAG, "backstack = " + fragmentManager.fragments)
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = ProgressDialog(activity)
dialog.setMessage(getString(arguments?.getInt(ARG_MESSAGE_ID) ?: R.string.dlg_loading))
dialog.isIndeterminate = true
dialog.setCancelable(false)
dialog.setCanceledOnTouchOutside(false)
// Disable the back button
val keyListener = DialogInterface.OnKeyListener { dialog,
keyCode,
event ->
keyCode == KeyEvent.KEYCODE_BACK
}
dialog.setOnKeyListener(keyListener)
return dialog
}
} | bsd-3-clause |
GeoffreyMetais/vlc-android | application/live-plot-graph/src/main/java/org/videolan/liveplotgraph/PlotView.kt | 1 | 9662 | /*
* ************************************************************************
* PlotView.kt
* *************************************************************************
* Copyright © 2020 VLC authors and VideoLAN
* Author: Nicolas POMEPUY
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
* **************************************************************************
*
*
*/
package org.videolan.liveplotgraph
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Log
import android.widget.FrameLayout
import org.videolan.tools.dp
import kotlin.math.log10
import kotlin.math.pow
import kotlin.math.round
class PlotView : FrameLayout {
private val textPaint: Paint by lazy {
val p = Paint()
p.color = color
p.textSize = 10.dp.toFloat()
p
}
val data = ArrayList<LineGraph>()
private val maxsY = ArrayList<Float>()
private val maxsX = ArrayList<Long>()
private val minsX = ArrayList<Long>()
private var color: Int = 0xFFFFFF
private var listeners = ArrayList<PlotViewDataChangeListener>()
constructor(context: Context) : super(context) {
setWillNotDraw(false)
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
initAttributes(attrs, 0)
setWillNotDraw(false)
}
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
initAttributes(attrs, defStyle)
setWillNotDraw(false)
}
private fun initAttributes(attrs: AttributeSet, defStyle: Int) {
attrs.let {
val a = context.theme.obtainStyledAttributes(attrs, R.styleable.LPGPlotView, 0, defStyle)
try {
color = a.getInt(R.styleable.LPGPlotView_lpg_color, 0xFFFFFF)
} catch (e: Exception) {
Log.w("", e.message, e)
} finally {
a.recycle()
}
}
}
fun addData(index: Int, value: Pair<Long, Float>) {
data.forEach { lineGraph ->
if (lineGraph.index == index) {
lineGraph.data[value.first] = value.second
if (lineGraph.data.size > 30) {
lineGraph.data.remove(lineGraph.data.toSortedMap().firstKey())
}
invalidate()
val listenerValue = ArrayList<Pair<LineGraph, String>>(data.size)
data.forEach { lineGraph ->
listenerValue.add(Pair(lineGraph, "${String.format("%.0f", lineGraph.data[lineGraph.data.keys.max()])} kb/s"))
}
listeners.forEach { it.onDataChanged(listenerValue) }
}
}
}
fun addListener(listener: PlotViewDataChangeListener) {
listeners.add(listener)
}
fun removeListener(listener: PlotViewDataChangeListener) {
listeners.remove(listener)
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
maxsY.clear()
maxsX.clear()
minsX.clear()
data.forEach {
maxsY.add(it.data.maxBy { it.value }?.value ?: 0f)
}
val maxY = maxsY.max() ?: 0f
data.forEach {
maxsX.add(it.data.maxBy { it.key }?.key ?: 0L)
}
val maxX = maxsX.max() ?: 0L
data.forEach {
minsX.add(it.data.minBy { it.key }?.key ?: 0L)
}
val minX = minsX.min() ?: 0L
drawLines(maxY, minX, maxX, canvas)
drawGrid(canvas, maxY, minX, maxX)
}
private fun drawGrid(canvas: Canvas?, maxY: Float, minX: Long, maxX: Long) {
canvas?.let {
if (maxY <= 0F) return
// it.drawText("0", 10F, it.height.toFloat() - 2.dp, textPaint)
it.drawText("${String.format("%.0f", maxY)} kb/s", 10F, 10.dp.toFloat(), textPaint)
var center = maxY / 2
center = getRoundedByUnit(center)
if (BuildConfig.DEBUG) Log.d(this::class.java.simpleName, "Center: $center")
val centerCoord = measuredHeight * ((maxY - center) / maxY)
it.drawLine(0f, centerCoord, measuredWidth.toFloat(), centerCoord, textPaint)
it.drawText("${String.format("%.0f", center)} kb/s", 10F, centerCoord - 2.dp, textPaint)
//timestamps
var index = maxX - 1000
if (BuildConfig.DEBUG) Log.d(this::class.java.simpleName, "FirstIndex: $index")
while (index > minX) {
val xCoord = (measuredWidth * ((index - minX).toDouble() / (maxX - minX).toDouble())).toFloat()
it.drawLine(xCoord, 0F, xCoord, measuredHeight.toFloat() - 12.dp, textPaint)
val formattedText = "${String.format("%.0f", getRoundedByUnit((index - maxX).toFloat()) / 1000)}s"
it.drawText(formattedText, xCoord - (textPaint.measureText(formattedText) / 2), measuredHeight.toFloat(), textPaint)
index -= 1000
}
}
}
private fun getRoundedByUnit(number: Float): Float {
val lengthX = log10(number.toDouble()).toInt()
return (round(number / (10.0.pow(lengthX.toDouble()))) * (10.0.pow(lengthX.toDouble()))).toFloat()
}
private fun drawLines(maxY: Float, minX: Long, maxX: Long, canvas: Canvas?) {
data.forEach { line ->
var initialPoint: Pair<Float, Float>? = null
line.data.toSortedMap().forEach { point ->
if (initialPoint == null) {
initialPoint = getCoordinates(point, maxY, minX, maxX, measuredWidth, measuredHeight)
} else {
val currentPoint = getCoordinates(point, maxY, minX, maxX, measuredWidth, measuredHeight)
currentPoint.let {
canvas?.drawLine(initialPoint!!.first, initialPoint!!.second, it.first, it.second, line.paint)
initialPoint = it
}
}
}
}
}
// fun drawLines2(maxY: Float, minX: Long, maxX: Long, canvas: Canvas?) {
//
//
// data.forEach { line ->
// path.reset()
// val points = line.data.map {
// val coord = getCoordinates(it, maxY, minX, maxX, measuredWidth, measuredHeight)
// GraphPoint(coord.first, coord.second)
// }.sortedBy { it.x }
// for (i in points.indices) {
// val point = points[i]
// val smoothing = 100
// when (i) {
// 0 -> {
// val next: GraphPoint = points[i + 1]
// point.dx = (next.x - point.x) / smoothing
// point.dy = (next.y - point.y) / smoothing
// }
// points.size - 1 -> {
// val prev: GraphPoint = points[i - 1]
// point.dx = (point.x - prev.x) / smoothing
// point.dy = (point.y - prev.y) / smoothing
// }
// else -> {
// val next: GraphPoint = points[i + 1]
// val prev: GraphPoint = points[i - 1]
// point.dx = next.x - prev.x / smoothing
// point.dy = (next.y - prev.y) / smoothing
// }
// }
// }
// for (i in points.indices) {
// val point: GraphPoint = points[i]
// when {
// i == 0 -> {
// path.moveTo(point.x, point.y)
// }
// i < points.size - 1 -> {
// val prev: GraphPoint = points[i - 1]
// path.cubicTo(prev.x + prev.dx, prev.y + prev.dy, point.x - point.dx, point.y - point.dy, point.x, point.y)
// canvas?.drawCircle(point.x, point.y, 2.dp.toFloat(), line.paint)
// }
// else -> {
// path.lineTo(point.x, point.y)
// }
// }
// }
// canvas?.drawPath(path, line.paint)
// }
//
// }
private fun getCoordinates(point: Map.Entry<Long, Float>, maxY: Float, minX: Long, maxX: Long, measuredWidth: Int, measuredHeight: Int): Pair<Float, Float> = Pair((measuredWidth * ((point.key - minX).toDouble() / (maxX - minX).toDouble())).toFloat(), measuredHeight * ((maxY - point.value) / maxY))
fun clear() {
data.forEach {
it.data.clear()
}
}
fun addLine(lineGraph: LineGraph) {
if (!data.contains(lineGraph)) {
data.add(lineGraph)
}
}
}
data class GraphPoint(val x: Float, val y: Float) {
var dx: Float = 0F
var dy: Float = 0F
}
interface PlotViewDataChangeListener {
fun onDataChanged(data: List<Pair<LineGraph, String>>)
} | gpl-2.0 |
ansman/okhttp | okhttp/src/main/kotlin/okhttp3/HttpUrl.kt | 1 | 70588 | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3
import java.net.InetAddress
import java.net.MalformedURLException
import java.net.URI
import java.net.URISyntaxException
import java.net.URL
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets.UTF_8
import java.util.Collections
import java.util.LinkedHashSet
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.internal.canParseAsIpAddress
import okhttp3.internal.delimiterOffset
import okhttp3.internal.indexOfFirstNonAsciiWhitespace
import okhttp3.internal.indexOfLastNonAsciiWhitespace
import okhttp3.internal.parseHexDigit
import okhttp3.internal.publicsuffix.PublicSuffixDatabase
import okhttp3.internal.toCanonicalHost
import okio.Buffer
/**
* A uniform resource locator (URL) with a scheme of either `http` or `https`. Use this class to
* compose and decompose Internet addresses. For example, this code will compose and print a URL for
* Google search:
*
* ```
* HttpUrl url = new HttpUrl.Builder()
* .scheme("https")
* .host("www.google.com")
* .addPathSegment("search")
* .addQueryParameter("q", "polar bears")
* .build();
* System.out.println(url);
* ```
*
* which prints:
*
* ```
* https://www.google.com/search?q=polar%20bears
* ```
*
* As another example, this code prints the human-readable query parameters of a Twitter search:
*
* ```
* HttpUrl url = HttpUrl.parse("https://twitter.com/search?q=cute%20%23puppies&f=images");
* for (int i = 0, size = url.querySize(); i < size; i++) {
* System.out.println(url.queryParameterName(i) + ": " + url.queryParameterValue(i));
* }
* ```
*
* which prints:
*
* ```
* q: cute #puppies
* f: images
* ```
*
* In addition to composing URLs from their component parts and decomposing URLs into their
* component parts, this class implements relative URL resolution: what address you'd reach by
* clicking a relative link on a specified page. For example:
*
* ```
* HttpUrl base = HttpUrl.parse("https://www.youtube.com/user/WatchTheDaily/videos");
* HttpUrl link = base.resolve("../../watch?v=cbP2N1BQdYc");
* System.out.println(link);
* ```
*
* which prints:
*
* ```
* https://www.youtube.com/watch?v=cbP2N1BQdYc
* ```
*
* ## What's in a URL?
*
* A URL has several components.
*
* ### Scheme
*
* Sometimes referred to as *protocol*, A URL's scheme describes what mechanism should be used to
* retrieve the resource. Although URLs have many schemes (`mailto`, `file`, `ftp`), this class only
* supports `http` and `https`. Use [java.net.URI][URI] for URLs with arbitrary schemes.
*
* ### Username and Password
*
* Username and password are either present, or the empty string `""` if absent. This class offers
* no mechanism to differentiate empty from absent. Neither of these components are popular in
* practice. Typically HTTP applications use other mechanisms for user identification and
* authentication.
*
* ### Host
*
* The host identifies the webserver that serves the URL's resource. It is either a hostname like
* `square.com` or `localhost`, an IPv4 address like `192.168.0.1`, or an IPv6 address like `::1`.
*
* Usually a webserver is reachable with multiple identifiers: its IP addresses, registered
* domain names, and even `localhost` when connecting from the server itself. Each of a web server's
* names is a distinct URL and they are not interchangeable. For example, even if
* `http://square.github.io/dagger` and `http://google.github.io/dagger` are served by the same IP
* address, the two URLs identify different resources.
*
* ### Port
*
* The port used to connect to the web server. By default this is 80 for HTTP and 443 for HTTPS.
* This class never returns -1 for the port: if no port is explicitly specified in the URL then the
* scheme's default is used.
*
* ### Path
*
* The path identifies a specific resource on the host. Paths have a hierarchical structure like
* "/square/okhttp/issues/1486" and decompose into a list of segments like `["square", "okhttp",
* "issues", "1486"]`.
*
* This class offers methods to compose and decompose paths by segment. It composes each path
* from a list of segments by alternating between "/" and the encoded segment. For example the
* segments `["a", "b"]` build "/a/b" and the segments `["a", "b", ""]` build "/a/b/".
*
* If a path's last segment is the empty string then the path ends with "/". This class always
* builds non-empty paths: if the path is omitted it defaults to "/". The default path's segment
* list is a single empty string: `[""]`.
*
* ### Query
*
* The query is optional: it can be null, empty, or non-empty. For many HTTP URLs the query string
* is subdivided into a collection of name-value parameters. This class offers methods to set the
* query as the single string, or as individual name-value parameters. With name-value parameters
* the values are optional and names may be repeated.
*
* ### Fragment
*
* The fragment is optional: it can be null, empty, or non-empty. Unlike host, port, path, and
* query the fragment is not sent to the webserver: it's private to the client.
*
* ## Encoding
*
* Each component must be encoded before it is embedded in the complete URL. As we saw above, the
* string `cute #puppies` is encoded as `cute%20%23puppies` when used as a query parameter value.
*
* ### Percent encoding
*
* Percent encoding replaces a character (like `\ud83c\udf69`) with its UTF-8 hex bytes (like
* `%F0%9F%8D%A9`). This approach works for whitespace characters, control characters, non-ASCII
* characters, and characters that already have another meaning in a particular context.
*
* Percent encoding is used in every URL component except for the hostname. But the set of
* characters that need to be encoded is different for each component. For example, the path
* component must escape all of its `?` characters, otherwise it could be interpreted as the
* start of the URL's query. But within the query and fragment components, the `?` character
* doesn't delimit anything and doesn't need to be escaped.
*
* ```
* HttpUrl url = HttpUrl.parse("http://who-let-the-dogs.out").newBuilder()
* .addPathSegment("_Who?_")
* .query("_Who?_")
* .fragment("_Who?_")
* .build();
* System.out.println(url);
* ```
*
* This prints:
*
* ```
* http://who-let-the-dogs.out/_Who%3F_?_Who?_#_Who?_
* ```
*
* When parsing URLs that lack percent encoding where it is required, this class will percent encode
* the offending characters.
*
* ### IDNA Mapping and Punycode encoding
*
* Hostnames have different requirements and use a different encoding scheme. It consists of IDNA
* mapping and Punycode encoding.
*
* In order to avoid confusion and discourage phishing attacks, [IDNA Mapping][idna] transforms
* names to avoid confusing characters. This includes basic case folding: transforming shouting
* `SQUARE.COM` into cool and casual `square.com`. It also handles more exotic characters. For
* example, the Unicode trademark sign (™) could be confused for the letters "TM" in
* `http://ho™mail.com`. To mitigate this, the single character (™) maps to the string (tm). There
* is similar policy for all of the 1.1 million Unicode code points. Note that some code points such
* as "\ud83c\udf69" are not mapped and cannot be used in a hostname.
*
* [Punycode](http://ietf.org/rfc/rfc3492.txt) converts a Unicode string to an ASCII string to make
* international domain names work everywhere. For example, "σ" encodes as "xn--4xa". The encoded
* string is not human readable, but can be used with classes like [InetAddress] to establish
* connections.
*
* ## Why another URL model?
*
* Java includes both [java.net.URL][URL] and [java.net.URI][URI]. We offer a new URL
* model to address problems that the others don't.
*
* ### Different URLs should be different
*
* Although they have different content, `java.net.URL` considers the following two URLs
* equal, and the [equals()][Object.equals] method between them returns true:
*
* * https://example.net/
*
* * https://example.com/
*
* This is because those two hosts share the same IP address. This is an old, bad design decision
* that makes `java.net.URL` unusable for many things. It shouldn't be used as a [Map] key or in a
* [Set]. Doing so is both inefficient because equality may require a DNS lookup, and incorrect
* because unequal URLs may be equal because of how they are hosted.
*
* ### Equal URLs should be equal
*
* These two URLs are semantically identical, but `java.net.URI` disagrees:
*
* * http://host:80/
*
* * http://host
*
* Both the unnecessary port specification (`:80`) and the absent trailing slash (`/`) cause URI to
* bucket the two URLs separately. This harms URI's usefulness in collections. Any application that
* stores information-per-URL will need to either canonicalize manually, or suffer unnecessary
* redundancy for such URLs.
*
* Because they don't attempt canonical form, these classes are surprisingly difficult to use
* securely. Suppose you're building a webservice that checks that incoming paths are prefixed
* "/static/images/" before serving the corresponding assets from the filesystem.
*
* ```
* String attack = "http://example.com/static/images/../../../../../etc/passwd";
* System.out.println(new URL(attack).getPath());
* System.out.println(new URI(attack).getPath());
* System.out.println(HttpUrl.parse(attack).encodedPath());
* ```
*
* By canonicalizing the input paths, they are complicit in directory traversal attacks. Code that
* checks only the path prefix may suffer!
*
* ```
* /static/images/../../../../../etc/passwd
* /static/images/../../../../../etc/passwd
* /etc/passwd
* ```
*
* ### If it works on the web, it should work in your application
*
* The `java.net.URI` class is strict around what URLs it accepts. It rejects URLs like
* `http://example.com/abc|def` because the `|` character is unsupported. This class is more
* forgiving: it will automatically percent-encode the `|'` yielding `http://example.com/abc%7Cdef`.
* This kind behavior is consistent with web browsers. `HttpUrl` prefers consistency with major web
* browsers over consistency with obsolete specifications.
*
* ### Paths and Queries should decompose
*
* Neither of the built-in URL models offer direct access to path segments or query parameters.
* Manually using `StringBuilder` to assemble these components is cumbersome: do '+' characters get
* silently replaced with spaces? If a query parameter contains a '&', does that get escaped?
* By offering methods to read and write individual query parameters directly, application
* developers are saved from the hassles of encoding and decoding.
*
* ### Plus a modern API
*
* The URL (JDK1.0) and URI (Java 1.4) classes predate builders and instead use telescoping
* constructors. For example, there's no API to compose a URI with a custom port without also
* providing a query and fragment.
*
* Instances of [HttpUrl] are well-formed and always have a scheme, host, and path. With
* `java.net.URL` it's possible to create an awkward URL like `http:/` with scheme and path but no
* hostname. Building APIs that consume such malformed values is difficult!
*
* This class has a modern API. It avoids punitive checked exceptions: [toHttpUrl] throws
* [IllegalArgumentException] on invalid input or [toHttpUrlOrNull] returns null if the input is an
* invalid URL. You can even be explicit about whether each component has been encoded already.
*
* [idna]: http://www.unicode.org/reports/tr46/#ToASCII
*/
class HttpUrl internal constructor(
/** Either "http" or "https". */
@get:JvmName("scheme") val scheme: String,
/**
* The decoded username, or an empty string if none is present.
*
* | URL | `username()` |
* | :------------------------------- | :----------- |
* | `http://host/` | `""` |
* | `http://username@host/` | `"username"` |
* | `http://username:password@host/` | `"username"` |
* | `http://a%20b:c%20d@host/` | `"a b"` |
*/
@get:JvmName("username") val username: String,
/**
* Returns the decoded password, or an empty string if none is present.
*
* | URL | `password()` |
* | :------------------------------- | :----------- |
* | `http://host/` | `""` |
* | `http://username@host/` | `""` |
* | `http://username:password@host/` | `"password"` |
* | `http://a%20b:c%20d@host/` | `"c d"` |
*/
@get:JvmName("password") val password: String,
/**
* The host address suitable for use with [InetAddress.getAllByName]. May be:
*
* * A regular host name, like `android.com`.
*
* * An IPv4 address, like `127.0.0.1`.
*
* * An IPv6 address, like `::1`. Note that there are no square braces.
*
* * An encoded IDN, like `xn--n3h.net`.
*
* | URL | `host()` |
* | :-------------------- | :-------------- |
* | `http://android.com/` | `"android.com"` |
* | `http://127.0.0.1/` | `"127.0.0.1"` |
* | `http://[::1]/` | `"::1"` |
* | `http://xn--n3h.net/` | `"xn--n3h.net"` |
*/
@get:JvmName("host") val host: String,
/**
* The explicitly-specified port if one was provided, or the default port for this URL's scheme.
* For example, this returns 8443 for `https://square.com:8443/` and 443 for
* `https://square.com/`. The result is in `[1..65535]`.
*
* | URL | `port()` |
* | :------------------ | :------- |
* | `http://host/` | `80` |
* | `http://host:8000/` | `8000` |
* | `https://host/` | `443` |
*/
@get:JvmName("port") val port: Int,
/**
* A list of path segments like `["a", "b", "c"]` for the URL `http://host/a/b/c`. This list is
* never empty though it may contain a single empty string.
*
* | URL | `pathSegments()` |
* | :----------------------- | :------------------ |
* | `http://host/` | `[""]` |
* | `http://host/a/b/c"` | `["a", "b", "c"]` |
* | `http://host/a/b%20c/d"` | `["a", "b c", "d"]` |
*/
@get:JvmName("pathSegments") val pathSegments: List<String>,
/**
* Alternating, decoded query names and values, or null for no query. Names may be empty or
* non-empty, but never null. Values are null if the name has no corresponding '=' separator, or
* empty, or non-empty.
*/
private val queryNamesAndValues: List<String?>?,
/**
* This URL's fragment, like `"abc"` for `http://host/#abc`. This is null if the URL has no
* fragment.
*
* | URL | `fragment()` |
* | :--------------------- | :----------- |
* | `http://host/` | null |
* | `http://host/#` | `""` |
* | `http://host/#abc` | `"abc"` |
* | `http://host/#abc|def` | `"abc|def"` |
*/
@get:JvmName("fragment") val fragment: String?,
/** Canonical URL. */
private val url: String
) {
val isHttps: Boolean = scheme == "https"
/** Returns this URL as a [java.net.URL][URL]. */
@JvmName("url") fun toUrl(): URL {
try {
return URL(url)
} catch (e: MalformedURLException) {
throw RuntimeException(e) // Unexpected!
}
}
/**
* Returns this URL as a [java.net.URI][URI]. Because `URI` is more strict than this class, the
* returned URI may be semantically different from this URL:
*
* * Characters forbidden by URI like `[` and `|` will be escaped.
*
* * Invalid percent-encoded sequences like `%xx` will be encoded like `%25xx`.
*
* * Whitespace and control characters in the fragment will be stripped.
*
* These differences may have a significant consequence when the URI is interpreted by a
* web server. For this reason the [URI class][URI] and this method should be avoided.
*/
@JvmName("uri") fun toUri(): URI {
val uri = newBuilder().reencodeForUri().toString()
return try {
URI(uri)
} catch (e: URISyntaxException) {
// Unlikely edge case: the URI has a forbidden character in the fragment. Strip it & retry.
try {
val stripped = uri.replace(Regex("[\\u0000-\\u001F\\u007F-\\u009F\\p{javaWhitespace}]"), "")
URI.create(stripped)
} catch (e1: Exception) {
throw RuntimeException(e) // Unexpected!
}
}
}
/**
* The username, or an empty string if none is set.
*
* | URL | `encodedUsername()` |
* | :------------------------------- | :------------------ |
* | `http://host/` | `""` |
* | `http://username@host/` | `"username"` |
* | `http://username:password@host/` | `"username"` |
* | `http://a%20b:c%20d@host/` | `"a%20b"` |
*/
@get:JvmName("encodedUsername") val encodedUsername: String
get() {
if (username.isEmpty()) return ""
val usernameStart = scheme.length + 3 // "://".length() == 3.
val usernameEnd = url.delimiterOffset(":@", usernameStart, url.length)
return url.substring(usernameStart, usernameEnd)
}
/**
* The password, or an empty string if none is set.
*
* | URL | `encodedPassword()` |
* | :--------------------------------| :------------------ |
* | `http://host/` | `""` |
* | `http://username@host/` | `""` |
* | `http://username:password@host/` | `"password"` |
* | `http://a%20b:c%20d@host/` | `"c%20d"` |
*/
@get:JvmName("encodedPassword") val encodedPassword: String
get() {
if (password.isEmpty()) return ""
val passwordStart = url.indexOf(':', scheme.length + 3) + 1
val passwordEnd = url.indexOf('@')
return url.substring(passwordStart, passwordEnd)
}
/**
* The number of segments in this URL's path. This is also the number of slashes in this URL's
* path, like 3 in `http://host/a/b/c`. This is always at least 1.
*
* | URL | `pathSize()` |
* | :------------------- | :----------- |
* | `http://host/` | `1` |
* | `http://host/a/b/c` | `3` |
* | `http://host/a/b/c/` | `4` |
*/
@get:JvmName("pathSize") val pathSize: Int get() = pathSegments.size
/**
* The entire path of this URL encoded for use in HTTP resource resolution. The returned path will
* start with `"/"`.
*
* | URL | `encodedPath()` |
* | :---------------------- | :-------------- |
* | `http://host/` | `"/"` |
* | `http://host/a/b/c` | `"/a/b/c"` |
* | `http://host/a/b%20c/d` | `"/a/b%20c/d"` |
*/
@get:JvmName("encodedPath") val encodedPath: String
get() {
val pathStart = url.indexOf('/', scheme.length + 3) // "://".length() == 3.
val pathEnd = url.delimiterOffset("?#", pathStart, url.length)
return url.substring(pathStart, pathEnd)
}
/**
* A list of encoded path segments like `["a", "b", "c"]` for the URL `http://host/a/b/c`. This
* list is never empty though it may contain a single empty string.
*
* | URL | `encodedPathSegments()` |
* | :---------------------- | :---------------------- |
* | `http://host/` | `[""]` |
* | `http://host/a/b/c` | `["a", "b", "c"]` |
* | `http://host/a/b%20c/d` | `["a", "b%20c", "d"]` |
*/
@get:JvmName("encodedPathSegments") val encodedPathSegments: List<String>
get() {
val pathStart = url.indexOf('/', scheme.length + 3)
val pathEnd = url.delimiterOffset("?#", pathStart, url.length)
val result = mutableListOf<String>()
var i = pathStart
while (i < pathEnd) {
i++ // Skip the '/'.
val segmentEnd = url.delimiterOffset('/', i, pathEnd)
result.add(url.substring(i, segmentEnd))
i = segmentEnd
}
return result
}
/**
* The query of this URL, encoded for use in HTTP resource resolution. This string may be null
* (for URLs with no query), empty (for URLs with an empty query) or non-empty (all other URLs).
*
* | URL | `encodedQuery()` |
* | :-------------------------------- | :--------------------- |
* | `http://host/` | null |
* | `http://host/?` | `""` |
* | `http://host/?a=apple&k=key+lime` | `"a=apple&k=key+lime"` |
* | `http://host/?a=apple&a=apricot` | `"a=apple&a=apricot"` |
* | `http://host/?a=apple&b` | `"a=apple&b"` |
*/
@get:JvmName("encodedQuery") val encodedQuery: String?
get() {
if (queryNamesAndValues == null) return null // No query.
val queryStart = url.indexOf('?') + 1
val queryEnd = url.delimiterOffset('#', queryStart, url.length)
return url.substring(queryStart, queryEnd)
}
/**
* This URL's query, like `"abc"` for `http://host/?abc`. Most callers should prefer
* [queryParameterName] and [queryParameterValue] because these methods offer direct access to
* individual query parameters.
*
* | URL | `query()` |
* | :-------------------------------- | :--------------------- |
* | `http://host/` | null |
* | `http://host/?` | `""` |
* | `http://host/?a=apple&k=key+lime` | `"a=apple&k=key lime"` |
* | `http://host/?a=apple&a=apricot` | `"a=apple&a=apricot"` |
* | `http://host/?a=apple&b` | `"a=apple&b"` |
*/
@get:JvmName("query") val query: String?
get() {
if (queryNamesAndValues == null) return null // No query.
val result = StringBuilder()
queryNamesAndValues.toQueryString(result)
return result.toString()
}
/**
* The number of query parameters in this URL, like 2 for `http://host/?a=apple&b=banana`. If this
* URL has no query this is 0. Otherwise it is one more than the number of `"&"` separators in the
* query.
*
* | URL | `querySize()` |
* | :-------------------------------- | :------------ |
* | `http://host/` | `0` |
* | `http://host/?` | `1` |
* | `http://host/?a=apple&k=key+lime` | `2` |
* | `http://host/?a=apple&a=apricot` | `2` |
* | `http://host/?a=apple&b` | `2` |
*/
@get:JvmName("querySize") val querySize: Int
get() {
return if (queryNamesAndValues != null) queryNamesAndValues.size / 2 else 0
}
/**
* The first query parameter named `name` decoded using UTF-8, or null if there is no such query
* parameter.
*
* | URL | `queryParameter("a")` |
* | :-------------------------------- | :-------------------- |
* | `http://host/` | null |
* | `http://host/?` | null |
* | `http://host/?a=apple&k=key+lime` | `"apple"` |
* | `http://host/?a=apple&a=apricot` | `"apple"` |
* | `http://host/?a=apple&b` | `"apple"` |
*/
fun queryParameter(name: String): String? {
if (queryNamesAndValues == null) return null
for (i in 0 until queryNamesAndValues.size step 2) {
if (name == queryNamesAndValues[i]) {
return queryNamesAndValues[i + 1]
}
}
return null
}
/**
* The distinct query parameter names in this URL, like `["a", "b"]` for
* `http://host/?a=apple&b=banana`. If this URL has no query this is the empty set.
*
* | URL | `queryParameterNames()` |
* | :-------------------------------- | :---------------------- |
* | `http://host/` | `[]` |
* | `http://host/?` | `[""]` |
* | `http://host/?a=apple&k=key+lime` | `["a", "k"]` |
* | `http://host/?a=apple&a=apricot` | `["a"]` |
* | `http://host/?a=apple&b` | `["a", "b"]` |
*/
@get:JvmName("queryParameterNames") val queryParameterNames: Set<String>
get() {
if (queryNamesAndValues == null) return emptySet()
val result = LinkedHashSet<String>()
for (i in 0 until queryNamesAndValues.size step 2) {
result.add(queryNamesAndValues[i]!!)
}
return Collections.unmodifiableSet(result)
}
/**
* Returns all values for the query parameter `name` ordered by their appearance in this
* URL. For example this returns `["banana"]` for `queryParameterValue("b")` on
* `http://host/?a=apple&b=banana`.
*
* | URL | `queryParameterValues("a")` | `queryParameterValues("b")` |
* | :-------------------------------- | :-------------------------- | :-------------------------- |
* | `http://host/` | `[]` | `[]` |
* | `http://host/?` | `[]` | `[]` |
* | `http://host/?a=apple&k=key+lime` | `["apple"]` | `[]` |
* | `http://host/?a=apple&a=apricot` | `["apple", "apricot"]` | `[]` |
* | `http://host/?a=apple&b` | `["apple"]` | `[null]` |
*/
fun queryParameterValues(name: String): List<String?> {
if (queryNamesAndValues == null) return emptyList()
val result = mutableListOf<String?>()
for (i in 0 until queryNamesAndValues.size step 2) {
if (name == queryNamesAndValues[i]) {
result.add(queryNamesAndValues[i + 1])
}
}
return Collections.unmodifiableList(result)
}
/**
* Returns the name of the query parameter at `index`. For example this returns `"a"`
* for `queryParameterName(0)` on `http://host/?a=apple&b=banana`. This throws if
* `index` is not less than the [query size][querySize].
*
* | URL | `queryParameterName(0)` | `queryParameterName(1)` |
* | :-------------------------------- | :---------------------- | :---------------------- |
* | `http://host/` | exception | exception |
* | `http://host/?` | `""` | exception |
* | `http://host/?a=apple&k=key+lime` | `"a"` | `"k"` |
* | `http://host/?a=apple&a=apricot` | `"a"` | `"a"` |
* | `http://host/?a=apple&b` | `"a"` | `"b"` |
*/
fun queryParameterName(index: Int): String {
if (queryNamesAndValues == null) throw IndexOutOfBoundsException()
return queryNamesAndValues[index * 2]!!
}
/**
* Returns the value of the query parameter at `index`. For example this returns `"apple"` for
* `queryParameterName(0)` on `http://host/?a=apple&b=banana`. This throws if `index` is not less
* than the [query size][querySize].
*
* | URL | `queryParameterValue(0)` | `queryParameterValue(1)` |
* | :-------------------------------- | :----------------------- | :----------------------- |
* | `http://host/` | exception | exception |
* | `http://host/?` | null | exception |
* | `http://host/?a=apple&k=key+lime` | `"apple"` | `"key lime"` |
* | `http://host/?a=apple&a=apricot` | `"apple"` | `"apricot"` |
* | `http://host/?a=apple&b` | `"apple"` | null |
*/
fun queryParameterValue(index: Int): String? {
if (queryNamesAndValues == null) throw IndexOutOfBoundsException()
return queryNamesAndValues[index * 2 + 1]
}
/**
* This URL's encoded fragment, like `"abc"` for `http://host/#abc`. This is null if the URL has
* no fragment.
*
* | URL | `encodedFragment()` |
* | :--------------------- | :------------------ |
* | `http://host/` | null |
* | `http://host/#` | `""` |
* | `http://host/#abc` | `"abc"` |
* | `http://host/#abc|def` | `"abc|def"` |
*/
@get:JvmName("encodedFragment") val encodedFragment: String?
get() {
if (fragment == null) return null
val fragmentStart = url.indexOf('#') + 1
return url.substring(fragmentStart)
}
/**
* Returns a string with containing this URL with its username, password, query, and fragment
* stripped, and its path replaced with `/...`. For example, redacting
* `http://username:[email protected]/path` returns `http://example.com/...`.
*/
fun redact(): String {
return newBuilder("/...")!!
.username("")
.password("")
.build()
.toString()
}
/**
* Returns the URL that would be retrieved by following `link` from this URL, or null if the
* resulting URL is not well-formed.
*/
fun resolve(link: String): HttpUrl? = newBuilder(link)?.build()
/**
* Returns a builder based on this URL.
*/
fun newBuilder(): Builder {
val result = Builder()
result.scheme = scheme
result.encodedUsername = encodedUsername
result.encodedPassword = encodedPassword
result.host = host
// If we're set to a default port, unset it in case of a scheme change.
result.port = if (port != defaultPort(scheme)) port else -1
result.encodedPathSegments.clear()
result.encodedPathSegments.addAll(encodedPathSegments)
result.encodedQuery(encodedQuery)
result.encodedFragment = encodedFragment
return result
}
/**
* Returns a builder for the URL that would be retrieved by following `link` from this URL,
* or null if the resulting URL is not well-formed.
*/
fun newBuilder(link: String): Builder? {
return try {
Builder().parse(this, link)
} catch (_: IllegalArgumentException) {
null
}
}
override fun equals(other: Any?): Boolean {
return other is HttpUrl && other.url == url
}
override fun hashCode(): Int = url.hashCode()
override fun toString(): String = url
/**
* Returns the domain name of this URL's [host] that is one level beneath the public suffix by
* consulting the [public suffix list](https://publicsuffix.org). Returns null if this URL's
* [host] is an IP address or is considered a public suffix by the public suffix list.
*
* In general this method **should not** be used to test whether a domain is valid or routable.
* Instead, DNS is the recommended source for that information.
*
* | URL | `topPrivateDomain()` |
* | :---------------------------- | :------------------- |
* | `http://google.com` | `"google.com"` |
* | `http://adwords.google.co.uk` | `"google.co.uk"` |
* | `http://square` | null |
* | `http://co.uk` | null |
* | `http://localhost` | null |
* | `http://127.0.0.1` | null |
*/
fun topPrivateDomain(): String? {
return if (host.canParseAsIpAddress()) {
null
} else {
PublicSuffixDatabase.get().getEffectiveTldPlusOne(host)
}
}
@JvmName("-deprecated_url")
@Deprecated(
message = "moved to toUrl()",
replaceWith = ReplaceWith(expression = "toUrl()"),
level = DeprecationLevel.ERROR)
fun url() = toUrl()
@JvmName("-deprecated_uri")
@Deprecated(
message = "moved to toUri()",
replaceWith = ReplaceWith(expression = "toUri()"),
level = DeprecationLevel.ERROR)
fun uri() = toUri()
@JvmName("-deprecated_scheme")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "scheme"),
level = DeprecationLevel.ERROR)
fun scheme(): String = scheme
@JvmName("-deprecated_encodedUsername")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "encodedUsername"),
level = DeprecationLevel.ERROR)
fun encodedUsername(): String = encodedUsername
@JvmName("-deprecated_username")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "username"),
level = DeprecationLevel.ERROR)
fun username(): String = username
@JvmName("-deprecated_encodedPassword")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "encodedPassword"),
level = DeprecationLevel.ERROR)
fun encodedPassword(): String = encodedPassword
@JvmName("-deprecated_password")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "password"),
level = DeprecationLevel.ERROR)
fun password(): String = password
@JvmName("-deprecated_host")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "host"),
level = DeprecationLevel.ERROR)
fun host(): String = host
@JvmName("-deprecated_port")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "port"),
level = DeprecationLevel.ERROR)
fun port(): Int = port
@JvmName("-deprecated_pathSize")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "pathSize"),
level = DeprecationLevel.ERROR)
fun pathSize(): Int = pathSize
@JvmName("-deprecated_encodedPath")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "encodedPath"),
level = DeprecationLevel.ERROR)
fun encodedPath(): String = encodedPath
@JvmName("-deprecated_encodedPathSegments")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "encodedPathSegments"),
level = DeprecationLevel.ERROR)
fun encodedPathSegments(): List<String> = encodedPathSegments
@JvmName("-deprecated_pathSegments")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "pathSegments"),
level = DeprecationLevel.ERROR)
fun pathSegments(): List<String> = pathSegments
@JvmName("-deprecated_encodedQuery")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "encodedQuery"),
level = DeprecationLevel.ERROR)
fun encodedQuery(): String? = encodedQuery
@JvmName("-deprecated_query")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "query"),
level = DeprecationLevel.ERROR)
fun query(): String? = query
@JvmName("-deprecated_querySize")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "querySize"),
level = DeprecationLevel.ERROR)
fun querySize(): Int = querySize
@JvmName("-deprecated_queryParameterNames")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "queryParameterNames"),
level = DeprecationLevel.ERROR)
fun queryParameterNames(): Set<String> = queryParameterNames
@JvmName("-deprecated_encodedFragment")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "encodedFragment"),
level = DeprecationLevel.ERROR)
fun encodedFragment(): String? = encodedFragment
@JvmName("-deprecated_fragment")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "fragment"),
level = DeprecationLevel.ERROR)
fun fragment(): String? = fragment
class Builder {
internal var scheme: String? = null
internal var encodedUsername = ""
internal var encodedPassword = ""
internal var host: String? = null
internal var port = -1
internal val encodedPathSegments = mutableListOf<String>()
internal var encodedQueryNamesAndValues: MutableList<String?>? = null
internal var encodedFragment: String? = null
init {
encodedPathSegments.add("") // The default path is '/' which needs a trailing space.
}
/**
* @param scheme either "http" or "https".
*/
fun scheme(scheme: String) = apply {
when {
scheme.equals("http", ignoreCase = true) -> this.scheme = "http"
scheme.equals("https", ignoreCase = true) -> this.scheme = "https"
else -> throw IllegalArgumentException("unexpected scheme: $scheme")
}
}
fun username(username: String) = apply {
this.encodedUsername = username.canonicalize(encodeSet = USERNAME_ENCODE_SET)
}
fun encodedUsername(encodedUsername: String) = apply {
this.encodedUsername = encodedUsername.canonicalize(
encodeSet = USERNAME_ENCODE_SET,
alreadyEncoded = true
)
}
fun password(password: String) = apply {
this.encodedPassword = password.canonicalize(encodeSet = PASSWORD_ENCODE_SET)
}
fun encodedPassword(encodedPassword: String) = apply {
this.encodedPassword = encodedPassword.canonicalize(
encodeSet = PASSWORD_ENCODE_SET,
alreadyEncoded = true
)
}
/**
* @param host either a regular hostname, International Domain Name, IPv4 address, or IPv6
* address.
*/
fun host(host: String) = apply {
val encoded = host.percentDecode().toCanonicalHost() ?: throw IllegalArgumentException(
"unexpected host: $host")
this.host = encoded
}
fun port(port: Int) = apply {
require(port in 1..65535) { "unexpected port: $port" }
this.port = port
}
private fun effectivePort(): Int {
return if (port != -1) port else defaultPort(scheme!!)
}
fun addPathSegment(pathSegment: String) = apply {
push(pathSegment, 0, pathSegment.length, addTrailingSlash = false, alreadyEncoded = false)
}
/**
* Adds a set of path segments separated by a slash (either `\` or `/`). If `pathSegments`
* starts with a slash, the resulting URL will have empty path segment.
*/
fun addPathSegments(pathSegments: String): Builder = addPathSegments(pathSegments, false)
fun addEncodedPathSegment(encodedPathSegment: String) = apply {
push(encodedPathSegment, 0, encodedPathSegment.length, addTrailingSlash = false,
alreadyEncoded = true)
}
/**
* Adds a set of encoded path segments separated by a slash (either `\` or `/`). If
* `encodedPathSegments` starts with a slash, the resulting URL will have empty path segment.
*/
fun addEncodedPathSegments(encodedPathSegments: String): Builder =
addPathSegments(encodedPathSegments, true)
private fun addPathSegments(pathSegments: String, alreadyEncoded: Boolean) = apply {
var offset = 0
do {
val segmentEnd = pathSegments.delimiterOffset("/\\", offset, pathSegments.length)
val addTrailingSlash = segmentEnd < pathSegments.length
push(pathSegments, offset, segmentEnd, addTrailingSlash, alreadyEncoded)
offset = segmentEnd + 1
} while (offset <= pathSegments.length)
}
fun setPathSegment(index: Int, pathSegment: String) = apply {
val canonicalPathSegment = pathSegment.canonicalize(encodeSet = PATH_SEGMENT_ENCODE_SET)
require(!isDot(canonicalPathSegment) && !isDotDot(canonicalPathSegment)) {
"unexpected path segment: $pathSegment"
}
encodedPathSegments[index] = canonicalPathSegment
}
fun setEncodedPathSegment(index: Int, encodedPathSegment: String) = apply {
val canonicalPathSegment = encodedPathSegment.canonicalize(
encodeSet = PATH_SEGMENT_ENCODE_SET,
alreadyEncoded = true
)
encodedPathSegments[index] = canonicalPathSegment
require(!isDot(canonicalPathSegment) && !isDotDot(canonicalPathSegment)) {
"unexpected path segment: $encodedPathSegment"
}
}
fun removePathSegment(index: Int) = apply {
encodedPathSegments.removeAt(index)
if (encodedPathSegments.isEmpty()) {
encodedPathSegments.add("") // Always leave at least one '/'.
}
}
fun encodedPath(encodedPath: String) = apply {
require(encodedPath.startsWith("/")) { "unexpected encodedPath: $encodedPath" }
resolvePath(encodedPath, 0, encodedPath.length)
}
fun query(query: String?) = apply {
this.encodedQueryNamesAndValues = query?.canonicalize(
encodeSet = QUERY_ENCODE_SET,
plusIsSpace = true
)?.toQueryNamesAndValues()
}
fun encodedQuery(encodedQuery: String?) = apply {
this.encodedQueryNamesAndValues = encodedQuery?.canonicalize(
encodeSet = QUERY_ENCODE_SET,
alreadyEncoded = true,
plusIsSpace = true
)?.toQueryNamesAndValues()
}
/** Encodes the query parameter using UTF-8 and adds it to this URL's query string. */
fun addQueryParameter(name: String, value: String?) = apply {
if (encodedQueryNamesAndValues == null) encodedQueryNamesAndValues = mutableListOf()
encodedQueryNamesAndValues!!.add(name.canonicalize(
encodeSet = QUERY_COMPONENT_ENCODE_SET,
plusIsSpace = true
))
encodedQueryNamesAndValues!!.add(value?.canonicalize(
encodeSet = QUERY_COMPONENT_ENCODE_SET,
plusIsSpace = true
))
}
/** Adds the pre-encoded query parameter to this URL's query string. */
fun addEncodedQueryParameter(encodedName: String, encodedValue: String?) = apply {
if (encodedQueryNamesAndValues == null) encodedQueryNamesAndValues = mutableListOf()
encodedQueryNamesAndValues!!.add(encodedName.canonicalize(
encodeSet = QUERY_COMPONENT_REENCODE_SET,
alreadyEncoded = true,
plusIsSpace = true
))
encodedQueryNamesAndValues!!.add(encodedValue?.canonicalize(
encodeSet = QUERY_COMPONENT_REENCODE_SET,
alreadyEncoded = true,
plusIsSpace = true
))
}
fun setQueryParameter(name: String, value: String?) = apply {
removeAllQueryParameters(name)
addQueryParameter(name, value)
}
fun setEncodedQueryParameter(encodedName: String, encodedValue: String?) = apply {
removeAllEncodedQueryParameters(encodedName)
addEncodedQueryParameter(encodedName, encodedValue)
}
fun removeAllQueryParameters(name: String) = apply {
if (encodedQueryNamesAndValues == null) return this
val nameToRemove = name.canonicalize(
encodeSet = QUERY_COMPONENT_ENCODE_SET,
plusIsSpace = true
)
removeAllCanonicalQueryParameters(nameToRemove)
}
fun removeAllEncodedQueryParameters(encodedName: String) = apply {
if (encodedQueryNamesAndValues == null) return this
removeAllCanonicalQueryParameters(encodedName.canonicalize(
encodeSet = QUERY_COMPONENT_REENCODE_SET,
alreadyEncoded = true,
plusIsSpace = true
))
}
private fun removeAllCanonicalQueryParameters(canonicalName: String) {
for (i in encodedQueryNamesAndValues!!.size - 2 downTo 0 step 2) {
if (canonicalName == encodedQueryNamesAndValues!![i]) {
encodedQueryNamesAndValues!!.removeAt(i + 1)
encodedQueryNamesAndValues!!.removeAt(i)
if (encodedQueryNamesAndValues!!.isEmpty()) {
encodedQueryNamesAndValues = null
return
}
}
}
}
fun fragment(fragment: String?) = apply {
this.encodedFragment = fragment?.canonicalize(
encodeSet = FRAGMENT_ENCODE_SET,
unicodeAllowed = true
)
}
fun encodedFragment(encodedFragment: String?) = apply {
this.encodedFragment = encodedFragment?.canonicalize(
encodeSet = FRAGMENT_ENCODE_SET,
alreadyEncoded = true,
unicodeAllowed = true
)
}
/**
* Re-encodes the components of this URL so that it satisfies (obsolete) RFC 2396, which is
* particularly strict for certain components.
*/
internal fun reencodeForUri() = apply {
host = host?.replace(Regex("[\"<>^`{|}]"), "")
for (i in 0 until encodedPathSegments.size) {
encodedPathSegments[i] = encodedPathSegments[i].canonicalize(
encodeSet = PATH_SEGMENT_ENCODE_SET_URI,
alreadyEncoded = true,
strict = true
)
}
val encodedQueryNamesAndValues = this.encodedQueryNamesAndValues
if (encodedQueryNamesAndValues != null) {
for (i in 0 until encodedQueryNamesAndValues.size) {
encodedQueryNamesAndValues[i] = encodedQueryNamesAndValues[i]?.canonicalize(
encodeSet = QUERY_COMPONENT_ENCODE_SET_URI,
alreadyEncoded = true,
strict = true,
plusIsSpace = true
)
}
}
encodedFragment = encodedFragment?.canonicalize(
encodeSet = FRAGMENT_ENCODE_SET_URI,
alreadyEncoded = true,
strict = true,
unicodeAllowed = true
)
}
fun build(): HttpUrl {
@Suppress("UNCHECKED_CAST") // percentDecode returns either List<String?> or List<String>.
return HttpUrl(
scheme = scheme ?: throw IllegalStateException("scheme == null"),
username = encodedUsername.percentDecode(),
password = encodedPassword.percentDecode(),
host = host ?: throw IllegalStateException("host == null"),
port = effectivePort(),
pathSegments = encodedPathSegments.map { it.percentDecode() },
queryNamesAndValues = encodedQueryNamesAndValues?.map { it?.percentDecode(plusIsSpace = true) },
fragment = encodedFragment?.percentDecode(),
url = toString()
)
}
override fun toString(): String {
return buildString {
if (scheme != null) {
append(scheme)
append("://")
} else {
append("//")
}
if (encodedUsername.isNotEmpty() || encodedPassword.isNotEmpty()) {
append(encodedUsername)
if (encodedPassword.isNotEmpty()) {
append(':')
append(encodedPassword)
}
append('@')
}
if (host != null) {
if (':' in host!!) {
// Host is an IPv6 address.
append('[')
append(host)
append(']')
} else {
append(host)
}
}
if (port != -1 || scheme != null) {
val effectivePort = effectivePort()
if (scheme == null || effectivePort != defaultPort(scheme!!)) {
append(':')
append(effectivePort)
}
}
encodedPathSegments.toPathString(this)
if (encodedQueryNamesAndValues != null) {
append('?')
encodedQueryNamesAndValues!!.toQueryString(this)
}
if (encodedFragment != null) {
append('#')
append(encodedFragment)
}
}
}
internal fun parse(base: HttpUrl?, input: String): Builder {
var pos = input.indexOfFirstNonAsciiWhitespace()
val limit = input.indexOfLastNonAsciiWhitespace(pos)
// Scheme.
val schemeDelimiterOffset = schemeDelimiterOffset(input, pos, limit)
if (schemeDelimiterOffset != -1) {
when {
input.startsWith("https:", ignoreCase = true, startIndex = pos) -> {
this.scheme = "https"
pos += "https:".length
}
input.startsWith("http:", ignoreCase = true, startIndex = pos) -> {
this.scheme = "http"
pos += "http:".length
}
else -> throw IllegalArgumentException("Expected URL scheme 'http' or 'https' but was '" +
input.substring(0, schemeDelimiterOffset) + "'")
}
} else if (base != null) {
this.scheme = base.scheme
} else {
throw IllegalArgumentException(
"Expected URL scheme 'http' or 'https' but no colon was found")
}
// Authority.
var hasUsername = false
var hasPassword = false
val slashCount = input.slashCount(pos, limit)
if (slashCount >= 2 || base == null || base.scheme != this.scheme) {
// Read an authority if either:
// * The input starts with 2 or more slashes. These follow the scheme if it exists.
// * The input scheme exists and is different from the base URL's scheme.
//
// The structure of an authority is:
// username:password@host:port
//
// Username, password and port are optional.
// [username[:password]@]host[:port]
pos += slashCount
authority@ while (true) {
val componentDelimiterOffset = input.delimiterOffset("@/\\?#", pos, limit)
val c = if (componentDelimiterOffset != limit) {
input[componentDelimiterOffset].toInt()
} else {
-1
}
when (c) {
'@'.toInt() -> {
// User info precedes.
if (!hasPassword) {
val passwordColonOffset = input.delimiterOffset(':', pos, componentDelimiterOffset)
val canonicalUsername = input.canonicalize(
pos = pos,
limit = passwordColonOffset,
encodeSet = USERNAME_ENCODE_SET,
alreadyEncoded = true
)
this.encodedUsername = if (hasUsername) {
this.encodedUsername + "%40" + canonicalUsername
} else {
canonicalUsername
}
if (passwordColonOffset != componentDelimiterOffset) {
hasPassword = true
this.encodedPassword = input.canonicalize(
pos = passwordColonOffset + 1,
limit = componentDelimiterOffset,
encodeSet = PASSWORD_ENCODE_SET,
alreadyEncoded = true
)
}
hasUsername = true
} else {
this.encodedPassword = this.encodedPassword + "%40" + input.canonicalize(
pos = pos,
limit = componentDelimiterOffset,
encodeSet = PASSWORD_ENCODE_SET,
alreadyEncoded = true
)
}
pos = componentDelimiterOffset + 1
}
-1, '/'.toInt(), '\\'.toInt(), '?'.toInt(), '#'.toInt() -> {
// Host info precedes.
val portColonOffset = portColonOffset(input, pos, componentDelimiterOffset)
if (portColonOffset + 1 < componentDelimiterOffset) {
host = input.percentDecode(pos = pos, limit = portColonOffset).toCanonicalHost()
port = parsePort(input, portColonOffset + 1, componentDelimiterOffset)
require(port != -1) {
"Invalid URL port: \"${input.substring(portColonOffset + 1,
componentDelimiterOffset)}\""
}
} else {
host = input.percentDecode(pos = pos, limit = portColonOffset).toCanonicalHost()
port = defaultPort(scheme!!)
}
require(host != null) {
"$INVALID_HOST: \"${input.substring(pos, portColonOffset)}\""
}
pos = componentDelimiterOffset
break@authority
}
}
}
} else {
// This is a relative link. Copy over all authority components. Also maybe the path & query.
this.encodedUsername = base.encodedUsername
this.encodedPassword = base.encodedPassword
this.host = base.host
this.port = base.port
this.encodedPathSegments.clear()
this.encodedPathSegments.addAll(base.encodedPathSegments)
if (pos == limit || input[pos] == '#') {
encodedQuery(base.encodedQuery)
}
}
// Resolve the relative path.
val pathDelimiterOffset = input.delimiterOffset("?#", pos, limit)
resolvePath(input, pos, pathDelimiterOffset)
pos = pathDelimiterOffset
// Query.
if (pos < limit && input[pos] == '?') {
val queryDelimiterOffset = input.delimiterOffset('#', pos, limit)
this.encodedQueryNamesAndValues = input.canonicalize(
pos = pos + 1,
limit = queryDelimiterOffset,
encodeSet = QUERY_ENCODE_SET,
alreadyEncoded = true,
plusIsSpace = true
).toQueryNamesAndValues()
pos = queryDelimiterOffset
}
// Fragment.
if (pos < limit && input[pos] == '#') {
this.encodedFragment = input.canonicalize(
pos = pos + 1,
limit = limit,
encodeSet = FRAGMENT_ENCODE_SET,
alreadyEncoded = true,
unicodeAllowed = true
)
}
return this
}
private fun resolvePath(input: String, startPos: Int, limit: Int) {
var pos = startPos
// Read a delimiter.
if (pos == limit) {
// Empty path: keep the base path as-is.
return
}
val c = input[pos]
if (c == '/' || c == '\\') {
// Absolute path: reset to the default "/".
encodedPathSegments.clear()
encodedPathSegments.add("")
pos++
} else {
// Relative path: clear everything after the last '/'.
encodedPathSegments[encodedPathSegments.size - 1] = ""
}
// Read path segments.
var i = pos
while (i < limit) {
val pathSegmentDelimiterOffset = input.delimiterOffset("/\\", i, limit)
val segmentHasTrailingSlash = pathSegmentDelimiterOffset < limit
push(input, i, pathSegmentDelimiterOffset, segmentHasTrailingSlash, true)
i = pathSegmentDelimiterOffset
if (segmentHasTrailingSlash) i++
}
}
/** Adds a path segment. If the input is ".." or equivalent, this pops a path segment. */
private fun push(
input: String,
pos: Int,
limit: Int,
addTrailingSlash: Boolean,
alreadyEncoded: Boolean
) {
val segment = input.canonicalize(
pos = pos,
limit = limit,
encodeSet = PATH_SEGMENT_ENCODE_SET,
alreadyEncoded = alreadyEncoded
)
if (isDot(segment)) {
return // Skip '.' path segments.
}
if (isDotDot(segment)) {
pop()
return
}
if (encodedPathSegments[encodedPathSegments.size - 1].isEmpty()) {
encodedPathSegments[encodedPathSegments.size - 1] = segment
} else {
encodedPathSegments.add(segment)
}
if (addTrailingSlash) {
encodedPathSegments.add("")
}
}
private fun isDot(input: String): Boolean {
return input == "." || input.equals("%2e", ignoreCase = true)
}
private fun isDotDot(input: String): Boolean {
return input == ".." ||
input.equals("%2e.", ignoreCase = true) ||
input.equals(".%2e", ignoreCase = true) ||
input.equals("%2e%2e", ignoreCase = true)
}
/**
* Removes a path segment. When this method returns the last segment is always "", which means
* the encoded path will have a trailing '/'.
*
* Popping "/a/b/c/" yields "/a/b/". In this case the list of path segments goes from ["a",
* "b", "c", ""] to ["a", "b", ""].
*
* Popping "/a/b/c" also yields "/a/b/". The list of path segments goes from ["a", "b", "c"]
* to ["a", "b", ""].
*/
private fun pop() {
val removed = encodedPathSegments.removeAt(encodedPathSegments.size - 1)
// Make sure the path ends with a '/' by either adding an empty string or clearing a segment.
if (removed.isEmpty() && encodedPathSegments.isNotEmpty()) {
encodedPathSegments[encodedPathSegments.size - 1] = ""
} else {
encodedPathSegments.add("")
}
}
companion object {
internal const val INVALID_HOST = "Invalid URL host"
/**
* Returns the index of the ':' in `input` that is after scheme characters. Returns -1 if
* `input` does not have a scheme that starts at `pos`.
*/
private fun schemeDelimiterOffset(input: String, pos: Int, limit: Int): Int {
if (limit - pos < 2) return -1
val c0 = input[pos]
if ((c0 < 'a' || c0 > 'z') && (c0 < 'A' || c0 > 'Z')) return -1 // Not a scheme start char.
characters@ for (i in pos + 1 until limit) {
return when (input[i]) {
// Scheme character. Keep going.
in 'a'..'z', in 'A'..'Z', in '0'..'9', '+', '-', '.' -> continue@characters
// Scheme prefix!
':' -> i
// Non-scheme character before the first ':'.
else -> -1
}
}
return -1 // No ':'; doesn't start with a scheme.
}
/** Returns the number of '/' and '\' slashes in this, starting at `pos`. */
private fun String.slashCount(pos: Int, limit: Int): Int {
var slashCount = 0
for (i in pos until limit) {
val c = this[i]
if (c == '\\' || c == '/') {
slashCount++
} else {
break
}
}
return slashCount
}
/** Finds the first ':' in `input`, skipping characters between square braces "[...]". */
private fun portColonOffset(input: String, pos: Int, limit: Int): Int {
var i = pos
while (i < limit) {
when (input[i]) {
'[' -> {
while (++i < limit) {
if (input[i] == ']') break
}
}
':' -> return i
}
i++
}
return limit // No colon.
}
private fun parsePort(input: String, pos: Int, limit: Int): Int {
return try {
// Canonicalize the port string to skip '\n' etc.
val portString = input.canonicalize(pos = pos, limit = limit, encodeSet = "")
val i = portString.toInt()
if (i in 1..65535) i else -1
} catch (_: NumberFormatException) {
-1 // Invalid port.
}
}
}
}
companion object {
private val HEX_DIGITS =
charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F')
internal const val USERNAME_ENCODE_SET = " \"':;<=>@[]^`{}|/\\?#"
internal const val PASSWORD_ENCODE_SET = " \"':;<=>@[]^`{}|/\\?#"
internal const val PATH_SEGMENT_ENCODE_SET = " \"<>^`{}|/\\?#"
internal const val PATH_SEGMENT_ENCODE_SET_URI = "[]"
internal const val QUERY_ENCODE_SET = " \"'<>#"
internal const val QUERY_COMPONENT_REENCODE_SET = " \"'<>#&="
internal const val QUERY_COMPONENT_ENCODE_SET = " !\"#$&'(),/:;<=>?@[]\\^`{|}~"
internal const val QUERY_COMPONENT_ENCODE_SET_URI = "\\^`{|}"
internal const val FORM_ENCODE_SET = " \"':;<=>@[]^`{}|/\\?#&!$(),~"
internal const val FRAGMENT_ENCODE_SET = ""
internal const val FRAGMENT_ENCODE_SET_URI = " \"#<>\\^`{|}"
/** Returns 80 if `scheme.equals("http")`, 443 if `scheme.equals("https")` and -1 otherwise. */
@JvmStatic
fun defaultPort(scheme: String): Int {
return when (scheme) {
"http" -> 80
"https" -> 443
else -> -1
}
}
/** Returns a path string for this list of path segments. */
internal fun List<String>.toPathString(out: StringBuilder) {
for (i in 0 until size) {
out.append('/')
out.append(this[i])
}
}
/** Returns a string for this list of query names and values. */
internal fun List<String?>.toQueryString(out: StringBuilder) {
for (i in 0 until size step 2) {
val name = this[i]
val value = this[i + 1]
if (i > 0) out.append('&')
out.append(name)
if (value != null) {
out.append('=')
out.append(value)
}
}
}
/**
* Cuts this string up into alternating parameter names and values. This divides a query string
* like `subject=math&easy&problem=5-2=3` into the list `["subject", "math", "easy", null,
* "problem", "5-2=3"]`. Note that values may be null and may contain '=' characters.
*/
internal fun String.toQueryNamesAndValues(): MutableList<String?> {
val result = mutableListOf<String?>()
var pos = 0
while (pos <= length) {
var ampersandOffset = indexOf('&', pos)
if (ampersandOffset == -1) ampersandOffset = length
val equalsOffset = indexOf('=', pos)
if (equalsOffset == -1 || equalsOffset > ampersandOffset) {
result.add(substring(pos, ampersandOffset))
result.add(null) // No value for this name.
} else {
result.add(substring(pos, equalsOffset))
result.add(substring(equalsOffset + 1, ampersandOffset))
}
pos = ampersandOffset + 1
}
return result
}
/**
* Returns a new [HttpUrl] representing this.
*
* @throws IllegalArgumentException If this is not a well-formed HTTP or HTTPS URL.
*/
@JvmStatic
@JvmName("get") fun String.toHttpUrl(): HttpUrl = Builder().parse(null, this).build()
/**
* Returns a new `HttpUrl` representing `url` if it is a well-formed HTTP or HTTPS URL, or null
* if it isn't.
*/
@JvmStatic
@JvmName("parse") fun String.toHttpUrlOrNull(): HttpUrl? {
return try {
toHttpUrl()
} catch (_: IllegalArgumentException) {
null
}
}
/**
* Returns an [HttpUrl] for this if its protocol is `http` or `https`, or null if it has any
* other protocol.
*/
@JvmStatic
@JvmName("get") fun URL.toHttpUrlOrNull(): HttpUrl? = toString().toHttpUrlOrNull()
@JvmStatic
@JvmName("get") fun URI.toHttpUrlOrNull(): HttpUrl? = toString().toHttpUrlOrNull()
@JvmName("-deprecated_get")
@Deprecated(
message = "moved to extension function",
replaceWith = ReplaceWith(
expression = "url.toHttpUrl()",
imports = ["okhttp3.HttpUrl.Companion.toHttpUrl"]),
level = DeprecationLevel.ERROR)
fun get(url: String): HttpUrl = url.toHttpUrl()
@JvmName("-deprecated_parse")
@Deprecated(
message = "moved to extension function",
replaceWith = ReplaceWith(
expression = "url.toHttpUrlOrNull()",
imports = ["okhttp3.HttpUrl.Companion.toHttpUrlOrNull"]),
level = DeprecationLevel.ERROR)
fun parse(url: String): HttpUrl? = url.toHttpUrlOrNull()
@JvmName("-deprecated_get")
@Deprecated(
message = "moved to extension function",
replaceWith = ReplaceWith(
expression = "url.toHttpUrlOrNull()",
imports = ["okhttp3.HttpUrl.Companion.toHttpUrlOrNull"]),
level = DeprecationLevel.ERROR)
fun get(url: URL): HttpUrl? = url.toHttpUrlOrNull()
@JvmName("-deprecated_get")
@Deprecated(
message = "moved to extension function",
replaceWith = ReplaceWith(
expression = "uri.toHttpUrlOrNull()",
imports = ["okhttp3.HttpUrl.Companion.toHttpUrlOrNull"]),
level = DeprecationLevel.ERROR)
fun get(uri: URI): HttpUrl? = uri.toHttpUrlOrNull()
internal fun String.percentDecode(
pos: Int = 0,
limit: Int = length,
plusIsSpace: Boolean = false
): String {
for (i in pos until limit) {
val c = this[i]
if (c == '%' || c == '+' && plusIsSpace) {
// Slow path: the character at i requires decoding!
val out = Buffer()
out.writeUtf8(this, pos, i)
out.writePercentDecoded(this, pos = i, limit = limit, plusIsSpace = plusIsSpace)
return out.readUtf8()
}
}
// Fast path: no characters in [pos..limit) required decoding.
return substring(pos, limit)
}
private fun Buffer.writePercentDecoded(
encoded: String,
pos: Int,
limit: Int,
plusIsSpace: Boolean
) {
var codePoint: Int
var i = pos
while (i < limit) {
codePoint = encoded.codePointAt(i)
if (codePoint == '%'.toInt() && i + 2 < limit) {
val d1 = encoded[i + 1].parseHexDigit()
val d2 = encoded[i + 2].parseHexDigit()
if (d1 != -1 && d2 != -1) {
writeByte((d1 shl 4) + d2)
i += 2
i += Character.charCount(codePoint)
continue
}
} else if (codePoint == '+'.toInt() && plusIsSpace) {
writeByte(' '.toInt())
i++
continue
}
writeUtf8CodePoint(codePoint)
i += Character.charCount(codePoint)
}
}
private fun String.isPercentEncoded(pos: Int, limit: Int): Boolean {
return pos + 2 < limit &&
this[pos] == '%' &&
this[pos + 1].parseHexDigit() != -1 &&
this[pos + 2].parseHexDigit() != -1
}
/**
* Returns a substring of `input` on the range `[pos..limit)` with the following
* transformations:
*
* * Tabs, newlines, form feeds and carriage returns are skipped.
*
* * In queries, ' ' is encoded to '+' and '+' is encoded to "%2B".
*
* * Characters in `encodeSet` are percent-encoded.
*
* * Control characters and non-ASCII characters are percent-encoded.
*
* * All other characters are copied without transformation.
*
* @param alreadyEncoded true to leave '%' as-is; false to convert it to '%25'.
* @param strict true to encode '%' if it is not the prefix of a valid percent encoding.
* @param plusIsSpace true to encode '+' as "%2B" if it is not already encoded.
* @param unicodeAllowed true to leave non-ASCII codepoint unencoded.
* @param charset which charset to use, null equals UTF-8.
*/
internal fun String.canonicalize(
pos: Int = 0,
limit: Int = length,
encodeSet: String,
alreadyEncoded: Boolean = false,
strict: Boolean = false,
plusIsSpace: Boolean = false,
unicodeAllowed: Boolean = false,
charset: Charset? = null
): String {
var codePoint: Int
var i = pos
while (i < limit) {
codePoint = codePointAt(i)
if (codePoint < 0x20 ||
codePoint == 0x7f ||
codePoint >= 0x80 && !unicodeAllowed ||
codePoint.toChar() in encodeSet ||
codePoint == '%'.toInt() &&
(!alreadyEncoded || strict && !isPercentEncoded(i, limit)) ||
codePoint == '+'.toInt() && plusIsSpace) {
// Slow path: the character at i requires encoding!
val out = Buffer()
out.writeUtf8(this, pos, i)
out.writeCanonicalized(
input = this,
pos = i,
limit = limit,
encodeSet = encodeSet,
alreadyEncoded = alreadyEncoded,
strict = strict,
plusIsSpace = plusIsSpace,
unicodeAllowed = unicodeAllowed,
charset = charset
)
return out.readUtf8()
}
i += Character.charCount(codePoint)
}
// Fast path: no characters in [pos..limit) required encoding.
return substring(pos, limit)
}
private fun Buffer.writeCanonicalized(
input: String,
pos: Int,
limit: Int,
encodeSet: String,
alreadyEncoded: Boolean,
strict: Boolean,
plusIsSpace: Boolean,
unicodeAllowed: Boolean,
charset: Charset?
) {
var encodedCharBuffer: Buffer? = null // Lazily allocated.
var codePoint: Int
var i = pos
while (i < limit) {
codePoint = input.codePointAt(i)
if (alreadyEncoded && (codePoint == '\t'.toInt() || codePoint == '\n'.toInt() ||
codePoint == '\u000c'.toInt() || codePoint == '\r'.toInt())) {
// Skip this character.
} else if (codePoint == '+'.toInt() && plusIsSpace) {
// Encode '+' as '%2B' since we permit ' ' to be encoded as either '+' or '%20'.
writeUtf8(if (alreadyEncoded) "+" else "%2B")
} else if (codePoint < 0x20 ||
codePoint == 0x7f ||
codePoint >= 0x80 && !unicodeAllowed ||
codePoint.toChar() in encodeSet ||
codePoint == '%'.toInt() &&
(!alreadyEncoded || strict && !input.isPercentEncoded(i, limit))) {
// Percent encode this character.
if (encodedCharBuffer == null) {
encodedCharBuffer = Buffer()
}
if (charset == null || charset == UTF_8) {
encodedCharBuffer.writeUtf8CodePoint(codePoint)
} else {
encodedCharBuffer.writeString(input, i, i + Character.charCount(codePoint), charset)
}
while (!encodedCharBuffer.exhausted()) {
val b = encodedCharBuffer.readByte().toInt() and 0xff
writeByte('%'.toInt())
writeByte(HEX_DIGITS[b shr 4 and 0xf].toInt())
writeByte(HEX_DIGITS[b and 0xf].toInt())
}
} else {
// This character doesn't need encoding. Just copy it over.
writeUtf8CodePoint(codePoint)
}
i += Character.charCount(codePoint)
}
}
}
}
| apache-2.0 |
SuperAwesomeLTD/sa-mobile-sdk-android | superawesome-base/src/main/java/tv/superawesome/sdk/publisher/QueryAdditionalOptions.kt | 1 | 452 | package tv.superawesome.sdk.publisher
import org.json.JSONObject
data class QueryAdditionalOptions(val map: Map<String, String>) {
fun appendTo(jsonObject: JSONObject) {
map.forEach { (key, value) ->
jsonObject.put(key, value)
}
}
companion object {
var default: QueryAdditionalOptions? = null
fun appendTo(jsonObject: JSONObject) {
default?.appendTo(jsonObject)
}
}
} | lgpl-3.0 |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/RendererDelegate.kt | 1 | 3024 | /*****************************************************************************
* RendererDelegate.java
*
* Copyright © 2017 VLC authors and VideoLAN
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*/
package org.videolan.vlc
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import org.videolan.libvlc.RendererDiscoverer
import org.videolan.libvlc.RendererItem
import org.videolan.resources.AppContextProvider
import org.videolan.resources.VLCInstance
import org.videolan.tools.AppScope
import org.videolan.tools.NetworkMonitor
import org.videolan.tools.isAppStarted
import org.videolan.tools.livedata.LiveDataset
import org.videolan.tools.retry
import java.util.*
@ObsoleteCoroutinesApi
@ExperimentalCoroutinesApi
object RendererDelegate : RendererDiscoverer.EventListener {
private val TAG = "VLC/RendererDelegate"
private val discoverers = ArrayList<RendererDiscoverer>()
val renderers : LiveDataset<RendererItem> = LiveDataset()
@Volatile private var started = false
init {
NetworkMonitor.getInstance(AppContextProvider.appContext).connectionFlow.onEach { if (it.connected) start() else stop() }.launchIn(AppScope)
}
suspend fun start() {
if (started) return
val libVlc = withContext(Dispatchers.IO) { VLCInstance.get(AppContextProvider.appContext) }
started = true
for (discoverer in RendererDiscoverer.list(libVlc)) {
val rd = RendererDiscoverer(libVlc, discoverer.name)
discoverers.add(rd)
rd.setEventListener(this@RendererDelegate)
retry(5, 1000L) { if (!rd.isReleased) rd.start() else false }
}
}
fun stop() {
if (!started) return
started = false
for (discoverer in discoverers) discoverer.stop()
if (isAppStarted() || PlaybackService.instance?.run { !isPlaying } != false) {
PlaybackService.renderer.value = null
}
clear()
}
private fun clear() {
discoverers.clear()
renderers.clear()
}
override fun onEvent(event: RendererDiscoverer.Event?) {
when (event?.type) {
RendererDiscoverer.Event.ItemAdded -> renderers.add(event.item)
RendererDiscoverer.Event.ItemDeleted -> renderers.remove(event.item)
}
}
}
| gpl-2.0 |
AoEiuV020/PaNovel | api/src/main/java/cc/aoeiuv020/panovel/api/site/snwx.kt | 1 | 2648 | package cc.aoeiuv020.panovel.api.site
import cc.aoeiuv020.base.jar.ownLinesString
import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext
import cc.aoeiuv020.panovel.api.firstThreeIntPattern
import cc.aoeiuv020.panovel.api.firstTwoIntPattern
/**
*
* Created by AoEiuV020 on 2018.03.07-02:42:57.
*/
class Snwx : DslJsoupNovelContext() {init {
hide = true
site {
name = "少年文学"
baseUrl = "https://www.snwx3.com"
logo = "https://www.snwx3.com/xiaoyi/images/logo.gif"
}
cookieFilter {
// 删除cookie绕开搜索时间间隔限制,
// 这网站只删除jieqiVisitTime已经没用了,
removeAll {
httpUrl.encodedPath().startsWith("/modules/article/search.php")
}
}
search {
get {
charset = "GBK"
url = "/modules/article/search.php"
data {
"searchkey" to it
}
}
document {
items("#newscontent > div.l > ul > li") {
name("> span.s2 > a")
author("> span.s4")
}
}
}
bookIdRegex = firstTwoIntPattern
// https://www.snwxx.com/book/66/66076/
detailPageTemplate = "/book/%s/"
detail {
document {
val div = element("#info")
val title = element("> div.infotitle", parent = div)
novel {
name("> h1", parent = title)
author("> i:nth-child(2)", parent = title, block = pickString("作\\s*者:(\\S*)"))
}
image("#fmimg > img")
introduction("> div.intro", parent = div) {
// 可能没有简介,
it.textNodes().first {
// TextNode不可避免的有空的,
!it.isBlank
&& !it.wholeText.let {
// 后面几个TextNode广告包含这些文字,
it.startsWith("各位书友要是觉得《${novel?.name}》还不错的话请不要忘记向您QQ群和微博里的朋友推荐哦!")
|| it.startsWith("${novel?.name}最新章节,${novel?.name}无弹窗,${novel?.name}全文阅读.")
}
}.ownLinesString()
}
// 这网站详情页没有更新时间,
}
}
chapters {
document {
items("#list > dl > dd > a")
}
}
bookIdWithChapterIdRegex = firstThreeIntPattern
contentPageTemplate = "/book/%s.html"
content {
document {
items("#BookText")
}
}
}
}
| gpl-3.0 |
AoEiuV020/PaNovel | app/src/main/java/cc/aoeiuv020/panovel/search/SiteSettingsPresenter.kt | 1 | 3806 | package cc.aoeiuv020.panovel.search
import cc.aoeiuv020.panovel.Presenter
import cc.aoeiuv020.panovel.api.NovelContext
import cc.aoeiuv020.panovel.data.DataManager
import cc.aoeiuv020.panovel.report.Reporter
import cc.aoeiuv020.panovel.util.notNullOrReport
import cc.aoeiuv020.regex.compileRegex
import okhttp3.Cookie
import okhttp3.Headers
import okhttp3.HttpUrl
import org.jetbrains.anko.*
import java.nio.charset.Charset
/**
* Created by AoEiuV020 on 2019.05.01-19:56:11.
*/
class SiteSettingsPresenter(
private val site: String
) : Presenter<SiteSettingsActivity>(), AnkoLogger {
private lateinit var context: NovelContext
fun start() {
view?.doAsync({ e ->
val message = "读取网站失败,"
Reporter.post(message, e)
error(message, e)
view?.runOnUiThread {
view?.showError(message, e)
view?.finish()
}
}) {
context = DataManager.getNovelContextByName(site)
uiThread { view ->
view.init()
}
}
}
fun setCookie(input: (String) -> String?, success: () -> Unit) {
view?.doAsync({ e ->
val message = "设置Cookie失败,"
Reporter.post(message, e)
error(message, e)
view?.runOnUiThread {
view?.showError(message, e)
}
}) {
val oldCookie = context.cookies.values.joinToString("; ") {
it.run { "${name()}=${value()}" }
}
val newCookie = input(oldCookie)
?: return@doAsync
val cookieMap = newCookie.split(";").mapNotNull { cookiePair ->
debug { "pull cookie: <$cookiePair>" }
// 取出来的cookiePair只有name=value,Cookie.parse一定能通过,也因此可能有超时信息拿不出来的问题,
Cookie.parse(HttpUrl.parse(context.site.baseUrl).notNullOrReport(), cookiePair)?.let { cookie ->
cookie.name() to cookie
}
}.toMap()
context.replaceCookies(cookieMap)
uiThread {
success()
}
}
}
fun setHeader(input: (String) -> String?, success: () -> Unit) {
view?.doAsync({ e ->
val message = "设置Header失败,"
Reporter.post(message, e)
error(message, e)
view?.runOnUiThread {
view?.showError(message, e)
}
}) {
val old = context.headers.toList().joinToString("\n") { (name, value) ->
"$name: $value"
}
val new = input(old)
?: return@doAsync
val headers: Headers = Headers.of(*new.split(compileRegex("\n|(: *)")).toTypedArray())
context.replaceHeaders(headers)
uiThread {
success()
}
}
}
fun setCharset(input: (String) -> String?, success: () -> Unit) {
view?.doAsync({ e ->
val message = "设置编码失败,"
Reporter.post(message, e)
error(message, e)
view?.runOnUiThread {
view?.showError(message, e)
}
}) {
val old = context.forceCharset ?: context.charset ?: context.defaultCharset
val new = input(old)
?: return@doAsync
if (new.isNotBlank()) {
Charset.forName(new)
}
context.forceCharset = new
uiThread {
success()
}
}
}
fun getReason(): String {
return context.reason
}
fun isUpkeep(): Boolean {
return context.upkeep
}
}
| gpl-3.0 |
natanieljr/droidmate | project/pcComponents/core/src/main/kotlin/org/droidmate/misc/Failable.kt | 1 | 1417 | // DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2018. Saarland University
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// Current Maintainers:
// Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland>
// Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland>
//
// Former Maintainers:
// Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de>
//
// web: www.droidmate.org
package org.droidmate.misc
import org.droidmate.exploration.ExplorationContext
import java.io.Serializable
data class Failable<out TResult , out TException> (val result: TResult?, val error: TException) : Serializable {
companion object {
private const val serialVersionUID: Long = 1
}
}
typealias FailableExploration = Failable<ExplorationContext<*,*,*>, List<Throwable>>
| gpl-3.0 |
hypercube1024/firefly | firefly-net/src/main/kotlin/com/fireflysource/net/http/server/impl/content/provider/DefaultContentProvider.kt | 1 | 2226 | package com.fireflysource.net.http.server.impl.content.provider
import com.fireflysource.common.io.BufferUtils
import com.fireflysource.common.sys.ProjectVersion
import com.fireflysource.net.http.common.model.HttpStatus
import com.fireflysource.net.http.server.HttpServerContentProvider
import com.fireflysource.net.http.server.RoutingContext
import java.nio.ByteBuffer
import java.nio.charset.StandardCharsets
import java.util.*
import java.util.concurrent.CompletableFuture
class DefaultContentProvider(
private val status: Int,
private val exception: Throwable?,
private val ctx: RoutingContext
) : HttpServerContentProvider {
private val html = """
|<!DOCTYPE html>
|<html>
|<head>
|<title>${getTitle()}</title>
|</head>
|<body>
|<h1>${getTitle()}</h1>
|<p>${getContent()}</p>
|<hr/>
|<footer><em>powered by Firefly ${ProjectVersion.getValue()}</em></footer>
|</body>
|</html>
""".trimMargin()
private val contentByteBuffer = BufferUtils.toBuffer(html, StandardCharsets.UTF_8)
private val provider: ByteBufferContentProvider = ByteBufferContentProvider(contentByteBuffer)
private fun getTitle(): String {
return "$status ${getCode().message}"
}
private fun getCode(): HttpStatus.Code {
return Optional.ofNullable(HttpStatus.getCode(status)).orElse(HttpStatus.Code.INTERNAL_SERVER_ERROR)
}
private fun getContent(): String {
return when (getCode()) {
HttpStatus.Code.NOT_FOUND -> "The resource ${ctx.uri.path} is not found"
HttpStatus.Code.INTERNAL_SERVER_ERROR -> "The server internal error. <br/> ${exception?.message}"
else -> "${getTitle()} <br/> ${exception?.message}"
}
}
override fun length(): Long = provider.length()
override fun isOpen(): Boolean = provider.isOpen
override fun toByteBuffer(): ByteBuffer = provider.toByteBuffer()
override fun closeAsync(): CompletableFuture<Void> = provider.closeAsync()
override fun close() = provider.close()
override fun read(byteBuffer: ByteBuffer): CompletableFuture<Int> = provider.read(byteBuffer)
} | apache-2.0 |
nemerosa/ontrack | ontrack-extension-git/src/main/java/net/nemerosa/ontrack/extension/git/service/GitPullRequestCache.kt | 1 | 493 | package net.nemerosa.ontrack.extension.git.service
import net.nemerosa.ontrack.extension.git.model.GitPullRequest
import net.nemerosa.ontrack.model.structure.Branch
/**
* Caching the pull requests for the branches.
*/
interface GitPullRequestCache {
/**
* Gets a PR for a branch from the cache if not empty and valid, and loads it if not available.
*/
fun getBranchPullRequest(
branch: Branch,
prProvider: () -> GitPullRequest?,
): GitPullRequest?
} | mit |
mobilejazz/Colloc | server/src/main/kotlin/com/mobilejazz/colloc/domain/model/Platform.kt | 1 | 104 | package com.mobilejazz.colloc.domain.model
enum class Platform {
IOS,
ANDROID,
JSON,
ANGULAR
}
| apache-2.0 |
nickbutcher/plaid | core/src/test/java/io/plaidapp/core/designernews/TestData.kt | 1 | 1296 | /*
* Copyright 2018 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.plaidapp.core.designernews
import io.plaidapp.core.designernews.data.stories.model.StoryLinks
import io.plaidapp.core.designernews.data.users.model.User
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.ResponseBody.Companion.toResponseBody
/**
* Test data
*/
val user = User(
id = 111L,
firstName = "Plaicent",
lastName = "van Plaid",
displayName = "Plaicent van Plaid",
portraitUrl = "www"
)
val errorResponseBody = "Error".toResponseBody("".toMediaTypeOrNull())
const val userId = 123L
val storyLinks = StoryLinks(
user = userId,
comments = listOf(1, 2, 3),
upvotes = listOf(11, 22, 33),
downvotes = listOf(111, 222, 333)
)
| apache-2.0 |
goodwinnk/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/impl/GuiTestUtilKt.kt | 1 | 15573 | // 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.testGuiFramework.impl
import com.intellij.diagnostic.MessagePool
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.Ref
import com.intellij.testGuiFramework.framework.GuiTestUtil
import com.intellij.testGuiFramework.framework.Timeouts
import com.intellij.testGuiFramework.framework.toPrintable
import com.intellij.ui.EngravedLabel
import org.fest.swing.core.ComponentMatcher
import org.fest.swing.core.GenericTypeMatcher
import org.fest.swing.core.Robot
import org.fest.swing.edt.GuiActionRunner
import org.fest.swing.edt.GuiQuery
import org.fest.swing.edt.GuiTask
import org.fest.swing.exception.ComponentLookupException
import org.fest.swing.exception.WaitTimedOutError
import org.fest.swing.timing.Condition
import org.fest.swing.timing.Pause
import org.fest.swing.timing.Timeout
import org.fest.swing.timing.Wait
import java.awt.Component
import java.awt.Container
import java.awt.Window
import java.util.*
import java.util.concurrent.TimeUnit
import javax.swing.JCheckBox
import javax.swing.JDialog
import javax.swing.JLabel
import javax.swing.JRadioButton
import kotlin.collections.ArrayList
/**
* @author Sergey Karashevich
*/
object GuiTestUtilKt {
fun createTree(string: String): ImmutableTree<String> {
val currentPath = ArrayList<String>()
var lines = string.split("\n")
if (lines.last().isEmpty()) lines = lines.subList(0, lines.lastIndex - 1)
val tree: ImmutableTree<String> = ImmutableTree()
var lastNode: ImmutableTreeNode<String>? = null
try {
for (line in lines) {
if (currentPath.isEmpty()) {
currentPath.add(line)
tree.root = ImmutableTreeNode(line.withoutIndent(), null)
lastNode = tree.root
}
else {
if (currentPath.last() hasDiffIndentFrom line) {
if (currentPath.last().getIndent() > line.getIndent()) {
while (currentPath.last() hasDiffIndentFrom line) {
currentPath.removeAt(currentPath.lastIndex)
lastNode = lastNode!!.parent
}
currentPath.removeAt(currentPath.lastIndex)
currentPath.add(line)
lastNode = lastNode!!.parent!!.createChild(line.withoutIndent())
}
else {
currentPath.add(line)
lastNode = lastNode!!.createChild(line.withoutIndent())
}
}
else {
currentPath.removeAt(currentPath.lastIndex)
currentPath.add(line)
lastNode = lastNode!!.parent!!.createChild(line.withoutIndent())
}
}
}
return tree
}
catch (e: Exception) {
throw Exception("Unable to build a tree from given data. Check indents and ")
}
}
private infix fun String.hasDiffIndentFrom(s: String): Boolean {
return this.getIndent() != s.getIndent()
}
private fun String.getIndent() = this.indexOfFirst { it != ' ' }
private fun String.withoutIndent() = this.substring(this.getIndent())
private operator fun String.times(n: Int): String {
val sb = StringBuilder(n)
for (i in 1..n) {
sb.append(this)
}
return sb.toString()
}
class ImmutableTree<Value> {
var root: ImmutableTreeNode<Value>? = null
fun print() {
if (root == null) throw Exception("Unable to print tree without root (or if root is null)")
printRecursive(root!!, 0)
}
fun printRecursive(root: ImmutableTreeNode<Value>, indent: Int) {
println(" " * indent + root.value)
if (!root.isLeaf()) root.children.forEach { printRecursive(it, indent + 2) }
}
}
data class ImmutableTreeNode<Value>(val value: Value,
val parent: ImmutableTreeNode<Value>?,
val children: LinkedList<ImmutableTreeNode<Value>> = LinkedList()) {
fun createChild(childValue: Value): ImmutableTreeNode<Value> {
val child = ImmutableTreeNode<Value>(childValue, this)
children.add(child)
return child
}
fun countChildren(): Int = children.count()
fun isLeaf(): Boolean = (children.count() == 0)
}
fun Component.isTextComponent(): Boolean {
val textComponentsTypes = arrayOf(JLabel::class.java, JRadioButton::class.java, JCheckBox::class.java)
return textComponentsTypes.any { it.isInstance(this) }
}
fun Component.getComponentText(): String? {
when (this) {
is JLabel -> return this.text
is JRadioButton -> return this.text
is JCheckBox -> return this.text
else -> return null
}
}
private fun findComponentByText(robot: Robot, container: Container, text: String, timeout: Timeout = Timeouts.seconds30): Component {
return withPauseWhenNull(timeout = timeout) {
robot.finder().findAll(container, ComponentMatcher { component ->
component!!.isShowing && component.isTextComponent() && component.getComponentText() == text
}).firstOrNull()
}
}
fun <BoundedComponent> findBoundedComponentByText(robot: Robot,
container: Container,
text: String,
componentType: Class<BoundedComponent>,
timeout: Timeout = Timeouts.seconds30): BoundedComponent {
val componentWithText = findComponentByText(robot, container, text, timeout)
if (componentWithText is JLabel && componentWithText.labelFor != null) {
val labeledComponent = componentWithText.labelFor
if (componentType.isInstance(labeledComponent)) return labeledComponent as BoundedComponent
return robot.finder().find(labeledComponent as Container) { component -> componentType.isInstance(component) } as BoundedComponent
}
try {
return withPauseWhenNull(timeout = timeout) {
val componentsOfInstance = robot.finder().findAll(container, ComponentMatcher { component -> componentType.isInstance(component) })
componentsOfInstance.filter { it.isShowing && it.onHeightCenter(componentWithText, true) }
.sortedBy { it.bounds.x }
.firstOrNull()
} as BoundedComponent
}
catch (e: WaitTimedOutError) {
throw ComponentLookupException("Unable to find component of type: ${componentType.simpleName} in $container by text: $text")
}
}
//Does the textComponent intersects horizontal line going through the center of this component and lays lefter than this component
fun Component.onHeightCenter(textComponent: Component, onLeft: Boolean): Boolean {
val centerXAxis = this.bounds.height / 2 + this.locationOnScreen.y
val sideCheck =
if (onLeft)
textComponent.locationOnScreen.x < this.locationOnScreen.x
else
textComponent.locationOnScreen.x > this.locationOnScreen.x
return (textComponent.locationOnScreen.y <= centerXAxis)
&& (textComponent.locationOnScreen.y + textComponent.bounds.height >= centerXAxis)
&& (sideCheck)
}
fun runOnEdt(task: () -> Unit) {
GuiActionRunner.execute(object : GuiTask() {
override fun executeInEDT() {
task()
}
})
}
/**
* waits for 30 sec timeout when functionProbeToNull() not return null
*
* @throws WaitTimedOutError with the text: "Timed out waiting for $timeout second(s) until {@code conditionText} will be not null"
*/
fun <ReturnType> withPauseWhenNull(conditionText: String = "function to probe will",
timeout: Timeout = Timeouts.defaultTimeout,
functionProbeToNull: () -> ReturnType?): ReturnType {
var result: ReturnType? = null
waitUntil("$conditionText will be not null", timeout) {
result = functionProbeToNull()
result != null
}
return result!!
}
fun waitUntil(condition: String, timeout: Timeout = Timeouts.defaultTimeout, conditionalFunction: () -> Boolean) {
Pause.pause(object : Condition("${timeout.toPrintable()} until $condition") {
override fun test() = conditionalFunction()
}, timeout)
}
fun <R> tryWithPause(exceptionClass: Class<out Exception>,
condition: String = "try block will not throw ${exceptionClass.name} exception",
timeout: Timeout,
tryBlock: () -> R): R {
val exceptionRef: Ref<Exception> = Ref.create()
try {
return withPauseWhenNull (condition, timeout) {
try {
tryBlock()
}
catch (e: Exception) {
if (exceptionClass.isInstance(e)) {
exceptionRef.set(e)
return@withPauseWhenNull null
}
throw e
}
}
}
catch (e: WaitTimedOutError) {
throw Exception("Timeout for $condition exceeded ${timeout.toPrintable()}", exceptionRef.get())
}
}
fun silentWaitUntil(condition: String, timeoutInSeconds: Int = 60, conditionalFunction: () -> Boolean) {
try {
Pause.pause(object : Condition("$timeoutInSeconds second(s) until $condition silently") {
override fun test() = conditionalFunction()
}, Timeout.timeout(timeoutInSeconds.toLong(), TimeUnit.SECONDS))
}
catch (ignore: WaitTimedOutError) {
}
}
fun <ComponentType : Component> findAllWithBFS(container: Container, clazz: Class<ComponentType>): List<ComponentType> {
val result = LinkedList<ComponentType>()
val queue: Queue<Component> = LinkedList()
@Suppress("UNCHECKED_CAST")
fun check(container: Component) {
if (clazz.isInstance(container)) result.add(container as ComponentType)
}
queue.add(container)
while (queue.isNotEmpty()) {
val polled = queue.poll()
check(polled)
if (polled is Container)
queue.addAll(polled.components)
}
return result
}
fun <ComponentType : Component> waitUntilGone(robot: Robot,
timeout: Timeout = Timeouts.seconds30,
root: Container? = null,
matcher: GenericTypeMatcher<ComponentType>) {
return GuiTestUtil.waitUntilGone(root, timeout, matcher)
}
fun GuiTestCase.waitProgressDialogUntilGone(dialogTitle: String,
timeoutToAppear: Timeout = Timeouts.seconds05,
timeoutToGone: Timeout = Timeouts.defaultTimeout) {
waitProgressDialogUntilGone(this.robot(), dialogTitle, timeoutToAppear, timeoutToGone)
}
fun waitProgressDialogUntilGone(robot: Robot,
progressTitle: String,
timeoutToAppear: Timeout = Timeouts.seconds30,
timeoutToGone: Timeout = Timeouts.defaultTimeout) {
//wait dialog appearance. In a bad case we could pass dialog appearance.
var dialog: JDialog? = null
try {
waitUntil("progress dialog with title $progressTitle will appear", timeoutToAppear) {
dialog = findProgressDialog(robot, progressTitle)
dialog != null
}
}
catch (timeoutError: WaitTimedOutError) {
return
}
waitUntil("progress dialog with title $progressTitle will gone", timeoutToGone) { dialog == null || !dialog!!.isShowing }
}
fun findProgressDialog(robot: Robot, progressTitle: String): JDialog? {
return robot.finder().findAll(typeMatcher(JDialog::class.java) {
findAllWithBFS(it, EngravedLabel::class.java).filter { it.isShowing && it.text == progressTitle }.any()
}).firstOrNull()
}
fun <ComponentType : Component?> typeMatcher(componentTypeClass: Class<ComponentType>,
matcher: (ComponentType) -> Boolean): GenericTypeMatcher<ComponentType> {
return object : GenericTypeMatcher<ComponentType>(componentTypeClass) {
override fun isMatching(component: ComponentType): Boolean = matcher(component)
}
}
fun <ReturnType> computeOnEdt(query: () -> ReturnType): ReturnType? = GuiActionRunner.execute(object : GuiQuery<ReturnType>() {
override fun executeInEDT(): ReturnType = query()
})
fun <ReturnType> computeOnEdtWithTry(query: () -> ReturnType?): ReturnType? {
val result = GuiActionRunner.execute(object : GuiQuery<Pair<ReturnType?, Throwable?>>() {
override fun executeInEDT(): kotlin.Pair<ReturnType?, Throwable?> {
return try {
Pair(query(), null)
}
catch (e: Exception) {
Pair(null, e)
}
}
})
if (result?.second != null) throw result.second!!
return result?.first
}
inline fun <T> ignoreComponentLookupException(action: () -> T): T? = try {
action()
}
catch (ignore: ComponentLookupException) {
null
}
fun ensureCreateHasDone(guiTestCase: GuiTestCase) {
try {
com.intellij.testGuiFramework.impl.GuiTestUtilKt.waitUntilGone(robot = guiTestCase.robot(),
matcher = com.intellij.testGuiFramework.impl.GuiTestUtilKt.typeMatcher(
com.intellij.openapi.wm.impl.welcomeScreen.FlatWelcomeFrame::class.java) { it.isShowing })
}
catch (timeoutError: WaitTimedOutError) {
with(guiTestCase) {
welcomeFrame { button("Create").clickWhenEnabled() }
}
}
}
fun windowsShowing(): List<Window> {
val listBuilder = ArrayList<Window>()
Window.getWindows().filterTo(listBuilder) { it.isShowing }
return listBuilder
}
fun fatalErrorsFromIde(afterDate: Date = Date(0)): List<Error> {
val errorMessages = MessagePool.getInstance().getFatalErrors(true, true)
val freshErrorMessages = errorMessages.filter { it.date > afterDate }
val errors = mutableListOf<Error>()
for (errorMessage in freshErrorMessages) {
val messageBuilder = StringBuilder(errorMessage.message ?: "")
val additionalInfo: String? = errorMessage.additionalInfo
if (additionalInfo != null && additionalInfo.isNotEmpty())
messageBuilder.append(System.getProperty("line.separator")).append("Additional Info: ").append(additionalInfo)
val error = Error(messageBuilder.toString(), errorMessage.throwable)
errors.add(error)
}
return Collections.unmodifiableList(errors)
}
fun waitForBackgroundTasks(robot: Robot, timeoutInSeconds: Int = 120) {
Wait.seconds(timeoutInSeconds.toLong()).expecting("background tasks to finish")
.until {
robot.waitForIdle()
val progressManager = ProgressManager.getInstance()
!progressManager.hasModalProgressIndicator() &&
!progressManager.hasProgressIndicator() &&
!progressManager.hasUnsafeProgressIndicator()
}
}
}
fun main(args: Array<String>) {
val tree = GuiTestUtilKt.createTree("project\n" +
" src\n" +
" com.username\n" +
" Test1.java\n" +
" Test2.java\n" +
" lib\n" +
" someLib1\n" +
" someLib2")
tree.print()
}
| apache-2.0 |
usbpc102/usbBot | src/main/kotlin/usbbot/config/DBCommand.kt | 1 | 4390 | package usbbot.config
import org.apache.commons.dbutils.ResultSetHandler
fun getCommandForGuild(guildID: Long, name: String) : DBCommand? =
DatabaseConnection.queryRunner
.query("SELECT * FROM commands WHERE guildid = ? AND name = ?",
DBCommand.singleCommandHandler,
guildID, name)
fun getCommandsForGuild(guildID: Long) : Collection<DBCommand> =
DatabaseConnection.queryRunner
.query("SELECT * FROM commands WHERE guildid = ?",
DBCommand.allCommandsHandler,
guildID)
fun createDBCommand(guildID: Long, name: String, rolemode: String, usermode: String) : DBCommand {
val ID = DatabaseConnection.queryRunner
.insert("INSERT INTO commands (guildid, name, rolemode, usermode) VALUES (?, ?, ?, ?)",
DBCommand.insertHandler,
guildID, name, rolemode, usermode) ?: throw IllegalStateException("ID shall not be NULL here")
return DBCommand(ID, guildID, name, rolemode, usermode)
}
open class DBCommand(val ID: Int, val guildID: Long, val name: String, var rolemode: String, var usermode: String) : DatabaseEntry() {
companion object {
val insertHandler = ResultSetHandler {
if (it.next()) {
it.getInt(1)
} else {
null
}
}
val allCommandsHandler = ResultSetHandler {
val output = mutableListOf<DBCommand>()
while (it.next()) {
output.add(
DBCommand(
it.getInt(1),
it.getLong(2),
it.getString(3),
it.getString(4),
it.getString(5)))
}
output
}
val singleCommandHandler = ResultSetHandler {
if (it.next()) {
DBCommand(
it.getInt(1),
it.getLong(2),
it.getString(3),
it.getString(4),
it.getString(5))
} else {
null
}
}
}
fun getPermissionRoles() : Collection<Long> =
DatabaseConnection.queryRunner
.query("SELECT roleid FROM permissionRoles WHERE commandid = ?",
MiscResultSetHandlers.longCollection,
ID)
fun getPermissionUsers() : Collection<Long> =
DatabaseConnection.queryRunner
.query("SELECT userid FROM permissionUsers WHERE commandid = ?",
MiscResultSetHandlers.longCollection,
ID)
fun addUserToList(userID: Long) : Int =
DatabaseConnection.queryRunner
.update("INSERT INTO permissionusers (commandid, userid) values (?, ?)",
ID, userID)
fun delUserFromList(userID: Long) : Int =
DatabaseConnection.queryRunner
.update("DELETE FROM permissionusers WHERE commandid = ? AND userid = ?",
ID, userID)
fun addRoleToList(roleID: Long) : Int =
DatabaseConnection.queryRunner
.update("INSERT INTO permissionroles (commandid, roleid) values (?, ?)",
ID, roleID)
fun delRoleFromList(roleID: Long) : Int =
DatabaseConnection.queryRunner
.update("DELETE FROM permissionroles WHERE commandid = ? AND roleid = ?",
ID, roleID)
fun setRoleMode(roleMode: String) : Int {
rolemode = roleMode
return DatabaseConnection.queryRunner
.update("UPDATE commands SET rolemode = ? WHERE commandid = ?",
roleMode, ID)
}
fun setUserMode(userMode: String) : Int {
usermode = userMode
return DatabaseConnection.queryRunner
.update("UPDATE commands SET usermode = ? WHERE commandid = ?",
userMode, ID)
}
override fun delete() : Int =
DatabaseConnection.queryRunner
.update("DELETE FROM commands WHERE id = ?",
ID)
} | mit |
antoniolg/Bandhook-Kotlin | app/src/main/java/com/antonioleiva/bandhookkotlin/di/subcomponent/detail/ArtistActivityModule.kt | 1 | 2246 | package com.antonioleiva.bandhookkotlin.di.subcomponent.detail
import com.antonioleiva.bandhookkotlin.di.ActivityModule
import com.antonioleiva.bandhookkotlin.di.scope.ActivityScope
import com.antonioleiva.bandhookkotlin.domain.interactor.GetArtistDetailInteractor
import com.antonioleiva.bandhookkotlin.domain.interactor.GetTopAlbumsInteractor
import com.antonioleiva.bandhookkotlin.domain.interactor.base.Bus
import com.antonioleiva.bandhookkotlin.domain.interactor.base.InteractorExecutor
import com.antonioleiva.bandhookkotlin.ui.entity.mapper.ArtistDetailDataMapper
import com.antonioleiva.bandhookkotlin.ui.entity.mapper.ImageTitleDataMapper
import com.antonioleiva.bandhookkotlin.ui.presenter.ArtistPresenter
import com.antonioleiva.bandhookkotlin.ui.screens.detail.AlbumsFragment
import com.antonioleiva.bandhookkotlin.ui.screens.detail.ArtistActivity
import com.antonioleiva.bandhookkotlin.ui.screens.detail.BiographyFragment
import com.antonioleiva.bandhookkotlin.ui.view.ArtistView
import dagger.Module
import dagger.Provides
@Module
class ArtistActivityModule(activity: ArtistActivity) : ActivityModule(activity) {
@Provides @ActivityScope
fun provideArtistView(): ArtistView = activity as ArtistView
@Provides @ActivityScope
fun provideArtistDataMapper() = ArtistDetailDataMapper()
@Provides @ActivityScope
fun provideImageTitleDataMapper() = ImageTitleDataMapper()
@Provides @ActivityScope
fun provideActivityPresenter(view: ArtistView,
bus: Bus,
artistDetailInteractor: GetArtistDetailInteractor,
topAlbumsInteractor: GetTopAlbumsInteractor,
interactorExecutor: InteractorExecutor,
detailDataMapper: ArtistDetailDataMapper,
imageTitleDataMapper: ImageTitleDataMapper)
= ArtistPresenter(view, bus, artistDetailInteractor, topAlbumsInteractor,
interactorExecutor, detailDataMapper, imageTitleDataMapper)
@Provides @ActivityScope
fun provideAlbumsFragment() = AlbumsFragment()
@Provides @ActivityScope
fun provideBiographyFragment() = BiographyFragment()
} | apache-2.0 |
yifeidesu/DayPlus-Countdown | app/src/main/java/com/robyn/dayplus2/data/source/enums/EventCategory.kt | 1 | 361 | package com.robyn.dayplus2.data.source.enums
/**
* Enum [MyEvent]'s category values.
*
* Implements [EventFilter] so that [MyEvent].category can act as filter when filter the list
*
* Created by yifei on 11/20/2017.
*/
enum class EventCategory : EventFilter {
CAKE_EVENTS,
LOVED_EVENTS,
FACE_EVENTS,
EXPLORE_EVENTS,
WORK_EVENTS
} | apache-2.0 |
equeim/tremotesf-android | app/src/main/kotlin/org/equeim/tremotesf/ui/torrentslistfragment/AddTorrentMenuFragment.kt | 1 | 1769 | package org.equeim.tremotesf.ui.torrentslistfragment
import android.content.ActivityNotFoundException
import android.os.Bundle
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import org.equeim.tremotesf.R
import org.equeim.tremotesf.databinding.AddTorrentMenuFragmentBinding
import org.equeim.tremotesf.ui.NavigationBottomSheetDialogFragment
import timber.log.Timber
class AddTorrentMenuFragment : NavigationBottomSheetDialogFragment(R.layout.add_torrent_menu_fragment) {
private lateinit var getContentActivityLauncher: ActivityResultLauncher<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
getContentActivityLauncher =
registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
if (uri != null) {
navigate(AddTorrentMenuFragmentDirections.toAddTorrentFileFragment(uri))
} else {
navController.popBackStack()
}
}
}
override fun onViewStateRestored(savedInstanceState: Bundle?) {
super.onViewStateRestored(savedInstanceState)
val binding = AddTorrentMenuFragmentBinding.bind(requireView())
binding.addTorrentFile.setOnClickListener {
startFilePickerActivity()
}
binding.addTorrentLink.setOnClickListener { navigate(AddTorrentMenuFragmentDirections.toAddTorrentLinkFragment()) }
}
private fun startFilePickerActivity() {
try {
getContentActivityLauncher.launch("application/x-bittorrent")
} catch (e: ActivityNotFoundException) {
Timber.e(e, "Failed to start activity")
}
}
} | gpl-3.0 |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/platform/mcp/at/AtLanguage.kt | 1 | 257 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.at
import com.intellij.lang.Language
object AtLanguage : Language("Access Transformers")
| mit |
arturbosch/TiNBo | tinbo-notes/src/main/kotlin/io/gitlab/arturbosch/tinbo/notes/NoteExecutor.kt | 1 | 715 | package io.gitlab.arturbosch.tinbo.notes
import io.gitlab.arturbosch.tinbo.api.config.TinboConfig
import io.gitlab.arturbosch.tinbo.api.model.AbstractExecutor
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
/**
* @author artur
*/
@Component
open class NoteExecutor @Autowired constructor(noteDataHolder: NoteDataHolder,
tinboConfig: TinboConfig) :
AbstractExecutor<NoteEntry, NoteData, DummyNote>(noteDataHolder, tinboConfig) {
override val tableHeader: String
get() = "No.;Message"
override fun newEntry(index: Int, dummy: DummyNote): NoteEntry {
val entry = entriesInMemory[index]
return entry.copy(dummy.message)
}
}
| apache-2.0 |
Le-Chiffre/Yttrium | Server/src/com/rimmer/yttrium/server/Client.kt | 2 | 2276 | package com.rimmer.yttrium.server
import io.netty.bootstrap.Bootstrap
import io.netty.channel.*
import io.netty.channel.epoll.Epoll
import io.netty.channel.epoll.EpollEventLoopGroup
import io.netty.channel.epoll.EpollSocketChannel
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioSocketChannel
/** Connects to a remote server as a client. */
inline fun connect(
loop: EventLoopGroup,
host: String,
port: Int,
timeout: Int = 0,
useNative: Boolean = false,
crossinline pipeline: ChannelPipeline.() -> Unit,
crossinline onFail: (Throwable?) -> Unit
): ChannelFuture {
val channelType = if(useNative && Epoll.isAvailable()) {
EpollSocketChannel::class.java
} else {
NioSocketChannel::class.java
}
val init = object: ChannelInitializer<SocketChannel>() {
override fun initChannel(channel: SocketChannel) { pipeline(channel.pipeline()) }
}
val b = Bootstrap().group(loop).channel(channelType).handler(init)
if(timeout > 0) b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout)
val promise = b.connect(host, port)
promise.addListener {
if(!it.isSuccess) { onFail(it.cause()) }
}
return promise
}
/**
* Runs a client by creating a server context and returning it.
* @param threadCount The number of threads to use. If 0, one thread is created for each cpu.
* @param useNative Use native transport instead of NIO if possible (Linux only).
*/
fun runClient(threadCount: Int = 0, useNative: Boolean = false): ServerContext {
// Create the server thread pools to use for every module.
// Use native Epoll if possible, since it gives much better performance for small packets.
val handlerThreads = if(threadCount == 0) Runtime.getRuntime().availableProcessors() else threadCount
val acceptorGroup: EventLoopGroup
val handlerGroup: EventLoopGroup
if(Epoll.isAvailable() && useNative) {
acceptorGroup = EpollEventLoopGroup(1)
handlerGroup = EpollEventLoopGroup(handlerThreads)
} else {
acceptorGroup = NioEventLoopGroup(1)
handlerGroup = NioEventLoopGroup(handlerThreads)
}
return ServerContext(acceptorGroup, handlerGroup)
} | mit |
bozaro/git-as-svn | src/main/kotlin/svnserver/server/command/UnlockCmd.kt | 1 | 2341 | /*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver.server.command
import org.tmatesoft.svn.core.SVNErrorCode
import org.tmatesoft.svn.core.SVNErrorMessage
import org.tmatesoft.svn.core.SVNException
import ru.bozaro.gitlfs.common.LockConflictException
import svnserver.parser.SvnServerWriter
import svnserver.repository.locks.LockStorage
import svnserver.repository.locks.UnlockTarget
import svnserver.server.SessionContext
import java.io.IOException
/**
* <pre>
* unlock
* params: ( path:string [ token:string ] break-lock:bool )
* response: ( )
</pre> *
*
* @author Marat Radchenko <[email protected]>
*/
class UnlockCmd : BaseCmd<UnlockCmd.Params>() {
override val arguments: Class<out Params>
get() {
return Params::class.java
}
@Throws(IOException::class, SVNException::class)
override fun processCommand(context: SessionContext, args: Params) {
val path: String = context.getRepositoryPath(args.path)
val lockToken: String? = if (args.lockToken.isEmpty()) null else args.lockToken[0]
context.branch.repository.wrapLockWrite { lockStorage: LockStorage ->
try {
lockStorage.unlock(context.user, context.branch, args.breakLock, arrayOf(UnlockTarget(context.getRepositoryPath(path), lockToken)))
} catch (e: LockConflictException) {
throw SVNException(SVNErrorMessage.create(SVNErrorCode.FS_BAD_LOCK_TOKEN, e.lock.path))
}
true
}
val writer: SvnServerWriter = context.writer
writer
.listBegin()
.word("success")
.listBegin()
.listEnd()
.listEnd()
}
@Throws(IOException::class, SVNException::class)
override fun permissionCheck(context: SessionContext, args: Params) {
context.checkWrite(context.getRepositoryPath(args.path))
}
class Params constructor(val path: String, val lockToken: Array<String>, val breakLock: Boolean)
}
| gpl-2.0 |
cashapp/sqldelight | sqldelight-gradle-plugin/src/test/kotlin/app/cash/sqldelight/tests/GenerateSchemaTest.kt | 1 | 2662 | package app.cash.sqldelight.tests
import app.cash.sqldelight.withCommonConfiguration
import com.google.common.truth.Truth.assertThat
import org.gradle.testkit.runner.GradleRunner
import org.junit.Test
import java.io.File
class GenerateSchemaTest {
@Test fun `schema file generates correctly`() {
val fixtureRoot = File("src/test/schema-file")
val schemaFile = File(fixtureRoot, "src/main/sqldelight/databases/1.db")
if (schemaFile.exists()) schemaFile.delete()
GradleRunner.create()
.withCommonConfiguration(fixtureRoot)
.withArguments("clean", "generateMainDatabaseSchema", "--stacktrace")
.build()
// verify
assertThat(schemaFile.exists())
.isTrue()
schemaFile.delete()
}
@Test fun `generateSchema task can run twice`() {
val fixtureRoot = File("src/test/schema-file")
val schemaFile = File(fixtureRoot, "src/main/sqldelight/databases/1.db")
if (schemaFile.exists()) schemaFile.delete()
GradleRunner.create()
.withCommonConfiguration(fixtureRoot)
.withArguments("clean", "generateMainDatabaseSchema", "--stacktrace")
.build()
// verify
assertThat(schemaFile.exists())
.isTrue()
val lastModified = schemaFile.lastModified()
while (System.currentTimeMillis() - lastModified <= 1000) {
// last modified only updates per second.
Thread.yield()
}
GradleRunner.create()
.withCommonConfiguration(fixtureRoot)
.withArguments("clean", "--rerun-tasks", "generateMainDatabaseSchema", "--stacktrace")
.build()
// verify
assertThat(schemaFile.exists()).isTrue()
assertThat(schemaFile.lastModified()).isNotEqualTo(lastModified)
schemaFile.delete()
}
@Test fun `schema file generates correctly with existing sqm files`() {
val fixtureRoot = File("src/test/schema-file-sqm")
GradleRunner.create()
.withCommonConfiguration(fixtureRoot)
.withArguments("clean", "generateMainDatabaseSchema", "--stacktrace")
.build()
// verify
val schemaFile = File(fixtureRoot, "src/main/sqldelight/databases/3.db")
assertThat(schemaFile.exists())
.isTrue()
schemaFile.delete()
}
@Test fun `schema file generates correctly for android`() {
val fixtureRoot = File("src/test/schema-file-android")
val schemaFile = File(fixtureRoot, "src/main/sqldelight/databases/1.db")
if (schemaFile.exists()) schemaFile.delete()
GradleRunner.create()
.withCommonConfiguration(fixtureRoot)
.withArguments("clean", "generateDebugDatabaseSchema", "--stacktrace")
.build()
// verify
assertThat(schemaFile.exists()).isTrue()
}
}
| apache-2.0 |
jitsi/jicofo | jicofo/src/test/kotlin/org/jitsi/jicofo/bridge/BridgePinTest.kt | 1 | 5441 | /*
* Jicofo, the Jitsi Conference Focus.
*
* Copyright @ 2022-Present 8x8, 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 org.jitsi.jicofo.bridge
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.matchers.shouldBe
import org.jitsi.jicofo.FocusManager
import org.jitsi.utils.time.FakeClock
import org.json.simple.JSONArray
import org.json.simple.JSONObject
import org.jxmpp.jid.impl.JidCreate
import java.time.Duration
/**
* Test conference pin operations.
*/
class BridgePinTest : ShouldSpec() {
private val conf1 = JidCreate.entityBareFrom("[email protected]")
private val conf2 = JidCreate.entityBareFrom("[email protected]")
private val conf3 = JidCreate.entityBareFrom("[email protected]")
private val v1 = "1.1.1"
private val v2 = "2.2.2"
private val v3 = "3.3.3"
init {
context("basic functionality") {
val clock = FakeClock()
val focusManager = FocusManager(clock)
focusManager.pinConference(conf1, v1, Duration.ofMinutes(10))
focusManager.pinConference(conf2, v2, Duration.ofMinutes(12))
focusManager.pinConference(conf3, v3, Duration.ofMinutes(14))
should("pin correctly") {
getNumPins(focusManager.getPinnedConferencesJson()) shouldBe 3
focusManager.getBridgeVersionForConference(conf1) shouldBe v1
focusManager.getBridgeVersionForConference(conf2) shouldBe v2
focusManager.getBridgeVersionForConference(conf3) shouldBe v3
}
should("expire") {
clock.elapse(Duration.ofMinutes(11))
getNumPins(focusManager.getPinnedConferencesJson()) shouldBe 2
focusManager.getBridgeVersionForConference(conf1) shouldBe null
focusManager.getBridgeVersionForConference(conf2) shouldBe v2
focusManager.getBridgeVersionForConference(conf3) shouldBe v3
clock.elapse(Duration.ofMinutes(2))
getNumPins(focusManager.getPinnedConferencesJson()) shouldBe 1
focusManager.getBridgeVersionForConference(conf1) shouldBe null
focusManager.getBridgeVersionForConference(conf2) shouldBe null
focusManager.getBridgeVersionForConference(conf3) shouldBe v3
clock.elapse(Duration.ofMinutes(2))
getNumPins(focusManager.getPinnedConferencesJson()) shouldBe 0
focusManager.getBridgeVersionForConference(conf1) shouldBe null
focusManager.getBridgeVersionForConference(conf2) shouldBe null
focusManager.getBridgeVersionForConference(conf3) shouldBe null
}
}
context("modifications") {
val clock = FakeClock()
val focusManager = FocusManager(clock)
focusManager.pinConference(conf1, v1, Duration.ofMinutes(10))
focusManager.pinConference(conf2, v2, Duration.ofMinutes(12))
focusManager.pinConference(conf3, v3, Duration.ofMinutes(14))
should("unpin") {
focusManager.unpinConference(conf3)
getNumPins(focusManager.getPinnedConferencesJson()) shouldBe 2
focusManager.getBridgeVersionForConference(conf1) shouldBe v1
focusManager.getBridgeVersionForConference(conf2) shouldBe v2
focusManager.getBridgeVersionForConference(conf3) shouldBe null
}
should("modify version and timeout") {
clock.elapse(Duration.ofMinutes(4))
focusManager.pinConference(conf1, v3, Duration.ofMinutes(10))
getNumPins(focusManager.getPinnedConferencesJson()) shouldBe 2
focusManager.getBridgeVersionForConference(conf1) shouldBe v3
focusManager.getBridgeVersionForConference(conf2) shouldBe v2
focusManager.getBridgeVersionForConference(conf3) shouldBe null
clock.elapse(Duration.ofMinutes(9))
getNumPins(focusManager.getPinnedConferencesJson()) shouldBe 1
focusManager.getBridgeVersionForConference(conf1) shouldBe v3
focusManager.getBridgeVersionForConference(conf2) shouldBe null
focusManager.getBridgeVersionForConference(conf3) shouldBe null
clock.elapse(Duration.ofMinutes(2))
getNumPins(focusManager.getPinnedConferencesJson()) shouldBe 0
focusManager.getBridgeVersionForConference(conf1) shouldBe null
focusManager.getBridgeVersionForConference(conf2) shouldBe null
focusManager.getBridgeVersionForConference(conf3) shouldBe null
}
}
}
}
fun getNumPins(obj: JSONObject): Int {
val pins = obj["pins"]
if (pins is JSONArray)
return pins.size
else
return -1
}
| apache-2.0 |
edvin/tornadofx | src/test/kotlin/tornadofx/tests/EventBusTest.kt | 1 | 1463 | package tornadofx.tests
import javafx.application.Platform
import javafx.stage.Stage
import org.junit.Test
import org.testfx.api.FxToolkit
import tornadofx.*
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import kotlin.test.assertTrue
class EventBusTest {
val primaryStage: Stage = FxToolkit.registerPrimaryStage()
private val success = AtomicBoolean(true)
private val latch = Latch()
init {
FxToolkit.setupFixture {
Thread.setDefaultUncaughtExceptionHandler { _, t ->
t.printStackTrace()
success.set(false)
latch.countDown()
}
}
}
val iterations: Int = 100
val count = AtomicInteger(0)
val view = object : View() {
init {
for (i in 1..iterations) {
subscribe<FXEvent>(times = i) {
callOnUndock()
print(" ${count.getAndIncrement()} ")
callOnDock()
}
}
}
override val root = vbox {}
}
@Test
fun testUnsubscribe() {
Platform.runLater {
view.callOnDock()
repeat(iterations / 2) {
view.fire(FXEvent())
view.fire(FXEvent(EventBus.RunOn.BackgroundThread))
}
latch.countDown()
}
latch.await()
assertTrue(success.get())
}
}
| apache-2.0 |
martin-nordberg/KatyDOM | Katydid-VDOM-JS/src/main/kotlin/i/katydid/vdom/elements/edits/KatydidIns.kt | 1 | 2754 | //
// (C) Copyright 2018-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package i.katydid.vdom.elements.edits
import i.katydid.vdom.builders.KatydidFlowContentBuilderImpl
import i.katydid.vdom.builders.KatydidPhrasingContentBuilderImpl
import i.katydid.vdom.elements.KatydidHtmlElementImpl
import o.katydid.vdom.builders.KatydidFlowContentBuilder
import o.katydid.vdom.builders.KatydidPhrasingContentBuilder
import o.katydid.vdom.types.EDirection
import o.katydid.vdom.types.FlowContent
import x.katydid.vdom.types.KatyDateTime
//---------------------------------------------------------------------------------------------------------------------
/**
* Virtual node for an `<ins>` element.
*/
internal class KatydidIns<Msg>
: KatydidHtmlElementImpl<Msg> {
constructor(
phrasingContent: KatydidPhrasingContentBuilderImpl<Msg>,
selector: String?,
key: Any?,
accesskey: Char?,
cite: String?,
contenteditable: Boolean?,
datetime: KatyDateTime?,
dir: EDirection?,
draggable: Boolean?,
hidden: Boolean?,
lang: String?,
spellcheck: Boolean?,
style: String?,
tabindex: Int?,
title: String?,
translate: Boolean?,
defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit
) : super(selector, key, accesskey, contenteditable, dir, draggable,
hidden, lang, spellcheck, style, tabindex, title, translate) {
setAttribute("cite", cite)
setDateTimeAttribute("datetime", datetime)
phrasingContent.withNoAddedRestrictions(this).defineContent()
this.freeze()
}
@Suppress("UNUSED_PARAMETER")
constructor(
flowContent: KatydidFlowContentBuilderImpl<Msg>,
selector: String?,
key: Any?,
accesskey: Char?,
cite: String?,
contenteditable: Boolean?,
datetime: KatyDateTime?,
dir: EDirection?,
draggable: Boolean?,
hidden: Boolean?,
lang: String?,
spellcheck: Boolean?,
style: String?,
tabindex: Int?,
title: String?,
translate: Boolean?,
contentType: FlowContent,
defineContent: KatydidFlowContentBuilder<Msg>.() -> Unit
) : super(selector, key, accesskey, contenteditable, dir, draggable,
hidden, lang, spellcheck, style, tabindex, title, translate) {
setAttribute("cite", cite)
setDateTimeAttribute("datetime", datetime)
flowContent.withNoAddedRestrictions(this).defineContent()
this.freeze()
}
////
override val nodeName = "INS"
}
//---------------------------------------------------------------------------------------------------------------------
| apache-2.0 |
permissions-dispatcher/PermissionsDispatcher | test/src/test/java/permissions/dispatcher/test/ActivityWithSystemAlertWindowAllAnnotationsPermissionsDispatcherTest.kt | 1 | 4965 | package permissions.dispatcher.test
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.core.app.ActivityCompat
import androidx.core.app.AppOpsManagerCompat
import androidx.core.content.ContextCompat
import org.junit.After
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Matchers
import org.mockito.Mockito
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
import permissions.dispatcher.PermissionRequest
import permissions.dispatcher.test.ActivityWithSystemAlertWindowAllAnnotationsPermissionsDispatcher.onActivityResult
import permissions.dispatcher.test.ActivityWithSystemAlertWindowAllAnnotationsPermissionsDispatcher.systemAlertWindowWithPermissionCheck
@Suppress("IllegalIdentifier")
@RunWith(PowerMockRunner::class)
@PrepareForTest(ActivityCompat::class, ContextCompat::class,
AppOpsManagerCompat::class, Settings::class, Build.VERSION::class, Uri::class)
class ActivityWithSystemAlertWindowAllAnnotationsPermissionsDispatcherTest {
private lateinit var activity: ActivityWithSystemAlertWindowAllAnnotations
companion object {
private var requestCode = 0
@BeforeClass
@JvmStatic
fun setUpForClass() {
requestCode = getRequestSystemAlertWindow(ActivityWithSystemAlertWindowAllAnnotationsPermissionsDispatcher::class.java)
}
}
@Before
fun setUp() {
activity = Mockito.mock(ActivityWithSystemAlertWindowAllAnnotations::class.java)
PowerMockito.mockStatic(ActivityCompat::class.java)
PowerMockito.mockStatic(ContextCompat::class.java)
PowerMockito.mockStatic(Settings::class.java)
PowerMockito.mockStatic(Uri::class.java)
PowerMockito.mockStatic(Build.VERSION::class.java)
PowerMockito.field(Build.VERSION::class.java, "SDK_INT").setInt(null, 25)
}
@After
fun tearDown() {
clearCustomSdkInt()
}
@Test
fun `already granted call the method`() {
mockCheckSelfPermission(true)
systemAlertWindowWithPermissionCheck(activity)
Mockito.verify(activity, Mockito.times(1)).systemAlertWindow()
}
@Test
fun `checkSelfPermission returns false but canDrawOverlays returns true means granted`() {
mockCheckSelfPermission(false)
mockCanDrawOverlays(true)
systemAlertWindowWithPermissionCheck(activity)
Mockito.verify(activity, Mockito.times(1)).systemAlertWindow()
}
@Test
fun `if permission not granted and no rationale activity, then call startActivityForResult`() {
mockCheckSelfPermission(false)
mockCanDrawOverlays(false)
mockUriParse()
mockShouldShowRequestPermissionRationaleActivity(false)
systemAlertWindowWithPermissionCheck(activity)
Mockito.verify(activity, Mockito.times(1)).startActivityForResult(Matchers.any(Intent::class.java), Matchers.eq(requestCode))
}
@Test
fun `if permission not granted and requires rationale activity, then call method for show rationale`() {
mockCheckSelfPermission(false)
mockCanDrawOverlays(false)
mockUriParse()
mockShouldShowRequestPermissionRationaleActivity(true)
systemAlertWindowWithPermissionCheck(activity)
Mockito.verify(activity, Mockito.times(1)).showRationaleForSystemAlertWindow(Matchers.any(PermissionRequest::class.java))
}
@Test
fun `do nothing if requestCode is wrong one`() {
onActivityResult(activity, -1)
Mockito.verify(activity, Mockito.times(0)).systemAlertWindow()
}
@Test
fun `call the method if permission granted`() {
mockCheckSelfPermission(true)
onActivityResult(activity, requestCode)
Mockito.verify(activity, Mockito.times(1)).systemAlertWindow()
}
@Test
fun `call the method if canDrawOverlays returns true`() {
mockCheckSelfPermission(false)
mockCanDrawOverlays(true)
onActivityResult(activity, requestCode)
Mockito.verify(activity, Mockito.times(1)).systemAlertWindow()
}
@Test
fun `No call the method if permission not granted`() {
mockCheckSelfPermission(false)
mockCanDrawOverlays(false)
onActivityResult(activity, requestCode)
Mockito.verify(activity, Mockito.times(0)).systemAlertWindow()
}
@Test
fun `call showDenied method if permission not granted and shouldShowRequestPermissionRationale true`() {
mockCheckSelfPermission(false)
mockCanDrawOverlays(false)
mockShouldShowRequestPermissionRationaleActivity(true)
onActivityResult(activity, requestCode)
Mockito.verify(activity, Mockito.times(1)).showDeniedForSystemAlertWindow()
}
} | apache-2.0 |
jjtParadox/Barometer | src/test/kotlin/com/jjtparadox/barometer/test/BarometerExampleTest.kt | 1 | 2552 | package com.jjtparadox.barometer.test
import com.jjtparadox.barometer.Barometer
import com.jjtparadox.barometer.TestUtils
import com.jjtparadox.barometer.tester.BarometerTester
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.assertSame
import junit.framework.TestCase.assertTrue
import junit.framework.TestCase.fail
import net.minecraft.init.Blocks
import net.minecraft.init.Items
import net.minecraft.item.ItemStack
import net.minecraft.tileentity.TileEntityFurnace
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(BarometerTester::class)
class BarometerExampleTest {
@Test
fun testThatThisHackWorks() {
println("One test successful!")
}
lateinit var world: World
@Before
fun setUp() {
world = Barometer.server.entityWorld
}
@Test
fun testFurnacePlacement() {
if (Blocks.FURNACE != null) {
val pos = BlockPos.ORIGIN
world.setBlockState(pos, Blocks.FURNACE.defaultState)
val state = world.getBlockState(pos)
val block = state.block
assertEquals(block, Blocks.FURNACE)
val tile = world.getTileEntity(pos)
assertSame(tile?.javaClass, TileEntityFurnace::class.java)
} else {
fail("Blocks.FURNACE is null")
}
}
@Test
fun testFurnaceRemoval() {
val pos = BlockPos.ORIGIN
world.setBlockState(pos, Blocks.FURNACE.defaultState)
world.setBlockToAir(pos)
TestUtils.tickServer()
assertTrue(world.getTileEntity(pos) == null)
}
@Test
fun testFurnaceSmelt() {
val pos = BlockPos.ORIGIN
world.setBlockState(pos, Blocks.FURNACE.defaultState)
val furnace = world.getTileEntity(pos) as TileEntityFurnace
val coal = ItemStack(Items.COAL)
val ore = ItemStack(Blocks.IRON_ORE)
val ingot = ItemStack(Items.IRON_INGOT)
val furnaceData = furnace.tileData
var cookTime: Int
// 0 = input, 1 = fuel, 2 = output
furnace.setInventorySlotContents(0, ore)
furnace.setInventorySlotContents(1, coal)
for (i in 0..2399) {
TestUtils.tickServer()
cookTime = furnaceData.getInteger("CookTime")
if (cookTime > 0 && !furnace.getStackInSlot(2).isEmpty) {
break
}
}
assertTrue(ingot.isItemEqual(furnace.getStackInSlot(2)))
}
}
| lgpl-3.0 |
vlad1m1r990/KotlinSample | app/src/main/java/com/vlad1m1r/kotlintest/presentation/base/BaseViewHolder.kt | 1 | 809 | /*
* Copyright 2017 Vladimir Jovanovic
*
* 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.vlad1m1r.kotlintest.presentation.base
import android.support.v7.widget.RecyclerView
import android.view.View
abstract class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
| apache-2.0 |
pokk/KotlinKnifer | kotlinshaver/src/main/java/com/devrapid/kotlinshaver/ArrayList.kt | 1 | 286 | package com.devrapid.kotlinshaver
fun <E> ArrayList<E>.removeRange(range: IntRange) =
if (!(range.first in 0 until size && range.last in 0 until size && range.first > range.last)) {
false
}
else {
subList(range.first, range.last).clear()
true
}
| apache-2.0 |
shlusiak/Freebloks-Android | game/src/main/java/de/saschahlusiak/freebloks/network/message/MessageRequestUndo.kt | 1 | 261 | package de.saschahlusiak.freebloks.network.message
import de.saschahlusiak.freebloks.network.*
class MessageRequestUndo: Message(MessageType.RequestUndo, 0) {
override fun equals(other: Any?) = other is MessageRequestUndo
override fun hashCode() = 0
} | gpl-2.0 |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/activity/content/AbsStatusDialogActivity.kt | 1 | 3440 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.activity.content
import android.content.Intent
import android.os.Bundle
import de.vanita5.twittnuker.TwittnukerConstants.REQUEST_SELECT_ACCOUNT
import de.vanita5.twittnuker.activity.AccountSelectorActivity
import de.vanita5.twittnuker.activity.BaseActivity
import de.vanita5.twittnuker.constant.IntentConstants.*
import de.vanita5.twittnuker.model.ParcelableStatus
import de.vanita5.twittnuker.model.UserKey
abstract class AbsStatusDialogActivity : BaseActivity() {
private val statusId: String?
get() = intent.getStringExtra(EXTRA_STATUS_ID)
private val accountKey: UserKey?
get() = intent.getParcelableExtra(EXTRA_ACCOUNT_KEY)
private val accountHost: String?
get() = intent.getStringExtra(EXTRA_ACCOUNT_HOST)
private val status: ParcelableStatus?
get() = intent.getParcelableExtra(EXTRA_STATUS)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
val statusId = this.statusId ?: run {
setResult(RESULT_CANCELED)
finish()
return
}
val accountKey = this.accountKey
if (accountKey != null) {
showDialogFragment(accountKey, statusId, status)
} else {
val intent = Intent(this, AccountSelectorActivity::class.java)
intent.putExtra(EXTRA_SINGLE_SELECTION, true)
intent.putExtra(EXTRA_SELECT_ONLY_ITEM_AUTOMATICALLY, true)
intent.putExtra(EXTRA_ACCOUNT_HOST, accountHost)
startActivityForResult(intent, REQUEST_SELECT_ACCOUNT)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
REQUEST_SELECT_ACCOUNT -> {
if (resultCode == RESULT_OK && data != null) {
val statusId = this.statusId ?: run {
setResult(RESULT_CANCELED)
finish()
return
}
val accountKey = data.getParcelableExtra<UserKey>(EXTRA_ACCOUNT_KEY)
showDialogFragment(accountKey, statusId, status)
return
}
}
}
finish()
}
protected abstract fun showDialogFragment(accountKey: UserKey, statusId: String,
status: ParcelableStatus?)
} | gpl-3.0 |
DarrenAtherton49/android-kotlin-base | app/src/main/kotlin/com/atherton/sample/presentation/features/settings/licenses/LicensesList.kt | 1 | 12719 | package com.atherton.sample.presentation.features.settings.licenses
import android.content.Context
import com.atherton.sample.R
private const val APACHE_2_0_URL = "https://www.apache.org/licenses/LICENSE-2.0"
private const val GROUPIE_LICENSE_URL = "https://github.com/lisawray/groupie/blob/master/LICENSE"
private const val GLIDE_LICENSE_URL = "https://github.com/bumptech/glide/blob/master/LICENSE"
internal fun generateLicenses(context: Context): List<License> {
with(context) {
var id = 0L
val appCompat = License(
id = ++id,
name = getString(R.string.license_app_compat_name),
contributor = getString(R.string.license_contributor_android_open_source),
description = getString(R.string.license_app_compat_description),
url = APACHE_2_0_URL
)
val constraintLayout = License(
id = ++id,
name = getString(R.string.license_constraint_layout_name),
contributor = getString(R.string.license_contributor_android_open_source),
description = getString(R.string.license_constraint_layout_description),
url = APACHE_2_0_URL
)
val dagger2 = License(
id = ++id,
name = getString(R.string.license_dagger_2_name),
contributor = getString(R.string.license_contributor_dagger_2_authors),
description = getString(R.string.license_dagger_2_description),
url = APACHE_2_0_URL
)
val dagger2Compiler = License(
id = ++id,
name = getString(R.string.license_dagger_2_compiler_name),
contributor = getString(R.string.license_contributor_dagger_2_authors),
description = getString(R.string.license_dagger_2_compiler_description),
url = APACHE_2_0_URL
)
val glide = License(
id = ++id,
name = getString(R.string.license_glide_name),
contributor = getString(R.string.license_contributor_google_inc),
description = getString(R.string.license_glide_description),
url = GLIDE_LICENSE_URL
)
val glideCompiler = License(
id = ++id,
name = getString(R.string.license_glide_compiler_name),
contributor = getString(R.string.license_contributor_google_inc),
description = getString(R.string.license_glide_compiler_description),
url = GLIDE_LICENSE_URL
)
val groupie = License(
id = ++id,
name = getString(R.string.license_groupie_name),
contributor = getString(R.string.license_contributor_lisa_wray),
description = getString(R.string.license_groupie_description),
url = GROUPIE_LICENSE_URL
)
val kotlin = License(
id = ++id,
name = getString(R.string.license_kotlin_name),
contributor = getString(R.string.license_contributor_jetbrains),
description = getString(R.string.license_kotlin_description),
url = APACHE_2_0_URL
)
val kotlinReflect = License(
id = ++id,
name = getString(R.string.license_kotlin_reflect_name),
contributor = getString(R.string.license_contributor_jetbrains),
description = getString(R.string.license_kotlin_reflect_description),
url = APACHE_2_0_URL
)
val materialComponents = License(
id = ++id,
name = getString(R.string.license_material_components_name),
contributor = getString(R.string.license_contributor_google_inc),
description = getString(R.string.license_material_components_description),
url = APACHE_2_0_URL
)
val leakCanary = License(
id = ++id,
name = getString(R.string.license_leak_canary_name),
contributor = getString(R.string.license_contributor_square_inc),
description = getString(R.string.license_leak_canary_description),
url = APACHE_2_0_URL
)
val leakCanaryFragment = License(
id = ++id,
name = getString(R.string.license_leak_canary_fragment_name),
contributor = getString(R.string.license_contributor_square_inc),
description = getString(R.string.license_leak_canary_fragment_description),
url = APACHE_2_0_URL
)
val leakCanaryNoOp = License(
id = ++id,
name = getString(R.string.license_leak_canary_no_op_name),
contributor = getString(R.string.license_contributor_square_inc),
description = getString(R.string.license_leak_canary_no_op_description),
url = APACHE_2_0_URL
)
val lifecycleCompiler = License(
id = ++id,
name = getString(R.string.license_lifecycle_compiler_name),
contributor = getString(R.string.license_contributor_android_open_source),
description = getString(R.string.license_lifecycle_compiler_description),
url = APACHE_2_0_URL
)
val lifecycleExtensions = License(
id = ++id,
name = getString(R.string.license_lifecycle_extensions_name),
contributor = getString(R.string.license_contributor_android_open_source),
description = getString(R.string.license_lifecycle_extensions_description),
url = APACHE_2_0_URL
)
val moshi = License(
id = ++id,
name = getString(R.string.license_moshi_name),
contributor = getString(R.string.license_contributor_square_inc),
description = getString(R.string.license_moshi_description),
url = APACHE_2_0_URL
)
val moshiKotlin = License(
id = ++id,
name = getString(R.string.license_moshi_kotlin_name),
contributor = getString(R.string.license_contributor_square_inc),
description = getString(R.string.license_moshi_kotlin_description),
url = APACHE_2_0_URL
)
val navigationFragment = License(
id = ++id,
name = getString(R.string.license_navigation_fragment_ktx_name),
contributor = getString(R.string.license_contributor_android_open_source),
description = getString(R.string.license_navigation_fragment_ktx_description),
url = APACHE_2_0_URL
)
val navigationUI = License(
id = ++id,
name = getString(R.string.license_navigation_ui_ktx_name),
contributor = getString(R.string.license_contributor_android_open_source),
description = getString(R.string.license_navigation_ui_ktx_description),
url = APACHE_2_0_URL
)
val okHttpLoggingInterceptor = License(
id = ++id,
name = getString(R.string.license_ok_http_logging_interceptor_name),
contributor = getString(R.string.license_contributor_square_inc),
description = getString(R.string.license_ok_http_logging_interceptor_description),
url = APACHE_2_0_URL
)
val palette = License(
id = ++id,
name = getString(R.string.license_palette_name),
contributor = getString(R.string.license_contributor_android_open_source),
description = getString(R.string.license_palette_description),
url = APACHE_2_0_URL
)
val recyclerView = License(
id = ++id,
name = getString(R.string.license_recycler_view_name),
contributor = getString(R.string.license_contributor_android_open_source),
description = getString(R.string.license_recycler_view_description),
url = APACHE_2_0_URL
)
val retrofit = License(
id = ++id,
name = getString(R.string.license_retrofit_name),
contributor = getString(R.string.license_contributor_square_inc),
description = getString(R.string.license_retrofit_description),
url = APACHE_2_0_URL
)
val retrofitMoshi = License(
id = ++id,
name = getString(R.string.license_retrofit_moshi_name),
contributor = getString(R.string.license_contributor_square_inc),
description = getString(R.string.license_retrofit_moshi_description),
url = APACHE_2_0_URL
)
val retrofitRxJava2Adapter = License(
id = ++id,
name = getString(R.string.license_retrofit_rxjava_2_adapter_name),
contributor = getString(R.string.license_contributor_square_inc),
description = getString(R.string.license_retrofit_rxjava_2_adapter_description),
url = APACHE_2_0_URL
)
val roomRuntime = License(
id = ++id,
name = getString(R.string.license_room_runtime_name),
contributor = getString(R.string.license_contributor_android_open_source),
description = getString(R.string.license_room_runtime_description),
url = APACHE_2_0_URL
)
val roomCompiler = License(
id = ++id,
name = getString(R.string.license_room_compiler_name),
contributor = getString(R.string.license_contributor_android_open_source),
description = getString(R.string.license_room_compiler_description),
url = APACHE_2_0_URL
)
val roomRxJava2 = License(
id = ++id,
name = getString(R.string.license_room_rxjava2_name),
contributor = getString(R.string.license_contributor_android_open_source),
description = getString(R.string.license_room_rxjava2_description),
url = APACHE_2_0_URL
)
val roxie = License(
id = ++id,
name = getString(R.string.license_roxie_name),
contributor = getString(R.string.license_contributor_ww_tech),
description = getString(R.string.license_roxie_description),
url = APACHE_2_0_URL
)
val rxAndroid = License(
id = ++id,
name = getString(R.string.license_rx_android_name),
contributor = getString(R.string.license_contributor_rx_android_authors),
description = getString(R.string.license_rx_android_description),
url = APACHE_2_0_URL
)
val rxJava2 = License(
id = ++id,
name = getString(R.string.license_rxjava_2_name),
contributor = getString(R.string.license_contributor_rxjava_2_authors),
description = getString(R.string.license_rxjava_2_description),
url = APACHE_2_0_URL
)
val rxKotlin = License(
id = ++id,
name = getString(R.string.license_rxkotlin_name),
contributor = getString(R.string.license_contributor_rxjava_2_authors),
description = getString(R.string.license_rxkotlin_description),
url = APACHE_2_0_URL
)
val rxRelay = License(
id = ++id,
name = getString(R.string.license_rxrelay_name),
contributor = getString(R.string.license_contributor_netflix_and_jake_wharton),
description = getString(R.string.license_rxrelay_description),
url = APACHE_2_0_URL
)
val timber = License(
id = ++id,
name = getString(R.string.license_timber_name),
contributor = getString(R.string.license_contributor_jake_wharton),
description = getString(R.string.license_timber_description),
url = APACHE_2_0_URL
)
return listOf(
appCompat,
constraintLayout,
dagger2,
dagger2Compiler,
glide,
glideCompiler,
groupie,
kotlin,
kotlinReflect,
materialComponents,
leakCanary,
leakCanaryFragment,
leakCanaryNoOp,
lifecycleCompiler,
lifecycleExtensions,
moshi,
moshiKotlin,
navigationFragment,
navigationUI,
okHttpLoggingInterceptor,
palette,
recyclerView,
retrofit,
retrofitMoshi,
retrofitRxJava2Adapter,
roomRuntime,
roomCompiler,
roomRxJava2,
roxie,
rxAndroid,
rxJava2,
rxKotlin,
rxRelay,
timber
).sortedBy { it.name }
}
}
| mit |
stripe/stripe-android | payments-core/src/test/java/com/stripe/android/model/parsers/PaymentIntentJsonParserTest.kt | 1 | 14514 | package com.stripe.android.model.parsers
import android.net.Uri
import com.google.common.truth.Truth.assertThat
import com.stripe.android.LUXE_NEXT_ACTION
import com.stripe.android.model.Address
import com.stripe.android.model.LuxePostConfirmActionCreator
import com.stripe.android.model.LuxePostConfirmActionRepository
import com.stripe.android.model.MicrodepositType
import com.stripe.android.model.PaymentIntent
import com.stripe.android.model.PaymentIntentFixtures
import com.stripe.android.model.StripeIntent
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import kotlin.test.Test
@RunWith(RobolectricTestRunner::class)
class PaymentIntentJsonParserTest {
@Test
fun parse_withExpandedPaymentMethod_shouldCreateExpectedObject() {
val paymentIntent = PaymentIntentJsonParser().parse(
PaymentIntentFixtures.EXPANDED_PAYMENT_METHOD_JSON
)
assertThat(paymentIntent?.paymentMethodId)
.isEqualTo("pm_1GSTxOCRMbs6FrXfYCosDqyr")
assertThat(paymentIntent?.paymentMethod?.id)
.isEqualTo("pm_1GSTxOCRMbs6FrXfYCosDqyr")
}
@Test
fun parse_withShipping_shouldCreateExpectedObject() {
val paymentIntent = PaymentIntentJsonParser().parse(
PaymentIntentFixtures.PI_WITH_SHIPPING_JSON
)
assertThat(paymentIntent?.shipping)
.isEqualTo(
PaymentIntent.Shipping(
address = Address(
line1 = "123 Market St",
line2 = "#345",
city = "San Francisco",
state = "CA",
postalCode = "94107",
country = "US"
),
carrier = "UPS",
name = "Jenny Rosen",
phone = "1-800-555-1234",
trackingNumber = "12345"
)
)
}
@Test
fun parse_withOxxo_shouldCreateExpectedNextActionData() {
val paymentIntent = requireNotNull(
PaymentIntentJsonParser().parse(
PaymentIntentFixtures.OXXO_REQUIRES_ACTION_JSON
)
)
assertThat(paymentIntent.nextActionData)
.isEqualTo(
StripeIntent.NextActionData.DisplayOxxoDetails(
expiresAfter = 1617944399,
number = "12345678901234657890123456789012",
hostedVoucherUrl = "https://payments.stripe.com/oxxo/voucher/test_YWNjdF8xSWN1c1VMMzJLbFJvdDAxLF9KRlBtckVBMERWM0lBZEUyb"
)
)
}
@Test
fun parse_withRedirectAction_shouldCreateExpectedNextActionData() {
val paymentIntent = PaymentIntentFixtures.PI_REQUIRES_REDIRECT
assertThat(paymentIntent.nextActionData)
.isEqualTo(
StripeIntent.NextActionData.RedirectToUrl(
Uri.parse("https://hooks.stripe.com/3d_secure_2_eap/begin_test/src_1Ecaz6CRMbs6FrXfuYKBRSUG/src_client_secret_F6octeOshkgxT47dr0ZxSZiv"),
returnUrl = "stripe://deeplink"
)
)
}
@Test
fun parse_with3ds1Action_shouldCreateExpectedNextActionData() {
val paymentIntent = PaymentIntentFixtures.PI_REQUIRES_3DS1
assertThat(paymentIntent.nextActionData)
.isEqualTo(
StripeIntent.NextActionData.SdkData.Use3DS1(
"https://hooks.stripe.com/3d_secure_2_eap/begin_test/src_1Ecve7CRMbs6FrXfm8AxXMIh/src_client_secret_F79yszOBAiuaZTuIhbn3LPUW"
)
)
}
@Test
fun parse_with3ds2Action_shouldCreateExpectedNextActionData() {
val paymentIntent = PaymentIntentFixtures.PI_REQUIRES_MASTERCARD_3DS2
assertThat(paymentIntent.nextActionData)
.isEqualTo(
StripeIntent.NextActionData.SdkData.Use3DS2(
"src_1ExkUeAWhjPjYwPiLWUvXrSA",
"mastercard",
"34b16ea1-1206-4ee8-84d2-d292bc73c2ae",
StripeIntent.NextActionData.SdkData.Use3DS2.DirectoryServerEncryption(
"A000000004",
"-----BEGIN CERTIFICATE-----\nMIIFtTCCA52gAwIBAgIQJqSRaPua/6cpablmVDHWUDANBgkqhkiG9w0BAQsFADB6\nMQswCQYDVQQGEwJVUzETMBEGA1UEChMKTWFzdGVyQ2FyZDEoMCYGA1UECxMfTWFz\ndGVyQ2FyZCBJZGVudGl0eSBDaGVjayBHZW4gMzEsMCoGA1UEAxMjUFJEIE1hc3Rl\nckNhcmQgM0RTMiBBY3F1aXJlciBTdWIgQ0EwHhcNMTgxMTIwMTQ1MzIzWhcNMjEx\nMTIwMTQ1MzIzWjBxMQswCQYDVQQGEwJVUzEdMBsGA1UEChMUTWFzdGVyQ2FyZCBX\nb3JsZHdpZGUxGzAZBgNVBAsTEmdhdGV3YXktZW5jcnlwdGlvbjEmMCQGA1UEAxMd\nM2RzMi5kaXJlY3RvcnkubWFzdGVyY2FyZC5jb20wggEiMA0GCSqGSIb3DQEBAQUA\nA4IBDwAwggEKAoIBAQCFlZjqbbL9bDKOzZFawdbyfQcezVEUSDCWWsYKw/V6co9A\nGaPBUsGgzxF6+EDgVj3vYytgSl8xFvVPsb4ZJ6BJGvimda8QiIyrX7WUxQMB3hyS\nBOPf4OB72CP+UkaFNR6hdlO5ofzTmB2oj1FdLGZmTN/sj6ZoHkn2Zzums8QAHFjv\nFjspKUYCmms91gpNpJPUUztn0N1YMWVFpFMytahHIlpiGqTDt4314F7sFABLxzFr\nDmcqhf623SPV3kwQiLVWOvewO62ItYUFgHwle2dq76YiKrUv1C7vADSk2Am4gqwv\n7dcCnFeM2AHbBFBa1ZBRQXosuXVw8ZcQqfY8m4iNAgMBAAGjggE+MIIBOjAOBgNV\nHQ8BAf8EBAMCAygwCQYDVR0TBAIwADAfBgNVHSMEGDAWgBSakqJUx4CN/s5W4wMU\n/17uSLhFuzBIBggrBgEFBQcBAQQ8MDowOAYIKwYBBQUHMAGGLGh0dHA6Ly9vY3Nw\nLnBraS5pZGVudGl0eWNoZWNrLm1hc3RlcmNhcmQuY29tMCgGA1UdEQQhMB+CHTNk\nczIuZGlyZWN0b3J5Lm1hc3RlcmNhcmQuY29tMGkGA1UdHwRiMGAwXqBcoFqGWGh0\ndHA6Ly9jcmwucGtpLmlkZW50aXR5Y2hlY2subWFzdGVyY2FyZC5jb20vOWE5MmEy\nNTRjNzgwOGRmZWNlNTZlMzAzMTRmZjVlZWU0OGI4NDViYi5jcmwwHQYDVR0OBBYE\nFHxN6+P0r3+dFWmi/+pDQ8JWaCbuMA0GCSqGSIb3DQEBCwUAA4ICAQAtwW8siyCi\nmhon1WUAUmufZ7bbegf3cTOafQh77NvA0xgVeloELUNCwsSSZgcOIa4Zgpsa0xi5\nfYxXsPLgVPLM0mBhTOD1DnPu1AAm32QVelHe6oB98XxbkQlHGXeOLs62PLtDZd94\n7pm08QMVb+MoCnHLaBLV6eKhKK+SNrfcxr33m0h3v2EMoiJ6zCvp8HgIHEhVpleU\n8H2Uo5YObatb/KUHgtp2z0vEfyGhZR7hrr48vUQpfVGBABsCV0aqUkPxtAXWfQo9\n1N9B7H3EIcSjbiUz5vkj9YeDSyJIi0Y/IZbzuNMsz2cRi1CWLl37w2fe128qWxYq\nY/k+Y4HX7uYchB8xPaZR4JczCvg1FV2JrkOcFvElVXWSMpBbe2PS6OMr3XxrHjzp\nDyM9qvzge0Ai9+rq8AyGoG1dP2Ay83Ndlgi42X3yl1uEUW2feGojCQQCFFArazEj\nLUkSlrB2kA12SWAhsqqQwnBLGSTp7PqPZeWkluQVXS0sbj0878kTra6TjG3U+KqO\nJCj8v6G380qIkAXe1xMHHNQ6GS59HZMeBPYkK2y5hmh/JVo4bRfK7Ya3blBSBfB8\nAVWQ5GqVWklvXZsQLN7FH/fMIT3y8iE1W19Ua4whlhvn7o/aYWOkHr1G2xyh8BHj\n7H63A2hjcPlW/ZAJSTuBZUClAhsNohH2Jg==\n-----END CERTIFICATE-----\n",
listOf(
"-----BEGIN CERTIFICATE-----\nMIIFxzCCA6+gAwIBAgIQFsjyIuqhw80wNMjXU47lfjANBgkqhkiG9w0BAQsFADB8\nMQswCQYDVQQGEwJVUzETMBEGA1UEChMKTWFzdGVyQ2FyZDEoMCYGA1UECxMfTWFz\ndGVyQ2FyZCBJZGVudGl0eSBDaGVjayBHZW4gMzEuMCwGA1UEAxMlUFJEIE1hc3Rl\nckNhcmQgSWRlbnRpdHkgQ2hlY2sgUm9vdCBDQTAeFw0xNjA3MTQwNzI0MDBaFw0z\nMDA3MTUwODEwMDBaMHwxCzAJBgNVBAYTAlVTMRMwEQYDVQQKEwpNYXN0ZXJDYXJk\nMSgwJgYDVQQLEx9NYXN0ZXJDYXJkIElkZW50aXR5IENoZWNrIEdlbiAzMS4wLAYD\nVQQDEyVQUkQgTWFzdGVyQ2FyZCBJZGVudGl0eSBDaGVjayBSb290IENBMIICIjAN\nBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAxZF3nCEiT8XFFaq+3BPT0cMDlWE7\n6IBsdx27w3hLxwVLog42UTasIgzmysTKpBc17HEZyNAqk9GrCHo0Oyk4JZuXHoW8\n0goZaR2sMnn49ytt7aGsE1PsfVup8gqAorfm3IFab2/CniJJNXaWPgn94+U/nsoa\nqTQ6j+6JBoIwnFklhbXHfKrqlkUZJCYaWbZRiQ7nkANYYM2Td3N87FmRanmDXj5B\nG6lc9o1clTC7UvRQmNIL9OdDDZ8qlqY2Fi0eztBnuo2DUS5tGdVy8SgqPM3E12ft\nk4EdlKyrWmBqFcYwGx4AcSJ88O3rQmRBMxtk0r5vhgr6hDCGq7FHK/hQFP9LhUO9\n1qxWEtMn76Sa7DPCLas+tfNRVwG12FBuEZFhdS/qKMdIYUE5Q6uwGTEvTzg2kmgJ\nT3sNa6dbhlYnYn9iIjTh0dPGgiXap1Bhi8B9aaPFcHEHSqW8nZUINcrwf5AUi+7D\n+q/AG5ItiBtQTCaaFm74gv51yutzwgKnH9Q+x3mtuK/uwlLCslj9DeXgOzMWFxFg\nuuwLGX39ktDnetxNw3PLabjHkDlGDIfx0MCQakM74sTcuW8ICiHvNA7fxXCnbtjs\ny7at/yXYwAd+IDS51MA/g3OYVN4M+0pG843Re6Z53oODp0Ymugx0FNO1NxT3HO1h\nd7dXyjAV/tN/GGcCAwEAAaNFMEMwDgYDVR0PAQH/BAQDAgGGMBIGA1UdEwEB/wQI\nMAYBAf8CAQEwHQYDVR0OBBYEFNSlUaqS2hGLFMT/EXrhHeEx+UqxMA0GCSqGSIb3\nDQEBCwUAA4ICAQBLqIYorrtVz56F6WOoLX9CcRjSFim7gO873a3p7+62I6joXMsM\nr0nd9nRPcEwduEloZXwFgErVUQWaUZWNpue0mGvU7BUAgV9Tu0J0yA+9srizVoMv\nx+o4zTJ3Vu5p5aTf1aYoH1xYVo5ooFgl/hI/EXD2lo/xOUfPKXBY7twfiqOziQmT\nGBuqPRq8h3dQRlXYxX/rzGf80SecIT6wo9KavDkjOmJWGzzHsn6Ryo6MEClMaPn0\nte87ukNN740AdPhTvNeZdWlwyqWAJpsv24caEckjSpgpoIZOjc7PAcEVQOWFSxUe\nsMk4Jz5bVZa/ABjzcp+rsq1QLSJ5quqHwWFTewChwpw5gpw+E5SpKY6FIHPlTdl+\nqHThvN8lsKNAQg0qTdEbIFZCUQC0Cl3Ti3q/cXv8tguLJNWvdGzB600Y32QHclMp\neyabT4/QeOesqpx6Da70J2KvLT1j6Ch2BsKSzeVLahrjnoPrdgiIYYBOgeA3T8SE\n1pgagt56R7nIkRQbtesoRKi+NfC7pPb/G1VUsj/cREAHH1i1UKa0aCsIiANfEdQN\n5Ok6wtFJJhp3apAvnVkrZDfOG5we9bYzvGoI7SUnleURBJ+N3ihjARfL4hDeeRHh\nYyLkM3kEyEkrJBL5r0GDjicxM+aFcR2fCBAkv3grT5kz4kLcvsmHX+9DBw==\n-----END CERTIFICATE-----\n\n"
),
"7c4debe3f4af7f9d1569a2ffea4343c2566826ee"
),
"pi_1ExkUeAWhjPjYwPiLWUvXrSA",
"pk_test_nextActionData"
)
)
}
@Test
fun parse_withAlipayAction_shoulddCreateExpectedNextActionData() {
val paymentIntent = PaymentIntentJsonParser().parse(
PaymentIntentFixtures.ALIPAY_REQUIRES_ACTION_JSON
)
assertThat(paymentIntent?.nextActionData)
.isEqualTo(
StripeIntent.NextActionData.AlipayRedirect(
"_input_charset=utf-8&app_pay=Y¤cy=USD&forex_biz=FP¬ify_url=https%3A%2F%2Fhooks.stripe.com%2Falipay%2Falipay%2Fhook%2F6255d30b067c8f7a162c79c654483646%2Fsrc_1HDEFWKlwPmebFhp6tcpln8T&out_trade_no=src_1HDEFWKlwPmebFhp6tcpln8T&partner=2088621828244481&payment_type=1&product_code=NEW_WAP_OVERSEAS_SELLER&return_url=https%3A%2F%2Fhooks.stripe.com%2Fadapter%2Falipay%2Fredirect%2Fcomplete%2Fsrc_1HDEFWKlwPmebFhp6tcpln8T%2Fsrc_client_secret_S6H9mVMKK6qxk9YxsUvbH55K&secondary_merchant_id=acct_1EqOyCKlwPmebFhp&secondary_merchant_industry=5734&secondary_merchant_name=Yuki-Test&sendFormat=normal&service=create_forex_trade_wap&sign=b691876a7f0bd889530f54a271d314d5&sign_type=MD5&subject=Yuki-Test&supplier=Yuki-Test&timeout_rule=20m&total_fee=1.00",
"https://hooks.stripe.com/redirect/authenticate/src_1HDEFWKlwPmebFhp6tcpln8T?client_secret=src_client_secret_S6H9mVMKK6qxk9YxsUvbH55K",
"example://return_url"
)
)
}
@Test
fun parse_withVerifyWithMicrodepositsAction_shoulddCreateExpectedNextActionData() {
val paymentIntent = PaymentIntentJsonParser().parse(
PaymentIntentFixtures.PI_WITH_US_BANK_ACCOUNT_IN_PAYMENT_METHODS_JSON
)
assertThat(paymentIntent?.nextActionData)
.isEqualTo(
StripeIntent.NextActionData.VerifyWithMicrodeposits(
1647241200,
"https://payments.stripe.com/microdeposit/pacs_test_YWNjdF8xS2J1SjlGbmt1bWlGVUZ4LHBhX25vbmNlX0xJcFVEaERaU0JOVVR3akhxMXc5eklOQkl3UTlwNWo0000v3GS1Jej",
MicrodepositType.AMOUNTS
)
)
}
@Test
fun `verify luxe next action is queried first for next action and returns no next action`() {
val repository = LuxePostConfirmActionRepository()
var stripeIntent = PaymentIntentJsonParser(repository).parse(
PaymentIntentFixtures.AFTERPAY_REQUIRES_ACTION_JSON
)
// This is using the old hard coded path
assertThat(stripeIntent?.nextActionData)
.isInstanceOf(StripeIntent.NextActionData.RedirectToUrl::class.java)
assertThat(stripeIntent?.nextActionType)
.isEqualTo(StripeIntent.NextActionType.RedirectToUrl)
repository.update(
mapOf(
"afterpay_clearpay" to
LUXE_NEXT_ACTION.copy(
postConfirmStatusToAction = mapOf(
StripeIntent.Status.RequiresAction to
LuxePostConfirmActionCreator.NoActionCreator
)
)
)
)
stripeIntent = PaymentIntentJsonParser(repository).parse(
PaymentIntentFixtures.AFTERPAY_REQUIRES_ACTION_JSON
)
// This will use the result of the LuxeNextActionRepo
assertThat(stripeIntent?.nextActionData)
.isNull()
assertThat(stripeIntent?.nextActionType)
.isNull()
}
@Test
fun `verify luxe next action is queried first for next action and returns next action`() {
val repository = LuxePostConfirmActionRepository()
var stripeIntent = PaymentIntentJsonParser(repository).parse(
PaymentIntentFixtures.LLAMAPAY_REQUIRES_ACTION_JSON
)
// This is using the old hard coded path
assertThat(stripeIntent).isNotNull()
assertThat(stripeIntent?.nextActionType).isNull()
assertThat(stripeIntent?.nextActionData).isNull()
repository.update(
mapOf(
"llamapay" to
LUXE_NEXT_ACTION.copy(
postConfirmStatusToAction = mapOf(
StripeIntent.Status.RequiresAction to
LuxePostConfirmActionCreator.RedirectActionCreator(
redirectPagePath = "next_action[llamapay_redirect_to_url][url]",
returnToUrlPath = "next_action[llamapay_redirect_to_url][return_url]"
)
)
)
)
)
stripeIntent = PaymentIntentJsonParser(repository).parse(
PaymentIntentFixtures.LLAMAPAY_REQUIRES_ACTION_JSON
)
// This will use the result of the LuxeNextActionRepo
assertThat(stripeIntent?.nextActionType).isEqualTo(
StripeIntent.NextActionType.RedirectToUrl
)
assertThat(stripeIntent?.nextActionData).isEqualTo(
StripeIntent.NextActionData.RedirectToUrl(
Uri.parse(
"https://hooks.stripe.com/llamapay/acct_1HvTI7Lu5o3P18Zp/" +
"pa_nonce_M5WcnAEWqB7mMANvtyWuxOWAXIHw9T9/redirect"
),
"stripesdk://payment_return_url/com.stripe.android.paymentsheet.example"
)
)
}
@Test
fun parse_withLinkFundingSources_shouldCreateExpectedObject() {
val paymentIntent = PaymentIntentFixtures.PI_WITH_LINK_FUNDING_SOURCES
assertThat(paymentIntent.linkFundingSources).containsExactly("card", "bank_account")
}
@Test
fun parse_withCountryCode_shouldCreateExpectedObject() {
val paymentIntent = PaymentIntentFixtures.PI_WITH_COUNTRY_CODE
assertThat(paymentIntent.countryCode).isEqualTo("US")
}
}
| mit |
stripe/stripe-android | identity/src/test/java/com/stripe/android/identity/states/FaceDetectorTransitionerTest.kt | 1 | 9802 | package com.stripe.android.identity.states
import com.google.common.truth.Truth.assertThat
import com.stripe.android.camera.framework.time.ClockMark
import com.stripe.android.camera.framework.time.milliseconds
import com.stripe.android.core.model.StripeFilePurpose
import com.stripe.android.identity.ml.AnalyzerInput
import com.stripe.android.identity.ml.BoundingBox
import com.stripe.android.identity.ml.FaceDetectorOutput
import com.stripe.android.identity.networking.models.VerificationPageStaticContentSelfieCapturePage
import com.stripe.android.identity.networking.models.VerificationPageStaticContentSelfieModels
import kotlinx.coroutines.runBlocking
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.same
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
internal class FaceDetectorTransitionerTest {
private val mockNeverTimeoutClockMark = mock<ClockMark>().also {
whenever(it.hasPassed()).thenReturn(false)
}
private val mockAlwaysTimeoutClockMark = mock<ClockMark>().also {
whenever(it.hasPassed()).thenReturn(true)
}
private val mockReachedStateAt = mock<ClockMark>()
private val mockSelfieFrameSaver = mock<FaceDetectorTransitioner.SelfieFrameSaver>()
@Test
fun `Initial transitions to TimeOut when timeout`() = runBlocking {
val transitioner =
FaceDetectorTransitioner(SELFIE_CAPTURE_PAGE, timeoutAt = mockAlwaysTimeoutClockMark)
assertThat(
transitioner.transitionFromInitial(
IdentityScanState.Initial(
IdentityScanState.ScanType.SELFIE,
transitioner
),
mock(),
mock<FaceDetectorOutput>()
)
).isInstanceOf(IdentityScanState.TimeOut::class.java)
}
@Test
fun `Initial transitions to Found when face is valid and frame is saved`() = runBlocking {
val transitioner =
FaceDetectorTransitioner(
SELFIE_CAPTURE_PAGE,
timeoutAt = mockNeverTimeoutClockMark,
selfieFrameSaver = mockSelfieFrameSaver
)
val initialState = IdentityScanState.Initial(
IdentityScanState.ScanType.SELFIE,
transitioner
)
val mockInput = mock<AnalyzerInput>()
val resultState = transitioner.transitionFromInitial(
initialState,
mockInput,
VALID_OUTPUT
)
verify(mockSelfieFrameSaver).saveFrame(
eq((mockInput to VALID_OUTPUT)),
same(VALID_OUTPUT)
)
assertThat(
resultState
).isInstanceOf(IdentityScanState.Found::class.java)
}
@Test
fun `Initial stays in Initial when face is invalid`() = runBlocking {
val transitioner =
FaceDetectorTransitioner(SELFIE_CAPTURE_PAGE, timeoutAt = mockNeverTimeoutClockMark)
val initialState = IdentityScanState.Initial(
IdentityScanState.ScanType.SELFIE,
transitioner
)
val resultState = transitioner.transitionFromInitial(
initialState,
mock(),
INVALID_OUTPUT
)
assertThat(
resultState
).isInstanceOf(IdentityScanState.Initial::class.java)
}
@Test
fun `Found transitions to TimeOut when timeout`() = runBlocking {
val transitioner =
FaceDetectorTransitioner(SELFIE_CAPTURE_PAGE, timeoutAt = mockAlwaysTimeoutClockMark)
assertThat(
transitioner.transitionFromFound(
IdentityScanState.Found(
IdentityScanState.ScanType.SELFIE,
transitioner
),
mock(),
mock<FaceDetectorOutput>()
)
).isInstanceOf(IdentityScanState.TimeOut::class.java)
}
@Test
fun `Found stays in to Found when sample interval not reached`() = runBlocking {
val transitioner =
FaceDetectorTransitioner(SELFIE_CAPTURE_PAGE, timeoutAt = mockNeverTimeoutClockMark)
whenever(mockReachedStateAt.elapsedSince()).thenReturn((SAMPLE_INTERVAL - 10).milliseconds)
val foundState = IdentityScanState.Found(
IdentityScanState.ScanType.SELFIE,
transitioner,
reachedStateAt = mockReachedStateAt
)
assertThat(
transitioner.transitionFromFound(
foundState,
mock(),
mock<FaceDetectorOutput>()
)
).isSameInstanceAs(foundState)
}
@Test
fun `Found stays in to Found when face is valid and not enough selfie collected`() =
runBlocking {
val transitioner =
FaceDetectorTransitioner(
selfieCapturePage = SELFIE_CAPTURE_PAGE,
timeoutAt = mockNeverTimeoutClockMark,
selfieFrameSaver = mockSelfieFrameSaver
)
whenever(mockReachedStateAt.elapsedSince()).thenReturn((SAMPLE_INTERVAL + 10).milliseconds)
whenever(mockSelfieFrameSaver.selfieCollected()).thenReturn(NUM_SAMPLES - 1)
val foundState = IdentityScanState.Found(
IdentityScanState.ScanType.SELFIE,
transitioner,
reachedStateAt = mockReachedStateAt
)
val resultState =
transitioner.transitionFromFound(
foundState,
mock(),
VALID_OUTPUT
)
assertThat(resultState).isNotSameInstanceAs(foundState)
assertThat(resultState).isInstanceOf(IdentityScanState.Found::class.java)
}
@Test
fun `Found transitions to Satisfed when face is valid and enough selfie collected`() =
runBlocking {
val transitioner =
FaceDetectorTransitioner(
selfieCapturePage = SELFIE_CAPTURE_PAGE,
timeoutAt = mockNeverTimeoutClockMark,
selfieFrameSaver = mockSelfieFrameSaver
)
whenever(mockReachedStateAt.elapsedSince()).thenReturn((SAMPLE_INTERVAL + 10).milliseconds)
whenever(mockSelfieFrameSaver.selfieCollected()).thenReturn(NUM_SAMPLES)
assertThat(
transitioner.transitionFromFound(
IdentityScanState.Found(
IdentityScanState.ScanType.SELFIE,
transitioner,
reachedStateAt = mockReachedStateAt
),
mock(),
VALID_OUTPUT
)
).isInstanceOf(IdentityScanState.Satisfied::class.java)
}
@Test
fun `Found stays in Found when face is invalid`() =
runBlocking {
val transitioner =
FaceDetectorTransitioner(
selfieCapturePage = SELFIE_CAPTURE_PAGE,
timeoutAt = mockNeverTimeoutClockMark,
selfieFrameSaver = mockSelfieFrameSaver
)
whenever(mockReachedStateAt.elapsedSince()).thenReturn((SAMPLE_INTERVAL + 10).milliseconds)
whenever(mockSelfieFrameSaver.selfieCollected()).thenReturn(NUM_SAMPLES - 1)
val foundState = IdentityScanState.Found(
IdentityScanState.ScanType.SELFIE,
transitioner,
reachedStateAt = mockReachedStateAt
)
val resultState =
transitioner.transitionFromFound(
foundState,
mock(),
INVALID_OUTPUT
)
assertThat(resultState).isNotSameInstanceAs(foundState)
assertThat(resultState).isInstanceOf(IdentityScanState.Found::class.java)
}
private companion object {
const val SCORE_THRESHOLD = 0.8f
const val VALID_SCORE = SCORE_THRESHOLD + 0.1f
const val INVALID_SCORE = SCORE_THRESHOLD - 0.1f
const val SAMPLE_INTERVAL = 200
const val NUM_SAMPLES = 8
val SELFIE_CAPTURE_PAGE = VerificationPageStaticContentSelfieCapturePage(
autoCaptureTimeout = 15000,
filePurpose = StripeFilePurpose.IdentityPrivate.code,
numSamples = NUM_SAMPLES,
sampleInterval = SAMPLE_INTERVAL,
models = VerificationPageStaticContentSelfieModels(
faceDetectorUrl = "",
faceDetectorMinScore = SCORE_THRESHOLD,
faceDetectorIou = 0.5f
),
maxCenteredThresholdX = 0.2f,
maxCenteredThresholdY = 0.2f,
minEdgeThreshold = 0.05f,
minCoverageThreshold = 0.07f,
maxCoverageThreshold = 0.8f,
lowResImageMaxDimension = 800,
lowResImageCompressionQuality = 0.82f,
highResImageMaxDimension = 1440,
highResImageCompressionQuality = 0.92f,
highResImageCropPadding = 0.5f,
consentText = "consent"
)
val VALID_OUTPUT = FaceDetectorOutput(
boundingBox = BoundingBox(
0.2f,
0.2f,
0.6f,
0.6f
),
resultScore = VALID_SCORE
)
val INVALID_OUTPUT = FaceDetectorOutput(
boundingBox = BoundingBox(
0.2f,
0.2f,
0.6f,
0.6f
),
resultScore = INVALID_SCORE
)
}
}
| mit |
Nunnery/MythicDrops | src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/events/RandomItemGenerationEvent.kt | 1 | 2026 | /*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* 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.tealcube.minecraft.bukkit.mythicdrops.events
import com.tealcube.minecraft.bukkit.mythicdrops.api.events.MythicDropsCancellableEvent
import com.tealcube.minecraft.bukkit.mythicdrops.api.items.ItemGenerationReason
import com.tealcube.minecraft.bukkit.mythicdrops.api.tiers.Tier
import org.bukkit.event.HandlerList
import org.bukkit.inventory.ItemStack
class RandomItemGenerationEvent(val tier: Tier, itemStack: ItemStack, val reason: ItemGenerationReason) :
MythicDropsCancellableEvent() {
companion object {
@JvmStatic
val handlerList = HandlerList()
}
var isModified: Boolean = false
private set
var itemStack: ItemStack = itemStack
set(value) {
field = value
isModified = true
}
override fun getHandlers(): HandlerList = handlerList
}
| mit |
peervalhoegen/SudoQ | sudoq-app/sudoq-persistence-xml/src/main/kotlin/de/sudoq/persistence/game/GamesListRepo.kt | 1 | 1511 | package de.sudoq.persistence.game
import de.sudoq.model.game.GameData
import de.sudoq.persistence.XmlHelper
import de.sudoq.persistence.XmlTree
import de.sudoq.model.persistence.xml.game.IGamesListRepo
import de.sudoq.persistence.game.GameDataBE
import de.sudoq.persistence.game.GameDataMapper
import java.io.File
import java.io.IOException
class GamesListRepo(private val gamesDir: File,
private val gamesFile: File) : IGamesListRepo {
override fun load(): MutableList<GameData> {
try {
return XmlHelper()
.loadXml(this.gamesFile)!!
.map { GameDataBE.fromXml(it) }
.map { GameDataMapper.fromBE(it) }
.sortedDescending().toMutableList()
} catch (e: IOException) {
throw IllegalStateException("Profile broken", e)
}
}
override fun fileExists(id: Int): Boolean = getGameFile(id).exists()
//todo this should be in gameRepo, but then it would need its own interface...
fun getGameFile(id: Int): File {
return File(gamesDir, "game_$id.xml")
}
override fun saveGamesFile(games: List<GameData>) {
val xmlTree = XmlTree("games")
games.map { GameDataMapper.toBE(it) }
.map { it.toXmlTree() }
.forEach { xmlTree.addChild(it) }
try {
XmlHelper().saveXml(xmlTree, gamesFile)
} catch (e: IOException) {
throw IllegalStateException("Profile broken", e)
}
}
} | gpl-3.0 |
Tapchicoma/ultrasonic | ultrasonic/src/main/kotlin/org/moire/ultrasonic/service/RESTMusicService.kt | 1 | 35237 | /*
This file is part of Subsonic.
Subsonic 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.
Subsonic 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 Subsonic. If not, see <http://www.gnu.org/licenses/>.
Copyright 2009 (C) Sindre Mehus
*/
package org.moire.ultrasonic.service
import android.content.Context
import android.graphics.Bitmap
import android.text.TextUtils
import androidx.annotation.StringRes
import java.io.BufferedWriter
import java.io.File
import java.io.FileOutputStream
import java.io.FileWriter
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import org.moire.ultrasonic.R
import org.moire.ultrasonic.api.subsonic.ApiNotSupportedException
import org.moire.ultrasonic.api.subsonic.SubsonicAPIClient
import org.moire.ultrasonic.api.subsonic.models.AlbumListType.Companion.fromName
import org.moire.ultrasonic.api.subsonic.models.JukeboxAction
import org.moire.ultrasonic.api.subsonic.response.StreamResponse
import org.moire.ultrasonic.cache.PermanentFileStorage
import org.moire.ultrasonic.cache.serializers.getIndexesSerializer
import org.moire.ultrasonic.cache.serializers.getMusicFolderListSerializer
import org.moire.ultrasonic.data.ActiveServerProvider
import org.moire.ultrasonic.data.ActiveServerProvider.Companion.isOffline
import org.moire.ultrasonic.data.ActiveServerProvider.Companion.isServerScalingEnabled
import org.moire.ultrasonic.domain.Bookmark
import org.moire.ultrasonic.domain.ChatMessage
import org.moire.ultrasonic.domain.Genre
import org.moire.ultrasonic.domain.Indexes
import org.moire.ultrasonic.domain.JukeboxStatus
import org.moire.ultrasonic.domain.Lyrics
import org.moire.ultrasonic.domain.MusicDirectory
import org.moire.ultrasonic.domain.MusicFolder
import org.moire.ultrasonic.domain.Playlist
import org.moire.ultrasonic.domain.PodcastsChannel
import org.moire.ultrasonic.domain.SearchCriteria
import org.moire.ultrasonic.domain.SearchResult
import org.moire.ultrasonic.domain.Share
import org.moire.ultrasonic.domain.UserInfo
import org.moire.ultrasonic.domain.toDomainEntitiesList
import org.moire.ultrasonic.domain.toDomainEntity
import org.moire.ultrasonic.domain.toDomainEntityList
import org.moire.ultrasonic.domain.toMusicDirectoryDomainEntity
import org.moire.ultrasonic.util.CancellableTask
import org.moire.ultrasonic.util.FileUtil
import org.moire.ultrasonic.util.ProgressListener
import org.moire.ultrasonic.util.Util
import timber.log.Timber
/**
* @author Sindre Mehus
*/
open class RESTMusicService(
private val subsonicAPIClient: SubsonicAPIClient,
private val fileStorage: PermanentFileStorage,
private val activeServerProvider: ActiveServerProvider,
private val responseChecker: ApiCallResponseChecker
) : MusicService {
@Throws(Exception::class)
override fun ping(context: Context, progressListener: ProgressListener?) {
updateProgressListener(progressListener, R.string.service_connecting)
responseChecker.callWithResponseCheck { api -> api.ping().execute() }
}
@Throws(Exception::class)
override fun isLicenseValid(context: Context, progressListener: ProgressListener?): Boolean {
updateProgressListener(progressListener, R.string.service_connecting)
val response = responseChecker.callWithResponseCheck { api -> api.getLicense().execute() }
return response.body()!!.license.valid
}
@Throws(Exception::class)
override fun getMusicFolders(
refresh: Boolean,
context: Context,
progressListener: ProgressListener?
): List<MusicFolder> {
val cachedMusicFolders = fileStorage.load(
MUSIC_FOLDER_STORAGE_NAME, getMusicFolderListSerializer()
)
if (cachedMusicFolders != null && !refresh) return cachedMusicFolders
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.getMusicFolders().execute()
}
val musicFolders = response.body()!!.musicFolders.toDomainEntityList()
fileStorage.store(MUSIC_FOLDER_STORAGE_NAME, musicFolders, getMusicFolderListSerializer())
return musicFolders
}
@Throws(Exception::class)
override fun getIndexes(
musicFolderId: String?,
refresh: Boolean,
context: Context,
progressListener: ProgressListener?
): Indexes {
val cachedIndexes = fileStorage.load(INDEXES_STORAGE_NAME, getIndexesSerializer())
if (cachedIndexes != null && !refresh) return cachedIndexes
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.getIndexes(musicFolderId, null).execute()
}
val indexes = response.body()!!.indexes.toDomainEntity()
fileStorage.store(INDEXES_STORAGE_NAME, indexes, getIndexesSerializer())
return indexes
}
@Throws(Exception::class)
override fun getArtists(
refresh: Boolean,
context: Context,
progressListener: ProgressListener?
): Indexes {
val cachedArtists = fileStorage.load(ARTISTS_STORAGE_NAME, getIndexesSerializer())
if (cachedArtists != null && !refresh) return cachedArtists
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.getArtists(null).execute()
}
val indexes = response.body()!!.indexes.toDomainEntity()
fileStorage.store(ARTISTS_STORAGE_NAME, indexes, getIndexesSerializer())
return indexes
}
@Throws(Exception::class)
override fun star(
id: String?,
albumId: String?,
artistId: String?,
context: Context,
progressListener: ProgressListener?
) {
updateProgressListener(progressListener, R.string.parser_reading)
responseChecker.callWithResponseCheck { api -> api.star(id, albumId, artistId).execute() }
}
@Throws(Exception::class)
override fun unstar(
id: String?,
albumId: String?,
artistId: String?,
context: Context,
progressListener: ProgressListener?
) {
updateProgressListener(progressListener, R.string.parser_reading)
responseChecker.callWithResponseCheck { api -> api.unstar(id, albumId, artistId).execute() }
}
@Throws(Exception::class)
override fun setRating(
id: String,
rating: Int,
context: Context,
progressListener: ProgressListener?
) {
updateProgressListener(progressListener, R.string.parser_reading)
responseChecker.callWithResponseCheck { api -> api.setRating(id, rating).execute() }
}
@Throws(Exception::class)
override fun getMusicDirectory(
id: String,
name: String?,
refresh: Boolean,
context: Context,
progressListener: ProgressListener?
): MusicDirectory {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.getMusicDirectory(id).execute()
}
return response.body()!!.musicDirectory.toDomainEntity()
}
@Throws(Exception::class)
override fun getArtist(
id: String,
name: String?,
refresh: Boolean,
context: Context,
progressListener: ProgressListener?
): MusicDirectory {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api -> api.getArtist(id).execute() }
return response.body()!!.artist.toMusicDirectoryDomainEntity()
}
@Throws(Exception::class)
override fun getAlbum(
id: String,
name: String?,
refresh: Boolean,
context: Context,
progressListener: ProgressListener?
): MusicDirectory {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api -> api.getAlbum(id).execute() }
return response.body()!!.album.toMusicDirectoryDomainEntity()
}
@Throws(Exception::class)
override fun search(
criteria: SearchCriteria,
context: Context,
progressListener: ProgressListener?
): SearchResult {
return try {
if (
!isOffline(context) &&
Util.getShouldUseId3Tags(context)
) search3(criteria, progressListener)
else search2(criteria, progressListener)
} catch (ignored: ApiNotSupportedException) {
// Ensure backward compatibility with REST 1.3.
searchOld(criteria, progressListener)
}
}
/**
* Search using the "search" REST method.
*/
@Throws(Exception::class)
private fun searchOld(
criteria: SearchCriteria,
progressListener: ProgressListener?
): SearchResult {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.search(null, null, null, criteria.query, criteria.songCount, null, null)
.execute()
}
return response.body()!!.searchResult.toDomainEntity()
}
/**
* Search using the "search2" REST method, available in 1.4.0 and later.
*/
@Throws(Exception::class)
private fun search2(
criteria: SearchCriteria,
progressListener: ProgressListener?
): SearchResult {
requireNotNull(criteria.query) { "Query param is null" }
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.search2(
criteria.query, criteria.artistCount, null, criteria.albumCount, null,
criteria.songCount, null
).execute()
}
return response.body()!!.searchResult.toDomainEntity()
}
@Throws(Exception::class)
private fun search3(
criteria: SearchCriteria,
progressListener: ProgressListener?
): SearchResult {
requireNotNull(criteria.query) { "Query param is null" }
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.search3(
criteria.query, criteria.artistCount, null, criteria.albumCount, null,
criteria.songCount, null
).execute()
}
return response.body()!!.searchResult.toDomainEntity()
}
@Throws(Exception::class)
override fun getPlaylist(
id: String,
name: String?,
context: Context,
progressListener: ProgressListener?
): MusicDirectory {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.getPlaylist(id).execute()
}
val playlist = response.body()!!.playlist.toMusicDirectoryDomainEntity()
savePlaylist(name, context, playlist)
return playlist
}
@Throws(IOException::class)
private fun savePlaylist(
name: String?,
context: Context,
playlist: MusicDirectory
) {
val playlistFile = FileUtil.getPlaylistFile(
context, activeServerProvider.getActiveServer().name, name
)
val fw = FileWriter(playlistFile)
val bw = BufferedWriter(fw)
try {
fw.write("#EXTM3U\n")
for (e in playlist.getChildren()) {
var filePath = FileUtil.getSongFile(context, e).absolutePath
if (!File(filePath).exists()) {
val ext = FileUtil.getExtension(filePath)
val base = FileUtil.getBaseName(filePath)
filePath = "$base.complete.$ext"
}
fw.write(filePath + "\n")
}
} catch (e: IOException) {
Timber.w("Failed to save playlist: %s", name)
throw e
} finally {
bw.close()
fw.close()
}
}
@Throws(Exception::class)
override fun getPlaylists(
refresh: Boolean,
context: Context,
progressListener: ProgressListener?
): List<Playlist> {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.getPlaylists(null).execute()
}
return response.body()!!.playlists.toDomainEntitiesList()
}
@Throws(Exception::class)
override fun createPlaylist(
id: String?,
name: String?,
entries: List<MusicDirectory.Entry>,
context: Context,
progressListener: ProgressListener?
) {
val pSongIds: MutableList<String> = ArrayList(entries.size)
for ((id1) in entries) {
if (id1 != null) {
pSongIds.add(id1)
}
}
updateProgressListener(progressListener, R.string.parser_reading)
responseChecker.callWithResponseCheck { api ->
api.createPlaylist(id, name, pSongIds.toList()).execute()
}
}
@Throws(Exception::class)
override fun deletePlaylist(
id: String,
context: Context,
progressListener: ProgressListener?
) {
updateProgressListener(progressListener, R.string.parser_reading)
responseChecker.callWithResponseCheck { api -> api.deletePlaylist(id).execute() }
}
@Throws(Exception::class)
override fun updatePlaylist(
id: String,
name: String?,
comment: String?,
pub: Boolean,
context: Context?,
progressListener: ProgressListener?
) {
updateProgressListener(progressListener, R.string.parser_reading)
responseChecker.callWithResponseCheck { api ->
api.updatePlaylist(id, name, comment, pub, null, null)
.execute()
}
}
@Throws(Exception::class)
override fun getPodcastsChannels(
refresh: Boolean,
context: Context,
progressListener: ProgressListener?
): List<PodcastsChannel> {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.getPodcasts(false, null).execute()
}
return response.body()!!.podcastChannels.toDomainEntitiesList()
}
@Throws(Exception::class)
override fun getPodcastEpisodes(
podcastChannelId: String?,
context: Context,
progressListener: ProgressListener?
): MusicDirectory {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.getPodcasts(true, podcastChannelId).execute()
}
val podcastEntries = response.body()!!.podcastChannels[0].episodeList
val musicDirectory = MusicDirectory()
for (podcastEntry in podcastEntries) {
if (
"skipped" != podcastEntry.status &&
"error" != podcastEntry.status
) {
val entry = podcastEntry.toDomainEntity()
entry.track = null
musicDirectory.addChild(entry)
}
}
return musicDirectory
}
@Throws(Exception::class)
override fun getLyrics(
artist: String?,
title: String?,
context: Context,
progressListener: ProgressListener?
): Lyrics {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.getLyrics(artist, title).execute()
}
return response.body()!!.lyrics.toDomainEntity()
}
@Throws(Exception::class)
override fun scrobble(
id: String,
submission: Boolean,
context: Context,
progressListener: ProgressListener?
) {
updateProgressListener(progressListener, R.string.parser_reading)
responseChecker.callWithResponseCheck { api ->
api.scrobble(id, null, submission).execute()
}
}
@Throws(Exception::class)
override fun getAlbumList(
type: String,
size: Int,
offset: Int,
context: Context,
progressListener: ProgressListener?
): MusicDirectory {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.getAlbumList(fromName(type), size, offset, null, null, null, null)
.execute()
}
val childList = response.body()!!.albumList.toDomainEntityList()
val result = MusicDirectory()
result.addAll(childList)
return result
}
@Throws(Exception::class)
override fun getAlbumList2(
type: String,
size: Int,
offset: Int,
context: Context,
progressListener: ProgressListener?
): MusicDirectory {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.getAlbumList2(
fromName(type),
size,
offset,
null,
null,
null,
null
).execute()
}
val result = MusicDirectory()
result.addAll(response.body()!!.albumList.toDomainEntityList())
return result
}
@Throws(Exception::class)
override fun getRandomSongs(
size: Int,
context: Context,
progressListener: ProgressListener?
): MusicDirectory {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.getRandomSongs(
size,
null,
null,
null,
null
).execute()
}
val result = MusicDirectory()
result.addAll(response.body()!!.songsList.toDomainEntityList())
return result
}
@Throws(Exception::class)
override fun getStarred(
context: Context,
progressListener: ProgressListener?
): SearchResult {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.getStarred(null).execute()
}
return response.body()!!.starred.toDomainEntity()
}
@Throws(Exception::class)
override fun getStarred2(
context: Context,
progressListener: ProgressListener?
): SearchResult {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.getStarred2(null).execute()
}
return response.body()!!.starred2.toDomainEntity()
}
@Throws(Exception::class)
override fun getCoverArt(
context: Context,
entry: MusicDirectory.Entry?,
size: Int,
saveToFile: Boolean,
highQuality: Boolean,
progressListener: ProgressListener?
): Bitmap? {
// Synchronize on the entry so that we don't download concurrently for
// the same song.
if (entry == null) {
return null
}
synchronized(entry) {
// Use cached file, if existing.
var bitmap = FileUtil.getAlbumArtBitmap(context, entry, size, highQuality)
val serverScaling = isServerScalingEnabled(context)
if (bitmap == null) {
Timber.d("Loading cover art for: %s", entry)
val id = entry.coverArt
if (TextUtils.isEmpty(id)) {
return null // Can't load
}
val response = subsonicAPIClient.getCoverArt(id!!, size.toLong())
checkStreamResponseError(response)
if (response.stream == null) {
return null // Failed to load
}
var inputStream: InputStream? = null
try {
inputStream = response.stream
val bytes = Util.toByteArray(inputStream)
// If we aren't allowing server-side scaling, always save the file to disk
// because it will be unmodified
if (!serverScaling || saveToFile) {
var outputStream: OutputStream? = null
try {
outputStream = FileOutputStream(
FileUtil.getAlbumArtFile(context, entry)
)
outputStream.write(bytes)
} finally {
Util.close(outputStream)
}
}
bitmap = FileUtil.getSampledBitmap(bytes, size, highQuality)
} finally {
Util.close(inputStream)
}
}
// Return scaled bitmap
return Util.scaleBitmap(bitmap, size)
}
}
@Throws(SubsonicRESTException::class, IOException::class)
private fun checkStreamResponseError(response: StreamResponse) {
if (response.hasError() || response.stream == null) {
if (response.apiError != null) {
throw SubsonicRESTException(response.apiError!!)
} else {
throw IOException(
"Failed to make endpoint request, code: " + response.responseHttpCode
)
}
}
}
@Throws(Exception::class)
override fun getDownloadInputStream(
context: Context,
song: MusicDirectory.Entry,
offset: Long,
maxBitrate: Int,
task: CancellableTask
): Pair<InputStream, Boolean> {
val songOffset = if (offset < 0) 0 else offset
val response = subsonicAPIClient.stream(song.id!!, maxBitrate, songOffset)
checkStreamResponseError(response)
if (response.stream == null) {
throw IOException("Null stream response")
}
val partial = response.responseHttpCode == 206
return Pair(response.stream!!, partial)
}
@Throws(Exception::class)
override fun getVideoUrl(
context: Context,
id: String,
useFlash: Boolean
): String {
// This method should not exists as video should be loaded using stream method
// Previous method implementation uses assumption that video will be available
// by videoPlayer.view?id=<id>&maxBitRate=500&autoplay=true, but this url is not
// official Subsonic API call.
val expectedResult = arrayOfNulls<String>(1)
expectedResult[0] = null
val latch = CountDownLatch(1)
Thread(
{
expectedResult[0] = subsonicAPIClient.getStreamUrl(id) + "&format=raw"
latch.countDown()
},
"Get-Video-Url"
).start()
latch.await(3, TimeUnit.SECONDS)
return expectedResult[0]!!
}
@Throws(Exception::class)
override fun updateJukeboxPlaylist(
ids: List<String>?,
context: Context,
progressListener: ProgressListener?
): JukeboxStatus {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.jukeboxControl(JukeboxAction.SET, null, null, ids, null)
.execute()
}
return response.body()!!.jukebox.toDomainEntity()
}
@Throws(Exception::class)
override fun skipJukebox(
index: Int,
offsetSeconds: Int,
context: Context,
progressListener: ProgressListener?
): JukeboxStatus {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.jukeboxControl(JukeboxAction.SKIP, index, offsetSeconds, null, null)
.execute()
}
return response.body()!!.jukebox.toDomainEntity()
}
@Throws(Exception::class)
override fun stopJukebox(
context: Context,
progressListener: ProgressListener?
): JukeboxStatus {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.jukeboxControl(JukeboxAction.STOP, null, null, null, null)
.execute()
}
return response.body()!!.jukebox.toDomainEntity()
}
@Throws(Exception::class)
override fun startJukebox(
context: Context,
progressListener: ProgressListener?
): JukeboxStatus {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.jukeboxControl(JukeboxAction.START, null, null, null, null)
.execute()
}
return response.body()!!.jukebox.toDomainEntity()
}
@Throws(Exception::class)
override fun getJukeboxStatus(
context: Context,
progressListener: ProgressListener?
): JukeboxStatus {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.jukeboxControl(JukeboxAction.STATUS, null, null, null, null)
.execute()
}
return response.body()!!.jukebox.toDomainEntity()
}
@Throws(Exception::class)
override fun setJukeboxGain(
gain: Float,
context: Context,
progressListener: ProgressListener?
): JukeboxStatus {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.jukeboxControl(JukeboxAction.SET_GAIN, null, null, null, gain)
.execute()
}
return response.body()!!.jukebox.toDomainEntity()
}
@Throws(Exception::class)
override fun getShares(
refresh: Boolean,
context: Context,
progressListener: ProgressListener?
): List<Share> {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api -> api.getShares().execute() }
return response.body()!!.shares.toDomainEntitiesList()
}
@Throws(Exception::class)
override fun getGenres(
refresh: Boolean,
context: Context,
progressListener: ProgressListener?
): List<Genre> {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api -> api.getGenres().execute() }
return response.body()!!.genresList.toDomainEntityList()
}
@Throws(Exception::class)
override fun getSongsByGenre(
genre: String,
count: Int,
offset: Int,
context: Context,
progressListener: ProgressListener?
): MusicDirectory {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.getSongsByGenre(genre, count, offset, null).execute()
}
val result = MusicDirectory()
result.addAll(response.body()!!.songsList.toDomainEntityList())
return result
}
@Throws(Exception::class)
override fun getUser(
username: String,
context: Context,
progressListener: ProgressListener?
): UserInfo {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.getUser(username).execute()
}
return response.body()!!.user.toDomainEntity()
}
@Throws(Exception::class)
override fun getChatMessages(
since: Long?,
context: Context,
progressListener: ProgressListener?
): List<ChatMessage> {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.getChatMessages(since).execute()
}
return response.body()!!.chatMessages.toDomainEntitiesList()
}
@Throws(Exception::class)
override fun addChatMessage(
message: String,
context: Context,
progressListener: ProgressListener?
) {
updateProgressListener(progressListener, R.string.parser_reading)
responseChecker.callWithResponseCheck { api -> api.addChatMessage(message).execute() }
}
@Throws(Exception::class)
override fun getBookmarks(
context: Context,
progressListener: ProgressListener?
): List<Bookmark> {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api -> api.getBookmarks().execute() }
return response.body()!!.bookmarkList.toDomainEntitiesList()
}
@Throws(Exception::class)
override fun createBookmark(
id: String,
position: Int,
context: Context,
progressListener: ProgressListener?
) {
updateProgressListener(progressListener, R.string.parser_reading)
responseChecker.callWithResponseCheck { api ->
api.createBookmark(id, position.toLong(), null).execute()
}
}
@Throws(Exception::class)
override fun deleteBookmark(
id: String,
context: Context,
progressListener: ProgressListener?
) {
updateProgressListener(progressListener, R.string.parser_reading)
responseChecker.callWithResponseCheck { api -> api.deleteBookmark(id).execute() }
}
@Throws(Exception::class)
override fun getVideos(
refresh: Boolean,
context: Context,
progressListener: ProgressListener?
): MusicDirectory {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api -> api.getVideos().execute() }
val musicDirectory = MusicDirectory()
musicDirectory.addAll(response.body()!!.videosList.toDomainEntityList())
return musicDirectory
}
@Throws(Exception::class)
override fun createShare(
ids: List<String>,
description: String?,
expires: Long?,
context: Context,
progressListener: ProgressListener?
): List<Share> {
updateProgressListener(progressListener, R.string.parser_reading)
val response = responseChecker.callWithResponseCheck { api ->
api.createShare(ids, description, expires).execute()
}
return response.body()!!.shares.toDomainEntitiesList()
}
@Throws(Exception::class)
override fun deleteShare(
id: String,
context: Context,
progressListener: ProgressListener?
) {
updateProgressListener(progressListener, R.string.parser_reading)
responseChecker.callWithResponseCheck { api -> api.deleteShare(id).execute() }
}
@Throws(Exception::class)
override fun updateShare(
id: String,
description: String?,
expires: Long?,
context: Context,
progressListener: ProgressListener?
) {
var expiresValue: Long? = expires
if (expires != null && expires == 0L) {
expiresValue = null
}
updateProgressListener(progressListener, R.string.parser_reading)
responseChecker.callWithResponseCheck { api ->
api.updateShare(id, description, expiresValue).execute()
}
}
@Throws(Exception::class)
override fun getAvatar(
context: Context,
username: String?,
size: Int,
saveToFile: Boolean,
highQuality: Boolean,
progressListener: ProgressListener?
): Bitmap? {
// Synchronize on the username so that we don't download concurrently for
// the same user.
if (username == null) {
return null
}
synchronized(username) {
// Use cached file, if existing.
var bitmap = FileUtil.getAvatarBitmap(context, username, size, highQuality)
if (bitmap == null) {
var inputStream: InputStream? = null
try {
updateProgressListener(progressListener, R.string.parser_reading)
val response = subsonicAPIClient.getAvatar(username)
if (response.hasError()) return null
inputStream = response.stream
val bytes = Util.toByteArray(inputStream)
// If we aren't allowing server-side scaling, always save the file to disk
// because it will be unmodified
if (saveToFile) {
var outputStream: OutputStream? = null
try {
outputStream = FileOutputStream(
FileUtil.getAvatarFile(context, username)
)
outputStream.write(bytes)
} finally {
Util.close(outputStream)
}
}
bitmap = FileUtil.getSampledBitmap(bytes, size, highQuality)
} finally {
Util.close(inputStream)
}
}
// Return scaled bitmap
return Util.scaleBitmap(bitmap, size)
}
}
private fun updateProgressListener(
progressListener: ProgressListener?,
@StringRes messageId: Int
) {
progressListener?.updateProgress(messageId)
}
companion object {
private const val MUSIC_FOLDER_STORAGE_NAME = "music_folder"
private const val INDEXES_STORAGE_NAME = "indexes"
private const val ARTISTS_STORAGE_NAME = "artists"
}
}
| gpl-3.0 |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/resolve/RsCachedTypeAlias.kt | 2 | 1759 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.resolve
import org.rust.lang.core.crate.Crate
import org.rust.lang.core.psi.RsTypeAlias
import org.rust.lang.core.psi.ext.RsAbstractableOwner
import org.rust.lang.core.psi.ext.RsTypeAliasImplMixin
import org.rust.lang.core.psi.ext.owner
import org.rust.lang.core.psi.isValidProjectMemberAndContainingCrate
import org.rust.lang.core.types.consts.CtConstParameter
import org.rust.lang.core.types.infer.constGenerics
import org.rust.lang.core.types.infer.generics
import org.rust.lang.core.types.ty.Ty
import org.rust.lang.core.types.ty.TyTypeParameter
import kotlin.LazyThreadSafetyMode.PUBLICATION
/**
* Used for optimization purposes, to reduce access to cache and PSI tree in some very hot places,
* [ImplLookup.processTyFingerprintsWithAliases] in particular
*/
class RsCachedTypeAlias(
val alias: RsTypeAlias
) {
val name: String? = alias.name
val isFreeAndValid: Boolean
val containingCrate: Crate?
val containingCrates: List<Crate>
init {
val (isValid, crate, crates) = alias.isValidProjectMemberAndContainingCrate
this.containingCrate = crate
this.containingCrates = crates
this.isFreeAndValid = isValid
&& name != null
&& alias.owner is RsAbstractableOwner.Free
}
val typeAndGenerics: Triple<Ty, List<TyTypeParameter>, List<CtConstParameter>> by lazy(PUBLICATION) {
Triple(alias.declaredType, alias.generics, alias.constGenerics)
}
companion object {
fun forAlias(alias: RsTypeAlias): RsCachedTypeAlias {
return (alias as RsTypeAliasImplMixin).cachedImplItem.value
}
}
}
| mit |
RSDT/Japp16 | app/src/main/java/nl/rsdt/japp/jotial/maps/sighting/SightingSession.kt | 1 | 11645 | package nl.rsdt.japp.jotial.maps.sighting
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.util.Pair
import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.google.android.material.snackbar.BaseTransientBottomBar
import com.google.android.material.snackbar.Snackbar
import com.google.gson.Gson
import nl.rsdt.japp.R
import nl.rsdt.japp.application.Japp
import nl.rsdt.japp.application.JappPreferences
import nl.rsdt.japp.jotial.maps.deelgebied.Deelgebied
import nl.rsdt.japp.jotial.maps.management.MarkerIdentifier
import nl.rsdt.japp.jotial.maps.wrapper.IJotiMap
import nl.rsdt.japp.jotial.maps.wrapper.IMarker
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 13-7-2016
* Class for Sighting
*/
class SightingSession : Snackbar.Callback(), View.OnClickListener, DialogInterface.OnClickListener, IJotiMap.SnapshotReadyCallback, IJotiMap.OnMapClickListener, IJotiMap.CancelableCallback {
/**
* The type of the sighting.
*/
private var type: String? = null
/**
* The GoogleMap used to create markers.
*/
private var jotiMap: IJotiMap? = null
/**
* The Marker that indicates the location.
*/
private var marker: IMarker? = null
/**
* The Context used for creating dialogs etc.
*/
private var context: Context? = null
/**
* The view where the Snackbar is going to be made on.
*/
private var targetView: View? = null
/**
* The Snackbar that informs the user.
*/
private var snackbar: Snackbar? = null
/**
* The AlertDialog that asks for the users confirmation.
*/
private var dialog: AlertDialog? = null
/**
* The last LatLng that was selected.
*/
private var lastLatLng: LatLng? = null
/**
* The callback for when the sighting is completed;
*/
private var callback: OnSightingCompletedCallback? = null
/**
* The Deelgebied where the lastLatLng is in, null if none.
*/
private var deelgebied: Deelgebied? = null
/**
* The last koppel that was selected.
*/
private var extra: String = ""
/**
* Initializes the SightingSession.
*/
private fun initialize() {
val bm: Bitmap?
when (type) {
SIGHT_HUNT -> bm = BitmapFactory.decodeResource(Japp.instance!!.resources, R.drawable.vos_zwart_4)
SIGHT_SPOT -> bm = BitmapFactory.decodeResource(Japp.instance!!.resources, R.drawable.vos_zwart_3)
else -> bm = null
}
snackbar = Snackbar.make(targetView!!, R.string.sighting_standard_text, Snackbar.LENGTH_INDEFINITE)
snackbar!!.setAction(R.string.sighting_snackbar_action_text, this)
snackbar!!.addCallback(this)
marker = jotiMap!!.addMarker(Pair(MarkerOptions()
.visible(false)
.position(LatLng(0.0, 0.0)), bm))
val inflater = LayoutInflater.from(context)
@SuppressLint("InflateParams") val view = inflater.inflate(R.layout.sighting_input_dialog, null)
dialog = AlertDialog.Builder(context)
.setCancelable(false)
.setPositiveButton(R.string.confirm, this)
.setNegativeButton(R.string.cancel, this)
.setView(view)
.create()
//val et = dialog?.findViewById<EditText>(R.id.sighting_dialog_info_edit)
//et?.setText(JappPreferences.defaultKoppel())
}
override fun onDismissed(snackbar: Snackbar?, event: Int) {
super.onDismissed(snackbar, event)
if (event == BaseTransientBottomBar.BaseCallback.DISMISS_EVENT_SWIPE) {
if (callback != null) {
callback!!.onSightingCompleted(null, null, null)
}
destroy()
}
}
/**
* Starts the SightingSession.
*/
fun start() {
jotiMap!!.setOnMapClickListener(this)
snackbar!!.show()
}
private fun updateDeelgebied(latLng: LatLng, onUpdate: (LatLng) -> Unit){
var updateMarker = false
val deelgebieden = listOf("A", "B", "C", "D", "E", "F", "X").toTypedArray()
val deelgebiedDialog = AlertDialog.Builder(targetView?.context)
.setTitle("Welke Vos?")
.setItems(deelgebieden) { _, whichDeelgebied ->
val deelgebied = deelgebieden[whichDeelgebied]
val newdeelgebied = Deelgebied.parse(deelgebied)
if (newdeelgebied != this.deelgebied){
this.deelgebied = newdeelgebied
onUpdate(latLng)
}
}
.create()
deelgebiedDialog.show()
}
private fun updateExtra(latLng: LatLng, onUpdate: (LatLng) -> Unit){
val koppels = listOf(JappPreferences.defaultKoppel(),"Onbekend", "1", "2", "3", "4", "5", "6").toTypedArray()
val koppelDialog = AlertDialog.Builder(targetView?.context)
.setTitle("Welk Koppel?")
.setItems(koppels) { _, whichKoppel ->
val koppel = koppels[whichKoppel]
if (koppel != this.extra){
this.extra = koppel
onUpdate(latLng)
}
}
.create()
koppelDialog.show()
}
override fun onMapClick(latLng: LatLng): Boolean {
lastLatLng = latLng
marker?.position = latLng
updateDeelgebied(latLng) {
updateExtra(it) {
if (deelgebied != null) {
var icon: String? = null
when (type) {
SIGHT_HUNT -> {
marker!!.setIcon(deelgebied!!.drawableHunt)
icon = deelgebied?.drawableHunt.toString()
}
SIGHT_SPOT -> {
marker?.setIcon(deelgebied!!.drawableSpot)
icon = deelgebied?.drawableSpot.toString()
}
}
val identifier = MarkerIdentifier.Builder()
.setType(MarkerIdentifier.TYPE_SIGHTING)
.add("text", type)
.add("icon", icon)
.create()
marker?.title = Gson().toJson(identifier)
}
}
marker?.isVisible = true
}
return false
}
override fun onClick(dialogInterface: DialogInterface, i: Int) {
when (i) {
AlertDialog.BUTTON_POSITIVE -> if (callback != null) {
callback!!.onSightingCompleted(lastLatLng, deelgebied, this.extra)
destroy()
}
AlertDialog.BUTTON_NEGATIVE -> {
snackbar!!.setText(R.string.sighting_standard_text)
snackbar!!.show()
}
}
}
override fun onClick(view: View) {
if (deelgebied == null) {
deelgebied = Deelgebied.Xray
}
jotiMap!!.animateCamera(lastLatLng?:LatLng(0.0, 0.0), 12, this)
}
override fun onFinish() {
dialog?.show()
(dialog?.findViewById<View>(R.id.sighting_dialog_title) as TextView?)?.text = context!!.getString(R.string.confirm_type, type)
(dialog?.findViewById<View>(R.id.sighting_dialog_team_label) as TextView?)?.text = context!!.getString(R.string.deelgebied_name, deelgebied!!.name)
jotiMap?.snapshot(this@SightingSession)
}
override fun onCancel() {
dialog?.show()
(dialog?.findViewById<View>(R.id.sighting_dialog_title) as TextView).text = context!!.getString(R.string.confirm_type, type)
(dialog?.findViewById<View>(R.id.sighting_dialog_team_label) as TextView).text = context!!.getString(R.string.deelgebied_name, deelgebied!!.name)
jotiMap?.snapshot(this@SightingSession)
}
override fun onSnapshotReady(bitmap: Bitmap) {
(dialog?.findViewById<View>(R.id.sighting_dialog_snapshot) as ImageView).setImageDrawable(BitmapDrawable(Japp.appResources, bitmap))
}
/**
* Destroys the SightingSession.
*/
fun destroy() {
type = null
if (jotiMap != null) {
jotiMap!!.setOnMapClickListener(null)
jotiMap = null
}
if (marker != null) {
marker!!.remove()
marker = null
}
if (dialog != null) {
dialog!!.dismiss()
dialog = null
}
if (snackbar != null) {
snackbar!!.dismiss()
snackbar = null
}
lastLatLng = null
callback = null
deelgebied = null
}
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 13-7-2016
* Builder for the SightingSession.
*/
class Builder {
/**
* Buffer to hold the SightingSession.
*/
private val buffer = SightingSession()
/**
* Sets the GoogleMap of the SightingSession.
*/
fun setGoogleMap(jotiMap: IJotiMap?): Builder {
buffer.jotiMap = jotiMap
return this
}
/**
* Sets the Type of the SightingSession.
*/
fun setType(type: String): Builder {
buffer.type = type
return this
}
/**
* Sets the TargetView of the SightingSession.
*/
fun setTargetView(view: View): Builder {
buffer.targetView = view
return this
}
/**
* Sets the Context for the Dialog of the SightingSession.
*/
fun setDialogContext(context: Context): Builder {
buffer.context = context
return this
}
/**
* Sets the callback of the SightingSession.
*/
fun setOnSightingCompletedCallback(callback: OnSightingCompletedCallback): Builder {
buffer.callback = callback
return this
}
/**
* Creates the SightingSession.
*/
fun create(): SightingSession {
buffer.initialize()
return buffer
}
}
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 13-7-2016
* Callback for when a SightingSession is completed.
*/
interface OnSightingCompletedCallback {
/**
* Gets invoked when a SightingSession has been completed.
*
* @param chosen The chosen LatLng.
* @param deelgebied The Deelgebied where the LatLng is in, null if none.
* @param optionalInfo The optional info the user can provide.
*/
fun onSightingCompleted(chosen: LatLng?, deelgebied: Deelgebied?, optionalInfo: String?)
}
companion object {
/**
* Defines the SightingSession type HUNT.
*/
val SIGHT_HUNT = "HUNT"
/**
* Defines the SightingSession type SPOT.
*/
val SIGHT_SPOT = "SPOT"
}
}
| apache-2.0 |
RSDT/Japp16 | app/src/main/java/nl/rsdt/japp/application/activities/PreLoginSplashActivity.kt | 1 | 6043 | package nl.rsdt.japp.application.activities
import android.app.Activity
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import nl.rsdt.japp.BuildConfig
import nl.rsdt.japp.R
import nl.rsdt.japp.application.Japp
import nl.rsdt.japp.application.JappPreferences
import nl.rsdt.japp.jotial.auth.Authentication
import nl.rsdt.japp.jotial.io.AppData
import nl.rsdt.japp.jotial.net.apis.AuthApi
import org.acra.ACRA
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.IOException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import com.android.volley.Request as VRequest
import com.android.volley.Response as VResponse
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 8-7-2016
* Description...
*/
class PreLoginSplashActivity : Activity() {
internal var permission_check: Int = 0
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
/*
* Checks if the Fresh-Start feature is enabled if so the data of the app is cleared.
* */
if (JappPreferences.isFreshStart) {
/*
* Clear preferences.
* */
JappPreferences.clear()
/*
* Clear all the data files
* */
AppData.clear()
}
}
override fun onResume() {
super.onResume()
checkLatestReleaseAndValidate()
}
private fun checkLatestReleaseAndValidate() {
var currentVersionName = BuildConfig.VERSION_NAME
val queue = Volley.newRequestQueue(this)
val url = "https://api.github.com/repos/rsdt/japp/releases/latest"
var dialog = AlertDialog.Builder(this)
dialog.setNegativeButton("negeren") { dialogInterface: DialogInterface, i: Int -> validate()}
// Request a string response from the provided URL.
val stringRequest = StringRequest(VRequest.Method.GET, url,
VResponse.Listener<String> { response ->
var json = JSONObject(response)
var newVersionName = json["name"]
if (currentVersionName != newVersionName){
dialog.setTitle("Er is een nieuwe versie van de app: ${newVersionName}")
dialog.setPositiveButton("Naar Download") { dialogInterface: DialogInterface, i: Int ->
var url = "https://github.com/RSDT/Japp16/releases/latest"
var myIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
startActivity(myIntent)
//validate()
}
dialog.create()
dialog.show()
}else{
validate()
}
},
VResponse.ErrorListener {
dialog.setTitle("error bij het controleren op updates")
dialog.create()
dialog.show()
})
// Add the request to thpreviewe RequestQueue.
queue.add(stringRequest)
}
fun validate() {
val api = Japp.getApi(AuthApi::class.java)
api.validateKey(JappPreferences.accountKey).enqueue(object : Callback<Authentication.ValidateObject> {
override fun onResponse(call: Call<Authentication.ValidateObject>, response: Response<Authentication.ValidateObject>) {
if (response.code() == 200) {
val `object` = response.body()
if (`object` != null) {
if (!`object`.exists()) {
Authentication.startLoginActivity(this@PreLoginSplashActivity)
} else {
determineAndStartNewActivity()
}
}
} else {
Authentication.startLoginActivity(this@PreLoginSplashActivity)
}
}
override fun onFailure(call: Call<Authentication.ValidateObject>, t: Throwable) {
if (t is UnknownHostException) {
determineAndStartNewActivity()
} else if (t is SocketTimeoutException) {
AlertDialog.Builder(this@PreLoginSplashActivity)
.setTitle(getString(R.string.err_verification))
.setMessage(R.string.splash_activity_socket_timed_out)
.setPositiveButton(R.string.try_again) { _, _ -> determineAndStartNewActivity() }
.create()
.show()
} else {
AlertDialog.Builder(this@PreLoginSplashActivity)
.setTitle(getString(R.string.err_verification))
.setMessage(t.toString())
.setPositiveButton(getString(R.string.try_again)) { _, _ -> validate() }
.create()
.show()
}
ACRA.errorReporter.handleException(t)
Log.e(TAG, t.toString(), t)
}
})
}
fun determineAndStartNewActivity() {
val key = JappPreferences.accountKey
if (key?.isEmpty() != false) {
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
finish()
} else {
val intent = Intent(this, SplashActivity::class.java)
startActivity(intent)
finish()
}
}
companion object {
val TAG = "PreLoginSplashActivity"
val LOAD_ID = "LOAD_RESULTS"
}
}
| apache-2.0 |
charleskorn/batect | app/src/main/kotlin/batect/logging/ApplicationInfoLogger.kt | 1 | 1691 | /*
Copyright 2017-2020 Charles Korn.
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 batect.logging
import batect.VersionInfo
import batect.data
import batect.docker.client.DockerSystemInfoClient
import batect.os.SystemInfo
import batect.os.data
class ApplicationInfoLogger(
private val logger: Logger,
private val versionInfo: VersionInfo,
private val systemInfo: SystemInfo,
private val dockerSystemInfoClient: DockerSystemInfoClient,
private val environmentVariables: Map<String, String>
) {
constructor(logger: Logger, versionInfo: VersionInfo, systemInfo: SystemInfo, dockerSystemInfoClient: DockerSystemInfoClient)
: this(logger, versionInfo, systemInfo, dockerSystemInfoClient, System.getenv())
fun logApplicationInfo(commandLineArgs: Iterable<String>) {
logger.info {
message("Application started.")
data("commandLine", commandLineArgs)
data("versionInfo", versionInfo)
data("systemInfo", systemInfo)
data("dockerVersionInfo", dockerSystemInfoClient.getDockerVersionInfo().toString())
data("environment", environmentVariables)
}
}
}
| apache-2.0 |
SimpleMobileTools/Simple-Commons | commons/src/main/kotlin/com/simplemobiletools/commons/views/MySeekBar.kt | 1 | 654 | package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import android.widget.SeekBar
import com.simplemobiletools.commons.extensions.applyColorFilter
class MySeekBar : SeekBar {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) {
progressDrawable.applyColorFilter(accentColor)
thumb?.applyColorFilter(accentColor)
}
}
| gpl-3.0 |
androidx/androidx | compose/integration-tests/docs-snippets/src/main/java/androidx/compose/integration/docs/layering/Layering.kt | 3 | 3729 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("unused", "UNUSED_PARAMETER", "UNUSED_VARIABLE")
package androidx.compose.integration.docs.layering
import androidx.compose.animation.Animatable
import androidx.compose.animation.animateColorAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.material.MaterialTheme
import androidx.compose.material.ProvideTextStyle
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
/**
* This file lets DevRel track changes to snippets present in
* https://developer.android.com/jetpack/compose/layering
*
* No action required if it's modified.
*/
@Composable
private fun LayeringSnippetControl1() {
val color = animateColorAsState(if (condition) Color.Green else Color.Red)
}
@Composable
private fun LayeringSnippetControl2() {
val color = remember { Animatable(Color.Gray) }
LaunchedEffect(condition) {
color.animateTo(if (condition) Color.Green else Color.Red)
}
}
@Composable
private fun LayeringSnippetCustomization1() {
@Composable
fun Button(
// …
content: @Composable RowScope.() -> Unit
) {
Surface(/* … */) {
CompositionLocalProvider(/* LocalContentAlpha … */) {
ProvideTextStyle(MaterialTheme.typography.button) {
Row(
// …
content = content
)
}
}
}
}
}
@Composable
private fun LayeringSnippetCustomization2() {
@Composable
fun GradientButton(
// …
background: List<Color>,
content: @Composable RowScope.() -> Unit
) {
Row(
// …
modifier = modifier
.clickable(/* … */)
.background(
Brush.horizontalGradient(background)
)
) {
// Use Material LocalContentAlpha & ProvideTextStyle
CompositionLocalProvider(/* LocalContentAlpha … */) {
ProvideTextStyle(MaterialTheme.typography.button) {
content()
}
}
}
}
}
@Composable
private fun LayeringSnippetCustomization3() {
@Composable
fun BespokeButton(
// …
content: @Composable RowScope.() -> Unit
) {
// No Material components used
Row(
// …
modifier = modifier
.clickable(/* … */)
.background(/* … */),
content = content
)
}
}
/*
Fakes needed for snippets to build:
*/
private val condition = false
private val modifier = Modifier
private fun Modifier.clickable() = this
private fun Modifier.background() = this
| apache-2.0 |
Niky4000/UsefulUtils | projects/tutorials-master/tutorials-master/core-kotlin/src/test/kotlin/com/baeldung/fuel/FuelHttpUnitTest.kt | 1 | 8523 | package com.baeldung.fuel
import com.github.kittinunf.fuel.Fuel
import com.github.kittinunf.fuel.core.FuelManager
import com.github.kittinunf.fuel.core.interceptors.cUrlLoggingRequestInterceptor
import com.github.kittinunf.fuel.gson.responseObject
import com.github.kittinunf.fuel.httpGet
import com.github.kittinunf.fuel.rx.rx_object
import com.google.gson.Gson
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import java.io.File
import java.util.concurrent.CountDownLatch
internal class FuelHttpUnitTest {
@Test
fun whenMakingAsyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
val latch = CountDownLatch(1)
"http://httpbin.org/get".httpGet().response{
request, response, result ->
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
latch.countDown()
}
latch.await()
}
@Test
fun whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
val (request, response, result) = "http://httpbin.org/get".httpGet().response()
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
}
@Test
fun whenMakingSyncHttpGetURLEncodedRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
val (request, response, result) =
"https://jsonplaceholder.typicode.com/posts"
.httpGet(listOf("id" to "1")).response()
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
}
@Test
fun whenMakingAsyncHttpPostRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
val latch = CountDownLatch(1)
Fuel.post("http://httpbin.org/post").response{
request, response, result ->
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
latch.countDown()
}
latch.await()
}
@Test
fun whenMakingSyncHttpPostRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
val (request, response, result) = Fuel.post("http://httpbin.org/post").response()
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
}
@Test
fun whenMakingSyncHttpPostRequestwithBody_thenResponseNotNullAndErrorNullAndStatusCode200() {
val (request, response, result) = Fuel.post("https://jsonplaceholder.typicode.com/posts")
.body("{ \"title\" : \"foo\",\"body\" : \"bar\",\"id\" : \"1\"}")
.response()
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(201,response.statusCode)
}
@Test
fun givenFuelInstance_whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
FuelManager.instance.basePath = "http://httpbin.org"
FuelManager.instance.baseHeaders = mapOf("OS" to "macOS High Sierra")
FuelManager.instance.addRequestInterceptor(cUrlLoggingRequestInterceptor())
FuelManager.instance.addRequestInterceptor(tokenInterceptor())
val (request, response, result) = "/get"
.httpGet().response()
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
}
@Test
fun givenInterceptors_whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {
FuelManager.instance.basePath = "http://httpbin.org"
FuelManager.instance.addRequestInterceptor(cUrlLoggingRequestInterceptor())
FuelManager.instance.addRequestInterceptor(tokenInterceptor())
val (request, response, result) = "/get"
.httpGet().response()
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
}
@Test
fun whenDownloadFile_thenCreateFileResponseNotNullAndErrorNullAndStatusCode200() {
Fuel.download("http://httpbin.org/bytes/32768").destination { response, url ->
File.createTempFile("temp", ".tmp")
}.response{
request, response, result ->
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
}
}
@Test
fun whenDownloadFilewithProgressHandler_thenCreateFileResponseNotNullAndErrorNullAndStatusCode200() {
val (request, response, result) = Fuel.download("http://httpbin.org/bytes/327680")
.destination { response, url -> File.createTempFile("temp", ".tmp")
}.progress { readBytes, totalBytes ->
val progress = readBytes.toFloat() / totalBytes.toFloat()
}.response ()
val (data, error) = result
Assertions.assertNull(error)
Assertions.assertNotNull(data)
Assertions.assertEquals(200,response.statusCode)
}
@Test
fun whenMakeGetRequest_thenDeserializePostwithGson() {
val latch = CountDownLatch(1)
"https://jsonplaceholder.typicode.com/posts/1".httpGet().responseObject<Post> { _,_, result ->
val post = result.component1()
Assertions.assertEquals(1, post?.userId)
latch.countDown()
}
latch.await()
}
@Test
fun whenMakePOSTRequest_thenSerializePostwithGson() {
val post = Post(1,1, "Lorem", "Lorem Ipse dolor sit amet")
val (request, response, result) = Fuel.post("https://jsonplaceholder.typicode.com/posts")
.header("Content-Type" to "application/json")
.body(Gson().toJson(post).toString())
.response()
Assertions.assertEquals(201,response.statusCode)
}
@Test
fun whenMakeGETRequestWithRxJava_thenDeserializePostwithGson() {
val latch = CountDownLatch(1)
"https://jsonplaceholder.typicode.com/posts?id=1"
.httpGet().rx_object(Post.Deserializer()).subscribe{
res, throwable ->
val post = res.component1()
Assertions.assertEquals(1, post?.get(0)?.userId)
latch.countDown()
}
latch.await()
}
// The new 1.3 coroutine APIs, aren't implemented yet in Fuel Library
// @Test
// fun whenMakeGETRequestUsingCoroutines_thenResponseStatusCode200() = runBlocking {
// val (request, response, result) = Fuel.get("http://httpbin.org/get").awaitStringResponse()
//
// result.fold({ data ->
// Assertions.assertEquals(200, response.statusCode)
//
// }, { error -> })
// }
// The new 1.3 coroutine APIs, aren't implemented yet in Fuel Library
// @Test
// fun whenMakeGETRequestUsingCoroutines_thenDeserializeResponse() = runBlocking {
// Fuel.get("https://jsonplaceholder.typicode.com/posts?id=1").awaitObjectResult(Post.Deserializer())
// .fold({ data ->
// Assertions.assertEquals(1, data.get(0).userId)
// }, { error -> })
// }
@Test
fun whenMakeGETPostRequestUsingRoutingAPI_thenDeserializeResponse() {
val latch = CountDownLatch(1)
Fuel.request(PostRoutingAPI.posts("1",null))
.responseObject(Post.Deserializer()) {
request, response, result ->
Assertions.assertEquals(1, result.component1()?.get(0)?.userId)
latch.countDown()
}
latch.await()
}
@Test
fun whenMakeGETCommentRequestUsingRoutingAPI_thenResponseStausCode200() {
val latch = CountDownLatch(1)
Fuel.request(PostRoutingAPI.comments("1",null))
.responseString { request, response, result ->
Assertions.assertEquals(200, response.statusCode)
latch.countDown()
}
latch.await()
}
} | gpl-3.0 |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/sponge/inspection/SpongeLoggingInspection.kt | 1 | 2271 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.sponge.inspection
import com.demonwav.mcdev.platform.sponge.SpongeModuleType
import com.demonwav.mcdev.util.Constants
import com.demonwav.mcdev.util.fullQualifiedName
import com.intellij.codeInspection.AbstractBaseJavaLocalInspectionTool
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.JavaElementVisitor
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiField
import com.intellij.psi.PsiFile
class SpongeLoggingInspection : AbstractBaseJavaLocalInspectionTool() {
override fun getStaticDescription() =
"Sponge provides a ${Constants.SLF4J_LOGGER} logger implementation using @Inject in your plugin class. " +
"You should not use ${Constants.JAVA_UTIL_LOGGER} in your plugin."
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return if (SpongeModuleType.isInModule(holder.file)) {
Visitor(holder)
} else {
PsiElementVisitor.EMPTY_VISITOR
}
}
override fun processFile(file: PsiFile, manager: InspectionManager): List<ProblemDescriptor> {
return if (SpongeModuleType.isInModule(file)) {
super.processFile(file, manager)
} else {
emptyList()
}
}
private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() {
override fun visitField(field: PsiField) {
val element = field.typeElement ?: return
val name = (field.type as? PsiClassType)?.fullQualifiedName ?: return
if (name != Constants.JAVA_UTIL_LOGGER) {
return
}
holder.registerProblem(
element,
"Sponge plugins should use ${Constants.SLF4J_LOGGER} rather than ${Constants.JAVA_UTIL_LOGGER}.",
ProblemHighlightType.GENERIC_ERROR_OR_WARNING
)
}
}
}
| mit |
EventFahrplan/EventFahrplan | app/src/main/java/nerd/tuxmobil/fahrplan/congress/utils/ServerBackendType.kt | 1 | 250 | package nerd.tuxmobil.fahrplan.congress.utils
sealed class ServerBackendType(val name: String) {
object PENTABARF : ServerBackendType("pentabarf")
object FRAB : ServerBackendType("frab")
object PRETALX : ServerBackendType("pretalx")
}
| apache-2.0 |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/IntentExtra.kt | 1 | 4109 | /**
* Copyright (C) 2015 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app
import org.andstatus.app.account.MyAccount
import org.andstatus.app.appwidget.MyAppWidgetProvider
import org.andstatus.app.data.ParsedUri
import org.andstatus.app.service.MyService
import org.andstatus.app.service.MyServiceState
import org.andstatus.app.timeline.meta.TimelineType
/**
* Names of extras are used in the Intent-messaging
* (e.g. to notify Widget of a new Notes)
*/
enum class IntentExtra(keySuffix: String?) {
/**
* This extra is used as a command to be executed by [MyService] and by
* [MyAppWidgetProvider]. Value of this extra is a string code of CommandEnum
*/
COMMAND("COMMAND_ENUM"),
COMMAND_DESCRIPTION("COMMAND_DESCRIPTION"),
REQUEST_CODE("REQUEST_CODE"),
/**
* Command parameter: long - ID of the Tweet (or Note) / Actor / Origin
*/
ITEM_ID("ITEM_ID"),
INSTANCE_ID("INSTANCE_ID"),
COMMAND_RESULT("COMMAND_RESULT"),
/**
* [MyServiceState]
*/
SERVICE_STATE("SERVICE_STATE"),
SERVICE_EVENT("SERVICE_EVENT"),
PROGRESS_TEXT("PROGRESS_TEXT"),
/** Text of the note/"tweet" */
NOTE_TEXT("NOTE_TEXT"),
MEDIA_URI("MEDIA_URI"),
/** Account name, see [MyAccount.getAccountName] */
ACCOUNT_NAME("ACCOUNT_NAME"),
/** Selected Actor. E.g. the Actor whose notes we are seeing */
ACTOR_ID("ACTOR_ID"),
USERNAME("ACTOR_NAME"),
ORIGIN_ID("ORIGIN_ID"),
ORIGIN_NAME("ORIGIN_NAME"),
ORIGIN_TYPE("ORIGIN_TYPE"),
/** @see org.andstatus.app.view.MyContextMenu.MENU_GROUP_ACTOR MENU_GROUP_...
*/
MENU_GROUP("MENU_GROUP"),
/**
* Name of the preference to set
*/
PREFERENCE_KEY("PREFERENCE_KEY"),
PREFERENCE_VALUE("PREFERENCE_VALUE"),
/**
* Reply to
*/
IN_REPLY_TO_ID("IN_REPLY_TO_ID"),
/**
* Recipient of a (usually private) note
*/
RECIPIENT_ID("RECIPIENT_ID"),
SEARCH_QUERY("SEARCH_QUERY"),
/**
* Number of new tweets. Value is integer
*/
NUM_TWEETS("NUM_TWEETS"),
/** See [ParsedUri] */
MATCHED_URI("MATCHED_URI"),
/**
* This extra is used to determine which timeline to show in
* TimelineActivity Value is [TimelineType]
*/
TIMELINE_TYPE("TIMELINE_TYPE"),
TIMELINE_ID("TIMELINE_ID"),
SELECTABLE_ENUM("SELECTABLE_ENUM"),
/**
* Is the timeline combined
*/
TIMELINE_IS_COMBINED("TIMELINE_IS_COMBINED"),
ROWS_LIMIT("ROWS_LIMIT"),
POSITION_RESTORED("POSITION_RESTORED"),
WHICH_PAGE("WHICH_PAGE"),
COMMAND_ID("COMMAND_ID"),
CREATED_DATE("UPDATED_DATE"),
LAST_EXECUTED_DATE("LAST_EXECUTED_DATE"),
EXECUTION_COUNT("EXECUTION_COUNT"),
FINISH("FINISH"),
RETRIES_LEFT("RETRIES_LEFT"),
NUM_AUTH_EXCEPTIONS("NUM_AUTH_EXCEPTIONS"),
NUM_IO_EXCEPTIONS("NUM_IO_EXCEPTIONS"),
NUM_PARSE_EXCEPTIONS("NUM_PARSE_EXCEPTIONS"),
ERROR_MESSAGE("ERROR_MESSAGE"),
DOWNLOADED_COUNT("DOWNLOADED_COUNT"),
IN_FOREGROUND("IN_FOREGROUND"),
MANUALLY_LAUNCHED("MANUALLY_LAUNCHED"),
IS_STEP("IS_STEP"),
CHAINED_REQUEST("CHAINED_REQUEST"),
COLLAPSE_DUPLICATES("COLLAPSE_DUPLICATES"),
INITIAL_ACCOUNT_SYNC("INITIAL_ACCOUNT_SYNC"),
SYNC("SYNC"),
CHECK_DATA("CHECK_DATA"),
CHECK_SCOPE("CHECK_SCOPE"),
FULL_CHECK("FULL_CHECK"),
COUNT_ONLY("COUNT_ONLY"),
SETTINGS_GROUP("SETTINGS_GROUP"),
UNKNOWN("UNKNOWN");
val key: String = ClassInApplicationPackage.PACKAGE_NAME + "." + keySuffix
}
| apache-2.0 |
Tvede-dk/CommonsenseAndroidKotlin | base/src/test/kotlin/com/commonsense/android/kotlin/base/patterns/ExpectedFailedTest.kt | 1 | 305 | package com.commonsense.android.kotlin.base.patterns
import org.junit.*
import org.junit.jupiter.api.Test
/**
*
*/
internal class ExpectedFailedTest {
@Ignore
@Test
fun isError() {
}
@Ignore
@Test
fun getError() {
}
@Ignore
@Test
fun getValue() {
}
} | mit |
adgvcxz/Diycode | app/src/main/java/com/adgvcxz/diycode/rxbus/OpenMainDrawer.kt | 1 | 112 | package com.adgvcxz.diycode.rxbus
/**
* zhaowei
* Created by zhaowei on 2017/2/13.
*/
class OpenMainDrawer
| apache-2.0 |
inorichi/tachiyomi-extensions | src/th/nekopost/src/eu/kanade/tachiyomi/extension/th/nekopost/Nekopost.kt | 1 | 11241 | package eu.kanade.tachiyomi.extension.th.nekopost
import com.google.gson.Gson
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.asObservableSuccess
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.Headers
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import rx.Observable
import java.text.SimpleDateFormat
import java.util.Locale
class Nekopost : ParsedHttpSource() {
override val baseUrl: String = "https://www.nekopost.net/manga/"
private val mangaListUrl: String = "https://tuner.nekopost.net/ApiTest/getLatestChapterOffset/m/"
private val projectDataUrl: String = "https://tuner.nekopost.net/ApiTest/getProjectDetailFull/"
private val fileUrl: String = "https://fs.nekopost.net/"
override val client: OkHttpClient = network.cloudflareClient
override fun headersBuilder(): Headers.Builder {
return super.headersBuilder().add("Referer", baseUrl)
}
override val lang: String = "th"
override val name: String = "Nekopost"
override val supportsLatest: Boolean = true
private data class MangaListTracker(
var offset: Int = 0,
val list: HashSet<String> = HashSet()
)
private var latestMangaTracker = MangaListTracker()
private var popularMangaTracker = MangaListTracker()
data class ProjectRecord(
val project: SManga,
val project_id: String,
val chapter_list: HashSet<String> = HashSet(),
)
data class ChapterRecord(
val chapter: SChapter,
val chapter_id: String,
val project: ProjectRecord,
val pages_data: String,
)
private var projectUrlMap = HashMap<String, ProjectRecord>()
private var chapterList = HashMap<String, ChapterRecord>()
private fun getStatus(status: String) = when (status) {
"1" -> SManga.ONGOING
"2" -> SManga.COMPLETED
"3" -> SManga.LICENSED
else -> SManga.UNKNOWN
}
private fun fetchMangas(page: Int, tracker: MangaListTracker): Observable<MangasPage> {
if (page == 1) {
tracker.list.clear()
tracker.offset = 0
}
return client.newCall(latestUpdatesRequest(page + tracker.offset))
.asObservableSuccess()
.concatMap { response ->
latestUpdatesParse(response).let {
if (it.mangas.isEmpty() && it.hasNextPage) {
tracker.offset++
fetchLatestUpdates(page)
} else {
Observable.just(it)
}
}
}
}
private fun mangasRequest(page: Int): Request = GET("$mangaListUrl${page - 1}")
private fun mangasParse(response: Response, tracker: MangaListTracker): MangasPage {
val mangaData = Gson().fromJson(response.body!!.string(), RawMangaDataList::class.java)
return if (mangaData.listItem != null) {
val mangas: List<SManga> = mangaData.listItem.filter {
!tracker.list.contains(it.np_project_id)
}.map {
tracker.list.add(it.np_project_id)
SManga.create().apply {
url = it.np_project_id
title = it.np_name
thumbnail_url = "${fileUrl}collectManga/${it.np_project_id}/${it.np_project_id}_cover.jpg"
initialized = false
projectUrlMap[it.np_project_id] = ProjectRecord(
project = this,
project_id = it.np_project_id
)
}
}
MangasPage(mangas, true)
} else {
MangasPage(emptyList(), true)
}
}
override fun chapterListSelector(): String = throw NotImplementedError("Unused")
override fun chapterFromElement(element: Element): SChapter = throw NotImplementedError("Unused")
override fun fetchImageUrl(page: Page): Observable<String> = Observable.just(page.imageUrl)
override fun imageUrlParse(document: Document): String = throw NotImplementedError("Unused")
override fun fetchLatestUpdates(page: Int): Observable<MangasPage> = fetchMangas(page, latestMangaTracker)
override fun latestUpdatesParse(response: Response): MangasPage = mangasParse(response, latestMangaTracker)
override fun latestUpdatesFromElement(element: Element): SManga = throw Exception("Unused")
override fun latestUpdatesNextPageSelector(): String = throw Exception("Unused")
override fun latestUpdatesRequest(page: Int): Request = mangasRequest(page)
override fun latestUpdatesSelector(): String = throw Exception("Unused")
override fun mangaDetailsParse(document: Document): SManga = throw NotImplementedError("Unused")
override fun fetchMangaDetails(sManga: SManga): Observable<SManga> {
val manga = projectUrlMap[sManga.url]!!
return client.newCall(GET("$projectDataUrl${manga.project_id}"))
.asObservableSuccess()
.concatMap {
val mangaData = Gson().fromJson(it.body!!.string(), RawMangaDetailedData::class.java)
Observable.just(
manga.project.apply {
mangaData.projectInfo.also { projectData ->
artist = projectData.artist_name
author = projectData.author_name
description = projectData.np_info
status = getStatus(projectData.np_status)
initialized = true
}
genre = mangaData.projectCategoryUsed?.joinToString(", ") { cat -> cat.npc_name }
?: ""
}
)
}
}
override fun fetchChapterList(sManga: SManga): Observable<List<SChapter>> {
val manga = projectUrlMap[sManga.url]!!
return if (manga.project.status != SManga.LICENSED) {
client.newCall(GET("$projectDataUrl${manga.project_id}"))
.asObservableSuccess()
.map {
val mangaData = Gson().fromJson(it.body!!.string(), RawMangaDetailedData::class.java)
mangaData.projectChapterList.map { chapter ->
val chapterUrl = "$baseUrl${manga.project_id}/${chapter.nc_chapter_no}"
manga.chapter_list.add(chapterUrl)
val createdChapter = SChapter.create().apply {
url = chapterUrl
name = chapter.nc_chapter_name
date_upload = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale("th")).parse(chapter.nc_created_date)?.time
?: 0L
chapter_number = chapter.nc_chapter_no.toFloat()
scanlator = chapter.cu_displayname
}
chapterList[chapterUrl] = ChapterRecord(
chapter = createdChapter,
project = manga,
chapter_id = chapter.nc_chapter_id,
pages_data = chapter.nc_data_file,
)
createdChapter
}
}
} else {
Observable.error(Exception("Licensed - No chapter to show"))
}
}
override fun fetchPageList(sChapter: SChapter): Observable<List<Page>> {
val chapter = chapterList[sChapter.url]!!
return client.newCall(GET("${fileUrl}collectManga/${chapter.project.project_id}/${chapter.chapter_id}/${chapter.pages_data}"))
.asObservableSuccess()
.map {
val chapterData = Gson().fromJson(it.body!!.string(), RawChapterDetailedData::class.java)
chapterData.pageItem.map { pageData ->
Page(
index = pageData.pageNo,
imageUrl = "${fileUrl}collectManga/${chapter.project.project_id}/${chapter.chapter_id}/${pageData.fileName}",
)
}
}
}
override fun pageListParse(document: Document): List<Page> = throw NotImplementedError("Unused")
override fun fetchPopularManga(page: Int): Observable<MangasPage> = fetchMangas(page, popularMangaTracker)
override fun popularMangaParse(response: Response): MangasPage = mangasParse(response, popularMangaTracker)
override fun popularMangaFromElement(element: Element): SManga = throw NotImplementedError("Unused")
override fun popularMangaNextPageSelector(): String = throw Exception("Unused")
override fun popularMangaRequest(page: Int): Request = mangasRequest(page)
override fun popularMangaSelector(): String = throw Exception("Unused")
override fun searchMangaFromElement(element: Element): SManga = throw Exception("Unused")
override fun searchMangaNextPageSelector(): String = throw Exception("Unused")
override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> {
return client.newCall(GET("${fileUrl}dataJson/dataProjectName.json"))
.asObservableSuccess()
.map {
val nameData = Gson().fromJson(it.body!!.string(), Array<MangaNameList>::class.java)
val mangas: List<SManga> = nameData.filter { d -> Regex(query, setOf(RegexOption.IGNORE_CASE, RegexOption.MULTILINE)).find(d.np_name) != null }
.map { matchedManga ->
if (!projectUrlMap.containsKey(matchedManga.np_project_id)) {
SManga.create().apply {
url = matchedManga.np_project_id
title = matchedManga.np_name
thumbnail_url = "${fileUrl}collectManga/${matchedManga.np_project_id}/${matchedManga.np_project_id}_cover.jpg"
initialized = false
projectUrlMap[matchedManga.np_project_id] = ProjectRecord(
project = this,
project_id = matchedManga.np_project_id
)
}
} else {
projectUrlMap[matchedManga.np_project_id]!!.project
}
}
MangasPage(mangas, true)
}
}
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request = throw Exception("Unused")
override fun searchMangaParse(response: Response): MangasPage = throw Exception("Unused")
override fun searchMangaSelector(): String = throw Exception("Unused")
}
| apache-2.0 |
campos20/tnoodle | tnoodle-server/src/main/kotlin/org/worldcubeassociation/tnoodle/server/crypto/SymmetricCipher.kt | 1 | 1025 | package org.worldcubeassociation.tnoodle.server.crypto
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.SecretKeySpec
object SymmetricCipher {
const val CIPHER_SALT = "TNOODLE_WCA"
const val CIPHER_KEY_ITERATIONS = 65536
const val CIPHER_KEY_LENGTH = 256
const val CIPHER_ALGORITHM = "AES"
const val CIPHER_KEY_ALGORITHM = "PBKDF2WithHmacSHA$CIPHER_KEY_LENGTH"
val CIPHER_CHARSET = Charsets.UTF_8
val CIPHER_INSTANCE = Cipher.getInstance(CIPHER_ALGORITHM)
val CIPHER_KEY_FACTORY = SecretKeyFactory.getInstance(CIPHER_KEY_ALGORITHM)
fun generateKey(password: String): SecretKey {
val saltBytes = CIPHER_SALT.toByteArray(CIPHER_CHARSET)
val spec = PBEKeySpec(password.toCharArray(), saltBytes, CIPHER_KEY_ITERATIONS, CIPHER_KEY_LENGTH)
val key = CIPHER_KEY_FACTORY.generateSecret(spec)
return SecretKeySpec(key.encoded, CIPHER_ALGORITHM)
}
}
| gpl-3.0 |
rhdunn/xquery-intellij-plugin | src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/ast/xquery/XQueryTryCatchExpr.kt | 1 | 956 | /*
* Copyright (C) 2016, 2020-2021 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xquery.ast.xquery
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathExprSingle
import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.XpmTryCatchExpression
/**
* An XQuery 1.0 `TryCatchExpr` node in the XQuery AST.
*/
interface XQueryTryCatchExpr : XPathExprSingle, XpmTryCatchExpression
| apache-2.0 |
rhdunn/xquery-intellij-plugin | src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/psi/impl/xpath/XPathOtherwiseExprPsiImpl.kt | 1 | 1435 | /*
* Copyright (C) 2020 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xpath.psi.impl.xpath
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathOtherwiseExpr
import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement
import xqt.platform.intellij.xpath.XPathTokenProvider
class XPathOtherwiseExprPsiImpl(node: ASTNode) :
ASTWrapperPsiElement(node),
XPathOtherwiseExpr,
XpmSyntaxValidationElement {
// region XpmExpression
override val expressionElement: PsiElement
get() = findChildByType(XPathTokenProvider.KOtherwise)!!
// endregion
// region XpmSyntaxValidationElement
override val conformanceElement: PsiElement
get() = expressionElement
// endregion
}
| apache-2.0 |
westnordost/osmagent | app/src/main/java/de/westnordost/streetcomplete/quests/OsmQuestAnswerListener.kt | 1 | 834 | package de.westnordost.streetcomplete.quests
import de.westnordost.streetcomplete.data.QuestGroup
interface OsmQuestAnswerListener {
/** Called when the user answered the quest with the given id. What is in the bundle, is up to
* the dialog with which the quest was answered */
fun onAnsweredQuest(questId: Long, group: QuestGroup, answer: Any)
/** Called when the user chose to leave a note instead */
fun onComposeNote(questId: Long, group: QuestGroup, questTitle: String)
/** Called when the user did not answer the quest with the given id but instead left a note */
fun onLeaveNote(questId: Long, group: QuestGroup, questTitle: String, note: String, imagePaths: List<String>?)
/** Called when the user chose to skip the quest */
fun onSkippedQuest(questId: Long, group: QuestGroup)
}
| gpl-3.0 |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/surface/Surface.kt | 1 | 1422 | package de.westnordost.streetcomplete.quests.surface
import de.westnordost.streetcomplete.quests.surface.Surface.*
enum class Surface(val osmValue: String) {
ASPHALT("asphalt"),
CONCRETE("concrete"),
FINE_GRAVEL("fine_gravel"),
PAVING_STONES("paving_stones"),
COMPACTED("compacted"),
DIRT("dirt"),
SETT("sett"),
// https://forum.openstreetmap.org/viewtopic.php?id=61042
UNHEWN_COBBLESTONE("unhewn_cobblestone"),
GRASS_PAVER("grass_paver"),
WOOD("wood"),
METAL("metal"),
GRAVEL("gravel"),
PEBBLES("pebblestone"),
GRASS("grass"),
SAND("sand"),
ROCK("rock"),
CLAY("clay"),
ARTIFICIAL_TURF("artificial_turf"),
TARTAN("tartan"),
PAVED("paved"),
UNPAVED("unpaved"),
GROUND("ground"),
}
val PAVED_SURFACES = listOf(
ASPHALT, CONCRETE, PAVING_STONES,
SETT, UNHEWN_COBBLESTONE, GRASS_PAVER,
WOOD, METAL
)
val UNPAVED_SURFACES = listOf(
COMPACTED, FINE_GRAVEL, GRAVEL, PEBBLES
)
val GROUND_SURFACES = listOf(
DIRT, GRASS, SAND, ROCK
)
val PITCH_SURFACES = listOf(
GRASS, ASPHALT, SAND, CONCRETE,
CLAY, ARTIFICIAL_TURF, TARTAN, DIRT,
FINE_GRAVEL, PAVING_STONES, COMPACTED,
SETT, UNHEWN_COBBLESTONE, GRASS_PAVER,
WOOD, METAL, GRAVEL, PEBBLES,
ROCK
)
val GENERIC_SURFACES = listOf(
PAVED, UNPAVED, GROUND
)
val Surface.shouldBeDescribed: Boolean get() = this == PAVED || this == UNPAVED
| gpl-3.0 |
StepicOrg/stepic-android | app/src/main/java/org/stepic/droid/util/CompatibilityExtensions.kt | 2 | 317 | package org.stepic.droid.util
import android.content.res.Configuration
import android.os.Build
import java.util.Locale
val Configuration.defaultLocale: Locale
get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
locales.get(0)
} else {
@Suppress("DEPRECATION")
locale
}
| apache-2.0 |
worker8/TourGuide | tourguide/src/main/java/tourguide/tourguide/ToolTip.kt | 2 | 4275 | package tourguide.tourguide
import android.graphics.Color
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.view.animation.BounceInterpolator
class ToolTip() {
var title: String
private set
var description: String
private set
var mBackgroundColor: Int = 0
var mTextColor: Int = 0
var mEnterAnimation: Animation
var mExitAnimation: Animation? = null
var mShadow: Boolean = false
var mGravity: Int = 0
var mOnClickListener: View.OnClickListener? = null
var mCustomView: ViewGroup? = null
var mWidth: Int = 0
init {
/* default values */
title = ""
description = ""
mBackgroundColor = Color.parseColor("#3498db")
mTextColor = Color.parseColor("#FFFFFF")
mEnterAnimation = AlphaAnimation(0f, 1f)
mEnterAnimation.duration = 1000
mEnterAnimation.fillAfter = true
mEnterAnimation.interpolator = BounceInterpolator()
mShadow = true
mWidth = -1
// TODO: exit animation
mGravity = Gravity.CENTER
}
constructor(init: ToolTip.() -> Unit) : this() {
init()
}
fun title(block: () -> String) {
title = block()
}
fun description(block: () -> String) {
description = block()
}
fun backgroundColor(block: () -> Int) {
mBackgroundColor = block()
}
fun textColor(block: () -> Int) {
mTextColor = block()
}
fun gravity(block: () -> Int) {
mGravity = block()
}
fun shadow(block: () -> Boolean) {
mShadow = block()
}
fun enterAnimation(block: () -> Animation) {
mEnterAnimation = block()
}
fun exitAnimation(block: () -> Animation) {
mExitAnimation = block()
}
/**
* Set title text
* @param title
* @return return ToolTip instance for chaining purpose
*/
fun setTitle(title: String): ToolTip {
this.title = title
return this
}
/**
* Set description text
* @param description
* @return return ToolTip instance for chaining purpose
*/
fun setDescription(description: String): ToolTip {
this.description = description
return this
}
/**
* Set background color
* @param backgroundColor
* @return return ToolTip instance for chaining purpose
*/
fun setBackgroundColor(backgroundColor: Int): ToolTip {
mBackgroundColor = backgroundColor
return this
}
/**
* Set text color
* @param textColor
* @return return ToolTip instance for chaining purpose
*/
fun setTextColor(textColor: Int): ToolTip {
mTextColor = textColor
return this
}
/**
* Set enter animation
* @param enterAnimation
* @return return ToolTip instance for chaining purpose
*/
fun setEnterAnimation(enterAnimation: Animation): ToolTip {
mEnterAnimation = enterAnimation
return this
}
/**
* Set the gravity, the setGravity is centered relative to the targeted button
* @param gravity Gravity.CENTER, Gravity.TOP, Gravity.BOTTOM, etc
* @return return ToolTip instance for chaining purpose
*/
fun setGravity(gravity: Int): ToolTip {
mGravity = gravity
return this
}
/**
* Set if you want to have setShadow
* @param shadow
* @return return ToolTip instance for chaining purpose
*/
fun setShadow(shadow: Boolean): ToolTip {
mShadow = shadow
return this
}
/**
* Method to set the width of the ToolTip
* @param px desired width of ToolTip in pixels
* @return ToolTip instance for chaining purposes
*/
fun setWidth(px: Int): ToolTip {
if (px >= 0) mWidth = px
return this
}
fun setOnClickListener(onClickListener: View.OnClickListener): ToolTip {
mOnClickListener = onClickListener
return this
}
fun getCustomView(): ViewGroup? {
return mCustomView
}
fun setCustomView(view: ViewGroup): ToolTip {
mCustomView = view
return this
}
} | mit |
StepicOrg/stepic-android | billing/src/main/java/org/stepik/android/data/billing/source/BillingRemoteDataSource.kt | 1 | 443 | package org.stepik.android.data.billing.source
import io.reactivex.Completable
import io.reactivex.Single
import org.solovyev.android.checkout.Purchase
import org.solovyev.android.checkout.Sku
interface BillingRemoteDataSource {
fun getInventory(productType: String, skuIds: List<String>): Single<List<Sku>>
fun getAllPurchases(productType: String): Single<List<Purchase>>
fun consumePurchase(purchase: Purchase): Completable
} | apache-2.0 |
mtzaperas/burpbuddy | src/main/kotlin/burp/BCookie.kt | 1 | 453 | package burp
import java.util.Date
class BCookie(val cookie: Cookie): ICookie {
override fun getDomain(): String {
return cookie.domain
}
override fun getExpiration(): Date {
return cookie.expiration
}
override fun getName(): String {
return cookie.name
}
override fun getPath(): String {
return cookie.path
}
override fun getValue(): String {
return cookie.value
}
} | mit |
andrewoma/kwery | core/src/main/kotlin/com/github/andrewoma/kwery/core/Session.kt | 1 | 5413 | /*
* Copyright (c) 2015 Andrew O'Malley
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.andrewoma.kwery.core
import com.github.andrewoma.kwery.core.dialect.Dialect
import org.intellij.lang.annotations.Language
import java.sql.Connection
/**
* Session is the key interface for querying the database in kwery.
*
* Sessions hold an underlying JDBC connection.
*/
interface Session {
/**
* The current transaction for the session if a transaction has been started
*/
val currentTransaction: Transaction?
/**
* The underlying JDBC connection
*/
val connection: Connection
val dialect: Dialect
/**
* The default StatementOptions used for this session unless overridden explicitly on calls
*/
val defaultOptions: StatementOptions
/**
* Executes a query returning the results as `List`
*/
fun <R> select(@Language("SQL") sql: String,
parameters: Map<String, Any?> = mapOf(),
options: StatementOptions = defaultOptions,
mapper: (Row) -> R): List<R>
/**
* Executes an update returning the count of rows affected by the statement
*/
fun update(@Language("SQL") sql: String,
parameters: Map<String, Any?> = mapOf(),
options: StatementOptions = defaultOptions): Int
/**
* Executes an insert statement with generated keys, returning the keys
*/
fun <K> insert(@Language("SQL") sql: String,
parameters: Map<String, Any?> = mapOf(),
options: StatementOptions = defaultOptions, f: (Row) -> K): Pair<Int, K>
/**
* Executes a batch of update statements returning the counts of each statement executed
*/
fun batchUpdate(@Language("SQL") sql: String,
parametersList: List<Map<String, Any?>>,
options: StatementOptions = defaultOptions): List<Int>
/**
* Executes a batch of insert statements with generated keys, returning the list of keys
*/
fun <K> batchInsert(@Language("SQL") sql: String,
parametersList: List<Map<String, Any?>>,
options: StatementOptions = defaultOptions,
f: (Row) -> K): List<Pair<Int, K>>
/**
* Executes a query, providing the results as a sequence for streaming.
* This is the most flexible method for handling large result sets without loading them into memory.
*/
fun <R> asSequence(@Language("SQL") sql: String,
parameters: Map<String, Any?> = mapOf(),
options: StatementOptions = defaultOptions,
f: (Sequence<Row>) -> R): R
/**
* Executes a query, invoking the supplied function for each row returned.
* This is suitable for handling large result sets without loading them into memory.
*/
fun forEach(@Language("SQL") sql: String,
parameters: Map<String, Any?> = mapOf(),
options: StatementOptions = defaultOptions,
f: (Row) -> Unit): Unit
/**
* Binds parameters into a static SQL string.
*
* This can be used for logging, or (in the future) for direct execution bypassing prepared statements.
*
* Be careful not to introduce SQL injections if binding strings. The dialect will attempt to escape
* strings so they are safe, but it is probably not reliable for untrusted strings.
*/
fun bindParameters(@Language("SQL") sql: String,
parameters: Map<String, Any?>,
closeParameters: Boolean = true,
limit: Int = -1,
consumeStreams: Boolean = true): String
/**
* Starts a transaction for the lifetime of the supplied function.
* The transaction will be committed automatically unless an exception is thrown or `transaction.rollbackOnly`
* is set to true
*/
fun <R> transaction(f: (Transaction) -> R): R
/**
* Starts a transaction, allowing manual control over whether the transaction is committed or rolled back.
* The use of this method is discouraged and is intended for use by framework code - use the `transaction`
* method instead where possible.
*/
fun manualTransaction(): ManualTransaction
}
| mit |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/components/IconButton.kt | 1 | 244 | package eu.kanade.presentation.components
import androidx.compose.ui.unit.dp
/**
* Exposing some internal tokens.
*
* @see androidx.compose.material3.tokens.IconButtonTokens
*/
object IconButtonTokens {
val StateLayerSize = 40.0.dp
}
| apache-2.0 |
exponentjs/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/sensors/modules/GyroscopeModule.kt | 2 | 1779 | // Copyright 2015-present 650 Industries. All rights reserved.
package abi44_0_0.expo.modules.sensors.modules
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorManager
import android.os.Bundle
import abi44_0_0.expo.modules.interfaces.sensors.SensorServiceInterface
import abi44_0_0.expo.modules.interfaces.sensors.services.GyroscopeServiceInterface
import abi44_0_0.expo.modules.core.Promise
import abi44_0_0.expo.modules.core.interfaces.ExpoMethod
class GyroscopeModule(reactContext: Context?) : BaseSensorModule(reactContext) {
override val eventName: String = "gyroscopeDidUpdate"
override fun getName(): String = "ExponentGyroscope"
override fun getSensorService(): SensorServiceInterface {
return moduleRegistry.getModule(GyroscopeServiceInterface::class.java)
}
override fun eventToMap(sensorEvent: SensorEvent): Bundle {
return Bundle().apply {
putDouble("x", sensorEvent.values[0].toDouble())
putDouble("y", sensorEvent.values[1].toDouble())
putDouble("z", sensorEvent.values[2].toDouble())
}
}
@ExpoMethod
fun startObserving(promise: Promise) {
super.startObserving()
promise.resolve(null)
}
@ExpoMethod
fun stopObserving(promise: Promise) {
super.stopObserving()
promise.resolve(null)
}
@ExpoMethod
fun setUpdateInterval(updateInterval: Int, promise: Promise) {
super.setUpdateInterval(updateInterval)
promise.resolve(null)
}
@ExpoMethod
fun isAvailableAsync(promise: Promise) {
val mSensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
val isAvailable = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) != null
promise.resolve(isAvailable)
}
}
| bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.