repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
eyesniper2/skRayFall | src/main/java/net/rayfall/eyesniper2/skrayfall/VersionedGeneralSyntaxManager.kt | 1 | 25091 | package net.rayfall.eyesniper2.skrayfall
import ch.njol.skript.Skript
import ch.njol.skript.lang.ExpressionType
import ch.njol.skript.lang.util.SimpleEvent
import ch.njol.skript.registrations.EventValues
import ch.njol.skript.util.Getter
import ch.njol.skript.util.Version
import net.rayfall.eyesniper2.skrayfall.bossbar.*
import net.rayfall.eyesniper2.skrayfall.general.conditions.CondIsGlowing
import net.rayfall.eyesniper2.skrayfall.general.effects.EffMakePlayerGlow
import net.rayfall.eyesniper2.skrayfall.general.effects.EffUnglowPlayer
import net.rayfall.eyesniper2.skrayfall.general.events.ArmorStandDamageEvent
import net.rayfall.eyesniper2.skrayfall.general.events.ArmorStandListener
import net.rayfall.eyesniper2.skrayfall.general.expressions.ExprNoNbt
import net.rayfall.eyesniper2.skrayfall.general.expressions.ExprRayfallOffhand
import net.rayfall.eyesniper2.skrayfall.general.expressions.ExprShinyItem
import net.rayfall.eyesniper2.skrayfall.v1_10.EffActionBarV1_10
import net.rayfall.eyesniper2.skrayfall.v1_10.EffParticlesV1_10
import net.rayfall.eyesniper2.skrayfall.v1_10.EffTabTitlesV1_10
import net.rayfall.eyesniper2.skrayfall.v1_10.EffTitleV1_10
import net.rayfall.eyesniper2.skrayfall.v1_11.EffActionBarV1_11
import net.rayfall.eyesniper2.skrayfall.v1_11.EffParticlesV1_11
import net.rayfall.eyesniper2.skrayfall.v1_11.EffTabTitlesV1_11
import net.rayfall.eyesniper2.skrayfall.v1_11.EffTitleV1_11
import net.rayfall.eyesniper2.skrayfall.v1_12.EffActionBarV1_12
import net.rayfall.eyesniper2.skrayfall.v1_12.EffParticlesV1_12
import net.rayfall.eyesniper2.skrayfall.v1_12.EffTabTitlesV1_12
import net.rayfall.eyesniper2.skrayfall.v1_12.EffTitleV1_12
import net.rayfall.eyesniper2.skrayfall.v1_13.EffActionBarV1_13
import net.rayfall.eyesniper2.skrayfall.v1_13.EffParticlesV1_13
import net.rayfall.eyesniper2.skrayfall.v1_13.EffTabTitlesV1_13
import net.rayfall.eyesniper2.skrayfall.v1_13.EffTitleV1_13
import net.rayfall.eyesniper2.skrayfall.v1_13_1.EffActionBarV1_13_1
import net.rayfall.eyesniper2.skrayfall.v1_13_1.EffParticlesV1_13_1
import net.rayfall.eyesniper2.skrayfall.v1_13_1.EffTabTitlesV1_13_1
import net.rayfall.eyesniper2.skrayfall.v1_13_1.EffTitleV1_13_1
import net.rayfall.eyesniper2.skrayfall.v1_14.EffActionBarV1_14
import net.rayfall.eyesniper2.skrayfall.v1_14.EffParticlesV1_14
import net.rayfall.eyesniper2.skrayfall.v1_14.EffTabTitlesV1_14
import net.rayfall.eyesniper2.skrayfall.v1_14.EffTitleV1_14
import net.rayfall.eyesniper2.skrayfall.v1_15.EffActionBarV1_15
import net.rayfall.eyesniper2.skrayfall.v1_15.EffParticlesV1_15
import net.rayfall.eyesniper2.skrayfall.v1_15.EffTabTitlesV1_15
import net.rayfall.eyesniper2.skrayfall.v1_15.EffTitleV1_15
import net.rayfall.eyesniper2.skrayfall.v1_16.EffActionBarV1_16
import net.rayfall.eyesniper2.skrayfall.v1_16.EffParticlesV1_16
import net.rayfall.eyesniper2.skrayfall.v1_16.EffTabTitlesV1_16
import net.rayfall.eyesniper2.skrayfall.v1_16.EffTitleV1_16
import net.rayfall.eyesniper2.skrayfall.v1_16_2.EffActionBarV1_16_2
import net.rayfall.eyesniper2.skrayfall.v1_16_2.EffParticlesV1_16_2
import net.rayfall.eyesniper2.skrayfall.v1_16_2.EffTabTitlesV1_16_2
import net.rayfall.eyesniper2.skrayfall.v1_16_2.EffTitleV1_16_2
import net.rayfall.eyesniper2.skrayfall.v1_16_3.EffActionBarV1_16_3
import net.rayfall.eyesniper2.skrayfall.v1_16_3.EffParticlesV1_16_3
import net.rayfall.eyesniper2.skrayfall.v1_16_3.EffTabTitlesV1_16_3
import net.rayfall.eyesniper2.skrayfall.v1_16_3.EffTitleV1_16_3
import net.rayfall.eyesniper2.skrayfall.v1_17.EffActionBarV1_17
import net.rayfall.eyesniper2.skrayfall.v1_17.EffParticlesV1_17
import net.rayfall.eyesniper2.skrayfall.v1_17.EffTabTitlesV1_17
import net.rayfall.eyesniper2.skrayfall.v1_17.EffTitleV1_17
import net.rayfall.eyesniper2.skrayfall.v1_8.EffActionBarV1_8
import net.rayfall.eyesniper2.skrayfall.v1_8.EffParticlesV1_8
import net.rayfall.eyesniper2.skrayfall.v1_8.EffTabTitlesV1_8
import net.rayfall.eyesniper2.skrayfall.v1_8.EffTitleV1_8
import net.rayfall.eyesniper2.skrayfall.v1_8_3.EffActionBarV1_8_3
import net.rayfall.eyesniper2.skrayfall.v1_8_3.EffParticlesV1_8_3
import net.rayfall.eyesniper2.skrayfall.v1_8_3.EffTabTitlesV1_8_3
import net.rayfall.eyesniper2.skrayfall.v1_8_3.EffTitleV1_8_3
import net.rayfall.eyesniper2.skrayfall.v1_8_4.EffActionBarV1_8_4
import net.rayfall.eyesniper2.skrayfall.v1_8_4.EffParticlesV1_8_4
import net.rayfall.eyesniper2.skrayfall.v1_8_4.EffTabTitlesV1_8_4
import net.rayfall.eyesniper2.skrayfall.v1_8_4.EffTitleV1_8_4
import net.rayfall.eyesniper2.skrayfall.v1_9.EffActionBarV1_9
import net.rayfall.eyesniper2.skrayfall.v1_9.EffParticlesV1_9
import net.rayfall.eyesniper2.skrayfall.v1_9.EffTabTitlesV1_9
import net.rayfall.eyesniper2.skrayfall.v1_9.EffTitleV1_9
import net.rayfall.eyesniper2.skrayfall.v1_9_4.EffActionBarV1_9_4
import net.rayfall.eyesniper2.skrayfall.v1_9_4.EffParticlesV1_9_4
import net.rayfall.eyesniper2.skrayfall.v1_9_4.EffTabTitlesV1_9_4
import net.rayfall.eyesniper2.skrayfall.v1_9_4.EffTitleV1_9_4
import org.bukkit.entity.Entity
import org.bukkit.entity.Player
import org.bukkit.inventory.ItemStack
import org.bukkit.plugin.Plugin
import org.eclipse.jdt.annotation.Nullable
class VersionedGeneralSyntaxManager(val plugin: Plugin) : SyntaxManagerInterface {
val bossbarManager: BossBarManager = BossBarManager()
override fun registerSyntax() {
if (Skript.isRunningMinecraft(1, 8)) {
plugin.logger.info("Enabling general 1.8+ bacon!")
Skript.registerExpression(ExprShinyItem::class.java, ItemStack::class.java, ExpressionType.PROPERTY,
"shiny %itemstacks%")
Skript.registerExpression(ExprNoNbt::class.java, ItemStack::class.java, ExpressionType.PROPERTY,
"%itemstacks% with no nbt")
ArmorStandListener(plugin)
Skript.registerEvent("armorstand damage", SimpleEvent::class.java, ArmorStandDamageEvent::class.java,
"armo[u]r stand damage")
EventValues.registerEventValue(ArmorStandDamageEvent::class.java, Entity::class.java,
object : Getter<Entity, ArmorStandDamageEvent>() {
@Nullable
override fun get(evt: ArmorStandDamageEvent): Entity {
return evt.armorStand
}
}, 0)
EventValues.registerEventValue(ArmorStandDamageEvent::class.java, Player::class.java,
object : Getter<Player, ArmorStandDamageEvent>() {
@Nullable
override fun get(evt: ArmorStandDamageEvent): Player {
return evt.damager
}
}, 0)
}
if (Skript.getMinecraftVersion().compareTo(Version(1, 8)) == 0) {
plugin.logger.info("Getting all the special 1.8 bacon!")
Skript.registerEffect(EffTitleV1_8::class.java,
"send %players% title %string% [with subtitle %-string%] [for %-timespan%] " + "[with %-timespan% fade in and %-timespan% fade out]")
Skript.registerEffect(EffParticlesV1_8::class.java,
"show %number% %string% particle[s] at %location% for %player% " + "[offset by %number%, %number%( and|,) %number%]")
Skript.registerEffect(EffActionBarV1_8::class.java, "set action bar of %players% to %string%",
"set %player%['s] action bar to %string%")
Skript.registerEffect(EffTabTitlesV1_8::class.java,
"set tab header to %string% and footer to %string% for %player%")
}
if (Skript.getMinecraftVersion().compareTo(Version(1, 8, 3)) == 0) {
plugin.logger.info("Getting the extra special 1.8.3 bacon!")
Skript.registerEffect(EffTitleV1_8_3::class.java,
"send %players% title %string% [with subtitle %-string%] [for %-timespan%] " + "[with %-timespan% fade in and %-timespan% fade out]")
Skript.registerEffect(EffParticlesV1_8_3::class.java,
"show %number% %string% particle[s] at %location% for %player% " + "[offset by %number%, %number%( and|,) %number%]")
Skript.registerEffect(EffActionBarV1_8_3::class.java, "set action bar of %players% to %string%",
"set %player%['s] action bar to %string%")
Skript.registerEffect(EffTabTitlesV1_8_3::class.java,
"set tab header to %string% and footer to %string% for %player%")
}
if (Skript.getMinecraftVersion() >= Version(1, 8, 4) && Skript.getMinecraftVersion() <= Version(1, 8, 8)) {
plugin.logger.info("Getting the extra special 1.8.4 - 1.8.8 bacon!")
Skript.registerEffect(EffTitleV1_8_4::class.java,
"send %players% title %string% [with subtitle %-string%] [for %-timespan%] " + "[with %-timespan% fade in and %-timespan% fade out]")
Skript.registerEffect(EffParticlesV1_8_4::class.java,
"show %number% %string% particle[s] at %location% for %player% " + "[offset by %number%, %number%( and|,) %number%]")
Skript.registerEffect(EffActionBarV1_8_4::class.java, "set action bar of %players% to %string%",
"set %player%['s] action bar to %string%")
Skript.registerEffect(EffTabTitlesV1_8_4::class.java,
"set tab header to %string% and footer to %string% for %player%")
}
if (Skript.isRunningMinecraft(1, 9)) {
plugin.logger.info("Getting the general 1.9+ bacon!")
// New bossbar content
Skript.registerEffect(EffCreateModernBossBar::class.java,
"create (bossbar|boss bar) title[d] %string% and id %string% for %players% "
+ "[with (value|progress) %number%] [with colors %-bossbarcolor%] "
+ "[with style %-bossbarstyle%] [with flags %-bossbarflag%]")
Skript.registerEffect(EffDeleteModernBossBar::class.java, "(remove|destroy) bossbar %string%")
Skript.registerEffect(EffRemovePlayerFromBossBar::class.java,
"remove %players% [from] bossbar %string%")
Skript.registerEffect(EffSetBossBar::class.java,
"(add|set) bossbar %string% for %player% ",
"(add|give) %players% [to] bossbar %string%")
Skript.registerEffect(EffChangeBossBarValue::class.java,
"(set|edit) bossbar %string% (value|progress) to %number%")
Skript.registerEffect(EffChangeBossBarColor::class.java,
"(set|edit) bossbar %string% colo[u]r to %bossbarcolor%")
Skript.registerEffect(EffChangeBossBarTitle::class.java,
"(set|edit) bossbar %string% (title|name) to %string%")
Skript.registerEffect(EffChangeBossBarStyle::class.java,
"(set|edit) bossbar %string% style to %bossbarstyle%")
Skript.registerEffect(EffBossBarAddFlag::class.java,
"(add|set) [a] [the] flag %bossbarflag% to [the] bossbar %string%")
Skript.registerEffect(EffBossBarRemoveFlag::class.java,
"(remove|delete) [a] [the] flag %bossbarflag% [to] [from] [the] bossbar %string%")
Skript.registerEffect(EffBossBarShow::class.java, "(show|display|unhide) bossbar %string%")
Skript.registerEffect(EffBossBarHide::class.java, "hide bossbar %string%")
Skript.registerExpression(ExprBossBarTitle::class.java, String::class.java, ExpressionType.SIMPLE,
"(title|name) of bossbar %string%")
Skript.registerExpression(ExprBossBarValue::class.java, Number::class.java, ExpressionType.SIMPLE,
"(value|progress) of bossbar %string%")
// Glowing API
Skript.registerEffect(EffMakePlayerGlow::class.java, "make %player% glow")
Skript.registerEffect(EffUnglowPlayer::class.java, "make %player% (unglow|stop glowing)")
Skript.registerCondition(CondIsGlowing::class.java,"%player% glowing")
// 1.9.2 Team stuff
// Skript.registerEffect(Eff1_9MessageOnDeathRule.class,
// "(show|display) death message[s] %teamoptionstatus% for team %string%");
// Skript.registerEffect(Eff1_9NameTagVisibility.class,
// "(show|display) (name tags|nametags) %teamoptionstatus% for team %string%");
// Skript.registerEffect(Eff1_9TeamCollisionRule.class,
// "(set|define) team collision [rule] as %teamoptionstatus% for team %string%");
Skript.registerExpression(ExprRayfallOffhand::class.java, ItemStack::class.java, ExpressionType.SIMPLE,
"%player%['s] offhand", "item in %player%['s] offhand")
}
if (Skript.getMinecraftVersion() >= Version(1, 9, 0) && Skript.getMinecraftVersion() <= Version(1, 9, 3)) {
plugin.logger.info("Getting the extra special 1.9 - 1.9.3 bacon!")
Skript.registerEffect(EffTitleV1_9::class.java,
"send %players% title %string% [with subtitle %-string%] [for %-timespan%] " + "[with %-timespan% fade in and %-timespan% fade out]")
Skript.registerEffect(EffParticlesV1_9::class.java,
"show %number% %string% particle[s] at %location% for %player% " + "[offset by %number%, %number%( and|,) %number%]")
Skript.registerEffect(EffActionBarV1_9::class.java, "set action bar of %players% to %string%",
"set %player%['s] action bar to %string%")
Skript.registerEffect(EffTabTitlesV1_9::class.java,
"set tab header to %string% and footer to %string% for %player%")
}
if (Skript.getMinecraftVersion().compareTo(Version(1, 9, 4)) == 0) {
plugin.logger.info("Getting the extra special 1.9.4 bacon!")
Skript.registerEffect(EffTitleV1_9_4::class.java,
"send %players% title %string% [with subtitle %-string%] [for %-timespan%] " + "[with %-timespan% fade in and %-timespan% fade out]")
Skript.registerEffect(EffParticlesV1_9_4::class.java,
"show %number% %string% particle[s] at %location% for %player% " + "[offset by %number%, %number%( and|,) %number%]")
Skript.registerEffect(EffActionBarV1_9_4::class.java, "set action bar of %players% to %string%",
"set %player%['s] action bar to %string%")
Skript.registerEffect(EffTabTitlesV1_9_4::class.java,
"set tab header to %string% and footer to %string% for %player%")
}
if (Skript.getMinecraftVersion() >= Version(1, 10, 0) && Skript.getMinecraftVersion() <= Version(1, 10, 3)) {
plugin.logger.info("Getting the extra special 1.10 - 1.10.2 bacon!")
Skript.registerEffect(EffTitleV1_10::class.java,
"send %players% title %string% [with subtitle %-string%] [for %-timespan%] " + "[with %-timespan% fade in and %-timespan% fade out]")
Skript.registerEffect(EffParticlesV1_10::class.java,
"show %number% %string% particle[s] at %location% for %player% " + "[offset by %number%, %number%( and|,) %number%]")
Skript.registerEffect(EffActionBarV1_10::class.java, "set action bar of %players% to %string%",
"set %player%['s] action bar to %string%")
Skript.registerEffect(EffTabTitlesV1_10::class.java,
"set tab header to %string% and footer to %string% for %player%")
}
if (Skript.getMinecraftVersion() >= Version(1, 11, 0) && Skript.getMinecraftVersion() < Version(1, 12, 0)) {
plugin.logger.info("Getting the extra special 1.11 bacon!")
Skript.registerEffect(EffTitleV1_11::class.java,
"send %players% title %string% [with subtitle %-string%] [for %-timespan%] " + "[with %-timespan% fade in and %-timespan% fade out]")
Skript.registerEffect(EffParticlesV1_11::class.java,
"show %number% %string% particle[s] at %location% for %player% " + "[offset by %number%, %number%( and|,) %number%]")
Skript.registerEffect(EffActionBarV1_11::class.java, "set action bar of %players% to %string%",
"set %player%['s] action bar to %string%")
Skript.registerEffect(EffTabTitlesV1_11::class.java,
"set tab header to %string% and footer to %string% for %player%")
}
if (Skript.getMinecraftVersion() >= Version(1, 12, 0) && Skript.getMinecraftVersion() < Version(1, 13, 0)) {
plugin.logger.info("Getting the extra special 1.12 bacon!")
Skript.registerEffect(EffTitleV1_12::class.java,
"send %players% title %string% [with subtitle %-string%] [for %-timespan%] " + "[with %-timespan% fade in and %-timespan% fade out]")
Skript.registerEffect(EffParticlesV1_12::class.java,
"show %number% %string% particle[s] at %location% for %player% " + "[offset by %number%, %number%( and|,) %number%]")
Skript.registerEffect(EffActionBarV1_12::class.java, "set action bar of %players% to %string%",
"set %player%['s] action bar to %string%")
Skript.registerEffect(EffTabTitlesV1_12::class.java,
"set tab header to %string% and footer to %string% for %player%")
}
if (Skript.getMinecraftVersion() >= Version(1, 13, 0) && Skript.getMinecraftVersion() < Version(1, 13, 1)) {
plugin.logger.info("Getting the extra special 1.13 bacon!")
Skript.registerEffect(EffTitleV1_13::class.java,
"send %players% title %string% [with subtitle %-string%] [for %-timespan%] " + "[with %-timespan% fade in and %-timespan% fade out]")
Skript.registerEffect(EffParticlesV1_13::class.java,
"show %number% %string% particle[s] at %location% for %player% " + "[offset by %number%, %number%( and|,) %number%]")
Skript.registerEffect(EffActionBarV1_13::class.java, "set action bar of %players% to %string%",
"set %player%['s] action bar to %string%")
Skript.registerEffect(EffTabTitlesV1_13::class.java,
"set tab header to %string% and footer to %string% for %player%")
}
if (Skript.getMinecraftVersion() >= Version(1, 13, 1) && Skript.getMinecraftVersion() < Version(1, 14)) {
plugin.logger.info("Getting the extra special 1.13.1 bacon!")
Skript.registerEffect(EffTitleV1_13_1::class.java,
"send %players% title %string% [with subtitle %-string%] [for %-timespan%] " + "[with %-timespan% fade in and %-timespan% fade out]")
Skript.registerEffect(EffParticlesV1_13_1::class.java,
"show %number% %string% particle[s] at %location% for %player% " + "[offset by %number%, %number%( and|,) %number%]")
Skript.registerEffect(EffActionBarV1_13_1::class.java, "set action bar of %players% to %string%",
"set %player%['s] action bar to %string%")
Skript.registerEffect(EffTabTitlesV1_13_1::class.java,
"set tab header to %string% and footer to %string% for %player%")
}
if (Skript.getMinecraftVersion() >= Version(1, 14, 0) && Skript.getMinecraftVersion() < Version(1, 14, 5)) {
plugin.logger.info("Getting the extra special 1.14 - 1.14.4 bacon!")
Skript.registerEffect(EffTitleV1_14::class.java,
"send %players% title %string% [with subtitle %-string%] [for %-timespan%] " + "[with %-timespan% fade in and %-timespan% fade out]")
Skript.registerEffect(EffParticlesV1_14::class.java,
"show %number% %string% particle[s] at %location% for %player% " + "[offset by %number%, %number%( and|,) %number%]")
Skript.registerEffect(EffActionBarV1_14::class.java, "set action bar of %players% to %string%",
"set %player%['s] action bar to %string%")
Skript.registerEffect(EffTabTitlesV1_14::class.java,
"set tab header to %string% and footer to %string% for %player%")
}
if (Skript.getMinecraftVersion() >= Version(1, 15, 0) && Skript.getMinecraftVersion() < Version(1, 15, 3)) {
plugin.logger.info("Getting the extra special 1.15 - 1.15.2 bacon!")
Skript.registerEffect(EffTitleV1_15::class.java,
"send %players% title %string% [with subtitle %-string%] [for %-timespan%] " + "[with %-timespan% fade in and %-timespan% fade out]")
Skript.registerEffect(EffParticlesV1_15::class.java,
"show %number% %string% particle[s] at %location% for %player% " + "[offset by %number%, %number%( and|,) %number%]")
Skript.registerEffect(EffActionBarV1_15::class.java, "set action bar of %players% to %string%",
"set %player%['s] action bar to %string%")
Skript.registerEffect(EffTabTitlesV1_15::class.java,
"set tab header to %string% and footer to %string% for %player%")
}
if (Skript.getMinecraftVersion() >= Version(1, 16, 0) && Skript.getMinecraftVersion() < Version(1, 16, 2)) {
plugin.logger.info("Getting the extra special 1.16 - 1.16.2 bacon!")
Skript.registerEffect(EffTitleV1_16::class.java,
"send %players% title %string% [with subtitle %-string%] [for %-timespan%] " + "[with %-timespan% fade in and %-timespan% fade out]")
Skript.registerEffect(EffParticlesV1_16::class.java,
"show %number% %string% particle[s] at %location% for %player% " + "[offset by %number%, %number%( and|,) %number%]")
Skript.registerEffect(EffActionBarV1_16::class.java, "set action bar of %players% to %string%",
"set %player%['s] action bar to %string%")
Skript.registerEffect(EffTabTitlesV1_16::class.java,
"set tab header to %string% and footer to %string% for %player%")
}
if (Skript.getMinecraftVersion() >= Version(1, 16, 2) && Skript.getMinecraftVersion() < Version(1, 16, 4)) {
plugin.logger.info("Getting the extra special 1.16.2 - 1.16.4 bacon!")
Skript.registerEffect(EffTitleV1_16_2::class.java,
"send %players% title %string% [with subtitle %-string%] [for %-timespan%] " + "[with %-timespan% fade in and %-timespan% fade out]")
Skript.registerEffect(EffParticlesV1_16_2::class.java,
"show %number% %string% particle[s] at %location% for %player% " + "[offset by %number%, %number%( and|,) %number%]")
Skript.registerEffect(EffActionBarV1_16_2::class.java, "set action bar of %players% to %string%",
"set %player%['s] action bar to %string%")
Skript.registerEffect(EffTabTitlesV1_16_2::class.java,
"set tab header to %string% and footer to %string% for %player%")
}
if (Skript.getMinecraftVersion() >= Version(1, 16, 4) && Skript.getMinecraftVersion() < Version(1, 16, 6)) {
plugin.logger.info("Getting the extra special 1.16.4 bacon!")
Skript.registerEffect(EffTitleV1_16_3::class.java,
"send %players% title %string% [with subtitle %-string%] [for %-timespan%] " + "[with %-timespan% fade in and %-timespan% fade out]")
Skript.registerEffect(EffParticlesV1_16_3::class.java,
"show %number% %string% particle[s] at %location% for %player% " + "[offset by %number%, %number%( and|,) %number%]")
Skript.registerEffect(EffActionBarV1_16_3::class.java, "set action bar of %players% to %string%",
"set %player%['s] action bar to %string%")
Skript.registerEffect(EffTabTitlesV1_16_3::class.java,
"set tab header to %string% and footer to %string% for %player%")
}
if (Skript.getMinecraftVersion() >= Version(1, 17, 0)) {
plugin.logger.info("Getting the extra special 1.17+ bacon!")
Skript.registerEffect(EffTitleV1_17::class.java,
"send %players% title %string% [with subtitle %-string%] [for %-timespan%] " + "[with %-timespan% fade in and %-timespan% fade out]")
Skript.registerEffect(EffParticlesV1_17::class.java,
"show %number% %string% particle[s] at %location% for %player% " + "[offset by %number%, %number%( and|,) %number%]")
Skript.registerEffect(EffActionBarV1_17::class.java, "set action bar of %players% to %string%",
"set %player%['s] action bar to %string%")
Skript.registerEffect(EffTabTitlesV1_17::class.java,
"set tab header to %string% and footer to %string% for %player%")
}
}
} | gpl-3.0 | 44e3f0bfa6946f71535be6f8fc098608 | 73.017699 | 153 | 0.646965 | 3.4156 | false | false | false | false |
androidx/androidx | health/health-services-client/src/main/java/androidx/health/services/client/data/ExerciseEndReason.kt | 3 | 4657 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.health.services.client.data
import androidx.annotation.IntDef
import androidx.health.services.client.proto.DataProto
import androidx.health.services.client.ExerciseClient
import kotlin.annotation.AnnotationRetention.SOURCE
/**
* The reason why an exercise has been ended for [ExerciseState] used in [ExerciseStateInfo].
*
* @hide
*/
@Retention(SOURCE)
@IntDef(
ExerciseEndReason.UNKNOWN,
ExerciseEndReason.AUTO_END_PERMISSION_LOST,
ExerciseEndReason.AUTO_END_PAUSE_EXPIRED,
ExerciseEndReason.AUTO_END_MISSING_LISTENER,
ExerciseEndReason.USER_END,
ExerciseEndReason.AUTO_END_SUPERSEDED,
ExerciseEndReason.AUTO_END_PREPARE_EXPIRED
)
public annotation class ExerciseEndReason {
public companion object {
/** The exercise has been ended, but the end reason is not known or has not been set. */
public const val UNKNOWN: Int = 0
/**
* The exercise has been automatically ended due to lack of client's permissions to receive
* data for the exercise.
*/
public const val AUTO_END_PERMISSION_LOST: Int = 1
/** The exercise has been automatically ended due to being paused for too long. */
public const val AUTO_END_PAUSE_EXPIRED: Int = 2
/**
* The exercise being automatically ended, due to a lack of exercise updates being received
* by the user.
*/
public const val AUTO_END_MISSING_LISTENER: Int = 3
/** The exercise has been ended by a direct call to [ExerciseClient.endExerciseAsync]. */
public const val USER_END: Int = 4
/**
* The exercise has been ended because it was superseded by a new exercise being started by
* another client.
*/
public const val AUTO_END_SUPERSEDED: Int = 5
/** The exercise has been ended due to being in PREPARE state for too long. */
public const val AUTO_END_PREPARE_EXPIRED: Int = 6
internal fun @receiver:ExerciseEndReason Int.toProto(): DataProto.ExerciseEndReason =
when (this) {
UNKNOWN -> DataProto.ExerciseEndReason.EXERCISE_END_REASON_UNKNOWN
AUTO_END_PERMISSION_LOST ->
DataProto.ExerciseEndReason.EXERCISE_END_REASON_AUTO_END_PERMISSION_LOST
AUTO_END_PAUSE_EXPIRED ->
DataProto.ExerciseEndReason.EXERCISE_END_REASON_AUTO_END_PAUSE_EXPIRED
AUTO_END_MISSING_LISTENER ->
DataProto.ExerciseEndReason.EXERCISE_END_REASON_AUTO_END_MISSING_LISTENER
USER_END -> DataProto.ExerciseEndReason.EXERCISE_END_REASON_USER_END
AUTO_END_SUPERSEDED ->
DataProto.ExerciseEndReason.EXERCISE_END_REASON_AUTO_END_SUPERSEDED
AUTO_END_PREPARE_EXPIRED ->
DataProto.ExerciseEndReason.EXERCISE_END_REASON_AUTO_END_PREPARE_EXPIRED
else -> DataProto.ExerciseEndReason.EXERCISE_END_REASON_UNKNOWN
}
/** @hide */
@ExerciseEndReason
internal fun fromProto(proto: DataProto.ExerciseEndReason): Int =
when (proto) {
DataProto.ExerciseEndReason.EXERCISE_END_REASON_UNKNOWN -> UNKNOWN
DataProto.ExerciseEndReason.EXERCISE_END_REASON_AUTO_END_PERMISSION_LOST ->
AUTO_END_PERMISSION_LOST
DataProto.ExerciseEndReason.EXERCISE_END_REASON_AUTO_END_PAUSE_EXPIRED ->
AUTO_END_PAUSE_EXPIRED
DataProto.ExerciseEndReason.EXERCISE_END_REASON_AUTO_END_MISSING_LISTENER ->
AUTO_END_MISSING_LISTENER
DataProto.ExerciseEndReason.EXERCISE_END_REASON_USER_END -> USER_END
DataProto.ExerciseEndReason.EXERCISE_END_REASON_AUTO_END_SUPERSEDED ->
AUTO_END_SUPERSEDED
DataProto.ExerciseEndReason.EXERCISE_END_REASON_AUTO_END_PREPARE_EXPIRED ->
AUTO_END_PREPARE_EXPIRED
}
}
}
| apache-2.0 | 49c187acd0a4fff39c2950a480eadb5a | 42.523364 | 99 | 0.662658 | 4.482194 | false | false | false | false |
androidx/androidx | compose/runtime/runtime/src/jvmTest/kotlin/androidx/compose/runtime/LiveEditTests.kt | 3 | 17298 | /*
* 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.
*/
package androidx.compose.runtime
import androidx.compose.runtime.mock.Text
import androidx.compose.runtime.mock.compositionTest
import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Ignore
import org.junit.Test
class LiveEditTests {
@Before
fun setUp() {
Recomposer.setHotReloadEnabled(true)
}
@After
fun tearDown() {
clearCompositionErrors()
Recomposer.setHotReloadEnabled(false)
}
@Test
fun testRestartableFunctionPreservesParentAndSiblingState() = liveEditTest {
EnsureStatePreservedAndNotRecomposed("a")
RestartGroup {
Text("Hello World")
EnsureStatePreservedAndNotRecomposed("b")
Target("c")
}
}
// TODO: This should pass but doesn't. Need to investigate why.
@Ignore
fun testNonRestartableTargetAtRootScope() = liveEditTest {
Target("b", restartable = false)
}
@Test
fun testTargetSiblings() = liveEditTest {
Target("a")
Target("b")
}
@Test
fun testMultipleFunctionPreservesParentAndSiblingState() = liveEditTest {
EnsureStatePreservedAndNotRecomposed("a")
Target("b")
RestartGroup {
Text("Hello World")
EnsureStatePreservedAndNotRecomposed("c")
Target("d")
Target("e")
}
Target("f")
}
@Test
fun testChildGroupStateIsDestroyed() = liveEditTest {
EnsureStatePreservedAndNotRecomposed("a")
RestartGroup {
Text("Hello World")
EnsureStatePreservedAndNotRecomposed("b")
Target("c") {
Text("Hello World")
EnsureStateLost("d")
}
}
}
@Test
fun testTargetWithinTarget() = liveEditTest {
EnsureStatePreservedAndNotRecomposed("a")
RestartGroup {
Text("Hello World")
EnsureStatePreservedAndNotRecomposed("b")
Target("c") {
Text("Hello World")
EnsureStateLost("d")
RestartGroup {
MarkAsTarget()
}
}
}
}
@Test
fun testNonRestartableFunctionPreservesParentAndSiblingState() = liveEditTest {
EnsureStatePreservedButRecomposed("a")
RestartGroup {
Text("Hello World")
EnsureStatePreservedButRecomposed("b")
Target("c", restartable = false)
}
}
@Test
fun testMultipleNonRestartableFunctionPreservesParentAndSiblingState() = liveEditTest {
RestartGroup {
EnsureStatePreservedButRecomposed("a")
Target("b", restartable = false)
RestartGroup {
Text("Hello World")
EnsureStatePreservedButRecomposed("c")
Target("d", restartable = false)
Target("e", restartable = false)
}
Target("f", restartable = false)
}
}
@Test
fun testLambda() = liveEditTest {
RestartGroup {
MarkAsTarget()
EnsureStateLost("a")
Text("Hello World")
}
}
@Test
fun testInlineComposableLambda() = liveEditTest {
RestartGroup {
InlineTarget("a")
EnsureStatePreservedButRecomposed("b")
Text("Hello World")
}
}
@Test
fun testThrowing_initialComposition() = liveEditTest {
RestartGroup {
MarkAsTarget()
// Fail once per each reload
expectError("throwInCompose", 2)
// Composed once - failed once
Expect(
"throw",
compose = 2,
onRememberd = 0,
onForgotten = 0,
onAbandoned = 2
)
error("throwInCompose")
}
}
@Test
fun testThrowing_recomposition() {
var recomposeCount = 0
liveEditTest(reloadCount = 2) {
RestartGroup {
MarkAsTarget()
// only failed on 2nd recomposition
expectError("throwInCompose", 1)
// Composed 3 times, failed once
Expect(
"throw",
compose = 3,
onRememberd = 2,
onForgotten = 1,
onAbandoned = 1
)
recomposeCount++
if (recomposeCount == 2) {
error("throwInCompose")
}
}
}
}
@Test
fun testThrowing_initialComposition_sideEffect() {
liveEditTest {
RestartGroup {
MarkAsTarget()
// The error is not recoverable, so reload doesn't fix the error
expectError("throwInEffect", 1)
// Composition happens as usual
Expect(
"a",
compose = 1,
onRememberd = 1,
onForgotten = 0,
onAbandoned = 0,
)
SideEffect {
error("throwInEffect")
}
}
}
}
@Test
fun testThrowing_recomposition_sideEffect() {
var recomposeCount = 0
liveEditTest {
RestartGroup {
MarkAsTarget()
// The error is not recoverable, so reload doesn't fix the error
expectError("throwInEffect", 1)
// Composition happens as usual
Expect(
"a",
compose = 2,
onRememberd = 2,
onForgotten = 1,
onAbandoned = 0,
)
recomposeCount++
SideEffect {
if (recomposeCount == 2) {
error("throwInEffect")
}
}
}
}
}
@Test
fun testThrowing_initialComposition_remembered() {
liveEditTest {
RestartGroup {
MarkAsTarget()
// The error is not recoverable, so reload doesn't fix the error
expectError("throwOnRemember", 1)
// remembers as usual
Expect(
"a",
compose = 1,
onRememberd = 1,
onForgotten = 0,
onAbandoned = 0,
)
remember {
object : RememberObserver {
override fun onRemembered() {
error("throwOnRemember")
}
override fun onForgotten() {}
override fun onAbandoned() {}
}
}
// The rest of remembers fail
Expect(
"b",
compose = 1,
onRememberd = 0,
onForgotten = 0,
onAbandoned = 1,
)
}
}
}
@Test
fun testThrowing_recomposition_remembered() {
var recomposeCount = 0
liveEditTest {
RestartGroup {
MarkAsTarget()
// The error is not recoverable, so reload doesn't fix the error
expectError("throwOnRemember", 1)
recomposeCount++
// remembers as usual
Expect(
"a",
compose = 2,
onRememberd = 2,
onForgotten = 1,
onAbandoned = 0,
)
remember {
object : RememberObserver {
override fun onRemembered() {
if (recomposeCount == 2) {
error("throwOnRemember")
}
}
override fun onForgotten() {}
override fun onAbandoned() {}
}
}
// The rest of remembers fail
Expect(
"b",
compose = 2,
onRememberd = 1,
// todo: ensure forgotten is not dispatched for abandons?
onForgotten = 1,
onAbandoned = 1,
)
}
}
}
@Test
fun testThrowing_invalidationsCarriedAfterCrash() {
var recomposeCount = 0
val state = mutableStateOf(0)
liveEditTest(reloadCount = 2) {
RestartGroup {
RestartGroup {
MarkAsTarget()
// Only error the first time
expectError("throwInComposition", 1)
if (recomposeCount == 0) {
// invalidate sibling group below in first composition
state.value += 1
}
if (recomposeCount++ == 1) {
// crash after first reload
error("throwInComposition")
}
}
}
RestartGroup {
// read state
state.value
// composed initially + invalidated by crashed composition
Expect(
"state",
compose = 2,
onRememberd = 1,
onForgotten = 0,
onAbandoned = 0
)
}
}
}
@Test
fun testThrowing_movableContent() {
liveEditTest {
RestartGroup {
MarkAsTarget()
expectError("throwInMovableContent", 2)
val content = remember {
movableContentOf {
error("throwInMovableContent")
}
}
content()
}
}
}
@Test
fun testThrowing_movableContent_recomposition() {
var recomposeCount = 0
liveEditTest(reloadCount = 2) {
RestartGroup {
MarkAsTarget()
expectError("throwInMovableContent", 1)
val content = remember {
movableContentOf {
Expect(
"movable",
compose = 3,
onRememberd = 2,
onForgotten = 1,
onAbandoned = 1
)
if (recomposeCount == 1) {
error("throwInMovableContent")
}
}
}
content()
recomposeCount++
}
}
}
@Test
fun testThrowing_movableContent_throwAfterMove() {
var recomposeCount = 0
liveEditTest(reloadCount = 2) {
expectError("throwInMovableContent", 1)
val content = remember {
movableContentOf {
recomposeCount++
Expect(
"movable",
compose = 4,
onRememberd = 3,
onForgotten = 2,
onAbandoned = 1
)
if (recomposeCount == 1) {
error("throwInMovableContent")
}
}
}
RestartGroup {
MarkAsTarget()
if (recomposeCount == 0) {
content()
}
}
RestartGroup {
MarkAsTarget()
if (recomposeCount > 0) {
content()
}
}
}
}
}
@Composable
@NonRestartableComposable
fun LiveEditTestScope.EnsureStatePreservedButRecomposed(ref: String) {
Expect(
ref,
compose = 2,
onRememberd = 1,
onForgotten = 0,
onAbandoned = 0,
)
}
@Composable
@NonRestartableComposable
fun LiveEditTestScope.EnsureStatePreservedAndNotRecomposed(ref: String) {
Expect(
ref,
compose = 1,
onRememberd = 1,
onForgotten = 0,
onAbandoned = 0,
)
}
@Composable
@NonRestartableComposable
fun LiveEditTestScope.EnsureStateLost(ref: String) {
Expect(
ref,
compose = 2,
onRememberd = 2,
onForgotten = 1,
onAbandoned = 0,
)
}
@Composable
@NonRestartableComposable
fun LiveEditTestScope.Expect(
ref: String,
compose: Int,
onRememberd: Int,
onForgotten: Int,
onAbandoned: Int,
) {
log(ref, "compose")
remember {
object : RememberObserver {
override fun onRemembered() {
log(ref, "onRemembered")
}
override fun onForgotten() {
log(ref, "onForgotten")
}
override fun onAbandoned() {
log(ref, "onAbandoned")
}
}
}
expectLogCount(ref, "compose", compose)
expectLogCount(ref, "onRemembered", onRememberd)
expectLogCount(ref, "onForgotten", onForgotten)
expectLogCount(ref, "onAbandoned", onAbandoned)
}
@Composable fun LiveEditTestScope.Target(
ref: String,
restartable: Boolean = true,
content: @Composable () -> Unit = {}
) {
if (restartable) currentRecomposeScope
MarkAsTarget()
Expect(
ref,
compose = 2,
onRememberd = 2,
onForgotten = 1,
onAbandoned = 0,
)
content()
}
@Composable fun LiveEditTestScope.InlineTarget(
ref: String,
content: @Composable () -> Unit = {}
) {
MarkAsTarget()
Expect(
ref,
compose = 2,
onRememberd = 2,
onForgotten = 1,
onAbandoned = 0,
)
content()
}
@Composable
@ExplicitGroupsComposable
fun LiveEditTestScope.MarkAsTarget() {
addTargetKey((currentComposer as ComposerImpl).parentKey())
}
@OptIn(InternalComposeApi::class)
fun liveEditTest(
reloadCount: Int = 1,
fn: @Composable LiveEditTestScope.() -> Unit,
) = compositionTest {
with(LiveEditTestScope()) {
addCheck {
(composition as? ControlledComposition)?.verifyConsistent()
}
recordErrors {
compose { fn(this) }
}
repeat(reloadCount) {
invalidateTargets()
recordErrors {
advance()
}
}
runChecks()
}
}
@OptIn(InternalComposeApi::class)
private inline fun LiveEditTestScope.recordErrors(
block: () -> Unit
) {
try {
block()
} catch (e: ComposeRuntimeError) {
throw e
} catch (e: Exception) {
addError(e)
}
currentCompositionErrors().forEach {
addError(it.first)
}
}
@Stable
class LiveEditTestScope {
private val targetKeys = mutableSetOf<Int>()
private val checks = mutableListOf<() -> Unit>()
private val errors = mutableSetOf<Exception>()
private val logs = mutableListOf<Pair<String, String>>()
fun invalidateTargets() {
for (key in targetKeys) {
invalidateGroupsWithKey(key)
}
}
fun runChecks() {
for (check in checks) {
check()
}
}
fun addTargetKey(key: Int) {
targetKeys.add(key)
}
fun log(ref: String, msg: String) {
logs.add(ref to msg)
}
fun addError(e: Exception) {
errors.add(e)
}
fun addCheck(check: () -> Unit) {
checks.add(check)
}
fun expectLogCount(ref: String, msg: String, expected: Int) {
addCheck {
val logs = logs.filter { it.first == ref }.map { it.second }.toList()
val actual = logs.filter { m -> m == msg }.count()
Assert.assertEquals(
"Ref '$ref' had an unexpected # of '$msg' logs",
expected,
actual
)
}
}
fun expectError(message: String, count: Int) {
addCheck {
val errors = errors.filter { it.message == message }
Assert.assertEquals(
"Got ${errors.size} errors with $message",
count,
errors.size
)
}
}
}
| apache-2.0 | 7d635e981650a3d91795f86fa04c64d2 | 24.89521 | 91 | 0.475893 | 5.177492 | false | true | false | false |
DSteve595/Put.io | app/src/main/java/com/stevenschoen/putionew/files/FileListAdapter.kt | 1 | 5267 | package com.stevenschoen.putionew.files
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Checkable
import android.widget.ImageView
import android.widget.TextView
import androidx.collection.ArraySet
import androidx.recyclerview.widget.RecyclerView
import com.squareup.picasso.Picasso
import com.stevenschoen.putionew.PutioUtils
import com.stevenschoen.putionew.R
import com.stevenschoen.putionew.model.files.PutioFile
class FileListAdapter(
private val data: List<PutioFile>,
val onFileClicked: (file: PutioFile, holder: FileHolder) -> Unit,
val onFileLongClicked: (file: PutioFile, holder: FileHolder) -> Unit
) : RecyclerView.Adapter<FileListAdapter.FileHolder>() {
private var itemsCheckedChangedListener: OnItemsCheckedChangedListener? = null
val checkedIds = ArraySet<Long>()
init {
setHasStableIds(true)
registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
override fun onChanged() {
super.onChanged()
if (isInCheckMode()) {
val idsToRemove = ArraySet<Long>()
for (checkedId in checkedIds) {
val stillHas = data.any { it.id == checkedId }
if (!stillHas) {
idsToRemove.add(checkedId)
}
}
for (id in idsToRemove) {
checkedIds.remove(id)
notifyItemChanged(getItemPosition(id))
}
if (!idsToRemove.isEmpty() && itemsCheckedChangedListener != null) {
itemsCheckedChangedListener!!.onItemsCheckedChanged()
}
}
}
})
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FileHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.file_putio, parent, false)
return FileHolder(view)
}
override fun onBindViewHolder(holder: FileHolder, position: Int) {
if (holder.itemView is Checkable) {
holder.itemView.isChecked = isPositionChecked(position)
}
val file = data[position]
holder.textName.text = file.name
holder.textDescription.text = PutioUtils.humanReadableByteCount(file.size!!, false)
if (file.isFolder) {
Picasso.get().cancelRequest(holder.iconImg)
holder.iconImg.setImageResource(R.drawable.ic_putio_folder_accent)
} else {
if (!file.icon.isNullOrEmpty()) {
Picasso.get().load(file.icon).into(holder.iconImg)
}
}
if (file.isAccessed) {
holder.iconAccessed.visibility = View.VISIBLE
} else {
holder.iconAccessed.visibility = View.GONE
}
}
override fun getItemId(position: Int): Long {
if (position != -1 && !data.isEmpty()) {
return data[position].id
}
return 0
}
fun getItemPosition(fileId: Long): Int {
for (i in data.indices) {
val file = data[i]
if (file.id == fileId) {
return i
}
}
return -1
}
override fun getItemCount() = data.size
fun isInCheckMode() = checkedIds.isNotEmpty()
fun checkedCount() = checkedIds.size
fun isPositionChecked(position: Int): Boolean {
val itemId = getItemId(position)
return (itemId != -1L) && (checkedIds.contains(itemId))
}
fun getCheckedPositions() = checkedIds.map { getItemPosition(it) }
fun setPositionChecked(position: Int, checked: Boolean) {
val itemId = getItemId(position)
if (checked) {
checkedIds.add(itemId)
} else {
checkedIds.remove(itemId)
}
notifyItemChanged(position)
if (itemsCheckedChangedListener != null) {
itemsCheckedChangedListener!!.onItemsCheckedChanged()
}
}
fun togglePositionChecked(position: Int) {
setPositionChecked(position, !isPositionChecked(position))
}
fun addCheckedIds(vararg ids: Long) {
ids
.filter { checkedIds.add(it) }
.forEach { notifyItemChanged(getItemPosition(it)) }
if (itemsCheckedChangedListener != null) {
itemsCheckedChangedListener!!.onItemsCheckedChanged()
}
}
fun clearChecked() {
if (checkedIds.isNotEmpty()) {
val previouslyCheckedIds = ArraySet<Long>(checkedIds)
checkedIds.clear()
for (id in previouslyCheckedIds) {
notifyItemChanged(getItemPosition(id))
}
if (itemsCheckedChangedListener != null) {
itemsCheckedChangedListener!!.onItemsCheckedChanged()
}
}
}
fun setItemsCheckedChangedListener(itemsCheckedChangedListener: OnItemsCheckedChangedListener) {
this.itemsCheckedChangedListener = itemsCheckedChangedListener
}
interface OnItemsCheckedChangedListener {
fun onItemsCheckedChanged()
}
inner class FileHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val textName: TextView = itemView.findViewById(R.id.text_file_name)
val textDescription: TextView = itemView.findViewById(R.id.text_file_description)
val iconImg: ImageView = itemView.findViewById(R.id.icon_file_img)
val iconAccessed: ImageView = itemView.findViewById(R.id.icon_file_accessed)
init {
itemView.setOnClickListener {
onFileClicked.invoke(data[adapterPosition], this)
}
itemView.setOnLongClickListener {
onFileLongClicked.invoke(data[adapterPosition], this)
true
}
}
}
}
| mit | 857d2f54b863eafcafd586b9f3cbf1dd | 28.757062 | 98 | 0.68559 | 4.317213 | false | false | false | false |
GunoH/intellij-community | platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/service/execution/ExternalSystemJdkUtilTest.kt | 7 | 8360 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.externalSystem.service.execution
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkUtil.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.*
import com.intellij.openapi.projectRoots.impl.JavaDependentSdkType
import com.intellij.openapi.projectRoots.impl.MockSdk
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess
import com.intellij.testFramework.IdeaTestUtil
import com.intellij.testFramework.RunAll
import com.intellij.testFramework.UsefulTestCase
import com.intellij.testFramework.fixtures.IdeaProjectTestFixture
import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory
import com.intellij.util.EnvironmentUtil
import com.intellij.util.SystemProperties
import com.intellij.util.ThrowableRunnable
import com.intellij.util.containers.MultiMap
import com.intellij.util.lang.JavaVersion
import org.assertj.core.api.Assertions.assertThat
import org.jdom.Element
import org.junit.Test
import org.mockito.Mockito.mock
import java.io.File
class ExternalSystemJdkUtilTest : UsefulTestCase() {
lateinit var testFixture: IdeaProjectTestFixture
lateinit var project: Project
override fun setUp() {
super.setUp()
testFixture = IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(name, true).fixture
testFixture.setUp()
project = testFixture.project
allowJavaHomeAccess()
}
override fun tearDown() {
RunAll(
ThrowableRunnable { testFixture.tearDown() },
ThrowableRunnable { super.tearDown() }
).run()
}
private fun allowJavaHomeAccess() {
val javaHome = EnvironmentUtil.getValue("JAVA_HOME") ?: return
VfsRootAccess.allowRootAccess(project, javaHome)
}
@Test
fun testGetJdk() {
assertThat(getJdk(project, null)).isNull()
assertThat(resolveJdkName(null, USE_INTERNAL_JAVA)?.homePath)
.isEqualTo(StringUtil.trimEnd(FileUtil.toSystemIndependentName(SystemProperties.getJavaHome()), "/jre"))
val javaHomeEnv = EnvironmentUtil.getValue("JAVA_HOME")?.let { FileUtil.toSystemIndependentName(it) }
if (javaHomeEnv.isNullOrBlank()) {
assertThrows(UndefinedJavaHomeException::class.java) { getJdk(project, USE_JAVA_HOME) }
}
else {
assertThat(getJdk(project, USE_JAVA_HOME)?.homePath)
.isEqualTo(javaHomeEnv)
}
val sdk = IdeaTestUtil.getMockJdk9()
WriteAction.run<Throwable> {
ProjectJdkTable.getInstance().addJdk(sdk, testFixture.testRootDisposable)
ProjectRootManager.getInstance(project).projectSdk = sdk
}
assertThat(getJdk(project, USE_PROJECT_JDK))
.isEqualTo(sdk)
}
@Test
fun testResolveJdkName() {
// Kotlin generates private `testResolveJdkName$lambda-6` and `testResolveJdkName$lambda-7` methods,
// and JUnit yields a warning about non-public test method.
// Separate `doTestResolveJdkName` method makes Kotlin generate the same methods with another names,
// which are not considered as tests by JUnit.
doTestResolveJdkName()
}
private fun doTestResolveJdkName() {
assertThat(resolveJdkName(null, null)).isNull()
assertThat(resolveJdkName(null, USE_INTERNAL_JAVA)?.homePath)
.isEqualTo(StringUtil.trimEnd(FileUtil.toSystemIndependentName(SystemProperties.getJavaHome()), "/jre"))
val javaHomeEnv = EnvironmentUtil.getValue("JAVA_HOME")?.let { FileUtil.toSystemIndependentName(it) }
if (javaHomeEnv.isNullOrBlank()) {
assertThrows(UndefinedJavaHomeException::class.java) { resolveJdkName(null, USE_JAVA_HOME) }
}
else {
assertThat(resolveJdkName(null, USE_JAVA_HOME)?.homePath)
.isEqualTo(javaHomeEnv)
}
assertThrows(ProjectJdkNotFoundException::class.java) {
resolveJdkName(null, USE_PROJECT_JDK)
}
val sdk: Sdk = mock(Sdk::class.java)
assertThat(resolveJdkName(sdk, USE_PROJECT_JDK))
.isEqualTo(sdk)
}
@Test
fun testGetAvailableJdkChoosesLatestSdk() {
val sdk8 = createMockJdk(JavaVersion.compose(8))
val sdk9 = createMockJdk(JavaVersion.compose(9))
WriteAction.run<Throwable> {
ProjectJdkTable.getInstance().addJdk(sdk8, testFixture.testRootDisposable)
ProjectJdkTable.getInstance().addJdk(sdk9, testFixture.testRootDisposable)
}
assertThat(getAvailableJdk(project).second).isEqualTo(sdk9)
}
@Test
fun testGetAvailableJdkPrefersProjectSDKDependency() {
val sdk8 = createMockJdk(JavaVersion.compose(8))
val sdk9 = createMockJdk(JavaVersion.compose(9))
val dependentSDK = TestJavaDependentSdk(sdk8)
WriteAction.run<Throwable> {
with(ProjectJdkTable.getInstance()) {
addJdk(sdk8, testFixture.testRootDisposable)
addJdk(sdk9, testFixture.testRootDisposable)
addJdk(dependentSDK, testFixture.testRootDisposable)
}
ProjectRootManager.getInstance(project).projectSdk = dependentSDK
}
assertThat(getAvailableJdk(project).second).isEqualTo(sdk8)
}
private fun createMockJdk(jdkVersion: JavaVersion): Sdk {
val jdkVersionStr = jdkVersion.toString()
val jdkDir = FileUtil.createTempDirectory(jdkVersionStr, null)
listOf("bin/javac",
"bin/java",
"jre/lib/rt.jar")
.forEach {
File(jdkDir, it).apply {
parentFile.mkdirs()
createNewFile()
writeText("Fake")
}
}
val path = jdkDir.absolutePath
assertThat(isValidJdk(path)).`as`("Mock JDK at $path is expected to pass validation by com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkUtil.isValidJdk() " +
"Please, check validation code and update mock accordingly").isTrue()
return IdeaTestUtil.createMockJdk(jdkVersionStr, path)
}
}
class TestJavaDependentSdk(val sdk: Sdk) : MockSdk("TestJavaDependentSdk",
"fake/path",
"1.0",
MultiMap.empty<OrderRootType, VirtualFile>(),
TestJavaDependentSdkType.getInstance())
class TestJavaDependentSdkType(val myName: String): JavaDependentSdkType(myName) {
companion object {
private val instance = TestJavaDependentSdkType("TestSdkType")
fun getInstance(): TestJavaDependentSdkType = instance
}
override fun suggestHomePath(): String? {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isValidSdkHome(path: String): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun suggestSdkName(currentSdkName: String?, sdkHome: String): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createAdditionalDataConfigurable(sdkModel: SdkModel, sdkModificator: SdkModificator): AdditionalDataConfigurable? {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getPresentableName(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getBinPath(sdk: Sdk): String {
return (sdk as? TestJavaDependentSdk)?.let { JavaSdk.getInstance().getBinPath(it.sdk) }!!
}
override fun getToolsPath(sdk: Sdk): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getVMExecutablePath(sdk: Sdk): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun saveAdditionalData(additionalData: SdkAdditionalData, additional: Element) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
| apache-2.0 | d31d4f289e0a1c96e261d7efb60a82a4 | 37.173516 | 183 | 0.726196 | 4.578313 | false | true | false | false |
GunoH/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensibility/AbstractPackageUpdateInspectionCheck.kt | 7 | 2663 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.extensibility
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtil
import com.intellij.psi.PsiFile
import com.jetbrains.packagesearch.intellij.plugin.util.packageSearchProjectService
abstract class AbstractPackageUpdateInspectionCheck : LocalInspectionTool() {
protected open fun shouldCheckFile(file: PsiFile): Boolean = false
protected open fun selectPsiElementIndex(dependencyDeclarationIndexes: DependencyDeclarationIndexes): Int? = null
final override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor> {
val isFileNotTracked by lazy {
file.virtualFile !in file.project.packageSearchProjectService
.projectModulesStateFlow
.value
.map { it.buildFile }
}
val shouldNotCheckFile by lazy { !shouldCheckFile(file) }
val isNotAvailable = !file.project.packageSearchProjectService.isAvailable
if (isNotAvailable || isFileNotTracked || shouldNotCheckFile) {
return emptyArray()
}
val fileModule = ModuleUtil.findModuleForFile(file)
if (fileModule == null) {
thisLogger().warn("Inspecting file belonging to an unknown module")
return emptyArray()
}
val problemsHolder = ProblemsHolder(manager, file, isOnTheFly)
problemsHolder.checkFile(file, fileModule)
return problemsHolder.resultsArray
}
abstract fun ProblemsHolder.checkFile(file: PsiFile, fileModule: Module)
}
| apache-2.0 | 185fadbd163986c1a20c1705bc74399c | 41.951613 | 124 | 0.701089 | 5.294235 | false | false | false | false |
GunoH/intellij-community | plugins/configuration-script/test/PropertyValueReaderTest.kt | 7 | 1596 | package com.intellij.configurationScript
import com.intellij.configurationScript.providers.PluginsConfiguration
import com.intellij.configurationScript.schemaGenerators.PluginJsonSchemaGenerator
import com.intellij.testFramework.ProjectRule
import com.intellij.testFramework.assertions.Assertions.assertThat
import org.intellij.lang.annotations.Language
import org.junit.ClassRule
import org.junit.Test
import org.snakeyaml.engine.v2.nodes.MappingNode
class PropertyValueReaderTest {
companion object {
@JvmField
@ClassRule
val projectRule = ProjectRule()
}
@Test
fun collection() {
val result = doReadPluginsConfiguration("""
plugins:
repositories:
- foo
- bar
- http://example.com
""")
val options = PluginsConfiguration()
options.repositories.addAll(listOf("foo", "bar", "http://example.com"))
assertThat(result).isEqualTo(options)
}
@Test
fun `list of objects`() {
val result = JdkAutoHints()
readIntoObject(result, readYaml("""
sdks:
- sdkName: foo
sdkPath: /home/foo
""").value)
assertThat(result.sdks).hasSize(1)
val sdks = result.sdks
assertThat(sdks).hasSize(1)
}
}
private fun readYaml(@Language("YAML") data: String): MappingNode {
return doRead(data.trimIndent().reader())!!
}
private fun doReadPluginsConfiguration(@Suppress("SameParameterValue") @Language("YAML") data: String): PluginsConfiguration {
return readIntoObject(PluginsConfiguration(), findValueNodeByPath(PluginJsonSchemaGenerator.plugins, readYaml(data).value)!!)
} | apache-2.0 | dc388409e09a89943ebd6e7633e4d133 | 28.574074 | 127 | 0.724311 | 4.470588 | false | true | false | false |
GunoH/intellij-community | python/src/com/jetbrains/python/packaging/toolwindow/PyPackagingToolWindowPanel.kt | 1 | 18839 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.packaging.toolwindow
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.components.service
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.SimpleToolWindowPanel
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.PopupStep
import com.intellij.openapi.ui.popup.util.BaseListPopupStep
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.ui.*
import com.intellij.ui.components.*
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.jcef.JCEFHtmlPanel
import com.intellij.util.Alarm
import com.intellij.util.Alarm.ThreadToUse
import com.intellij.util.SingleAlarm
import com.intellij.util.childScope
import com.intellij.util.ui.JBFont
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.NamedColorUtil
import com.intellij.util.ui.UIUtil
import com.jetbrains.python.PyBundle.message
import com.jetbrains.python.packaging.common.PythonLocalPackageSpecification
import com.jetbrains.python.packaging.common.PythonPackageDetails
import com.jetbrains.python.packaging.common.PythonVcsPackageSpecification
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.awt.BorderLayout
import java.awt.Component
import java.awt.Dimension
import java.awt.event.ActionEvent
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.*
import javax.swing.event.DocumentEvent
class PyPackagingToolWindowPanel(private val project: Project, toolWindow: ToolWindow) : SimpleToolWindowPanel(false, true), Disposable {
private val packagingScope = ApplicationManager.getApplication().coroutineScope.childScope(Dispatchers.Default)
private var selectedPackage: DisplayablePackage? = null
private var selectedPackageDetails: PythonPackageDetails? = null
// UI elements
private val packageNameLabel = JLabel().apply { font = JBFont.h4().asBold(); isVisible = false }
private val versionLabel = JLabel().apply { isVisible = false }
private val documentationLink = HyperlinkLabel(message("python.toolwindow.packages.documentation.link")).apply {
addHyperlinkListener { if (documentationUrl != null) BrowserUtil.browse(documentationUrl!!) }
isVisible = false
}
private val searchTextField: SearchTextField
private val searchAlarm: Alarm
private val installButton: JBOptionButton
private val uninstallAction: JComponent
private val progressBar: JProgressBar
private val versionSelector: JBComboBoxLabel
private val descriptionPanel: JCEFHtmlPanel
private var documentationUrl: String? = null
private val packageListPanel: JPanel
private val tablesView: PyPackagingTablesView
private val noPackagePanel = JBPanelWithEmptyText().apply { emptyText.text = message("python.toolwindow.packages.description.panel.placeholder") }
// layout
private var mainPanel: JPanel? = null
private var splitter: OnePixelSplitter? = null
private val leftPanel: JScrollPane
private val rightPanel: JComponent
internal var contentVisible: Boolean
get() = mainPanel!!.isVisible
set(value) {
mainPanel!!.isVisible = value
}
private val latestText: String
get() = message("python.toolwindow.packages.latest.version.label")
private val fromVcsText: String
get() = message("python.toolwindow.packages.add.package.from.vcs")
private val fromDiscText: String
get() = message("python.toolwindow.packages.add.package.from.disc")
init {
val service = project.service<PyPackagingToolWindowService>()
Disposer.register(service, this)
withEmptyText(message("python.toolwindow.packages.no.interpreter.text"))
descriptionPanel = PyPackagingJcefHtmlPanel(service.project)
Disposer.register(toolWindow.disposable, descriptionPanel)
versionSelector = JBComboBoxLabel().apply {
text = latestText
isVisible = false
addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent?) {
val versions = listOf(latestText) + (selectedPackageDetails?.availableVersions ?: emptyList())
JBPopupFactory.getInstance().createListPopup(
object : BaseListPopupStep<String>(null, versions) {
override fun onChosen(@NlsContexts.Label selectedValue: String, finalChoice: Boolean): PopupStep<*>? {
[email protected] = selectedValue
return FINAL_CHOICE
}
}, 8).showUnderneathOf(this@apply)
}
})
}
// todo[akniazev]: add options to install with args
installButton = JBOptionButton(null, null).apply { isVisible = false }
val uninstallToolbar = ActionManager.getInstance()
.createActionToolbar(ActionPlaces.TOOLWINDOW_CONTENT, DefaultActionGroup(DefaultActionGroup().apply {
add(object : AnAction(message("python.toolwindow.packages.delete.package")) {
override fun actionPerformed(e: AnActionEvent) {
if (selectedPackage is InstalledPackage) {
packagingScope.launch(Dispatchers.Main) {
startProgress()
withContext(Dispatchers.IO) {
service.deletePackage(selectedPackage as InstalledPackage)
}
stopProgress()
}
} else error("Trying to delete package, that is not InstalledPackage")
}
})
isPopup = true
with(templatePresentation) {
putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, true)
icon = AllIcons.Actions.More
}
}), true)
uninstallToolbar.targetComponent = this
uninstallAction = uninstallToolbar.component
progressBar = JProgressBar(JProgressBar.HORIZONTAL).apply {
maximumSize.width = 200
minimumSize.width = 200
preferredSize.width = 200
isVisible = false
isIndeterminate = true
}
packageListPanel = JPanel().apply {
layout = BoxLayout(this, BoxLayout.Y_AXIS)
alignmentX = LEFT_ALIGNMENT
background = UIUtil.getListBackground()
}
tablesView = PyPackagingTablesView(project, packageListPanel, this)
leftPanel = ScrollPaneFactory.createScrollPane(packageListPanel, true)
rightPanel = borderPanel {
add(borderPanel {
border = SideBorder(JBColor.GRAY, SideBorder.BOTTOM)
preferredSize = Dimension(preferredSize.width, 50)
minimumSize = Dimension(minimumSize.width, 50)
maximumSize = Dimension(maximumSize.width, 50)
add(boxPanel {
add(Box.createHorizontalStrut(10))
add(packageNameLabel)
add(Box.createHorizontalStrut(10))
add(documentationLink)
}, BorderLayout.WEST)
add(boxPanel {
alignmentX = Component.RIGHT_ALIGNMENT
add(progressBar)
add(versionSelector)
add(versionLabel)
add(installButton)
add(uninstallAction)
add(Box.createHorizontalStrut(10))
}, BorderLayout.EAST)
}, BorderLayout.NORTH)
add(descriptionPanel.component, BorderLayout.CENTER)
}
searchTextField = object : SearchTextField(false) {
init {
preferredSize = Dimension(250, 30)
minimumSize = Dimension(250, 30)
maximumSize = Dimension(250, 30)
textEditor.border = JBUI.Borders.empty(0, 6, 0, 0)
textEditor.isOpaque = true
textEditor.emptyText.text = message("python.toolwindow.packages.search.text.placeholder")
}
override fun onFieldCleared() {
service.handleSearch("")
}
}
searchAlarm = SingleAlarm({
service.handleSearch(searchTextField.text.trim())
}, 500, service, ThreadToUse.SWING_THREAD, ModalityState.NON_MODAL)
searchTextField.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
searchAlarm.cancelAndRequest()
}
})
initOrientation(service, true)
trackOrientation(service)
}
private fun initOrientation(service: PyPackagingToolWindowService, horizontal: Boolean) {
val second = if (splitter?.secondComponent == rightPanel) rightPanel else noPackagePanel
val proportionKey = if (horizontal) HORIZONTAL_SPLITTER_KEY else VERTICAL_SPLITTER_KEY
splitter = OnePixelSplitter(!horizontal, proportionKey, 0.3f).apply {
firstComponent = leftPanel
secondComponent = second
}
val actionGroup = DefaultActionGroup()
actionGroup.add(object : AnAction({ message("python.toolwindow.packages.reload.repositories.action")}, AllIcons.Actions.Refresh) {
override fun actionPerformed(e: AnActionEvent) {
service.reloadPackages()
}
})
actionGroup.add(object : AnAction({ message("python.toolwindow.packages.manage.repositories.action") }, AllIcons.General.GearPlain) {
override fun actionPerformed(e: AnActionEvent) {
service.manageRepositories()
}
})
val actionToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.TOOLWINDOW_CONTENT, actionGroup,true)
actionToolbar.targetComponent = this
val installFromLocationLink = DropDownLink(message("python.toolwindow.packages.add.package.action"),
listOf(fromVcsText, fromDiscText)) {
val specification = when (it) {
fromDiscText -> showInstallFromDiscDialog(service)
fromVcsText -> showInstallFromVcsDialog(service)
else -> throw IllegalStateException("Unknown operation")
}
if (specification != null) {
packagingScope.launch {
service.installPackage(specification)
}
}
}
mainPanel = borderPanel {
val topToolbar = boxPanel {
border = SideBorder(NamedColorUtil.getBoundsColor(), SideBorder.BOTTOM)
preferredSize = Dimension(preferredSize.width, 30)
minimumSize = Dimension(minimumSize.width, 30)
maximumSize = Dimension(maximumSize.width, 30)
add(searchTextField)
actionToolbar.component.maximumSize = Dimension(70, actionToolbar.component.maximumSize.height)
add(actionToolbar.component)
add(installFromLocationLink)
}
add(topToolbar, BorderLayout.NORTH)
add(splitter!!, BorderLayout.CENTER)
}
setContent(mainPanel!!)
}
private fun showInstallFromVcsDialog(service: PyPackagingToolWindowService): PythonVcsPackageSpecification? {
var editable = false
var link = ""
val systems = listOf(message("python.toolwindow.packages.add.package.vcs.git"),
message("python.toolwindow.packages.add.package.vcs.svn"),
message("python.toolwindow.packages.add.package.vcs.hg"),
message("python.toolwindow.packages.add.package.vcs.bzr"))
var vcs = systems.first()
val panel = panel {
row {
comboBox(systems)
.bindItem({ vcs }, { vcs = it!! })
textField()
.columns(COLUMNS_MEDIUM)
.bindText({ link }, { link = it })
.align(AlignX.FILL)
}
row {
checkBox(message("python.toolwindow.packages.add.package.as.editable"))
.bindSelected({ editable }, { editable = it })
}
}
val shouldInstall = dialog(message("python.toolwindow.packages.add.package.dialog.title"), panel, project = service.project, resizable = true).showAndGet()
if (shouldInstall) {
val prefix = when (vcs) {
message("python.toolwindow.packages.add.package.vcs.git") -> "git+"
message("python.toolwindow.packages.add.package.vcs.svn") -> "svn+"
message("python.toolwindow.packages.add.package.vcs.hg") -> "hg+"
message("python.toolwindow.packages.add.package.vcs.bzr") -> "bzr+"
else -> throw IllegalStateException("Unknown VCS")
}
return PythonVcsPackageSpecification(link, link, prefix, editable)
}
return null
}
private fun showInstallFromDiscDialog(service: PyPackagingToolWindowService): PythonLocalPackageSpecification? {
var editable = false
val textField = TextFieldWithBrowseButton().apply {
addBrowseFolderListener(message("python.toolwindow.packages.add.package.path.selector"), "", service.project,
FileChooserDescriptorFactory.createSingleFileOrFolderDescriptor())
}
val panel = panel {
row(message("python.toolwindow.packages.add.package.path")) {
cell(textField)
.columns(COLUMNS_MEDIUM)
.align(AlignX.FILL)
}
row {
checkBox(message("python.toolwindow.packages.add.package.as.editable"))
.bindSelected({ editable }, { editable = it })
}
}
val shouldInstall = dialog(message("python.toolwindow.packages.add.package.dialog.title"), panel, project = service.project, resizable = true).showAndGet()
return if (shouldInstall) PythonLocalPackageSpecification(textField.text, textField.text, editable) else null
}
private fun trackOrientation(service: PyPackagingToolWindowService) {
service.project.messageBus.connect(service).subscribe(ToolWindowManagerListener.TOPIC, object : ToolWindowManagerListener {
var myHorizontal = true
override fun stateChanged(toolWindowManager: ToolWindowManager) {
val toolWindow = toolWindowManager.getToolWindow("Python Packages")
if (toolWindow == null || toolWindow.isDisposed) return
val isHorizontal = toolWindow.anchor.isHorizontal
if (myHorizontal != isHorizontal) {
myHorizontal = isHorizontal
val content = toolWindow.contentManager.contents.find { it?.component is PyPackagingToolWindowPanel }
val panel = content?.component as? PyPackagingToolWindowPanel ?: return
panel.initOrientation(service, myHorizontal)
}
}
})
}
fun packageSelected(selectedPackage: DisplayablePackage) {
showHeaderForPackage(selectedPackage)
this.selectedPackage = selectedPackage
packagingScope.launch(Dispatchers.IO) {
val service = project.service<PyPackagingToolWindowService>()
val packageDetails = service.detailsForPackage(selectedPackage)
val installActions = PythonPackagingToolwindowActionProvider.EP_NAME
.extensionList
.firstNotNullOf {
it.getInstallActions(packageDetails, service.manager)
}
withContext(Dispatchers.Main) {
selectedPackageDetails = packageDetails
if (splitter?.secondComponent != rightPanel) {
splitter!!.secondComponent = rightPanel
}
val renderedDescription = with(packageDetails) {
when {
!description.isNullOrEmpty() -> service.convertToHTML(descriptionContentType, description!!)
!summary.isNullOrEmpty() -> service.wrapHtml(summary!!)
else -> NO_DESCRIPTION
}
}
descriptionPanel.setHtml(renderedDescription)
documentationUrl = packageDetails.documentationUrl
documentationLink.isVisible = documentationUrl != null
installButton.action = wrapAction(installActions.first(), packageDetails)
if (installActions.size > 1) {
installButton.options = installActions
.asSequence().drop(1).map { wrapAction(it, packageDetails) }.toList().toTypedArray()
}
installButton.repaint()
}
}
}
private fun wrapAction(installAction: PythonPackageInstallAction, details: PythonPackageDetails): Action {
return object : AbstractAction(installAction.text) {
override fun actionPerformed(e: ActionEvent?) {
val version = if (versionSelector.text == latestText) null else versionSelector.text
packagingScope.launch(Dispatchers.IO) {
val specification = details.toPackageSpecification(version)
installAction.installPackage(specification)
}
}
}
}
fun showSearchResult(installed: List<InstalledPackage>, repoData: List<PyPackagesViewData>) {
tablesView.showSearchResult(installed, repoData)
}
fun resetSearch(installed: List<InstalledPackage>, repos: List<PyPackagesViewData>) {
tablesView.resetSearch(installed, repos)
}
fun startProgress() {
progressBar.isVisible = true
hideInstallableControls()
hideInstalledControls()
}
fun stopProgress() {
progressBar.isVisible = false
}
private fun showInstalledControls() {
hideInstallableControls()
progressBar.isVisible = false
versionLabel.isVisible = true
uninstallAction.isVisible = true
}
private fun showInstallableControls() {
hideInstalledControls()
progressBar.isVisible = false
versionSelector.isVisible = true
versionSelector.text = latestText
installButton.isVisible = true
}
private fun hideInstalledControls() {
versionLabel.isVisible = false
uninstallAction.isVisible = false
}
private fun hideInstallableControls() {
installButton.isVisible = false
versionSelector.isVisible = false
}
private fun showHeaderForPackage(selectedPackage: DisplayablePackage) {
packageNameLabel.text = selectedPackage.name
packageNameLabel.isVisible = true
documentationLink.isVisible = false
if (selectedPackage is InstalledPackage) {
@Suppress("HardCodedStringLiteral")
versionLabel.text = selectedPackage.instance.version
showInstalledControls()
}
else {
showInstallableControls()
}
}
fun setEmpty() {
hideInstalledControls()
hideInstallableControls()
listOf(packageNameLabel, packageNameLabel, documentationLink).forEach { it.isVisible = false }
splitter?.secondComponent = noPackagePanel
}
override fun dispose() {
packagingScope.cancel()
}
companion object {
private const val HORIZONTAL_SPLITTER_KEY = "Python.PackagingToolWindow.Horizontal"
private const val VERTICAL_SPLITTER_KEY = "Python.PackagingToolWindow.Vertical"
val NO_DESCRIPTION: String
get() = message("python.toolwindow.packages.no.description.placeholder")
}
} | apache-2.0 | 1a82a5749da8fce5b2572abeb836687e | 37.370672 | 159 | 0.711184 | 5.00904 | false | false | false | false |
GunoH/intellij-community | platform/core-impl/src/com/intellij/ide/plugins/ExpiredPluginsState.kt | 4 | 2652 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.plugins
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.PluginId
import org.jetbrains.annotations.ApiStatus.Internal
import org.jetbrains.annotations.NonNls
import java.nio.file.Path
@Internal
class ExpiredPluginsState : PluginEnabler {
companion object {
const val EXPIRED_PLUGINS_FILENAME: @NonNls String = "expired_plugins.txt"
private var expiredPluginIds_: MutableSet<PluginId>? = null
private val defaultFilePath: Path
get() = PathManager.getConfigDir().resolve(EXPIRED_PLUGINS_FILENAME)
private val logger
get() = Logger.getInstance(ExpiredPluginsState::class.java)
@JvmStatic
fun getInstance(): ExpiredPluginsState =
ApplicationManager.getApplication().getService(ExpiredPluginsState::class.java)
@JvmStatic
val expiredPluginIds: Set<PluginId>
get() {
expiredPluginIds_?.let {
return it
}
synchronized(ExpiredPluginsState::class.java) {
var result = expiredPluginIds_
if (result == null) {
result = LinkedHashSet(PluginManagerCore.tryReadPluginIdsFromFile(defaultFilePath, logger))
expiredPluginIds_ = result
}
return result
}
}
@JvmStatic
fun isExpired(pluginId: PluginId): Boolean = expiredPluginIds.contains(pluginId)
@JvmStatic
fun setExpiredState(pluginIds: Set<PluginId>, expired: Boolean): Boolean {
logger.info(pluginIds.joinedPluginIds("expire"))
val expiredPluginIds = expiredPluginIds as MutableSet
return (if (expired) expiredPluginIds.addAll(pluginIds) else expiredPluginIds.removeAll(pluginIds))
&& PluginManagerCore.tryWritePluginIdsToFile(defaultFilePath, expiredPluginIds, logger)
}
}
init {
logger.info(expiredPluginIds.joinedPluginIds("skip"))
}
override fun isDisabled(pluginId: PluginId): Boolean = isExpired(pluginId)
override fun enableById(pluginIds: Set<PluginId>): Boolean = setExpiredState(pluginIds, expired = true)
override fun disableById(pluginIds: Set<PluginId>): Boolean = setExpiredState(pluginIds, expired = false)
override fun enable(descriptors: Collection<IdeaPluginDescriptor>): Boolean = enableById(descriptors.toPluginIdSet())
override fun disable(descriptors: Collection<IdeaPluginDescriptor>): Boolean = disableById(descriptors.toPluginIdSet())
}
| apache-2.0 | 3cd94c0c18ef8625e2bbaf74f4abbda4 | 34.837838 | 121 | 0.739819 | 4.79566 | false | false | false | false |
NlRVANA/Unity | app/src/main/java/com/zwq65/unity/utils/ImageLoad.kt | 1 | 3152 | package com.zwq65.unity.utils
import android.content.Context
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.Priority
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.request.RequestOptions
import java.lang.ref.WeakReference
/**
*================================================
* 图片加载函数类
*
* Created by NIRVANA on 2018/7/25
* Contact with <[email protected]>
*================================================
*/
/**
* 加载图片url
*
* @param url 图片url
*/
fun ImageView.loadUrl(url: String?) {
// 具体图片加载实现可以使用第三方框架加载,也可以自己实现,
val requestOptions = RequestOptions()
.centerCrop()
.transform(CenterCrop())
.format(DecodeFormat.PREFER_RGB_565)
.priority(Priority.NORMAL)
.dontAnimate()
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
Glide.with(context.applicationContext)
.load(url)
.apply(requestOptions)
.into(this)
}
/**
* 加载圆形图片url
*
* @param url 图片url
*/
fun ImageView.loadCircle(url: String?) {
// 具体图片加载逻辑
val requestOptions = RequestOptions()
.centerCrop()
.transform(CenterCrop())
.format(DecodeFormat.PREFER_RGB_565)
.priority(Priority.NORMAL)
.circleCrop()
.dontAnimate()
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
Glide.with(context.applicationContext)
.load(url)
.apply(requestOptions)
.into(this)
}
/**
* 加载圆形图片資源
*
* @param url 图片url
*/
fun ImageView.loadCircle(source: Int?) {
// 具体图片加载逻辑
val requestOptions = RequestOptions()
.centerCrop()
.transform(CenterCrop())
.format(DecodeFormat.PREFER_RGB_565)
.priority(Priority.NORMAL)
.circleCrop()
.dontAnimate()
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
Glide.with(context.applicationContext)
.load(source)
.apply(requestOptions)
.into(this)
}
fun load(context: WeakReference<Context>, url: String?, image: ImageView?, transformation: BitmapTransformation) {
if (image == null) return
// 具体图片加载逻辑
}
fun load(holder: Int, context: WeakReference<Context>, url: String, image: ImageView?, width: Int, height: Int) {
if (image == null) return
// 具体图片加载逻辑
}
fun loadCircle(context: WeakReference<Context>, url: String?, image: ImageView?, width_height: Int) {
if (image == null) return
// 具体图片加载逻辑
}
fun clearCache(context: WeakReference<Context>) {
// 强制清楚缓存,可以为内存缓存也可以为硬盘缓存
Glide.get(context.get()!!.applicationContext).clearMemory()
System.gc()
}
| apache-2.0 | d0eedd6e0cec779613b366ea368289d1 | 25.944444 | 114 | 0.628522 | 4.019337 | false | false | false | false |
sheungon/AndroidEasyLog | sample/src/main/java/com/sotwtm/log/sample/MainActivity.kt | 1 | 6145 | package com.sotwtm.log.sample
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.FileObserver
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import com.sotwtm.log.sample.databinding.ActivityMainBinding
import com.sotwtm.util.ECLogcatUtil
import com.sotwtm.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.lang.ref.WeakReference
import java.util.*
class MainActivity : AppCompatActivity() {
companion object {
private const val REQUIRED_PERMISSIONS = Manifest.permission.WRITE_EXTERNAL_STORAGE
private const val REQUEST_PERMISSION = 1000
}
private var mBinding: ActivityMainBinding? = null
private var mLogObserver: MyFileObserver? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val logPath = ApplicationClass.instance
.logFile
.absolutePath
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
mBinding?.activity = this
mBinding?.logPath = logPath
mLogObserver = MyFileObserver(
this,
logPath,
FileObserver.MODIFY or FileObserver.DELETE or FileObserver.CLOSE_WRITE or FileObserver.CREATE
)
mLogObserver?.startWatching()
updateLogView()
}
override fun onPostResume() {
super.onPostResume()
val permissionCheck = ContextCompat.checkSelfPermission(
this,
REQUIRED_PERMISSIONS
)
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(
this,
Manifest.permission.READ_CONTACTS
)
) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
Toast.makeText(this, R.string.msg_needed_external_access, Toast.LENGTH_LONG)
.show()
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(
this,
arrayOf(REQUIRED_PERMISSIONS),
REQUEST_PERMISSION
)
}
}
}
override fun onDestroy() {
super.onDestroy()
mLogObserver?.stopWatching()
mLogObserver = null
mBinding?.unbind()
mBinding = null
}
fun onClickStart() {
if (ECLogcatUtil.getInstance(application).startLogcat()) {
Log.v("*** Log Started ***")
}
mLogObserver?.stopWatching()
CoroutineScope(Dispatchers.Default).launch {
delay(500)
mLogObserver?.startWatching()
}
}
fun onClickStop() {
if (ECLogcatUtil.getInstance(application).stopLogcat()) {
Log.v("*** Log Stopped ***")
}
}
fun onClickClear() {
if (ECLogcatUtil.getInstance(application).clearLogcat()) {
Log.v("*** Log Cleared ***")
}
mLogObserver?.stopWatching()
CoroutineScope(Dispatchers.Default).launch {
delay(500)
mLogObserver?.startWatching()
}
}
fun onClickReset() {
if (ECLogcatUtil.getInstance(application).resetLogcat()) {
Log.v("*** Log Reset ***")
}
mLogObserver?.stopWatching()
CoroutineScope(Dispatchers.Default).launch {
delay(500)
mLogObserver?.startWatching()
}
}
fun onClickFilter() {
val binding = mBinding ?: return
val logcatUtil = ECLogcatUtil.getInstance(application)
logcatUtil.setFilterLogTag(binding.filterText.text.toString())
logcatUtil.stopLogcat()
logcatUtil.startLogcat()
mLogObserver?.stopWatching()
CoroutineScope(Dispatchers.Default).launch {
delay(500)
mLogObserver?.startWatching()
}
}
fun onClickLog() {
Log.d("Clicked at : " + Date())
Test().log()
}
private fun updateLogView() {
val binding = mBinding ?: return
val logFile = ApplicationClass.instance.logFile
if (!logFile.isFile) {
// Log file not yet created
binding.setLog(getString(R.string.error_log_not_created))
return
}
if (!logFile.canRead()) {
binding.setLog(getString(R.string.error_read_log))
return
}
val logContentBuilder = StringBuilder()
logFile.readTextFile(logContentBuilder)
binding.setLog(logContentBuilder.toString())
// Force log scroll view to the bottom
binding.scrollViewLog.postDelayed({ binding.scrollViewLog.fullScroll(View.FOCUS_DOWN) }, 200)
}
///////////////////////////
// Class and interface
///////////////////////////
private class MyFileObserver(
activity: MainActivity,
path: String,
mask: Int
) : FileObserver(path, mask) {
private val mActivityRef: WeakReference<MainActivity> = WeakReference(activity)
private val mUpdateLogTask = Runnable {
mActivityRef.get()?.updateLogView()
}
override fun onEvent(event: Int, path: String?) {
val activity = mActivityRef.get() ?: return
when (event) {
MODIFY, CLOSE_WRITE, DELETE, DELETE_SELF -> activity.runOnUiThread(
mUpdateLogTask
)
}
}
}
private class Test {
fun log() {
Log.d("Clicked at : " + Date())
}
}
}
| apache-2.0 | 1704e9b1512c86e7ff24f27e01985e7f | 27.985849 | 105 | 0.599024 | 5.03276 | false | false | false | false |
liujoshua/BridgeAndroidSDK | sageresearch-app-sdk/src/main/java/org/sagebionetworks/research/sageresearch/manager/ActivityGroup.kt | 1 | 5646 | package org.sagebionetworks.research.sageresearch.manager
import org.sagebionetworks.research.domain.step.ui.theme.ImageTheme
//
// Copyright © 2018 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
/**
* A protocol that can be used to filter and parse the scheduled activities for a
* variety of customized UI/UX designs based on the objects defined
*/
interface ActivityGroup: TaskGroup {
/**
* @property journeyTitle The text to display for the task group when displaying this in a list or
* collection where the format of the string is compact or extended, depending
* upon the requirements of the UI design.
*/
val journeyTitle: String?
/**
* @property activityIdentifiers A list of the activity identifiers associated with this task group.
*/
val activityIdentifiers : Set<String>
/**
* The schedule plan guid that can be used to map scheduled activities to
* the appropriate group in the case where more than one group may contain
* the same tasks.
*/
val schedulePlanGuid : String?
/**
* The activity guid map that can be used to map scheduled activities to
* the appropriate group in the case where more than one group may contain
* the same tasks **but** where the activities are not all grouped on the server
* using the same schedule. This guid can be found in the Bridge Study Manager UI
* by hovering your cursor over the copy icon and selecting "Copy GUID".
*/
val activityGuidMap : Map<String, String>?
// TODO: mdephillips 9/4/18 not sure we need this
/// An identifier that can be used to associate an `SBBScheduledActivity` instance
/// with setting up a local reminder for when to perform a task.
//var notificationIdentifier : RSDIdentifier? { get }
}
/**
* `ActivityGroupObject` is a concrete implementation of interface ActivityGroup
*
* - example:
* ````
* // Example activity group using a shared `schedulePlanGuid`.
* let json = """
* {
* "identifier": "foo",
* "title": "Title",
* "journeyTitle": "Journey title",
* "detail": "A detail about the object",
* "imageSource": "fooImage",
* "activityIdentifiers": ["taskA", "taskB", "taskC"],
* "notificationIdentifier": "scheduleFoo",
* "schedulePlanGuid": "abcdef12-3456-7890",
* }
* """.data(using: .utf8)! // our data in native (JSON) format
*
* // Example activity group using the `activity.guid` identifiers to map schedules to tasks.
* let json = """
* {
* "identifier": "foo",
* "activityIdentifiers": ["taskA", "taskB", "taskC"],
* "activityGuidMap": {
* "taskA":"ababab12-3456-7890",
* "taskB":"cdcdcd12-3456-7890",
* "taskC":"efefef12-3456-7890"
* }
* }
* """.data(using: .utf8)! // our data in native (JSON) format
*
* // Example activity group where the first schedule matching the given activity identifer is used.
* let json = """
* {
* "identifier": "foo",
* "activityIdentifiers": ["taskA", "taskB", "taskC"]
* }
* """.data(using: .utf8)! // our data in native (JSON) format
* ````
*/
data class ActivityGroupObject(
override val identifier: String,
override val title: String? = null,
override val detail: String? = null,
override val imageName: String? = null,
override val tasks: Set<TaskInfo> = setOf(),
override val journeyTitle: String? = null,
override val activityIdentifiers : Set<String> = setOf(),
override val schedulePlanGuid : String? = null,
override val activityGuidMap : Map<String, String>? = null): ActivityGroup
| apache-2.0 | 20b2ab30155ba21691d3dec3e05fbbda | 43.801587 | 104 | 0.649247 | 4.465981 | false | false | false | false |
bmaslakov/kotlin-algorithm-club | src/main/io/uuddlrlrba/ktalgs/geometry/convexhull/GrahamScan.kt | 1 | 2803 | /*
* Copyright (c) 2017 Kotlin Algorithm Club
*
* 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 io.uuddlrlrba.ktalgs.geometry.convexhull
import io.uuddlrlrba.ktalgs.datastructures.Stack
import io.uuddlrlrba.ktalgs.geometry.Point
class GrahamScan: ConvexHullAlgorithm {
override fun convexHull(points: Array<Point>): Collection<Point> {
if (points.size < 3) throw IllegalArgumentException("there must be at least 3 points")
val hull = Stack<Point>()
// Find the leftmost point
points.sortBy { it.y }
// Sort points by polar angle with p
points.sortWith( Comparator { q1, q2 ->
val dx1 = q1.x - points[0].x
val dy1 = q1.y - points[0].y
val dx2 = q2.x - points[0].x
val dy2 = q2.y - points[0].y
if (dy1 >= 0 && dy2 < 0)
-1 // q1 above; q2 below
else if (dy2 >= 0 && dy1 < 0)
+1 // q1 below; q2 above
else if (dy1 == 0 && dy2 == 0) { // 3-collinear and horizontal
if (dx1 >= 0 && dx2 < 0)
-1
else if (dx2 >= 0 && dx1 < 0)
+1
else
0
} else
-Point.orientation(points[0], q1, q2) // both above or below
// Note: ccw() recomputes dx1, dy1, dx2, and dy2
})
hull.push(points[0])
hull.push(points[1])
for (i in IntRange(2, points.size - 1)) {
var top = hull.poll()
while (Point.orientation(hull.peek(), top, points[i]) <= 0) {
top = hull.poll()
}
hull.push(top)
hull.push(points[i])
}
return hull
}
}
| mit | f6a9ddc094b48884dcbd8f0ecfa04e61 | 36.878378 | 94 | 0.595077 | 3.975887 | false | false | false | false |
sw926/ImageFileSelector | library/src/main/java/com/sw926/imagefileselector/ImageCropHelper.kt | 1 | 4258 | package com.sw926.imagefileselector
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.activity.result.ActivityResultLauncher
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.sw926.imagefileselector.contract.CropImageContract
import java.io.File
import java.lang.ref.WeakReference
class ImageCropHelper {
data class CropParam(
val inputUri: Uri,
val outputUri: Uri,
val outPutX: Int = -1,
val outPutY: Int = -1,
val aspectX: Int = -1,
val aspectY: Int = -1,
val scale: Boolean = true,
)
private val cropImage: ActivityResultLauncher<CropParam>
private var outPutX = -1
private var outPutY = -1
private var aspectX = -1
private var aspectY = -1
private var scale = true
private var outputFile: File? = null
/**
* 记录裁切过程中产生的临时文件,裁切完成后进行删除
*/
private val tempFiles = mutableListOf<String>()
private var listener: ImageFileResultListener? = null
private val context: WeakReference<Context>
constructor(activity: AppCompatActivity) {
cropImage = activity.registerForActivityResult(CropImageContract()) {
onCropResult(it)
}
context = WeakReference(activity)
}
constructor(fragment: Fragment) {
cropImage = fragment.registerForActivityResult(CropImageContract()) {
onCropResult(it)
}
context = WeakReference(fragment.context)
}
private fun onCropResult(uri: Uri?) {
outputFile?.let {
if (it.exists()) {
listener?.onSuccess(it.path)
return
}
}
if (uri == null) {
listener?.onCancel()
return
}
val context = this.context.get()
if (context == null) {
listener?.onError()
return
}
val filePath = CommonUtils.getPathFromFileProviderUri(context, uri)
if (filePath != null) {
listener?.onSuccess(filePath)
} else {
listener?.onError()
}
}
fun setOutPut(width: Int, height: Int) {
outPutX = width
outPutY = height
}
fun setOutPutAspect(width: Int, height: Int) {
aspectX = width
aspectY = height
}
fun setScale(scale: Boolean) {
this.scale = scale
}
fun setListener(listener: ImageFileResultListener?) {
this.listener = listener
}
private fun getCropperPackageName(context: Context): String? {
return kotlin.runCatching {
val intent = Intent("com.android.camera.action.CROP")
intent.putExtra("crop", "true")
intent.type = "image/*"
context.packageManager.resolveActivity(intent, 0)?.activityInfo?.packageName
}.getOrNull()
}
fun cropImage(srcFile: String) {
val context = this.context.get()
if (context == null) {
listener?.onError()
return
}
val cropperPackageName = getCropperPackageName(context)
if (cropperPackageName == null) {
listener?.onError()
return
}
val inputFile = CommonUtils.generateImageCacheFile(context, ".jpg")
File(srcFile).copyTo(inputFile)
tempFiles.add(inputFile.path)
val inputUri = CommonUtils.getFileUri(context, inputFile)
context.grantUriPermission(cropperPackageName, inputUri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
val outputFile = CommonUtils.generateImageCacheFile(context, ".jpg")
this.outputFile = outputFile
val outputUri = CommonUtils.getFileUri(context, outputFile)
context.grantUriPermission(cropperPackageName, outputUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION)
val param = CropParam(
inputUri = inputUri,
outputUri = outputUri,
outPutX = outPutX,
outPutY = outPutY,
aspectX = aspectX,
aspectY = aspectY,
scale = scale
)
cropImage.launch(param)
}
} | apache-2.0 | 9a35138ca45a72bd436aefab048534d2 | 26.167742 | 146 | 0.614252 | 4.541532 | false | false | false | false |
daverix/ajvm | core/src/commonMain/kotlin/net/daverix/ajvm/io/ConstantPool.kt | 1 | 5317 | package net.daverix.ajvm.io
import net.daverix.ajvm.wrapToDouble
import net.daverix.ajvm.wrapToLong
data class ConstantPool(private val data: Array<Any?>) {
operator fun get(index: Int): Any? {
return data[index]
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as ConstantPool
if (!data.contentEquals(other.data)) return false
return true
}
override fun hashCode(): Int {
return data.contentHashCode()
}
companion object {
private const val CONSTANT_TAG_UTF8 = 1
private const val CONSTANT_TAG_INTEGER = 3
private const val CONSTANT_TAG_FLOAT = 4
private const val CONSTANT_TAG_LONG = 5
private const val CONSTANT_TAG_DOUBLE = 6
private const val CONSTANT_TAG_CLASS = 7
private const val CONSTANT_TAG_STRING = 8
private const val CONSTANT_TAG_FIELD_REFERENCE = 9
private const val CONSTANT_TAG_METHOD_REFERENCE = 10
private const val CONSTANT_TAG_INTERFACE_METHOD_REFERENCE = 11
private const val CONSTANT_TAG_NAME_AND_TYPE = 12
private const val CONSTANT_TAG_METHOD_HANDLE = 15
private const val CONSTANT_TAG_METHOD_TYPE = 16
private const val CONSTANT_TAG_INVOKE_DYNAMIC = 18
fun DataInputStream.readConstantPool(): ConstantPool {
val constantPoolCount = readUnsignedShort()
val constantPool = arrayOfNulls<Any?>(constantPoolCount)
var i = 1
while (i < constantPoolCount) {
when (readUnsignedByte()) {
-1 -> error("EOF when reading type from constant pool")
CONSTANT_TAG_UTF8 -> constantPool[i++] = readUTF()
CONSTANT_TAG_INTEGER -> constantPool[i++] = readInt()
CONSTANT_TAG_FLOAT -> constantPool[i++] = readFloat()
CONSTANT_TAG_LONG -> {
val longBytes = ByteArray(8)
if (read(longBytes, 0, 4) != 4)
error("could not read high part of long")
if (read(longBytes, 4, 4) != 4)
error("could not read low part of long")
constantPool[i] = longBytes.wrapToLong()
// we advance index one additional time because we are sure that the second
// part comes directly after
i += 2
}
CONSTANT_TAG_DOUBLE -> {
val doubleBytes = ByteArray(8)
if (read(doubleBytes, 0, 4) != 4)
error("could not read high part of double")
if (read(doubleBytes, 4, 4) != 4)
error("could not read low part of double")
constantPool[i] = doubleBytes.wrapToDouble()
// we advance index one additional time because we are sure that the second
// part comes directly after
i += 2
}
CONSTANT_TAG_CLASS -> constantPool[i++] = ClassReference(
nameIndex = readUnsignedShort()
)
CONSTANT_TAG_STRING -> constantPool[i++] = StringReference(
index = readUnsignedShort()
)
CONSTANT_TAG_FIELD_REFERENCE -> constantPool[i++] = FieldReference(
classIndex = readUnsignedShort(),
nameAndTypeIndex = readUnsignedShort()
)
CONSTANT_TAG_METHOD_REFERENCE -> constantPool[i++] = MethodReference(
classIndex = readUnsignedShort(),
nameAndTypeIndex = readUnsignedShort()
)
CONSTANT_TAG_INTERFACE_METHOD_REFERENCE -> constantPool[i++] = InterfaceMethodReference(
classIndex = readUnsignedShort(),
nameAndTypeIndex = readUnsignedShort()
)
CONSTANT_TAG_NAME_AND_TYPE -> constantPool[i++] = NameAndTypeDescriptorReference(
nameIndex = readUnsignedShort(),
descriptorIndex = readUnsignedShort()
)
CONSTANT_TAG_METHOD_TYPE -> constantPool[i++] = MethodTypeReference(
descriptorIndex = readUnsignedShort()
)
CONSTANT_TAG_METHOD_HANDLE -> constantPool[i++] = MethodHandleReference(
referenceKind = readUnsignedByte(),
referenceIndex = readUnsignedShort()
)
CONSTANT_TAG_INVOKE_DYNAMIC -> constantPool[i++] = InvokeDynamicReference(
bootstrapMethodAttrIndex = readUnsignedShort(),
nameAndTypeIndex = readUnsignedShort()
)
}
}
return ConstantPool(constantPool)
}
}
}
| gpl-3.0 | db057bfa2ec06247e0a74e32cf9bcdf7 | 44.836207 | 108 | 0.51514 | 5.60274 | false | false | false | false |
Magneticraft-Team/ModelLoader | src/main/kotlin/com/cout970/modelloader/animation/AnimationOptimizer.kt | 1 | 4399 | package com.cout970.modelloader.animation
import com.cout970.modelloader.api.*
import net.minecraft.client.renderer.Tessellator
import net.minecraft.client.renderer.vertex.DefaultVertexFormats
import net.minecraft.util.ResourceLocation
import org.lwjgl.opengl.GL11
import javax.vecmath.Matrix4f
import javax.vecmath.Point3f
object AnimationOptimizer {
fun optimize(nodes: List<AnimationNodeBuilder>, animationPoints: Set<Int>): List<AnimatedNode> {
return nodes
.map { compactNode(it, animationPoints) }
.map { it.toAnimated() }
}
fun unoptimized(nodes: List<AnimationNodeBuilder>): List<AnimatedNode>{
return nodes.map { unoptimizedNode(it) }
}
private fun unoptimizedNode(it: AnimationNodeBuilder): AnimatedNode {
val caches = it.vertices.map { (tex, vertex) ->
TextureModelCache(tex, ModelCache { renderVertex(vertex) })
}
return AnimatedNode(
index = it.id,
transform = it.transform.toImmutable(),
children = it.children.map { unoptimizedNode(it) },
cache = if (caches.size == 1) caches.first() else ModelGroupCache(*caches.toTypedArray())
)
}
private data class CompactNode(
val index: Int,
val transform: TRSTransformation,
val dynamic: List<CompactNode>,
val static: List<VertexGroup>
)
private fun compactNode(tree: AnimationNodeBuilder, animatedNodes: Set<Int>): CompactNode {
val list = tree.children.map { childData -> compactNode(childData, animatedNodes) }
val matrix = tree.transform.toImmutable().matrixVec.apply { transpose() }
val (animated, nonAnimated) = list.partition { it.index in animatedNodes }
val childrenVertex = if (tree.id in animatedNodes) {
nonAnimated.flatMap { node -> node.static }
} else {
nonAnimated.flatMap { node ->
node.static.map { (tex, vertex) ->
VertexGroup(tex, vertex.map { matrix.transform(it) })
}
}
}
val thisVertex = if (tree.id in animatedNodes) {
tree.vertices.toList()
} else {
tree.vertices.map { (tex, list) -> tex to list.map { matrix.transform(it) } }
}
val map = mutableMapOf<ResourceLocation, MutableList<Vertex>>()
// join duplicated pairs (groups of vertex with the same texture)
childrenVertex.forEach { (tex, vertex) ->
if (tex in map) {
map[tex]!!.addAll(vertex)
} else {
map[tex] = vertex.toMutableList()
}
}
thisVertex.forEach { (tex, vertex) ->
if (tex in map) {
map[tex]!!.addAll(vertex)
} else {
map[tex] = vertex.toMutableList()
}
}
val allAnimated = animated + nonAnimated.filter { it.dynamic.isNotEmpty() }.map { it.copy(static = emptyList()) }
return CompactNode(tree.id, tree.transform.toImmutable(), allAnimated, map.map { VertexGroup(it.key, it.value) })
}
private fun CompactNode.toAnimated(): AnimatedNode {
val caches = static.map { (tex, vertex) ->
TextureModelCache(tex, ModelCache { renderVertex(vertex) })
}
return AnimatedNode(
index = index,
transform = transform,
children = dynamic.map { it.toAnimated() },
cache = if (caches.size == 1) caches.first() else ModelGroupCache(*caches.toTypedArray())
)
}
private fun renderVertex(vertex: List<Vertex>) {
val tessellator = Tessellator.getInstance()
val buffer = tessellator.buffer
buffer.apply {
begin(GL11.GL_QUADS, DefaultVertexFormats.OLDMODEL_POSITION_TEX_NORMAL)
setTranslation(0.0, 0.0, 0.0)
vertex.forEach {
pos(it.x.toDouble(), it.y.toDouble(), it.z.toDouble())
.tex(it.u.toDouble(), it.v.toDouble())
.normal(it.xn, it.yn, it.zn)
.endVertex()
}
tessellator.draw()
}
}
private fun Matrix4f.transform(vertex: Vertex): Vertex {
val pos = Point3f(vertex.x, vertex.y, vertex.z)
transform(pos)
return vertex.copy(x = pos.x, y = pos.y, z = pos.z)
}
} | gpl-2.0 | f00743df2b5b8ed396efcc0625413ead | 34.772358 | 121 | 0.590361 | 4.254352 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/ui/note/NoteBuilder.kt | 1 | 4754 | package com.orgzly.android.ui.note
import android.content.Context
import com.orgzly.android.db.entity.NoteProperty
import com.orgzly.android.db.entity.NoteView
import com.orgzly.android.prefs.AppPreferences
import com.orgzly.android.ui.NoteStates
import com.orgzly.android.util.EventsInNote
import com.orgzly.android.util.OrgFormatter
import com.orgzly.org.OrgProperties
import com.orgzly.org.datetime.OrgDateTime
import com.orgzly.org.datetime.OrgRange
import com.orgzly.org.utils.StateChangeLogic
import java.util.*
class NoteBuilder {
companion object {
@JvmStatic
fun changeState(context: Context, notePayload: NotePayload, state: String?): NotePayload {
val doneKeywords = AppPreferences.doneKeywordsSet(context)
var title = notePayload.title
var content = notePayload.content
val properties = notePayload.properties
val eventsInNote = EventsInNote(title, content)
val scl = StateChangeLogic(doneKeywords)
scl.setState(
state,
notePayload.state,
OrgRange.parseOrNull(notePayload.scheduled),
OrgRange.parseOrNull(notePayload.deadline),
eventsInNote.timestamps.map { OrgRange(it) })
if (scl.isShifted) {
eventsInNote.replaceEvents(scl.timestamps).apply {
title = first
content = second
}
val now = OrgDateTime(false).toString()
// Set last-repeat property
if (AppPreferences.setLastRepeatOnTimeShift(context)) {
properties.set(OrgFormatter.LAST_REPEAT_PROPERTY, now)
}
// Log state change
if (AppPreferences.logOnTimeShift(context)) {
val logEntry = OrgFormatter.stateChangeLine(notePayload.state, state, now)
content = OrgFormatter.insertLogbookEntryLine(content, logEntry)
}
}
return notePayload.copy(
title = title,
content = content,
state = scl.state,
scheduled = scl.scheduled?.toString(),
deadline = scl.deadline?.toString(),
closed = scl.closed?.toString(),
properties = properties
)
}
// fun newRootNote(bookId: Long): Note {
// val note = Note()
//
// val position = note.position
//
// position.setBookId(bookId)
// position.setLevel(0)
// position.setLft(1)
// position.setRgt(2)
//
// return note
// }
fun newPayload(noteView: NoteView, properties: List<NoteProperty>): NotePayload {
return NotePayload(
noteView.note.title,
noteView.note.content,
noteView.note.state,
noteView.note.priority,
noteView.scheduledRangeString,
noteView.deadlineRangeString,
noteView.closedRangeString,
noteView.note.getTagsList(),
OrgProperties().apply { properties.forEach { put(it.name, it.value) } })
}
@JvmStatic
fun newPayload(context: Context, title: String, content: String?): NotePayload {
val scheduled = initialScheduledTime(context)
val state = initialState(context)
return NotePayload(
title = title,
content = content,
state = state,
scheduled = scheduled
)
}
private fun initialScheduledTime(context: Context): String? {
return if (AppPreferences.isNewNoteScheduled(context)) {
val cal = Calendar.getInstance()
val timestamp = OrgDateTime.Builder()
.setIsActive(true)
.setYear(cal.get(Calendar.YEAR))
.setMonth(cal.get(Calendar.MONTH))
.setDay(cal.get(Calendar.DAY_OF_MONTH))
.build()
OrgRange(timestamp).toString()
} else {
null
}
}
private fun initialState(context: Context): String? {
AppPreferences.newNoteState(context).let {
return if (NoteStates.isKeyword(it)) {
it
} else {
null
}
}
}
private val TAG = NoteBuilder::class.java.name
}
} | gpl-3.0 | a3473b7ba124153ad90448e217e230f3 | 31.568493 | 98 | 0.537863 | 5.06823 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/test/testdata/inspections/flushInsideLoop/Test2.kt | 1 | 599 | package flushInsideLoop
import com.badlogic.gdx.graphics.g2d.PolygonSpriteBatch
import com.badlogic.gdx.graphics.g2d.SpriteBatch
class Clazz {
var i: Int = 0
get() {
PolygonSpriteBatch().flush()
return 1
}
var j: Int = 0
set(value) {
PolygonSpriteBatch().flush()
j = value
}
fun bla() {
PolygonSpriteBatch().flush()
}
}
class Clazz1 {
init {
SpriteBatch().transformMatrix = null
}
}
class Clazz2 {
constructor() {
}
@Suppress("UNUSED_PARAMETER")
constructor(str: String) {
SpriteBatch().transformMatrix = null
}
} | apache-2.0 | ecbdbfd451259eb215707a7067736494 | 12.953488 | 55 | 0.631052 | 3.652439 | false | false | false | false |
EndlessCodeGroup/BukkitGradle | src/main/kotlin/meta/util/StringUtils.kt | 1 | 703 | package ru.endlesscode.bukkitgradle.meta.util
internal object StringUtils {
/** Converts [text] to PascalCase. */
@JvmStatic
fun toPascalCase(text: String): String {
val camelCaseText = text.replace(Regex("[ _-]([A-Za-z0-9])")) { match -> match.groupValues[1].toUpperCase() }
return camelCaseText.capitalize()
}
@JvmStatic
fun parseApiVersion(version: String): String? {
val versionParts = version.split('.').mapNotNull { it.toIntOrNull() }
require(versionParts.size in 2..3) { "Unable to parse API version '$version'." }
val (major, minor) = versionParts
return if (major >= 1 && minor >= 13) "$major.$minor" else null
}
}
| mit | 0ab7555cbb497d37aa0617fb2e279432 | 36 | 117 | 0.634424 | 3.905556 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/lists/database/SgListHelper.kt | 1 | 4873 | package com.battlelancer.seriesguide.lists.database
import androidx.annotation.VisibleForTesting
import androidx.lifecycle.LiveData
import androidx.room.ColumnInfo
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.RawQuery
import androidx.room.Transaction
import androidx.sqlite.db.SupportSQLiteQuery
import com.battlelancer.seriesguide.provider.SeriesGuideContract.ListItemTypes
import com.battlelancer.seriesguide.provider.SeriesGuideContract.ListItems
import com.battlelancer.seriesguide.provider.SeriesGuideContract.Lists
import com.battlelancer.seriesguide.provider.SeriesGuideContract.SgShow2Columns
import com.battlelancer.seriesguide.shows.database.SgShow2
import com.battlelancer.seriesguide.shows.tools.ShowStatus
@Dao
interface SgListHelper {
@Query("SELECT * FROM lists ORDER BY ${Lists.SORT_ORDER_THEN_NAME}")
fun getListsForDisplay(): LiveData<List<SgList>>
@Query("SELECT * FROM lists ORDER BY ${Lists.SORT_ORDER_THEN_NAME}")
fun getListsForExport(): List<SgList>
@Query("SELECT * FROM listitems WHERE item_ref_id = :tmdbId AND item_type = ${ListItemTypes.TMDB_SHOW}")
fun getListItemsWithTmdbId(tmdbId: Int): List<SgListItem>
@RawQuery(observedEntities = [SgListItem::class, SgShow2::class])
fun getListItemsWithDetails(query: SupportSQLiteQuery): LiveData<List<SgListItemWithDetails>>
@Query("SELECT * FROM listitems WHERE list_id = :listId")
fun getListItemsForExport(listId: String): List<SgListItem>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertListItems(listItems: List<SgListItem>)
@Query("SELECT * FROM listitems WHERE item_type = ${ListItemTypes.TVDB_SHOW}")
fun getTvdbShowListItems(): List<SgListItem>
@Query("DELETE FROM listitems WHERE list_item_id = :listItemId")
fun deleteListItem(listItemId: String)
@Transaction
fun deleteListItems(listItemIds: List<String>) {
listItemIds.forEach {
deleteListItem(it)
}
}
/**
* By default the database inserts a first list when being created, d
*/
@VisibleForTesting
@Query("DELETE FROM lists")
fun deleteAllLists()
}
// Compare with SeriesGuideDatabase.Tables.LIST_ITEMS_WITH_DETAILS
data class SgListItemWithDetails(
@ColumnInfo(name = ListItems._ID) val id: Long,
@ColumnInfo(name = ListItems.LIST_ITEM_ID) val listItemId: String,
@ColumnInfo(name = Lists.LIST_ID) val listId: String,
@ColumnInfo(name = ListItems.TYPE) val type: Int,
@ColumnInfo(name = ListItems.ITEM_REF_ID) val itemRefId: String,
@ColumnInfo(name = SgShow2Columns.REF_SHOW_ID) val showId: Long,
@ColumnInfo(name = SgShow2Columns.RELEASE_TIME) val releaseTime: Int?,
@ColumnInfo(name = SgShow2Columns.NEXTTEXT) val nextText: String?,
@ColumnInfo(name = SgShow2Columns.NEXTAIRDATEMS) val nextAirdateMs: Long,
@ColumnInfo(name = SgShow2Columns.TITLE) val title: String,
@ColumnInfo(name = SgShow2Columns.TITLE_NOARTICLE) val titleNoArticle: String?,
@ColumnInfo(name = SgShow2Columns.POSTER_SMALL) val posterSmall: String?,
@ColumnInfo(name = SgShow2Columns.NETWORK) val network: String?,
@ColumnInfo(name = SgShow2Columns.STATUS) val status: Int?,
@ColumnInfo(name = SgShow2Columns.FAVORITE) var favorite: Boolean,
@ColumnInfo(name = SgShow2Columns.RELEASE_WEEKDAY) val releaseWeekDay: Int?,
@ColumnInfo(name = SgShow2Columns.RELEASE_TIMEZONE) val releaseTimeZone: String?,
@ColumnInfo(name = SgShow2Columns.RELEASE_COUNTRY) val releaseCountry: String?,
@ColumnInfo(name = SgShow2Columns.LASTWATCHED_MS) val lastWatchedMs: Long,
@ColumnInfo(name = SgShow2Columns.UNWATCHED_COUNT) val unwatchedCount: Int,
) {
val releaseTimeOrDefault: Int
get() = releaseTime ?: -1
val releaseWeekDayOrDefault: Int
get() = releaseWeekDay ?: -1
val statusOrUnknown: Int
get() = status ?: ShowStatus.UNKNOWN
companion object {
const val SELECT = "SELECT ${ListItems._ID}," +
"${ListItems.LIST_ITEM_ID}," +
"${ListItems.ITEM_REF_ID}," +
"${ListItems.TYPE}," +
"${SgShow2Columns.REF_SHOW_ID}," +
"${SgShow2Columns.TITLE}," +
"${SgShow2Columns.POSTER_SMALL}," +
"${SgShow2Columns.NETWORK}," +
"${SgShow2Columns.RELEASE_TIME}," +
"${SgShow2Columns.RELEASE_WEEKDAY}," +
"${SgShow2Columns.RELEASE_TIMEZONE}," +
"${SgShow2Columns.RELEASE_COUNTRY}," +
"${SgShow2Columns.STATUS}," +
"${SgShow2Columns.NEXTTEXT}," +
"${SgShow2Columns.NEXTAIRDATEMS}," +
"${SgShow2Columns.FAVORITE}," +
SgShow2Columns.UNWATCHED_COUNT
}
}
| apache-2.0 | 1d7b238e329f9c21915578f8a65cc790 | 42.123894 | 109 | 0.702237 | 4.204487 | false | false | false | false |
AlmasB/FXGL | fxgl-gameplay/src/main/kotlin/com/almasb/fxgl/trade/view/TradeView.kt | 1 | 926 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.trade.view
import javafx.scene.Parent
import javafx.scene.control.Tab
import javafx.scene.control.TabPane
/**
*
* @author Almas Baimagambetov ([email protected])
*/
class TradeView<T>(val playerShopView: ShopView<T>, val npcShopView: ShopView<T>) : Parent() {
val tabPane = TabPane()
init {
tabPane.styleClass.addAll("fxgl-trade-tab-pane")
stylesheets.add(javaClass.getResource("fxgl_trade.css").toExternalForm())
val tab1 = Tab("Sell")
tab1.content = playerShopView
tab1.isClosable = false
val tab2 = Tab("Buy")
tab2.content = npcShopView
tab2.isClosable = false
tabPane.tabs.addAll(
tab1,
tab2
)
children += tabPane
}
} | mit | 3e4976e8c3df487112a4c72c42ec67ef | 21.609756 | 94 | 0.62743 | 3.674603 | false | false | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/Scene.kt | 1 | 6754 | /*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle
import uk.co.nickthecoder.tickle.graphics.Color
import uk.co.nickthecoder.tickle.graphics.Renderer
import uk.co.nickthecoder.tickle.resources.Resources
import uk.co.nickthecoder.tickle.stage.FlexPosition
import uk.co.nickthecoder.tickle.stage.Stage
import uk.co.nickthecoder.tickle.stage.StageView
import uk.co.nickthecoder.tickle.stage.View
class Scene {
var background: Color = Color.black()
var showMouse: Boolean = true
val stages = mutableMapOf<String, Stage>()
internal val views = mutableMapOf<String, View>()
private val autoPositions = mutableMapOf<String, FlexPosition>()
private var orderedViews: List<View>? = null
fun stages() = stages.values
fun views(): Collection<View> = orderedViews ?: views.values
fun findStage(name: String) = stages[name]
fun findView(name: String) = views[name]
fun findStageView(name: String): StageView? {
val view = findView(name)
if (view is StageView) {
return view
} else {
return null
}
}
fun findActorById(id: Int): Actor? {
stages().forEach {
val result = it.findActorById(id)
if (result != null) {
return result
}
}
return null
}
/**
* Changes the size of the view based on the size in GameInfo. This is done when the scene is first loaded.
* Note that [View.changeRect] is NOT called, so the actors are NOT adjusted based on their alignment.
*/
private fun layoutToGameInfo() {
val gi = Resources.instance.gameInfo
autoPositions.forEach { name, position ->
views[name]?.rect = position.calculateRectangle(gi.width, gi.height)
}
}
/**
* Lays out the Views, expanding, or contracting them to fit into the window without margins and without scaling.
*/
fun layoutToFit() {
val window = Game.instance.window
autoPositions.forEach { name, position ->
views[name]?.changeRect(position.calculateRectangle(window.width, window.height))
}
}
/**
* Lays out the Views, keeping them at the size defined in GameInfo centered in the middle of the screen.
* Therefore if the size in GameInfo is smaller than the window size, then there will be blank margins.
*/
fun layoutWithMargins() {
val gameInfo = Resources.instance.gameInfo
val window = Game.instance.window
val dx = (window.width - gameInfo.width) / 2
val dy = (window.height - gameInfo.height) / 2
autoPositions.forEach { name, position ->
views[name]?.let { view ->
val rect = position.calculateRectangle(gameInfo.width, gameInfo.height)
rect.left += dx
rect.right += dx
rect.top += dy
rect.bottom += dy
view.changeRect(rect)
}
}
}
fun addView(name: String, view: View, position: FlexPosition? = null) {
views[name] = view
position?.let {
autoPositions[name] = it
}
}
fun removeView(name: String) {
views.remove(name)
autoPositions.remove(name)
}
fun begin() {
Game.instance.window.showMouse(showMouse)
Game.instance.director.createWorlds()
stages.values.forEach { stage ->
val world = stage.world
if (world != null) {
stage.actors.forEach { actor ->
actor.costume.bodyDef?.let { bodyDef ->
world.createBody(bodyDef, actor)
}
}
}
stage.begin()
}
layoutToGameInfo()
Game.instance.producer.layout()
orderedViews = views.values.sortedBy { it.zOrder }
}
fun activated() {
stages.values.forEach { stage ->
stage.activated()
}
}
fun end() {
stages.values.forEach { stage ->
stage.end()
}
}
fun draw(renderer: Renderer) {
// println("Rendering scene rects=${views.values.map { it.rect }} #actors=${views.values.filterIsInstance<StageView>().map { it.stage.actors.size }}")
renderer.clearColor(background)
renderer.clear()
orderedViews?.forEach { view ->
renderer.beginView()
view.draw(renderer)
renderer.endView()
}
}
internal fun merge(extraScene: Scene) {
extraScene.stages.forEach { stageName, extraStage ->
val existingStage = stages[stageName]
if (existingStage == null) {
stages[stageName] = extraStage
} else {
if (existingStage.javaClass !== extraStage.javaClass) {
System.err.println("WARNING. Mering stage $stageName with a stage of the same name, but a different class")
}
// TODO Add warning if they have different StageConstraints when StageConstraints are implemented.
extraStage.actors.toList().forEach { actor ->
existingStage.add(actor)
}
}
}
extraScene.views.forEach { viewName, view ->
if (view is StageView) {
if (stages().contains(view.stage)) {
if (views.containsKey(viewName)) {
System.err.println("WARNING. Duplicate view '$viewName' ignored while merging scene.")
} else {
addView(viewName, view, extraScene.autoPositions[viewName])
}
} else {
// Do nothing. We don't need to include views for stages whose actors have been moved to an
// existing stage.
}
} else {
if (!views.containsKey(viewName)) {
addView(viewName, view, extraScene.autoPositions[viewName])
}
}
}
}
}
| gpl-3.0 | caadb9811f2f98c646399aebec3d79f9 | 31.628019 | 158 | 0.589873 | 4.578983 | false | false | false | false |
sdeleuze/reactor-core | reactor-core/src/main/kotlin/reactor/core/publisher/MonoExtensions.kt | 1 | 3641 | /*
* Copyright (c) 2011-2017 Pivotal Software Inc, All Rights Reserved.
*
* 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 reactor.core.publisher
import org.reactivestreams.Publisher
import java.util.concurrent.Callable
import java.util.concurrent.CompletableFuture
import java.util.function.Supplier
import kotlin.reflect.KClass
/**
* Extension to convert any [Publisher] of [T] to a [Mono] that only emits its first
* element.
*
* Note this extension doesn't make much sense on a [Mono] but it won't be converted so it
* doesn't hurt.
*
* @author Simon Baslé
* @since 3.1.1
*/
fun <T> Publisher<T>.toMono(): Mono<T> = Mono.from(this)
/**
* Extension to convert any [Supplier] of [T] to a [Mono] that emits supplied element.
*
* @author Sergio Dos Santos
*/
fun <T> (() -> T?).toMono(): Mono<T> = Mono.fromSupplier(this)
/**
* Extension for transforming an object to a [Mono].
*
* @author Sebastien Deleuze
* @since 3.1
*/
fun <T : Any> T.toMono(): Mono<T> = Mono.just(this)
/**
* Extension for transforming an [CompletableFuture] to a [Mono].
*
* @author Sebastien Deleuze
* @since 3.1
*/
fun <T> CompletableFuture<out T?>.toMono(): Mono<T> = Mono.fromFuture(this)
/**
* Extension for transforming an [Callable] to a [Mono].
*
* @author Sebastien Deleuze
* @since 3.1
*/
fun <T> Callable<T?>.toMono(): Mono<T> = Mono.fromCallable(this::call)
/**
* Extension for transforming an exception to a [Mono] that completes with the specified error.
*
* @author Sebastien Deleuze
* @since 3.1
*/
fun <T> Throwable.toMono(): Mono<T> = Mono.error(this)
/**
* Extension for [Mono.cast] providing a `cast<Foo>()` variant.
*
* @author Sebastien
* @since 3.1
*/
inline fun <reified T : Any> Mono<*>.cast(): Mono<T> = cast(T::class.java)
/**
* Extension for [Mono.doOnError] providing a [KClass] based variant.
*
* @author Sebastien Deleuze
* @since 3.1
*/
fun <T, E : Throwable> Mono<T>.doOnError(exceptionType: KClass<E>, onError: (E) -> Unit): Mono<T> =
doOnError(exceptionType.java, { onError(it) })
/**
* Extension for [Mono.onErrorMap] providing a [KClass] based variant.
*
* @author Sebastien Deleuze
* @since 3.1
*/
fun <T, E : Throwable> Mono<T>.onErrorMap(exceptionType: KClass<E>, mapper: (E) -> Throwable): Mono<T> =
onErrorMap(exceptionType.java, { mapper(it) })
/**
* Extension for [Mono.ofType] providing a `ofType<Foo>()` variant.
*
* @author Sebastien Deleuze
* @since 3.1
*/
inline fun <reified T : Any> Mono<*>.ofType(): Mono<T> = ofType(T::class.java)
/**
* Extension for [Mono.onErrorResume] providing a [KClass] based variant.
*
* @author Sebastien Deleuze
* @since 3.1
*/
fun <T : Any, E : Throwable> Mono<T>.onErrorResume(exceptionType: KClass<E>, fallback: (E) -> Mono<T>): Mono<T> =
onErrorResume(exceptionType.java, { fallback(it) })
/**
* Extension for [Mono.onErrorReturn] providing a [KClass] based variant.
*
* @author Sebastien Deleuze
* @since 3.1
*/
fun <T : Any, E : Throwable> Mono<T>.onErrorReturn(exceptionType: KClass<E>, value: T): Mono<T> =
onErrorReturn(exceptionType.java, value)
| apache-2.0 | e392e3f73e4ac088e042069e0f3f368a | 27.888889 | 113 | 0.679396 | 3.367253 | false | false | false | false |
nt-ca-aqe/library-app | library-service/src/main/kotlin/library/service/api/ErrorHandlers.kt | 1 | 5933 | package library.service.api
import library.service.business.exceptions.MalformedValueException
import library.service.business.exceptions.NotFoundException
import library.service.business.exceptions.NotPossibleException
import library.service.correlation.CorrelationIdHolder
import library.service.logging.logger
import org.springframework.http.HttpStatus
import org.springframework.http.converter.HttpMessageNotReadableException
import org.springframework.security.access.AccessDeniedException
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseStatus
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException
import java.time.Clock
import java.time.OffsetDateTime
import javax.servlet.http.HttpServletRequest
/**
* Defines a number of commonly used exception handlers for REST endpoints.
*
* This includes basic handlers for common business exceptions like:
* - [NotFoundException]
* - [NotPossibleException]
* - [MalformedValueException]
*
* As well as a number of framework exceptions related to bad user input.
*
* This class should _not_ contain any domain specific exception handlers.
* Those need to be defined in the corresponding controller!
*/
@RestControllerAdvice
class ErrorHandlers(
private val clock: Clock,
private val correlationIdHolder: CorrelationIdHolder
) {
private val log = ErrorHandlers::class.logger
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NotFoundException::class)
fun handle(e: NotFoundException): ErrorDescription {
log.debug("received request for non existing resource:", e)
return errorDescription(
httpStatus = HttpStatus.NOT_FOUND,
message = e.message!!
)
}
@ResponseStatus(HttpStatus.CONFLICT)
@ExceptionHandler(NotPossibleException::class)
fun handle(e: NotPossibleException): ErrorDescription {
log.debug("received conflicting request:", e)
return errorDescription(
httpStatus = HttpStatus.CONFLICT,
message = e.message!!
)
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MalformedValueException::class)
fun handle(e: MalformedValueException): ErrorDescription {
log.debug("received malformed request:", e)
return errorDescription(
httpStatus = HttpStatus.BAD_REQUEST,
message = e.message!!
)
}
/** In case the request parameter has wrong type. */
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentTypeMismatchException::class)
fun handle(e: MethodArgumentTypeMismatchException): ErrorDescription {
log.debug("received bad request:", e)
return errorDescription(
httpStatus = HttpStatus.BAD_REQUEST,
message = "The request's '${e.name}' parameter is malformed."
)
}
/** In case the request body is malformed or non existing. */
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException::class)
fun handle(e: HttpMessageNotReadableException): ErrorDescription {
log.debug("received bad request:", e)
return errorDescription(
httpStatus = HttpStatus.BAD_REQUEST,
message = "The request's body could not be read. It is either empty or malformed."
)
}
/** In case a validation on a request body property fails */
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException::class)
fun handle(e: MethodArgumentNotValidException): ErrorDescription {
log.debug("received bad request:", e)
val fieldDetails = e.bindingResult.fieldErrors.map { "The field '${it.field}' ${it.defaultMessage}." }
val globalDetails = e.bindingResult.globalErrors.map { it.defaultMessage }
val details = fieldDetails + globalDetails
val sortedDetails = details.sorted()
return errorDescription(
httpStatus = HttpStatus.BAD_REQUEST,
message = "The request's body is invalid. See details...",
details = sortedDetails
)
}
@ResponseStatus(HttpStatus.FORBIDDEN)
@ExceptionHandler(AccessDeniedException::class)
fun handle(e: AccessDeniedException, request: HttpServletRequest): ErrorDescription {
val userName = SecurityContextHolder.getContext()?.authentication?.name
log.debug("blocked illegal access from user [{}]: {} {}", userName, request.method, request.requestURI)
return errorDescription(
httpStatus = HttpStatus.FORBIDDEN,
message = "You don't have the necessary rights to to this."
)
}
/** In case any other exception occurs. */
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception::class)
fun handle(e: Exception): ErrorDescription {
log.error("internal server error occurred:", e)
return errorDescription(
httpStatus = HttpStatus.INTERNAL_SERVER_ERROR,
message = "An internal server error occurred, see server logs for more information."
)
}
private fun errorDescription(
httpStatus: HttpStatus,
message: String,
details: List<String> = emptyList()
) = ErrorDescription(
status = httpStatus.value(),
error = httpStatus.reasonPhrase,
timestamp = OffsetDateTime.now(clock).toString(),
correlationId = correlationIdHolder.get(),
message = message,
details = details
)
} | apache-2.0 | 779391fe5e368cdc44509ec0208f9a7f | 39.367347 | 111 | 0.700489 | 5.062287 | false | false | false | false |
cliffano/swaggy-jenkins | clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/EmptyChangeLogSet.kt | 1 | 865 | package org.openapitools.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonProperty
import javax.validation.constraints.DecimalMax
import javax.validation.constraints.DecimalMin
import javax.validation.constraints.Email
import javax.validation.constraints.Max
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
import javax.validation.constraints.Pattern
import javax.validation.constraints.Size
import javax.validation.Valid
import io.swagger.v3.oas.annotations.media.Schema
/**
*
* @param propertyClass
* @param kind
*/
data class EmptyChangeLogSet(
@Schema(example = "null", description = "")
@field:JsonProperty("_class") val propertyClass: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("kind") val kind: kotlin.String? = null
) {
}
| mit | dfaf1e2e1a74b0e950fa045eaa641aed | 26.903226 | 75 | 0.780347 | 4.119048 | false | false | false | false |
Bombe/Sone | src/test/kotlin/net/pterodactylus/sone/main/SoneModuleTest.kt | 1 | 7113 | package net.pterodactylus.sone.main
import com.codahale.metrics.*
import com.google.common.base.*
import com.google.common.eventbus.*
import com.google.inject.Guice.*
import com.google.inject.Injector
import com.google.inject.name.Names.*
import freenet.clients.http.SessionManager
import freenet.l10n.*
import net.pterodactylus.sone.core.*
import net.pterodactylus.sone.database.*
import net.pterodactylus.sone.database.memory.*
import net.pterodactylus.sone.freenet.*
import net.pterodactylus.sone.freenet.plugin.*
import net.pterodactylus.sone.freenet.wot.*
import net.pterodactylus.sone.test.*
import net.pterodactylus.sone.web.SessionProvider
import net.pterodactylus.util.config.*
import net.pterodactylus.util.version.Version
import org.hamcrest.MatcherAssert.*
import org.hamcrest.Matchers.*
import org.junit.experimental.categories.*
import org.mockito.Mockito.*
import java.io.*
import java.util.concurrent.*
import java.util.concurrent.atomic.*
import kotlin.test.*
const val versionString = "v80"
@Category(NotParallel::class)
class SoneModuleTest {
private val currentDir: File = File(".")
private val pluginVersion = Version("", 80)
private val pluginYear = 2019
private val pluginHomepage = "home://page"
private val l10n = deepMock<PluginL10n>()
private val sonePlugin = mock<SonePlugin>().apply {
whenever(version).thenReturn(versionString)
whenever(year).thenReturn(pluginYear)
whenever(homepage).thenReturn(pluginHomepage)
whenever(l10n()).thenReturn(l10n)
}
private val injector by lazy { createInjector() }
@AfterTest
fun removePropertiesFromCurrentDirectory() {
File(currentDir, "sone.properties").delete()
}
@Test
fun `creator binds configuration when no file is present`() {
File(currentDir, "sone.properties").delete()
assertThat(injector.getInstance<Configuration>(), notNullValue())
}
@Test
fun `creator binds first start to true when no file is present`() {
File(currentDir, "sone.properties").delete()
assertThat(injector.getInstance(named("FirstStart")), equalTo(true))
}
@Test
fun `config file is created in current directory if not present`() {
File(currentDir, "sone.properties").delete()
val configuration = injector.getInstance<Configuration>()
configuration.save()
assertThat(File(currentDir, "sone.properties").exists(), equalTo(true))
}
@Test
fun `creator binds configuration when file is present`() {
File(currentDir, "sone.properties").writeText("Option=old")
assertThat(injector.getInstance<Configuration>().getStringValue("Option").value, equalTo("old"))
}
@Test
fun `creator binds first start to false when file is present`() {
File(currentDir, "sone.properties").writeText("Option=old")
assertThat(injector.getInstance(named("FirstStart")), equalTo(false))
}
@Test
fun `invalid config file leads to new config being created`() {
File(currentDir, "sone.properties").writeText("Option=old\nbroken")
val configuration = injector.getInstance<Configuration>()
assertThat(configuration.getStringValue("Option").getValue(null), nullValue())
}
@Test
fun `invalid config file leads to new config being set to true`() {
File(currentDir, "sone.properties").writeText("Option=old\nbroken")
assertThat(injector.getInstance(named("NewConfig")), equalTo(true))
}
@Test
fun `valid config file leads to new config being set to false`() {
File(currentDir, "sone.properties").writeText("Option=old")
assertThat(injector.getInstance(named("NewConfig")), equalTo(false))
}
@Test
fun `event bus is bound`() {
assertThat(injector.getInstance<EventBus>(), notNullValue())
}
@Test
fun `context is bound`() {
assertThat(injector.getInstance<Context>().context, equalTo("Sone"))
}
@Test
fun `optional context is bound`() {
assertThat(injector.getInstance<Optional<Context>>().get().context, equalTo("Sone"))
}
@Test
fun `sone plugin is bound`() {
assertThat(injector.getInstance(), sameInstance(sonePlugin))
}
@Test
fun `version is bound`() {
assertThat(injector.getInstance(), equalTo(pluginVersion))
}
@Test
fun `plugin version is bound`() {
assertThat(injector.getInstance(), equalTo(PluginVersion(versionString)))
}
@Test
fun `plugin year is bound`() {
assertThat(injector.getInstance(), equalTo(PluginYear(pluginYear)))
}
@Test
fun `plugin homepage in bound`() {
assertThat(injector.getInstance(), equalTo(PluginHomepage(pluginHomepage)))
}
@Test
fun `database is bound correctly`() {
assertThat(injector.getInstance<Database>(), instanceOf(MemoryDatabase::class.java))
}
@Test
fun `translation is bound correctly`() {
assertThat(injector.getInstance<Translation>(), notNullValue())
}
@Test
fun `default loader is used without dev options`() {
assertThat(injector.getInstance<Loaders>(), instanceOf(DefaultLoaders::class.java))
}
@Test
fun `default loaders are used if no path is given`() {
File(currentDir, "sone.properties").writeText("Developer.LoadFromFilesystem=true")
assertThat(injector.getInstance<Loaders>(), instanceOf(DefaultLoaders::class.java))
}
@Test
fun `debug loaders are used if path is given`() {
File(currentDir, "sone.properties").writeText("Developer.LoadFromFilesystem=true\nDeveloper.FilesystemPath=/tmp")
assertThat(injector.getInstance<Loaders>(), instanceOf(DebugLoaders::class.java))
}
class TestObject {
val ref: AtomicReference<Any?> = AtomicReference()
@Subscribe
fun testEvent(event: Any?) {
ref.set(event)
}
}
@Test
fun `created objects are registered with event bus`() {
val eventBus: EventBus = injector.getInstance()
val testObject = injector.getInstance<TestObject>()
val event = Any()
eventBus.post(event)
assertThat(testObject.ref.get(), sameInstance(event))
}
@Test
fun `core is created as singleton`() {
injector.verifySingletonInstance<Core>()
}
@Test
fun `core is registered with event bus`() {
val eventBus = mock<EventBus>()
val injector = createInjector(eventBus)
val core = injector.getInstance<Core>()
verify(eventBus).register(core)
}
private fun createInjector(eventBus: EventBus = EventBus()): Injector =
createInjector(
SoneModule(sonePlugin, eventBus),
FreenetInterface::class.isProvidedByDeepMock(),
PluginRespiratorFacade::class.isProvidedByDeepMock(),
PluginConnector::class.isProvidedByDeepMock(),
SessionManager::class.isProvidedByMock()
)
@Test
fun `metrics registry is created as singleton`() {
injector.verifySingletonInstance<MetricRegistry>()
}
@Test
fun `wot connector is created as singleton`() {
injector.verifySingletonInstance<WebOfTrustConnector>()
}
@Test
fun `notification ticker is created as singleton`() {
injector.verifySingletonInstance<ScheduledExecutorService>(named("notification"))
}
@Test
fun `ticker shutdown is created as singleton`() {
injector.verifySingletonInstance<TickerShutdown>()
}
@Test
fun `sone URI creator is created as singleton`() {
injector.verifySingletonInstance<SoneUriCreator>()
}
@Test
fun `session provider is created as singleton`() {
injector.verifySingletonInstance<SessionProvider>()
}
}
| gpl-3.0 | 2107745eedc1076de811c220a00f9fcf | 28.514523 | 115 | 0.746239 | 3.765484 | false | true | false | false |
ruuvi/Android_RuuvitagScanner | app/src/main/java/com/ruuvi/station/firebase/domain/FirebasePropertiesSaver.kt | 1 | 2942 | package com.ruuvi.station.firebase.domain
import com.google.firebase.analytics.FirebaseAnalytics
import com.ruuvi.station.app.preferences.PreferencesRepository
import com.ruuvi.station.tag.domain.TagInteractor
import com.ruuvi.station.util.BackgroundScanModes
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import timber.log.Timber
import java.lang.Exception
class FirebasePropertiesSaver(
private val firebaseAnalytics: FirebaseAnalytics,
private val preferences: PreferencesRepository,
private val tagInteractor: TagInteractor
) {
fun saveUserProperties() {
CoroutineScope(Dispatchers.IO).launch {
Timber.d("FirebasePropertySaver.saveUserProperties")
try {
firebaseAnalytics.setUserProperty("background_scan_enabled",
(preferences.getBackgroundScanMode() == BackgroundScanModes.BACKGROUND).toString())
firebaseAnalytics.setUserProperty("background_scan_interval", preferences.getBackgroundScanInterval().toString())
firebaseAnalytics.setUserProperty("gateway_enabled", preferences.getGatewayUrl().isNotEmpty().toString())
firebaseAnalytics.setUserProperty("temperature_unit", preferences.getTemperatureUnit().code)
firebaseAnalytics.setUserProperty("humidity_unit", preferences.getHumidityUnit().code.toString())
firebaseAnalytics.setUserProperty("pressure_unit", preferences.getPressureUnit().code.toString())
firebaseAnalytics.setUserProperty("dashboard_enabled", preferences.isDashboardEnabled().toString())
firebaseAnalytics.setUserProperty("graph_point_interval", preferences.getGraphPointInterval().toString())
firebaseAnalytics.setUserProperty("graph_view_period", preferences.getGraphViewPeriodDays().toString())
firebaseAnalytics.setUserProperty("graph_show_all_points", preferences.isShowAllGraphPoint().toString())
firebaseAnalytics.setUserProperty("graph_draw_dots", preferences.graphDrawDots().toString())
val addedTags = tagInteractor.getTagEntities(true).size
val notAddedTags = tagInteractor.getTagEntities(false).size
val seenTags = addedTags + notAddedTags
if (seenTags < 10) {
firebaseAnalytics.setUserProperty("seen_tags", (addedTags + notAddedTags).toString())
} else {
firebaseAnalytics.setUserProperty("seen_tags", "10+")
}
if (addedTags < 10) {
firebaseAnalytics.setUserProperty("added_tags", addedTags.toString())
} else {
firebaseAnalytics.setUserProperty("added_tags", "10+")
}
} catch (e: Exception) {
Timber.e(e)
}
}
}
} | mit | a9b6db124e57df5b3ff02f4315246575 | 51.553571 | 129 | 0.680829 | 5.60381 | false | false | false | false |
vhromada/Catalog-Spring | src/main/kotlin/cz/vhromada/catalog/web/mapper/impl/GameMapperImpl.kt | 1 | 1756 | package cz.vhromada.catalog.web.mapper.impl
import cz.vhromada.catalog.entity.Game
import cz.vhromada.catalog.web.fo.GameFO
import cz.vhromada.catalog.web.mapper.GameMapper
import org.springframework.stereotype.Component
/**
* A class represents implementation of mapper for games.
*
* @author Vladimir Hromada
*/
@Component("webGameMapper")
class GameMapperImpl : GameMapper {
override fun map(source: Game): GameFO {
return GameFO(id = source.id,
name = source.name,
wikiEn = source.wikiEn,
wikiCz = source.wikiCz,
mediaCount = source.mediaCount!!.toString(),
crack = source.crack,
serialKey = source.serialKey,
patch = source.patch,
trainer = source.trainer,
trainerData = source.trainerData,
editor = source.editor,
saves = source.saves,
otherData = source.otherData,
note = source.note,
position = source.position)
}
override fun mapBack(source: GameFO): Game {
return Game(id = source.id,
name = source.name,
wikiEn = source.wikiEn,
wikiCz = source.wikiCz,
mediaCount = source.mediaCount!!.toInt(),
crack = source.crack,
serialKey = source.serialKey,
patch = source.patch,
trainer = source.trainer,
trainerData = source.trainerData,
editor = source.editor,
saves = source.saves,
otherData = source.otherData,
note = source.note,
position = source.position)
}
}
| mit | 3bb78af20e2a9db98d4d49bc0057295e | 32.769231 | 60 | 0.55467 | 4.946479 | false | false | false | false |
lttng/lttng-scope | lttng-scope-ui/src/main/kotlin/org/lttng/scope/views/timecontrol/TimeRangeTextFields.kt | 1 | 7567 | /*
* Copyright (C) 2017-2018 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.lttng.scope.views.timecontrol
import com.efficios.jabberwocky.common.TimeRange
import com.efficios.jabberwocky.context.ViewGroupContext
import javafx.beans.property.ObjectProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.scene.control.TextField
import javafx.scene.input.KeyCode
import org.lttng.scope.application.ScopeOptions
import org.lttng.scope.common.TimestampFormat
import org.lttng.scope.views.context.ViewGroupContextManager
import kotlin.math.max
import kotlin.math.min
/**
* Group of 3 {@link TextField} linked together to represent a
* {@link TimeRange}.
*/
class TimeRangeTextFields(initialLimits: TimeRange, private val minimumDuration: Long?) {
var limits: TimeRange = initialLimits
val startTextField: TextField = StartTextField()
val endTextField: TextField = EndTextField()
val durationTextField: TextField = DurationTextField()
private val timeRangeProperty: ObjectProperty<TimeRange?> = SimpleObjectProperty()
fun timeRangeProperty() = timeRangeProperty
var timeRange: TimeRange?
get() = timeRangeProperty.get()
set(timeRange) = timeRangeProperty.set(timeRange)
init {
if (minimumDuration != null
&& initialLimits != ViewGroupContext.UNINITIALIZED_RANGE
&& minimumDuration > initialLimits.duration) {
throw IllegalArgumentException()
}
timeRangeProperty.addListener { _ -> resetAllValues() }
ScopeOptions.timestampFormatProperty().addListener { _ -> resetAllValues() }
ScopeOptions.timestampTimeZoneProperty().addListener { _ -> resetAllValues() }
}
private fun resetAllValues() {
listOf(startTextField, endTextField, durationTextField)
.map { it as TimeRangeTextField }
.forEach { it.resetValue() }
}
private abstract inner class TimeRangeTextField : TextField() {
init {
focusedProperty().addListener { _, _, isFocused ->
if (!isFocused) resetValue()
}
setOnKeyPressed { event ->
when (event.code) {
KeyCode.ENTER -> applyCurrentText()
KeyCode.ESCAPE -> resetValue()
else -> {
}
}
}
}
/**
* Re-synchronize the displayed value, by making it equal to the tracked time
* range.
*/
abstract fun resetValue()
fun applyCurrentText() {
/* First see if the current text makes sense. */
val range = ViewGroupContextManager.getCurrent().getCurrentProjectFullRange()
val value = getTimestampFormat().stringToTs(range, text)
if (value == null) {
/* Invalid value, reset to previous one */
resetValue()
return
}
applyValue(value)
}
protected abstract fun applyValue(value: Long)
protected open fun getTimestampFormat(): TimestampFormat = ScopeOptions.timestampFormatProperty().get()
}
private inner class StartTextField : TimeRangeTextField() {
override fun resetValue() {
val start = timeRange?.startTime ?: 0L
text = getTimestampFormat().tsToString(start)
}
override fun applyValue(value: Long) {
val prevEnd = timeRange?.endTime ?: 0L
/* The value is valid, apply it as the new range start. */
var newStart = value.coerceIn(limits.startTime, limits.endTime)
/* Update the end time if we need to (it needs to stay >= start) */
var newEnd = max(newStart, prevEnd)
if (minimumDuration != null && (newEnd - newStart) < minimumDuration) {
if (limits.endTime - newStart > minimumDuration) {
/* We have room, only offset the end time */
newEnd = newStart + minimumDuration
} else {
/* We don't have room, clamp to end and also offset the new start. */
newEnd = limits.endTime
newStart = newEnd - minimumDuration
}
}
timeRangeProperty.set(TimeRange.of(newStart, newEnd))
resetAllValues()
}
}
private inner class EndTextField : TimeRangeTextField() {
override fun resetValue() {
val end = timeRange?.endTime ?: 0L
text = getTimestampFormat().tsToString(end)
}
override fun applyValue(value: Long) {
val prevStart = timeRange?.startTime ?: 0L
var newEnd = value.coerceIn(limits.startTime, limits.endTime)
var newStart = min(newEnd, prevStart)
if (minimumDuration != null && (newEnd - newStart) < minimumDuration) {
if (newEnd - limits.startTime > minimumDuration) {
/* We have room, only offset the start time */
newStart = newEnd - minimumDuration
} else {
/* We don't have room, clamp to end and also offset the new start. */
newStart = limits.startTime
newEnd = newStart + minimumDuration
}
}
timeRangeProperty.set(TimeRange.of(newStart, newEnd))
resetAllValues()
}
}
private inner class DurationTextField : TimeRangeTextField() {
override fun resetValue() {
val duration = timeRange?.duration ?: 0L
text = getTimestampFormat().tsToString(duration)
}
override fun applyValue(value: Long) {
val prevTimeRange = timeRange ?: TimeRange.of(0L, 0L)
val requestedDuration = minimumDuration?.let { max(minimumDuration, value) } ?: value
/*
* If the entered time span is greater than the limits, we will simply change it
* to the limits themselves.
*/
val newRange: TimeRange = if (requestedDuration >= limits.duration) {
limits
} else if ((limits.endTime - prevTimeRange.startTime) > requestedDuration) {
/*
* We will apply the requested time span no matter what. We will prioritize
* modifying the end time first.
*/
/* There is room, we only need to change the end time. */
val newStart = prevTimeRange.startTime
val newEnd = newStart + requestedDuration
TimeRange.of(newStart, newEnd)
} else {
/*
* There is not enough "room", we will clamp the end to the limit and also
* modify the start time.
*/
val newEnd = limits.endTime
val newStart = newEnd - requestedDuration
TimeRange.of(newStart, newEnd)
}
timeRangeProperty.set(newRange)
resetAllValues()
}
/* Duration always uses s.ns */
override fun getTimestampFormat() = TimestampFormat.SECONDS_POINT_NANOS
}
}
| epl-1.0 | 6e810b330b7cf9073ee8c3476e9c7eb2 | 35.73301 | 111 | 0.591516 | 5.088769 | false | false | false | false |
f-droid/fdroidclient | libs/index/src/androidTest/kotlin/org/fdroid/index/v2/EntryVerifierTest.kt | 1 | 5054 | package org.fdroid.index.v2
import org.fdroid.index.SigningException
import org.fdroid.test.VerifierConstants.CERTIFICATE
import org.fdroid.test.VerifierConstants.FINGERPRINT
import org.fdroid.test.VerifierConstants.VERIFICATION_DIR
import org.junit.Test
import java.io.File
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
internal class EntryVerifierTest {
@Test
fun testNoCertAndFingerprintAllowed() {
val file = File("$VERIFICATION_DIR/valid-v2.jar")
assertFailsWith<IllegalArgumentException> {
EntryVerifier(file, CERTIFICATE, FINGERPRINT)
}
}
@Test
fun testValid() {
val file = File("$VERIFICATION_DIR/valid-v2.jar")
val verifier = EntryVerifier(file, null, null)
val (certificate, _) = verifier.getStreamAndVerify { inputStream ->
assertEquals("foo\n", inputStream.readBytes().decodeToString())
}
assertEquals(CERTIFICATE, certificate)
}
@Test
fun testValidApkSigner() {
val file = File("$VERIFICATION_DIR/valid-apksigner-v2.jar")
val verifier = EntryVerifier(file, null, null)
val (certificate, _) = verifier.getStreamAndVerify { inputStream ->
assertEquals("foo\n", inputStream.readBytes().decodeToString())
}
assertEquals(CERTIFICATE, certificate)
}
@Test
fun testValidMatchesFingerprint() {
val file = File("$VERIFICATION_DIR/valid-v2.jar")
val verifier = EntryVerifier(file, null, FINGERPRINT)
val (certificate, _) = verifier.getStreamAndVerify { inputStream ->
assertEquals("foo\n", inputStream.readBytes().decodeToString())
}
assertEquals(CERTIFICATE, certificate)
}
@Test
fun testValidWrongFingerprint() {
val file = File("$VERIFICATION_DIR/valid-v2.jar")
val verifier = EntryVerifier(file, null, "foo bar")
val e = assertFailsWith<SigningException> {
verifier.getStreamAndVerify { inputStream ->
assertEquals("foo\n", inputStream.readBytes().decodeToString())
}
}
assertTrue(e.message!!.contains("fingerprint"))
}
@Test
fun testValidWithExpectedCertificate() {
val file = File("$VERIFICATION_DIR/valid-v2.jar")
val verifier = EntryVerifier(file, CERTIFICATE, null)
val (certificate, _) = verifier.getStreamAndVerify { inputStream ->
assertEquals("foo\n", inputStream.readBytes().decodeToString())
}
assertEquals(CERTIFICATE, certificate)
}
@Test
fun testValidWithWrongCertificate() {
val file = File("$VERIFICATION_DIR/valid-v2.jar")
val verifier = EntryVerifier(file, FINGERPRINT, null)
val e = assertFailsWith<SigningException> {
verifier.getStreamAndVerify { inputStream ->
assertEquals("foo\n", inputStream.readBytes().decodeToString())
}
}
assertTrue(e.message!!.contains("certificate"))
}
@Test
fun testUnsigned() {
val file = File("$VERIFICATION_DIR/unsigned.jar")
val verifier = EntryVerifier(file, null, null)
assertFailsWith<SigningException> {
verifier.getStreamAndVerify { inputStream ->
assertEquals("foo\n", inputStream.readBytes().decodeToString())
}
}
}
@Test
fun testInvalid() {
val file = File("$VERIFICATION_DIR/invalid-v2.jar")
val verifier = EntryVerifier(file, null, null)
assertFailsWith<SigningException> {
verifier.getStreamAndVerify { }
}
}
@Test
fun testWrongEntry() {
val file = File("$VERIFICATION_DIR/invalid-wrong-entry-v1.jar")
val verifier = EntryVerifier(file, null, null)
val e = assertFailsWith<SigningException> {
verifier.getStreamAndVerify { }
}
assertTrue(e.message!!.contains("entry.json"))
}
@Test
fun testSHA1Digest() {
val file = File("$VERIFICATION_DIR/invalid-SHA1-SHA1withRSA-v2.jar")
val verifier = EntryVerifier(file, null, null)
val e = assertFailsWith<SigningException> {
verifier.getStreamAndVerify { }
}
assertTrue(e.message!!.contains("Unsupported digest"))
}
@Test
fun testMD5Digest() {
val file = File("$VERIFICATION_DIR/invalid-MD5-SHA1withRSA-v2.jar")
val verifier = EntryVerifier(file, null, null)
val e = assertFailsWith<SigningException> {
verifier.getStreamAndVerify { }
}
assertTrue(e.message!!.contains("Unsupported digest"))
}
@Test
fun testMD5SignatureAlgo() {
val file = File("$VERIFICATION_DIR/invalid-MD5-MD5withRSA-v2.jar")
val verifier = EntryVerifier(file, null, null)
val e = assertFailsWith<SigningException> {
verifier.getStreamAndVerify { }
}
assertTrue(e.message!!.contains("Unsupported digest"))
}
}
| gpl-3.0 | 733420005dd3a1070d6351c2f1c583f3 | 30.786164 | 79 | 0.635734 | 4.582049 | false | true | false | false |
jiro-aqua/KantanRosenKensaku | app/src/main/java/jp/gr/aqua/rosen/StationPickerActivity.kt | 1 | 5078 | package jp.gr.aqua.rosen
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.ContextMenu
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.TextView
import kotlinx.android.synthetic.main.location_list.*
import rx.Observable
import rx.subjects.PublishSubject
import rx.subscriptions.CompositeSubscription
public class StationPickerActivity : AppCompatActivity() {
val subscriptions = CompositeSubscription()
val sp : SharedPreferences by lazy {getSharedPreferences("stations", Context.MODE_PRIVATE )}
val stations = arrayListOf("--")
val stationAdapter : ArrayAdapter<String> by lazy { ArrayAdapter<String>(this,R.layout.location_list_row, stations) }
val contextMenuClickObservable = PublishSubject.create<MenuItem>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setTitle(R.string.app_title)
setContentView(R.layout.location_list)
val init = getIntent().getStringExtra(EXTRA_INITIAL_STRING)
init?.let { station_edit.setText(it) }
list.setAdapter(stationAdapter)
registerForContextMenu(list)
refresh()
// 登録ボタンまたは入力欄でエンターキー
subscriptions.add( Observable.merge(
station_register.clickEvents(),
station_edit.editorActionEvents().filter { it.actionId() == EditorInfo.IME_ACTION_DONE }
) .filter { station_register.isEnabled()}
.subscribe {
sp.edit().putLong( station_edit.getText().toString(), System.currentTimeMillis() ) .apply()
refresh()
station_edit.setText("")
})
// 入力欄の内容で登録ボタンを無効化
subscriptions.add(station_edit.textChanges().subscribe {
station_register.setEnabled( it.length != 0 )
})
// リストのアイテムクリック
subscriptions.add(list.itemClickEvents().subscribe {
val item = stationAdapter.getItem(it.position())
val result = Intent()
result.putExtra(EXTRA_ADDRESS, item)
setResult( Activity.RESULT_OK , result )
finish()
})
// リストの内容変更
subscriptions.add(stationAdapter.dataChanges().subscribe {
empty.setVisibility( if ( it.getCount()== 0) View.VISIBLE else View.GONE )
})
// コンテクストメニューのアイテムクリック
subscriptions.add(contextMenuClickObservable.subscribe {
val contextmenuinfo = it.getMenuInfo() as AdapterView.AdapterContextMenuInfo
val textview = contextmenuinfo.targetView as TextView
val text = textview.getText().toString()
when( it.getItemId() ){
1 -> sp.edit().remove(text).apply() // 削除
2 -> sp.edit().putLong(text,System.currentTimeMillis()).apply() // 先頭に移動
}
refresh()
})
}
private fun refresh() {
stations.clear()
// SharedPreferencesの中身を列挙して、
// キー/バリューPairの配列に変換して、
// バリュー値で降順にソートして、
// stationsの中にキー値を格納する。
// ※ここはRxJavaではなく、KotlinのコレクションAPIで操作
sp.getAll().map { it.key to it.value as Long }.sortedBy { -it.second }.mapTo(stations) { it.first }
stationAdapter.notifyDataSetChanged()
}
override fun onDestroy() {
super.onDestroy()
subscriptions.unsubscribe()
}
override fun onCreateContextMenu(contextmenu: ContextMenu, view: View , contextmenuinfo: android.view.ContextMenu.ContextMenuInfo )
{
super.onCreateContextMenu(contextmenu, view, contextmenuinfo);
contextmenu.add(0, 1, 0, R.string.menu_remove);
contextmenu.add(0, 2, 1, R.string.menu_move_to_top);
}
override fun onContextItemSelected(item: MenuItem?): Boolean {
item?.let{ contextMenuClickObservable.onNext(item) }
return true;
}
companion object {
@JvmStatic public fun getStartIntent(context : Context, init: String?) : Intent{
val intent = Intent( context , StationPickerActivity::class.java )
init?.let { intent.putExtra(EXTRA_INITIAL_STRING, init ) }
return intent
}
@JvmStatic public fun getAddress(intent : Intent) : String {
return intent.getStringExtra(EXTRA_ADDRESS)!!
}
private val EXTRA_ADDRESS = "addr"
private val EXTRA_INITIAL_STRING = "init"
}
}
| apache-2.0 | 15e17b69e56e06cf47fa44aa34418481 | 36.208 | 135 | 0.641122 | 4.275739 | false | false | false | false |
square/leakcanary | leakcanary-object-watcher-android-core/src/main/java/leakcanary/FragmentAndViewModelWatcher.kt | 2 | 4267 | package leakcanary
import android.app.Activity
import android.app.Application
import android.os.Build.VERSION.SDK_INT
import android.os.Build.VERSION_CODES.O
import android.os.Bundle
import leakcanary.internal.AndroidOFragmentDestroyWatcher
import leakcanary.internal.friendly.noOpDelegate
/**
* Expects:
* - Fragments (Support Library, Android X and AOSP) to become weakly reachable soon after they
* receive the Fragment#onDestroy() callback.
* - Fragment views (Support Library, Android X and AOSP) to become weakly reachable soon after
* fragments receive the Fragment#onDestroyView() callback.
* - Android X view models (both activity and fragment view models) to become weakly reachable soon
* after they received the ViewModel#onCleared() callback.
*/
class FragmentAndViewModelWatcher(
private val application: Application,
private val reachabilityWatcher: ReachabilityWatcher
) : InstallableWatcher {
private val fragmentDestroyWatchers: List<(Activity) -> Unit> = run {
val fragmentDestroyWatchers = mutableListOf<(Activity) -> Unit>()
if (SDK_INT >= O) {
fragmentDestroyWatchers.add(
AndroidOFragmentDestroyWatcher(reachabilityWatcher)
)
}
getWatcherIfAvailable(
ANDROIDX_FRAGMENT_CLASS_NAME,
ANDROIDX_FRAGMENT_DESTROY_WATCHER_CLASS_NAME,
reachabilityWatcher
)?.let {
fragmentDestroyWatchers.add(it)
}
getWatcherIfAvailable(
ANDROID_SUPPORT_FRAGMENT_CLASS_NAME,
ANDROID_SUPPORT_FRAGMENT_DESTROY_WATCHER_CLASS_NAME,
reachabilityWatcher
)?.let {
fragmentDestroyWatchers.add(it)
}
fragmentDestroyWatchers
}
private val lifecycleCallbacks =
object : Application.ActivityLifecycleCallbacks by noOpDelegate() {
override fun onActivityCreated(
activity: Activity,
savedInstanceState: Bundle?
) {
for (watcher in fragmentDestroyWatchers) {
watcher(activity)
}
}
}
override fun install() {
application.registerActivityLifecycleCallbacks(lifecycleCallbacks)
}
override fun uninstall() {
application.unregisterActivityLifecycleCallbacks(lifecycleCallbacks)
}
private fun getWatcherIfAvailable(
fragmentClassName: String,
watcherClassName: String,
reachabilityWatcher: ReachabilityWatcher
): ((Activity) -> Unit)? {
return if (classAvailable(fragmentClassName) &&
classAvailable(watcherClassName)
) {
val watcherConstructor =
Class.forName(watcherClassName).getDeclaredConstructor(ReachabilityWatcher::class.java)
@Suppress("UNCHECKED_CAST")
watcherConstructor.newInstance(reachabilityWatcher) as (Activity) -> Unit
} else {
null
}
}
private fun classAvailable(className: String): Boolean {
return try {
Class.forName(className)
true
} catch (e: Throwable) {
// e is typically expected to be a ClassNotFoundException
// Unfortunately, prior to version 25.0.2 of the support library the
// FragmentManager.FragmentLifecycleCallbacks class was a non static inner class.
// Our AndroidSupportFragmentDestroyWatcher class is compiled against the static version of
// the FragmentManager.FragmentLifecycleCallbacks class, leading to the
// AndroidSupportFragmentDestroyWatcher class being rejected and a NoClassDefFoundError being
// thrown here. So we're just covering our butts here and catching everything, and assuming
// any throwable means "can't use this". See https://github.com/square/leakcanary/issues/1662
false
}
}
companion object {
private const val ANDROIDX_FRAGMENT_CLASS_NAME = "androidx.fragment.app.Fragment"
private const val ANDROIDX_FRAGMENT_DESTROY_WATCHER_CLASS_NAME =
"leakcanary.internal.AndroidXFragmentDestroyWatcher"
// Using a string builder to prevent Jetifier from changing this string to Android X Fragment
@Suppress("VariableNaming", "PropertyName")
private val ANDROID_SUPPORT_FRAGMENT_CLASS_NAME =
StringBuilder("android.").append("support.v4.app.Fragment")
.toString()
private const val ANDROID_SUPPORT_FRAGMENT_DESTROY_WATCHER_CLASS_NAME =
"leakcanary.internal.AndroidSupportFragmentDestroyWatcher"
}
}
| apache-2.0 | 8916f99e6d957e14d7025b456a9225d0 | 34.558333 | 99 | 0.733302 | 4.756968 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/smartspace/IcuDateTextView.kt | 1 | 6259 | package app.lawnchair.smartspace
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.icu.text.DateFormat
import android.icu.text.DisplayContext
import android.os.SystemClock
import android.util.AttributeSet
import app.lawnchair.preferences2.PreferenceManager2
import app.lawnchair.smartspace.model.SmartspaceCalendar
import app.lawnchair.util.broadcastReceiverFlow
import app.lawnchair.util.repeatOnAttached
import app.lawnchair.util.subscribeBlocking
import com.android.launcher3.R
import com.patrykmichalik.opto.core.firstBlocking
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import saman.zamani.persiandate.PersianDate
import saman.zamani.persiandate.PersianDateFormat
import java.util.*
typealias FormatterFunction = (Long) -> String
class IcuDateTextView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : DoubleShadowTextView(context, attrs) {
private val prefs = PreferenceManager2.getInstance(context)
private var calendar: SmartspaceCalendar? = null
private lateinit var dateTimeOptions: DateTimeOptions
private var formatterFunction: FormatterFunction? = null
private val ticker = this::onTimeTick
init {
repeatOnAttached {
val calendarSelectionEnabled = prefs.enableSmartspaceCalendarSelection.firstBlocking()
val calendarFlow =
if (calendarSelectionEnabled) prefs.smartspaceCalendar.get()
else flowOf(prefs.smartspaceCalendar.defaultValue)
val optionsFlow = DateTimeOptions.fromPrefs(prefs)
combine(calendarFlow, optionsFlow) { calendar, options -> calendar to options }
.subscribeBlocking(this) {
calendar = it.first
dateTimeOptions = it.second
onTimeChanged(true)
}
val intentFilter = IntentFilter()
intentFilter.addAction(Intent.ACTION_TIME_CHANGED)
intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED)
broadcastReceiverFlow(context, intentFilter)
.onEach { onTimeChanged(it.action != Intent.ACTION_TIME_TICK) }
.launchIn(this)
}
}
private fun onTimeChanged(updateFormatter: Boolean) {
if (isShown) {
val timeText = getTimeText(updateFormatter)
if (text != timeText) {
textAlignment = if (shouldAlignToTextEnd()) TEXT_ALIGNMENT_TEXT_END else TEXT_ALIGNMENT_TEXT_START
text = timeText
contentDescription = timeText
}
} else if (updateFormatter) {
formatterFunction = null
}
}
private fun shouldAlignToTextEnd(): Boolean {
val shouldNotAlignToEnd = dateTimeOptions.showTime && dateTimeOptions.time24HourFormat && !dateTimeOptions.showDate
return calendar == SmartspaceCalendar.Persian && !shouldNotAlignToEnd
}
private fun getTimeText(updateFormatter: Boolean): String {
val formatter = getFormatterFunction(updateFormatter)
return formatter(System.currentTimeMillis())
}
private fun getFormatterFunction(updateFormatter: Boolean): FormatterFunction {
if (formatterFunction != null && !updateFormatter) {
return formatterFunction!!
}
val formatter = when (calendar) {
SmartspaceCalendar.Persian -> createPersianFormatter()
else -> createGregorianFormatter()
}
formatterFunction = formatter
return formatter
}
private fun createPersianFormatter(): FormatterFunction {
var format: String
if (dateTimeOptions.showTime) {
format = context.getString(
if (dateTimeOptions.time24HourFormat) R.string.smartspace_icu_date_pattern_persian_time
else R.string.smartspace_icu_date_pattern_persian_time_12h
)
if (dateTimeOptions.showDate) format = context.getString(R.string.smartspace_icu_date_pattern_persian_date) + format
} else {
format = context.getString(R.string.smartspace_icu_date_pattern_persian_wday_month_day_no_year)
}
val formatter = PersianDateFormat(format, PersianDateFormat.PersianDateNumberCharacter.FARSI)
return { formatter.format(PersianDate(it)) }
}
private fun createGregorianFormatter(): FormatterFunction {
var format: String
if (dateTimeOptions.showTime) {
format = context.getString(
if (dateTimeOptions.time24HourFormat) R.string.smartspace_icu_date_pattern_gregorian_time
else R.string.smartspace_icu_date_pattern_gregorian_time_12h
)
if (dateTimeOptions.showDate) format += context.getString(R.string.smartspace_icu_date_pattern_gregorian_date)
} else {
format = context.getString(R.string.smartspace_icu_date_pattern_gregorian_wday_month_day_no_year)
}
val formatter = DateFormat.getInstanceForSkeleton(format, Locale.getDefault())
formatter.setContext(DisplayContext.CAPITALIZATION_FOR_STANDALONE)
return { formatter.format(it) }
}
private fun onTimeTick() {
onTimeChanged(false)
val uptimeMillis: Long = SystemClock.uptimeMillis()
handler?.postAtTime(ticker, uptimeMillis + (1000 - uptimeMillis % 1000))
}
override fun onVisibilityAggregated(isVisible: Boolean) {
super.onVisibilityAggregated(isVisible)
handler?.removeCallbacks(ticker)
if (isVisible) {
ticker()
}
}
}
data class DateTimeOptions(
val showDate: Boolean,
val showTime: Boolean,
val time24HourFormat: Boolean,
) {
companion object {
fun fromPrefs(prefs: PreferenceManager2) =
combine(
prefs.smartspaceShowDate.get(),
prefs.smartspaceShowTime.get(),
prefs.smartspace24HourFormat.get()
) { showDate, showTime, time24HourFormat ->
DateTimeOptions(showDate, showTime, time24HourFormat)
}
}
}
| gpl-3.0 | 7dd0d18f9341ec4a475ea6a25605b433 | 39.121795 | 128 | 0.679661 | 4.745262 | false | false | false | false |
google/ksp | compiler-plugin/src/main/kotlin/com/google/devtools/ksp/symbol/impl/java/KSValueArgumentJavaImpl.kt | 1 | 1891 | /*
* Copyright 2020 Google LLC
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.ksp.symbol.impl.java
import com.google.devtools.ksp.KSObjectCache
import com.google.devtools.ksp.symbol.KSAnnotation
import com.google.devtools.ksp.symbol.KSName
import com.google.devtools.ksp.symbol.KSNode
import com.google.devtools.ksp.symbol.Location
import com.google.devtools.ksp.symbol.NonExistLocation
import com.google.devtools.ksp.symbol.Origin
import com.google.devtools.ksp.symbol.impl.kotlin.KSValueArgumentImpl
class KSValueArgumentJavaImpl private constructor(
override val name: KSName?,
override val value: Any?,
override val parent: KSNode?
) : KSValueArgumentImpl() {
companion object : KSObjectCache<Triple<KSName?, Any?, KSNode?>, KSValueArgumentJavaImpl>() {
fun getCached(name: KSName?, value: Any?, parent: KSNode?) =
cache.getOrPut(Triple(name, value, parent)) { KSValueArgumentJavaImpl(name, value, parent) }
}
override val origin = Origin.JAVA
override val location: Location = NonExistLocation
override val isSpread: Boolean = false
override val annotations: Sequence<KSAnnotation> = emptySequence()
override fun toString(): String {
return "${name?.asString() ?: ""}:$value"
}
}
| apache-2.0 | 969e6619c0b4b1d5dbb7269488f57919 | 36.82 | 104 | 0.746695 | 4.183628 | false | false | false | false |
chrisbanes/tivi | data/src/main/java/app/tivi/data/resultentities/SeasonWithEpisodes.kt | 1 | 1252 | /*
* 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 app.tivi.data.resultentities
import androidx.room.Embedded
import androidx.room.Relation
import app.tivi.data.entities.Episode
import app.tivi.data.entities.Season
import java.util.Objects
class SeasonWithEpisodes {
@Embedded
var season: Season? = null
@Relation(parentColumn = "id", entityColumn = "season_id")
var episodes: List<Episode> = emptyList()
override fun equals(other: Any?): Boolean = when {
other === this -> true
other is SeasonWithEpisodes -> season == other.season && episodes == other.episodes
else -> false
}
override fun hashCode(): Int = Objects.hash(season, episodes)
}
| apache-2.0 | 0631df3eb002a0da387c807b25090993 | 31.102564 | 91 | 0.716454 | 4.173333 | false | false | false | false |
ntemplon/legends-of-omterra | core/src/com/jupiter/europa/entity/ability/AttackAbility.kt | 1 | 2396 | /*
* The MIT License
*
* Copyright 2015 Nathan Templon.
*
* 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.jupiter.europa.entity.ability
import com.badlogic.ashley.core.Entity
import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.jupiter.europa.EuropaGame
import com.jupiter.europa.io.FileLocations
import kotlin.properties.Delegates
/**
* Created by nathan on 5/22/15.
*/
public class AttackAbility(private val entity: Entity) : Ability {
private var sprite: TextureRegion = TextureRegion()
// Public Methods
override val name: String = NAME
override val description: String = "Perform a basic attack with a melee or ranged weapon."
override val cost: Cost = COST
override val action: Action = AttackAction(entity)
override val category: AbilityCategory = BasicAbilityCategories.ALL_ABILITIES
override val icon: TextureRegion = ICON
public class AttackAction internal constructor(entity: Entity) : Action(entity) {
}
companion object {
// Constants
private val NAME = "Attack"
private val ICON_NAME = "attack"
private val COST = Cost.NONE
private val ICON by Delegates.lazy { EuropaGame.game.assetManager!!.get(FileLocations.ICON_ATLAS, javaClass<TextureAtlas>()).findRegion(ICON_NAME) }
}
}
| mit | 9d99b4ce47031fe972ea48c8de1e2599 | 36.4375 | 156 | 0.745409 | 4.478505 | false | false | false | false |
SixCan/SixTomato | app/src/main/java/ca/six/tomato/data/TaskDbRpository.kt | 1 | 2604 | package ca.six.tomato.data
import ca.six.tomato.data.entity.TaskItem
import ca.six.tomato.util.Globals
import ca.six.tomato.util.read
import ca.six.tomato.util.write
import org.json.JSONArray
import org.json.JSONObject
import java.util.*
/**
* Created by songzhw on 2016-06-17
*/
class TaskDbRpository : ITaskRepository {
private var taskList = arrayListOf<TaskItem>()
private val lineSeparator = "\n"
override fun deleteItem(position: Int) {
if (position < taskList.size) {
taskList.removeAt(position)
val itemList = StringBuilder()
for (item in taskList) {
itemList.append(item.toString()).append(lineSeparator)
}
write(itemList.toString(), Globals.TASK_DATA_PATH)
}
}
override fun swapItem(from: Int, to: Int) {
val taskSize = taskList.size
if(from < taskSize && to < taskSize){
Collections.swap(taskList, from, to)
val itemList = StringBuilder()
for(item in taskList){
itemList.append(item.toString()).append(lineSeparator)
}
write(itemList.toString(), Globals.TASK_DATA_PATH)
}
}
override fun getAllTasks(): ArrayList<TaskItem> {
val tmpList = arrayListOf<TaskItem>()
val taskArray = read(Globals.TASK_DATA_PATH)
val taskLength = taskArray.length()
for (i in 0..(taskLength - 1)) {
val item = taskArray.get(i) as JSONObject
val taskItem = TaskItem(item.optLong(Globals.JSON_NAME_TASK_ID),
item.optString(Globals.JSON_NAME_TASK_TITLE),
item.optString(Globals.JSON_NAME_TASK_CONTENT))
taskItem.isComplete = item.optBoolean(Globals.JSON_NAME_TASK_STATUS)
taskList.add(taskItem)
}
for(item in taskList){
tmpList.add(item)
}
return tmpList
}
override fun addItem(title: String, content: String) {
taskList.add(TaskItem(System.currentTimeMillis(), title, content))
val itemList = StringBuilder()
for (item in taskList) {
itemList.append(item.toString()).append(lineSeparator)
}
write(itemList.toString(), Globals.TASK_DATA_PATH)
}
override fun saveAllTasks(taskList : ArrayList<TaskItem>){
this.taskList = taskList
val itemList = StringBuilder()
for(item in this.taskList){
itemList.append(item.toString()).append(lineSeparator)
}
write(itemList.toString(), Globals.TASK_DATA_PATH)
}
}
| gpl-3.0 | 964b7c22a514b0d16f36e3fb45d5a195 | 32.384615 | 80 | 0.615207 | 4.227273 | false | false | false | false |
charlesmadere/smash-ranks-android | smash-ranks-android/app/src/main/java/com/garpr/android/features/logViewer/LogViewerActivity.kt | 1 | 3797 | package com.garpr.android.features.logViewer
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.garpr.android.R
import com.garpr.android.extensions.layoutInflater
import com.garpr.android.features.common.activities.BaseActivity
import com.garpr.android.misc.Refreshable
import com.garpr.android.misc.Timber
import kotlinx.android.synthetic.main.activity_log_viewer.*
import org.koin.androidx.viewmodel.ext.android.viewModel
class LogViewerActivity : BaseActivity(), LogViewerToolbar.Listener, Refreshable,
SwipeRefreshLayout.OnRefreshListener {
private val adapter = Adapter()
private val viewModel: LogViewerViewModel by viewModel()
companion object {
private const val TAG = "LogViewerActivity"
fun getLaunchIntent(context: Context) = Intent(context, LogViewerActivity::class.java)
}
override val activityName = TAG
private fun initListeners() {
viewModel.stateLiveData.observe(this, Observer {
refreshState(it)
})
}
override fun onClearClick(v: LogViewerToolbar) {
viewModel.clearEntries()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_log_viewer)
initListeners()
refresh()
}
override fun onRefresh() {
refresh()
}
override fun onViewsBound() {
super.onViewsBound()
refreshLayout.setOnRefreshListener(this)
recyclerView.addItemDecoration(DividerItemDecoration(this,
DividerItemDecoration.VERTICAL))
recyclerView.setHasFixedSize(true)
recyclerView.adapter = adapter
toolbar.listener = this
}
override fun refresh() {
viewModel.fetchEntries()
}
private fun refreshState(state: LogViewerViewModel.State) {
if (state.isEmpty) {
adapter.clear()
recyclerView.visibility = View.GONE
empty.visibility = View.VISIBLE
toolbar.isClearEnabled = false
} else {
adapter.set(state.entries)
empty.visibility = View.GONE
recyclerView.visibility = View.VISIBLE
toolbar.isClearEnabled = true
}
refreshLayout.isRefreshing = state.isFetching
}
private class Adapter : RecyclerView.Adapter<TimberEntryViewHolder>() {
private val list = mutableListOf<Timber.Entry>()
internal fun clear() {
list.clear()
notifyDataSetChanged()
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: TimberEntryViewHolder, position: Int) {
holder.timberEntryItemView.setContent(list[position])
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TimberEntryViewHolder {
val inflater = parent.layoutInflater
return TimberEntryViewHolder(inflater.inflate(R.layout.item_timber_entry, parent,
false))
}
internal fun set(list: List<Timber.Entry>?) {
this.list.clear()
if (!list.isNullOrEmpty()) {
this.list.addAll(list)
}
notifyDataSetChanged()
}
}
private class TimberEntryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
internal val timberEntryItemView: TimberEntryItemView = itemView as TimberEntryItemView
}
}
| unlicense | c843f3f1eb8f3f632f892171282ca0fb | 28.897638 | 98 | 0.67606 | 5.158967 | false | false | false | false |
Jonatino/Droid-Explorer | src/main/kotlin/com/droid/explorer/filesystem/entry/Entry.kt | 1 | 2997 | /*
* Copyright 2016 Jonathan Beaudoin
*
* 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.droid.explorer.filesystem.entry
import com.droid.explorer.filesystem.FileSystem
import com.droid.explorer.gui.Icons
import javafx.scene.image.ImageView
import java.util.*
/**
* Created by Jonathan on 4/25/2016.
*/
abstract class Entry(val parent: Entry?, val name: String, val date: String, val permissions: String) {
abstract val type: Type
fun isRoot() = name == "/"
fun isDirectory() = type === Type.DIRECTORY
fun isSymbolicLink() = type === Type.SYMLINK
var files = listOf<Entry>()
var lastChild: Entry? = null
open val absolutePath: String by lazy {
var path = "/"
parents.forEach { path += "$it/" }
if (type === Type.FILE) {
path = path.substring(0, path.length - 1)
}
path
}
val parents: List<Entry?> by lazy {
val entries = ArrayList<Entry?>()
if (!isRoot()) entries.add(this)
var currentEntry: Entry? = this
while (currentEntry?.parent != null) {
val parent = currentEntry.parent
if (!parent!!.isRoot()) {
entries.add(parent)
}
currentEntry = parent
}
entries.reversed()
}
fun navigate() {
if (isDirectory() || isSymbolicLink())
FileSystem.currentPath = this
}
fun contains(entry: Entry) = files.any { it -> it.type == entry.type && it.name == entry.name }
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Entry) return false
if (parent != other.parent) return false
if (name != other.name) return false
if (date != other.date) return false
if (permissions != other.permissions) return false
if (absolutePath != other.absolutePath) return false
return true
}
override fun hashCode(): Int {
var result = parent?.hashCode() ?: 0
result += 31 * result + name.hashCode()
result += 31 * result + date.hashCode()
result += 31 * result + permissions.hashCode()
result += 31 * result + absolutePath.hashCode()
return result
}
override fun toString() = if (isRoot()) name else name.replace("/", "")
enum class Type(val icon: ImageView) {
DIRECTORY(Icons.DIRECTORY), SYMLINK(Icons.SYMLINK), FILE(Icons.FILE)
}
} | apache-2.0 | 3754169b2fcc6c78995d1a5389b224d3 | 30.229167 | 103 | 0.613614 | 4.257102 | false | false | false | false |
Zukkari/nirdizati-training-ui | src/main/kotlin/cs/ut/engine/events/Annotations.kt | 1 | 717 | package cs.ut.engine.events
import java.lang.reflect.Method
import kotlin.reflect.KClass
/**
* Annotation used by JobManager to call back on event that has happened
*/
@Retention(AnnotationRetention.RUNTIME)
annotation class Callback(val event: KClass<*>)
fun findCallback(target: Class<*>, eventType: KClass<*>): Method? {
val methods: List<Method> = target.methods.filter { it.isAnnotationPresent(Callback::class.java) }
methods.forEach { m ->
val annotations = m.annotations
annotations.forEach {
if (it.annotationClass == Callback::class) {
it as Callback
if (it.event == eventType) return m
}
}
}
return null
}
| lgpl-3.0 | 14891743bf89daa6e112714f3f843be6 | 28.875 | 102 | 0.651325 | 4.371951 | false | false | false | false |
openMF/android-client | mifosng-android/src/main/java/com/mifos/mifosxdroid/online/collectionsheetindividual/NewIndividualCollectionSheetFragment.kt | 1 | 11328 | package com.mifos.mifosxdroid.online.collectionsheetindividual
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import android.widget.AdapterView.OnItemSelectedListener
import androidx.fragment.app.DialogFragment
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.mifos.api.model.RequestCollectionSheetPayload
import com.mifos.mifosxdroid.R
import com.mifos.mifosxdroid.core.MifosBaseActivity
import com.mifos.mifosxdroid.core.MifosBaseFragment
import com.mifos.mifosxdroid.core.util.Toaster
import com.mifos.mifosxdroid.dialogfragments.collectionsheetdialog.CollectionSheetDialogFragment
import com.mifos.mifosxdroid.dialogfragments.searchdialog.SearchDialog
import com.mifos.mifosxdroid.online.collectionsheetindividualdetails.IndividualCollectionSheetDetailsFragment
import com.mifos.mifosxdroid.uihelpers.MFDatePicker
import com.mifos.mifosxdroid.uihelpers.MFDatePicker.OnDatePickListener
import com.mifos.mifosxdroid.views.CustomSpinner
import com.mifos.mifosxdroid.views.CustomSpinner.OnSpinnerEventsListener
import com.mifos.objects.collectionsheet.IndividualCollectionSheet
import com.mifos.objects.organisation.Office
import com.mifos.objects.organisation.Staff
import com.mifos.utils.Constants
import com.mifos.utils.DateHelper
import com.mifos.utils.FragmentConstants
import java.util.*
import javax.inject.Inject
/**
* Created by aksh on 18/6/18.
*/
class NewIndividualCollectionSheetFragment : MifosBaseFragment(), IndividualCollectionSheetMvpView, OnDatePickListener, OnItemSelectedListener, View.OnClickListener {
@JvmField
@BindView(R.id.btn_fetch_collection_sheet)
var btnFetchSheet: Button? = null
@JvmField
@BindView(R.id.sp_office_list)
var spOffices: CustomSpinner? = null
@JvmField
@BindView(R.id.sp_staff_list)
var spStaff: CustomSpinner? = null
@JvmField
@BindView(R.id.tv_repayment_date)
var tvRepaymentDate: TextView? = null
@JvmField
@BindView(R.id.btn_clear)
var btnClear: Button? = null
@JvmField
@Inject
var presenter: NewIndividualCollectionSheetPresenter? = null
private var sheet: IndividualCollectionSheet? = null
private var datePicker: DialogFragment? = null
private var requestPayload: RequestCollectionSheetPayload? = null
private lateinit var rootView: View
private var officeAdapter: ArrayAdapter<String>? = null
private var officeNameList: ArrayList<String>? = null
private var officeList: List<Office>? = null
private var staffAdapter: ArrayAdapter<String>? = null
private var staffNameList: ArrayList<String>? = null
private var staffList: List<Staff>? = null
private var officeId = 0
private var staffId = 0
private val requestCode = 1
private var success = true
private var actualDisbursementDate: String? = null
private var transactionDate: String? = null
private var officeSearchDialog: SearchDialog? = null
private var staffSearchDialog: SearchDialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(activity as MifosBaseActivity?)!!.activityComponent.inject(this)
if (savedInstanceState != null) {
sheet = savedInstanceState[Constants.EXTRA_COLLECTION_INDIVIDUAL] as IndividualCollectionSheet
}
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
rootView = inflater.inflate(R.layout.fragment_new_collection_sheet, container, false)
ButterKnife.bind(this, rootView)
setToolbarTitle(getStringMessage(R.string.individual_collection_sheet))
presenter!!.attachView(this)
setUpUi()
return rootView
}
private fun setUpUi() {
setRepaymentDate()
officeNameList = ArrayList()
officeAdapter = ArrayAdapter(requireActivity(),
android.R.layout.simple_spinner_item, officeNameList ?: emptyList())
officeAdapter!!.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spOffices!!.adapter = officeAdapter
spOffices!!.onItemSelectedListener = this
staffNameList = ArrayList()
staffAdapter = ArrayAdapter(requireActivity(),
android.R.layout.simple_spinner_item, staffNameList ?: emptyList())
staffAdapter!!.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spStaff!!.adapter = staffAdapter
tvRepaymentDate!!.setOnClickListener(this)
btnFetchSheet!!.setOnClickListener(this)
presenter!!.fetchOffices()
spOffices!!.setSpinnerEventsListener(object : OnSpinnerEventsListener {
override fun onSpinnerOpened(spinner: Spinner, isItemListLarge: Boolean) {
if (isItemListLarge) {
enableOfficeSearch()
}
}
override fun onSpinnerClosed(spinner: Spinner) {}
})
spStaff!!.setSpinnerEventsListener(object : OnSpinnerEventsListener {
override fun onSpinnerOpened(spinner: Spinner, isItemListLarge: Boolean) {
if (isItemListLarge) {
enableStaffSearch()
}
}
override fun onSpinnerClosed(spinner: Spinner) {}
})
}
fun enableOfficeSearch() {
if (officeSearchDialog == null) {
val listener = AdapterView.OnItemClickListener { adapterView, view, i, l -> spOffices!!.setSelection(i) }
officeSearchDialog = SearchDialog(requireContext(), officeNameList, listener)
}
officeSearchDialog!!.show()
}
fun enableStaffSearch() {
if (staffSearchDialog == null) {
val listener = AdapterView.OnItemClickListener { adapterView, view, i, l -> spStaff!!.setSelection(i) }
staffSearchDialog = SearchDialog(requireContext(), staffNameList, listener)
}
staffSearchDialog!!.show()
}
fun setRepaymentDate() {
datePicker = MFDatePicker.newInsance(this)
val date = DateHelper.getDateAsStringUsedForCollectionSheetPayload(MFDatePicker.getDatePickedAsString())
tvRepaymentDate!!.text = date.replace('-', ' ')
transactionDate = date.replace('-', ' ')
actualDisbursementDate = transactionDate
}
private fun prepareRequestPayload() {
requestPayload = RequestCollectionSheetPayload()
requestPayload!!.officeId = officeId
requestPayload!!.staffId = staffId
requestPayload!!.transactionDate = tvRepaymentDate!!.text.toString()
}
override fun setOfficeSpinner(offices: List<Office>?) {
officeList = offices
officeNameList!!.clear()
officeNameList!!.add(getString(R.string.spinner_office))
officeNameList!!.addAll(presenter!!.filterOffices(officeList))
officeAdapter!!.notifyDataSetChanged()
}
override fun onDatePicked(date: String) {
val d = DateHelper.getDateAsStringUsedForCollectionSheetPayload(date)
tvRepaymentDate!!.text = d.replace('-', ' ')
}
fun retrieveCollectionSheet() {
prepareRequestPayload()
presenter!!.fetchIndividualCollectionSheet(requestPayload)
}
fun setTvRepaymentDate() {
datePicker!!.show(requireActivity().supportFragmentManager,
FragmentConstants.DFRAG_DATE_PICKER)
}
override fun setStaffSpinner(staffs: List<Staff>?) {
spStaff!!.onItemSelectedListener = this
staffList = staffs
staffNameList!!.clear()
staffNameList!!.add(getString(R.string.spinner_staff))
staffNameList!!.addAll(presenter!!.filterStaff(staffList))
staffAdapter!!.notifyDataSetChanged()
}
override fun onItemSelected(adapterView: AdapterView<*>, view: View, i: Int, l: Long) {
when (adapterView.id) {
R.id.sp_office_list -> if (i == officeList!!.size || i == 0) {
Toaster.show(rootView, getStringMessage(R.string.error_select_office))
} else {
Toaster.show(rootView, officeNameList!![i])
officeId = officeList!![i - 1].id
presenter!!.fetchStaff(officeId)
}
R.id.sp_staff_list -> if (i == staffList!!.size || i == 0) {
Toaster.show(rootView, getStringMessage(R.string.error_select_staff))
} else {
staffId = staffList!![i - 1].id
}
}
}
fun popupDialog() {
val collectionSheetDialogFragment = CollectionSheetDialogFragment.newInstance(tvRepaymentDate!!.text.toString(),
sheet!!.clients.size)
collectionSheetDialogFragment.setTargetFragment(this, requestCode)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_DOCUMENT_LIST)
collectionSheetDialogFragment.show(fragmentTransaction, "Identifier Dialog Fragment")
}
fun getResponse(response: String?) {
when (response) {
Constants.FILLNOW -> {
val fm = activity
?.getSupportFragmentManager()
fm!!.popBackStack()
val fragment: IndividualCollectionSheetDetailsFragment = IndividualCollectionSheetDetailsFragment().newInstance(sheet,
actualDisbursementDate, transactionDate)
(activity as MifosBaseActivity?)!!.replaceFragment(fragment,
true, R.id.container)
}
}
}
override fun onNothingSelected(adapterView: AdapterView<*>?) {}
override fun showSheet(individualCollectionSheet: IndividualCollectionSheet?) {
sheet = individualCollectionSheet
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putParcelable(Constants.EXTRA_COLLECTION_INDIVIDUAL, sheet)
}
override fun showSuccess() {
if (success) {
popupDialog()
}
}
override fun showError(message: String?) {
Toaster.show(rootView, message)
}
override fun showNoSheetFound() {
success = false
Toaster.show(rootView, getStringMessage(R.string.no_collectionsheet_found))
}
override fun showProgressbar(b: Boolean) {
if (b) {
showMifosProgressDialog()
} else {
hideMifosProgressDialog()
}
}
override fun onClick(view: View) {
when (view.id) {
R.id.tv_repayment_date -> setTvRepaymentDate()
R.id.btn_fetch_collection_sheet -> retrieveCollectionSheet()
}
}
@OnClick(R.id.btn_clear)
fun clear() {
spOffices!!.adapter = null
spStaff!!.adapter = null
setUpUi()
}
companion object {
fun newInstance(): NewIndividualCollectionSheetFragment {
val args = Bundle()
val fragment = NewIndividualCollectionSheetFragment()
fragment.arguments = args
return fragment
}
}
} | mpl-2.0 | e942dccf194c157a63c575848cd69442 | 36.889632 | 166 | 0.677172 | 4.916667 | false | false | false | false |
blackbbc/Tucao | app/src/main/kotlin/me/sweetll/tucao/business/login/RegisterActivity.kt | 1 | 4653 | package me.sweetll.tucao.business.login
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.content.Context
import android.content.Intent
import androidx.databinding.DataBindingUtil
import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.appcompat.widget.Toolbar
import android.view.View
import android.view.ViewTreeObserver
import androidx.interpolator.view.animation.FastOutSlowInInterpolator
import com.google.android.material.snackbar.Snackbar
import io.codetail.animation.ViewAnimationUtils
import me.sweetll.tucao.R
import me.sweetll.tucao.base.BaseActivity
import me.sweetll.tucao.business.login.viewmodel.RegisterViewModel
import me.sweetll.tucao.databinding.ActivityRegisterBinding
import me.sweetll.tucao.extension.dp2px
import me.sweetll.tucao.extension.logD
import me.sweetll.tucao.widget.MorphingButton
class RegisterActivity : BaseActivity() {
private lateinit var binding: ActivityRegisterBinding
private lateinit var viewModel: RegisterViewModel
override fun getStatusBar(): View = binding.statusBar
override fun getToolbar(): Toolbar = binding.toolbar
companion object {
fun intentTo(context: Context) {
val intent = Intent(context, RegisterActivity::class.java)
context.startActivity(intent)
}
}
private var buttonHeight: Int = 0
private var buttonWidth: Int = 0
override fun initView(savedInstanceState: Bundle?) {
binding = DataBindingUtil.setContentView(this, R.layout.activity_register)
viewModel = RegisterViewModel(this)
binding.viewModel = viewModel
binding.registerBtn.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
binding.registerBtn.viewTreeObserver.removeOnGlobalLayoutListener(this)
buttonWidth = binding.registerBtn.width
buttonHeight = binding.registerBtn.height
morphToSquare(binding.registerBtn, 0)
}
})
}
fun startRegister() {
"开始注册".logD()
morphToCircle(binding.registerBtn, 500)
}
fun registerSuccess() {
"注册成功".logD()
val cx = binding.registerBtn.left + binding.registerBtn.width / 2
val cy = binding.registerBtn.top + binding.registerBtn.height / 2 + binding.statusBar.height + binding.toolbar.height
val startRadius = buttonHeight / 2f
val finalRadius = Math.hypot(cy.toDouble(), cx.toDouble()) + 10f.dp2px()
val animator = ViewAnimationUtils.createCircularReveal(binding.revealView, cx, cy, startRadius, finalRadius.toFloat())
animator.interpolator = FastOutSlowInInterpolator()
animator.duration = 300
animator.addListener(object: AnimatorListenerAdapter() {
override fun onAnimationStart(animation: Animator?) {
binding.revealView.visibility = View.VISIBLE
}
override fun onAnimationEnd(animation: Animator?) {
finish()
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
}
})
animator.start()
}
fun registerFailed(msg: String) {
morphToSquare(binding.registerBtn, 500)
Snackbar.make(binding.root, msg, Snackbar.LENGTH_SHORT).show()
}
private fun morphToSquare(morphBtn: MorphingButton, duration: Int) {
val square = MorphingButton.Params.create()
.duration(duration)
.cornerRadius(20f.dp2px().toInt())
.width(buttonWidth)
.height(buttonHeight)
.color(ContextCompat.getColor(this, R.color.pink_400))
.colorPressed(ContextCompat.getColor(this, R.color.pink_700))
.text("创建新用户")
morphBtn.morph(square)
}
private fun morphToCircle(morphBtn: MorphingButton, duration: Int) {
val circle = MorphingButton.Params.create()
.duration(duration)
.cornerRadius(buttonHeight)
.width(buttonHeight)
.height(buttonHeight)
.color(ContextCompat.getColor(this, R.color.pink_400))
.colorPressed(ContextCompat.getColor(this, R.color.pink_700))
.icon(R.drawable.ic_code)
morphBtn.morph(circle)
}
override fun initToolbar() {
super.initToolbar()
supportActionBar?.let {
it.setDisplayHomeAsUpEnabled(true)
it.title = "注册帐号"
}
}
}
| mit | 6731013195c3a730d90bd087252b6832 | 36.860656 | 126 | 0.676986 | 4.670374 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/edithistory/EditHistoryAdapter.kt | 1 | 7704 | package de.westnordost.streetcomplete.edithistory
import android.text.format.DateUtils
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.view.isGone
import androidx.core.view.isInvisible
import androidx.recyclerview.widget.RecyclerView
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.edithistory.Edit
import de.westnordost.streetcomplete.data.edithistory.icon
import de.westnordost.streetcomplete.data.edithistory.overlayIcon
import de.westnordost.streetcomplete.databinding.RowEditItemBinding
import de.westnordost.streetcomplete.databinding.RowEditSyncedBinding
import de.westnordost.streetcomplete.ktx.findNext
import de.westnordost.streetcomplete.ktx.toast
import java.lang.System.currentTimeMillis
import java.text.DateFormat
import java.util.Collections
import kotlin.collections.ArrayList
/** Adapter to show the edit history in a list */
class EditHistoryAdapter(
val onSelected: (edit: Edit) -> Unit,
val onSelectionDeleted: () -> Unit,
val onUndo: (edit: Edit) -> Unit
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val rows: MutableList<EditHistoryItem> = ArrayList()
private var selectedEdit: Edit? = null
private var recyclerView: RecyclerView? = null
fun setEdits(edits: List<Edit>) {
rows.clear()
val sortedEdits = edits.sortedByDescending { it.createdTimestamp }
rows.addAll(sortedEdits.map { EditItem(it) })
val firstSyncedItemIndex = sortedEdits.indexOfFirst { it.isSynced == true }
if (firstSyncedItemIndex != -1) {
rows.add(firstSyncedItemIndex, IsSyncedItem)
}
notifyDataSetChanged()
}
fun onAdded(edit: Edit) {
var insertIndex = rows.indexOfFirst { it is EditItem && it.edit.createdTimestamp < edit.createdTimestamp }
if (insertIndex == -1) insertIndex = rows.size
rows.add(insertIndex, EditItem(edit))
if (insertIndex < rows.size) notifyItemChanged(insertIndex)
notifyItemInserted(insertIndex)
}
fun onSynced(edit: Edit) {
val editIndex = rows.indexOfFirst { it is EditItem && it.edit == edit }
check(editIndex != -1)
val syncedItemIndex = rows.indexOfFirst { it is IsSyncedItem }
if (syncedItemIndex != -1) {
Collections.swap(rows, syncedItemIndex, editIndex)
notifyItemMoved(syncedItemIndex, editIndex)
}
// there is no "synced" item yet
else {
rows.add(editIndex, IsSyncedItem)
notifyItemInserted(editIndex)
}
}
fun onDeleted(edits: List<Edit>) {
val editIndices = edits
.map { edit -> rows.indexOfFirst { it is EditItem && it.edit == edit } }
.filter { it != -1 }
.sortedDescending()
if (selectedEdit != null && edits.contains(selectedEdit)) {
selectedEdit = null
onSelectionDeleted()
}
for (index in editIndices) {
rows.removeAt(index)
notifyItemRemoved(index)
if (index < rows.size) notifyItemChanged(index)
}
}
override fun getItemViewType(position: Int): Int = when(rows[position]) {
is EditItem -> EDIT
IsSyncedItem -> SYNCED
}
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
this.recyclerView = recyclerView
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
super.onDetachedFromRecyclerView(recyclerView)
this.recyclerView = null
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val inflater = LayoutInflater.from(parent.context)
return when (viewType) {
EDIT -> EditViewHolder(RowEditItemBinding.inflate(inflater))
SYNCED -> SyncedViewHolder(RowEditSyncedBinding.inflate(inflater))
else -> throw IllegalArgumentException("Unknown viewType $viewType")
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val row = rows[position]
val rowAbove = rows.findNext(position+1) { it is EditItem } as EditItem?
when(holder) {
is EditViewHolder -> holder.onBind((row as EditItem).edit, rowAbove?.edit)
}
}
override fun getItemCount(): Int = rows.size
fun select(edit: Edit) {
val previousSelectedIndex = rows.indexOfFirst { it is EditItem && it.edit == selectedEdit }
val newSelectedIndex = rows.indexOfFirst { it is EditItem && it.edit == edit }
/* edit can in rare cases not be in adapter any more - when the edit is removed from the
database while it is being tapped */
if (newSelectedIndex == -1) return
recyclerView?.scrollToPosition(newSelectedIndex)
selectedEdit = edit
if (previousSelectedIndex != -1) notifyItemChanged(previousSelectedIndex)
notifyItemChanged(newSelectedIndex)
onSelected(edit)
}
private fun undo(edit: Edit) {
onUndo(edit)
}
private inner class EditViewHolder(
private val binding: RowEditItemBinding
) : RecyclerView.ViewHolder(binding.root) {
fun onBind(edit: Edit, editAbove: Edit?) {
binding.undoButtonIcon.isEnabled = edit.isUndoable
binding.undoButtonIcon.isInvisible = selectedEdit != edit
binding.selectionRing.isInvisible = selectedEdit != edit
if (edit.icon != 0) binding.questIcon.setImageResource(edit.icon)
else binding.questIcon.setImageDrawable(null)
if (edit.overlayIcon != 0) binding.overlayIcon.setImageResource(edit.overlayIcon)
else binding.overlayIcon.setImageDrawable(null)
val aboveTimeStr = editAbove?.formatSameDayTime()
val timeStr = edit.formatSameDayTime()
binding.timeTextContainer.isGone = aboveTimeStr == timeStr
binding.timeText.text = timeStr
// Only show today's date if there is an above from a different day
binding.todayTextContainer.isGone = !(edit.isToday && editAbove?.isToday == false)
binding.todayText.text = edit.formatDate()
val res = itemView.context.resources
val bgColor = res.getColor(if (edit.isSynced == true) R.color.slightly_greyed_out else R.color.background)
itemView.setBackgroundColor(bgColor)
binding.clickArea.isSelected = edit == selectedEdit
binding.clickArea.setOnClickListener {
if (selectedEdit == edit) {
if (edit.isUndoable) {
undo(edit)
} else {
itemView.context.toast(R.string.toast_undo_unavailable, Toast.LENGTH_LONG)
}
} else {
select(edit)
}
}
}
}
private class SyncedViewHolder(binding: RowEditSyncedBinding) : RecyclerView.ViewHolder(binding.root)
}
private fun Edit.formatSameDayTime() = DateUtils.formatSameDayTime(
createdTimestamp, currentTimeMillis(), DateFormat.SHORT, DateFormat.SHORT
)
private fun Edit.formatDate() = DateFormat.getDateInstance(DateFormat.SHORT).format(createdTimestamp)
private val Edit.isToday: Boolean get() = DateUtils.isToday(this.createdTimestamp)
private sealed class EditHistoryItem
private data class EditItem(val edit: Edit) : EditHistoryItem()
private object IsSyncedItem : EditHistoryItem()
private const val EDIT = 0
private const val SYNCED = 1
| gpl-3.0 | 7761533cc7f995b0f10fe5725a287423 | 36.580488 | 118 | 0.669912 | 4.738007 | false | false | false | false |
sleberknight/kotlin-koans | src/iv_properties/_35_HowDelegatesWork.kt | 1 | 1754 | package iv_properties
import iii_conventions.MyDate
import util.TODO
import java.util.*
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
fun todoTask35(): Nothing = TODO(
"""
Task 35.
A delegate expression must have special 'get' and 'set' methods.
You can see their signatures below (as members of the 'ReadWriteProperty' interface).
Implement the members of the class 'EffectiveDate' so it can be delegated to.
Store only the time in milliseconds in 'timeInMillis' property.
Use the extension functions 'MyDate.toMillis' and 'Long.toDate'.
""",
references = { date: MyDate -> date.toMillis().toDate()}
)
class D {
var date by EffectiveDate()
// The property date$delegate of type EffectiveDate is created;
// the generated 'get' and 'set' accessors for 'date' are delegated to it.
// You can look at the bytecode (by calling "Show Kotlin Bytecode" action in IntelliJ IDEA) for details.
}
class EffectiveDate<in R> : ReadWriteProperty<R, MyDate> {
var timeInMillis: Long? = null
override operator fun getValue(thisRef: R, property: KProperty<*>): MyDate {
return timeInMillis?.toDate() ?: throw IllegalStateException("not initialized")
}
override operator fun setValue(thisRef: R, property: KProperty<*>, value: MyDate) {
timeInMillis = value.toMillis()
}
}
fun MyDate.toMillis(): Long {
val c = Calendar.getInstance()
c.set(year, month, dayOfMonth, 0, 0, 0)
c.set(Calendar.MILLISECOND, 0)
return c.timeInMillis
}
fun Long.toDate(): MyDate {
val c = Calendar.getInstance()
c.timeInMillis = this
return MyDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE))
}
| mit | 1417582c3fa3be6ba5cb8a0a9f064500 | 32.730769 | 108 | 0.692702 | 4.246973 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/network/rest/wpcom/wc/order/OrderRestClient.kt | 2 | 42571 | @file:Suppress("DEPRECATION_ERROR")
package org.wordpress.android.fluxc.network.rest.wpcom.wc.order
import android.content.Context
import com.android.volley.RequestQueue
import com.google.gson.JsonElement
import com.google.gson.reflect.TypeToken
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.action.WCOrderAction
import org.wordpress.android.fluxc.generated.WCOrderActionBuilder
import org.wordpress.android.fluxc.generated.endpoint.WOOCOMMERCE
import org.wordpress.android.fluxc.model.LocalOrRemoteId.RemoteId
import org.wordpress.android.fluxc.model.OrderEntity
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.WCOrderListDescriptor
import org.wordpress.android.fluxc.model.WCOrderShipmentProviderModel
import org.wordpress.android.fluxc.model.WCOrderShipmentTrackingModel
import org.wordpress.android.fluxc.model.WCOrderStatusModel
import org.wordpress.android.fluxc.model.WCOrderSummaryModel
import org.wordpress.android.fluxc.model.order.UpdateOrderRequest
import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType
import org.wordpress.android.fluxc.network.UserAgent
import org.wordpress.android.fluxc.network.rest.wpcom.BaseWPComRestClient
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequest
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequest.WPComErrorListener
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequest.WPComGsonNetworkError
import org.wordpress.android.fluxc.network.rest.wpcom.auth.AccessToken
import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequest
import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder
import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackError
import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackSuccess
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooError
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooErrorType
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooPayload
import org.wordpress.android.fluxc.network.rest.wpcom.wc.order.OrderDto.Billing
import org.wordpress.android.fluxc.network.rest.wpcom.wc.order.OrderDto.Shipping
import org.wordpress.android.fluxc.network.rest.wpcom.wc.order.OrderDtoMapper.Companion.toDto
import org.wordpress.android.fluxc.network.rest.wpcom.wc.toWooError
import org.wordpress.android.fluxc.persistence.entity.OrderNoteEntity
import org.wordpress.android.fluxc.store.WCOrderStore
import org.wordpress.android.fluxc.store.WCOrderStore.AddOrderShipmentTrackingResponsePayload
import org.wordpress.android.fluxc.store.WCOrderStore.DeleteOrderShipmentTrackingResponsePayload
import org.wordpress.android.fluxc.store.WCOrderStore.FetchHasOrdersResponsePayload
import org.wordpress.android.fluxc.store.WCOrderStore.FetchOrderListResponsePayload
import org.wordpress.android.fluxc.store.WCOrderStore.FetchOrderShipmentProvidersResponsePayload
import org.wordpress.android.fluxc.store.WCOrderStore.FetchOrderShipmentTrackingsResponsePayload
import org.wordpress.android.fluxc.store.WCOrderStore.FetchOrderStatusOptionsResponsePayload
import org.wordpress.android.fluxc.store.WCOrderStore.FetchOrdersByIdsResponsePayload
import org.wordpress.android.fluxc.store.WCOrderStore.FetchOrdersCountResponsePayload
import org.wordpress.android.fluxc.store.WCOrderStore.FetchOrdersResponsePayload
import org.wordpress.android.fluxc.store.WCOrderStore.OrderError
import org.wordpress.android.fluxc.store.WCOrderStore.OrderErrorType
import org.wordpress.android.fluxc.store.WCOrderStore.OrderErrorType.GENERIC_ERROR
import org.wordpress.android.fluxc.store.WCOrderStore.OrderErrorType.INVALID_RESPONSE
import org.wordpress.android.fluxc.store.WCOrderStore.RemoteOrderPayload
import org.wordpress.android.fluxc.store.WCOrderStore.SearchOrdersResponsePayload
import org.wordpress.android.fluxc.utils.DateUtils
import org.wordpress.android.fluxc.utils.putIfNotEmpty
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AppLog.T
import java.util.Calendar
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Singleton
import kotlin.collections.MutableMap.MutableEntry
@Suppress("LargeClass")
@Singleton
class OrderRestClient @Inject constructor(
appContext: Context,
private val dispatcher: Dispatcher,
@Named("regular") requestQueue: RequestQueue,
private val jetpackTunnelGsonRequestBuilder: JetpackTunnelGsonRequestBuilder,
private val orderDtoMapper: OrderDtoMapper,
accessToken: AccessToken,
userAgent: UserAgent
) : BaseWPComRestClient(appContext, dispatcher, requestQueue, accessToken, userAgent) {
/**
* Makes a GET call to `/wc/v3/orders` via the Jetpack tunnel (see [JetpackTunnelGsonRequest]),
* retrieving a list of orders for the given WooCommerce [SiteModel].
*
* The number of orders fetched is defined in [WCOrderStore.NUM_ORDERS_PER_FETCH], and retrieving older
* orders is done by passing an [offset].
*
* Dispatches a [WCOrderAction.FETCHED_ORDERS] action with the resulting list of orders.
*
* @param [filterByStatus] Nullable. If not null, fetch only orders with a matching order status.
*/
fun fetchOrders(site: SiteModel, offset: Int, filterByStatus: String? = null) {
// If null, set the filter to the api default value of "any", which will not apply any order status filters.
val statusFilter = filterByStatus.takeUnless { it.isNullOrBlank() } ?: WCOrderStore.DEFAULT_ORDER_STATUS
val url = WOOCOMMERCE.orders.pathV3
val responseType = object : TypeToken<List<OrderDto>>() {}.type
val params = mapOf(
"per_page" to WCOrderStore.NUM_ORDERS_PER_FETCH.toString(),
"offset" to offset.toString(),
"status" to statusFilter,
"_fields" to ORDER_FIELDS)
val request = JetpackTunnelGsonRequest.buildGetRequest(url, site.siteId, params, responseType,
{ response: List<OrderDto>? ->
val orderModels = response?.map { orderDto ->
orderDtoMapper.toDatabaseEntity(orderDto, site.localId())
}.orEmpty()
val canLoadMore = orderModels.size == WCOrderStore.NUM_ORDERS_PER_FETCH
val payload = FetchOrdersResponsePayload(
site, orderModels, filterByStatus, offset > 0, canLoadMore)
dispatcher.dispatch(WCOrderActionBuilder.newFetchedOrdersAction(payload))
},
WPComErrorListener { networkError ->
val orderError = networkErrorToOrderError(networkError)
val payload = FetchOrdersResponsePayload(orderError, site)
dispatcher.dispatch(WCOrderActionBuilder.newFetchedOrdersAction(payload))
},
{ request: WPComGsonRequest<*> -> add(request) })
add(request)
}
/**
* Fetches orders from the API, but only requests `id` and `date_created_gmt` fields be returned. This is
* used to determine what orders should be fetched (either existing orders that have since changed or new
* orders not yet downloaded).
*
* Makes a GET call to `/wc/v3/orders` via the Jetpack tunnel (see [JetpackTunnelGsonRequest]),
* retrieving a list of orders for the given WooCommerce [SiteModel].
*
* Dispatches a [WCOrderAction.FETCHED_ORDER_LIST] action with the resulting list of order summaries.
*
* @param listDescriptor The [WCOrderListDescriptor] that describes the type of list being fetched and
* the optional parameters in effect.
* @param offset Used to retrieve older orders
*/
fun fetchOrderListSummaries(listDescriptor: WCOrderListDescriptor, offset: Long, requestStartTime: Calendar) {
// If null, set the filter to the api default value of "any", which will not apply any order status filters.
val statusFilter = listDescriptor.statusFilter.takeUnless { it.isNullOrBlank() }
?: WCOrderStore.DEFAULT_ORDER_STATUS
val url = WOOCOMMERCE.orders.pathV3
val responseType = object : TypeToken<List<OrderSummaryApiResponse>>() {}.type
val networkPageSize = listDescriptor.config.networkPageSize
val params = mutableMapOf(
"per_page" to networkPageSize.toString(),
"offset" to offset.toString(),
"status" to statusFilter,
"_fields" to "id,date_created_gmt,date_modified_gmt"
).putIfNotEmpty(
"search" to listDescriptor.searchQuery,
"before" to listDescriptor.beforeFilter,
"after" to listDescriptor.afterFilter
)
val request = JetpackTunnelGsonRequest.buildGetRequest(url, listDescriptor.site.siteId, params, responseType,
{ response: List<OrderSummaryApiResponse>? ->
val orderSummaries = response?.map {
orderResponseToOrderSummaryModel(it).apply { localSiteId = listDescriptor.site.id }
}.orEmpty()
val canLoadMore = orderSummaries.size == networkPageSize
val payload = FetchOrderListResponsePayload(
listDescriptor = listDescriptor,
orderSummaries = orderSummaries,
loadedMore = offset > 0,
canLoadMore = canLoadMore,
requestStartTime = requestStartTime
)
dispatcher.dispatch(WCOrderActionBuilder.newFetchedOrderListAction(payload))
},
WPComErrorListener { networkError ->
val orderError = networkErrorToOrderError(networkError)
val payload = FetchOrderListResponsePayload(
error = orderError,
listDescriptor = listDescriptor,
requestStartTime = requestStartTime
)
dispatcher.dispatch(WCOrderActionBuilder.newFetchedOrderListAction(payload))
},
{ request: WPComGsonRequest<*> -> add(request) })
add(request)
}
/**
* Requests orders from the API that match the provided list of [orderIds] by making a GET call to
* `/wc/v3/orders` via the Jetpack tunnel (see [JetpackTunnelGsonRequest]).
*
* Dispatches a [WCOrderAction.FETCHED_ORDERS_BY_IDS] action with the resulting list of orders.
*
* @param site The WooCommerce [SiteModel] the orders belong to
* @param orderIds A list of remote order identifiers to fetch from the API
*/
fun fetchOrdersByIds(site: SiteModel, orderIds: List<Long>) {
val url = WOOCOMMERCE.orders.pathV3
val responseType = object : TypeToken<List<OrderDto>>() {}.type
val params = mapOf(
"per_page" to orderIds.size.toString(),
"include" to orderIds.map { it }.joinToString(),
"_fields" to ORDER_FIELDS)
val request = JetpackTunnelGsonRequest.buildGetRequest(url, site.siteId, params, responseType,
{ response: List<OrderDto>? ->
val orderModels = response?.map { orderDto ->
orderDtoMapper.toDatabaseEntity(orderDto, site.localId())
}.orEmpty()
val payload = FetchOrdersByIdsResponsePayload(
site = site,
orderIds = orderIds,
fetchedOrders = orderModels
)
dispatcher.dispatch(WCOrderActionBuilder.newFetchedOrdersByIdsAction(payload))
},
{ networkError ->
val orderError = networkErrorToOrderError(networkError)
val payload = FetchOrdersByIdsResponsePayload(
error = orderError, site = site, orderIds = orderIds)
dispatcher.dispatch(WCOrderActionBuilder.newFetchedOrdersByIdsAction(payload))
},
{ request: WPComGsonRequest<*> -> add(request) })
add(request)
}
/**
* Makes a GET call to `/wc/v3/reports/orders/totals` via the Jetpack tunnel (see [JetpackTunnelGsonRequest]),
* retrieving a list of available order status options for the given WooCommerce [SiteModel].
*
* Dispatches a [WCOrderAction.FETCHED_ORDER_STATUS_OPTIONS] action with the resulting list of order status labels.
*/
fun fetchOrderStatusOptions(site: SiteModel) {
val url = WOOCOMMERCE.reports.orders.totals.pathV3
val params = emptyMap<String, String>()
val responseType = object : TypeToken<List<OrderStatusApiResponse>>() {}.type
val request = JetpackTunnelGsonRequest.buildGetRequest(url, site.siteId, params, responseType,
{ response: List<OrderStatusApiResponse>? ->
val orderStatusOptions = response?.map {
orderStatusResponseToOrderStatusModel(it, site)
}.orEmpty()
val payload = FetchOrderStatusOptionsResponsePayload(site, orderStatusOptions)
dispatcher.dispatch(WCOrderActionBuilder.newFetchedOrderStatusOptionsAction(payload))
},
{ networkError ->
val orderError = networkErrorToOrderError(networkError)
val payload = FetchOrderStatusOptionsResponsePayload(orderError, site)
dispatcher.dispatch(WCOrderActionBuilder.newFetchedOrderStatusOptionsAction(payload))
},
{ request: WPComGsonRequest<*> -> add(request) })
add(request)
}
/**
* Makes a GET call to `/wc/v3/orders` via the Jetpack tunnel (see [JetpackTunnelGsonRequest]),
* retrieving a list of orders for the given WooCommerce [SiteModel] matching [searchQuery]
*
* The number of orders fetched is defined in [WCOrderStore.NUM_ORDERS_PER_FETCH]
*
* Dispatches a [WCOrderAction.SEARCHED_ORDERS] action with the resulting list of orders.
*
* @param [searchQuery] the keyword or phrase to match orders with
*/
fun searchOrders(site: SiteModel, searchQuery: String, offset: Int) {
val url = WOOCOMMERCE.orders.pathV3
val responseType = object : TypeToken<List<OrderDto>>() {}.type
val params = mutableMapOf(
"per_page" to WCOrderStore.NUM_ORDERS_PER_FETCH.toString(),
"offset" to offset.toString(),
"status" to WCOrderStore.DEFAULT_ORDER_STATUS,
"_fields" to ORDER_FIELDS
).putIfNotEmpty("search" to searchQuery)
val request = JetpackTunnelGsonRequest.buildGetRequest(url, site.siteId, params, responseType,
{ response: List<OrderDto>? ->
val orderModels = response?.map { orderDto ->
orderDtoMapper.toDatabaseEntity(orderDto, site.localId())
}.orEmpty()
val canLoadMore = orderModels.size == WCOrderStore.NUM_ORDERS_PER_FETCH
val nextOffset = offset + orderModels.size
val payload = SearchOrdersResponsePayload(
site,
searchQuery,
canLoadMore,
nextOffset,
orderModels.map { it.first }
)
dispatcher.dispatch(WCOrderActionBuilder.newSearchedOrdersAction(payload))
},
WPComErrorListener { networkError ->
val orderError = networkErrorToOrderError(networkError)
val payload = SearchOrdersResponsePayload(orderError, site, searchQuery)
dispatcher.dispatch(WCOrderActionBuilder.newSearchedOrdersAction(payload))
},
{ request: WPComGsonRequest<*> -> add(request) })
add(request)
}
/**
* Makes a GET request to `/wc/v3/orders/{remoteOrderId}` to fetch a single order by the remoteOrderId.
*
* @param [orderId] Unique server id of the order to fetch
*/
suspend fun fetchSingleOrder(site: SiteModel, orderId: Long): RemoteOrderPayload.Fetching {
val url = WOOCOMMERCE.orders.id(orderId).pathV3
val params = mapOf("_fields" to ORDER_FIELDS)
val response = jetpackTunnelGsonRequestBuilder.syncGetRequest(
this,
site,
url,
params,
OrderDto::class.java
)
return when (response) {
is JetpackSuccess -> {
response.data?.let { orderDto ->
val newModel = orderDtoMapper.toDatabaseEntity(orderDto, site.localId())
RemoteOrderPayload.Fetching(newModel, site)
} ?: RemoteOrderPayload.Fetching(
OrderError(type = GENERIC_ERROR, message = "Success response with empty data"),
OrderEntity(
orderId = orderId,
localSiteId = site.localId()
) to emptyList(),
site
)
}
is JetpackError -> {
val orderError = networkErrorToOrderError(response.error)
RemoteOrderPayload.Fetching(
orderError,
OrderEntity(
orderId = orderId,
localSiteId = site.localId()
) to emptyList(),
site
)
}
}
}
/**
* Makes a GET call to `/wc/v3/reports/orders/totals` via the Jetpack tunnel (see [JetpackTunnelGsonRequest]),
* retrieving count of orders for the given WooCommerce [SiteModel], broken down by order status.
*
* Dispatches a [WCOrderAction.FETCHED_ORDERS_COUNT] action with the resulting count.
*
* @param [filterByStatus] The order status to return a count for
*/
fun fetchOrderCount(site: SiteModel, filterByStatus: String) {
val url = WOOCOMMERCE.reports.orders.totals.pathV3
val params = mapOf("status" to filterByStatus)
val responseType = object : TypeToken<List<OrderCountApiResponse>>() {}.type
val request = JetpackTunnelGsonRequest.buildGetRequest(url, site.siteId, params, responseType,
{ response: List<OrderCountApiResponse>? ->
val total = response?.find { it.slug == filterByStatus }?.total
total?.let {
val payload = FetchOrdersCountResponsePayload(site, filterByStatus, it)
dispatcher.dispatch(WCOrderActionBuilder.newFetchedOrdersCountAction(payload))
} ?: run {
val orderError = OrderError(OrderErrorType.ORDER_STATUS_NOT_FOUND)
val payload = FetchOrdersCountResponsePayload(orderError, site, filterByStatus)
dispatcher.dispatch(WCOrderActionBuilder.newFetchedOrdersCountAction(payload))
}
},
WPComErrorListener { networkError ->
val orderError = networkErrorToOrderError(networkError)
val payload = FetchOrdersCountResponsePayload(orderError, site, filterByStatus)
dispatcher.dispatch(WCOrderActionBuilder.newFetchedOrdersCountAction(payload))
},
{ request: WPComGsonRequest<*> -> add(request) })
add(request)
}
/**
* Makes a GET request to `/wc/v3/orders` for a single order of a specific type (or any type) in order to
* determine if there are any orders in the store.
*
*
* @param [filterByStatus] Nullable. If not null, consider only orders with a matching order status.
*/
suspend fun fetchHasOrders(site: SiteModel, filterByStatus: String? = null): FetchHasOrdersResponsePayload {
val statusFilter = if (filterByStatus.isNullOrBlank()) { "any" } else { filterByStatus }
val url = WOOCOMMERCE.orders.pathV3
val params = mapOf(
"per_page" to "1",
"offset" to "0",
"status" to statusFilter)
val response = jetpackTunnelGsonRequestBuilder.syncGetRequest(
this,
site,
url,
params,
Array<OrderDto>::class.java
)
return when (response) {
is JetpackSuccess -> {
response.data?.let {
FetchHasOrdersResponsePayload(
site,
filterByStatus,
it.count() > 0
)
} ?: FetchHasOrdersResponsePayload(
OrderError(type = GENERIC_ERROR, message = "Success response with empty data"),
site
)
}
is JetpackError -> {
var orderError = networkErrorToOrderError(response.error)
FetchHasOrdersResponsePayload(
orderError,
site
)
}
}
}
/**
* Makes a PUT call to `/wc/v3/orders/<id>` via the Jetpack tunnel (see [JetpackTunnelGsonRequest]),
* updating the order.
*/
private suspend fun updateOrder(
orderToUpdate: OrderEntity,
site: SiteModel,
updatePayload: Map<String, Any>
): RemoteOrderPayload.Updating {
val url = WOOCOMMERCE.orders.id(orderToUpdate.orderId).pathV3
val response = jetpackTunnelGsonRequestBuilder.syncPutRequest(
restClient = this,
site = site,
url = url,
body = updatePayload.plus("_fields" to ORDER_FIELDS),
clazz = OrderDto::class.java
)
return when (response) {
is JetpackSuccess -> {
response.data?.let { orderDto ->
val newModel = orderDtoMapper.toDatabaseEntity(orderDto, site.localId())
.first
.copy(
orderId = orderToUpdate.orderId
)
RemoteOrderPayload.Updating(newModel, site)
} ?: RemoteOrderPayload.Updating(
OrderError(type = GENERIC_ERROR, message = "Success response with empty data"),
orderToUpdate,
site
)
}
is JetpackError -> {
val orderError = networkErrorToOrderError(response.error)
RemoteOrderPayload.Updating(
orderError,
orderToUpdate,
site
)
}
}
}
suspend fun updateOrderStatus(orderToUpdate: OrderEntity, site: SiteModel, status: String) =
updateOrder(orderToUpdate, site, mapOf("status" to status))
suspend fun updateCustomerOrderNote(orderToUpdate: OrderEntity, site: SiteModel, newNotes: String) =
updateOrder(orderToUpdate, site, mapOf("customer_note" to newNotes))
suspend fun updateBillingAddress(orderToUpdate: OrderEntity, site: SiteModel, billing: Billing) =
updateOrder(orderToUpdate, site, mapOf("billing" to billing))
suspend fun updateShippingAddress(orderToUpdate: OrderEntity, site: SiteModel, shipping: Shipping) =
updateOrder(orderToUpdate, site, mapOf("shipping" to shipping))
suspend fun updateBothOrderAddresses(
orderToUpdate: OrderEntity,
site: SiteModel,
shipping: Shipping,
billing: Billing
) = updateOrder(
orderToUpdate, site,
mapOf("shipping" to shipping, "billing" to billing)
)
/**
* Makes a GET call to `/wc/v3/orders/<id>/notes` via the Jetpack tunnel (see [JetpackTunnelGsonRequest]),
* retrieving a list of notes for the given WooCommerce [SiteModel] and [OrderEntity].
*/
suspend fun fetchOrderNotes(
orderId: Long,
site: SiteModel
): WooPayload<List<OrderNoteEntity>> {
val url = WOOCOMMERCE.orders.id(orderId).notes.pathV3
val response = jetpackTunnelGsonRequestBuilder.syncGetRequest(
this,
site,
url,
mapOf(),
Array<OrderNoteApiResponse>::class.java
)
return when (response) {
is JetpackSuccess -> {
val noteModels = response.data?.map {
it.toDataModel(site.remoteId(), RemoteId(orderId))
}.orEmpty()
WooPayload(noteModels)
}
is JetpackError -> WooPayload(response.error.toWooError())
}
}
/**
* Makes a POST call to `/wc/v3/orders/<id>/notes` via the Jetpack tunnel (see [JetpackTunnelGsonRequest]),
* saving the provide4d note for the given WooCommerce [SiteModel] and [OrderEntity].
*/
suspend fun postOrderNote(
orderId: Long,
site: SiteModel,
note: String,
isCustomerNote: Boolean
): WooPayload<OrderNoteEntity> {
val url = WOOCOMMERCE.orders.id(orderId).notes.pathV3
val params = mutableMapOf(
"note" to note,
"customer_note" to isCustomerNote,
"added_by_user" to true
)
val response = jetpackTunnelGsonRequestBuilder.syncPostRequest(
this,
site,
url,
params,
OrderNoteApiResponse::class.java
)
return when (response) {
is JetpackSuccess -> {
response.data?.let {
val newNote = it.toDataModel(site.remoteId(), RemoteId(orderId))
return WooPayload(newNote)
} ?: WooPayload(
WooError(
type = WooErrorType.GENERIC_ERROR,
original = GenericErrorType.UNKNOWN,
message = "Success response with empty data"
)
)
}
is JetpackError -> WooPayload(response.error.toWooError())
}
}
/**
* Makes a GET call to `/wc/v2/orders/<order_id>/shipment-trackings/` via the Jetpack tunnel
* (see [JetpackTunnelGsonRequest]), retrieving a list of shipment tracking objects for a single [OrderEntity].
*
* Note: This is not currently supported in v3, but will be in the short future.
*
*/
suspend fun fetchOrderShipmentTrackings(
site: SiteModel,
orderId: Long
): FetchOrderShipmentTrackingsResponsePayload {
val url = WOOCOMMERCE.orders.id(orderId).shipment_trackings.pathV2
val params = mapOf("_fields" to TRACKING_FIELDS)
val response = jetpackTunnelGsonRequestBuilder.syncGetRequest(
this,
site,
url,
params,
Array<OrderShipmentTrackingApiResponse>::class.java
)
return when (response) {
is JetpackSuccess -> {
val trackings = response.data?.map {
orderShipmentTrackingResponseToModel(it).apply {
localSiteId = site.id
this.orderId = orderId
}
}.orEmpty()
FetchOrderShipmentTrackingsResponsePayload(site, orderId, trackings)
}
is JetpackError -> {
val trackingsError = networkErrorToOrderError(response.error)
FetchOrderShipmentTrackingsResponsePayload(trackingsError, site, orderId)
}
}
}
/**
* Posts a new Order Shipment Tracking record to the API for an order.
*
* Makes a POST call to save a Shipment Tracking record via the Jetpack tunnel (see [JetpackTunnelGsonRequest]).
* The API calls for different fields depending on if the new record uses a custom provider or not, so this is
* why there is an if-statement. Either way, the same standard [WCOrderShipmentTrackingModel] is returned.
*
* Note: This API does not currently support v3.
*/
suspend fun addOrderShipmentTrackingForOrder(
site: SiteModel,
orderId: Long,
tracking: WCOrderShipmentTrackingModel,
isCustomProvider: Boolean
): AddOrderShipmentTrackingResponsePayload {
val url = WOOCOMMERCE.orders.id(orderId).shipment_trackings.pathV2
val params = if (isCustomProvider) {
mutableMapOf(
"custom_tracking_provider" to tracking.trackingProvider,
"custom_tracking_link" to tracking.trackingLink)
} else {
mutableMapOf("tracking_provider" to tracking.trackingProvider)
}
params.put("tracking_number", tracking.trackingNumber)
params.put("date_shipped", tracking.dateShipped)
val response = jetpackTunnelGsonRequestBuilder.syncPostRequest(
this,
site,
url,
params,
OrderShipmentTrackingApiResponse::class.java
)
return when (response) {
is JetpackSuccess -> {
response.data?.let {
val trackingModel = orderShipmentTrackingResponseToModel(it).apply {
this.orderId = orderId
localSiteId = site.id
}
AddOrderShipmentTrackingResponsePayload(site, orderId, trackingModel)
} ?: AddOrderShipmentTrackingResponsePayload(
OrderError(type = GENERIC_ERROR, message = "Success response with empty data"),
site,
orderId,
tracking
)
}
is JetpackError -> {
val trackingsError = networkErrorToOrderError(response.error)
AddOrderShipmentTrackingResponsePayload(trackingsError, site, orderId, tracking)
}
}
}
/**
* Deletes a single shipment tracking record for an order.
*
* Makes a POST call requesting a DELETE method on `/wc/v2/orders/<order_id>/shipment_trackings/<tracking_id>/`
* via the Jetpack tunnel (see [JetpackTunnelGsonRequest].
*
* Note this is currently not supported in v3, but will be in the future.
*/
suspend fun deleteShipmentTrackingForOrder(
site: SiteModel,
orderId: Long,
tracking: WCOrderShipmentTrackingModel
): DeleteOrderShipmentTrackingResponsePayload {
val url = WOOCOMMERCE.orders.id(orderId)
.shipment_trackings.tracking(tracking.remoteTrackingId).pathV2
val response = jetpackTunnelGsonRequestBuilder.syncDeleteRequest(
this,
site,
url,
OrderShipmentTrackingApiResponse::class.java
)
return when (response) {
is JetpackSuccess -> {
response.data?.let {
val model = orderShipmentTrackingResponseToModel(it).apply {
localSiteId = site.id
this.orderId = orderId
id = tracking.id
}
DeleteOrderShipmentTrackingResponsePayload(
site,
orderId,
model
)
} ?: DeleteOrderShipmentTrackingResponsePayload(
OrderError(type = GENERIC_ERROR, message = "Success response with empty data"),
site,
orderId,
tracking
)
}
is JetpackError -> {
DeleteOrderShipmentTrackingResponsePayload(
networkErrorToOrderError(response.error),
site,
orderId,
tracking
)
}
}
}
/**
* Fetches a list of shipment providers from the WooCommerce Shipment Tracking plugin.
*
* Makes a GET call to `/wc/v2/orders/<order_id>/shipment-trackings/providers/` via the Jetpack tunnel
* (see [JetpackTunnelGsonRequest]), retrieving a list of shipment tracking provider objects. The `<order_id>`
* argument is only needed because it is a requirement of the plugins API even though this data is not directly
* related to shipment providers.
*/
suspend fun fetchOrderShipmentProviders(
site: SiteModel,
order: OrderEntity
): FetchOrderShipmentProvidersResponsePayload {
val url = WOOCOMMERCE.orders.id(order.orderId).shipment_trackings.providers.pathV2
val params = emptyMap<String, String>()
val response = jetpackTunnelGsonRequestBuilder.syncGetRequest(
this,
site,
url,
params,
JsonElement::class.java
)
return when (response) {
is JetpackSuccess -> {
response.data?.let {
try {
val providers = jsonResponseToShipmentProviderList(site, it)
FetchOrderShipmentProvidersResponsePayload(site, order, providers)
} catch (e: IllegalStateException) {
// we have at least once instance of the response being invalid json so we catch the exception
// https://github.com/wordpress-mobile/WordPress-FluxC-Android/issues/1331
AppLog.e(T.UTILS, "IllegalStateException parsing shipment provider list, response = $it")
FetchOrderShipmentProvidersResponsePayload(
OrderError(INVALID_RESPONSE, it.toString()),
site,
order
)
}
} ?: FetchOrderShipmentProvidersResponsePayload(
OrderError(GENERIC_ERROR, "Success response with empty data"),
site,
order
)
}
is JetpackError -> {
val trackingError = networkErrorToOrderError(response.error)
FetchOrderShipmentProvidersResponsePayload(trackingError, site, order)
}
}
}
suspend fun createOrder(
site: SiteModel,
request: UpdateOrderRequest
): WooPayload<OrderEntity> {
val url = WOOCOMMERCE.orders.pathV3
val params = request.toNetworkRequest()
val response = jetpackTunnelGsonRequestBuilder.syncPostRequest(
this,
site,
url,
params,
OrderDto::class.java
)
return when (response) {
is JetpackError -> WooPayload(response.error.toWooError())
is JetpackSuccess -> response.data?.let { orderDto ->
WooPayload(orderDtoMapper.toDatabaseEntity(orderDto, site.localId()).first)
} ?: WooPayload(
error = WooError(
type = WooErrorType.GENERIC_ERROR,
original = GenericErrorType.UNKNOWN,
message = "Success response with empty data"
)
)
}
}
suspend fun updateOrder(
site: SiteModel,
orderId: Long,
request: UpdateOrderRequest
): WooPayload<OrderEntity> {
val url = WOOCOMMERCE.orders.id(orderId).pathV3
val params = request.toNetworkRequest()
val response = jetpackTunnelGsonRequestBuilder.syncPutRequest(
this,
site,
url,
params,
OrderDto::class.java
)
return when (response) {
is JetpackError -> WooPayload(response.error.toWooError())
is JetpackSuccess -> response.data?.let { orderDto ->
WooPayload(orderDtoMapper.toDatabaseEntity(orderDto, site.localId()).first)
} ?: WooPayload(
error = WooError(
type = WooErrorType.GENERIC_ERROR,
original = GenericErrorType.UNKNOWN,
message = "Success response with empty data"
)
)
}
}
suspend fun deleteOrder(
site: SiteModel,
orderId: Long,
trash: Boolean
): WooPayload<Unit> {
val url = WOOCOMMERCE.orders.id(orderId).pathV3
val response = jetpackTunnelGsonRequestBuilder.syncDeleteRequest(
restClient = this,
site = site,
url = url,
clazz = Unit::class.java,
params = mapOf("force" to trash.not().toString())
)
return when (response) {
is JetpackError -> WooPayload(response.error.toWooError())
is JetpackSuccess -> WooPayload(Unit)
}
}
private fun UpdateOrderRequest.toNetworkRequest(): Map<String, Any> {
return mutableMapOf<String, Any>().apply {
status?.let { put("status", it.statusKey) }
lineItems?.let { put("line_items", it) }
shippingAddress?.toDto()?.let { put("shipping", it) }
billingAddress?.toDto()?.let { put("billing", it) }
feeLines?.let { put("fee_lines", it) }
shippingLines?.let { put("shipping_lines", it) }
customerNote?.let { put("customer_note", it) }
}
}
private fun orderResponseToOrderSummaryModel(response: OrderSummaryApiResponse): WCOrderSummaryModel {
return WCOrderSummaryModel().apply {
orderId = response.id ?: 0
dateCreated = convertDateToUTCString(response.dateCreatedGmt)
dateModified = convertDateToUTCString(response.dateModifiedGmt)
}
}
private fun networkErrorToOrderError(wpComError: WPComGsonNetworkError): OrderError {
val orderErrorType = when (wpComError.apiError) {
"rest_invalid_param" -> OrderErrorType.INVALID_PARAM
"woocommerce_rest_shop_order_invalid_id" -> OrderErrorType.INVALID_ID
"rest_no_route" -> OrderErrorType.PLUGIN_NOT_ACTIVE
else -> OrderErrorType.fromString(wpComError.apiError)
}
return OrderError(orderErrorType, wpComError.message)
}
private fun orderStatusResponseToOrderStatusModel(
response: OrderStatusApiResponse,
site: SiteModel
): WCOrderStatusModel {
return WCOrderStatusModel().apply {
localSiteId = site.id
statusKey = response.slug ?: ""
label = response.name ?: ""
statusCount = response.total
}
}
private fun orderShipmentTrackingResponseToModel(
response: OrderShipmentTrackingApiResponse
): WCOrderShipmentTrackingModel {
return WCOrderShipmentTrackingModel().apply {
remoteTrackingId = response.tracking_id ?: ""
trackingNumber = response.tracking_number ?: ""
trackingProvider = response.tracking_provider ?: ""
trackingLink = response.tracking_link ?: ""
dateShipped = response.date_shipped ?: ""
}
}
private fun convertDateToUTCString(date: String?): String =
date?.let { DateUtils.formatGmtAsUtcDateString(it) } ?: "" // Store the date in UTC format
private fun jsonResponseToShipmentProviderList(
site: SiteModel,
response: JsonElement
): List<WCOrderShipmentProviderModel> {
val providers = mutableListOf<WCOrderShipmentProviderModel>()
response.asJsonObject.entrySet()
.forEach { countryEntry: MutableEntry<String, JsonElement> ->
countryEntry.value.asJsonObject.entrySet().map { carrierEntry ->
carrierEntry?.let { carrier ->
val provider = WCOrderShipmentProviderModel().apply {
localSiteId = site.id
this.country = countryEntry.key
this.carrierName = carrier.key
this.carrierLink = carrier.value.asString
}
providers.add(provider)
}
}
}
return providers
}
companion object {
private val ORDER_FIELDS = arrayOf(
"billing",
"coupon_lines",
"currency",
"order_key",
"customer_note",
"date_created_gmt",
"date_modified_gmt",
"date_paid_gmt",
"discount_total",
"fee_lines",
"tax_lines",
"id",
"line_items",
"number",
"payment_method",
"payment_method_title",
"prices_include_tax",
"refunds",
"shipping",
"shipping_lines",
"shipping_total",
"status",
"total",
"total_tax",
"meta_data",
"payment_url",
"is_editable"
).joinToString(separator = ",")
private val TRACKING_FIELDS = arrayOf(
"date_shipped",
"tracking_id",
"tracking_link",
"tracking_number",
"tracking_provider"
).joinToString(separator = ",")
}
}
| gpl-2.0 | a61302361c5be75c2b212027df963d40 | 43.43737 | 130 | 0.597261 | 5.477483 | false | false | false | false |
stronganizer/stronganizer-android | Stronganizer/app/src/main/java/com/stronganizer/android/data/model/User.kt | 1 | 581 | package com.stronganizer.android.data.model
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
/**
* Created by valio_stoyanov on 7/30/17.
*/
@Entity(tableName = "user") data class User(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
@ColumnInfo(name = "first_name") val firstName: String,
@ColumnInfo(name = "last_name") val lastName: String,
@ColumnInfo(name = "email") val email: String,
@ColumnInfo(name = "password") val password: String
) | apache-2.0 | ad84fbf9aed01be69c52ebf9da4979d9 | 33.235294 | 63 | 0.702238 | 3.748387 | false | false | false | false |
brianmadden/krawler | src/main/kotlin/io/thelandscape/krawler/crawler/Krawler.kt | 1 | 19623 | /**
* Created by [email protected] on 10/26/16.
*
* Copyright (c) <2016> <H, llc>
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.thelandscape.krawler.crawler
import io.thelandscape.krawler.HSQLConnection
import io.thelandscape.krawler.crawler.History.KrawlHistoryEntry
import io.thelandscape.krawler.crawler.History.KrawlHistoryHSQLDao
import io.thelandscape.krawler.crawler.History.KrawlHistoryIf
import io.thelandscape.krawler.crawler.KrawlQueue.KrawlQueueEntry
import io.thelandscape.krawler.crawler.KrawlQueue.KrawlQueueHSQLDao
import io.thelandscape.krawler.crawler.KrawlQueue.KrawlQueueIf
import io.thelandscape.krawler.crawler.KrawlQueue.ScheduledQueue
import io.thelandscape.krawler.http.*
import io.thelandscape.krawler.robots.RoboMinder
import io.thelandscape.krawler.robots.RoboMinderIf
import io.thelandscape.krawler.robots.RobotsConfig
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.consumeEach
import kotlinx.coroutines.channels.produce
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
import java.time.LocalDateTime
import java.util.concurrent.atomic.AtomicInteger
/**
* Class defines the operations and data structures used to perform a web crawl.
*
* @param config: A KrawlConfig object to control the limits and settings of the crawler
* @param krawlHistory: KrawlHistoryIf provider, by default this will be a HSQL backed table
* @param krawlQueues: A KrawlQueueIf provider, by default this will be a HSQL backed queue
* @param robotsConfig: Configuration of the robots.txt management
* @param requestProvider: RequestProviderIf provider, default is Requests class
* @param job: Job context that threads will run in.
*
*/
abstract class Krawler(val config: KrawlConfig = KrawlConfig(),
private var krawlHistory: KrawlHistoryIf? = null,
private var krawlQueues: List<KrawlQueueIf>? = null,
robotsConfig: RobotsConfig? = null,
private val requestProvider: RequestProviderIf = Requests(config),
private val job: Job = Job()) {
private val logger: Logger = LogManager.getLogger()
// Map of start URL -> int id to track branches of a crawl
private val rootPageIds: MutableMap<String, Int> = mutableMapOf()
// Current Max ID
private val maximumUsedId: AtomicInteger = AtomicInteger(0)
init {
if (krawlHistory == null || krawlQueues == null) {
val hsqlConnection = HSQLConnection(config.persistentCrawl, config.crawlDirectory)
if (krawlHistory == null)
krawlHistory = KrawlHistoryHSQLDao(hsqlConnection.hsqlSession)
// This is safe because we don't have any KrawlHistoryIf implementations other than HSQL
val histDao: KrawlHistoryHSQLDao = krawlHistory as KrawlHistoryHSQLDao
if (krawlQueues == null)
// TODO: Dynamic number of queues? Why 10?
krawlQueues = (0 until 10).map {
KrawlQueueHSQLDao("queue$it", hsqlConnection.hsqlSession, histDao)
}
}
job.invokeOnCompletion {
logger.debug("Ending here... (job is no longer active)!!!!")
onCrawlEnd()
}
}
private val scheduledQueue: ScheduledQueue = ScheduledQueue(krawlQueues!!, config, job)
/**
* Handle robots.txt
*/
internal var minder: RoboMinderIf = RoboMinder(config.userAgent, requestProvider, robotsConfig ?: RobotsConfig())
/**
* Override this function to determine if a URL should be visited.
* Visiting a URL will issue an HTTP GET request.
* @param url KrawlUrl: The URL to consider visiting.
*
* @return boolean: true if we should visit, false otherwise
*/
abstract protected fun shouldVisit(url: KrawlUrl): Boolean
/**
* Override this function to determine if a URL should be checked.
* Checking a URL will issue an HTTP HEAD request, and return only a status code.
* Note: This will not GET the content of a page, and as a result will not follow any links on the checked page.
* As such checking a page should be reserved for content that does not contain hyperlinks.
* @param url KrawlUrl: The URL to consider visiting.
*
* @return boolean: true if we should check, false otherwise
*/
open protected fun shouldCheck(url: KrawlUrl): Boolean = false
/**
* Visit a URL by issuing an HTTP GET request
* @param url KrawlURL: The requested URL
* @param doc KrawlDocument: The resulting document from visting the URL
*/
abstract protected fun visit(url: KrawlUrl, doc: KrawlDocument)
/**
* Check a URL by issuing an HTTP HEAD request
* Note: This will not GET the content of a page, and as a result will not follow any links on the checked page.
* As such checking a page should be reserved for content that does not contain hyperlinks.
* @param url KrawlURL: The requested URL
* @param statusCode Int: The resulting status code from checking the URL
*/
open protected fun check(url: KrawlUrl, statusCode: Int) {
return
}
/**
* Function is called before creating a KrawlQueueEntry and is used to determine the entry's priority.
*
* @param url KrawlUrl: The url to be prioritized
* @param depth Int: The depth of the node that url points to
* @param parent KrawlHistoryEntry: The parent page that this link was harvested from
*
* @return a byte value between 0 - 255, where 0 is the highest priority and 255 is the lowest
*/
open protected fun assignQueuePriority(url: KrawlUrl, depth: Int, parent: KrawlHistoryEntry): Byte {
return 1
}
/**
* Function is called on unexpected status code (non 200).
* This can be overridden to take action on other status codes (500, 404, etc)
*
* @param url KrawlUrl: The URL that failed
* @param statusCode Int: The status code
*/
open protected fun onUnexpectedStatusCode(url: KrawlUrl, statusCode: Int) {
return
}
/**
* Function is called on content fetch error.
* This can be overridden to take action on content fetch errors.
*
* @param url KrawlUrl: The URL that failed
* @param reason String: An error message or reason for the error.
*/
open protected fun onContentFetchError(url: KrawlUrl, reason: String) {
return
}
/**
* Function is called if a link to a previously visited page is scheduled to be crawled.
* This can be overridden to take action when a URL has been seen multiple times.
*
* @param url KrawlUrl: URL of the page to visit
* @param parent KrawlUrl: The URL of the parent page
*/
open protected fun onRepeatVisit(url: KrawlUrl, parent: KrawlUrl) {
return
}
/**
* Function is called at the start of a crawl, prior to any worker threads taking any action.
* This should be overridden to take an action prior to any worker threads running.
*/
open protected fun onCrawlStart() {
return
}
/**
* Function is called at the end of a crawl, after all worker threads have exit.
* This should be overridden to take an action after all worker threads have exit.
*/
open protected fun onCrawlEnd() {
return
}
/**
* Submits urls for crawling. This method can be called during an active crawl to add additional
* URLs to the queue.
*
* @param urls List<String>: A list of URLs to add to the queue
*/
fun submitUrls(urls: List<String>, priority: Byte = 0) {
// Convert all URLs to KrawlUrls
val krawlUrls: List<KrawlUrl> = urls.map { KrawlUrl.new(it) }
krawlUrls.forEach {
val rootPageId: Int = maximumUsedId.getAndIncrement()
rootPageIds[it.rawUrl] = rootPageId
scheduledQueue.push(it.domain, listOf(KrawlQueueEntry(it.canonicalForm, rootPageId, priority = priority)))
}
}
/**
* Removes all queue entries that stemmed from rootUrl.
*
* @param rootUrl String: The origin URL of a crawl
* @return the number of entries removed from the queue
*/
fun removeUrlsByRootPage(rootUrl: String): Int {
val id: Int = rootPageIds[rootUrl] ?: return 0
return scheduledQueue.deleteByRootPageId(id)
}
/**
* Remove all queue entries that were inserted before beforeTime.
*
* @param beforeTime LocalDateTime: Time before which all entries are removed
* @return the number of entries removed from the queue
*/
fun removeUrlsByAge(beforeTime: LocalDateTime): Int = scheduledQueue.deleteByAge(beforeTime)
/**
* Starts the Krawler with the URLs provided. This method will call `onCrawlStart()`
* perform the crawl and then call `onCrawlEnd()`. This method will block for the duration
* of the crawl.
*
* @param: seedUrl List<String>: A list of seed URLs
* @param: blocking [Boolean]: (default true) whether to block until completion or immediately return
*
*/
fun start(seedUrl: List<String>, blocking: Boolean = true) = runBlocking {
// Convert all URLs to KrawlUrls
val krawlUrls: List<KrawlUrl> = seedUrl.map { KrawlUrl.new(it) }
krawlUrls.forEach {
val rootPageId: Int = maximumUsedId.getAndIncrement()
rootPageIds[it.rawUrl] = rootPageId
scheduledQueue.push(it.domain, listOf(KrawlQueueEntry(it.canonicalForm, rootPageId)))
}
onCrawlStart()
val urls: Channel<KrawlQueueEntry> = scheduledQueue.krawlQueueEntryChannel
repeat(krawlQueues!!.size) {
GlobalScope.launch(Dispatchers.Default) {
val actions: ReceiveChannel<KrawlAction> = produceKrawlActions(urls)
doCrawl(actions)
}
}
if (blocking)
job.join()
}
/**
* Starts the Krawler with the URL provided. This method will call `onCrawlStart()`
* perform the crawl and then call `onCrawlEnd()`. This method will block for the duration
* of the crawl.
*
* @param: seedUrl String: A single seed URL
*/
fun start(seedUrl: String) = start(listOf(seedUrl))
/**
* Starts the Krawler with the URL provided. This method will call `onCrawlStart()`
* start the crawl and then return. This method will -NOT- block during the crawl.
* Note that because this method does not block, it will also not call `onCrawlEnd()`.
*
* @param: seedUrl String: A single seed URL
*/
fun startNonblocking(seedUrl: String) = startNonblocking(listOf(seedUrl))
/**
* Starts the Krawler with the URLs provided. This method will call `onCrawlStart()`
* start the crawl and then return. This method will -NOT- block during the crawl.
* Note that because this method does not block, it will also not call `onCrawlEnd()`.
*
* @param: seedUrl List<String>: A list of seed URLs
*/
fun startNonblocking(seedUrl: List<String>) {
start(seedUrl, false)
}
/**
* Returns true if the threadpool is still actively running tasks, false otherwise
*
* @return: true if threadpool is active, false otherwise
*/
fun isActive(): Boolean {
return job.isActive
}
/**
* Attempts to stop Krawler by gracefully shutting down. All current threads will finish
* executing.
*/
fun stop() = job.cancel()
/**
* Private members
*/
internal sealed class KrawlAction {
data class Visit(val krawlUrl: KrawlUrl, val doc: KrawlDocument): KrawlAction()
data class Check(val krawlUrl: KrawlUrl, val statusCode: Int): KrawlAction()
object Noop : KrawlAction()
}
internal val visitCount: AtomicInteger = AtomicInteger(0)
internal suspend fun produceKrawlActions(entries: ReceiveChannel<KrawlQueueEntry>): ReceiveChannel<KrawlAction>
= GlobalScope.produce(Dispatchers.Default) {
while(true) {
// This is where we'll die bomb out if we don't receive an entry after some time
var timeoutCounter: Long = 0
while(entries.isEmpty) {
if (config.shutdownOnEmptyQueue && timeoutCounter++ == config.emptyQueueWaitTime) {
logger.debug("Closing channel after timeout reached")
channel.close()
job.cancel()
return@produce
}
delay(1000)
}
val (url, root, parent, depth) = entries.receive()
val krawlUrl: KrawlUrl = KrawlUrl.new(url)
val parentKrawlUrl: KrawlUrl = KrawlUrl.new(parent.url)
val action: KrawlAction = fetch(krawlUrl, depth, parentKrawlUrl, root).await()
if (action !is KrawlAction.Noop) {
if (visitCount.getAndIncrement() >= config.totalPages && config.totalPages > 0) {
logger.debug("Closing produceKrawlActions")
job.cancel()
return@produce
}
}
send(action)
}
}
internal fun fetch(krawlUrl: KrawlUrl, depth: Int, parent: KrawlUrl, rootPageId: Int): Deferred<KrawlAction>
= GlobalScope.async(Dispatchers.Default) {
// Make sure we're within depth limit
if (depth >= config.maxDepth && config.maxDepth != -1) {
logger.debug("Max depth!")
return@async KrawlAction.Noop
}
// Do a history check
val history: KrawlHistoryEntry =
if (krawlHistory!!.hasBeenSeen(krawlUrl)) { // If it has been seen
onRepeatVisit(krawlUrl, parent)
logger.debug("History says no")
return@async KrawlAction.Noop
} else {
krawlHistory!!.insert(krawlUrl)
}
val visit = shouldVisit(krawlUrl)
val check = shouldCheck(krawlUrl)
if (visit || check) {
// If we're respecting robots.txt check if it's ok to visit this page
if (config.respectRobotsTxt && !minder.isSafeToVisit(krawlUrl)) {
logger.debug("Robots says no")
return@async KrawlAction.Noop
}
val doc: RequestResponse = if (visit) {
requestProvider.getUrl(krawlUrl)
} else {
requestProvider.checkUrl(krawlUrl)
}
// If there was an error on trying to get the doc, call content fetch error
if (doc is ErrorResponse) {
onContentFetchError(krawlUrl, doc.reason)
logger.debug("Content fetch error!")
return@async KrawlAction.Noop
}
// If there was an error parsing the response, still a content fetch error
if (doc !is KrawlDocument) {
onContentFetchError(krawlUrl, "Krawler was unable to parse the response from the server.")
logger.debug("Content fetch error!")
return@async KrawlAction.Noop
}
val links = harvestLinks(doc, krawlUrl, history, depth, rootPageId)
scheduledQueue.push(krawlUrl.domain, links)
if (visit)
return@async KrawlAction.Visit(krawlUrl, doc)
else
return@async KrawlAction.Check(krawlUrl, doc.statusCode)
}
return@async KrawlAction.Noop
}
// Set of redirect codes
private val redirectCodes: Set<Int> = setOf(300, 301, 302, 303, 307, 308)
internal suspend fun doCrawl(channel: ReceiveChannel<KrawlAction>) {
channel.consumeEach { action ->
when(action) {
is KrawlAction.Visit ->
withContext(Dispatchers.Default) { visit(action.krawlUrl, action.doc) }
is KrawlAction.Check ->
withContext(Dispatchers.Default) { check(action.krawlUrl, action.statusCode) }
}
}
}
/**
* Harvests all of the links from a KrawlQueueDocument and creates KrawlQueueEntries from them.
* @param doc [KrawlDocument]: the document to harvest the anchor tags and other links from
* @param url [KrawlUrl]: url that links are being harvested from
* @param history [KrawlHistoryEntry]: the history entry generated for this URL
* @param depth [Int]: The current crawl depth
*
* @return a list of [KrawlQueueEntry] containing the URLs to crawl
*/
internal suspend fun harvestLinks(doc: KrawlDocument, url: KrawlUrl,
history: KrawlHistoryEntry, depth: Int, rootPageId: Int): List<KrawlQueueEntry> {
// Handle redirects by getting the location tag of the header and pushing that into the queue
if (!config.useFastRedirectStrategy && doc.statusCode in redirectCodes && config.followRedirects) {
// Queue the redirected URL
val locStr: String = doc.headers["location"] ?: return listOf()
val location: KrawlUrl = KrawlUrl.new(locStr, url)
// We won't count it as a visit since we didn't get any content
visitCount.decrementAndGet()
return listOf(KrawlQueueEntry(location.canonicalForm, rootPageId, history, depth))
}
// If it wasn't a redirect parse out the URLs from anchor tags and construct queue entries from them
return listOf(
// Anchor tags
doc.anchorTags
.asSequence()
.filterNot { it.attr("href").startsWith("#") }
.filter { it.attr("href").length <= 2048 }
.map { KrawlUrl.new(it.attr("href"), url) }
.filter { it != InvalidKrawlUrl && it.canonicalForm.isNotBlank() }
// TODO: Add in priority call?
.map { KrawlQueueEntry(it.canonicalForm, rootPageId, history, depth + 1,
assignQueuePriority(it, depth, history)) }
.toList(),
// Everything else (img tags, scripts, etc)
doc.otherOutgoingLinks
.asSequence()
.filterNot { it.startsWith("#")}
.filter { it.length <= 2048 }
.map { KrawlUrl.new(it, url) }
.map { KrawlQueueEntry(it.canonicalForm, rootPageId, history, depth + 1,
assignQueuePriority(it, depth, history))}
.toList()
).flatten()
}
}
| mit | f7c74ff52cfd6a408ef729f9cef9d625 | 39.627329 | 120 | 0.650206 | 4.409663 | false | true | false | false |
Lumeer/engine | lumeer-core/src/main/kotlin/io/lumeer/core/adapter/FileAttachmentAdapter.kt | 2 | 4649 | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* 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 io.lumeer.core.adapter
import io.lumeer.api.model.FileAttachment
import io.lumeer.api.model.FileAttachment.AttachmentType
import io.lumeer.api.model.Organization
import io.lumeer.api.model.Project
import io.lumeer.core.util.LumeerS3Client
import io.lumeer.storage.api.dao.FileAttachmentDao
import java.util.function.Consumer
private const val MAX_IDS_QUERY = 500
class FileAttachmentAdapter(val lumeerS3Client: LumeerS3Client, val fileAttachmentDao: FileAttachmentDao, val environment: String) {
fun createFileAttachment(fileAttachment: FileAttachment, data: ByteArray): FileAttachment {
val storedAttachment = fileAttachmentDao.createFileAttachment(fileAttachment)
lumeerS3Client.putObject(getFileAttachmentKey(fileAttachment), data)
return storedAttachment
}
fun getAllFileAttachments(organization: Organization, project: Project, collectionId: String, documentId: String, attributeId: String, type: AttachmentType): List<FileAttachment> =
fileAttachmentDao.findAllFileAttachments(
organization,
project,
collectionId, documentId, attributeId, type
)
fun getAllFileAttachments(organization: Organization, project: Project, resourceIds: Set<String>, type: AttachmentType): List<FileAttachment> =
fileAttachmentDao.findAllFileAttachments(organization, project, resourceIds, type)
fun getFileAttachmentNames(organization: Organization, project: Project, collectionId: String, documentId: String, attributeId: String, type: AttachmentType): String =
fileAttachmentDao.findAllFileAttachments(
organization,
project,
collectionId, documentId, attributeId, type
).joinToString(",", "[", "]") { "'" + "${it.id}:${it.fileName}".replace("([\\'\\\\])".toRegex(), "\\\\$1") + "'" }
fun removeFileAttachments(attachmentLocation: String) {
if (lumeerS3Client.isInitialized) {
lumeerS3Client.deleteObjects(lumeerS3Client.listObjects(attachmentLocation))
}
}
fun removeFileAttachment(fileAttachment: FileAttachment) {
if (lumeerS3Client.isInitialized) {
lumeerS3Client.deleteObject(getFileAttachmentKey(fileAttachment))
}
fileAttachmentDao.removeFileAttachment(fileAttachment)
}
fun removeFileAttachments(fileAttachments: Collection<FileAttachment>) {
if (lumeerS3Client.isInitialized) {
fileAttachments.forEach(Consumer { fileAttachment -> lumeerS3Client.deleteObject(getFileAttachmentKey(fileAttachment)) })
}
// large queries throw error in mongoDB
fileAttachments.map { it.id }.chunked(MAX_IDS_QUERY).forEach { ids ->
fileAttachmentDao.removeFileAttachments(ids)
}
}
fun readFileAttachment(fileAttachment: FileAttachment): ByteArray {
if (lumeerS3Client.isInitialized) {
return lumeerS3Client.readObject(getFileAttachmentKey(fileAttachment))
}
return ByteArray(0)
}
fun getFileAttachmentLocation(organizationId: String, projectId: String, collectionId: String?, documentId: String?, attributeId: String?, type: AttachmentType): String {
val sb = StringBuilder(environment + "/" + organizationId + "/" + projectId + "/" + type.name)
if (collectionId != null) {
sb.append("/").append(collectionId)
if (attributeId != null) {
sb.append("/").append(attributeId)
if (documentId != null) {
sb.append("/").append(documentId)
}
}
}
return sb.toString()
}
fun getFileAttachmentKey(fileAttachment: FileAttachment): String {
return (getFileAttachmentLocation(fileAttachment.organizationId, fileAttachment.projectId, fileAttachment.collectionId, fileAttachment.documentId, fileAttachment.attributeId, fileAttachment.attachmentType) + "/"
+ fileAttachment.id)
}
}
| gpl-3.0 | 98b7ccbeda88d49d5028586557535de7 | 41.651376 | 217 | 0.724887 | 4.461612 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/test/kotlin/org/wfanet/measurement/duchy/service/internal/computationcontrol/AsyncComputationControlServiceTest.kt | 1 | 18098 | // Copyright 2020 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.duchy.service.internal.computationcontrol
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.extensions.proto.ProtoTruth.assertThat
import io.grpc.Status
import io.grpc.StatusRuntimeException
import kotlin.test.assertFailsWith
import kotlinx.coroutines.runBlocking
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.kotlin.any
import org.mockito.kotlin.stub
import org.mockito.kotlin.whenever
import org.wfanet.measurement.common.grpc.testing.GrpcTestServerRule
import org.wfanet.measurement.common.grpc.testing.mockService
import org.wfanet.measurement.duchy.service.internal.computations.newEmptyOutputBlobMetadata
import org.wfanet.measurement.duchy.service.internal.computations.newInputBlobMetadata
import org.wfanet.measurement.duchy.service.internal.computations.newOutputBlobMetadata
import org.wfanet.measurement.duchy.service.internal.computations.newPassThroughBlobMetadata
import org.wfanet.measurement.duchy.service.internal.computations.toAdvanceComputationStageResponse
import org.wfanet.measurement.duchy.service.internal.computations.toGetComputationTokenResponse
import org.wfanet.measurement.duchy.service.internal.computations.toRecordOutputBlobPathResponse
import org.wfanet.measurement.duchy.toProtocolStage
import org.wfanet.measurement.internal.duchy.AdvanceComputationRequest
import org.wfanet.measurement.internal.duchy.AdvanceComputationStageRequest
import org.wfanet.measurement.internal.duchy.ComputationBlobDependency
import org.wfanet.measurement.internal.duchy.ComputationDetails
import org.wfanet.measurement.internal.duchy.ComputationStageDetails
import org.wfanet.measurement.internal.duchy.ComputationToken
import org.wfanet.measurement.internal.duchy.ComputationsGrpcKt.ComputationsCoroutineImplBase
import org.wfanet.measurement.internal.duchy.ComputationsGrpcKt.ComputationsCoroutineStub
import org.wfanet.measurement.internal.duchy.RecordOutputBlobPathRequest
import org.wfanet.measurement.internal.duchy.computationStageBlobMetadata
import org.wfanet.measurement.internal.duchy.computationStageDetails
import org.wfanet.measurement.internal.duchy.computationToken
import org.wfanet.measurement.internal.duchy.config.LiquidLegionsV2SetupConfig.RoleInComputation
import org.wfanet.measurement.internal.duchy.getOutputBlobMetadataRequest
import org.wfanet.measurement.internal.duchy.protocol.LiquidLegionsSketchAggregationV2.Stage
import org.wfanet.measurement.internal.duchy.protocol.LiquidLegionsSketchAggregationV2Kt
@RunWith(JUnit4::class)
class AsyncComputationControlServiceTest {
private val mockComputationsService: ComputationsCoroutineImplBase = mockService()
@get:Rule val grpcTestServerRule = GrpcTestServerRule { addService(mockComputationsService) }
private val service: AsyncComputationControlService by lazy {
AsyncComputationControlService(ComputationsCoroutineStub(grpcTestServerRule.channel))
}
private fun mockComputationsServiceCalls(
tokenBeforeRecord: ComputationToken,
tokenAfterRecord: ComputationToken
) = runBlocking {
whenever(mockComputationsService.getComputationToken(any())).thenAnswer {
tokenBeforeRecord.toGetComputationTokenResponse()
}
val recordBlobRequests = mutableListOf<RecordOutputBlobPathRequest>()
whenever(mockComputationsService.recordOutputBlobPath(any())).thenAnswer {
val req: RecordOutputBlobPathRequest = it.getArgument(0)
recordBlobRequests.add(req)
tokenAfterRecord.toRecordOutputBlobPathResponse()
}
val advanceComputationRequests = mutableListOf<AdvanceComputationStageRequest>()
whenever(mockComputationsService.advanceComputationStage(any())).thenAnswer {
val req: AdvanceComputationStageRequest = it.getArgument(0)
advanceComputationRequests.add(req)
req.token.toAdvanceComputationStageResponse()
}
return@runBlocking recordBlobRequests to advanceComputationRequests
}
@Test
fun `record only output and advance`() =
runBlocking<Unit> {
val tokenToWrite =
ComputationToken.newBuilder()
.apply {
computationStage = Stage.WAIT_EXECUTION_PHASE_ONE_INPUTS.toProtocolStage()
addBlobs(newInputBlobMetadata(0L, "input-to-the-stage"))
addBlobs(newEmptyOutputBlobMetadata(1L))
computationDetails = detailsFor(RoleInComputation.AGGREGATOR)
}
.build()
val tokenToAdvance =
tokenToWrite
.toBuilder()
.apply {
clearBlobs()
addBlobs(newOutputBlobMetadata(1L, BLOB_KEY))
}
.build()
val (recordBlobRequests, advanceComputationRequests) =
mockComputationsServiceCalls(tokenToWrite, tokenToAdvance)
service.advanceComputation(
AdvanceComputationRequest.newBuilder()
.apply {
globalComputationId = COMPUTATION_ID
computationStage = Stage.WAIT_EXECUTION_PHASE_ONE_INPUTS.toProtocolStage()
blobId = 1L
blobPath = BLOB_KEY
}
.build()
)
assertThat(recordBlobRequests)
.containsExactly(
RecordOutputBlobPathRequest.newBuilder()
.apply {
token = tokenToWrite
outputBlobId = 1
blobPath = BLOB_KEY
}
.build()
)
assertThat(advanceComputationRequests)
.containsExactly(
AdvanceComputationStageRequest.newBuilder()
.apply {
token = tokenToAdvance
nextComputationStage = Stage.EXECUTION_PHASE_ONE.toProtocolStage()
addInputBlobs(BLOB_KEY)
outputBlobs = 1
stageDetails = ComputationStageDetails.getDefaultInstance()
afterTransition =
AdvanceComputationStageRequest.AfterTransition.ADD_UNCLAIMED_TO_QUEUE
}
.build()
)
}
@Test
fun `record but more blobs to write so do not advance`() = runBlocking {
val tokenBeforeRecord =
ComputationToken.newBuilder()
.apply {
computationStage = Stage.WAIT_SETUP_PHASE_INPUTS.toProtocolStage()
addBlobs(newPassThroughBlobMetadata(0L, "pass-through-blob"))
addBlobs(newEmptyOutputBlobMetadata(1L))
addBlobs(newEmptyOutputBlobMetadata(2L))
computationDetails = detailsFor(RoleInComputation.AGGREGATOR)
stageSpecificDetailsBuilder.apply {
liquidLegionsV2Builder.apply {
waitSetupPhaseInputsDetailsBuilder.putExternalDuchyLocalBlobId("alice", 2L)
waitSetupPhaseInputsDetailsBuilder.putExternalDuchyLocalBlobId("bob", 1L)
}
}
}
.build()
val tokenAfterRecord =
tokenBeforeRecord
.toBuilder()
.apply {
clearBlobs()
addBlobs(newPassThroughBlobMetadata(0L, "pass-through-blob"))
addBlobs(newOutputBlobMetadata(1L, BLOB_KEY))
addBlobs(newEmptyOutputBlobMetadata(2L)) // There is still a blob without a key.
}
.build()
val (recordBlobRequests, advanceComputationRequests) =
mockComputationsServiceCalls(tokenBeforeRecord, tokenAfterRecord)
service.advanceComputation(
AdvanceComputationRequest.newBuilder()
.apply {
globalComputationId = COMPUTATION_ID
computationStage = Stage.WAIT_SETUP_PHASE_INPUTS.toProtocolStage()
blobId = 1L
blobPath = BLOB_KEY
}
.build()
)
assertThat(recordBlobRequests)
.containsExactly(
RecordOutputBlobPathRequest.newBuilder()
.apply {
token = tokenBeforeRecord
outputBlobId = 1
blobPath = BLOB_KEY
}
.build()
)
// Waiting on more outputs for the stage. Computation stage is not advanced.
assertThat(advanceComputationRequests).isEmpty()
}
@Test
fun `record last output blob`() =
runBlocking<Unit> {
val tokenBeforeRecord =
ComputationToken.newBuilder()
.apply {
computationStage = Stage.WAIT_SETUP_PHASE_INPUTS.toProtocolStage()
addBlobs(newPassThroughBlobMetadata(0L, "pass-through-blob"))
addBlobs(newEmptyOutputBlobMetadata(1L))
addBlobs(newOutputBlobMetadata(2L, "written-output"))
computationDetails = detailsFor(RoleInComputation.AGGREGATOR)
stageSpecificDetailsBuilder.apply {
liquidLegionsV2Builder.apply {
waitSetupPhaseInputsDetailsBuilder.putExternalDuchyLocalBlobId("alice", 2L)
waitSetupPhaseInputsDetailsBuilder.putExternalDuchyLocalBlobId("bob", 1L)
}
}
}
.build()
val tokenAfterRecord =
tokenBeforeRecord
.toBuilder()
.apply {
clearBlobs()
addBlobs(newPassThroughBlobMetadata(0L, "pass-through"))
addBlobs(newOutputBlobMetadata(1L, BLOB_KEY))
addBlobs(newOutputBlobMetadata(2L, "previously-written-output"))
}
.build()
val (recordBlobRequests, advanceComputationRequests) =
mockComputationsServiceCalls(tokenBeforeRecord, tokenAfterRecord)
service.advanceComputation(
AdvanceComputationRequest.newBuilder()
.apply {
globalComputationId = COMPUTATION_ID
computationStage = Stage.WAIT_SETUP_PHASE_INPUTS.toProtocolStage()
blobId = 1L
blobPath = BLOB_KEY
}
.build()
)
assertThat(recordBlobRequests)
.containsExactly(
RecordOutputBlobPathRequest.newBuilder()
.apply {
token = tokenBeforeRecord
outputBlobId = 1
blobPath = BLOB_KEY
}
.build()
)
assertThat(advanceComputationRequests)
.containsExactly(
AdvanceComputationStageRequest.newBuilder()
.apply {
token = tokenAfterRecord
nextComputationStage = Stage.SETUP_PHASE.toProtocolStage()
addInputBlobs("pass-through")
addInputBlobs(BLOB_KEY)
addInputBlobs("previously-written-output")
outputBlobs = 1
stageDetails = ComputationStageDetails.getDefaultInstance()
afterTransition =
AdvanceComputationStageRequest.AfterTransition.ADD_UNCLAIMED_TO_QUEUE
}
.build()
)
}
@Test
fun `advance when blob already written`() =
runBlocking<Unit> {
val tokenOfAlreadyRecordedOutput =
ComputationToken.newBuilder()
.apply {
computationStage = Stage.WAIT_EXECUTION_PHASE_ONE_INPUTS.toProtocolStage()
addBlobs(newOutputBlobMetadata(1L, BLOB_KEY))
computationDetails = detailsFor(RoleInComputation.NON_AGGREGATOR)
}
.build()
val (recordBlobRequests, advanceComputationRequests) =
mockComputationsServiceCalls(tokenOfAlreadyRecordedOutput, tokenOfAlreadyRecordedOutput)
service.advanceComputation(
AdvanceComputationRequest.newBuilder()
.apply {
globalComputationId = COMPUTATION_ID
computationStage = Stage.WAIT_EXECUTION_PHASE_ONE_INPUTS.toProtocolStage()
blobId = 1L
blobPath = BLOB_KEY
}
.build()
)
// The key of the output blob was already recorded.
assertThat(recordBlobRequests).isEmpty()
assertThat(advanceComputationRequests)
.containsExactly(
AdvanceComputationStageRequest.newBuilder()
.apply {
token = tokenOfAlreadyRecordedOutput
nextComputationStage = Stage.EXECUTION_PHASE_ONE.toProtocolStage()
addInputBlobs(BLOB_KEY)
outputBlobs = 1
stageDetails = ComputationStageDetails.getDefaultInstance()
afterTransition =
AdvanceComputationStageRequest.AfterTransition.ADD_UNCLAIMED_TO_QUEUE
}
.build()
)
}
@Test
fun `advance when stage already advanced is a noop`() = runBlocking {
val tokenOfAlreadyRecordedOutput =
ComputationToken.newBuilder()
.apply {
computationStage = Stage.EXECUTION_PHASE_ONE.toProtocolStage()
addBlobs(newOutputBlobMetadata(1L, BLOB_KEY))
computationDetails = detailsFor(RoleInComputation.NON_AGGREGATOR)
}
.build()
val (recordBlobRequests, advanceComputationRequests) =
mockComputationsServiceCalls(tokenOfAlreadyRecordedOutput, tokenOfAlreadyRecordedOutput)
service.advanceComputation(
AdvanceComputationRequest.newBuilder()
.apply {
globalComputationId = COMPUTATION_ID
computationStage = Stage.WAIT_EXECUTION_PHASE_ONE_INPUTS.toProtocolStage()
blobPath = BLOB_KEY
}
.build()
)
assertThat(recordBlobRequests).isEmpty()
assertThat(advanceComputationRequests).isEmpty()
}
@Test
fun `advance stage doesn't match throws exception`() = runBlocking {
val actualStage = Stage.EXECUTION_PHASE_ONE.toProtocolStage()
val oldToken = ComputationToken.newBuilder().setComputationStage(actualStage).build()
val (recordBlobRequests, advanceComputationRequests) =
mockComputationsServiceCalls(oldToken, oldToken)
assertFailsWith<StatusRuntimeException>(
message = "INVALID_ARGUMENT: Actual stage from computation ($actualStage) did not match"
) {
service.advanceComputation(
AdvanceComputationRequest.newBuilder()
.apply {
globalComputationId = COMPUTATION_ID
computationStage = Stage.EXECUTION_PHASE_ONE.toProtocolStage()
}
.build()
)
}
assertThat(recordBlobRequests).isEmpty()
assertThat(advanceComputationRequests).isEmpty()
}
@Test
fun `getBlobOutputMetadata returns by origin Duchy in LLv2 WAIT_SETUP_PHASE_INPUTS`() {
val token = computationToken {
computationStage = Stage.WAIT_SETUP_PHASE_INPUTS.toProtocolStage()
blobs += newPassThroughBlobMetadata(0L, "pass-through-blob")
blobs += newEmptyOutputBlobMetadata(1L)
blobs += newEmptyOutputBlobMetadata(2L)
stageSpecificDetails = computationStageDetails {
liquidLegionsV2 =
LiquidLegionsSketchAggregationV2Kt.stageDetails {
waitSetupPhaseInputsDetails =
LiquidLegionsSketchAggregationV2Kt.waitSetupPhaseInputsDetails {
externalDuchyLocalBlobId["Buck"] = 1L
externalDuchyLocalBlobId["Rippon"] = 2L
}
}
}
}
mockComputationsService.stub {
onBlocking { getComputationToken(any()) }.thenReturn(token.toGetComputationTokenResponse())
}
val blobMetadata = runBlocking {
service.getOutputBlobMetadata(
getOutputBlobMetadataRequest {
globalComputationId = COMPUTATION_ID
dataOrigin = "Buck"
}
)
}
assertThat(blobMetadata)
.isEqualTo(
computationStageBlobMetadata {
dependencyType = ComputationBlobDependency.OUTPUT
blobId = 1L
}
)
}
@Test
fun `getBlobOutputMetadata returns single output blob in LLv2 WAIT_EXECUTION_PHASE_INPUTS`() {
val token = computationToken {
computationStage = Stage.WAIT_EXECUTION_PHASE_ONE_INPUTS.toProtocolStage()
blobs += newInputBlobMetadata(0L, "input-blob")
blobs += newEmptyOutputBlobMetadata(1L)
stageSpecificDetails = computationStageDetails {
liquidLegionsV2 = LiquidLegionsSketchAggregationV2Kt.stageDetails {}
}
}
mockComputationsService.stub {
onBlocking { getComputationToken(any()) }.thenReturn(token.toGetComputationTokenResponse())
}
val blobMetadata = runBlocking {
service.getOutputBlobMetadata(
getOutputBlobMetadataRequest {
globalComputationId = COMPUTATION_ID
dataOrigin = "Buck"
}
)
}
assertThat(blobMetadata)
.isEqualTo(
computationStageBlobMetadata {
dependencyType = ComputationBlobDependency.OUTPUT
blobId = 1L
}
)
}
@Test
fun `getBlobOutputMetadata throws FAILED_PRECONDITION in unexpected LLv2 stage`() {
val token = computationToken { computationStage = Stage.EXECUTION_PHASE_ONE.toProtocolStage() }
mockComputationsService.stub {
onBlocking { getComputationToken(any()) }.thenReturn(token.toGetComputationTokenResponse())
}
val exception = runBlocking {
assertFailsWith<StatusRuntimeException> {
service.getOutputBlobMetadata(
getOutputBlobMetadataRequest {
globalComputationId = COMPUTATION_ID
dataOrigin = "Buck"
}
)
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.FAILED_PRECONDITION)
assertThat(exception).hasMessageThat().contains(Stage.EXECUTION_PHASE_ONE.name)
}
companion object {
private const val BLOB_KEY = "the-data-was-written-here"
private const val COMPUTATION_ID = "1234"
private fun detailsFor(r: RoleInComputation): ComputationDetails =
ComputationDetails.newBuilder().apply { liquidLegionsV2Builder.apply { role = r } }.build()
}
}
| apache-2.0 | 5e072f80590f8873af1b79bf937334d4 | 37.262156 | 99 | 0.692231 | 4.858523 | false | false | false | false |
SimonVT/cathode | trakt-api/src/main/java/net/simonvt/cathode/api/entity/Ids.kt | 1 | 828 | /*
* Copyright (C) 2014 Simon Vig Therkildsen
*
* 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.simonvt.cathode.api.entity
data class Ids(
val trakt: Long? = null,
val slug: String? = null,
val tvdb: Long? = null,
val imdb: String? = null,
val tmdb: Int? = null,
val tvrage: Long? = null
)
| apache-2.0 | b5632d6fe8e35311c4b3668ab0567b46 | 30.846154 | 75 | 0.71256 | 3.763636 | false | false | false | false |
SimonVT/cathode | trakt-api/src/main/java/net/simonvt/cathode/api/entity/ListItem.kt | 1 | 951 | /*
* Copyright (C) 2015 Simon Vig Therkildsen
*
* 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.simonvt.cathode.api.entity
import net.simonvt.cathode.api.enumeration.ItemType
data class ListItem(
val rank: Int,
val id: Long,
val listed_at: IsoTime,
val type: ItemType,
val movie: Movie? = null,
val show: Show? = null,
val season: Season? = null,
val episode: Episode? = null,
val person: Person? = null
)
| apache-2.0 | d3100e0ec82ee770c55de11b44ed31a1 | 29.677419 | 75 | 0.722397 | 3.804 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/completion/handlers/LatexNoMathInsertHandler.kt | 1 | 6375 | package nl.hannahsten.texifyidea.completion.handlers
import com.intellij.codeInsight.completion.InsertHandler
import com.intellij.codeInsight.completion.InsertionContext
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.template.Template
import com.intellij.codeInsight.template.TemplateEditingListener
import com.intellij.codeInsight.template.TemplateManager
import com.intellij.codeInsight.template.impl.TemplateImpl
import com.intellij.codeInsight.template.impl.TemplateState
import com.intellij.codeInsight.template.impl.TextExpression
import nl.hannahsten.texifyidea.lang.Environment
import nl.hannahsten.texifyidea.lang.commands.Argument
import nl.hannahsten.texifyidea.lang.commands.LatexCommand
import nl.hannahsten.texifyidea.lang.commands.LatexGenericRegularCommand
import nl.hannahsten.texifyidea.lang.commands.RequiredArgument
import nl.hannahsten.texifyidea.util.*
import nl.hannahsten.texifyidea.util.files.definitionsAndRedefinitionsInFileSet
import nl.hannahsten.texifyidea.util.magic.TypographyMagic
/**
* @author Hannah Schellekens, Sten Wessel
*/
class LatexNoMathInsertHandler(val arguments: List<Argument>? = null) : InsertHandler<LookupElement> {
override fun handleInsert(context: InsertionContext, item: LookupElement) {
removeWhiteSpaces(context)
val command = item.`object` as LatexCommand
when (command.command) {
LatexGenericRegularCommand.BEGIN.command -> {
insertBegin(context)
}
in TypographyMagic.pseudoCodeBeginEndOpposites -> {
insertPseudocodeEnd(command.command, context)
}
else -> {
LatexCommandArgumentInsertHandler(arguments).handleInsert(context, item)
}
}
RightInsertHandler().handleInsert(context, item)
LatexCommandPackageIncludeHandler().handleInsert(context, item)
}
private fun insertPseudocodeEnd(name: String, context: InsertionContext) {
val numberRequiredArguments = LatexCommand.lookup(name)
?.firstOrNull()?.arguments
?.count { it is RequiredArgument } ?: 0
val templateText = List(numberRequiredArguments) {
"{\$__Variable${it}\$}"
}.joinToString("") + "\n\$END\$\n\\${TypographyMagic.pseudoCodeBeginEndOpposites[name]}"
val parameterTemplate = object : TemplateImpl("", templateText, "") {
override fun isToReformat(): Boolean = false
}
repeat(numberRequiredArguments) { parameterTemplate.addVariable(TextExpression(""), true) }
TemplateManager.getInstance(context.project)
.startTemplate(context.editor, parameterTemplate)
}
/**
* Inserts a live template to make the end command match the begin command.
*/
private fun insertBegin(context: InsertionContext) {
val templateText = "{\$__Variable0\$}\$END\$\n\\end{\$__Variable0\$}"
val template = object : TemplateImpl("", templateText, "") {
override fun isToReformat(): Boolean = true
}
template.addVariable(TextExpression(""), true)
TemplateManager.getInstance(context.project)
.startTemplate(context.editor, template, EnvironmentInsertImports(context))
}
/**
* Insert a live template for the required arguments. When there are no required
* arguments, move to the content of the environment.
*/
private fun insertRequiredArguments(environment: Environment?, context: InsertionContext) {
val numberRequiredArguments = environment?.arguments
?.count { it is RequiredArgument } ?: 0
val templateText = List(numberRequiredArguments) { "{\$__Variable${it}\$}" }.joinToString("") + "\n\$END\$"
val parameterTemplate = object : TemplateImpl("", templateText, "") {
override fun isToReformat(): Boolean = true
}
repeat(numberRequiredArguments) { parameterTemplate.addVariable(TextExpression(""), true) }
TemplateManager.getInstance(context.project)
.startTemplate(context.editor, parameterTemplate)
}
/**
* Remove whitespaces and everything after that that was inserted by the lookup text.
*/
private fun removeWhiteSpaces(context: InsertionContext) {
val editor = context.editor
val document = editor.document
val offset = editor.caretModel.offset
// context.startOffset is the offset of the start of the just inserted text.
val insertedText = document.text.substring(context.startOffset, offset)
val indexFirstSpace = insertedText.indexOfFirst { it == ' ' }
if (indexFirstSpace == -1) return
document.deleteString(context.startOffset + indexFirstSpace, offset)
}
/**
* Makes sure environments get imported if required.
*
* @author Hannah Schellekens
*/
private inner class EnvironmentInsertImports(val context: InsertionContext) : TemplateEditingListener {
override fun beforeTemplateFinished(templateState: TemplateState, template: Template?) {
val envName = templateState.getVariableValue("__Variable0")?.text ?: return
val environment = Environment[envName]
insertRequiredArguments(environment, context)
environment ?: return
val pack = environment.dependency
val file = context.file
val editor = context.editor
val envDefinitions = file.definitionsAndRedefinitionsInFileSet().asSequence()
.filter { it.isEnvironmentDefinition() }
.mapNotNull { it.requiredParameter(0) }
.toSet()
// Include packages.
if (!file.includedPackages().contains(pack) && envName !in envDefinitions) {
file.insertUsepackage(pack)
}
// Add initial contents.
val initial = environment.initialContents
editor.insertAndMove(editor.caretModel.offset, initial)
}
override fun templateFinished(template: Template, b: Boolean) {}
override fun templateCancelled(template: Template?) {}
override fun currentVariableChanged(templateState: TemplateState, template: Template?, i: Int, i1: Int) {}
override fun waitingForInput(template: Template?) {}
}
}
| mit | 0a127cedd6a5e674ffa3fdc0caa1ab83 | 42.664384 | 115 | 0.686431 | 5.071599 | false | false | false | false |
jeffgbutler/mybatis-qbe | src/main/kotlin/org/mybatis/dynamic/sql/util/kotlin/spring/NamedParameterJdbcTemplateExtensions.kt | 1 | 13011 | /*
* Copyright 2016-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("TooManyFunctions")
package org.mybatis.dynamic.sql.util.kotlin.spring
import org.mybatis.dynamic.sql.BasicColumn
import org.mybatis.dynamic.sql.SqlTable
import org.mybatis.dynamic.sql.delete.render.DeleteStatementProvider
import org.mybatis.dynamic.sql.insert.render.BatchInsert
import org.mybatis.dynamic.sql.insert.render.GeneralInsertStatementProvider
import org.mybatis.dynamic.sql.insert.render.InsertSelectStatementProvider
import org.mybatis.dynamic.sql.insert.render.InsertStatementProvider
import org.mybatis.dynamic.sql.insert.render.MultiRowInsertStatementProvider
import org.mybatis.dynamic.sql.select.render.SelectStatementProvider
import org.mybatis.dynamic.sql.update.render.UpdateStatementProvider
import org.mybatis.dynamic.sql.util.kotlin.BatchInsertCompleter
import org.mybatis.dynamic.sql.util.kotlin.CountCompleter
import org.mybatis.dynamic.sql.util.kotlin.DeleteCompleter
import org.mybatis.dynamic.sql.util.kotlin.GeneralInsertCompleter
import org.mybatis.dynamic.sql.util.kotlin.InsertCompleter
import org.mybatis.dynamic.sql.util.kotlin.InsertSelectCompleter
import org.mybatis.dynamic.sql.util.kotlin.MultiRowInsertCompleter
import org.mybatis.dynamic.sql.util.kotlin.MyBatisDslMarker
import org.mybatis.dynamic.sql.util.kotlin.SelectCompleter
import org.mybatis.dynamic.sql.util.kotlin.UpdateCompleter
import org.mybatis.dynamic.sql.util.kotlin.elements.insert
import org.mybatis.dynamic.sql.util.kotlin.elements.insertBatch
import org.mybatis.dynamic.sql.util.kotlin.elements.insertMultiple
import org.springframework.dao.EmptyResultDataAccessException
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils
import org.springframework.jdbc.support.KeyHolder
import java.sql.ResultSet
import kotlin.reflect.KClass
fun NamedParameterJdbcTemplate.count(selectStatement: SelectStatementProvider): Long =
queryForObject(selectStatement.selectStatement, selectStatement.parameters, Long::class.java)!!
fun NamedParameterJdbcTemplate.count(column: BasicColumn, completer: CountCompleter): Long =
count(org.mybatis.dynamic.sql.util.kotlin.spring.count(column, completer))
fun NamedParameterJdbcTemplate.countDistinct(column: BasicColumn, completer: CountCompleter): Long =
count(org.mybatis.dynamic.sql.util.kotlin.spring.countDistinct(column, completer))
fun NamedParameterJdbcTemplate.countFrom(table: SqlTable, completer: CountCompleter): Long =
count(org.mybatis.dynamic.sql.util.kotlin.spring.countFrom(table, completer))
fun NamedParameterJdbcTemplate.delete(deleteStatement: DeleteStatementProvider): Int =
update(deleteStatement.deleteStatement, deleteStatement.parameters)
fun NamedParameterJdbcTemplate.deleteFrom(table: SqlTable, completer: DeleteCompleter): Int =
delete(org.mybatis.dynamic.sql.util.kotlin.spring.deleteFrom(table, completer))
// batch insert
fun <T> NamedParameterJdbcTemplate.insertBatch(insertStatement: BatchInsert<T>): IntArray =
batchUpdate(insertStatement.insertStatementSQL, SqlParameterSourceUtils.createBatch(insertStatement.records))
fun <T : Any> NamedParameterJdbcTemplate.insertBatch(vararg records: T): BatchInsertHelper<T> =
insertBatch(records.asList())
fun <T : Any> NamedParameterJdbcTemplate.insertBatch(records: List<T>): BatchInsertHelper<T> =
BatchInsertHelper(records, this)
// single row insert
fun <T : Any> NamedParameterJdbcTemplate.insert(insertStatement: InsertStatementProvider<T>): Int =
update(insertStatement.insertStatement, BeanPropertySqlParameterSource(insertStatement.row))
fun <T : Any> NamedParameterJdbcTemplate.insert(
insertStatement: InsertStatementProvider<T>,
keyHolder: KeyHolder
): Int =
update(insertStatement.insertStatement, BeanPropertySqlParameterSource(insertStatement.row), keyHolder)
fun <T : Any> NamedParameterJdbcTemplate.insert(row: T): SingleRowInsertHelper<T> =
SingleRowInsertHelper(row, this)
// general insert
fun NamedParameterJdbcTemplate.generalInsert(insertStatement: GeneralInsertStatementProvider): Int =
update(insertStatement.insertStatement, insertStatement.parameters)
fun NamedParameterJdbcTemplate.generalInsert(
insertStatement: GeneralInsertStatementProvider,
keyHolder: KeyHolder
): Int =
update(insertStatement.insertStatement, MapSqlParameterSource(insertStatement.parameters), keyHolder)
fun NamedParameterJdbcTemplate.insertInto(table: SqlTable, completer: GeneralInsertCompleter): Int =
generalInsert(org.mybatis.dynamic.sql.util.kotlin.spring.insertInto(table, completer))
// multiple row insert
fun <T : Any> NamedParameterJdbcTemplate.insertMultiple(vararg records: T): MultiRowInsertHelper<T> =
insertMultiple(records.asList())
fun <T : Any> NamedParameterJdbcTemplate.insertMultiple(records: List<T>): MultiRowInsertHelper<T> =
MultiRowInsertHelper(records, this)
fun <T> NamedParameterJdbcTemplate.insertMultiple(insertStatement: MultiRowInsertStatementProvider<T>): Int =
update(insertStatement.insertStatement, BeanPropertySqlParameterSource(insertStatement))
fun <T> NamedParameterJdbcTemplate.insertMultiple(
insertStatement: MultiRowInsertStatementProvider<T>,
keyHolder: KeyHolder
): Int =
update(insertStatement.insertStatement, BeanPropertySqlParameterSource(insertStatement), keyHolder)
fun NamedParameterJdbcTemplate.insertSelect(table: SqlTable, completer: InsertSelectCompleter): Int =
insertSelect(org.mybatis.dynamic.sql.util.kotlin.spring.insertSelect(table, completer))
fun NamedParameterJdbcTemplate.insertSelect(insertStatement: InsertSelectStatementProvider): Int =
update(insertStatement.insertStatement, MapSqlParameterSource(insertStatement.parameters))
fun NamedParameterJdbcTemplate.insertSelect(
insertStatement: InsertSelectStatementProvider,
keyHolder: KeyHolder
): Int =
update(insertStatement.insertStatement, MapSqlParameterSource(insertStatement.parameters), keyHolder)
// insert with KeyHolder support
fun NamedParameterJdbcTemplate.withKeyHolder(keyHolder: KeyHolder, build: KeyHolderHelper.() -> Int): Int =
build(KeyHolderHelper(keyHolder, this))
fun NamedParameterJdbcTemplate.select(
vararg selectList: BasicColumn,
completer: SelectCompleter
): SelectListMapperGatherer =
select(selectList.toList(), completer)
fun NamedParameterJdbcTemplate.select(
selectList: List<BasicColumn>,
completer: SelectCompleter
): SelectListMapperGatherer =
SelectListMapperGatherer(org.mybatis.dynamic.sql.util.kotlin.spring.select(selectList, completer), this)
fun NamedParameterJdbcTemplate.selectDistinct(
vararg selectList: BasicColumn,
completer: SelectCompleter
): SelectListMapperGatherer =
selectDistinct(selectList.toList(), completer)
fun NamedParameterJdbcTemplate.selectDistinct(
selectList: List<BasicColumn>,
completer: SelectCompleter
): SelectListMapperGatherer =
SelectListMapperGatherer(
org.mybatis.dynamic.sql.util.kotlin.spring.selectDistinct(selectList, completer),
this
)
fun <T> NamedParameterJdbcTemplate.selectList(
selectStatement: SelectStatementProvider,
rowMapper: (rs: ResultSet, rowNum: Int) -> T
): List<T> =
query(selectStatement.selectStatement, selectStatement.parameters, rowMapper)
fun <T : Any> NamedParameterJdbcTemplate.selectList(
selectStatement: SelectStatementProvider,
type: KClass<T>
): List<T?> =
queryForList(selectStatement.selectStatement, selectStatement.parameters, type.java)
fun NamedParameterJdbcTemplate.selectOne(
vararg selectList: BasicColumn,
completer: SelectCompleter
): SelectOneMapperGatherer =
selectOne(selectList.toList(), completer)
fun NamedParameterJdbcTemplate.selectOne(
selectList: List<BasicColumn>,
completer: SelectCompleter
): SelectOneMapperGatherer =
SelectOneMapperGatherer(
org.mybatis.dynamic.sql.util.kotlin.spring.select(selectList, completer),
this
)
fun <T> NamedParameterJdbcTemplate.selectOne(
selectStatement: SelectStatementProvider,
rowMapper: (rs: ResultSet, rowNum: Int) -> T
): T? = try {
queryForObject(selectStatement.selectStatement, selectStatement.parameters, rowMapper)
} catch (e: EmptyResultDataAccessException) {
null
}
fun <T : Any> NamedParameterJdbcTemplate.selectOne(
selectStatement: SelectStatementProvider,
type: KClass<T>
): T? = try {
queryForObject(selectStatement.selectStatement, selectStatement.parameters, type.java)
} catch (e: EmptyResultDataAccessException) {
null
}
fun NamedParameterJdbcTemplate.update(updateStatement: UpdateStatementProvider): Int =
update(updateStatement.updateStatement, updateStatement.parameters)
fun NamedParameterJdbcTemplate.update(table: SqlTable, completer: UpdateCompleter): Int =
update(org.mybatis.dynamic.sql.util.kotlin.spring.update(table, completer))
// support classes for select DSL
@MyBatisDslMarker
class SelectListMapperGatherer(
private val selectStatement: SelectStatementProvider,
private val template: NamedParameterJdbcTemplate
) {
fun <T> withRowMapper(rowMapper: (rs: ResultSet, rowNum: Int) -> T): List<T> =
template.selectList(selectStatement, rowMapper)
}
@MyBatisDslMarker
class SelectOneMapperGatherer(
private val selectStatement: SelectStatementProvider,
private val template: NamedParameterJdbcTemplate
) {
fun <T> withRowMapper(rowMapper: (rs: ResultSet, rowNum: Int) -> T): T? =
template.selectOne(selectStatement, rowMapper)
}
@MyBatisDslMarker
class KeyHolderHelper(private val keyHolder: KeyHolder, private val template: NamedParameterJdbcTemplate) {
fun insertInto(table: SqlTable, completer: GeneralInsertCompleter): Int =
template.generalInsert(org.mybatis.dynamic.sql.util.kotlin.spring.insertInto(table, completer), keyHolder)
fun <T : Any> insert(row: T): SingleRowInsertWithKeyHolderHelper<T> =
SingleRowInsertWithKeyHolderHelper(row, template, keyHolder)
fun <T : Any> insertMultiple(vararg records: T): MultiRowInsertWithKeyHolderHelper<T> =
insertMultiple(records.asList())
fun <T : Any> insertMultiple(records: List<T>): MultiRowInsertWithKeyHolderHelper<T> =
MultiRowInsertWithKeyHolderHelper(records, template, keyHolder)
fun insertSelect(table: SqlTable, completer: InsertSelectCompleter): Int =
template.insertSelect(org.mybatis.dynamic.sql.util.kotlin.spring.insertSelect(table, completer), keyHolder)
}
@MyBatisDslMarker
class BatchInsertHelper<T : Any>(private val records: List<T>, private val template: NamedParameterJdbcTemplate) {
fun into(table: SqlTable, completer: BatchInsertCompleter<T>): IntArray =
template.insertBatch(insertBatch(records).into(table, completer))
}
@MyBatisDslMarker
class MultiRowInsertHelper<T : Any>(
private val records: List<T>,
private val template: NamedParameterJdbcTemplate
) {
fun into(table: SqlTable, completer: MultiRowInsertCompleter<T>): Int =
with(insertMultiple(records).into(table, completer)) {
template.insertMultiple(this)
}
}
@MyBatisDslMarker
class MultiRowInsertWithKeyHolderHelper<T : Any>(
private val records: List<T>,
private val template: NamedParameterJdbcTemplate,
private val keyHolder: KeyHolder
) {
fun into(table: SqlTable, completer: MultiRowInsertCompleter<T>): Int =
with(insertMultiple(records).into(table, completer)) {
template.insertMultiple(this, keyHolder)
}
}
@MyBatisDslMarker
class SingleRowInsertHelper<T : Any>(
private val row: T,
private val template: NamedParameterJdbcTemplate
) {
fun into(table: SqlTable, completer: InsertCompleter<T>): Int =
with(insert(row).into(table, completer)) {
template.insert(this)
}
}
@MyBatisDslMarker
class SingleRowInsertWithKeyHolderHelper<T : Any>(
private val row: T,
private val template: NamedParameterJdbcTemplate,
private val keyHolder: KeyHolder
) {
fun into(table: SqlTable, completer: InsertCompleter<T>): Int =
with(insert(row).into(table, completer)) {
template.insert(this, keyHolder)
}
}
| apache-2.0 | c4b6a625ebb33fa55daddf80f5a854ec | 42.082781 | 115 | 0.790562 | 4.318287 | false | false | false | false |
deadpixelsociety/Kappatron | src/main/kotlin/com/thedeadpixelsociety/kappatron/irc/IrcMessage.kt | 1 | 3244 | package com.thedeadpixelsociety.kappatron.irc
import java.text.ParseException
/**
* Encapsulates an IRC message with optional tags.
* Based on the JavaScript implementation at https://github.com/sigkell/irc-message/blob/master/index.js
* @param prefix The message prefix.
* @param command The message command.
* @param params The message parameters (optional).
* @param tags The message tags (optional).
*/
data class IrcMessage(
val prefix: String,
val command: String,
val params: List<String> = listOf(),
val tags: Map<String, String> = mapOf()
) {
companion object {
/**
* Parses the given [message] string into an [IrcMessage]
* @param message The message string.
* @return The parsed [IrcMessage]
* @throws ParseException if the message is malformed.
*/
fun parse(message: String): IrcMessage {
var index = 0
var nextSpace: Int
val tags = mutableMapOf<String, String>()
var prefix = ""
var command = ""
val params = arrayListOf<String>()
fun consumeLeadingSpaces() {
while (message[index] == ' ') index++
}
if (message[index] == '@') {
nextSpace = message.indexOf(' ')
if (nextSpace == -1) throw ParseException("Malformed IRC message", index)
tags.putAll(message.substring(1, nextSpace).split(';').associate {
val kvp = it.split('=')
Pair(kvp[0], if (kvp.size == 2) kvp[1].replace("\\:", ";").replace("\\s", " ").replace("\\\\", "\\") else "true")
})
index = nextSpace + 1
}
consumeLeadingSpaces()
if (message[index] == ':') {
nextSpace = message.indexOf(' ', index)
if (nextSpace == -1) throw ParseException("Malformed IRC message", index)
prefix = message.substring(index + 1, nextSpace)
index = nextSpace + 1
consumeLeadingSpaces()
}
nextSpace = message.indexOf(' ', index)
if (nextSpace == -1) {
if (message.length > index) command = message.substring(index)
} else {
command = message.substring(index, nextSpace)
index = nextSpace + 1
consumeLeadingSpaces()
while (index < message.length) {
nextSpace = message.indexOf(' ', index)
if (message[index] == ':') {
params.add(message.substring(index + 1))
break
}
if (nextSpace != -1) {
params.add(message.substring(index, nextSpace))
index = nextSpace + 1
consumeLeadingSpaces()
continue
}
if (nextSpace == -1) {
params.add(message.substring(index))
break
}
}
}
return IrcMessage(prefix, command, params, tags)
}
}
} | mit | e5dea7201c6a3f1bd60428ee83e3b388 | 35.055556 | 133 | 0.495376 | 4.930091 | false | false | false | false |
die-tageszeitung/tazapp-android | tazapp/src/main/java/de/thecode/android/tazreader/room/DownloadsDao.kt | 1 | 957 | package de.thecode.android.tazreader.room
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Query
import de.thecode.android.tazreader.data.Download
import de.thecode.android.tazreader.data.DownloadType
import java.util.*
@Dao
interface DownloadsDao : BaseDao<Download> {
@Query("SELECT * FROM DOWNLOADS WHERE `key` = :key")
fun getDownloadByKey(key: String): Download?
@Query("SELECT * FROM DOWNLOADS WHERE `key` = :key")
fun getDownloadByKeyLive(key: String): LiveData<Download>
@Query("SELECT * FROM DOWNLOADS WHERE downloadManagerId = :id")
fun getDownloadById(id: Long): Download?
@Query("SELECT * FROM DOWNLOADS WHERE type = :type")
fun getByType(type: DownloadType): List<Download>
@Query("DELETE FROM DOWNLOADS WHERE `key` = :key")
fun deleteByKey(key: String)
@Query("SELECT * FROM DOWNLOADS WHERE workerUuid = :uuid")
fun getByWorkerUuid(uuid: UUID): Download?
} | agpl-3.0 | 7c157d3da5850dbf72c0b08db24d3794 | 32.034483 | 67 | 0.731452 | 3.709302 | false | false | false | false |
phw/PicardBarcodeScanner | app/src/main/java/org/musicbrainz/picard/barcodescanner/activities/PerformSearchActivity.kt | 1 | 5777 | /*
* Copyright (C) 2012, 2021 Philipp Wolfer <[email protected]>
* Copyright (C) 2021 Akshat Tiwari
*
* This file is part of MusicBrainz Picard Barcode Scanner.
*
* MusicBrainz Picard Barcode Scanner 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.
*
* MusicBrainz Picard Barcode Scanner 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
* MusicBrainz Picard Barcode Scanner. If not, see
* <http://www.gnu.org/licenses/>.
*/
package org.musicbrainz.picard.barcodescanner.activities
import android.content.Intent
import android.os.Bundle
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.musicbrainz.picard.barcodescanner.R
import org.musicbrainz.picard.barcodescanner.data.Release
import org.musicbrainz.picard.barcodescanner.data.ReleaseSearchResponse
import org.musicbrainz.picard.barcodescanner.databinding.ActivityPerformSearchBinding
import org.musicbrainz.picard.barcodescanner.util.Constants
import org.musicbrainz.picard.barcodescanner.webservice.MusicBrainzClient
import org.musicbrainz.picard.barcodescanner.webservice.PicardClient
class PerformSearchActivity : BaseActivity() {
private var mBarcode: String? = null
private val uiScope = CoroutineScope(Dispatchers.Main)
private lateinit var binding: ActivityPerformSearchBinding
/** Called when the activity is first created. */
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityPerformSearchBinding.inflate(layoutInflater)
setContentView(binding.root)
val actionBar = supportActionBar
actionBar!!.setDisplayHomeAsUpEnabled(true)
binding.loadingText.setText(R.string.loading_musicbrainz_text)
handleIntents()
uiScope.launch {
search()
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
uiScope.launch {
search()
}
}
override fun handleIntents() {
super.handleIntents()
val extras: Bundle? = intent.extras
if (extras != null) {
mBarcode = extras.getString(Constants.INTENT_EXTRA_BARCODE)
}
}
private suspend fun search() {
val result: ReleaseSearchResponse
try {
result = musicBrainzClient.queryReleasesByBarcode(mBarcode)
if (result.releases.isEmpty()) {
showResultActivity(result.releases)
return
}
}
catch (e: Exception){
Log.e(this.javaClass.name, e.message, e)
showResultActivityWithError(e.message)
return
}
if (sendToPicard(result.releases)) {
showResultActivity(result.releases)
} else {
configurePicard()
}
}
private suspend fun sendToPicard(releases: List<Release>) : Boolean {
binding.loadingText.setText(R.string.loading_picard_text)
val picardClient = PicardClient(preferences.ipAddress!!, preferences.port)
var status = false
for (release in releases) {
val result = picardClient.openRelease(release.id!!)
if (result) {
status = true
}
}
return status
}
private fun showResultActivityWithError(errorMessage: String?) {
val resultIntent = Intent(
this@PerformSearchActivity,
ResultActivity::class.java
)
resultIntent.putExtra(
Constants.INTENT_EXTRA_ERROR,
errorMessage
)
startActivity(resultIntent)
finish()
}
private fun showResultActivity(releases: List<Release>) {
val resultIntent = Intent(
this@PerformSearchActivity,
ResultActivity::class.java
)
val numberOfReleases = releases.size
val releaseTitles = arrayOfNulls<String>(numberOfReleases)
val releaseArtists = arrayOfNulls<String>(numberOfReleases)
val releaseDates = arrayOfNulls<String>(numberOfReleases)
for (i in 0 until numberOfReleases) {
val release: Release = releases[i]
releaseTitles[i] = release.title
releaseArtists[i] = release.releaseArtist
releaseDates[i] = release.date
}
resultIntent.putExtra(
Constants.INTENT_EXTRA_BARCODE,
mBarcode
)
resultIntent.putExtra(
Constants.INTENT_EXTRA_RELEASE_TITLES,
releaseTitles
)
resultIntent.putExtra(
Constants.INTENT_EXTRA_RELEASE_ARTISTS,
releaseArtists
)
resultIntent.putExtra(
Constants.INTENT_EXTRA_RELEASE_DATES,
releaseDates
)
startActivity(resultIntent)
finish()
}
private fun configurePicard() {
val configurePicard = Intent(
this@PerformSearchActivity,
PreferencesActivity::class.java
)
configurePicard.putExtra(
Constants.INTENT_EXTRA_BARCODE,
mBarcode
)
startActivity(configurePicard)
}
private val musicBrainzClient: MusicBrainzClient by lazy {
MusicBrainzClient()
}
}
| gpl-3.0 | 4da2b7cf772d7c32fa84664e0ed94e23 | 33.183432 | 85 | 0.660204 | 4.73913 | false | false | false | false |
sandjelkovic/dispatchd | content-service/src/test/kotlin/com/sandjelkovic/dispatchd/content/StriktExtensions.kt | 1 | 2235 | package com.sandjelkovic.dispatchd.content
import arrow.core.*
import strikt.api.Assertion
import strikt.assertions.isA
fun Assertion.Builder<String>.isEqualToOneOf(possibilities: Collection<String>): Assertion.Builder<String> =
assertThat("Value is not present") { actual -> possibilities.contains(actual) }
// Arrow
fun <T> Assertion.Builder<Option<T>>.isSome(valueAssertions: Assertion.Builder<T>.() -> Unit = {}): Assertion.Builder<T> =
assertThat("is Some") { it.isDefined() }
.isA<Some<T>>()
.get { t }
.and(valueAssertions)
fun <T> Assertion.Builder<Option<T>>.isNone(): Assertion.Builder<Option<T>> =
assertThat("is None") { it.isEmpty() }
fun <L, R> Assertion.Builder<Either<L, R>>.isRight(valueAssertions: Assertion.Builder<R>.() -> Unit = {}): Assertion.Builder<R> =
assertThat("is Right") { it.isRight() }
.isA<Either.Right<R>>()
.get { b }
.and(valueAssertions)
fun <L, R> Assertion.Builder<Either<L, R>>.isLeft(valueAssertions: Assertion.Builder<L>.() -> Unit = {}): Assertion.Builder<L> =
assertThat("is Left") { it.isLeft() }
.isA<Either.Left<L>>()
.get { a }
.and(valueAssertions)
fun <L, R> Assertion.Builder<Validated<L, R>>.isValid(valueAssertions: Assertion.Builder<R>.() -> Unit = {}): Assertion.Builder<R> =
assertThat("is Valid") { it.isValid }
.isA<Valid<R>>()
.get { a }
.and(valueAssertions)
fun <L, R> Assertion.Builder<Validated<L, R>>.isInvalid(valueAssertions: Assertion.Builder<L>.() -> Unit = {}): Assertion.Builder<L> =
assertThat("is Invalid") { it.isInvalid }
.isA<Invalid<L>>()
.get { e }
.and(valueAssertions)
fun <T> Assertion.Builder<Try<T>>.isSuccess(valueAssertions: Assertion.Builder<T>.() -> Unit = {}): Assertion.Builder<T> {
return assertThat("is Success") { it.isSuccess() }
.isA<Success<T>>()
.get { value }
.and(valueAssertions)
}
fun <T> Assertion.Builder<Try<T>>.isFailure(valueAssertions: Assertion.Builder<Throwable>.() -> Unit = {}): Assertion.Builder<Throwable> =
assertThat("is Failure") { it.isFailure() }
.isA<Failure>()
.get { exception }
.and(valueAssertions)
| apache-2.0 | 6ff366d69b864988c0be405710ed9fc7 | 38.910714 | 138 | 0.634452 | 3.628247 | false | false | false | false |
pgutkowski/KGraphQL | src/test/kotlin/com/github/pgutkowski/kgraphql/request/DocumentParserTest.kt | 1 | 7917 | package com.github.pgutkowski.kgraphql.request
import com.github.pgutkowski.kgraphql.request.graph.SelectionTree
import com.github.pgutkowski.kgraphql.request.graph.argBranch
import com.github.pgutkowski.kgraphql.request.graph.argLeaf
import com.github.pgutkowski.kgraphql.request.graph.args
import com.github.pgutkowski.kgraphql.request.graph.branch
import com.github.pgutkowski.kgraphql.request.graph.extFragment
import com.github.pgutkowski.kgraphql.request.graph.inlineFragment
import com.github.pgutkowski.kgraphql.request.graph.leaf
import com.github.pgutkowski.kgraphql.request.graph.leafs
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
class DocumentParserTest {
val graphParser = DocumentParser()
@Test
fun `nested query parsing`() {
val map = graphParser.parseSelectionTree("{hero{name appearsIn}\nvillain{name deeds}}")
val expected = SelectionTree(
branch( "hero",
leaf("name"),
leaf("appearsIn")
),
branch( "villain",
leaf("name"),
leaf("deeds")
)
)
assertThat(map, equalTo(expected))
}
@Test
fun `double nested query parsing`() {
val map = graphParser.parseSelectionTree("{hero{name appearsIn{title, year}}\nvillain{name deeds}}")
val expected = SelectionTree(
branch( "hero",
leaf("name"),
branch("appearsIn",
leaf("title"),
leaf("year")
)
),
branch( "villain",
leaf("name"),
leaf("deeds")
)
)
assertThat(map, equalTo(expected))
}
@Test
fun `triple nested query parsing`() {
val map = graphParser.parseSelectionTree("{hero{name appearsIn{title{abbr full} year}}\nvillain{name deeds}}")
val expected = SelectionTree(
branch( "hero",
leaf("name"),
branch("appearsIn",
branch("title",
leaf("abbr"),
leaf("full")),
leaf("year")
)
),
branch( "villain",
leaf("name"),
leaf("deeds")
)
)
assertThat(map, equalTo(expected))
}
@Test
fun `query with arguments parsing`() {
val map = graphParser.parseSelectionTree("{hero(name: \"Batman\"){ power }}")
val expected = SelectionTree(
argBranch("hero",
args("name" to "\"Batman\""),
leaf("power")
)
)
assertThat(map, equalTo(expected))
}
@Test
fun `query with alias parsing`() {
val map = graphParser.parseSelectionTree("{batman: hero(name: \"Batman\"){ power }}")
val expected = SelectionTree(
argBranch("hero", "batman",
args("name" to "\"Batman\""),
leaf("power")
)
)
assertThat(map, equalTo(expected))
}
@Test
fun `query with field alias parsing`() {
val map = graphParser.parseSelectionTree("{batman: hero(name: \"Batman\"){ skills : powers }}")
val expected = SelectionTree(
argBranch("hero", "batman",
args("name" to "\"Batman\""),
leaf("powers", "skills")
)
)
assertThat(map, equalTo(expected))
}
@Test
fun `mutation with field alias parsing`(){
val map = graphParser.parseSelectionTree(("{createHero(name: \"Batman\", appearsIn: \"The Dark Knight\")}"))
val expected = SelectionTree(
argLeaf("createHero", args("name" to "\"Batman\"", "appearsIn" to "\"The Dark Knight\""))
)
assertThat(map, equalTo(expected))
}
@Test
fun `field arguments parsing`(){
val map = graphParser.parseSelectionTree(("{hero{name height(unit: FOOT)}}"))
val expected = SelectionTree(
branch("hero",
leaf("name"),
argLeaf("height", args("unit" to "FOOT"))
)
)
assertThat(map, equalTo(expected))
}
@Test
fun `mutation selection set parsing`(){
val map = graphParser.parseSelectionTree(("{createHero(name: \"Batman\", appearsIn: \"The Dark Knight\"){id name timestamp}}"))
val expected = SelectionTree(
argBranch("createHero",
args("name" to "\"Batman\"", "appearsIn" to "\"The Dark Knight\""),
*leafs("id", "name", "timestamp")
)
)
assertThat(map, equalTo(expected))
}
@Test
fun `mutation nested selection set parsing`(){
val map = graphParser.parseSelectionTree(("{createHero(name: \"Batman\", appearsIn: \"The Dark Knight\"){id name {real asHero}}}"))
val expected = SelectionTree(
argBranch("createHero",
args("name" to "\"Batman\"", "appearsIn" to "\"The Dark Knight\""),
leaf("id"),
branch("name", *leafs("real", "asHero"))
)
)
assertThat(map, equalTo(expected))
}
@Test
fun `fragment parsing`(){
val map = graphParser.parseDocument("{hero {id ...heroName}} fragment heroName on Hero {name {real asHero}}")
val expected = SelectionTree(
branch("hero",
leaf("id"),
extFragment( "...heroName", "Hero", branch("name", *leafs("real", "asHero")))
)
)
assertThat(map.first().selectionTree, equalTo(expected))
}
@Test
fun `fragment with type condition parsing`(){
val map = graphParser.parseDocument("{hero {id ...heroName}} fragment heroName on Hero {name {real asHero}}")
val expected = SelectionTree(
branch("hero",
leaf("id"),
extFragment( "...heroName", "Hero",
branch("name", *leafs("real", "asHero"))
)
)
)
assertThat(map.first().selectionTree, equalTo(expected))
}
@Test
fun `inline fragment parsing`(){
val map = graphParser.parseDocument("{hero {id ... on Hero {height, power}}}")
val expected = SelectionTree(
branch("hero",
leaf("id"),
inlineFragment("Hero",
leaf("height"),
leaf("power")
)
)
)
assertThat(map.first().selectionTree, equalTo(expected))
}
@Test
fun `two inline fragments parsing`(){
val map = graphParser.parseDocument("{hero {id ... on Hero {height, power}, ... on Villain {height, deeds}}}")
val expected = SelectionTree(
branch("hero",
leaf("id"),
inlineFragment("Hero",
leaf("height"),
leaf("power")
),
inlineFragment("Villain",
leaf("height"),
leaf("deeds")
)
)
)
assertThat(map.first().selectionTree, equalTo(expected))
}
} | mit | bf16a75de894b682b3471d3ac0da8904 | 33.576419 | 139 | 0.484906 | 5.001263 | false | true | false | false |
soniccat/android-taskmanager | authorization/src/main/java/com/example/alexeyglushkov/authorization/requestbuilder/Parameter.kt | 1 | 945 | package com.example.alexeyglushkov.authorization.requestbuilder
/**
* @author Pablo Fernandez
*/
class Parameter(private val key: String, private val value: String) : Comparable<Parameter> {
fun asUrlEncodedPair(): String {
return OAuthEncoder.encode(key) + "=" + OAuthEncoder.encode(value)
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (other === this) return true
if (other !is Parameter) return false
val otherParam = other
return otherParam.key == key && otherParam.value == value
}
override fun hashCode(): Int {
return key.hashCode() + value.hashCode()
}
override fun compareTo(parameter: Parameter): Int {
val keyDiff = key.compareTo(parameter.key)
return if (keyDiff != 0) keyDiff else value.compareTo(parameter.value)
}
companion object {
private const val UTF = "UTF8"
}
} | mit | f2c0fb9547925777cf411810614c3aee | 28.5625 | 93 | 0.644444 | 4.256757 | false | false | false | false |
apollo-rsps/apollo | game/plugin/entity/following/src/org/apollo/plugin/entity/following/FollowAction.kt | 1 | 1414 | package org.apollo.plugin.entity.following
import org.apollo.game.action.Action
import org.apollo.game.model.Direction
import org.apollo.game.model.Position
import org.apollo.game.model.entity.Player
import org.apollo.net.message.Message
import org.apollo.plugin.entity.pathing.walkBehind
import org.apollo.plugin.entity.pathing.walkTo
class FollowAction(player: Player, private val target: Player) : Action<Player>(0, true, player) {
var lastPosition: Position? = null
companion object {
fun start(player: Player, target: Player, message: Message? = null) {
player.startAction(FollowAction(player, target))
message?.terminate()
}
}
override fun execute() {
if (!target.isActive) {
stop()
return
}
mob.interactingMob = target
if (target.position == lastPosition) {
return
}
val distance = mob.position.getDistance(target.position)
if (distance >= 15) {
stop()
return
}
if (mob.position == target.position) {
val directions = Direction.NESW
val directionOffset = (Math.random() * directions.size).toInt()
mob.walkTo(target.position.step(1, directions[directionOffset]))
} else {
mob.walkBehind(target)
lastPosition = target.position
}
}
} | isc | 595dcc1856f6b120c2134563a90096c7 | 27.877551 | 98 | 0.622348 | 4.271903 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-git/src/test/java/net/nemerosa/ontrack/extension/git/service/GitIssueSearchIT.kt | 1 | 5273 | package net.nemerosa.ontrack.extension.git.service
import net.nemerosa.ontrack.extension.git.AbstractGitTestJUnit4Support
import net.nemerosa.ontrack.extension.issues.support.MockIssue
import net.nemerosa.ontrack.extension.issues.support.MockIssueServiceExtension
import net.nemerosa.ontrack.extension.issues.support.MockIssueStatus
import org.junit.Test
import org.springframework.beans.factory.annotation.Autowired
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class GitIssueSearchIT : AbstractGitTestJUnit4Support() {
@Autowired
private lateinit var mockIssueServiceExtension: MockIssueServiceExtension
@Test
fun `Issue search on one branch`() {
createRepo {
commit(1, "#1 First commit", pause = true)
commit(2, "#2 Second commit", pause = true)
commit(3, "#2 Third commit", pause = true)
commit(4, "#1 Fourth commit")
} and { repo, _ ->
project {
gitProject(repo)
branch("main") {
gitBranch {
buildNameAsCommit(abbreviated = true)
}
build(repo.commitLookup("#1 First commit"))
build(repo.commitLookup("#2 Third commit"))
build(repo.commitLookup("#1 Fourth commit"))
// Makes sure to index the branch builds commits
gitService.collectIndexableGitCommitForBranch(this)
}
// Looks for an issue
val info = asUserWithView(this).call {
gitService.getIssueProjectInfo(id, "#2")
}
assertNotNull(info) { gitIssueInfo ->
assertEquals("2", gitIssueInfo.issue.key)
assertEquals("#2", gitIssueInfo.issue.displayKey)
assertNotNull(gitIssueInfo.commitInfo) { gitCommitInfo ->
gitCommitInfo.assertBranchInfos(
"Development" to listOf(
BranchInfoTest(
branch = "main",
firstBuild = repo.commitLookup("#2 Third commit")
)
)
)
}
}
}
}
}
/**
* Gets issue info across two branches.
*
* ```
* | |
* * | Commit #2 (main)
* | |
* | * Commit #2 (release/1.0)
* | |
* | /
* | /
* * Commit #2
* ```
*
* Last commit for issue #2 is located on branch `main` and therefore
* does not have any branch info (because not on a release branch).
*/
@Test
fun `Issue search between two branches`() {
createRepo {
val commit1 = commit(1, "Commit #2 one", pause = true)
git("checkout", "-b", "1.0")
val commit2 = commit(2, "Commit #2 two", pause = true)
git("checkout", "main")
val commit3 = commit(3, "Commit #2 three", pause = true)
// Commits index
mapOf(
1 to commit1,
2 to commit2,
3 to commit3
)
} and { repo, commits ->
// Creates a project and two branches<
project {
gitProject(repo)
branch("main") {
gitBranch("main") {
commitAsProperty()
}
build("1") {
gitCommitProperty(commits.getValue(1))
}
build("3") {
gitCommitProperty(commits.getValue(3))
}
}
branch("release-1.0") {
gitBranch("release/1.0") {
commitAsProperty()
}
build("2") {
gitCommitProperty(commits.getValue(2))
}
}
// Issue service
val issue2 = MockIssue(2, MockIssueStatus.OPEN, "feature")
mockIssueServiceExtension.register(issue2)
// Issue info
val info = asUserWithView(this).call {
gitService.getIssueProjectInfo(id, "#2")
}
assertNotNull(info) { gitIssueInfo ->
assertEquals("2", gitIssueInfo.issue.key)
assertEquals("#2", gitIssueInfo.issue.displayKey)
assertNotNull(gitIssueInfo.commitInfo) { gitCommitInfo ->
gitCommitInfo.assertBranchInfos(
"Development" to listOf(
BranchInfoTest(
branch = "main",
firstBuild = "3"
)
)
)
}
}
}
}
}
}
| mit | 0f41da96909a67eaf7f691eb110621c5 | 36.397163 | 97 | 0.448322 | 5.504175 | false | true | false | false |
openHPI/android-app | app/src/main/java/de/xikolo/controllers/main/DateListAdapter.kt | 1 | 5444 | package de.xikolo.controllers.main
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import butterknife.BindView
import butterknife.ButterKnife
import de.xikolo.App
import de.xikolo.R
import de.xikolo.controllers.base.BaseMetaRecyclerViewAdapter
import de.xikolo.models.CourseDate
import de.xikolo.models.DateOverview
import de.xikolo.utils.extensions.timeLeftUntilString
import de.xikolo.views.DateTextView
import java.text.DateFormat
import java.util.Locale
class DateListAdapter(private val onDateClickListener: OnDateClickListener?) :
BaseMetaRecyclerViewAdapter<DateOverview, CourseDate>() {
companion object {
val TAG: String = DateListAdapter::class.java.simpleName
}
var showCourse = true
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
ITEM_VIEW_TYPE_META ->
OverviewViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.item_date_list_overview, parent, false)
)
ITEM_VIEW_TYPE_HEADER ->
HeaderViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.item_header, parent, false)
)
else ->
CourseDateViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.item_date_list, parent, false)
)
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is HeaderViewHolder -> {
bindHeaderViewHolder(holder, position)
holder.header.setPadding(
App.instance.resources.getDimensionPixelSize(R.dimen.content_horizontal_margin),
holder.header.paddingTop,
App.instance.resources.getDimensionPixelSize(R.dimen.content_horizontal_margin),
holder.header.paddingBottom
)
}
is OverviewViewHolder -> {
val dateOverview = super.contentList.get(position) as DateOverview
holder.numberOfDatesToday.text = dateOverview.countToday.toString()
holder.numberOfDatesWeek.text = dateOverview.countNextSevenDays.toString()
holder.numberOfAllDates.text = dateOverview.countFuture.toString()
}
is CourseDateViewHolder -> {
val courseDate = super.contentList.get(position) as CourseDate
holder.textType.text = courseDate.getTypeString(App.instance)
holder.textCourse.text = courseDate.getCourse()?.title
if (onDateClickListener != null) {
holder.container.setOnClickListener {
onDateClickListener.onCourseClicked(courseDate.courseId)
}
} else {
holder.container.isClickable = false
courseDate.date?.let {
holder.textDate.text = DateFormat.getDateTimeInstance(
DateFormat.YEAR_FIELD or
DateFormat.MONTH_FIELD or
DateFormat.DATE_FIELD,
DateFormat.SHORT,
Locale.getDefault()
).format(it)
holder.textDate.setDate(it)
}
}
if (!showCourse) {
holder.textCourse.visibility = View.GONE
holder.textBullet.visibility = View.GONE
}
holder.textDateTitle.text = courseDate.title
courseDate.date?.let {
holder.textTimeLeft.text = String.format(
App.instance.getString(R.string.time_left),
it.timeLeftUntilString(App.instance)
)
}
}
}
}
interface OnDateClickListener {
fun onCourseClicked(courseId: String?)
}
class OverviewViewHolder(view: View) : RecyclerView.ViewHolder(view) {
@BindView(R.id.textNumberOfDatesToday)
lateinit var numberOfDatesToday: TextView
@BindView(R.id.textNumberOfDatesWeek)
lateinit var numberOfDatesWeek: TextView
@BindView(R.id.textNumberOfAllDates)
lateinit var numberOfAllDates: TextView
init {
ButterKnife.bind(this, view)
}
}
class CourseDateViewHolder(view: View) : RecyclerView.ViewHolder(view) {
@BindView(R.id.container)
lateinit var container: View
@BindView(R.id.textDateDate)
lateinit var textDate: DateTextView
@BindView(R.id.textDateType)
lateinit var textType: TextView
@BindView(R.id.textDateBullet)
lateinit var textBullet: TextView
@BindView(R.id.textDateTitle)
lateinit var textDateTitle: TextView
@BindView(R.id.textDateTimeLeft)
lateinit var textTimeLeft: TextView
@BindView(R.id.textDateCourse)
lateinit var textCourse: TextView
init {
ButterKnife.bind(this, view)
}
}
}
| bsd-3-clause | ac4e2916b3165f2111a78e61cf9f3c1a | 33.675159 | 100 | 0.593865 | 5.116541 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge3d/Skeleton3D.kt | 1 | 1560 | package com.soywiz.korge3d
import com.soywiz.korge3d.internal.*
import com.soywiz.korma.geom.*
@Korge3DExperimental
open class Joint3D constructor(
val jid: String,
val jname: String,
val jsid: String,
val jointParent: Joint3D? = null,
initialMatrix: Matrix3D
) : Container3D() {
init {
this.transform.setMatrix(initialMatrix)
this.name = jname
this.id = jid
if (jointParent != null) {
this.parent = jointParent
}
}
val poseMatrix = this.transform.globalMatrix.clone()
val poseMatrixInv = poseMatrix.clone().invert()
val childJoints = arrayListOf<Joint3D>()
val descendants: List<Joint3D> get() = childJoints.flatMap { it.descendantsAndThis }
val descendantsAndThis: List<Joint3D> get() = listOf(this) + descendants
//val jointTransform = Transform3D()
override fun render(ctx: RenderContext3D) {
}
override fun toString(): String = "Joint3D(id=$jid, name=$name, sid=$jsid)"
}
@Korge3DExperimental
data class Bone3D constructor(
val index: Int,
val name: String,
val invBindMatrix: Matrix3D
)
@Korge3DExperimental
data class Skin3D(val bindShapeMatrix: Matrix3D, val bones: List<Bone3D>) {
val bindShapeMatrixInv = bindShapeMatrix.clone().invert()
val matrices = Array(bones.size) { Matrix3D() }
}
@Korge3DExperimental
class Skeleton3D(val skin: Skin3D, val headJoint: Joint3D) : View3D() {
val allJoints = headJoint.descendantsAndThis
val jointsByName = allJoints.associateBy { it.jname }.toFast()
val jointsBySid = allJoints.associateBy { it.jsid }.toFast()
override fun render(ctx: RenderContext3D) {
}
}
| apache-2.0 | 5b7307c0dde1897b0d601c7932324fbb | 24.57377 | 85 | 0.742308 | 3 | false | false | false | false |
ffc-nectec/FFC | ffc/src/main/kotlin/ffc/api/DefaultInterceptor.kt | 1 | 1631 | /*
* Copyright (c) 2019 NECTEC
* National Electronics and Computer Technology Center, Thailand
*
* 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 ffc.api
import android.os.Build
import ffc.app.BuildConfig
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
import java.lang.String.format
class DefaultInterceptor : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val original = chain.request()
val builder = original.newBuilder()
.addHeader("User-Agent", USER_AGENT)
.addHeader("Accept-Charset", "utf-8")
.addHeader("X-Requested-By", "ffc-v3")
.addHeaderOptional("Accept", "application/json; charset=utf-8")
return chain.proceed(builder.build())
}
companion object {
private val ANDROID = format("Android ${Build.VERSION.RELEASE} (${Build.VERSION.SDK_INT})")
private val DEVICE = format("%s %s", Build.BRAND, Build.MODEL)
private val USER_AGENT = "FFC/${BuildConfig.VERSION_NAME} ($ANDROID; $DEVICE)"
}
}
| apache-2.0 | 1f09627dde3ca1c3efe5b5e90af0c0ff | 33.702128 | 99 | 0.697118 | 4.150127 | false | false | false | false |
vondear/RxTools | RxDemo/src/main/java/com/tamsiree/rxdemo/view/RxPinView.kt | 1 | 1522 | package com.tamsiree.rxdemo.view
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import com.tamsiree.rxdemo.R
import com.tamsiree.rxui.view.scaleimage.RxScaleImageView
/**
* @author tamsiree
*/
class RxPinView @JvmOverloads constructor(context: Context?, attr: AttributeSet? = null) : RxScaleImageView(context, attr) {
private var sPin: PointF? = null
private lateinit var pin: Bitmap
private lateinit var paint: Paint
fun getPin(): PointF? {
return sPin
}
fun setPin(sPin: PointF?) {
this.sPin = sPin
initialise()
invalidate()
}
private fun initialise() {
val density = resources.displayMetrics.densityDpi.toFloat()
pin = BitmapFactory.decodeResource(resources, R.drawable.pushpin_blue)
val w = (density / 420f) * pin.width
val h = density / 420f * pin.height
pin = Bitmap.createScaledBitmap(pin, w.toInt(), h.toInt(), true)
paint = Paint()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
// Don't draw pin before image is ready so it doesn't move around during setup.
if (!isReady) {
return
}
paint.isAntiAlias = true
if (sPin != null) {
val vPin = sourceToViewCoord(sPin)
val vX = vPin.x - pin.width / 2
val vY = vPin.y - pin.height
canvas.drawBitmap(pin, vX, vY, paint)
}
}
init {
initialise()
}
} | apache-2.0 | 4b17148f62f1f78e2cfff42aa2aeac1b | 26.690909 | 124 | 0.616294 | 4.058667 | false | false | false | false |
panpf/sketch | sketch/src/main/java/com/github/panpf/sketch/datasource/ContentDataSource.kt | 1 | 2182 | /*
* Copyright (C) 2022 panpf <[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.github.panpf.sketch.datasource
import android.net.Uri
import androidx.annotation.WorkerThread
import com.github.panpf.sketch.Sketch
import com.github.panpf.sketch.request.ImageRequest
import java.io.File
import java.io.IOException
import java.io.InputStream
/**
* Provides access to image data in content resources
*/
class ContentDataSource constructor(
override val sketch: Sketch,
override val request: ImageRequest,
val contentUri: Uri
) : DataSource {
override val dataFrom: DataFrom = DataFrom.LOCAL
private var _length = -1L
@WorkerThread
@Throws(IOException::class)
override fun length(): Long =
_length.takeIf { it != -1L }
?: (request.context.contentResolver.openFileDescriptor(contentUri, "r")
?.use {
it.statSize
} ?: throw IOException("Invalid content uri: $contentUri")).apply {
this@ContentDataSource._length = this
}
@WorkerThread
@Throws(IOException::class)
override fun newInputStream(): InputStream =
request.context.contentResolver.openInputStream(contentUri)
?: throw IOException("Invalid content uri: $contentUri")
@WorkerThread
@Throws(IOException::class)
override fun file(): File =
if (contentUri.scheme.equals("file", ignoreCase = true)) {
File(contentUri.toString().substring("file://".length))
} else {
super.file()
}
override fun toString(): String = "ContentDataSource('$contentUri')"
} | apache-2.0 | f9ffe704899fac358146b86894d99cb4 | 32.075758 | 83 | 0.681943 | 4.526971 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/imagemanipulator/actions/ResizeAction.kt | 2 | 1019 | package abi44_0_0.expo.modules.imagemanipulator.actions
import android.graphics.Bitmap
private const val KEY_WIDTH = "width"
private const val KEY_HEIGHT = "height"
class ResizeAction(private val width: Int?, private val height: Int?) : Action {
init {
require(width != null || height != null) { "At least one of width or height must be set." }
}
override fun run(bitmap: Bitmap): Bitmap {
val currentImageRatio = bitmap.width.toFloat() / bitmap.height
val newWidth = width ?: (height!! * currentImageRatio).toInt()
val newHeight = height ?: (width!! / currentImageRatio).toInt()
return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true)
}
companion object {
fun fromObject(o: Any): ResizeAction {
require(o is Map<*, *>)
val width = if (o.containsKey(KEY_WIDTH)) ((o[KEY_WIDTH] as Double).toInt()) else null
val height = if (o.containsKey(KEY_HEIGHT)) ((o[KEY_HEIGHT] as Double).toInt()) else null
return ResizeAction(width, height)
}
}
}
| bsd-3-clause | 4c7fe7ab55241b6c509af748a22139a3 | 35.392857 | 95 | 0.68106 | 3.802239 | false | false | false | false |
hannesa2/owncloud-android | owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/PublicShareDialogFragment.kt | 2 | 32826 | /**
* ownCloud Android client application
*
* @author David A. Velasco
* @author David González Verdugo
* @author Christian Schabesberger
* Copyright (C) 2020 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* 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:></http:>//www.gnu.org/licenses/>.
*/
package com.owncloud.android.presentation.ui.sharing.fragments
import android.accounts.Account
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.text.InputType
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.CompoundButton
import android.widget.TextView
import androidx.appcompat.widget.SwitchCompat
import androidx.core.view.isVisible
import androidx.fragment.app.DialogFragment
import com.owncloud.android.R
import com.owncloud.android.databinding.SharePublicDialogBinding
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType
import com.owncloud.android.domain.capabilities.model.OCCapability
import com.owncloud.android.domain.sharing.shares.model.OCShare
import com.owncloud.android.domain.utils.Event.EventObserver
import com.owncloud.android.extensions.avoidScreenshotsIfNeeded
import com.owncloud.android.extensions.parseError
import com.owncloud.android.lib.resources.shares.RemoteShare
import com.owncloud.android.lib.resources.status.OwnCloudVersion
import com.owncloud.android.presentation.UIResult
import com.owncloud.android.presentation.viewmodels.capabilities.OCCapabilityViewModel
import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel
import com.owncloud.android.ui.dialog.ExpirationDatePickerDialogFragment
import com.owncloud.android.utils.DateUtils
import com.owncloud.android.utils.PreferenceUtils
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.core.parameter.parametersOf
import timber.log.Timber
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Date
class PublicShareDialogFragment : DialogFragment() {
/**
* File to share, received as a parameter in construction time
*/
private var file: OCFile? = null
/**
* OC account holding the file to share, received as a parameter in construction time
*/
private var account: Account? = null
/**
* Existing share to update. If NULL, the dialog will create a new share for file.
*/
private var publicShare: OCShare? = null
/**
* Reference to parent listener
*/
private var listener: ShareFragmentListener? = null
/**
* Capabilities of the server
*/
private var capabilities: OCCapability? = null
/**
* Listener for changes in password switch
*/
private var onPasswordInteractionListener: OnPasswordInteractionListener? = null
/**
* Listener for changes in expiration date switch
*/
private var onExpirationDateInteractionListener: OnExpirationDateInteractionListener? = null
private val isSharedFolder: Boolean
get() = file?.isFolder == true || publicShare?.isFolder == true
private val isPasswordVisible: Boolean
get() = view != null && binding.shareViaLinkPasswordValue.inputType and
InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
private// Parse expiration date and convert it to milliseconds
// remember: format is defined by date picker
val expirationDateValueInMillis: Long
get() {
var publicLinkExpirationDateInMillis: Long = -1
val expirationDate = binding.shareViaLinkExpirationValue.text.toString()
if (expirationDate.isNotEmpty()) {
try {
publicLinkExpirationDateInMillis =
ExpirationDatePickerDialogFragment.getDateFormat().parse(expirationDate).time
} catch (e: ParseException) {
Timber.e(e, "Error reading expiration date from input field")
}
}
return publicLinkExpirationDateInMillis
}
/**
* Get expiration date imposed by the server, if any
*/
private val imposedExpirationDate: Long
get() = if (capabilities?.filesSharingPublicExpireDateEnforced == CapabilityBooleanType.TRUE) {
DateUtils.addDaysToDate(
Date(),
capabilities?.filesSharingPublicExpireDateDays!!
)
.time
} else -1
private val ocCapabilityViewModel: OCCapabilityViewModel by viewModel {
parametersOf(
account?.name
)
}
private val ocShareViewModel: OCShareViewModel by viewModel {
parametersOf(
file?.remotePath,
account?.name
)
}
private var _binding: SharePublicDialogBinding? = null
private val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
file = it.getParcelable(ARG_FILE)
account = it.getParcelable(ARG_ACCOUNT)
publicShare = it.getParcelable(ARG_SHARE)
}
check(file != null || publicShare != null) {
"Both ARG_FILE and ARG_SHARE cannot be NULL"
}
setStyle(STYLE_NO_TITLE, 0)
}
private fun updating(): Boolean = publicShare != null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = SharePublicDialogBinding.inflate(inflater, container, false)
return binding.root.apply {
// Allow or disallow touches with other visible windows
filterTouchesWhenObscured = PreferenceUtils.shouldDisallowTouchesWithOtherVisibleWindows(context)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// Get and set the values saved previous to the screen rotation, if any
if (savedInstanceState != null) {
val expirationDate = savedInstanceState.getString(KEY_EXPIRATION_DATE)
if (!expirationDate.isNullOrEmpty()) {
binding.shareViaLinkExpirationValue.isVisible = true
binding.shareViaLinkExpirationValue.text = expirationDate
}
}
initTitleAndLabels()
initPasswordListener()
initExpirationListener()
initPasswordFocusChangeListener()
initPasswordToggleListener()
binding.saveButton.setOnClickListener { onSaveShareSetting() }
binding.cancelButton.setOnClickListener { dismiss() }
dialog?.avoidScreenshotsIfNeeded()
}
private fun initTitleAndLabels() {
if (updating()) {
binding.publicShareDialogTitle.setText(R.string.share_via_link_edit_title)
binding.shareViaLinkNameValue.setText(publicShare?.name)
when (publicShare?.permissions) {
RemoteShare.CREATE_PERMISSION_FLAG
or RemoteShare.DELETE_PERMISSION_FLAG
or RemoteShare.UPDATE_PERMISSION_FLAG
or RemoteShare.READ_PERMISSION_FLAG ->
binding.shareViaLinkEditPermissionReadAndWrite.isChecked = true
RemoteShare.CREATE_PERMISSION_FLAG -> binding.shareViaLinkEditPermissionUploadFiles.isChecked = true
else -> binding.shareViaLinkEditPermissionReadOnly.isChecked = true
}
if (publicShare?.isPasswordProtected == true) {
setPasswordSwitchChecked()
binding.shareViaLinkPasswordValue.isVisible = true
binding.shareViaLinkPasswordValue.hint = getString(R.string.share_via_link_default_password)
}
if (publicShare?.expirationDate != 0L) {
setExpirationDateSwitchChecked()
val formattedDate = ExpirationDatePickerDialogFragment.getDateFormat().format(
Date(publicShare?.expirationDate!!)
)
binding.shareViaLinkExpirationValue.isVisible = true
binding.shareViaLinkExpirationValue.text = formattedDate
}
} else {
binding.shareViaLinkNameValue.setText(arguments?.getString(ARG_DEFAULT_LINK_NAME, ""))
}
}
private fun onSaveShareSetting() {
// Get data filled by user
val publicLinkName = binding.shareViaLinkNameValue.text.toString()
var publicLinkPassword: String? = binding.shareViaLinkPasswordValue.text.toString()
val publicLinkExpirationDateInMillis = expirationDateValueInMillis
val publicLinkPermissions: Int
val publicUploadPermission: Boolean
when (binding.shareViaLinkEditPermissionGroup.checkedRadioButtonId) {
R.id.shareViaLinkEditPermissionUploadFiles -> {
publicLinkPermissions = RemoteShare.CREATE_PERMISSION_FLAG
publicUploadPermission = true
}
R.id.shareViaLinkEditPermissionReadAndWrite -> {
publicLinkPermissions = (RemoteShare.CREATE_PERMISSION_FLAG
or RemoteShare.DELETE_PERMISSION_FLAG
or RemoteShare.UPDATE_PERMISSION_FLAG
or RemoteShare.READ_PERMISSION_FLAG)
publicUploadPermission = true
}
R.id.shareViaLinkEditPermissionReadOnly -> {
publicLinkPermissions = RemoteShare.READ_PERMISSION_FLAG
publicUploadPermission = false
}
else -> {
publicLinkPermissions = RemoteShare.READ_PERMISSION_FLAG
publicUploadPermission = false
}
}
if (!updating()) { // Creating a new public share
ocShareViewModel.insertPublicShare(
file?.remotePath!!,
publicLinkPermissions,
publicLinkName,
publicLinkPassword!!,
publicLinkExpirationDateInMillis,
false,
account?.name!!
)
} else { // Updating an existing public share
if (!binding.shareViaLinkPasswordSwitch.isChecked) {
publicLinkPassword = ""
} else if (binding.shareViaLinkPasswordValue.text.isEmpty()) {
// User has not added a new password, so do not update it
publicLinkPassword = null
}
ocShareViewModel.updatePublicShare(
publicShare?.remoteId!!,
publicLinkName,
publicLinkPassword,
publicLinkExpirationDateInMillis,
publicLinkPermissions,
publicUploadPermission,
account?.name!!
)
}
}
private fun initPasswordFocusChangeListener() {
binding.shareViaLinkPasswordValue.setOnFocusChangeListener { v: View, hasFocus: Boolean ->
if (v.id == R.id.shareViaLinkPasswordValue) {
onPasswordFocusChanged(hasFocus)
}
}
}
private fun initPasswordToggleListener() {
binding.shareViaLinkPasswordValue.setOnTouchListener(object : RightDrawableOnTouchListener() {
override fun onDrawableTouch(event: MotionEvent): Boolean {
if (event.action == MotionEvent.ACTION_UP) {
onViewPasswordClick()
}
return true
}
})
}
private abstract class RightDrawableOnTouchListener : View.OnTouchListener {
private val fuzz = 75
/**
* {@inheritDoc}
*/
override fun onTouch(view: View, event: MotionEvent): Boolean {
var rightDrawable: Drawable? = null
if (view is TextView) {
val drawables = view.compoundDrawables
if (drawables.size > 2) {
rightDrawable = drawables[2]
}
}
if (rightDrawable != null) {
val x = event.x.toInt()
val y = event.y.toInt()
val bounds = rightDrawable.bounds
if (x >= view.right - bounds.width() - fuzz &&
x <= view.right - view.paddingRight + fuzz &&
y >= view.paddingTop - fuzz &&
y <= view.height - view.paddingBottom + fuzz
) {
return onDrawableTouch(event)
}
}
return false
}
abstract fun onDrawableTouch(event: MotionEvent): Boolean
}
/**
* Handles changes in focus on the text input for the password (basic authorization).
* When (hasFocus), the button to toggle password visibility is shown.
* When (!hasFocus), the button is made invisible and the password is hidden.
*
* @param hasFocus 'True' if focus is received, 'false' if is lost
*/
private fun onPasswordFocusChanged(hasFocus: Boolean) {
if (hasFocus) {
showViewPasswordButton()
} else {
hidePassword()
hidePasswordButton()
}
}
/**
* Called when the eye icon in the password field is clicked.
*
* Toggles the visibility of the password in the field.
*/
fun onViewPasswordClick() {
if (view != null) {
if (isPasswordVisible) {
hidePassword()
} else {
showPassword()
}
binding.shareViaLinkPasswordValue.setSelection(
binding.shareViaLinkPasswordValue.selectionStart,
binding.shareViaLinkPasswordValue.selectionEnd
)
}
}
private fun showViewPasswordButton() {
val drawable = if (isPasswordVisible)
R.drawable.ic_view_black
else
R.drawable.ic_hide_black
binding.shareViaLinkPasswordValue.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable, 0)
}
private fun hidePasswordButton() {
binding.shareViaLinkPasswordValue.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0)
}
private fun showPassword() {
binding.shareViaLinkPasswordValue.inputType = InputType.TYPE_CLASS_TEXT or
InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD or
InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
showViewPasswordButton()
}
private fun hidePassword() {
binding.shareViaLinkPasswordValue.inputType = InputType.TYPE_CLASS_TEXT or
InputType.TYPE_TEXT_VARIATION_PASSWORD or
InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
showViewPasswordButton()
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
observeCapabilities()
observePublicShareCreation()
observePublicShareEdition()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(KEY_EXPIRATION_DATE, binding.shareViaLinkExpirationValue.text.toString())
}
override fun onAttach(context: Context) {
super.onAttach(context)
try {
listener = activity as ShareFragmentListener?
} catch (e: IllegalStateException) {
throw IllegalStateException(activity?.toString() + " must implement OnShareFragmentInteractionListener")
}
}
override fun onDetach() {
super.onDetach()
listener = null
}
private fun observeCapabilities() {
ocCapabilityViewModel.capabilities.observe(this) { event ->
when (val uiResult = event.peekContent()) {
is UIResult.Success -> {
updateCapabilities(uiResult.data)
listener?.dismissLoading()
}
is UIResult.Error -> {
}
is UIResult.Loading -> {
}
}
}
}
private fun observePublicShareCreation() {
ocShareViewModel.publicShareCreationStatus.observe(
this,
EventObserver { uiResult ->
when (uiResult) {
is UIResult.Success -> {
dismiss()
}
is UIResult.Error -> {
showError(getString(R.string.share_link_file_error), uiResult.error)
listener?.dismissLoading()
}
is UIResult.Loading -> {
listener?.showLoading()
}
}
}
)
}
private fun observePublicShareEdition() {
ocShareViewModel.publicShareEditionStatus.observe(
this,
EventObserver { uiResult ->
when (uiResult) {
is UIResult.Success -> {
dismiss()
}
is UIResult.Error -> {
showError(getString(R.string.update_link_file_error), uiResult.error)
listener?.dismissLoading()
}
is UIResult.Loading -> {
listener?.showLoading()
}
}
}
)
}
/**
* Binds listener for user actions that start any update on a password for the public link
* to the views receiving the user events.
*
*/
private fun initPasswordListener() {
onPasswordInteractionListener = OnPasswordInteractionListener()
binding.shareViaLinkPasswordSwitch.setOnCheckedChangeListener(onPasswordInteractionListener)
}
/**
* Listener for user actions that start any update on a password for the public link.
*/
private inner class OnPasswordInteractionListener : CompoundButton.OnCheckedChangeListener {
/**
* Called by R.id.shareViaLinkPasswordSwitch to set or clear the password.
*
* @param switchView [SwitchCompat] toggled by the user, R.id.shareViaLinkPasswordSwitch
* @param isChecked New switch state.
*/
override fun onCheckedChanged(switchView: CompoundButton, isChecked: Boolean) {
if (isChecked) {
binding.shareViaLinkPasswordValue.isVisible = true
binding.shareViaLinkPasswordValue.requestFocus()
// Show keyboard to fill in the password
val mgr = activity?.getSystemService(
Context.INPUT_METHOD_SERVICE
) as InputMethodManager?
mgr?.showSoftInput(binding.shareViaLinkPasswordValue, InputMethodManager.SHOW_IMPLICIT)
} else {
binding.shareViaLinkPasswordValue.isVisible = false
binding.shareViaLinkPasswordValue.text?.clear()
}
}
}
/**
* Binds listener for user actions that start any update on a expiration date
* for the public link to the views receiving the user events.
*
*/
private fun initExpirationListener() {
onExpirationDateInteractionListener = OnExpirationDateInteractionListener()
binding.shareViaLinkExpirationSwitch.setOnCheckedChangeListener(onExpirationDateInteractionListener)
binding.shareViaLinkExpirationLabel.setOnClickListener(onExpirationDateInteractionListener)
binding.shareViaLinkExpirationValue.setOnClickListener(onExpirationDateInteractionListener)
}
/**
* Listener for user actions that start any update on the expiration date for the public link.
*/
private inner class OnExpirationDateInteractionListener : CompoundButton.OnCheckedChangeListener,
View.OnClickListener, ExpirationDatePickerDialogFragment.DatePickerFragmentListener {
/**
* Called by R.id.shareViaLinkExpirationSwitch to set or clear the expiration date.
*
* @param switchView [SwitchCompat] toggled by the user, R.id.shareViaLinkExpirationSwitch
* @param isChecked New switch state.
*/
override fun onCheckedChanged(switchView: CompoundButton, isChecked: Boolean) {
if (!isResumed) {
// very important, setCheched(...) is called automatically during
// Fragment recreation on device rotations
return
}
if (isChecked) {
// Show calendar to set the expiration date
val dialog = ExpirationDatePickerDialogFragment.newInstance(
expirationDateValueInMillis,
imposedExpirationDate
)
dialog.setDatePickerListener(this)
dialog.show(
requireActivity().supportFragmentManager,
ExpirationDatePickerDialogFragment.DATE_PICKER_DIALOG
)
} else {
binding.shareViaLinkExpirationValue.visibility = View.INVISIBLE
binding.shareViaLinkExpirationValue.text = ""
}
}
/**
* Called by R.id.shareViaLinkExpirationLabel or R.id.shareViaLinkExpirationValue
* to change the current expiration date.
*
* @param expirationView Label or value view touched by the user.
*/
override fun onClick(expirationView: View) {
// Show calendar to set the expiration date
val dialog = ExpirationDatePickerDialogFragment.newInstance(
expirationDateValueInMillis,
imposedExpirationDate
)
dialog.setDatePickerListener(this)
dialog.show(
requireActivity().supportFragmentManager,
ExpirationDatePickerDialogFragment.DATE_PICKER_DIALOG
)
}
/**
* Update the selected date for the public link
*
* @param date date selected by the user
*/
override fun onDateSet(date: String) {
binding.shareViaLinkExpirationValue.isVisible = true
binding.shareViaLinkExpirationValue.text = date
}
override fun onCancelDatePicker() {
// If the date has not been set yet, uncheck the toggle
if (binding.shareViaLinkExpirationSwitch.isChecked && binding.shareViaLinkExpirationValue.text.isNullOrBlank()) {
binding.shareViaLinkExpirationSwitch.isChecked = false
}
}
}
private fun updateCapabilities(capabilities: OCCapability?) {
this.capabilities = capabilities
updateInputFormAccordingToServerCapabilities()
}
/**
* Updates the UI according to enforcements and allowances set by the server administrator.
*
* Includes:
* - hide the link name section if multiple public share is not supported, showing the keyboard
* to fill in the public share name otherwise
* - hide show file listing option
* - hide or show the switch to disable the password if it is enforced or not;
* - hide or show the switch to disable the expiration date it it is enforced or not;
* - show or hide the switch to allow public uploads if it is allowed or not;
* - set the default value for expiration date if defined (only if creating a new share).
*/
private fun updateInputFormAccordingToServerCapabilities() {
val serverVersion = capabilities?.versionString?.let {
OwnCloudVersion(it)
}
// Show keyboard to fill the public share name
dialog?.window?.setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE or WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
)
if (capabilities?.filesSharingPublicUpload == CapabilityBooleanType.TRUE && isSharedFolder) {
binding.shareViaLinkEditPermissionGroup.isVisible = true
}
// Show file listing option if all the following is true:
// - The file to share is a folder
// - Upload only is supported by the server version
// - Upload only capability is set
// - Allow editing capability is set
if (!(isSharedFolder &&
serverVersion?.isPublicSharingWriteOnlySupported == true &&
capabilities?.filesSharingPublicSupportsUploadOnly == CapabilityBooleanType.TRUE &&
capabilities?.filesSharingPublicUpload == CapabilityBooleanType.TRUE)
) {
binding.shareViaLinkEditPermissionGroup.isVisible = false
}
// Show default date enforced by the server, if any
if (!updating() && capabilities?.filesSharingPublicExpireDateDays ?: 0 > 0) {
setExpirationDateSwitchChecked()
val formattedDate = SimpleDateFormat.getDateInstance().format(
DateUtils.addDaysToDate(
Date(),
capabilities?.filesSharingPublicExpireDateDays!!
)
)
binding.shareViaLinkExpirationValue.apply {
isVisible = true
text = formattedDate
}
}
// Hide expiration date switch if date is enforced to prevent it is removed
if (capabilities?.filesSharingPublicExpireDateEnforced == CapabilityBooleanType.TRUE) {
binding.shareViaLinkExpirationLabel.text = getString(R.string.share_via_link_expiration_date_enforced_label)
binding.shareViaLinkExpirationSwitch.isVisible = false
binding.shareViaLinkExpirationExplanationLabel.isVisible = true
binding.shareViaLinkExpirationExplanationLabel.text = getString(
R.string.share_via_link_expiration_date_explanation_label,
capabilities?.filesSharingPublicExpireDateDays
)
}
// Set password label when opening the dialog
if (binding.shareViaLinkEditPermissionReadOnly.isChecked &&
capabilities?.filesSharingPublicPasswordEnforcedReadOnly == CapabilityBooleanType.TRUE ||
binding.shareViaLinkEditPermissionReadAndWrite.isChecked &&
capabilities?.filesSharingPublicPasswordEnforcedReadWrite == CapabilityBooleanType.TRUE ||
binding.shareViaLinkEditPermissionUploadFiles.isChecked &&
capabilities?.filesSharingPublicPasswordEnforcedUploadOnly == CapabilityBooleanType.TRUE
) {
setPasswordEnforced()
}
// Set password label depending on the checked permission option
binding.shareViaLinkEditPermissionGroup.setOnCheckedChangeListener { _, checkedId ->
binding.publicLinkErrorMessage.isVisible = false
if (checkedId == binding.shareViaLinkEditPermissionReadOnly.id) {
if (capabilities?.filesSharingPublicPasswordEnforcedReadOnly == CapabilityBooleanType.TRUE) {
setPasswordEnforced()
} else {
setPasswordNotEnforced()
}
} else if (checkedId == binding.shareViaLinkEditPermissionReadAndWrite.id) {
if (capabilities?.filesSharingPublicPasswordEnforcedReadWrite == CapabilityBooleanType.TRUE) {
setPasswordEnforced()
} else {
setPasswordNotEnforced()
}
} else if (checkedId == binding.shareViaLinkEditPermissionUploadFiles.id) {
if (capabilities?.filesSharingPublicPasswordEnforcedUploadOnly == CapabilityBooleanType.TRUE) {
setPasswordEnforced()
} else {
setPasswordNotEnforced()
}
}
}
// When there's no password enforced for capability
val hasPasswordEnforcedFor = capabilities?.filesSharingPublicPasswordEnforcedReadOnly ==
CapabilityBooleanType.TRUE ||
capabilities?.filesSharingPublicPasswordEnforcedReadWrite == CapabilityBooleanType.TRUE ||
capabilities?.filesSharingPublicPasswordEnforcedUploadOnly == CapabilityBooleanType.TRUE
// hide password switch if password is enforced to prevent it is removed
if (!hasPasswordEnforcedFor && capabilities?.filesSharingPublicPasswordEnforced == CapabilityBooleanType.TRUE) {
setPasswordEnforced()
}
}
private fun setPasswordNotEnforced() {
binding.shareViaLinkPasswordLabel.text = getString(R.string.share_via_link_password_label)
binding.shareViaLinkPasswordSwitch.isVisible = true
if (!binding.shareViaLinkPasswordSwitch.isChecked) {
binding.shareViaLinkPasswordValue.isVisible = false
}
}
private fun setPasswordEnforced() {
binding.shareViaLinkPasswordLabel.text = getString(R.string.share_via_link_password_enforced_label)
binding.shareViaLinkPasswordSwitch.isChecked = true
binding.shareViaLinkPasswordSwitch.isVisible = false
binding.shareViaLinkPasswordValue.isVisible = true
}
/**
* Show error when creating or updating the public share, if any
*/
private fun showError(genericErrorMessage: String, throwable: Throwable?) {
binding.publicLinkErrorMessage.text = throwable?.parseError(genericErrorMessage, resources)
binding.publicLinkErrorMessage.isVisible = true
}
private fun setPasswordSwitchChecked() {
binding.shareViaLinkPasswordSwitch.apply {
setOnCheckedChangeListener(null)
isChecked = true
setOnCheckedChangeListener(onPasswordInteractionListener)
}
}
private fun setExpirationDateSwitchChecked() {
binding.shareViaLinkExpirationSwitch.setOnCheckedChangeListener(null)
binding.shareViaLinkExpirationSwitch.isChecked = true
binding.shareViaLinkExpirationSwitch.setOnCheckedChangeListener(onExpirationDateInteractionListener)
}
companion object {
/**
* The fragment initialization parameters
*/
private const val ARG_FILE = "FILE"
private const val ARG_SHARE = "SHARE"
private const val ARG_ACCOUNT = "ACCOUNT"
private const val ARG_DEFAULT_LINK_NAME = "DEFAULT_LINK_NAME"
private const val KEY_EXPIRATION_DATE = "EXPIRATION_DATE"
/**
* Create a new instance of PublicShareDialogFragment, providing fileToShare as an argument.
*
* Dialog shown this way is intended to CREATE a new public share.
*
* @param fileToShare File to share with a new public share.
*/
fun newInstanceToCreate(
fileToShare: OCFile,
account: Account,
defaultLinkName: String
): PublicShareDialogFragment {
val args = Bundle().apply {
putParcelable(ARG_FILE, fileToShare)
putParcelable(ARG_ACCOUNT, account)
putString(ARG_DEFAULT_LINK_NAME, defaultLinkName)
}
return PublicShareDialogFragment().apply { arguments = args }
}
/**
* Update an instance of PublicShareDialogFragment, providing fileToShare, publicShare as arguments.
*
* Dialog shown this way is intended to UPDATE an existing public share.
*
* @param publicShare Public share to update.
*/
fun newInstanceToUpdate(
fileToShare: OCFile,
account: Account,
publicShare: OCShare
): PublicShareDialogFragment {
val args = Bundle().apply {
putParcelable(ARG_FILE, fileToShare)
putParcelable(ARG_ACCOUNT, account)
putParcelable(ARG_SHARE, publicShare)
}
return PublicShareDialogFragment().apply { arguments = args }
}
}
}
| gpl-2.0 | ad6eec68f163131ebb93ccbef91e5573 | 38.264354 | 125 | 0.633024 | 5.465368 | false | false | false | false |
erokhins/KotlinCV | Common/src/org/hanuna/kotlincv/Sizes.kt | 1 | 943 | package org.hanuna.kotlincv
/**
* Created by smevok on 5/11/14.
*/
public trait OneDimensionObject {
public val size: Int
}
public fun OneDimensionObject.forAll(f: (Int) -> Unit) {
for (index in 0..size-1)
f(index)
}
public trait Coordinates {
val col: Int
val row: Int
}
public class SimpleCoordinates(override val col: Int, override val row: Int) : Coordinates
public trait TwoDimensionObject {
public val cols: Int
public val rows: Int
}
public fun TwoDimensionObject.forAll(colRange: IntRange = 0..cols-1, rowRange: IntRange = 0..rows-1, f: (Coordinates) -> Unit) {
for (col in colRange)
for (row in rowRange)
f(SimpleCoordinates(col, row))
}
public fun OneDimensionObject.equalSize(other: OneDimensionObject): Boolean = this.size == other.size
public fun TwoDimensionObject.equalSize(other: TwoDimensionObject): Boolean = this.cols == other.cols && this.rows == other.rows | apache-2.0 | 96f2107376406524e49f64dbaf48c6a2 | 25.971429 | 128 | 0.699894 | 3.492593 | false | false | false | false |
Senspark/ee-x | src/android/adjust/src/main/java/com/ee/AdjustBridge.kt | 1 | 4654 | package com.ee
import android.app.Activity
import android.app.Application
import androidx.annotation.AnyThread
import com.adjust.sdk.Adjust
import com.adjust.sdk.AdjustConfig
import com.adjust.sdk.AdjustEvent
import com.adjust.sdk.LogLevel
import com.ee.internal.deserialize
import kotlinx.serialization.Serializable
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
class AdjustBridge(
private val _bridge: IMessageBridge,
private val _logger: ILogger,
private val _application: Application,
private var _activity: Activity?) : IPlugin {
companion object {
private val kTag = AdjustBridge::class.java.name
private const val kPrefix = "AdjustBridge"
private const val kInitialize = "${kPrefix}Initialize"
private const val kSetEnabled = "${kPrefix}SetEnabled"
private const val kGetAdvertisingIdentifier = "${kPrefix}GetAdvertisingIdentifier"
private const val kGetDeviceIdentifier = "${kPrefix}GetDeviceIdentifier"
private const val kSetPushToken = "${kPrefix}SetPushToken"
private const val kTrackEvent = "${kPrefix}TrackEvent"
}
init {
_logger.info("$kTag: constructor begin: application = $_application activity = $_activity")
registerHandlers()
_logger.info("$kTag: constructor end")
}
override fun onCreate(activity: Activity) {
_activity = activity
}
override fun onStart() {}
override fun onStop() {}
override fun onResume() {
Adjust.onResume()
}
override fun onPause() {
Adjust.onPause()
}
override fun onDestroy() {
_activity = null
}
override fun destroy() {
deregisterHandlers()
}
@Serializable
private class InitializeRequest(
val token: String,
val environment: Int,
val logLevel: Int,
val eventBufferingEnabled: Boolean,
)
@AnyThread
private fun registerHandlers() {
_bridge.registerHandler(kInitialize) { message ->
val request = deserialize<InitializeRequest>(message)
initialize(request.token, parseEnvironment(request.environment),
parseLogLevel(request.logLevel), request.eventBufferingEnabled)
""
}
_bridge.registerHandler(kSetEnabled) { message ->
setEnabled(Utils.toBoolean(message))
""
}
_bridge.registerAsyncHandler(kGetAdvertisingIdentifier) {
suspendCoroutine { cont ->
Adjust.getGoogleAdId(_application) { googleAdId ->
cont.resume(googleAdId ?: "")
}
}
}
_bridge.registerHandler(kGetDeviceIdentifier) {
Adjust.getAdid()
}
_bridge.registerHandler(kSetPushToken) { message ->
Adjust.setPushToken(message, _application)
""
}
_bridge.registerHandler(kTrackEvent) { message ->
trackEvent(message)
""
}
}
@AnyThread
private fun deregisterHandlers() {
_bridge.deregisterHandler(kInitialize)
_bridge.deregisterHandler(kSetEnabled)
_bridge.deregisterHandler(kGetAdvertisingIdentifier)
_bridge.deregisterHandler(kGetDeviceIdentifier)
_bridge.deregisterHandler(kSetPushToken)
_bridge.deregisterHandler(kTrackEvent)
}
@AnyThread
fun parseEnvironment(environment: Int): String {
if (environment == 0) {
return AdjustConfig.ENVIRONMENT_SANDBOX
}
if (environment == 1) {
return AdjustConfig.ENVIRONMENT_PRODUCTION
}
return ""
}
@AnyThread
fun parseLogLevel(logLevel: Int): LogLevel {
val dict = mapOf(
0 to LogLevel.VERBOSE,
1 to LogLevel.DEBUG,
2 to LogLevel.INFO,
3 to LogLevel.WARN,
4 to LogLevel.ERROR,
5 to LogLevel.ASSERT,
6 to LogLevel.SUPRESS
)
return dict[logLevel] ?: LogLevel.VERBOSE
}
@AnyThread
fun initialize(token: String, environment: String,
logLevel: LogLevel, eventBufferingEnabled: Boolean) {
val config = AdjustConfig(_application, token, environment)
config.setLogLevel(logLevel)
config.setEventBufferingEnabled(eventBufferingEnabled)
Adjust.onCreate(config)
}
@AnyThread
fun setEnabled(enabled: Boolean) {
Adjust.setEnabled(enabled)
}
@AnyThread
fun trackEvent(token: String) {
val event = AdjustEvent(token)
Adjust.trackEvent(event)
}
} | mit | ebc8673b6f5c1cbe957cb51cbd0aafaa | 29.227273 | 99 | 0.632144 | 4.888655 | false | true | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/ide/refactoring/ConvertToNamedFieldsRefactoringTest.kt | 3 | 5206 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.refactoring
import org.intellij.lang.annotations.Language
import org.rust.RsTestBase
import org.rust.launchAction
class ConvertToNamedFieldsRefactoringTest : RsTestBase() {
fun `test simple`() = doAvailableTest("""
struct Test (pub usize,/*caret*/ i32);
""", """
struct Test {
pub _0: usize,
_1: i32,
}
""")
fun `test empty`() = doAvailableTest("""
struct Test (/*caret*/);
""", """
struct Test {}
""")
fun `test simple enum`() = doAvailableTest("""
enum Test{
A(usize,/*caret*/ i32),
B
}
fn main(){
let Test::A(a, b) = Test::A(0, 0);
}
""", """
enum Test{
A { _0: usize, _1: i32 },
B
}
fn main(){
let Test::A { _0: a, _1: b } = Test::A {
_0: 0,
_1: 0
};
}
""")
fun `test convert tuple literal`() = doAvailableTest("""
struct Test(pub usize,/*caret*/ i32);
fn main (){
let a = Test(0, 0);
let Test{0: a, 1: b}= Test{0: 0, 1: 0};
}
""", """
struct Test {
pub _0: usize,
_1: i32,
}
fn main (){
let a = Test {
_0: 0,
_1: 0
};
let Test{ _0: a, _1: b}= Test{ _0: 0, _1: 0};
}
""")
fun `test convert field access`() = doAvailableTest("""
struct Test(pub usize,/*caret*/ i32);
fn main (){
let var = Test(0, 0);
let x = var.0;
let x = var.1;
}
""", """
struct Test {
pub _0: usize,
_1: i32,
}
fn main (){
let var = Test {
_0: 0,
_1: 0
};
let x = var._0;
let x = var._1;
}
""")
fun `test convert destructuring`() = doAvailableTest("""
struct Test(pub usize,/*caret*/ i32);
fn main (){
let var = Test(0, 0);
let Test(a, b) = &var;
let Test(ref a, mut b) = &var;
let Test(a, _) = &var;
let Test(a, ..) = &var;
let Test(.. ,b) = &var;
let Test(_, b) = &var;
}
""", """
struct Test {
pub _0: usize,
_1: i32,
}
fn main (){
let var = Test {
_0: 0,
_1: 0
};
let Test { _0: a, _1: b } = &var;
let Test { _0: ref a, _1: mut b } = &var;
let Test { _0: a, _1: _ } = &var;
let Test { _0: a, .. } = &var;
let Test { _1: b, .. } = &var;
let Test { _0: _, _1: b } = &var;
}
""")
// https://github.com/intellij-rust/intellij-rust/issues/5017
fun `test convert function call`() = doAvailableTest("""
struct S(/*caret*/u32);
impl S {
fn new(v: u32) -> S {
S(v)
}
}
fn main() {
let s = S::new(0);
}
""", """
struct S {
_0: u32,
}
impl S {
fn new(v: u32) -> S {
S { _0: v }
}
}
fn main() {
let s = S::new(0);
}
""")
fun `test convert function call in mod`() = doAvailableTest("""
mod nested {
pub struct S(/*caret*/pub u32);
impl S {
pub fn new(v: u32) -> S {
S(v)
}
}
}
fn main() {
let s1 = nested::S(1);
let s2 = nested::S::new(0);
}
""", """
mod nested {
pub struct S {
pub _0: u32,
}
impl S {
pub fn new(v: u32) -> S {
S { _0: v }
}
}
}
fn main() {
let s1 = nested::S { _0: 1 };
let s2 = nested::S::new(0);
}
""")
fun `test where clause`() = doAvailableTest("""
trait Trait {}
struct Test/*caret*/<T>(T) where T: Trait ;
""", """
trait Trait {}
struct Test<T> where T: Trait {
_0: T,
}
""")
fun `test where clause (multiline)`() = doAvailableTest("""
trait Trait {}
struct Test/*caret*/<T1, T2>(T1, T2)
where
T1: Trait,
T2: Trait;
""", """
trait Trait {}
struct Test<T1, T2>
where
T1: Trait,
T2: Trait
{
_0: T1,
_1: T2,
}
""")
private fun doAvailableTest(@Language("Rust") before: String, @Language("Rust") after: String) {
InlineFile(before.trimIndent()).withCaret()
myFixture.launchAction("Rust.RsConvertToNamedFields")
myFixture.checkResult(replaceCaretMarker(after.trimIndent()))
}
}
| mit | 73b948523d31a89b3357f7c3369dadf6 | 22.771689 | 100 | 0.37476 | 3.929057 | false | true | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/ide/intentions/ReplaceBlockCommentWithLineCommentIntentionTest.kt | 3 | 1606 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
class ReplaceBlockCommentWithLineCommentIntentionTest : RsIntentionTestBase(ReplaceBlockCommentWithLineCommentIntention::class) {
fun `test convert single block comment`() = doAvailableTest("""
/* /*caret*/Hello, World! */
""", """
/*caret*/// Hello, World!
""")
fun `test convert multiline block comment`() = doAvailableTest("""
/*
First
/*caret*/Second
Third
*/
""", """
/*caret*/// First
// Second
// Third
""")
fun `test convert multiline block comment with spaces`() = doAvailableTest("""
/*
First
Second/*caret*/ Third
*/
""", """
// First
//
//
// Second Third
""")
fun `test convert multiline block comment with indent`() = doAvailableTest("""
fn foo() {
/*
First
Second/*caret*/
*/
let x = 1;
}
""", """
fn foo() {
/*caret*/// First
// Second
let x = 1;
}
""")
fun `test convert multiple line comments with indent members`() = doAvailableTest("""
trait Foo {
/*
First
Second/*caret*/
*/
fn foo() {}
}
""", """
trait Foo {
/*caret*/// First
// Second
fn foo() {}
}
""")
}
| mit | 2200f60f949f87492d44beea2d1755ee | 21 | 129 | 0.449564 | 5.23127 | false | true | false | false |
Grisu118/csvExporter | src/test/kotlin/ch/grisu118/csv/CSVTest.kt | 1 | 4639 | package ch.grisu118.csv
import org.hamcrest.CoreMatchers.equalTo
import org.junit.Assert.assertThat
import org.junit.Before
import org.junit.Test
class CSVTest {
@Before
fun setUp() {
CSVKonfig.SEPARATOR = Separator.COMMA
CSVKonfig.CONVERTER.clear()
}
@Test
fun testSimple() {
assertThat(CSV.generate(listOf(TestObject(2L))).toString(),
equalTo(CSVBuilder(Separator.COMMA)
.newLine("id", "prop", "string")
.newLine("2", "Hello World", "Hello World")
.build()
))
}
@Test
fun testPrivateFieldAndPropterty() {
assertThat(listOf(PrivateObject("123541", "HH")).asCSV().toString(),
equalTo(CSVBuilder(Separator.COMMA)
.newLine("Kode", "Combined")
.newLine("123541", "HH-123541")
.build()
))
}
@Test
fun testPrefix() {
val obj = ObjectWithChilds(PrivateObject("123", "CH"), TestObject(321L))
assertThat(listOf(obj).asCSV().toString(),
equalTo(CSVBuilder(Separator.COMMA)
.newLine("pOKode", "pOCombined", "tOid", "tOprop", "tOstring")
.newLine("123", "CH-123", "321", "Hello World", "Hello World")
.build()
))
}
@Test
fun testOptionalHeader() {
class OptionalObj(@CSVField private val loremIpsum: String)
assertThat(listOf(OptionalObj("junitTest")).asCSV().toString(),
equalTo(CSVBuilder(Separator.COMMA)
.newLine("loremIpsum")
.newLine("junitTest")
.build()
))
}
@Test
fun testOtherSeparator() {
CSVKonfig.SEPARATOR = Separator.SEMICOLON
val obj = ObjectWithChilds(PrivateObject("123", "CH"), TestObject(321L))
assertThat(listOf(obj).asCSV().toString(),
equalTo(CSVBuilder(Separator.SEMICOLON)
.newLine("pOKode", "pOCombined", "tOid", "tOprop", "tOstring")
.newLine("123", "CH-123", "321", "Hello World", "Hello World")
.build()
))
}
@Test
fun testBooleanTransform() {
class BooleanObject(@CSVField private val loremIpsum: Boolean)
CSVKonfig.CONVERTER[Boolean::class] = {
if (it as Boolean) "Yes" else "No"
}
assertThat(listOf(BooleanObject(true), BooleanObject(false)).asCSV().toString(),
equalTo(CSVBuilder(Separator.COMMA)
.newLine("loremIpsum")
.newLine("Yes")
.newLine("No")
.build()
))
}
@Test
fun testArrayUseToString() {
class ArrayObject(@CSVField val array: IntArray)
val a = intArrayOf(1, 2, 42, 118)
assertThat(listOf(ArrayObject(a)).asCSV().toString(),
equalTo(CSVBuilder()
.newLine("array")
.newLine(a.toString())
.build()
))
}
@Test
fun testQuotationEscape() {
class SimpleObj(@CSVField(header = "Field With \"") private val someString: String)
assertThat(listOf(SimpleObj("Hello\" dude\"\" :)")).asCSV().toString(),
equalTo(CSVBuilder(Separator.COMMA)
.newLine("Field With \"\"")
.newLine("Hello\"\" dude\"\"\"\" :)")
.build()
))
}
@Test
fun testEnum() {
class SimpleObj(@CSVField private val enum: TestEnum)
assertThat(listOf(SimpleObj(TestEnum.VALUE)).asCSV().toString(),
equalTo(CSVBuilder(Separator.COMMA)
.newLine("enum")
.newLine("VALUE")
.build()
))
}
@Test
fun testEmptyRowsAnyWhere() {
data class Obj(@CSVField private val field: Int?)
assertThat(listOf(
Obj(1),
Obj(2),
Obj(null),
Obj(4)
).asCSV().toString(),
equalTo(CSVBuilder(Separator.COMMA)
.newLine("field")
.newLine("1")
.newLine("2")
.newLine("")
.newLine("4")
.build()))
}
@Test
fun testStartWithEmptyRows() {
data class Obj(@CSVField private val field: Int?)
assertThat(listOf(
Obj(null),
Obj(null),
Obj(1),
Obj(2)
).asCSV().toString(),
equalTo(CSVBuilder(Separator.COMMA)
.newLine("field")
.newLine("")
.newLine("")
.newLine("1")
.newLine("2")
.build()))
}
class PrivateObject(@CSVField("Kode") private val code: String, private val prefix: String) {
private val combined
@CSVField(header = "Combined")
get() = "$prefix-$code"
}
class TestObject(@field:CSVField("id", 1) val id: Long) {
@field:CSVField("string", 3)
val string = "Hello World"
@get:CSVField("prop", 2)
val prop
get() = string
}
class ObjectWithChilds(@CSVField("pObject", prefix = "pO") val privateObject: PrivateObject, @CSVField("testObj",
prefix = "tO") val testObject: TestObject)
enum class TestEnum {
VALUE,
KEY
}
}
| mit | 125dfdbf293a5cf696d2040d702694ae | 23.807487 | 115 | 0.599052 | 3.747173 | false | true | false | false |
eyesniper2/skRayFall | src/main/java/net/rayfall/eyesniper2/skrayfall/effectlibsupport/EffEffectTornado.kt | 1 | 3675 | package net.rayfall.eyesniper2.skrayfall.effectlibsupport
import ch.njol.skript.Skript
import ch.njol.skript.doc.Description
import ch.njol.skript.doc.Name
import ch.njol.skript.lang.Effect
import ch.njol.skript.lang.Expression
import ch.njol.skript.lang.SkriptParser
import ch.njol.skript.util.VisualEffect
import ch.njol.util.Kleenean
import de.slikey.effectlib.effect.TornadoEffect
import de.slikey.effectlib.effect.WaveEffect
import de.slikey.effectlib.util.DynamicLocation
import net.rayfall.eyesniper2.skrayfall.Core
import org.bukkit.Location
import org.bukkit.Particle
import org.bukkit.entity.Entity
import org.bukkit.event.Event
@Name("Tornado Effect")
@Description("Creates an EffectLib tornado effect.")
class EffEffectTornado : Effect() {
// (spawn|create|apply) (a|the|an) tornado (effect|formation) at %entity/location% with id
// %string% [with tornado particle[s] %visualeffects% and cloud particle[s]
// %visualeffects%] [(set|and) radius %number%] [(set|and) max height %number%]
private var targetExpression: Expression<*>? = null
private var idExpression: Expression<String>? = null
private var tornadoParticleExpression: Expression<VisualEffect>? = null
private var cloudParticleExpression: Expression<VisualEffect>? = null
private var radiusExpression: Expression<Number?>? = null
private var heightExpression: Expression<Number?>? = null
@Suppress("UNCHECKED_CAST")
override fun init(exp: Array<Expression<*>?>, arg1: Int, arg2: Kleenean, arg3: SkriptParser.ParseResult): Boolean {
targetExpression = exp[0]
idExpression = exp[1] as Expression<String>?
tornadoParticleExpression = exp[2] as? Expression<VisualEffect>?
cloudParticleExpression = exp[3] as? Expression<VisualEffect>?
radiusExpression = exp[4] as Expression<Number?>?
heightExpression = exp[5] as Expression<Number?>?
return true
}
override fun toString(evt: Event?, arg1: Boolean): String {
return ""
}
override fun execute(evt: Event) {
val target = targetExpression?.getSingle(evt)
val id = idExpression?.getSingle(evt)
val tornadoParticle = EffectLibUtils.getParticleFromVisualEffect(tornadoParticleExpression?.getSingle(evt))
val cloudParticle = EffectLibUtils.getParticleFromVisualEffect(cloudParticleExpression?.getSingle(evt))
val radius = radiusExpression?.getSingle(evt)
val height = heightExpression?.getSingle(evt)
val baseEffect = TornadoEffect(Core.effectManager)
if (id == null)
{
Skript.warning("Id was null for EffectLib Tornado")
return
}
when (target) {
is Entity -> {
baseEffect.setDynamicOrigin(DynamicLocation(target as Entity?))
}
is Location -> {
baseEffect.setDynamicOrigin(DynamicLocation(target as Location?))
}
else -> {
assert(false)
}
}
if (tornadoParticle != null) {
baseEffect.tornadoParticle = tornadoParticle
}
if (cloudParticle != null) {
baseEffect.cloudParticle = cloudParticle
}
if (height != null) {
baseEffect.tornadoHeight = height.toFloat()
}
if (radius != null) {
baseEffect.maxTornadoRadius = radius.toFloat()
}
baseEffect.infinite()
baseEffect.start()
val setEffectSuccess = Core.rayfallEffectManager.setEffect(baseEffect, id.replace("\"", ""))
if (!setEffectSuccess) {
baseEffect.cancel()
}
}
} | gpl-3.0 | c5e5944a382b7d6cc9bfd7056456b94d | 35.039216 | 119 | 0.669388 | 4.21445 | false | false | false | false |
androidx/androidx | health/health-services-client/src/main/java/androidx/health/services/client/data/DataTypeCondition.kt | 3 | 3356 | /*
* Copyright (C) 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.
*/
package androidx.health.services.client.data
import androidx.health.services.client.proto.DataProto
/** A condition which is considered met when a data type value passes a defined threshold. */
@Suppress("ParcelCreator")
public class DataTypeCondition<T : Number, D : DataType<T, out DataPoint<T>>>(
/** [DataType] which this condition applies to. */
public val dataType: D,
/** The threshold at which point this condition should be met. */
public val threshold: T,
/** The comparison type to use when comparing the threshold against the current value. */
public val comparisonType: ComparisonType,
) {
internal val proto: DataProto.DataTypeCondition =
DataProto.DataTypeCondition.newBuilder()
.setDataType(dataType.proto)
.setThreshold(dataType.toProtoFromValue(threshold))
.setComparisonType(comparisonType.toProto())
.build()
override fun toString(): String =
"DataTypeCondition(" +
"dataType=$dataType, threshold=$threshold, comparisonType=$comparisonType)"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is DataTypeCondition<*, *>) return false
if (dataType != other.dataType) return false
if (threshold != other.threshold) return false
if (comparisonType != other.comparisonType) return false
return true
}
override fun hashCode(): Int {
var result = dataType.hashCode()
result = 31 * result + threshold.hashCode()
result = 31 * result + comparisonType.hashCode()
return result
}
internal companion object {
@Suppress("UNCHECKED_CAST")
internal fun deltaFromProto(
proto: DataProto.DataTypeCondition
): DataTypeCondition<out Number, out DeltaDataType<out Number, *>> {
val dataType =
DataType.deltaFromProto(proto.dataType) as DeltaDataType<Number, *>
return DataTypeCondition(
dataType,
dataType.toValueFromProto(proto.threshold),
ComparisonType.fromProto(proto.comparisonType)
)
}
@Suppress("UNCHECKED_CAST")
internal fun aggregateFromProto(
proto: DataProto.DataTypeCondition
): DataTypeCondition<out Number, out AggregateDataType<out Number, *>> {
val dataType =
DataType.aggregateFromProto(proto.dataType) as AggregateDataType<Number, *>
return DataTypeCondition(
dataType,
dataType.toValueFromProto(proto.threshold),
ComparisonType.fromProto(proto.comparisonType)
)
}
}
}
| apache-2.0 | b64e8a236f52c147c056f2a595507417 | 36.707865 | 93 | 0.657628 | 4.928047 | false | false | false | false |
google/playhvz | Android/ghvzApp/app/src/main/java/com/app/playhvz/firebase/viewmodels/PlayerViewModel.kt | 1 | 3357 | /*
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.app.playhvz.firebase.viewmodels
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.app.playhvz.app.HvzData
import com.app.playhvz.firebase.classmodels.Player
import com.app.playhvz.firebase.constants.PlayerPath
import com.app.playhvz.firebase.constants.UniversalConstants.Companion.UNIVERSAL_FIELD__USER_ID
import com.app.playhvz.firebase.firebaseprovider.FirebaseProvider
import com.app.playhvz.firebase.utils.DataConverterUtil
class PlayerViewModel : ViewModel() {
companion object {
private val TAG = PlayerViewModel::class.qualifiedName
}
private var player: HvzData<Player> = HvzData()
/** Returns a Player LiveData object for the given id. */
fun getPlayer(
gameId: String,
playerId: String
): LiveData<Player> {
player.value = Player()
player.docIdListeners[playerId] = PlayerPath.PLAYERS_COLLECTION(gameId).document(playerId)
.addSnapshotListener { snapshot, e ->
if (e != null) {
Log.w(TAG, "Listen failed.", e)
return@addSnapshotListener
}
if (snapshot != null && snapshot.exists()) {
player.value = DataConverterUtil.convertSnapshotToPlayer(snapshot)
}
}
return player
}
/** Returns a Player LiveData object for the current user id. */
@Suppress("LABEL_NAME_CLASH")
fun getPlayer(gameId: String): MutableLiveData<Player> {
val userId = FirebaseProvider.getFirebaseAuth().uid
if (userId.isNullOrEmpty()) {
Log.w(TAG, "Player Id was empty and shouldn't be, not listening to data updates.")
return player
}
player.docIdListeners["query"] = PlayerPath.PLAYERS_COLLECTION(gameId)
.whereEqualTo(UNIVERSAL_FIELD__USER_ID, userId)
.addSnapshotListener { snapshot, e ->
if (e != null) {
Log.w(TAG, "Listen failed.", e)
return@addSnapshotListener
}
if (snapshot != null && snapshot.size() == 1) {
updatePlayerData(DataConverterUtil.convertSnapshotToPlayer(snapshot.documents[0]!!))
}
}
return player
}
// Clears out any reference to previous player data
fun reset() {
player = HvzData()
}
/** Returns the latest LiveData object we requested. */
fun getPlayer(): MutableLiveData<Player>? {
return if (player.value != null) player else null
}
private fun updatePlayerData(updatedPlayer: Player) {
player.value = updatedPlayer
}
} | apache-2.0 | 5e158b9e5dfd764d0cf0d5d35ddbca2c | 35.901099 | 104 | 0.649687 | 4.623967 | false | false | false | false |
klassm/BezahlScanner | app/src/main/java/li/klass/bezahl/scanner/parser/SwissQrCodeParser.kt | 1 | 700 | package li.klass.bezahl.scanner.parser
import li.klass.bezahl.scanner.DateTimeProvider
import li.klass.bezahl.scanner.Payment
class SwissQrCodeParser(val dateTimeProvider: DateTimeProvider) : QrCodeParser {
override fun canParse(value: String): Boolean = value.startsWith("SPC")
override fun parse(value: String): Payment? {
val lines = value.split("\n")
return Payment(
iban = lines[3],
amount = lines[16].replace(" ", ""),
currency = lines[17],
bic = "",
date = dateTimeProvider.now(),
reason = lines[27] + "\n" + lines[26],
name = lines[10]
)
}
} | gpl-2.0 | 76684ec9b3aa47741e0592fe88ef10bf | 32.380952 | 80 | 0.572857 | 4.142012 | false | false | false | false |
smichel17/simpletask-android | app/src/nextcloud/java/nl/mpcjanssen/simpletask/remote/LoginScreen.kt | 1 | 4786 | package nl.mpcjanssen.simpletask.remote
import android.content.*
import android.net.Uri
import android.os.Bundle
import android.util.Log
import com.owncloud.android.lib.common.OwnCloudClientFactory
import com.owncloud.android.lib.common.OwnCloudCredentialsFactory
import com.owncloud.android.lib.common.network.CertificateCombinedException
import com.owncloud.android.lib.common.network.NetworkUtils
import com.owncloud.android.lib.common.operations.RemoteOperationResult
import com.owncloud.android.lib.resources.files.ReadRemoteFolderOperation
import kotlinx.android.synthetic.nextcloud.login.*
import nl.mpcjanssen.simpletask.*
import nl.mpcjanssen.simpletask.util.Config
import nl.mpcjanssen.simpletask.util.FileStoreActionQueue
import nl.mpcjanssen.simpletask.util.showConfirmationDialog
import nl.mpcjanssen.simpletask.util.showToastLong
import java.io.File
class LoginScreen : ThemedActionBarActivity() {
private val url: String
get () {
val enteredUrl = nextcloud_server_url.text.toString().trimEnd('/')
return if (enteredUrl.startsWith("http://", ignoreCase = true) ||
enteredUrl.startsWith("https://", ignoreCase = true)) {
return enteredUrl
} else {
"https://$enteredUrl"
}
}
private var username by Config.StringOrNullPreference(FileStore.NEXTCLOUD_USER)
private var password by Config.StringOrNullPreference(FileStore.NEXTCLOUD_PASS)
private var serverUrl by Config.StringOrNullPreference(FileStore.NEXTCLOUD_URL)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (TodoApplication.app.isAuthenticated) {
switchToTodolist()
}
setTheme(Config.activeTheme)
setContentView(R.layout.login)
login.setOnClickListener {
startLogin()
}
logging.setOnClickListener {
startActivity(Intent(this, DebugInfoScreen::class.java))
}
}
private fun switchToTodolist() {
val intent = Intent(this, Simpletask::class.java)
startActivity(intent)
finish()
}
private fun finishLogin() {
username = nextcloud_username.text.toString()
password = nextcloud_password.text.toString()
serverUrl = url
Log.d(TAG, "Saved credentials for $username")
FileStore.resetClient()
switchToTodolist()
}
private fun startLogin() {
FileStoreActionQueue.add("login") {
val client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(url), this, true, true)
client.credentials = OwnCloudCredentialsFactory.newBasicCredentials(
nextcloud_username.text.toString(),
nextcloud_password.text.toString()
)
val op = ReadRemoteFolderOperation(File("/").canonicalPath)
val res: RemoteOperationResult = op.execute(client)
Log.d(TAG, res.logMessage)
Log.d(TAG, res.exception?.localizedMessage?:"No exception")
Log.d(TAG, res.httpCode.toString())
res.data?.let {
Log.d(TAG, it.joinToString(" "))
}
when {
res.isSuccess -> {
Log.d(TAG, "Logged in to Nextcloud: ${client.ownCloudVersion}")
finishLogin()
}
res.isSslRecoverableException -> {
Log.d(TAG, "Invalid certificate")
try {
val okListener = DialogInterface.OnClickListener { _, _ ->
val ex = res.exception as CertificateCombinedException
val cert = ex.serverCertificate
NetworkUtils.addCertToKnownServersStore(cert, this)
showToastLong(this, "Certificate saved")
Log.d(TAG, "Server certificate saved")
finishLogin()
}
showConfirmationDialog(this, R.string.invalid_certificate_msg, okListener, R.string.invalid_certificate_title )
} catch (e: Exception) {
Log.d(TAG, "Server certificate could not be saved in the known-servers trust store ", e)
showToastLong(this, "Failed to store certificate")
}
}
else -> {
showToastLong(this, "Login failed: ${res.code.name}")
Log.d(TAG, "Login failed: ${res.code.name}")
}
}
}
}
companion object {
internal val TAG = LoginScreen::class.java.simpleName
}
}
| gpl-3.0 | 8f875b8d53a9ca8a920b850f6997fd4b | 36.390625 | 135 | 0.607606 | 5.118717 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/ui/view/bbcode/prototype/SpoilerPrototype.kt | 1 | 1789 | package me.proxer.app.ui.view.bbcode.prototype
import android.view.View
import me.proxer.app.ui.view.bbcode.BBArgs
import me.proxer.app.ui.view.bbcode.BBCodeView
import me.proxer.app.ui.view.bbcode.BBSpoilerView
import me.proxer.app.ui.view.bbcode.BBTree
import me.proxer.app.ui.view.bbcode.BBUtils
import me.proxer.app.ui.view.bbcode.prototype.BBPrototype.Companion.REGEX_OPTIONS
/**
* @author Ruben Gees
*/
object SpoilerPrototype : AutoClosingPrototype {
const val SPOILER_TEXT_COLOR_ARGUMENT = "spoiler_text_color"
const val SPOILER_EXPAND_ARGUMENT = "spoiler_expand"
private const val TITLE_ARGUMENT = "title"
private val attributeRegex = Regex("spoiler *= *(.+?)$", REGEX_OPTIONS)
override val startRegex = Regex(" *spoiler( *=\"?.+?\"?)?( .*?)?", REGEX_OPTIONS)
override val endRegex = Regex("/ *spoiler *", REGEX_OPTIONS)
override fun construct(code: String, parent: BBTree): BBTree {
val title = BBUtils.cutAttribute(code, attributeRegex)
return BBTree(this, parent, args = BBArgs(custom = *arrayOf(TITLE_ARGUMENT to title)))
}
override fun makeViews(parent: BBCodeView, children: List<BBTree>, args: BBArgs): List<View> {
val childViews = super.makeViews(parent, children, args)
val title = args[TITLE_ARGUMENT] as String?
val shouldExpand = args[SPOILER_EXPAND_ARGUMENT] as Boolean? ?: false
return when (childViews.isEmpty()) {
true -> childViews
false -> listOf(BBSpoilerView(parent.context).apply {
(args[SPOILER_TEXT_COLOR_ARGUMENT] as? Int)?.let { spoilerTextColor = it }
spoilerTitle = title
isExpanded = shouldExpand
childViews.forEach { addView(it) }
})
}
}
}
| gpl-3.0 | 67ec3639fa80c1005ca1c6fd6606aca7 | 35.510204 | 98 | 0.669089 | 3.914661 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/mixin/util/Mixin.kt | 1 | 6794 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.util
import com.demonwav.mcdev.platform.mixin.action.FindMixinsAction
import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.ACCESSOR
import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.INVOKER
import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.MIXIN
import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Classes.ARGS
import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Classes.CALLBACK_INFO
import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Classes.CALLBACK_INFO_RETURNABLE
import com.demonwav.mcdev.util.cached
import com.demonwav.mcdev.util.computeStringArray
import com.demonwav.mcdev.util.findModule
import com.demonwav.mcdev.util.resolveClassArray
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiArrayType
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiDisjunctionType
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiIntersectionType
import com.intellij.psi.PsiPrimitiveType
import com.intellij.psi.PsiType
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.InheritanceUtil
import com.intellij.psi.util.PsiModificationTracker
import org.objectweb.asm.Opcodes
import org.objectweb.asm.tree.ClassNode
/**
* Returns whether the given [PsiClass] is a Mixin class with a `@Mixin` annotation.
*
* @receiver The class to check
* @return True if the given class is a Mixin
*/
val PsiClass.isMixin
get() = mixinAnnotation != null
/**
* Get the Mixin [PsiAnnotation] for the provided Mixin [PsiClass].
* Returns null if the provided class is null or the class is not a Mixin class.
*
* @receiver The [PsiClass] to check.
* @return The Mixin [PsiAnnotation] for the provided Mixin [PsiClass].
*/
val PsiClass.mixinAnnotation
get() = modifierList?.findAnnotation(MIXIN)
/**
* Get a list of every PsiClass target defined in the Mixin annotation of the given class.
* Returns an empty list if this is not a Mixin class or if there are no resolvable targets defined in the Mixin annotation.
*
* @receiver The [PsiClass] to check.
* @return A list of resolved classes defined in the Mixin targets.
*/
val PsiClass.mixinTargets: List<ClassNode>
get() {
return cached {
val mixinAnnotation = mixinAnnotation ?: return@cached emptyList()
// Read class targets (value)
val classTargets =
mixinAnnotation.findDeclaredAttributeValue(null)?.resolveClassArray()
?.mapNotNullTo(mutableListOf()) { it.bytecode } ?: mutableListOf()
// Read and add string targets (targets)
mixinAnnotation.findDeclaredAttributeValue("targets")?.computeStringArray()
?.mapNotNullTo(classTargets) { name ->
findClassNodeByQualifiedName(
project,
findModule(),
name.replace('/', '.')
)
}
classTargets
}
}
val PsiClass.bytecode: ClassNode?
get() = cached(PsiModificationTracker.MODIFICATION_COUNT) {
findClassNodeByPsiClass(this)
}
/**
* Checks if the given [PsiClass] is an accessor Mixin. Return true if and only if:
*
* 1. The class given is a Mixin.
* 2. The class given is an interface.
* 3. All member methods are decorated with either `@Accessor` or `@Invoker`.
* 4. All Mixin targets are classes.
*
* @receiver The class to check
* @return True if the above checks are satisfied.
*/
val PsiClass.isAccessorMixin: Boolean
get() {
if (!isInterface) {
return false
}
if (
methods.any {
it.modifierList.findAnnotation(ACCESSOR) == null &&
it.modifierList.findAnnotation(INVOKER) == null
}
) {
return false
}
val targets = mixinTargets
return targets.isNotEmpty() && !targets.any { it.hasAccess(Opcodes.ACC_INTERFACE) }
}
fun callbackInfoType(project: Project): PsiType =
PsiType.getTypeByName(CALLBACK_INFO, project, GlobalSearchScope.allScope(project))
fun callbackInfoReturnableType(project: Project, context: PsiElement, returnType: PsiType): PsiType? {
val boxedType = if (returnType is PsiPrimitiveType) {
returnType.getBoxedType(context) ?: return null
} else {
returnType
}
// TODO: Can we do this without looking up the PsiClass?
val psiClass =
JavaPsiFacade.getInstance(project).findClass(CALLBACK_INFO_RETURNABLE, GlobalSearchScope.allScope(project))
?: return null
return JavaPsiFacade.getElementFactory(project).createType(psiClass, boxedType)
}
fun argsType(project: Project): PsiType =
PsiType.getTypeByName(ARGS, project, GlobalSearchScope.allScope(project))
fun isAssignable(left: PsiType, right: PsiType): Boolean {
return when {
left is PsiIntersectionType -> left.conjuncts.all { isAssignable(it, right) }
right is PsiIntersectionType -> right.conjuncts.any { isAssignable(left, it) }
left is PsiDisjunctionType -> left.disjunctions.any { isAssignable(it, right) }
right is PsiDisjunctionType -> isAssignable(left, right.leastUpperBound)
left is PsiArrayType -> right is PsiArrayType && isAssignable(left.componentType, right.componentType)
else -> {
if (left !is PsiClassType || right !is PsiClassType) {
return false
}
val leftClass = left.resolve() ?: return false
val rightClass = right.resolve() ?: return false
if (rightClass.isMixin) {
val isMixinAssignable = rightClass.mixinTargets.any {
val stubClass = it.findStubClass(rightClass.project) ?: return@any false
isClassAssignable(leftClass, stubClass)
}
if (isMixinAssignable) {
return true
}
}
val mixins = FindMixinsAction.findMixins(rightClass, rightClass.project) ?: return false
return mixins.any { isClassAssignable(leftClass, it) }
}
}
}
private fun isClassAssignable(leftClass: PsiClass, rightClass: PsiClass): Boolean {
var result = false
InheritanceUtil.processSupers(rightClass, true) {
if (it == leftClass) {
result = true
false
} else {
true
}
}
return result
}
| mit | ccba938fa6db8f4ee22d21ae237c8620 | 36.125683 | 124 | 0.679423 | 4.590541 | false | false | false | false |
evanchooly/kibble | src/main/kotlin/com/antwerkz/kibble/KibbleVisitor.kt | 1 | 42072 | package com.antwerkz.kibble
import com.antwerkz.kibble.Kibble.addAutoImport
import com.antwerkz.kibble.Kibble.autoimport
import com.antwerkz.kibble.model.Accessor
import com.antwerkz.kibble.model.CallBlock.SuperCallBlock
import com.antwerkz.kibble.model.CallBlock.ThisCallBlock
import com.antwerkz.kibble.model.ClassType
import com.antwerkz.kibble.model.ClassType.ENUM
import com.antwerkz.kibble.model.ClassType.INTERFACE
import com.antwerkz.kibble.model.Delegate
import com.antwerkz.kibble.model.Import
import com.antwerkz.kibble.model.Mutator
import com.antwerkz.kibble.model.SuperCall
import com.antwerkz.kibble.model.SuperType
import com.antwerkz.kibble.model.TypeProjection
import com.squareup.kotlinpoet.AnnotationSpec
import com.squareup.kotlinpoet.AnnotationSpec.UseSiteTarget
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.KModifier.INTERNAL
import com.squareup.kotlinpoet.KModifier.PRIVATE
import com.squareup.kotlinpoet.KModifier.PROTECTED
import com.squareup.kotlinpoet.KModifier.PUBLIC
import com.squareup.kotlinpoet.KModifier.VARARG
import com.squareup.kotlinpoet.LambdaTypeName
import com.squareup.kotlinpoet.ParameterSpec
import com.squareup.kotlinpoet.ParameterizedTypeName
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.PropertySpec.Builder
import com.squareup.kotlinpoet.STAR
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.TypeVariableName
import org.jetbrains.kotlin.com.intellij.psi.PsiElement
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtSingleValueToken
import org.jetbrains.kotlin.psi.KtAnnotatedExpression
import org.jetbrains.kotlin.psi.KtAnnotation
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtAnnotationUseSiteTarget
import org.jetbrains.kotlin.psi.KtAnonymousInitializer
import org.jetbrains.kotlin.psi.KtArrayAccessExpression
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtBinaryExpressionWithTypeRHS
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtBlockStringTemplateEntry
import org.jetbrains.kotlin.psi.KtBreakExpression
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtCallableReferenceExpression
import org.jetbrains.kotlin.psi.KtCatchClause
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtClassBody
import org.jetbrains.kotlin.psi.KtClassInitializer
import org.jetbrains.kotlin.psi.KtClassLiteralExpression
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtCollectionLiteralExpression
import org.jetbrains.kotlin.psi.KtConstantExpression
import org.jetbrains.kotlin.psi.KtConstructorCalleeExpression
import org.jetbrains.kotlin.psi.KtConstructorDelegationCall
import org.jetbrains.kotlin.psi.KtConstructorDelegationReferenceExpression
import org.jetbrains.kotlin.psi.KtContinueExpression
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtDelegatedSuperTypeEntry
import org.jetbrains.kotlin.psi.KtDestructuringDeclaration
import org.jetbrains.kotlin.psi.KtDestructuringDeclarationEntry
import org.jetbrains.kotlin.psi.KtDoWhileExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtDoubleColonExpression
import org.jetbrains.kotlin.psi.KtDynamicType
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtEnumEntry
import org.jetbrains.kotlin.psi.KtEscapeStringTemplateEntry
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtExpressionWithLabel
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtFileAnnotationList
import org.jetbrains.kotlin.psi.KtFinallySection
import org.jetbrains.kotlin.psi.KtForExpression
import org.jetbrains.kotlin.psi.KtFunctionType
import org.jetbrains.kotlin.psi.KtIfExpression
import org.jetbrains.kotlin.psi.KtImportAlias
import org.jetbrains.kotlin.psi.KtImportDirective
import org.jetbrains.kotlin.psi.KtImportList
import org.jetbrains.kotlin.psi.KtInitializerList
import org.jetbrains.kotlin.psi.KtIsExpression
import org.jetbrains.kotlin.psi.KtLabeledExpression
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.psi.KtLiteralStringTemplateEntry
import org.jetbrains.kotlin.psi.KtLoopExpression
import org.jetbrains.kotlin.psi.KtModifierList
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtNullableType
import org.jetbrains.kotlin.psi.KtObjectDeclaration
import org.jetbrains.kotlin.psi.KtObjectLiteralExpression
import org.jetbrains.kotlin.psi.KtPackageDirective
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtParameterList
import org.jetbrains.kotlin.psi.KtParenthesizedExpression
import org.jetbrains.kotlin.psi.KtPostfixExpression
import org.jetbrains.kotlin.psi.KtPrefixExpression
import org.jetbrains.kotlin.psi.KtPrimaryConstructor
import org.jetbrains.kotlin.psi.KtProjectionKind
import org.jetbrains.kotlin.psi.KtProjectionKind.IN
import org.jetbrains.kotlin.psi.KtProjectionKind.OUT
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPropertyAccessor
import org.jetbrains.kotlin.psi.KtPropertyDelegate
import org.jetbrains.kotlin.psi.KtQualifiedExpression
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.psi.KtReturnExpression
import org.jetbrains.kotlin.psi.KtSafeQualifiedExpression
import org.jetbrains.kotlin.psi.KtScript
import org.jetbrains.kotlin.psi.KtScriptInitializer
import org.jetbrains.kotlin.psi.KtSecondaryConstructor
import org.jetbrains.kotlin.psi.KtSelfType
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.psi.KtSimpleNameStringTemplateEntry
import org.jetbrains.kotlin.psi.KtStringTemplateEntry
import org.jetbrains.kotlin.psi.KtStringTemplateEntryWithExpression
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
import org.jetbrains.kotlin.psi.KtSuperExpression
import org.jetbrains.kotlin.psi.KtSuperTypeCallEntry
import org.jetbrains.kotlin.psi.KtSuperTypeEntry
import org.jetbrains.kotlin.psi.KtSuperTypeList
import org.jetbrains.kotlin.psi.KtSuperTypeListEntry
import org.jetbrains.kotlin.psi.KtThisExpression
import org.jetbrains.kotlin.psi.KtThrowExpression
import org.jetbrains.kotlin.psi.KtTryExpression
import org.jetbrains.kotlin.psi.KtTypeAlias
import org.jetbrains.kotlin.psi.KtTypeArgumentList
import org.jetbrains.kotlin.psi.KtTypeConstraint
import org.jetbrains.kotlin.psi.KtTypeConstraintList
import org.jetbrains.kotlin.psi.KtTypeElement
import org.jetbrains.kotlin.psi.KtTypeParameter
import org.jetbrains.kotlin.psi.KtTypeParameterList
import org.jetbrains.kotlin.psi.KtTypeProjection
import org.jetbrains.kotlin.psi.KtTypeReference
import org.jetbrains.kotlin.psi.KtUnaryExpression
import org.jetbrains.kotlin.psi.KtUserType
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.psi.KtValueArgumentList
import org.jetbrains.kotlin.psi.KtVisitorVoid
import org.jetbrains.kotlin.psi.KtWhenConditionInRange
import org.jetbrains.kotlin.psi.KtWhenConditionIsPattern
import org.jetbrains.kotlin.psi.KtWhenConditionWithExpression
import org.jetbrains.kotlin.psi.KtWhenEntry
import org.jetbrains.kotlin.psi.KtWhenExpression
import org.jetbrains.kotlin.psi.KtWhileExpression
import org.jetbrains.kotlin.psi.psiUtil.PsiChildRange
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.types.Variance
import org.slf4j.LoggerFactory
import java.util.Locale
@Suppress("unused", "MemberVisibilityCanBePrivate")
internal class KibbleVisitor(private val context: KibbleContext) : KtVisitorVoid() {
companion object {
private val LOG = LoggerFactory.getLogger(KibbleVisitor::class.java)
object None : Any()
init {
addAutoImport("Any", "kotlin.Any")
addAutoImport("Array", "kotlin.Array")
addAutoImport("Boolean", "kotlin.Boolean")
addAutoImport("Byte", "kotlin.Byte")
addAutoImport("Char", "kotlin.Char")
addAutoImport("Double", "kotlin.Double")
addAutoImport("Float", "kotlin.Float")
addAutoImport("Int", "kotlin.Int")
addAutoImport("Long", "kotlin.Long")
addAutoImport("Short", "kotlin.Short")
addAutoImport("String", "kotlin.String")
addAutoImport("Unit", "kotlin.Unit")
addAutoImport("Nothing", "kotlin.Nothing")
addAutoImport("List", "kotlin.collections.List")
addAutoImport("Map", "kotlin.collections.Map")
addAutoImport("Set", "kotlin.collections.Set")
addAutoImport("MutableList", "kotlin.collections.MutableList")
addAutoImport("MutableMap", "kotlin.collections.MutableMap")
addAutoImport("MutableSet", "kotlin.collections.MutableSet")
addAutoImport("Iterable", "kotlin.collections.Iterable")
addAutoImport("Iterator", "kotlin.collections.Iterator")
addAutoImport("Sequence", "kotlin.sequences.Sequence")
}
}
private var pkgName = ""
private val imports = mutableMapOf<String, ClassName>()
override fun visitKtFile(kt: KtFile) {
context.defaultPackageName = kt.packageDirective?.fqName?.asString() ?: ""
val builder = FileSpec.builder(context.defaultPackageName, kt.name)
context.bookmark("visitKtFile: ${kt.name}")
kt.allChildren.forEach { it.accept(this) }
context.popToBookmark().forEach {
when (it) {
is TypeSpec -> builder.addType(it)
is FunSpec -> builder.addFunction(it)
is PropertySpec -> builder.addProperty(it)
is AnnotationSpec -> builder.addAnnotation(it)
is FileSpec.Builder -> {
} // ignore
is Import -> {
if (it.alias != null) {
builder.addAliasedImport(ClassName(it.packageName, it.shortName), it.alias)
} else {
builder.addImport(it.packageName, it.shortName)
}
}
else -> unknownType(it)
}
}
context.register(builder.build())
}
override fun visitImportDirective(directive: KtImportDirective) {
val fqName = directive.importedFqName!!
val alias = directive.aliasName
registerImport(fqName.parent().asString(), fqName.shortName().asString(), alias)
context.push(Import(fqName.parent().asString(), fqName.shortName().asString(), alias))
}
private fun registerImport(packageName: String, className: String, alias: String?) {
imports[alias ?: className] = ClassName(packageName, className)
}
override fun visitKtElement(element: KtElement) {
when (element) {
is KtAnnotationUseSiteTarget -> visitAnnotationUseSiteTarget(element)
is KtFileAnnotationList -> visitKtFileAnnotationList(element)
else -> unknownType(element)
}
}
override fun visitDeclaration(dcl: KtDeclaration) {
return when (dcl) {
is KtClass -> visitClass(dcl)
is KtObjectDeclaration -> visitObjectDeclaration(dcl)
is KtNamedFunction -> visitNamedFunction(dcl)
is KtProperty -> visitProperty(dcl)
is KtTypeParameter -> visitTypeParameter(dcl)
else -> unknownType(dcl)
}
}
override fun visitClass(kt: KtClass) {
val name = kt.name
val (builder, kind) = classBuilder(kt, name)
var primarySet = false
acceptChildren("visitClass", kt, builder) {
when (it) {
is FunSpec -> {
if (it.isConstructor && !primarySet) {
primaryConstructor(it)
primarySet = true
} else {
addFunction(it)
}
}
is KModifier -> addModifiers(it)
is PropertySpec -> addProperty(it)
is TypeName -> addSuperinterface(it)
is AnnotationSpec -> addAnnotation(it)
is SuperCall -> {
superclass(it.type)
it.arguments.forEach { arg -> addSuperclassConstructorParameter(arg) }
}
is TypeSpec -> {
when (kind) {
ENUM -> addEnumConstant(it.name ?: "", it)
else -> addType(it)
}
}
is CodeBlock -> addInitializerBlock(it)
is SuperType -> if (it.delegate != null) addSuperinterface(it.type, it.delegate!!) else addSuperinterface(it.type)
is TypeConstraint -> addTypeVariable(it.type)
else -> unknownType(it)
}
}
context.push(builder.build())
}
private fun classBuilder(kt: KtClass, name: String?): Pair<TypeSpec.Builder, ClassType> {
val kind: ClassType
val builder = when {
kt.isInterface() -> {
kind = INTERFACE
TypeSpec.interfaceBuilder(name!!)
}
kt.isEnum() -> {
kind = ENUM
TypeSpec.enumBuilder(name!!)
}
kt.isAnnotation() -> {
kind = ClassType.ANNOTATION
TypeSpec.annotationBuilder(name!!)
}
name == null -> {
kind = ClassType.CLASS
TypeSpec.anonymousClassBuilder()
}
!kt.isInterface() && !kt.isEnum() -> {
kind = ClassType.CLASS
TypeSpec.classBuilder(name)
}
else -> unknownType(kt)
}
return Pair(builder, kind)
}
override fun visitObjectDeclaration(declaration: KtObjectDeclaration) {
val builder = acceptChildren(
"visitObjectDeclaration", declaration,
TypeSpec.objectBuilder(declaration.name ?: "")
) {
when (it) {
is FunSpec -> addFunction(it)
is KModifier -> addModifiers(it)
is PropertySpec -> addProperty(it)
is TypeName -> addSuperinterface(it)
is AnnotationSpec -> addAnnotation(it)
is SuperCall -> {
superclass(it.type)
it.arguments.forEach { arg -> addSuperclassConstructorParameter(arg) }
}
is TypeSpec -> addType(it)
is CodeBlock -> addInitializerBlock(it)
else -> unknownType(it)
}
}
context.push(builder.build())
}
override fun visitClassOrObject(classOrObject: KtClassOrObject) {
this.visitNamedDeclaration(classOrObject)
}
override fun visitSecondaryConstructor(secondary: KtSecondaryConstructor) {
val builder = FunSpec.constructorBuilder()
acceptChildren("visitSecondaryConstructor", secondary, builder) {
when (it) {
is CodeBlock -> builder.addCode(it)
is KModifier -> builder.addModifiers(it)
is ParameterSpec -> builder.addParameter(it)
is AnnotationSpec -> builder.addAnnotation(it)
is ThisCallBlock -> builder.callThisConstructor(*it.arguments.toTypedArray())
is SuperCallBlock -> builder.callSuperConstructor(*it.arguments.toTypedArray())
else -> unknownType(it)
}
}
context.push(builder.build())
}
override fun visitPrimaryConstructor(primary: KtPrimaryConstructor) {
context.bookmark("visitPrimaryConstructor")
primary.valueParameters.forEach { it.accept(this) }
primary.modifierList?.acceptChildren(this)
val values = context.popToBookmark()
val builder = FunSpec.constructorBuilder()
processChildren(builder, values) {
when (it) {
is ParameterSpec -> builder.addParameter(it)
is PropertySpec -> context.push(it)
is AnnotationSpec -> builder.addAnnotation(it)
else -> unknownType(it)
}
}
context.push(builder.build())
}
private fun unknownType(it: Any): Nothing {
val text = if (it is KtElement) it.text else it.toString()
TODO("unknown type: ${it.javaClass}\n --> $text")
}
override fun visitNamedFunction(kt: KtNamedFunction) {
val builder = FunSpec.builder(kt.name ?: missing("function name is missing: ${kt.text}"))
acceptChildren("visitNamedFunction", kt, builder) {
when (it) {
is CodeBlock -> addCode(it)
is KModifier -> addModifiers(it)
is ParameterSpec -> addParameter(it)
is AnnotationSpec -> addAnnotation(it)
is TypeVariableName -> addTypeVariable(it)
is TypeConstraint -> addTypeVariable(it.type)
is TypeName -> returns(it)
else -> unknownType(it)
}
}
context.push(builder.build())
}
internal fun <T : Any> acceptChildren(bookmark: String, element: PsiElement, t: T, func: T.(it: Any) -> Unit): T {
context.bookmark(bookmark)
element.allChildren.accept(this)
processChildren(t, context.popToBookmark(), func)
return t
}
internal fun <T> processChildren(t: T, list: List<Any>, func: T.(it: Any) -> Unit) {
try {
list.forEach {
t.func(it)
}
} catch (e: NotImplementedError) {
LOG.error(" ===> ${context.stack[0]}")
LOG.error(" ===> $list")
throw e
}
}
private fun <T> KtElement.evaluate(visitor: KibbleVisitor): T {
this.accept(visitor)
return visitor.context.pop()
}
private fun <T> PsiElement.evaluate(visitor: KibbleVisitor): T {
this.accept(visitor)
return visitor.context.pop()
}
private fun <T> List<KtElement>.evaluate(visitor: KibbleVisitor): List<T> {
return map { it.evaluate<T>(visitor) }
}
override fun visitProperty(property: KtProperty) {
try {
val type = property.typeReference?.evaluate<TypeName>(this)
?: missing("properties must have types: ${property.text}")
val name = property.name ?: missing("properties must be named")
val builder = PropertySpec.builder(name, type)
builder.mutable(property.isVar)
buildProperty("visitProperty", property, builder)
context.push(builder.build())
} catch (e: IllegalArgumentException) {
println("property = ${property.text}")
throw e
}
}
private fun buildProperty(bookmark: String, property: PsiElement, builder: Builder) {
acceptChildren(bookmark, property, builder) {
when (it) {
is CodeBlock -> initializer(it)
is Delegate -> delegate(it.delegation)
is AnnotationSpec -> addAnnotation(it)
is KModifier -> addModifiers(it)
is TypeName -> {
} /* already handled */
is Accessor -> getter(it.function)
is Mutator -> setter(it.function)
else -> unknownType(it)
}
}
builder.modifiers.remove(VARARG)
}
private fun missing(message: String): Nothing {
throw Exception(message)
}
override fun visitDestructuringDeclaration(multiDeclaration: KtDestructuringDeclaration) {
this.visitDeclaration(multiDeclaration)
}
override fun visitDestructuringDeclarationEntry(multiDeclarationEntry: KtDestructuringDeclarationEntry) {
this.visitNamedDeclaration(multiDeclarationEntry)
}
override fun visitTypeAlias(typeAlias: KtTypeAlias) {
this.visitNamedDeclaration(typeAlias)
}
override fun visitScript(script: KtScript) {
this.visitDeclaration(script)
}
override fun visitImportAlias(importAlias: KtImportAlias) {
this.visitKtElement(importAlias)
}
override fun visitImportList(importList: KtImportList) {
importList.imports
.map { it.accept(this) }
.toList()
}
fun visitFileAnnotationList(fileAnnotationList: KtFileAnnotationList) {
this.visitKtElement(fileAnnotationList)
}
override fun visitClassBody(classBody: KtClassBody) {
classBody.acceptChildren(this)
/*
acceptChildren("visitClassBody", classBody, None) {
when (it) {
else -> unknownType(it)
}
}
*/
}
override fun visitModifierList(list: KtModifierList) {
list.allChildren.forEach {
when (it) {
is LeafPsiElement -> if (it.elementType is KtModifierKeywordToken) {
context.push(it.toKModifier())
}
else -> it.accept(this)
}
}
}
override fun visitAnnotation(annotation: KtAnnotation) {
// val annType = annotation.typeReference?.evaluate<ClassName>(this)!!
var useSiteTarget: UseSiteTarget? = null
acceptChildren("visitAnnotation", annotation, None) {
when (it) {
is UseSiteTarget -> useSiteTarget = it
is AnnotationSpec -> {
context.push(
it.toBuilder().useSiteTarget(useSiteTarget)
.build()
)
}
else -> unknownType(it)
}
}
}
@Suppress("UNCHECKED_CAST")
override fun visitAnnotationEntry(annotationEntry: KtAnnotationEntry) {
val annType = annotationEntry.typeReference?.evaluate<ClassName>(this)!!
val builder = AnnotationSpec.builder(annType)
context.bookmark("visitAnnotationEntry: $annType")
annotationEntry.valueArgumentList?.accept(this)
val arguments = context.popToBookmark()
arguments.forEach {
it as Pair<String, String>
builder.addMember(it.first, it.second)
}
context.push(builder.build())
}
fun visitAnnotationUseSiteTarget(annotationTarget: KtAnnotationUseSiteTarget) {
context.push(UseSiteTarget.valueOf(annotationTarget.getAnnotationUseSiteTarget().name))
}
fun visitKtFileAnnotationList(annotationTarget: KtFileAnnotationList) {
annotationTarget.allChildren.accept(this)
}
override fun visitConstructorCalleeExpression(kt: KtConstructorCalleeExpression) {
val superCall = SuperCall()
acceptChildren("visitConstructorCalleeExpression", kt, superCall) {
type = when (it) {
is ClassName -> it
is ParameterizedTypeName -> it
else -> unknownType(it)
}
}
context.push(superCall)
}
override fun visitTypeParameterList(list: KtTypeParameterList) {
list.acceptChildren(this)
}
override fun visitTypeParameter(parameter: KtTypeParameter) {
val bounds = acceptChildren<TypeName>("type parameter bounds", parameter.extendsBound)
val value = parameter.name ?: ""
val variance = when (parameter.variance) {
Variance.INVARIANT -> null
Variance.IN_VARIANCE -> KModifier.IN
Variance.OUT_VARIANCE -> KModifier.OUT
}
context.push(TypeVariableName(value, variance).copy(bounds = bounds))
}
override fun visitEnumEntry(enumEntry: KtEnumEntry) {
this.visitClass(enumEntry)
}
override fun visitParameterList(list: KtParameterList) {
list.parameters.map { it.accept(this) }
}
override fun visitParameter(parameter: KtParameter) {
val name = parameter.name ?: ""
visitTypeReference(parameter.typeReference!!)
val type = context.pop<TypeName>()
val builder = ParameterSpec.builder(name, type)
acceptChildren("visitParameter accept", parameter, builder) {
when (it) {
is TypeName -> { } // handled
is KModifier -> {
if (it !in listOf(PUBLIC, PRIVATE, PROTECTED, INTERNAL)) {
addModifiers(it)
}
}
is CodeBlock -> defaultValue(it)
is AnnotationSpec -> addAnnotation(it)
else -> unknownType(it)
}
}
if (parameter.hasValOrVar()) {
val propBuilder = PropertySpec.builder(name, type)
buildProperty("visitParameter", parameter, propBuilder)
propBuilder.mutable(parameter.isMutable)
context.push(propBuilder.build())
}
context.push(builder.build())
}
override fun visitSuperTypeList(list: KtSuperTypeList) {
list.entries.forEach { it.accept(this) }
}
override fun visitSuperTypeListEntry(specifier: KtSuperTypeListEntry) {
acceptChildren("visitSuperTypeListEntry", specifier, SuperType()) {
when (it) {
is CodeBlock -> delegate = it
is ParameterizedTypeName -> type = it
else -> unknownType(it)
}
}
}
override fun visitDelegatedSuperTypeEntry(specifier: KtDelegatedSuperTypeEntry) {
this.visitSuperTypeListEntry(specifier)
}
fun Pair<*, *>.toCodeBlock(): CodeBlock {
return when (first) {
"" -> second as CodeBlock
else -> CodeBlock.of(first as String, second)
}
}
override fun visitSuperTypeCallEntry(call: KtSuperTypeCallEntry) {
val superCall = SuperCall()
acceptChildren("visitSuperTypeCallEntry", call, superCall) {
when (it) {
is Pair<*, *> -> arguments += it.toCodeBlock()
is SuperCall -> type = it.type
else -> unknownType(it)
}
}
context.push(superCall)
}
override fun visitSuperTypeEntry(specifier: KtSuperTypeEntry) {
specifier.typeReference?.evaluate<TypeName>(this)?.let {
context.push(it)
}
}
override fun visitConstructorDelegationCall(call: KtConstructorDelegationCall) {
val callBlock = if (call.isCallToThis) ThisCallBlock() else SuperCallBlock()
context.bookmark("visitConstructorDelegationCall")
call.allChildren.accept(this)
val list = context.popToBookmark()
list.forEach {
when (it) {
is Pair<*, *> -> callBlock.arguments += it.toCodeBlock()
else -> unknownType(it)
}
}
context.push(callBlock)
}
override fun visitPropertyDelegate(delegate: KtPropertyDelegate) {
acceptChildren("visitPropertyDelegate", delegate, None) {
when (it) {
is CodeBlock -> context.push(Delegate(it))
else -> unknownType(it)
}
}
}
override fun visitTypeReference(typeReference: KtTypeReference) {
typeReference.acceptChildren(this)
// TODO: reexamine this call
}
override fun visitValueArgumentList(list: KtValueArgumentList) {
list.arguments.forEach { it.accept(this) }
}
override fun visitArgument(argument: KtValueArgument) {
val name = argument.getArgumentName()?.text ?: ""
val value = argument.getArgumentExpression()?.evaluate<Any>(this) ?: ""
context.push(name to value)
}
@Suppress("UNUSED_PARAMETER")
fun visitConstructorDelegationReferenceExpression(ignore: KtConstructorDelegationReferenceExpression) {
}
override fun visitExpression(expression: KtExpression) {
when (expression) {
is KtConstructorDelegationReferenceExpression -> visitConstructorDelegationReferenceExpression(expression)
else -> context.push(expression.toCodeBlock())
}
}
override fun visitLoopExpression(loopExpression: KtLoopExpression) {
this.visitExpression(loopExpression)
}
override fun visitConstantExpression(expression: KtConstantExpression) {
context.push(expression.toCodeBlock())
}
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
context.push(CodeBlock.of(expression.getReferencedName()))
}
override fun visitReferenceExpression(expression: KtReferenceExpression) {
this.visitExpression(expression)
}
override fun visitLabeledExpression(expression: KtLabeledExpression) {
context.push(expression.toCodeBlock())
}
override fun visitPrefixExpression(expression: KtPrefixExpression) {
context.push(expression.toCodeBlock())
}
override fun visitPostfixExpression(expression: KtPostfixExpression) {
this.visitUnaryExpression(expression)
}
override fun visitUnaryExpression(expression: KtUnaryExpression) {
val operationToken = expression.operationToken
val token = when (operationToken) {
is KtSingleValueToken -> operationToken.value
else -> unknownType(operationToken)
}
context.push(CodeBlock.of(token))
expression.baseExpression?.accept(this)
}
override fun visitBinaryExpression(expression: KtBinaryExpression) {
context.push(expression.toCodeBlock())
}
override fun visitReturnExpression(expression: KtReturnExpression) {
val returned = expression.returnedExpression?.evaluate<String>(this)
val retVal = returned ?: expression.labeledExpression?.evaluate<String>(this)
?: throw RuntimeException("Could not find value for return expression: $expression")
context.push(CodeBlock.of("return $retVal"))
}
override fun visitExpressionWithLabel(expression: KtExpressionWithLabel) {
this.visitExpression(expression)
}
override fun visitThrowExpression(expression: KtThrowExpression) {
this.visitExpression(expression)
}
override fun visitBreakExpression(expression: KtBreakExpression) {
this.visitExpressionWithLabel(expression)
}
override fun visitContinueExpression(expression: KtContinueExpression) {
this.visitExpressionWithLabel(expression)
}
override fun visitIfExpression(expression: KtIfExpression) {
this.visitExpression(expression)
}
override fun visitWhenExpression(expression: KtWhenExpression) {
context.push(expression.toCodeBlock())
}
override fun visitCollectionLiteralExpression(expression: KtCollectionLiteralExpression) {
this.visitExpression(expression)
}
override fun visitTryExpression(expression: KtTryExpression) {
this.visitExpression(expression)
}
override fun visitForExpression(expression: KtForExpression) {
val loopText = expression.prevSibling.text.dropWhile { it == '\n' } + expression.text
context.push(CodeBlock.of(loopText.trimIndent()))
}
override fun visitWhileExpression(expression: KtWhileExpression) {
this.visitLoopExpression(expression)
}
override fun visitDoWhileExpression(expression: KtDoWhileExpression) {
this.visitLoopExpression(expression)
}
override fun visitLambdaExpression(expression: KtLambdaExpression) {
this.visitExpression(expression)
}
override fun visitAnnotatedExpression(expression: KtAnnotatedExpression) {
if (expression.annotationEntries.size != 1) {
throw RuntimeException("Should have found one entry")
}
context.push(expression.annotationEntries[0].evaluate(this))
}
override fun visitCallExpression(expression: KtCallExpression) {
context.push(expression.toCodeBlock())
}
override fun visitArrayAccessExpression(expression: KtArrayAccessExpression) {
this.visitReferenceExpression(expression)
}
override fun visitQualifiedExpression(expression: KtQualifiedExpression) {
this.visitExpression(expression)
}
override fun visitDoubleColonExpression(expression: KtDoubleColonExpression) {
this.visitExpression(expression)
}
override fun visitCallableReferenceExpression(expression: KtCallableReferenceExpression) {
this.visitDoubleColonExpression(expression)
}
override fun visitClassLiteralExpression(expression: KtClassLiteralExpression) {
this.visitDoubleColonExpression(expression)
}
override fun visitDotQualifiedExpression(expression: KtDotQualifiedExpression) {
context.push(expression.toCodeBlock())
}
override fun visitSafeQualifiedExpression(expression: KtSafeQualifiedExpression) {
this.visitQualifiedExpression(expression)
}
override fun visitObjectLiteralExpression(expression: KtObjectLiteralExpression) {
this.visitExpression(expression)
}
override fun visitBlockExpression(expression: KtBlockExpression) {
val builder = CodeBlock.builder()
builder.add("%L", expression.text.drop(1).dropLast(1).trimIndent())
context.push(builder.build())
}
override fun visitCatchSection(catchClause: KtCatchClause) {
this.visitKtElement(catchClause)
}
override fun visitFinallySection(finallySection: KtFinallySection) {
this.visitKtElement(finallySection)
}
override fun visitTypeArgumentList(typeArgumentList: KtTypeArgumentList) {
this.visitKtElement(typeArgumentList)
}
override fun visitThisExpression(expression: KtThisExpression) {
this.visitExpressionWithLabel(expression)
}
override fun visitSuperExpression(expression: KtSuperExpression) {
this.visitExpressionWithLabel(expression)
}
override fun visitParenthesizedExpression(expression: KtParenthesizedExpression) {
this.visitExpression(expression)
}
override fun visitInitializerList(list: KtInitializerList) {
acceptChildren("visitInitializerList", list, None) {
when (it) {
is SuperCall -> context.push(it)
else -> unknownType(it)
}
}
}
override fun visitAnonymousInitializer(initializer: KtAnonymousInitializer) {
this.visitDeclaration(initializer)
}
override fun visitScriptInitializer(initializer: KtScriptInitializer) {
this.visitAnonymousInitializer(initializer)
}
override fun visitClassInitializer(initializer: KtClassInitializer) {
context.push(initializer.body?.evaluate(this) ?: CodeBlock.of(""))
}
override fun visitPropertyAccessor(accessor: KtPropertyAccessor) {
val builder = FunSpec.builder(if (accessor.isGetter) "get()" else "set()")
acceptChildren("visitPropertyAccessor", accessor, None) {
when (it) {
is CodeBlock -> builder.addCode(it)
is ParameterSpec -> builder.addParameter(it)
is KModifier -> builder.addModifiers(it)
else -> unknownType(it)
}
}
context.push(if (accessor.isGetter) Accessor(builder.build()) else Mutator(builder.build()))
}
data class TypeConstraint(val type: TypeVariableName)
override fun visitTypeConstraintList(list: KtTypeConstraintList) {
acceptChildren("visitTypeConstraintList", list, None) {
when (it) {
is TypeVariableName -> context.push(TypeConstraint(it))
else -> unknownType(it)
}
}
}
override fun visitTypeConstraint(constraint: KtTypeConstraint) {
var typeName: CodeBlock? = null
val bounds = mutableListOf<TypeName>()
val modifier: KModifier? = null
acceptChildren("visitTypeConstraint", constraint, None) {
when (it) {
is CodeBlock -> typeName = it
is TypeName -> bounds += it
else -> unknownType(it)
}
}
context.push(
TypeVariableName(typeName.toString(), modifier)
.copy(bounds = bounds)
)
}
private fun visitTypeElement(type: KtTypeElement) {
unknownType(type)
}
override fun visitUserType(type: KtUserType) {
val qualifier = type.qualifier?.text?.split(".") ?: listOf()
var pkgName = qualifier.takeWhile { it[0].isLowerCase() }
.joinToString(".")
val className: String = (qualifier.takeLastWhile { it[0].isUpperCase() } + type.referencedName!!)
.joinToString(".")
val list = acceptChildren<TypeProjection>("user type type arguments", type.typeArgumentList)
if (pkgName.isBlank()) {
pkgName = autoimport(className)?.packageName ?: (imports[className]?.packageName ?: this.pkgName)
}
val value = ClassName(pkgName, className)
if (list.isNotEmpty()) {
context.push(value.parameterizedBy(*list.map { it.type }.toTypedArray()))
} else {
context.push(value)
}
}
override fun visitDynamicType(type: KtDynamicType) {
this.visitTypeElement(type)
}
@Suppress("UNCHECKED_CAST")
override fun visitFunctionType(type: KtFunctionType) {
val parameters: List<ParameterSpec> = acceptChildren("function type parameters", type.parameterList)
val receiver = acceptChildren<TypeName>("function type receiver", type.receiver).firstOrNull()
val returnType = acceptChildren<TypeName>("function type return type", type.returnTypeReference).first()
val lambdaTypeName = LambdaTypeName.get(receiver, parameters, returnType)
context.push(lambdaTypeName)
}
@Suppress("UNCHECKED_CAST")
private fun <T> acceptChildren(bookmark: String, element: KtElement?): List<T> {
context.bookmark(bookmark)
element?.acceptChildren(this)
return context.popToBookmark() as List<T>
}
override fun visitSelfType(type: KtSelfType) {
this.visitTypeElement(type)
}
override fun visitBinaryWithTypeRHSExpression(expression: KtBinaryExpressionWithTypeRHS) {
this.visitExpression(expression)
}
override fun visitStringTemplateExpression(expression: KtStringTemplateExpression) {
context.push(expression.toCodeBlock())
}
override fun visitNamedDeclaration(declaration: KtNamedDeclaration) {
this.visitDeclaration(declaration)
}
override fun visitNullableType(nullableType: KtNullableType) {
nullableType.innerType?.accept(this)
val type = context.pop<TypeName>().copy(nullable = true)
if (nullableType.modifierList?.allChildren?.isEmpty == true) {
TODO("handle the modifiers: ${nullableType.modifierList}")
}
context.push(type)
}
override fun visitTypeProjection(typeProjection: KtTypeProjection) {
val value = if (typeProjection.projectionKind == KtProjectionKind.STAR) STAR
else typeProjection.typeReference!!.evaluate<TypeName>(this)
var variance: KModifier? = null
when (typeProjection.projectionKind) {
IN -> variance = KModifier.IN
OUT -> variance = KModifier.OUT
else -> {
LOG.debug("Found something other than IN/OUT for ${typeProjection.text}")
}
}
context.push(TypeProjection(value, variance))
}
override fun visitWhenEntry(jetWhenEntry: KtWhenEntry) {
context.push(jetWhenEntry.toCodeBlock())
}
override fun visitIsExpression(expression: KtIsExpression) {
this.visitExpression(expression)
}
override fun visitWhenConditionIsPattern(condition: KtWhenConditionIsPattern) {
this.visitKtElement(condition)
}
override fun visitWhenConditionInRange(condition: KtWhenConditionInRange) {
this.visitKtElement(condition)
}
override fun visitWhenConditionWithExpression(condition: KtWhenConditionWithExpression) {
this.visitKtElement(condition)
}
override fun visitStringTemplateEntry(entry: KtStringTemplateEntry) {
this.visitKtElement(entry)
}
override fun visitStringTemplateEntryWithExpression(entry: KtStringTemplateEntryWithExpression) {
this.visitStringTemplateEntry(entry)
}
override fun visitBlockStringTemplateEntry(entry: KtBlockStringTemplateEntry) {
this.visitStringTemplateEntryWithExpression(entry)
}
override fun visitSimpleNameStringTemplateEntry(entry: KtSimpleNameStringTemplateEntry) {
this.visitStringTemplateEntryWithExpression(entry)
}
override fun visitLiteralStringTemplateEntry(entry: KtLiteralStringTemplateEntry) {
this.visitStringTemplateEntry(entry)
}
override fun visitEscapeStringTemplateEntry(entry: KtEscapeStringTemplateEntry) {
this.visitStringTemplateEntry(entry)
}
override fun visitPackageDirective(directive: KtPackageDirective) {
pkgName = directive.qualifiedName
}
private fun PsiElement.toKModifier(): KModifier {
return KModifier.valueOf(this.text.uppercase(Locale.getDefault()))
}
internal fun PsiChildRange.accept(visitor: KibbleVisitor) {
forEach {
it.accept(visitor)
}
}
internal fun KtElement.toCodeBlock() = CodeBlock.of("%L", text)
}
| apache-2.0 | 5ce9f50ce73aefdc10a6e3f08731b041 | 37.247273 | 130 | 0.672775 | 5.109546 | false | false | false | false |
Gnar-Team/Gnar-bot | src/main/kotlin/xyz/gnarbot/gnar/commands/settings/SelfRoleCommand.kt | 1 | 3689 | package xyz.gnarbot.gnar.commands.settings
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.entities.IMentionable
import net.dv8tion.jda.api.entities.Role
import xyz.gnarbot.gnar.commands.BotInfo
import xyz.gnarbot.gnar.commands.Category
import xyz.gnarbot.gnar.commands.Command
import xyz.gnarbot.gnar.commands.Context
import xyz.gnarbot.gnar.commands.template.CommandTemplate
import xyz.gnarbot.gnar.commands.template.annotations.Description
@Command(
aliases = ["selfroles", "selfrole"],
usage = "(add|remove|clear) [@role]",
description = "Set self-roles that users can assign to themselves."
)
@BotInfo(
id = 59,
category = Category.SETTINGS,
permissions = [Permission.MANAGE_ROLES]
)
class SelfRoleCommand : CommandTemplate() {
@Description("Add a self-role.")
fun add(context: Context, role: Role) {
if (!context.selfMember.hasPermission(Permission.MANAGE_ROLES)) {
context.send().error("The bot can not needs the ${Permission.MANAGE_ROLES.getName()} permission.").queue()
return
}
if (role == context.guild.publicRole) {
context.send().error("You can't add the public role!").queue()
return
}
if (!context.selfMember.canInteract(role)) {
context.send().error("That role is higher than my role! Fix by changing the role hierarchy.").queue()
return
}
if (role.id in context.data.roles.selfRoles) {
context.send().error("${role.asMention} is already added as a self-assignable role.").queue()
return
}
context.data.roles.selfRoles.add(role.id)
context.data.save()
context.send().info("Added ${role.asMention} to the list of self-assignable roles. Users can get them using `_iam`.").queue()
}
@Description("Remove a self-role.")
fun remove(context: Context, role: Role) {
if (role.id !in context.data.roles.selfRoles) {
context.send().error("${role.asMention} is not a self-assignable role.").queue()
return
}
context.data.roles.selfRoles.remove(role.id)
context.data.save()
context.send().info("Removed ${role.asMention} from the list of self-assignable roles.").queue()
}
@Description("Clear all self-assignable roles.")
fun clear(context: Context) {
if (context.data.roles.selfRoles.isEmpty()) {
context.send().error("This guild doesn't have any self-assignable roles.").queue()
return
}
context.data.roles.selfRoles.clear()
context.data.save()
context.send().info("Cleared the list of self-assignable roles.").queue()
}
@Description("List self-assignable roles.")
fun list(context: Context) {
context.send().embed("Self-Roles") {
desc {
if (context.data.roles.selfRoles.isEmpty()) {
"This guild doesn't have any self-assignable roles."
} else {
buildString {
if (!context.selfMember.hasPermission(Permission.MANAGE_ROLES)) {
append("**WARNING:** Bot lacks the ${Permission.MANAGE_ROLES.getName()} permission.")
return
}
context.data.roles.selfRoles.mapNotNull(context.guild::getRoleById)
.map(IMentionable::getAsMention)
.forEach { append("• ").append(it).append('\n') }
}
}
}
}.action().queue()
}
} | mit | e0dccd40a3b72983cc5b2ff46b815fc9 | 36.252525 | 133 | 0.596149 | 4.384067 | false | false | false | false |
felipebz/sonar-plsql | zpa-checks/src/main/kotlin/org/sonar/plsqlopen/checks/SameBranchCheck.kt | 1 | 2709 | /**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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.sonar.plsqlopen.checks
import com.felipebz.flr.api.AstNode
import org.sonar.plsqlopen.asTree
import org.sonar.plsqlopen.sslr.IfStatement
import org.sonar.plugins.plsqlopen.api.PlSqlGrammar
import org.sonar.plugins.plsqlopen.api.annotations.*
@Rule(priority = Priority.MAJOR, tags = [Tags.BUG])
@ConstantRemediation("10min")
@RuleInfo(scope = RuleInfo.Scope.ALL)
@ActivatedByDefault
class SameBranchCheck : AbstractBaseCheck() {
override fun init() {
subscribeTo(PlSqlGrammar.IF_STATEMENT)
}
override fun visitNode(node: AstNode) {
val ifStatement = node.asTree<IfStatement>()
val branches = collectStatementsFromBranches(ifStatement)
findSameBranches(branches)
}
private fun findSameBranches(branches: List<AstNode>) {
for (i in 1 until branches.size) {
checkBranch(branches, i)
}
}
private fun checkBranch(branches: List<AstNode>, index: Int) {
val branch = branches[index]
val previousBranchIndex = index - 1
val otherBranch = branches[previousBranchIndex]
if (CheckUtils.equalNodes(otherBranch, branch)) {
addIssue(branch, getLocalizedMessage(), otherBranch.token.line)
.secondary(otherBranch, "Original")
}
}
private fun collectStatementsFromBranches(ifStatement: IfStatement): List<AstNode> {
val statementsFromBranches = ArrayList<AstNode>()
statementsFromBranches.add(ifStatement.statements.astNode)
for (branch in ifStatement.elsifClauses) {
statementsFromBranches.add(branch.statements.astNode)
}
val elseBranch = ifStatement.elseClause
if (elseBranch != null) {
statementsFromBranches.add(elseBranch.statements.astNode)
}
return statementsFromBranches
}
}
| lgpl-3.0 | 98490a26795e447a80a0b8066bcbea92 | 34.181818 | 88 | 0.707272 | 4.455592 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/helpers/SoundFileLoader.kt | 1 | 3089 | package com.habitrpg.android.habitica.helpers
import android.annotation.SuppressLint
import android.content.Context
import android.os.Environment
import com.habitrpg.android.habitica.HabiticaBaseApplication
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.schedulers.Schedulers
import java.io.File
import java.io.IOException
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okio.buffer
import okio.sink
// based on http://stackoverflow.com/questions/29838565/downloading-files-using-okhttp-okio-and-rxjava
class SoundFileLoader(private val context: Context) {
private val client: OkHttpClient = OkHttpClient()
private val externalCacheDir: String?
get() {
val cacheDir = HabiticaBaseApplication.getInstance(context)?.getExternalFilesDir(Environment.DIRECTORY_NOTIFICATIONS)
return cacheDir?.path
}
@SuppressLint("SetWorldReadable", "ReturnCount")
fun download(files: List<SoundFile>): Single<List<SoundFile>> {
return Observable.fromIterable(files)
.flatMap(
{ audioFile ->
val file = File(getFullAudioFilePath(audioFile))
if (file.exists() && file.length() > 5000) {
// Important, or else the MediaPlayer can't access this file
file.setReadable(true, false)
audioFile.file = file
return@flatMap Observable.just(audioFile)
}
val fileObservable = Observable.create<SoundFile> { sub ->
val request = Request.Builder().url(audioFile.webUrl).build()
val response: Response
try {
response = client.newCall(request).execute()
if (!response.isSuccessful) {
throw IOException()
}
} catch (io: IOException) {
sub.onComplete()
return@create
}
try {
val sink = file.sink().buffer()
sink.writeAll(response.body!!.source())
sink.flush()
sink.close()
} catch (io: IOException) {
sub.onComplete()
return@create
}
file.setReadable(true, false)
audioFile.file = file
sub.onNext(audioFile)
sub.onComplete()
}
fileObservable.subscribeOn(Schedulers.io())
},
5
)
.toList()
}
private fun getFullAudioFilePath(soundFile: SoundFile): String =
externalCacheDir + File.separator + soundFile.filePath
}
| gpl-3.0 | f6c00de7657d866ce7bc513a23b80dd1 | 38.101266 | 129 | 0.532859 | 5.626594 | false | false | false | false |
telegram-bots/telegram-channels-feed | tg/src/main/kotlin/com/github/telegram_bots/channels_feed/tg/service/updater/AbstractUpdater.kt | 1 | 1098 | package com.github.telegram_bots.channels_feed.tg.service.updater
import io.reactivex.Completable
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import mu.KLogging
import java.util.concurrent.Executors
import javax.annotation.PostConstruct
import javax.annotation.PreDestroy
abstract class AbstractUpdater(private val name: String) {
companion object : KLogging()
private val executor = Executors.newSingleThreadExecutor({ Thread(it, name) })
protected val scheduler = Schedulers.from(executor)
private var disposable: Disposable? = null
@PreDestroy
open fun onDestroy() = disposable?.dispose()
@PostConstruct
fun init() {
run()
.doOnSubscribe(this::onSubscribe)
.doOnError(this::onError)
.observeOn(scheduler)
.subscribe()
}
abstract fun run(): Completable
private fun onSubscribe(disposable: Disposable) {
this.disposable = disposable
}
private fun onError(throwable: Throwable) = logger.error("[ERROR]", throwable)
}
| mit | abddff4370b82b87139dc0d57d51828c | 28.675676 | 82 | 0.704918 | 4.88 | false | false | false | false |
apollostack/apollo-android | apollo-coroutines-support/src/main/kotlin/com/apollographql/apollo3/coroutines/CoroutinesExtensions.kt | 1 | 6567 | package com.apollographql.apollo3.coroutines
import com.apollographql.apollo3.ApolloCall
import com.apollographql.apollo3.ApolloPrefetch
import com.apollographql.apollo3.ApolloQueryWatcher
import com.apollographql.apollo3.ApolloSubscriptionCall
import com.apollographql.apollo3.api.Operation
import com.apollographql.apollo3.api.ApolloResponse
import com.apollographql.apollo3.exception.ApolloException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.suspendCancellableCoroutine
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.resume
/**
* Converts an [ApolloCall] to an [Flow].
*
* @param <D> the value type.
* @return a flow which emits [Responses<D>]
*/
@ExperimentalCoroutinesApi
fun <D: Operation.Data> ApolloCall<D>.toFlow(): Flow<ApolloResponse<D>> = callbackFlow {
val clone = clone()
clone.enqueue(
object : ApolloCall.Callback<D>() {
override fun onResponse(response: ApolloResponse<D>) {
runCatching {
offer(response)
}
}
override fun onFailure(e: ApolloException) {
close(e)
}
override fun onStatusEvent(event: ApolloCall.StatusEvent) {
if (event == ApolloCall.StatusEvent.COMPLETED) {
close()
}
}
}
)
awaitClose { clone.cancel() }
}
/**
* Converts an [ApolloQueryWatcher] to an [Flow].
*
* @param <D> the value type.
* @return a flow which emits [Responses<D>]
*/
@ExperimentalCoroutinesApi
fun <D: Operation.Data> ApolloQueryWatcher<D>.toFlow(): Flow<ApolloResponse<D>> = callbackFlow {
val clone = clone()
clone.enqueueAndWatch(
object : ApolloCall.Callback<D>() {
override fun onResponse(response: ApolloResponse<D>) {
runCatching {
offer(response)
}
}
override fun onFailure(e: ApolloException) {
close(e)
}
}
)
awaitClose { clone.cancel() }
}
/**
* Suspends the [ApolloCall] until it completes and returns the value on success or throws an exception on failure.
* The [ApolloCall] is cancelled when the coroutine running the operation is cancelled as well.
*
* This is a convenience method that will only return the first value emitted. If more than one
* response is required, for an example to retrieve cached and network response, use [toFlow] instead.
*
* @param <D> the value type.
* @return the response on success.
* @throws ApolloException on failure.
*/
suspend fun <D: Operation.Data> ApolloCall<D>.await(): ApolloResponse<D> = suspendCancellableCoroutine { cont ->
cont.invokeOnCancellation {
cancel()
}
enqueue(object : ApolloCall.Callback<D>() {
private val wasCalled = AtomicBoolean(false)
override fun onResponse(response: ApolloResponse<D>) {
if (!wasCalled.getAndSet(true)) {
cont.resume(response)
}
}
override fun onFailure(e: ApolloException) {
if (!wasCalled.getAndSet(true)) {
cont.resumeWithException(e)
}
}
})
}
/**
* Converts an [ApolloCall] to an [Deferred]. This is a convenience method that will only return the first value emitted.
* If the more than one response is required, for an example to retrieve cached and network response, use [toFlow] instead.
*
* @param <D> the value type.
* @return the deferred
*/
@Deprecated("Use await() instead.")
fun <D: Operation.Data> ApolloCall<D>.toDeferred(): Deferred<ApolloResponse<D>> {
val deferred = CompletableDeferred<ApolloResponse<D>>()
deferred.invokeOnCompletion {
if (deferred.isCancelled) {
cancel()
}
}
enqueue(object : ApolloCall.Callback<D>() {
override fun onResponse(response: ApolloResponse<D>) {
if (deferred.isActive) {
deferred.complete(response)
}
}
override fun onFailure(e: ApolloException) {
if (deferred.isActive) {
deferred.completeExceptionally(e)
}
}
})
return deferred
}
/**
* Converts an [ApolloSubscriptionCall] to an [Flow].
*
* @param <D> the value type.
* @return a flow which emits [Responses<D>]
*/
@ExperimentalCoroutinesApi
fun <D: Operation.Data> ApolloSubscriptionCall<D>.toFlow(): Flow<ApolloResponse<D>> = callbackFlow {
val clone = clone()
clone.execute(
object : ApolloSubscriptionCall.Callback<D> {
override fun onConnected() {
}
override fun onResponse(response: ApolloResponse<D>) {
runCatching {
channel.offer(response)
}
}
override fun onFailure(e: ApolloException) {
channel.close(e)
}
override fun onCompleted() {
channel.close()
}
override fun onTerminated() {
channel.close()
}
}
)
awaitClose { clone.cancel() }
}
/**
* Suspends the [ApolloPrefetch] until it completes and returns the value on success or throws an exception on failure.
* The [ApolloPrefetch] is cancelled when the coroutine running the operation is cancelled as well.
*
* @param <D> the value type.
* @return the response on success.
* @throws ApolloException on failure.
*/
suspend fun ApolloPrefetch.await(): Unit = suspendCancellableCoroutine { cont ->
cont.invokeOnCancellation {
cancel()
}
enqueue(object : ApolloPrefetch.Callback() {
private val wasCalled = AtomicBoolean(false)
override fun onSuccess() {
if (!wasCalled.getAndSet(true)) {
cont.resume(Unit)
}
}
override fun onFailure(e: ApolloException) {
if (!wasCalled.getAndSet(true)) {
cont.resumeWithException(e)
}
}
})
}
/**
* Converts an [ApolloPrefetch] to [Job].
*
* @param <D> the value type.
* @return the converted job
*/
@Deprecated("Use await() instead.")
fun ApolloPrefetch.toJob(): Job {
val deferred = CompletableDeferred<Unit>()
deferred.invokeOnCompletion {
if (deferred.isCancelled) {
cancel()
}
}
enqueue(object : ApolloPrefetch.Callback() {
override fun onSuccess() {
if (deferred.isActive) {
deferred.complete(Unit)
}
}
override fun onFailure(e: ApolloException) {
if (deferred.isActive) {
deferred.completeExceptionally(e)
}
}
})
return deferred
}
| mit | 12c0cb36d155097ede481d9a4f4ebe7b | 25.479839 | 123 | 0.671844 | 4.292157 | false | false | false | false |
apollostack/apollo-android | apollo-runtime/src/test/java/com/apollographql/apollo3/subscription/WebSocketSubscriptionTransportTest.kt | 1 | 6459 | package com.apollographql.apollo3.subscription
import com.google.common.truth.Truth.assertThat
import okhttp3.Protocol
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString
import org.junit.Before
import org.junit.Test
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
class WebSocketSubscriptionTransportTest {
private lateinit var webSocketRequest: Request
private lateinit var webSocketFactory: MockWebSocketFactory
private lateinit var subscriptionTransport: WebSocketSubscriptionTransport
@Before
@Throws(Exception::class)
fun setUp() {
webSocketRequest = Request.Builder().url("wss://localhost").build()
webSocketFactory = MockWebSocketFactory()
val factory = WebSocketSubscriptionTransport.Factory("wss://localhost/", webSocketFactory)
subscriptionTransport = factory.create(object : SubscriptionTransport.Callback {
override fun onConnected() {}
override fun onFailure(t: Throwable) {}
override fun onMessage(message: OperationServerMessage) {}
override fun onClosed() {}
}) as WebSocketSubscriptionTransport
}
@Test
fun connect() {
assertThat(subscriptionTransport.webSocket.get()).isNull()
assertThat(subscriptionTransport.webSocketListener.get()).isNull()
subscriptionTransport.connect()
assertThat(subscriptionTransport.webSocket.get()).isNotNull()
assertThat(subscriptionTransport.webSocketListener.get()).isNotNull()
assertThat(webSocketFactory.request.header("Sec-WebSocket-Protocol")).isEqualTo("graphql-ws")
assertThat(webSocketFactory.request.header("Cookie")).isEqualTo("")
}
@Test
fun disconnect() {
subscriptionTransport.connect()
assertThat(subscriptionTransport.webSocket.get()).isNotNull()
assertThat(subscriptionTransport.webSocketListener.get()).isNotNull()
subscriptionTransport.disconnect(OperationClientMessage.Terminate())
assertThat(subscriptionTransport.webSocket.get()).isNull()
assertThat(subscriptionTransport.webSocketListener.get()).isNull()
}
@Test
fun send() {
val callbackFailure = AtomicReference<Throwable?>()
subscriptionTransport = WebSocketSubscriptionTransport(webSocketRequest, webSocketFactory, object : SubscriptionTransport.Callback {
override fun onConnected() {}
override fun onFailure(t: Throwable) {
callbackFailure.set(t)
}
override fun onMessage(message: OperationServerMessage) {}
override fun onClosed() {}
})
subscriptionTransport.send(OperationClientMessage.Init(emptyMap<String, Any>()))
assertThat(callbackFailure.get()).isInstanceOf(IllegalStateException::class.java)
callbackFailure.set(null)
subscriptionTransport.connect()
subscriptionTransport.send(OperationClientMessage.Init(emptyMap<String, Any>()))
assertThat(callbackFailure.get()).isNull()
subscriptionTransport.disconnect(OperationClientMessage.Terminate())
subscriptionTransport.send(OperationClientMessage.Init(emptyMap<String, Any>()))
assertThat(callbackFailure.get()).isInstanceOf(IllegalStateException::class.java)
}
@Test
fun subscriptionTransportCallback() {
val callbackConnected = AtomicBoolean()
val callbackFailure = AtomicReference<Throwable>()
val callbackMessage = AtomicReference<OperationServerMessage>()
subscriptionTransport = WebSocketSubscriptionTransport(webSocketRequest, webSocketFactory, object : SubscriptionTransport.Callback {
override fun onConnected() {
callbackConnected.set(true)
}
override fun onFailure(t: Throwable) {
callbackFailure.set(t)
}
override fun onMessage(message: OperationServerMessage) {
callbackMessage.set(message)
}
override fun onClosed() {}
})
subscriptionTransport.connect()
webSocketFactory.webSocket.listener.onMessage(webSocketFactory.webSocket, "{\"type\":\"connection_ack\"}")
webSocketFactory.webSocket.listener.onFailure(webSocketFactory.webSocket, UnsupportedOperationException(), null)
assertThat(callbackConnected.get()).isTrue()
assertThat(callbackMessage.get()).isInstanceOf(OperationServerMessage.ConnectionAcknowledge::class.java)
assertThat(callbackFailure.get()).isInstanceOf(UnsupportedOperationException::class.java)
}
@Test
fun subscriptionTransportClosedCallback() {
val callbackConnected = AtomicBoolean()
val callbackClosed = AtomicBoolean()
subscriptionTransport = WebSocketSubscriptionTransport(webSocketRequest, webSocketFactory, object : SubscriptionTransport.Callback {
override fun onConnected() {
callbackConnected.set(true)
}
override fun onFailure(t: Throwable) {
throw UnsupportedOperationException("Unexpected")
}
override fun onMessage(message: OperationServerMessage) {}
override fun onClosed() {
callbackClosed.set(true)
}
})
subscriptionTransport.connect()
webSocketFactory.webSocket.listener.onClosed(webSocketFactory.webSocket, 1001, "")
assertThat(callbackConnected.get()).isTrue()
assertThat(callbackClosed.get()).isTrue()
}
private class MockWebSocketFactory : WebSocket.Factory {
lateinit var request: Request
lateinit var webSocket: MockWebSocket
override fun newWebSocket(request: Request, listener: WebSocketListener): WebSocket {
this.request = request
return MockWebSocket(request, listener).also { webSocket = it }
}
}
private class MockWebSocket(val request: Request, val listener: WebSocketListener) : WebSocket {
var lastSentMessage: String? = null
var closed = false
override fun request(): Request {
return request
}
override fun queueSize(): Long = throw UnsupportedOperationException()
override fun send(text: String): Boolean {
lastSentMessage = text
return true
}
override fun send(bytes: ByteString): Boolean {
throw UnsupportedOperationException()
}
override fun close(code: Int, reason: String?): Boolean {
closed = true
return true
}
override fun cancel() {
throw UnsupportedOperationException()
}
init {
listener.onOpen(this, Response.Builder()
.request(request)
.protocol(Protocol.HTTP_1_0)
.code(200)
.message("Ok")
.build()
)
}
}
} | mit | 3f4061d0df2ac43943889a64da182965 | 35.292135 | 136 | 0.73804 | 5.204674 | false | true | false | false |
square/wire | wire-library/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/FieldOrOneOfBinding.kt | 1 | 2639 | /*
* Copyright 2021 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire.internal
import com.squareup.wire.ProtoAdapter
import com.squareup.wire.Syntax
import com.squareup.wire.WireField
abstract class FieldOrOneOfBinding<M, B> {
abstract val tag: Int
abstract val label: WireField.Label
abstract val redacted: Boolean
abstract val isMap: Boolean
abstract val isMessage: Boolean
/**
* The name of the field in generated code. If the declared name is a keyword like `fun`, this
* will be a transformed name like `fun_`.
*/
abstract val name: String
/**
* The name of the field as declared in the `.proto` file.
*/
abstract val declaredName: String
/**
* The JSON name as determined at code-generation name. This is usually camelCase even if the
* field is declared in snake_case.
*/
abstract val wireFieldJsonName: String
abstract val keyAdapter: ProtoAdapter<*>
abstract val singleAdapter: ProtoAdapter<*>
/**
* If true, Wire will always write identity values.
*/
abstract val writeIdentityValues: Boolean
val adapter: ProtoAdapter<Any> by lazy {
// Delegate adapters are created lazily; otherwise we could stack overflow!
if (isMap) {
ProtoAdapter.newMapAdapter(
keyAdapter as ProtoAdapter<Any>,
singleAdapter as ProtoAdapter<Any>
) as ProtoAdapter<Any>
} else {
singleAdapter.withLabel(label) as ProtoAdapter<Any>
}
}
abstract fun value(builder: B, value: Any)
abstract fun set(builder: B, value: Any?)
abstract operator fun get(message: M): Any?
abstract fun getFromBuilder(builder: B): Any?
fun omitFromJson(syntax: Syntax, value: Any?): Boolean {
if (value == null) return true
return omitIdentity(syntax) && value == adapter.identity
}
private fun omitIdentity(syntax: Syntax): Boolean {
if (writeIdentityValues) return false
if (label == WireField.Label.OMIT_IDENTITY) return true
if (label.isRepeated && syntax == Syntax.PROTO_3) return true
if (isMap && syntax == Syntax.PROTO_3) return true
return false
}
}
| apache-2.0 | 56dbc12ff862f177aebe83b31e0f6b86 | 28 | 96 | 0.710496 | 4.229167 | false | false | false | false |
sjnyag/stamp | app/src/main/java/com/sjn/stamp/ui/fragment/media/FabFragment.kt | 1 | 7763 | package com.sjn.stamp.ui.fragment.media
import android.content.res.ColorStateList
import android.graphics.Color
import android.support.v4.app.Fragment
import android.support.v4.view.ViewCompat
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.animation.DecelerateInterpolator
import com.gordonwong.materialsheetfab.MaterialSheetFabEventListener
import com.sjn.stamp.R
import com.sjn.stamp.ui.SongAdapter
import com.sjn.stamp.ui.custom.CenteredMaterialSheetFab
import com.sjn.stamp.ui.custom.Fab
import com.sjn.stamp.ui.item.holder.SongViewHolder
import com.sjn.stamp.ui.observer.StampEditStateObserver
import com.sjn.stamp.utils.*
import com.takusemba.spotlight.SimpleTarget
import com.takusemba.spotlight.Spotlight
import io.multimoon.colorful.Colorful
abstract class FabFragment : Fragment(), StampEditStateObserver.Listener {
var isShowing = true
protected var recyclerView: RecyclerView? = null
protected var adapter: SongAdapter? = null
private var fab: Fab? = null
private var centeredMaterialSheetFab: CenteredMaterialSheetFab<*>? = null
private var startStampEdit: View.OnClickListener = View.OnClickListener { StampEditStateObserver.notifyStateChange(StampEditStateObserver.State.EDITING) }
private var stopStampEdit: View.OnClickListener = View.OnClickListener { StampEditStateObserver.notifyStateChange(StampEditStateObserver.State.NO_EDIT) }
private fun openStampEdit() {
if (centeredMaterialSheetFab == null || fab == null) return
if (centeredMaterialSheetFab?.isSheetVisible() == false) centeredMaterialSheetFab?.showSheet()
fab?.apply {
backgroundTintList = ColorStateList.valueOf(Color.RED)
setImageResource(R.drawable.ic_dialog_close_light)
setTag(R.id.fab_type, R.drawable.ic_dialog_close_light)
setOnClickListener(stopStampEdit)
}
}
private fun closeStampEdit() {
if (centeredMaterialSheetFab == null || fab == null) return
if (centeredMaterialSheetFab?.isSheetVisible() == true) centeredMaterialSheetFab?.hideSheet()
fab?.apply {
backgroundTintList = ColorStateList.valueOf(Color.WHITE)
setImageResource(R.drawable.ic_stamp)
setTag(R.id.fab_type, R.drawable.ic_stamp)
setOnClickListener(startStampEdit)
}
}
protected fun hideFab() {
fab ?: return
ViewCompat.animate(fab)
.scaleX(0f).scaleY(0f)
.alpha(0f).setDuration(100)
.start()
}
protected fun showFab() {
fab ?: return
ViewCompat.animate(fab)
.scaleX(1f).scaleY(1f)
.alpha(1f).setDuration(200)
.setStartDelay(300L)
.start()
}
protected fun initializeFab(resourceId: Int, color: ColorStateList, onClickListener: View.OnClickListener?) {
fab = activity?.findViewById<Fab>(R.id.fab)?.apply {
visibility = View.VISIBLE
if (Integer.valueOf(resourceId) != getTag(R.id.fab_type)) {
StampEditStateObserver.notifyStateChange(StampEditStateObserver.State.NO_EDIT)
setTag(R.id.fab_type, resourceId)
setImageResource(resourceId)
backgroundTintList = color
onClickListener?.let {
setOnClickListener(it)
}
ViewCompat.animate(this)
.scaleX(1f).scaleY(1f)
.alpha(1f).setDuration(100)
.setStartDelay(300L)
.start()
}
}
}
protected fun initializeFabWithStamp() {
initializeFab(R.drawable.ic_stamp, ColorStateList.valueOf(Colorful().getAccent().asInt()), startStampEdit)
activity?.let { activity ->
centeredMaterialSheetFab = CenteredMaterialSheetFab(fab!!,
activity.findViewById<View>(R.id.fab_sheet).apply {
visibility = View.VISIBLE
},
activity.findViewById<View>(R.id.overlay).apply {
visibility = View.VISIBLE
},
Colorful().getPrimaryDark().asInt(),
Colorful().getAccent().asInt())
centeredMaterialSheetFab?.setEventListener(object : MaterialSheetFabEventListener() {
override fun onShowSheet() {}
override fun onSheetShown() {
StampEditStateObserver.notifyStateChange(StampEditStateObserver.State.EDITING)
}
override fun onHideSheet() {}
override fun onSheetHidden() {
StampEditStateObserver.notifyStateChange(if (StampEditStateObserver.selectedStampList.isEmpty()) StampEditStateObserver.State.NO_EDIT else StampEditStateObserver.State.STAMPING)
}
})
}
}
fun performFabAction() {
//default implementation does nothing
}
override fun onStart() {
LogHelper.d(TAG, "onStart START")
super.onStart()
StampEditStateObserver.addListener(this)
LogHelper.d(TAG, "onStart END")
}
override fun onStop() {
LogHelper.d(TAG, "onStop START")
super.onStop()
if (centeredMaterialSheetFab?.isSheetVisible() == true) centeredMaterialSheetFab?.hideSheet()
StampEditStateObserver.removeListener(this)
LogHelper.d(TAG, "onStop END")
}
override fun onSelectedStampChange(selectedStampList: List<String>) {}
override fun onNewStampCreated(stamp: String) {}
/**
* [StampEditStateObserver.Listener]
*/
override fun onStampStateChange(state: StampEditStateObserver.State) {
LogHelper.d(TAG, "onStampStateChange: ", state)
if (centeredMaterialSheetFab == null || fab == null) {
return
}
when (state) {
StampEditStateObserver.State.EDITING -> openStampEdit()
StampEditStateObserver.State.NO_EDIT -> closeStampEdit()
StampEditStateObserver.State.STAMPING -> {
if (centeredMaterialSheetFab?.isSheetVisible() == true) {
centeredMaterialSheetFab?.hideSheet()
}
if (isShowing && !PreferenceHelper.isSpotlightShown(activity, PreferenceHelper.Key.Spotlight.STAMP_ADD)) {
showSpotlight()
}
}
}
adapter?.notifyDataSetChanged()
}
private fun showSpotlight() {
if (recyclerView == null) {
return
}
val view = recyclerView?.findFirstVisibleViewHolder()
if (view is SongViewHolder) {
view.showTapTargetView?.let { textView ->
activity?.let { activity ->
Spotlight.with(activity)
.setDuration(200L)
.setAnimation(DecelerateInterpolator(2f))
.setTargets(SimpleTarget.Builder(activity)
.setPoint(textView)
.setRadius(120f)
.setTitle(getString(R.string.spotlight_stamp_add_title))
.setDescription(getString(R.string.spotlight_stamp_add_description))
.build())
.start()
PreferenceHelper.setSpotlightShown(activity, PreferenceHelper.Key.Spotlight.STAMP_ADD)
}
}
}
}
companion object {
private val TAG = LogHelper.makeLogTag(FabFragment::class.java)
}
}
| apache-2.0 | 49a13961fe7e6396026026f868fffe39 | 39.222798 | 197 | 0.61046 | 4.845818 | false | false | false | false |
realm/realm-java | library-benchmarks/src/androidTest/java/io/realm/benchmarks/FrozenObjectsBenchmarks.kt | 1 | 3611 | /*
* Copyright 2019 Realm 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 io.realm.benchmarks
import androidx.benchmark.junit4.BenchmarkRule
import androidx.benchmark.junit4.measureRepeated
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import io.realm.Realm
import io.realm.RealmConfiguration
import io.realm.RealmList
import io.realm.RealmResults
import io.realm.benchmarks.entities.AllTypes
import io.realm.kotlin.createObject
import io.realm.kotlin.where
import io.realm.log.RealmLog
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.util.*
@RunWith(AndroidJUnit4::class)
class FrozenObjectsBenchmarks {
@get:Rule
val benchmarkRule = BenchmarkRule()
private lateinit var realm: Realm
private lateinit var readObject: AllTypes
private lateinit var realmConfig: RealmConfiguration
@Before
fun setUp() {
Realm.init(InstrumentationRegistry.getInstrumentation().context)
RealmLog.error("SETUP")
realmConfig = RealmConfiguration.Builder().name("frozen${Random().nextLong()}.realm").build()
realm = Realm.getInstance(realmConfig)
realm.executeTransaction { realm ->
readObject = realm.createObject(AllTypes::class.java)
readObject.columnString = "Foo"
readObject.columnLong = 42
readObject.columnDouble = 1.234
}
}
@After
fun tearDown() {
RealmLog.error("TEAR_DOWN");
realm.close()
}
@Test
fun freezeRealm() {
benchmarkRule.measureRepeated {
// Skip caching in Java and directly measure how fast it is to freeze the SharedRealm.
// ObjectStore do not cache it, so it should be safe to run in a loop.
realm.sharedRealm.freeze()
}
}
@Test
fun freezeResults() {
realm.executeTransaction { r ->
for (i in 0..10_0000) {
val obj = r.createObject<AllTypes>()
obj.columnString= "String: " + i
obj.columnLong = i.toLong()
obj.isColumnBoolean = (i % 2 == 0)
}
}
var results: RealmResults<AllTypes> = realm.where<AllTypes>().findAll()
benchmarkRule.measureRepeated {
results.freeze()
}
}
@Test
fun freezeList() {
var list: RealmList<AllTypes> = RealmList()
realm.executeTransaction { r ->
for (i in 0..10_0000) {
list = readObject.columnRealmList
val obj = r.createObject<AllTypes>()
obj.columnString= "String: " + i
obj.columnLong = i.toLong()
obj.isColumnBoolean = (i % 2 == 0)
list.add(obj)
}
}
benchmarkRule.measureRepeated {
list.freeze()
}
}
@Test
fun freezeObject() {
benchmarkRule.measureRepeated {
readObject.freeze<AllTypes>()
}
}
}
| apache-2.0 | c29573ca4e3efb77f278e6ac8dd57c93 | 29.344538 | 101 | 0.640543 | 4.51375 | false | true | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/LALR1/grammar/tree/ExpIndexAssign.kt | 1 | 3110 | package com.bajdcc.LALR1.grammar.tree
import com.bajdcc.LALR1.grammar.codegen.ICodegen
import com.bajdcc.LALR1.grammar.runtime.RuntimeInst
import com.bajdcc.LALR1.grammar.semantic.ISemanticRecorder
import com.bajdcc.LALR1.grammar.tree.closure.IClosureScope
import com.bajdcc.util.lexer.token.OperatorType
import com.bajdcc.util.lexer.token.Token
/**
* 【语义分析】间接寻址赋值
*
* @author bajdcc
*/
class ExpIndexAssign : IExp {
/**
* 操作符
*/
private var token: Token? = null
/**
* 对象
*/
var exp: IExp? = null
/**
* 索引
*/
var index: IExp? = null
/**
* 对象
*/
var obj: IExp? = null
fun setToken(token: Token) {
this.token = token
}
override fun isConstant(): Boolean {
return false
}
override fun isEnumerable(): Boolean {
return false
}
override fun simplify(recorder: ISemanticRecorder): IExp {
exp = exp!!.simplify(recorder)
index = index!!.simplify(recorder)
obj = obj!!.simplify(recorder)
return this
}
override fun analysis(recorder: ISemanticRecorder) {
exp!!.analysis(recorder)
index!!.analysis(recorder)
obj!!.analysis(recorder)
}
override fun genCode(codegen: ICodegen) {
if (token == null || token!!.obj === OperatorType.EQ_ASSIGN) {
obj!!.genCode(codegen)
} else {
exp!!.genCode(codegen)
index!!.genCode(codegen)
codegen.genCode(RuntimeInst.iidx)
obj!!.genCode(codegen)
when (token!!.obj as OperatorType?) {
OperatorType.PLUS_ASSIGN -> codegen.genCode(RuntimeInst.iadd)
OperatorType.MINUS_ASSIGN -> codegen.genCode(RuntimeInst.isub)
OperatorType.TIMES_ASSIGN -> codegen.genCode(RuntimeInst.imul)
OperatorType.DIV_ASSIGN -> codegen.genCode(RuntimeInst.idiv)
OperatorType.AND_ASSIGN -> codegen.genCode(RuntimeInst.iand)
OperatorType.OR_ASSIGN -> codegen.genCode(RuntimeInst.ior)
OperatorType.XOR_ASSIGN -> codegen.genCode(RuntimeInst.ixor)
OperatorType.MOD_ASSIGN -> codegen.genCode(RuntimeInst.imod)
else -> {}
}
}
exp!!.genCode(codegen)
index!!.genCode(codegen)
codegen.genCode(RuntimeInst.iidxa)
}
override fun toString(): String {
return print(StringBuilder())
}
override fun print(prefix: StringBuilder): String {
return exp!!.print(prefix) +
OperatorType.LSQUARE.desc +
index!!.print(prefix) +
OperatorType.RSQUARE.desc +
" " +
(if (token == null) OperatorType.ASSIGN.desc else token!!.toRealString()) +
" " +
obj!!.print(prefix)
}
override fun addClosure(scope: IClosureScope) {
exp!!.addClosure(scope)
index!!.addClosure(scope)
obj!!.addClosure(scope)
}
override fun setYield() {
}
}
| mit | ee9e996c5a0f07c4c6521066a8a0fd62 | 26.63964 | 91 | 0.58442 | 4.24343 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/reader/usecases/ReaderCommentsFollowUseCase.kt | 1 | 12764 | package org.wordpress.android.ui.reader.usecases
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import org.wordpress.android.R
import org.wordpress.android.analytics.AnalyticsTracker.Stat
import org.wordpress.android.datasets.wrappers.ReaderPostTableWrapper
import org.wordpress.android.fluxc.store.AccountStore
import org.wordpress.android.ui.reader.FollowConversationStatusFlags
import org.wordpress.android.ui.reader.comments.ThreadedCommentsActionSource
import org.wordpress.android.ui.reader.tracker.ReaderTracker
import org.wordpress.android.ui.reader.usecases.ReaderCommentsFollowUseCase.AnalyticsFollowCommentsAction.DISABLE_PUSH_NOTIFICATION
import org.wordpress.android.ui.reader.usecases.ReaderCommentsFollowUseCase.AnalyticsFollowCommentsAction.ENABLE_PUSH_NOTIFICATION
import org.wordpress.android.ui.reader.usecases.ReaderCommentsFollowUseCase.AnalyticsFollowCommentsAction.FOLLOW_COMMENTS
import org.wordpress.android.ui.reader.usecases.ReaderCommentsFollowUseCase.AnalyticsFollowCommentsAction.UNFOLLOW_COMMENTS
import org.wordpress.android.ui.reader.usecases.ReaderCommentsFollowUseCase.AnalyticsFollowCommentsActionResult.ERROR
import org.wordpress.android.ui.reader.usecases.ReaderCommentsFollowUseCase.AnalyticsFollowCommentsActionResult.SUCCEEDED
import org.wordpress.android.ui.reader.usecases.ReaderCommentsFollowUseCase.AnalyticsFollowCommentsGenericError.NO_NETWORK
import org.wordpress.android.ui.reader.usecases.ReaderCommentsFollowUseCase.FollowCommentsState.UserNotAuthenticated
import org.wordpress.android.ui.reader.utils.PostSubscribersApiCallsProvider
import org.wordpress.android.ui.reader.utils.PostSubscribersApiCallsProvider.PostSubscribersCallResult.Failure
import org.wordpress.android.ui.reader.utils.PostSubscribersApiCallsProvider.PostSubscribersCallResult.Success
import org.wordpress.android.ui.utils.UiString
import org.wordpress.android.ui.utils.UiString.UiStringRes
import org.wordpress.android.ui.utils.UiString.UiStringText
import org.wordpress.android.util.NetworkUtilsWrapper
import javax.inject.Inject
class ReaderCommentsFollowUseCase @Inject constructor(
private val networkUtilsWrapper: NetworkUtilsWrapper,
private val postSubscribersApiCallsProvider: PostSubscribersApiCallsProvider,
private val accountStore: AccountStore,
private val readerTracker: ReaderTracker,
private val readerPostTableWrapper: ReaderPostTableWrapper
) {
suspend fun getMySubscriptionToPost(blogId: Long, postId: Long, isInit: Boolean) = flow {
if (!accountStore.hasAccessToken()) {
emit(UserNotAuthenticated)
} else {
emit(FollowCommentsState.Loading)
if (!networkUtilsWrapper.isNetworkAvailable()) {
emit(FollowCommentsState.Failure(blogId, postId, UiStringRes(R.string.error_network_connection)))
} else {
val canFollowComments = postSubscribersApiCallsProvider.getCanFollowComments(blogId)
if (!canFollowComments) {
emit(FollowCommentsState.FollowCommentsNotAllowed)
} else {
val status = postSubscribersApiCallsProvider.getMySubscriptionToPost(blogId, postId)
when (status) {
is Success -> {
emit(
FollowCommentsState.FollowStateChanged(
blogId = blogId,
postId = postId,
isFollowing = status.isFollowing,
isReceivingNotifications = status.isReceivingNotifications,
isInit = isInit
)
)
}
is Failure -> {
emit(FollowCommentsState.Failure(blogId, postId, UiStringText(status.error)))
}
}
}
}
}
}
suspend fun setMySubscriptionToPost(
blogId: Long,
postId: Long,
subscribe: Boolean,
source: ThreadedCommentsActionSource
): Flow<FollowCommentsState> = flow {
val properties = mutableMapOf<String, Any?>()
properties.addFollowAction(subscribe)
properties.addFollowActionSource(source)
emit(FollowCommentsState.Loading)
if (!networkUtilsWrapper.isNetworkAvailable()) {
emit(FollowCommentsState.Failure(blogId, postId, UiStringRes(R.string.error_network_connection)))
properties.addFollowActionResult(ERROR, NO_NETWORK.errorMessage)
} else {
val status = if (subscribe) {
postSubscribersApiCallsProvider.subscribeMeToPost(blogId, postId)
} else {
postSubscribersApiCallsProvider.unsubscribeMeFromPost(blogId, postId)
}
when (status) {
is Success -> {
emit(
FollowCommentsState.FollowStateChanged(
blogId = blogId,
postId = postId,
isFollowing = status.isFollowing,
isReceivingNotifications = status.isReceivingNotifications,
false,
userMessage = UiStringRes(
if (status.isFollowing) {
R.string.reader_follow_comments_subscribe_success_enable_push
} else {
R.string.reader_follow_comments_unsubscribe_from_all_success
}
)
)
)
properties.addFollowActionResult(SUCCEEDED)
}
is Failure -> {
emit(FollowCommentsState.Failure(blogId, postId, UiStringText(status.error)))
properties.addFollowActionResult(ERROR, status.error)
}
}
}
val post = readerPostTableWrapper.getBlogPost(blogId, postId, true)
readerTracker.trackPostComments(
Stat.COMMENT_FOLLOW_CONVERSATION,
blogId,
postId,
post,
properties
)
}
suspend fun setEnableByPushNotifications(
blogId: Long,
postId: Long,
enable: Boolean,
source: ThreadedCommentsActionSource
): Flow<FollowCommentsState> = flow {
val properties = mutableMapOf<String, Any?>()
properties.addEnablePushNotificationAction(enable)
properties.addFollowActionSource(source)
if (!networkUtilsWrapper.isNetworkAvailable()) {
emit(FollowCommentsState.FollowStateChanged(
blogId = blogId,
postId = postId,
isFollowing = true,
isReceivingNotifications = !enable,
false,
userMessage = UiStringRes(R.string.error_network_connection),
true
))
properties.addFollowActionResult(ERROR, NO_NETWORK.errorMessage)
} else {
when (val status = postSubscribersApiCallsProvider.managePushNotificationsForPost(blogId, postId, enable)) {
is Success -> {
emit(FollowCommentsState.FollowStateChanged(
blogId = blogId,
postId = postId,
isFollowing = status.isFollowing,
isReceivingNotifications = status.isReceivingNotifications,
false,
userMessage = UiStringRes(if (enable) {
R.string.reader_follow_comments_subscribe_to_push_success
} else {
R.string.reader_follow_comments_unsubscribe_from_push_success
}),
false
))
properties.addFollowActionResult(SUCCEEDED)
}
is Failure -> {
emit(FollowCommentsState.FollowStateChanged(
blogId = blogId,
postId = postId,
isFollowing = true,
isReceivingNotifications = !enable,
false,
userMessage = UiStringRes(if (enable) {
R.string.reader_follow_comments_could_not_subscribe_to_push_error
} else {
R.string.reader_follow_comments_could_not_unsubscribe_from_push_error
}),
true
))
properties.addFollowActionResult(ERROR, status.error)
}
}
}
readerTracker.trackPostComments(
Stat.COMMENT_FOLLOW_CONVERSATION,
blogId,
postId,
readerPostTableWrapper.getBlogPost(blogId, postId, true),
properties
)
}
sealed class FollowCommentsState(open val forcePushNotificationsUpdate: Boolean = false) {
object Loading : FollowCommentsState()
data class FollowStateChanged(
val blogId: Long,
val postId: Long,
val isFollowing: Boolean,
val isReceivingNotifications: Boolean,
val isInit: Boolean = false,
val userMessage: UiString? = null,
override val forcePushNotificationsUpdate: Boolean = false
) : FollowCommentsState()
data class Failure(
val blogId: Long,
val postId: Long,
val error: UiString
) : FollowCommentsState()
object FollowCommentsNotAllowed : FollowCommentsState()
object UserNotAuthenticated : FollowCommentsState()
data class FlagsMappedState(
val flags: FollowConversationStatusFlags
) : FollowCommentsState()
}
private enum class AnalyticsFollowCommentsAction(val action: String) {
FOLLOW_COMMENTS("followed"),
UNFOLLOW_COMMENTS("unfollowed"),
ENABLE_PUSH_NOTIFICATION("enable_push_notifications"),
DISABLE_PUSH_NOTIFICATION("disable_push_notifications")
}
private enum class AnalyticsFollowCommentsActionResult(val actionResult: String) {
SUCCEEDED("succeeded"),
ERROR("error")
}
private enum class AnalyticsFollowCommentsGenericError(val errorMessage: String) {
NO_NETWORK("no_network")
}
private fun MutableMap<String, Any?>.addFollowAction(subscribe: Boolean): MutableMap<String, Any?> {
this[FOLLOW_COMMENT_ACTION] = if (subscribe) {
FOLLOW_COMMENTS.action
} else {
UNFOLLOW_COMMENTS.action
}
return this
}
private fun MutableMap<String, Any?>.addEnablePushNotificationAction(enable: Boolean): MutableMap<String, Any?> {
this[FOLLOW_COMMENT_ACTION] = if (enable) {
ENABLE_PUSH_NOTIFICATION.action
} else {
DISABLE_PUSH_NOTIFICATION.action
}
return this
}
private fun MutableMap<String, Any?>.addFollowActionResult(
result: AnalyticsFollowCommentsActionResult,
errorMessage: String? = null
): MutableMap<String, Any?> {
this[FOLLOW_COMMENT_ACTION_RESULT] = result.actionResult
errorMessage?.also {
this[FOLLOW_COMMENT_ACTION_ERROR] = errorMessage
}
return this
}
private fun MutableMap<String, Any?>.addFollowActionSource(
source: ThreadedCommentsActionSource
): MutableMap<String, Any?> {
this[FOLLOW_COMMENT_ACTION_SOURCE] = source.sourceDescription
return this
}
companion object {
private const val FOLLOW_COMMENT_ACTION = "follow_action"
private const val FOLLOW_COMMENT_ACTION_RESULT = "follow_action_result"
private const val FOLLOW_COMMENT_ACTION_ERROR = "follow_action_error"
private const val FOLLOW_COMMENT_ACTION_SOURCE = "source"
}
}
| gpl-2.0 | d9c18603e6a47e2c6fb54b9c5eb52246 | 43.629371 | 131 | 0.588217 | 5.833638 | false | false | false | false |
greenspand/kotlin-extensions | kotlin-ext/src/main/java/com/sorinirimies/kotlinx/conversionUtils.kt | 1 | 3327 | @file:JvmName("ConversionUtils")
package com.sorinirimies.kotlinx
import android.support.annotation.Keep
import android.util.Base64
import java.math.BigDecimal
import java.math.BigInteger
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.charset.Charset
/**
* Returns the integer value converted from a byte array
* @param b
* @return
*/
@Keep
fun ByteArray.toInt(): Int {
val bb = ByteBuffer.wrap(this)
bb.order(ByteOrder.LITTLE_ENDIAN)
return bb.int
}
@Keep
fun Int.byteArrayFromInt(): ByteArray = BigInteger.valueOf(this.toLong()).toByteArray()
/**
* One way of converting int into byte array
* @return
*/
@Keep
fun Int.toByteArray(): ByteArray {
val result = ByteArray(4)
result[0] = (this shr 24).toByte()
result[1] = (this shr 16).toByte()
result[2] = (this shr 8).toByte()
result[3] = (this shr 0).toByte()
return result
}
@Keep
fun IntArray.toByteArray(): ByteArray {
val output = ByteArray(this.size * 4)
for (i in this.indices) {
output[i * 4] = (this[i] and 255).toByte()
output[i * 4 + 1] = ((this[i] and 65280).ushr(8)).toByte()
output[i * 4 + 2] = ((this[i] and 16711680).ushr(16)).toByte()
output[i * 4 + 3] = ((this[i] and -16777216).ushr(24)).toByte()
}
return output
}
/**
* One way of converting int into byte array.
* @param value
* @return
*/
@Keep
fun convertIntToByteArray(value: Int): ByteArray = BigInteger.valueOf(value.toLong()).toByteArray()
@Keep
fun concatenateByteArray(payload: ByteArray, value: Int): ByteArray {
val intVal: ByteArray = value.toByteArray()
val combined = ByteArray(payload.size + intVal.size)
for (i in combined.indices) {
combined[i] = if (i < payload.size) payload[i] else intVal[i - intVal.size]
}
return combined
}
/**
* Returns the bytearray of a string, in format UTF-8
* @param str
* @return
*/
@Keep
fun returnByteArrayFromString(str: String, formatUTF: Boolean): ByteArray {
val bArray: ByteArray
if (formatUTF) {
bArray = str.toByteArray(Charset.forName("UTF-8"))
} else {
bArray = str.toByteArray()
}
return bArray
}
@Keep
fun returnByteArrayFromDouble(d: Double): ByteArray {
val b = ByteArray(8)
ByteBuffer.wrap(b).putDouble(d)
return b
}
/**
* Max 255
* Converts an integer to a byte. Max value is 255
* @return byte
*/
@Keep
fun returnByteFromInteger(i: Int): Byte {
val b = (i and 255).toByte()
return b
}
/**Number formatting */
@Keep
fun Double.toBigDecimal(): BigDecimal = BigDecimal.valueOf(this)
@Keep
operator fun BigDecimal.plus(a: BigDecimal): BigDecimal = this.add(a)
@Keep
operator fun BigDecimal.minus(a: BigDecimal): BigDecimal = this.subtract(a)
@Keep
operator fun BigDecimal.times(a: BigDecimal): BigDecimal = this.multiply(a)
@Keep
operator fun BigDecimal.div(a: BigDecimal): BigDecimal = this.divide(a)
/**
* Return the double from the byte array.
* @param b the given [ByteArray]
* @return the double from the [ByteArray]
*/
@Keep
fun doubleFromByteArray(b: ByteArray): Double = ByteBuffer.wrap(b).double
/**Decodes encoded Base 64 Chars*/
@Keep
fun base64Decode(s: String): ByteArray = Base64.decode(s, Base64.DEFAULT)
@Keep
fun base64Encode(b: ByteArray): String = Base64.encodeToString(b, Base64.DEFAULT).trim()
| mit | a00c651e00a0ce49f33df1de9c85ff4c | 23.644444 | 99 | 0.681996 | 3.405322 | false | false | false | false |
danielgimenes/Kotlin-Koans | src/ii_collections/n21Partition.kt | 2 | 633 | package ii_collections
fun example8() {
val numbers = listOf(1, 3, -4, 2, -11)
// The details (how multi-assignment works) will be explained later in the 'Conventions' task
val (positive, negative) = numbers.partition { it > 0 }
positive == listOf(1, 3, 2)
negative == listOf(-4, -11)
}
fun Shop.getCustomersWithMoreUndeliveredOrdersThanDelivered(): Set<Customer> {
// Return customers who have more undelivered orders than delivered
return this.customers.filter {
val (delivered, undelivered) = it.orders.partition { it.isDelivered }
undelivered.size > delivered.size
}.toSet()
}
| mit | 97810730f302f671668d77458a7734f0 | 32.315789 | 97 | 0.684044 | 3.981132 | false | false | false | false |
KotlinNLP/SimpleDNN | src/test/kotlin/core/layers/recurrent/simple/SimpleRecurrentLayerParametersSpec.kt | 1 | 2207 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package core.layers.recurrent.simple
import com.kotlinnlp.simplednn.core.functionalities.initializers.ConstantInitializer
import com.kotlinnlp.simplednn.core.functionalities.initializers.RandomInitializer
import com.kotlinnlp.simplednn.core.functionalities.randomgenerators.RandomGenerator
import com.kotlinnlp.simplednn.core.layers.models.recurrent.simple.SimpleRecurrentLayerParameters
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import kotlin.test.*
/**
*
*/
class SimpleRecurrentLayerParametersSpec : Spek({
describe("a SimpleRecurrentLayerParameters") {
context("initialization") {
context("dense input") {
var k = 0
val initValues = doubleArrayOf(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0)
val randomGenerator = mock<RandomGenerator>()
whenever(randomGenerator.next()).thenAnswer { initValues[k++] }
val params = SimpleRecurrentLayerParameters(
inputSize = 3,
outputSize = 2,
weightsInitializer = RandomInitializer(randomGenerator),
biasesInitializer = ConstantInitializer(0.9))
val w = params.unit.weights.values
val b = params.unit.biases.values
val wr = params.unit.recurrentWeights.values
it("should contain the expected initialized weights") {
(0 until w.length).forEach { i -> assertEquals(initValues[i], w[i]) }
}
it("should contain the expected initialized biases") {
(0 until b.length).forEach { i -> assertEquals(0.9, b[i]) }
}
it("should contain the expected initialized recurrent weights") {
(0 until wr.length).forEach { i -> assertEquals(initValues[i + 6], wr[i]) }
}
}
}
}
})
| mpl-2.0 | 826fa2413cdb074a1bc7f30f15891721 | 35.783333 | 97 | 0.674218 | 4.277132 | false | false | false | false |
ingokegel/intellij-community | plugins/git4idea/src/git4idea/actions/GitAdd.kt | 13 | 1132 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.actions
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.FileStatus
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.changes.actions.ScheduleForAdditionActionExtension
import com.intellij.openapi.vfs.VirtualFile
import git4idea.GitVcs
import git4idea.util.GitFileUtils
class GitAdd : ScheduleForAdditionActionExtension {
override fun getSupportedVcs(project: Project) = GitVcs.getInstance(project)
override fun isStatusForAddition(status: FileStatus) =
status === FileStatus.MODIFIED ||
status === FileStatus.MERGED_WITH_CONFLICTS ||
status === FileStatus.ADDED ||
status === FileStatus.DELETED ||
status === FileStatus.IGNORED
@Throws(VcsException::class)
override fun doAddFiles(project: Project, vcsRoot: VirtualFile, paths: List<FilePath>, containsIgnored: Boolean) {
GitFileUtils.addPaths(project, vcsRoot, paths, containsIgnored)
}
}
| apache-2.0 | 08674014ec3f68b98f56893af175a6eb | 40.925926 | 140 | 0.787986 | 4.255639 | false | false | false | false |
yunv/BJUTWiFi | app/src/main/kotlin/com/android/settings/graph/UsageView.kt | 2 | 4895 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.android.settings.graph
import android.content.Context
import android.util.AttributeSet
import android.util.SparseIntArray
import android.view.Gravity
import android.view.LayoutInflater
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.Space
import android.widget.TextView
import me.liuyun.bjutlgn.R
class UsageView(context: Context, attrs: AttributeSet) : FrameLayout(context, attrs) {
private val mUsageGraph: UsageGraph
private val mLabels: Array<TextView>
private val mBottomLabels: Array<TextView>
init {
LayoutInflater.from(context).inflate(R.layout.usage_view, this)
mUsageGraph = findViewById(R.id.usage_graph)
mLabels = arrayOf(findViewById(R.id.label_bottom), findViewById(R.id.label_middle), findViewById(R.id.label_top))
mBottomLabels = arrayOf(findViewById(R.id.label_start), findViewById(R.id.label_end))
val a = context.obtainStyledAttributes(attrs, R.styleable.UsageView, 0, 0)
if (a.hasValue(R.styleable.UsageView_sideLabels)) {
setSideLabels(a.getTextArray(R.styleable.UsageView_sideLabels))
}
if (a.hasValue(R.styleable.UsageView_bottomLabels)) {
setBottomLabels(a.getTextArray(R.styleable.UsageView_bottomLabels))
}
if (a.hasValue(R.styleable.UsageView_textColor)) {
val color = a.getColor(R.styleable.UsageView_textColor, 0)
for (v in mLabels) {
v.setTextColor(color)
}
for (v in mBottomLabels) {
v.setTextColor(color)
}
}
if (a.hasValue(R.styleable.UsageView_android_gravity)) {
val gravity = a.getInt(R.styleable.UsageView_android_gravity, 0)
if (gravity == Gravity.END) {
val layout: LinearLayout = findViewById(R.id.graph_label_group)
val labels: LinearLayout = findViewById(R.id.label_group)
// Swap the children order.
layout.removeView(labels)
layout.addView(labels)
// Set gravity.
labels.gravity = Gravity.END
// Swap the bottom space order.
val bottomLabels: LinearLayout = findViewById(R.id.bottom_label_group)
val bottomSpace: Space = bottomLabels.findViewById(R.id.bottom_label_space)
bottomLabels.removeView(bottomSpace)
bottomLabels.addView(bottomSpace)
} else if (gravity != Gravity.START) {
throw IllegalArgumentException("Unsupported gravity " + gravity)
}
}
mUsageGraph.setAccentColor(a.getColor(R.styleable.UsageView_android_colorAccent, 0))
}
fun clearPaths() {
mUsageGraph.clearPaths()
}
fun addPath(points: SparseIntArray) {
mUsageGraph.addPath(points)
}
fun configureGraph(maxX: Int, maxY: Int, showProjection: Boolean, projectUp: Boolean) {
mUsageGraph.setMax(maxX, maxY)
}
fun setAccentColor(color: Int) {
mUsageGraph.setAccentColor(color)
}
fun setDividerLoc(dividerLoc: Int) {
mUsageGraph.setDividerLoc(dividerLoc)
}
fun setDividerColors(middleColor: Int, topColor: Int) {
mUsageGraph.setDividerColors(middleColor, topColor)
}
fun setSideLabelWeights(before: Float, after: Float) {
setWeight(R.id.space1, before)
setWeight(R.id.space2, after)
}
private fun setWeight(id: Int, weight: Float) {
val v: LinearLayout = findViewById(id)
val params = v.layoutParams as LinearLayout.LayoutParams
params.weight = weight
v.layoutParams = params
}
fun setSideLabels(labels: Array<CharSequence>) {
if (labels.size != mLabels.size) {
throw IllegalArgumentException("Invalid number of labels")
}
for (i in mLabels.indices) {
mLabels[i].text = labels[i]
}
}
fun setBottomLabels(labels: Array<CharSequence>) {
if (labels.size != mBottomLabels.size) {
throw IllegalArgumentException("Invalid number of labels")
}
for (i in mBottomLabels.indices) {
mBottomLabels[i].text = labels[i]
}
}
}
| mit | 1aa7cd6546b566e84f8853dad2d36f8e | 36.366412 | 121 | 0.65332 | 4.201717 | false | false | false | false |
nkming2/libutils-android | src/androidTest/kotlin/com/nkming/utils/type/ext/ExtensionTest.kt | 1 | 712 | package com.nkming.utils.type.ext
import android.graphics.Point
import org.junit.Assert.*
import org.junit.Test
class ExtensionTest
{
@Test
fun PointPlus()
{
val sbj = Point(1, 0) + Point(5, -2)
assertEquals(6, sbj.x)
assertEquals(-2, sbj.y)
}
@Test
fun PointMinus()
{
val sbj = Point(1, 0) - Point(5, -2)
assertEquals(-4, sbj.x)
assertEquals(2, sbj.y)
}
@Test
fun PointTimes()
{
val sbj = Point(2, -4) * 3f
assertEquals(6, sbj.x)
assertEquals(-12, sbj.y)
}
@Test
fun PointLength()
{
assertEquals(10.0, Point(6, 8).length, .0001)
}
@Test
fun PointDist()
{
val obj1 = Point(1, 1)
val obj2 = Point(5, 3)
assertEquals(Math.sqrt(20.0), obj1.dist(obj2), .0001)
}
}
| mit | 84184ae5b8562e29d06756ba92865a3d | 14.478261 | 55 | 0.633427 | 2.27476 | false | true | false | false |
WeAreFrancis/auth-service | src/main/kotlin/com/wearefrancis/auth/security/Constants.kt | 1 | 450 | package com.wearefrancis.auth.security
const val USER_TARGET_TYPE = "user"
const val CHANGE_ROLE_PERMISSION = "change_role"
const val CREATE_PERMISSION = "create"
const val DELETE_PERMISSION = "delete"
const val ENABLE_PERMISSION = "enable"
const val LOCK_PERMISSION = "lock"
const val UPDATE_PERMISSION = "update"
internal const val BEARER = "Bearer"
internal const val CLAIM_KEY_CREATED = "created"
internal const val CLAIM_KEY_USERNAME = "sub"
| apache-2.0 | cd3417545c3e44fc4d28771f736b81c9 | 31.142857 | 48 | 0.766667 | 3.6 | false | false | false | false |
FlexSeries/FlexLib | src/main/kotlin/me/st28/flexseries/flexlib/message/list/ListBuilder.kt | 1 | 6210 | /**
* Copyright 2016 Stealth2800 <http://stealthyone.com/>
* Copyright 2016 Contributors <https://github.com/FlexSeries>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.st28.flexseries.flexlib.message.list
import me.st28.flexseries.flexlib.message.MasterMessageModule
import me.st28.flexseries.flexlib.message.Message
import me.st28.flexseries.flexlib.message.MessageModule
import me.st28.flexseries.flexlib.plugin.FlexPlugin
import org.bukkit.ChatColor
import org.bukkit.command.CommandSender
import java.util.*
class ListBuilder {
private val masterModule: MasterMessageModule
private var pageItems: Int
private var nextPageCommand: String = ""
private val messages: MutableList<Message> = ArrayList()
private var page: Int = 0
private var pageCount: Int = 0
private var index: Int = 0
private var emptyMessage: String = "&c&oNothing here"
init {
masterModule = FlexPlugin.getGlobalModule(MasterMessageModule::class)!!
pageItems = masterModule.listPageItems
}
/**
* Sets the page information for the builder.
*
* @param page The page to send. Starts at 1 since this is mostly supplied by user input.
* @param elemCount The total number of elements.
*/
fun page(page: Int, elemCount: Int): ListBuilder {
this.page = page - 1
this.pageCount = Math.ceil(elemCount / pageItems.toDouble()).toInt()
return this
}
fun pageItems(count: Int): ListBuilder {
this.pageItems = count
return this
}
fun nextPageCommand(command: String): ListBuilder {
this.nextPageCommand = command
return this
}
fun emptyMessage(message: String): ListBuilder {
this.emptyMessage = message
return this
}
fun header(name: String, vararg replacements: String): ListBuilder {
if (messages.isNotEmpty()) {
throw IllegalStateException("Messages have already been added")
}
val module = FlexPlugin.getGlobalModule(MasterMessageModule::class)
val header = module.listHeaderFormats[name]
val defaultHeader = module.listHeaderFormats["DEFAULT"]
if (header != null) {
messages.add(Message.plain(header.getFormatted(page + 1, pageCount, defaultHeader, *replacements)))
}
return this
}
fun message(message: String): ListBuilder {
messages.add(Message.plain(message))
return this
}
fun message(message: Message): ListBuilder {
messages.add(message)
return this
}
fun element(type: String, vararg replacements: String): ListBuilder {
val format = FlexPlugin.getGlobalModule(MasterMessageModule::class).listElementFormats[type]
?: "Unknown format: '$type'"
messages.add(Message.processed(String.format(MessageModule.setupPatternReplace(format), *replacements)))
return this
}
/**
* Retrieves elements from a specified populator.
*/
fun elements(type: String, populator: (Int) -> Array<String>): ListBuilder {
val index = page * pageItems
for (i in 0 until pageItems) {
try {
element(type, (index + 1 + i).toString(), *populator(index + i))
} catch (ex: IndexOutOfBoundsException) {
// We're done
break
}
}
return this
}
/**
* Similar to setMessagesString, except with direct Message objects
*/
fun messages(populator: (Int) -> Message): ListBuilder {
val index = page * pageItems
for (i in 0 until pageItems) {
try {
messages.add(populator.invoke(index + i))
} catch (ex: IndexOutOfBoundsException) {
// We're done
break
}
}
return this
}
/**
* Sets the messages for a specified page with a closure that receives the current index.
* Should throw an [IndexOutOfBoundsException] upon reaching the final element.
*
* @param page The current page, starting at 0.
*/
fun messagesString(populator: (Int) -> String): ListBuilder {
val index = page * pageItems
for (i in 0 until pageItems) {
try {
messages.add(Message.plain(populator.invoke(index + i)))
} catch (ex: IndexOutOfBoundsException) {
// We're done
break
}
}
return this
}
/**
* Similar to [messagesString] except with direct [Message] objects.
*/
fun messages(collection: Collection<Message>): ListBuilder {
val index = page * pageItems
for (i in 0 until pageItems) {
try {
messages.add(collection.elementAt(index))
} catch (ex: IndexOutOfBoundsException) {
// We're done
break
}
}
return this
}
/**
* Sets the messages for a specified page based on a given collection.
*/
fun messagesString(collection: Collection<String>): ListBuilder {
val index = page * pageItems
for (i in 0 until pageItems) {
try {
messages.add(Message.plain(collection.elementAt(index)))
} catch (ex: IndexOutOfBoundsException) {
// We're done
break
}
}
return this
}
fun sendTo(vararg sender: CommandSender) {
val senders = sender.asList()
if (messages.size <= 1) {
message(emptyMessage)
}
messages.forEach { it.sendTo(senders) }
}
} | apache-2.0 | bd996bcc901dc51212050f668a56ccfc | 30.368687 | 112 | 0.615942 | 4.662162 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.