repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
JashGaming/JashCraft | src/main/java/net/minecraft/server/EntityHorse.java | 39200 | package net.minecraft.server;
import java.util.Iterator;
import java.util.List;
// CraftBukkit start
import org.bukkit.craftbukkit.event.CraftEventFactory;
import org.bukkit.event.entity.EntityDamageEvent;
// CraftBukkit end
public class EntityHorse extends EntityAnimal implements IInventoryListener {
private static final IEntitySelector bu = new EntitySelectorHorse();
public static final IAttribute attributeJumpStrength = (new AttributeRanged("horse.jumpStrength", 0.7D, 0.0D, 2.0D)).a("Jump Strength").a(true); // CraftBukkit - private -> public
private static final String[] bw = new String[] { null, "textures/entity/horse/armor/horse_armor_iron.png", "textures/entity/horse/armor/horse_armor_gold.png", "textures/entity/horse/armor/horse_armor_diamond.png"};
private static final String[] bx = new String[] { "", "meo", "goo", "dio"};
private static final int[] by = new int[] { 0, 5, 7, 11};
private static final String[] bz = new String[] { "textures/entity/horse/horse_white.png", "textures/entity/horse/horse_creamy.png", "textures/entity/horse/horse_chestnut.png", "textures/entity/horse/horse_brown.png", "textures/entity/horse/horse_black.png", "textures/entity/horse/horse_gray.png", "textures/entity/horse/horse_darkbrown.png"};
private static final String[] bA = new String[] { "hwh", "hcr", "hch", "hbr", "hbl", "hgr", "hdb"};
private static final String[] bB = new String[] { null, "textures/entity/horse/horse_markings_white.png", "textures/entity/horse/horse_markings_whitefield.png", "textures/entity/horse/horse_markings_whitedots.png", "textures/entity/horse/horse_markings_blackdots.png"};
private static final String[] bC = new String[] { "", "wo_", "wmo", "wdo", "bdo"};
private int bD;
private int bE;
private int bF;
public int bp;
public int bq;
protected boolean br;
public InventoryHorseChest inventoryChest; // CraftBukkit - private -> public
private boolean bH;
protected int bs;
protected float bt;
private boolean bI;
private float bJ;
private float bK;
private float bL;
private float bM;
private float bN;
private float bO;
private int bP;
private String bQ;
private String[] bR = new String[3];
public int maxDomestication = 100; // CraftBukkit - store max domestication value
public EntityHorse(World world) {
super(world);
this.a(1.4F, 1.6F);
this.fireProof = false;
this.setHasChest(false);
this.getNavigation().a(true);
this.goalSelector.a(0, new PathfinderGoalFloat(this));
this.goalSelector.a(1, new PathfinderGoalPanic(this, 1.2D));
this.goalSelector.a(1, new PathfinderGoalTame(this, 1.2D));
this.goalSelector.a(2, new PathfinderGoalBreed(this, 1.0D));
this.goalSelector.a(4, new PathfinderGoalFollowParent(this, 1.0D));
this.goalSelector.a(6, new PathfinderGoalRandomStroll(this, 0.7D));
this.goalSelector.a(7, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 6.0F));
this.goalSelector.a(8, new PathfinderGoalRandomLookaround(this));
this.loadChest();
}
protected void a() {
super.a();
this.datawatcher.a(16, Integer.valueOf(0));
this.datawatcher.a(19, Byte.valueOf((byte) 0));
this.datawatcher.a(20, Integer.valueOf(0));
this.datawatcher.a(21, String.valueOf(""));
this.datawatcher.a(22, Integer.valueOf(0));
}
public void setType(int i) {
this.datawatcher.watch(19, Byte.valueOf((byte) i));
this.cJ();
}
public int getType() {
return this.datawatcher.getByte(19);
}
public void setVariant(int i) {
this.datawatcher.watch(20, Integer.valueOf(i));
this.cJ();
}
public int getVariant() {
return this.datawatcher.getInt(20);
}
public String getLocalizedName() {
if (this.hasCustomName()) {
return this.getCustomName();
} else {
int i = this.getType();
switch (i) {
case 0:
default:
return LocaleI18n.get("entity.horse.name");
case 1:
return LocaleI18n.get("entity.donkey.name");
case 2:
return LocaleI18n.get("entity.mule.name");
case 3:
return LocaleI18n.get("entity.zombiehorse.name");
case 4:
return LocaleI18n.get("entity.skeletonhorse.name");
}
}
}
private boolean w(int i) {
return (this.datawatcher.getInt(16) & i) != 0;
}
private void b(int i, boolean flag) {
int j = this.datawatcher.getInt(16);
if (flag) {
this.datawatcher.watch(16, Integer.valueOf(j | i));
} else {
this.datawatcher.watch(16, Integer.valueOf(j & ~i));
}
}
public boolean bV() {
return !this.isBaby();
}
public boolean isTame() {
return this.w(2);
}
public boolean ca() {
return this.bV();
}
public String getOwnerName() {
return this.datawatcher.getString(21);
}
public void setOwnerName(String s) {
this.datawatcher.watch(21, s);
}
public float cc() {
int i = this.getAge();
return i >= 0 ? 1.0F : 0.5F + (float) (-24000 - i) / -24000.0F * 0.5F;
}
public void a(boolean flag) {
if (flag) {
this.a(this.cc());
} else {
this.a(1.0F);
}
}
public boolean cd() {
return this.br;
}
public void setTame(boolean flag) {
this.b(2, flag);
}
public void j(boolean flag) {
this.br = flag;
}
public boolean bG() {
return !this.cy() && super.bG();
}
protected void o(float f) {
if (f > 6.0F && this.cg()) {
this.o(false);
}
}
public boolean hasChest() {
return this.w(8);
}
public int cf() {
return this.datawatcher.getInt(22);
}
public int d(ItemStack itemstack) {
return itemstack == null ? 0 : (itemstack.id == Item.HORSE_ARMOR_IRON.id ? 1 : (itemstack.id == Item.HORSE_ARMOR_GOLD.id ? 2 : (itemstack.id == Item.HORSE_ARMOR_DIAMOND.id ? 3 : 0)));
}
public boolean cg() {
return this.w(32);
}
public boolean ch() {
return this.w(64);
}
public boolean ci() {
return this.w(16);
}
public boolean cj() {
return this.bH;
}
public void r(int i) {
this.datawatcher.watch(22, Integer.valueOf(i));
this.cJ();
}
public void k(boolean flag) {
this.b(16, flag);
}
public void setHasChest(boolean flag) {
this.b(8, flag);
}
public void m(boolean flag) {
this.bH = flag;
}
public void n(boolean flag) {
this.b(4, flag);
}
public int getTemper() {
return this.bs;
}
public void setTemper(int i) {
this.bs = i;
}
public int t(int i) {
int j = MathHelper.a(this.getTemper() + i, 0, this.getMaxDomestication());
this.setTemper(j);
return j;
}
public boolean damageEntity(DamageSource damagesource, float f) {
Entity entity = damagesource.getEntity();
return this.passenger != null && this.passenger.equals(entity) ? false : super.damageEntity(damagesource, f);
}
public int aQ() {
return by[this.cf()];
}
public boolean M() {
return this.passenger == null;
}
public boolean cl() {
int i = MathHelper.floor(this.locX);
int j = MathHelper.floor(this.locZ);
this.world.getBiome(i, j);
return true;
}
public void cm() {
if (!this.world.isStatic && this.hasChest()) {
this.b(Block.CHEST.id, 1);
this.setHasChest(false);
}
}
private void cF() {
this.cM();
this.world.makeSound(this, "eating", 1.0F, 1.0F + (this.random.nextFloat() - this.random.nextFloat()) * 0.2F);
}
protected void b(float f) {
if (f > 1.0F) {
this.makeSound("mob.horse.land", 0.4F, 1.0F);
}
int i = MathHelper.f(f * 0.5F - 3.0F);
if (i > 0) {
// CraftBukkit start
EntityDamageEvent event = CraftEventFactory.callEntityDamageEvent(null, this, EntityDamageEvent.DamageCause.FALL, i);
if (!event.isCancelled()) {
float damage = (float) event.getDamage();
if (damage > 0) {
this.getBukkitEntity().setLastDamageCause(event);
this.damageEntity(DamageSource.FALL, damage);
}
}
if (this.passenger != null) {
EntityDamageEvent passengerEvent = CraftEventFactory.callEntityDamageEvent(null, this.passenger, EntityDamageEvent.DamageCause.FALL, i);
if (!passengerEvent.isCancelled() && this.passenger != null) { // Check again in case of plugin
float damage = (float) passengerEvent.getDamage();
if (damage > 0) {
this.passenger.getBukkitEntity().setLastDamageCause(passengerEvent);
this.passenger.damageEntity(DamageSource.FALL, damage);
}
}
// CraftBukkit end
}
int j = this.world.getTypeId(MathHelper.floor(this.locX), MathHelper.floor(this.locY - 0.2D - (double) this.lastYaw), MathHelper.floor(this.locZ));
if (j > 0) {
StepSound stepsound = Block.byId[j].stepSound;
this.world.makeSound(this, stepsound.getStepSound(), stepsound.getVolume1() * 0.5F, stepsound.getVolume2() * 0.75F);
}
}
}
private int cG() {
int i = this.getType();
return this.hasChest() /* && (i == 1 || i == 2) */ ? 17 : 2; // CraftBukkit - Remove type check
}
public void loadChest() { // CraftBukkit - private -> public
InventoryHorseChest inventoryhorsechest = this.inventoryChest;
this.inventoryChest = new InventoryHorseChest("HorseChest", this.cG(), this); // CraftBukkit - add this horse
this.inventoryChest.a(this.getLocalizedName());
if (inventoryhorsechest != null) {
inventoryhorsechest.b(this);
int i = Math.min(inventoryhorsechest.getSize(), this.inventoryChest.getSize());
for (int j = 0; j < i; ++j) {
ItemStack itemstack = inventoryhorsechest.getItem(j);
if (itemstack != null) {
this.inventoryChest.setItem(j, itemstack.cloneItemStack());
}
}
inventoryhorsechest = null;
}
this.inventoryChest.a(this);
this.cI();
}
private void cI() {
if (!this.world.isStatic) {
this.n(this.inventoryChest.getItem(0) != null);
if (this.cv()) {
this.r(this.d(this.inventoryChest.getItem(1)));
}
}
}
public void a(InventorySubcontainer inventorysubcontainer) {
int i = this.cf();
boolean flag = this.co();
this.cI();
if (this.ticksLived > 20) {
if (i == 0 && i != this.cf()) {
this.makeSound("mob.horse.armor", 0.5F, 1.0F);
}
if (!flag && this.co()) {
this.makeSound("mob.horse.leather", 0.5F, 1.0F);
}
}
}
public boolean canSpawn() {
this.cl();
return super.canSpawn();
}
protected EntityHorse a(Entity entity, double d0) {
double d1 = Double.MAX_VALUE;
Entity entity1 = null;
List list = this.world.getEntities(entity, entity.boundingBox.a(d0, d0, d0), bu);
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
Entity entity2 = (Entity) iterator.next();
double d2 = entity2.e(entity.locX, entity.locY, entity.locZ);
if (d2 < d1) {
entity1 = entity2;
d1 = d2;
}
}
return (EntityHorse) entity1;
}
public double getJumpStrength() {
return this.getAttributeInstance(attributeJumpStrength).getValue();
}
protected String aP() {
this.cM();
int i = this.getType();
return i == 3 ? "mob.horse.zombie.death" : (i == 4 ? "mob.horse.skeleton.death" : (i != 1 && i != 2 ? "mob.horse.death" : "mob.horse.donkey.death"));
}
protected int getLootId() {
boolean flag = this.random.nextInt(4) == 0;
int i = this.getType();
return i == 4 ? Item.BONE.id : (i == 3 ? (flag ? 0 : Item.ROTTEN_FLESH.id) : Item.LEATHER.id);
}
protected String aO() {
this.cM();
if (this.random.nextInt(3) == 0) {
this.cO();
}
int i = this.getType();
return i == 3 ? "mob.horse.zombie.hit" : (i == 4 ? "mob.horse.skeleton.hit" : (i != 1 && i != 2 ? "mob.horse.hit" : "mob.horse.donkey.hit"));
}
public boolean co() {
return this.w(4);
}
protected String r() {
this.cM();
if (this.random.nextInt(10) == 0 && !this.bc()) {
this.cO();
}
int i = this.getType();
return i == 3 ? "mob.horse.zombie.idle" : (i == 4 ? "mob.horse.skeleton.idle" : (i != 1 && i != 2 ? "mob.horse.idle" : "mob.horse.donkey.idle"));
}
protected String cp() {
this.cM();
this.cO();
int i = this.getType();
return i != 3 && i != 4 ? (i != 1 && i != 2 ? "mob.horse.angry" : "mob.horse.donkey.angry") : null;
}
protected void a(int i, int j, int k, int l) {
StepSound stepsound = Block.byId[l].stepSound;
if (this.world.getTypeId(i, j + 1, k) == Block.SNOW.id) {
stepsound = Block.SNOW.stepSound;
}
if (!Block.byId[l].material.isLiquid()) {
int i1 = this.getType();
if (this.passenger != null && i1 != 1 && i1 != 2) {
++this.bP;
if (this.bP > 5 && this.bP % 3 == 0) {
this.makeSound("mob.horse.gallop", stepsound.getVolume1() * 0.15F, stepsound.getVolume2());
if (i1 == 0 && this.random.nextInt(10) == 0) {
this.makeSound("mob.horse.breathe", stepsound.getVolume1() * 0.6F, stepsound.getVolume2());
}
} else if (this.bP <= 5) {
this.makeSound("mob.horse.wood", stepsound.getVolume1() * 0.15F, stepsound.getVolume2());
}
} else if (stepsound == Block.h) {
this.makeSound("mob.horse.soft", stepsound.getVolume1() * 0.15F, stepsound.getVolume2());
} else {
this.makeSound("mob.horse.wood", stepsound.getVolume1() * 0.15F, stepsound.getVolume2());
}
}
}
protected void az() {
super.az();
this.aX().b(attributeJumpStrength);
this.getAttributeInstance(GenericAttributes.a).setValue(53.0D);
this.getAttributeInstance(GenericAttributes.d).setValue(0.22499999403953552D);
}
public int bv() {
return 6;
}
public int getMaxDomestication() {
return this.maxDomestication; // CraftBukkit - return stored max domestication instead of 100
}
protected float ba() {
return 0.8F;
}
public int o() {
return 400;
}
private void cJ() {
this.bQ = null;
}
public void f(EntityHuman entityhuman) {
if (!this.world.isStatic && (this.passenger == null || this.passenger == entityhuman) && this.isTame()) {
this.inventoryChest.a(this.getLocalizedName());
entityhuman.openHorseInventory(this, this.inventoryChest);
}
}
public boolean a(EntityHuman entityhuman) {
ItemStack itemstack = entityhuman.inventory.getItemInHand();
if (itemstack != null && itemstack.id == Item.MONSTER_EGG.id) {
return super.a(entityhuman);
} else if (!this.isTame() && this.cy()) {
return false;
} else if (this.isTame() && this.bV() && entityhuman.isSneaking()) {
this.f(entityhuman);
return true;
} else if (this.ca() && this.passenger != null) {
return super.a(entityhuman);
} else {
if (itemstack != null) {
boolean flag = false;
if (this.cv()) {
byte b0 = -1;
if (itemstack.id == Item.HORSE_ARMOR_IRON.id) {
b0 = 1;
} else if (itemstack.id == Item.HORSE_ARMOR_GOLD.id) {
b0 = 2;
} else if (itemstack.id == Item.HORSE_ARMOR_DIAMOND.id) {
b0 = 3;
}
if (b0 >= 0) {
if (!this.isTame()) {
this.cD();
return true;
}
this.f(entityhuman);
return true;
}
}
if (!flag && !this.cy()) {
float f = 0.0F;
short short1 = 0;
byte b1 = 0;
if (itemstack.id == Item.WHEAT.id) {
f = 2.0F;
short1 = 60;
b1 = 3;
} else if (itemstack.id == Item.SUGAR.id) {
f = 1.0F;
short1 = 30;
b1 = 3;
} else if (itemstack.id == Item.BREAD.id) {
f = 7.0F;
short1 = 180;
b1 = 3;
} else if (itemstack.id == Block.HAY_BLOCK.id) {
f = 20.0F;
short1 = 180;
} else if (itemstack.id == Item.APPLE.id) {
f = 3.0F;
short1 = 60;
b1 = 3;
} else if (itemstack.id == Item.CARROT_GOLDEN.id) {
f = 4.0F;
short1 = 60;
b1 = 5;
if (this.isTame() && this.getAge() == 0) {
flag = true;
this.bX();
}
} else if (itemstack.id == Item.GOLDEN_APPLE.id) {
f = 10.0F;
short1 = 240;
b1 = 10;
if (this.isTame() && this.getAge() == 0) {
flag = true;
this.bX();
}
}
if (this.getHealth() < this.getMaxHealth() && f > 0.0F) {
this.heal(f);
flag = true;
}
if (!this.bV() && short1 > 0) {
this.a(short1);
flag = true;
}
if (b1 > 0 && (flag || !this.isTame()) && b1 < this.getMaxDomestication()) {
flag = true;
this.t(b1);
}
if (flag) {
this.cF();
}
}
if (!this.isTame() && !flag) {
if (itemstack != null && itemstack.a(entityhuman, (EntityLiving) this)) {
return true;
}
this.cD();
return true;
}
if (!flag && this.cw() && !this.hasChest() && itemstack.id == Block.CHEST.id) {
this.setHasChest(true);
this.makeSound("mob.chickenplop", 1.0F, (this.random.nextFloat() - this.random.nextFloat()) * 0.2F + 1.0F);
flag = true;
this.loadChest();
}
if (!flag && this.ca() && !this.co() && itemstack.id == Item.SADDLE.id) {
this.f(entityhuman);
return true;
}
if (flag) {
if (!entityhuman.abilities.canInstantlyBuild && --itemstack.count == 0) {
entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, (ItemStack) null);
}
return true;
}
}
if (this.ca() && this.passenger == null) {
if (itemstack != null && itemstack.a(entityhuman, (EntityLiving) this)) {
return true;
} else {
this.h(entityhuman);
return true;
}
} else {
return super.a(entityhuman);
}
}
}
private void h(EntityHuman entityhuman) {
entityhuman.yaw = this.yaw;
entityhuman.pitch = this.pitch;
this.o(false);
this.p(false);
if (!this.world.isStatic) {
entityhuman.mount(this);
}
}
public boolean cv() {
return this.getType() == 0;
}
public boolean cw() {
int i = this.getType();
return i == 2 || i == 1;
}
protected boolean bc() {
return this.passenger != null && this.co() ? true : this.cg() || this.ch();
}
public boolean cy() {
int i = this.getType();
return i == 3 || i == 4;
}
public boolean cz() {
return this.cy() || this.getType() == 2;
}
public boolean c(ItemStack itemstack) {
return false;
}
private void cL() {
this.bp = 1;
}
public void die(DamageSource damagesource) {
super.die(damagesource);
if (!this.world.isStatic) {
this.cE();
}
}
public void c() {
if (this.random.nextInt(200) == 0) {
this.cL();
}
super.c();
if (!this.world.isStatic) {
if (this.random.nextInt(900) == 0 && this.deathTicks == 0) {
this.heal(1.0F);
}
if (!this.cg() && this.passenger == null && this.random.nextInt(300) == 0 && this.world.getTypeId(MathHelper.floor(this.locX), MathHelper.floor(this.locY) - 1, MathHelper.floor(this.locZ)) == Block.GRASS.id) {
this.o(true);
}
if (this.cg() && ++this.bD > 50) {
this.bD = 0;
this.o(false);
}
if (this.ci() && !this.bV() && !this.cg()) {
EntityHorse entityhorse = this.a(this, 16.0D);
if (entityhorse != null && this.e(entityhorse) > 4.0D) {
PathEntity pathentity = this.world.findPath(this, entityhorse, 16.0F, true, false, false, true);
this.setPathEntity(pathentity);
}
}
}
}
public void l_() {
super.l_();
if (this.world.isStatic && this.datawatcher.a()) {
this.datawatcher.e();
this.cJ();
}
if (this.bE > 0 && ++this.bE > 30) {
this.bE = 0;
this.b(128, false);
}
if (!this.world.isStatic && this.bF > 0 && ++this.bF > 20) {
this.bF = 0;
this.p(false);
}
if (this.bp > 0 && ++this.bp > 8) {
this.bp = 0;
}
if (this.bq > 0) {
++this.bq;
if (this.bq > 300) {
this.bq = 0;
}
}
this.bK = this.bJ;
if (this.cg()) {
this.bJ += (1.0F - this.bJ) * 0.4F + 0.05F;
if (this.bJ > 1.0F) {
this.bJ = 1.0F;
}
} else {
this.bJ += (0.0F - this.bJ) * 0.4F - 0.05F;
if (this.bJ < 0.0F) {
this.bJ = 0.0F;
}
}
this.bM = this.bL;
if (this.ch()) {
this.bK = this.bJ = 0.0F;
this.bL += (1.0F - this.bL) * 0.4F + 0.05F;
if (this.bL > 1.0F) {
this.bL = 1.0F;
}
} else {
this.bI = false;
this.bL += (0.8F * this.bL * this.bL * this.bL - this.bL) * 0.6F - 0.05F;
if (this.bL < 0.0F) {
this.bL = 0.0F;
}
}
this.bO = this.bN;
if (this.w(128)) {
this.bN += (1.0F - this.bN) * 0.7F + 0.05F;
if (this.bN > 1.0F) {
this.bN = 1.0F;
}
} else {
this.bN += (0.0F - this.bN) * 0.7F - 0.05F;
if (this.bN < 0.0F) {
this.bN = 0.0F;
}
}
}
private void cM() {
if (!this.world.isStatic) {
this.bE = 1;
this.b(128, true);
}
}
private boolean cN() {
return this.passenger == null && this.vehicle == null && this.isTame() && this.bV() && !this.cz() && this.getHealth() >= this.getMaxHealth();
}
public void e(boolean flag) {
this.b(32, flag);
}
public void o(boolean flag) {
this.e(flag);
}
public void p(boolean flag) {
if (flag) {
this.o(false);
}
this.b(64, flag);
}
private void cO() {
if (!this.world.isStatic) {
this.bF = 1;
this.p(true);
}
}
public void cD() {
this.cO();
String s = this.cp();
if (s != null) {
this.makeSound(s, this.ba(), this.bb());
}
}
public void cE() {
this.a(this, this.inventoryChest);
this.cm();
}
private void a(Entity entity, InventoryHorseChest inventoryhorsechest) {
if (inventoryhorsechest != null && !this.world.isStatic) {
for (int i = 0; i < inventoryhorsechest.getSize(); ++i) {
ItemStack itemstack = inventoryhorsechest.getItem(i);
if (itemstack != null) {
this.a(itemstack, 0.0F);
}
}
}
}
public boolean g(EntityHuman entityhuman) {
this.setOwnerName(entityhuman.getName());
this.setTame(true);
return true;
}
public void e(float f, float f1) {
if (this.passenger != null && this.co()) {
this.lastYaw = this.yaw = this.passenger.yaw;
this.pitch = this.passenger.pitch * 0.5F;
this.b(this.yaw, this.pitch);
this.aP = this.aN = this.yaw;
f = ((EntityLiving) this.passenger).be * 0.5F;
f1 = ((EntityLiving) this.passenger).bf;
if (f1 <= 0.0F) {
f1 *= 0.25F;
this.bP = 0;
}
if (this.onGround && this.bt == 0.0F && this.ch() && !this.bI) {
f = 0.0F;
f1 = 0.0F;
}
if (this.bt > 0.0F && !this.cd() && this.onGround) {
this.motY = this.getJumpStrength() * (double) this.bt;
if (this.hasEffect(MobEffectList.JUMP)) {
this.motY += (double) ((float) (this.getEffect(MobEffectList.JUMP).getAmplifier() + 1) * 0.1F);
}
this.j(true);
this.an = true;
if (f1 > 0.0F) {
float f2 = MathHelper.sin(this.yaw * 3.1415927F / 180.0F);
float f3 = MathHelper.cos(this.yaw * 3.1415927F / 180.0F);
this.motX += (double) (-0.4F * f2 * this.bt);
this.motZ += (double) (0.4F * f3 * this.bt);
this.makeSound("mob.horse.jump", 0.4F, 1.0F);
}
this.bt = 0.0F;
}
this.Y = 1.0F;
this.aR = this.bg() * 0.1F;
if (!this.world.isStatic) {
this.i((float) this.getAttributeInstance(GenericAttributes.d).getValue());
super.e(f, f1);
}
if (this.onGround) {
this.bt = 0.0F;
this.j(false);
}
this.aF = this.aG;
double d0 = this.locX - this.lastX;
double d1 = this.locZ - this.lastZ;
float f4 = MathHelper.sqrt(d0 * d0 + d1 * d1) * 4.0F;
if (f4 > 1.0F) {
f4 = 1.0F;
}
this.aG += (f4 - this.aG) * 0.4F;
this.aH += this.aG;
} else {
this.Y = 0.5F;
this.aR = 0.02F;
super.e(f, f1);
}
}
public void b(NBTTagCompound nbttagcompound) {
super.b(nbttagcompound);
nbttagcompound.setBoolean("EatingHaystack", this.cg());
nbttagcompound.setBoolean("ChestedHorse", this.hasChest());
nbttagcompound.setBoolean("HasReproduced", this.cj());
nbttagcompound.setBoolean("Bred", this.ci());
nbttagcompound.setInt("Type", this.getType());
nbttagcompound.setInt("Variant", this.getVariant());
nbttagcompound.setInt("Temper", this.getTemper());
nbttagcompound.setBoolean("Tame", this.isTame());
nbttagcompound.setString("OwnerName", this.getOwnerName());
nbttagcompound.setInt("Bukkit.MaxDomestication", this.maxDomestication); // CraftBukkit
if (this.hasChest()) {
NBTTagList nbttaglist = new NBTTagList();
for (int i = 2; i < this.inventoryChest.getSize(); ++i) {
ItemStack itemstack = this.inventoryChest.getItem(i);
if (itemstack != null) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setByte("Slot", (byte) i);
itemstack.save(nbttagcompound1);
nbttaglist.add(nbttagcompound1);
}
}
nbttagcompound.set("Items", nbttaglist);
}
if (this.inventoryChest.getItem(1) != null) {
nbttagcompound.set("ArmorItem", this.inventoryChest.getItem(1).save(new NBTTagCompound("ArmorItem")));
}
if (this.inventoryChest.getItem(0) != null) {
nbttagcompound.set("SaddleItem", this.inventoryChest.getItem(0).save(new NBTTagCompound("SaddleItem")));
}
}
public void a(NBTTagCompound nbttagcompound) {
super.a(nbttagcompound);
this.o(nbttagcompound.getBoolean("EatingHaystack"));
this.k(nbttagcompound.getBoolean("Bred"));
this.setHasChest(nbttagcompound.getBoolean("ChestedHorse"));
this.m(nbttagcompound.getBoolean("HasReproduced"));
this.setType(nbttagcompound.getInt("Type"));
this.setVariant(nbttagcompound.getInt("Variant"));
this.setTemper(nbttagcompound.getInt("Temper"));
this.setTame(nbttagcompound.getBoolean("Tame"));
if (nbttagcompound.hasKey("OwnerName")) {
this.setOwnerName(nbttagcompound.getString("OwnerName"));
}
// CraftBukkit start
if (nbttagcompound.hasKey("Bukkit.MaxDomestication")) {
this.maxDomestication = nbttagcompound.getInt("Bukkit.MaxDomestication");
}
// CraftBukkit end
AttributeInstance attributeinstance = this.aX().a("Speed");
if (attributeinstance != null) {
this.getAttributeInstance(GenericAttributes.d).setValue(attributeinstance.b() * 0.25D);
}
if (this.hasChest()) {
NBTTagList nbttaglist = nbttagcompound.getList("Items");
this.loadChest();
for (int i = 0; i < nbttaglist.size(); ++i) {
NBTTagCompound nbttagcompound1 = (NBTTagCompound) nbttaglist.get(i);
int j = nbttagcompound1.getByte("Slot") & 255;
if (j >= 2 && j < this.inventoryChest.getSize()) {
this.inventoryChest.setItem(j, ItemStack.createStack(nbttagcompound1));
}
}
}
ItemStack itemstack;
if (nbttagcompound.hasKey("ArmorItem")) {
itemstack = ItemStack.createStack(nbttagcompound.getCompound("ArmorItem"));
if (itemstack != null && v(itemstack.id)) {
this.inventoryChest.setItem(1, itemstack);
}
}
if (nbttagcompound.hasKey("SaddleItem")) {
itemstack = ItemStack.createStack(nbttagcompound.getCompound("SaddleItem"));
if (itemstack != null && itemstack.id == Item.SADDLE.id) {
this.inventoryChest.setItem(0, itemstack);
}
} else if (nbttagcompound.getBoolean("Saddle")) {
this.inventoryChest.setItem(0, new ItemStack(Item.SADDLE));
}
this.cI();
}
public boolean mate(EntityAnimal entityanimal) {
if (entityanimal == this) {
return false;
} else if (entityanimal.getClass() != this.getClass()) {
return false;
} else {
EntityHorse entityhorse = (EntityHorse) entityanimal;
if (this.cN() && entityhorse.cN()) {
int i = this.getType();
int j = entityhorse.getType();
return i == j || i == 0 && j == 1 || i == 1 && j == 0;
} else {
return false;
}
}
}
public EntityAgeable createChild(EntityAgeable entityageable) {
EntityHorse entityhorse = (EntityHorse) entityageable;
EntityHorse entityhorse1 = new EntityHorse(this.world);
int i = this.getType();
int j = entityhorse.getType();
int k = 0;
if (i == j) {
k = i;
} else if (i == 0 && j == 1 || i == 1 && j == 0) {
k = 2;
}
if (k == 0) {
int l = this.random.nextInt(9);
int i1;
if (l < 4) {
i1 = this.getVariant() & 255;
} else if (l < 8) {
i1 = entityhorse.getVariant() & 255;
} else {
i1 = this.random.nextInt(7);
}
int j1 = this.random.nextInt(5);
if (j1 < 4) {
i1 |= this.getVariant() & '\uff00';
} else if (j1 < 8) {
i1 |= entityhorse.getVariant() & '\uff00';
} else {
i1 |= this.random.nextInt(5) << 8 & '\uff00';
}
entityhorse1.setVariant(i1);
}
entityhorse1.setType(k);
double d0 = this.getAttributeInstance(GenericAttributes.a).b() + entityageable.getAttributeInstance(GenericAttributes.a).b() + (double) this.cP();
entityhorse1.getAttributeInstance(GenericAttributes.a).setValue(d0 / 3.0D);
double d1 = this.getAttributeInstance(attributeJumpStrength).b() + entityageable.getAttributeInstance(attributeJumpStrength).b() + this.cQ();
entityhorse1.getAttributeInstance(attributeJumpStrength).setValue(d1 / 3.0D);
double d2 = this.getAttributeInstance(GenericAttributes.d).b() + entityageable.getAttributeInstance(GenericAttributes.d).b() + this.cR();
entityhorse1.getAttributeInstance(GenericAttributes.d).setValue(d2 / 3.0D);
return entityhorse1;
}
public GroupDataEntity a(GroupDataEntity groupdataentity) {
Object object = super.a(groupdataentity);
boolean flag = false;
int i = 0;
int j;
if (object instanceof GroupDataHorse) {
j = ((GroupDataHorse) object).a;
i = ((GroupDataHorse) object).b & 255 | this.random.nextInt(5) << 8;
} else {
if (this.random.nextInt(10) == 0) {
j = 1;
} else {
int k = this.random.nextInt(7);
int l = this.random.nextInt(5);
j = 0;
i = k | l << 8;
}
object = new GroupDataHorse(j, i);
}
this.setType(j);
this.setVariant(i);
if (this.random.nextInt(5) == 0) {
this.setAge(-24000);
}
if (j != 4 && j != 3) {
this.getAttributeInstance(GenericAttributes.a).setValue((double) this.cP());
if (j == 0) {
this.getAttributeInstance(GenericAttributes.d).setValue(this.cR());
} else {
this.getAttributeInstance(GenericAttributes.d).setValue(0.17499999701976776D);
}
} else {
this.getAttributeInstance(GenericAttributes.a).setValue(15.0D);
this.getAttributeInstance(GenericAttributes.d).setValue(0.20000000298023224D);
}
if (j != 2 && j != 1) {
this.getAttributeInstance(attributeJumpStrength).setValue(this.cQ());
} else {
this.getAttributeInstance(attributeJumpStrength).setValue(0.5D);
}
this.setHealth(this.getMaxHealth());
return (GroupDataEntity) object;
}
protected boolean bf() {
return true;
}
public void u(int i) {
if (this.co()) {
// CraftBukkit start - fire HorseJumpEvent, use event power
if (i < 0) {
i = 0;
}
float power;
if (i >= 90) {
power = 1.0F;
} else {
power = 0.4F + 0.4F * (float) i / 90.0F;
}
org.bukkit.event.entity.HorseJumpEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callHorseJumpEvent(this, power);
if (!event.isCancelled()) {
this.bI = true;
this.cO();
this.bt = event.getPower();
}
// CraftBukkit end
}
}
public void W() {
super.W();
if (this.bM > 0.0F) {
float f = MathHelper.sin(this.aN * 3.1415927F / 180.0F);
float f1 = MathHelper.cos(this.aN * 3.1415927F / 180.0F);
float f2 = 0.7F * this.bM;
float f3 = 0.15F * this.bM;
this.passenger.setPosition(this.locX + (double) (f2 * f), this.locY + this.Y() + this.passenger.X() + (double) f3, this.locZ - (double) (f2 * f1));
if (this.passenger instanceof EntityLiving) {
((EntityLiving) this.passenger).aN = this.aN;
}
}
}
private float cP() {
return 15.0F + (float) this.random.nextInt(8) + (float) this.random.nextInt(9);
}
private double cQ() {
return 0.4000000059604645D + this.random.nextDouble() * 0.2D + this.random.nextDouble() * 0.2D + this.random.nextDouble() * 0.2D;
}
private double cR() {
return (0.44999998807907104D + this.random.nextDouble() * 0.3D + this.random.nextDouble() * 0.3D + this.random.nextDouble() * 0.3D) * 0.25D;
}
public static boolean v(int i) {
return i == Item.HORSE_ARMOR_IRON.id || i == Item.HORSE_ARMOR_GOLD.id || i == Item.HORSE_ARMOR_DIAMOND.id;
}
public boolean e() {
return false;
}
}
| gpl-2.0 |
FauxFaux/jdk9-jdk | test/java/lang/invoke/VarHandles/VarHandleTestAccessModeMethodNames.java | 2088 | /*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @run testng VarHandleTestAccessModeMethodNames
*/
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.lang.invoke.VarHandle;
import java.util.stream.Stream;
import static org.testng.Assert.assertEquals;
public class VarHandleTestAccessModeMethodNames {
@DataProvider
public static Object[][] accessModesProvider() {
return Stream.of(VarHandle.AccessMode.values()).
map(am -> new Object[]{am}).
toArray(Object[][]::new);
}
@Test(dataProvider = "accessModesProvider")
public void testMethodName(VarHandle.AccessMode am) {
assertEquals(am.methodName(), toMethodName(am.name()));
}
private static String toMethodName(String name) {
StringBuilder s = new StringBuilder(name.toLowerCase());
int i;
while ((i = s.indexOf("_")) != -1) {
s.deleteCharAt(i);
s.setCharAt(i, Character.toUpperCase(s.charAt(i)));
}
return s.toString();
}
}
| gpl-2.0 |
outlying/weiter | app/src/main/java/com/antyzero/weiter/ui/adapter/ProductsAdapter.java | 4859 | package com.antyzero.weiter.ui.adapter;
import android.content.Context;
import android.content.res.Resources;
import android.util.LongSparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.antyzero.weiter.R;
import com.antyzero.weiter.VendSpaceApplication;
import com.antyzero.weiter.model.Order;
import com.antyzero.weiter.network.model.Product;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
/**
* Created by tornax on 18.10.14.
*/
public class ProductsAdapter extends BaseAdapter {
private final Resources resources;
private final long vendorId;
@Inject
Picasso picasso;
private final List<Product> productList;
private final LayoutInflater layoutInflater;
private final LongSparseArray<Integer> orderCount = new LongSparseArray<>();
/**
* @param context
* @param productList
*/
public ProductsAdapter( Context context, long vendorId, List<Product> productList ) {
this.vendorId = vendorId;
if( productList == null ) {
throw new IllegalArgumentException( "List cannot be null" );
}
VendSpaceApplication.get( context ).objectGraph().inject( this );
this.productList = productList;
this.layoutInflater = LayoutInflater.from( context );
this.resources = context.getResources();
}
@Override
public int getCount() {
return productList.size();
}
@Override
public Product getItem( int position ) {
return productList.get( position );
}
@Override
public long getItemId( int position ) {
return getItem( position ).getId();
}
@Override
public View getView( int position, View convertView, ViewGroup parent ) {
ViewHolder viewHolder;
if( convertView == null ) {
convertView = layoutInflater.inflate( R.layout.adapter_item_product_order, parent, false );
viewHolder = new ViewHolder( convertView );
convertView.setTag( viewHolder );
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Product product = getItem( position );
picasso.load( product.getImageUrl() ).into( viewHolder.imageView );
viewHolder.textViewTitle.setText( product.getName() );
final long productId = product.getId();
if( orderCount.indexOfKey( productId ) < 0 ) {
viewHolder.textViewCounter.setText( "0" );
} else {
viewHolder.textViewCounter.setText( String.valueOf( orderCount.get( productId ) ) );
}
viewHolder.buttonDown.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick( View v ) {
Integer oldValue = orderCount.get( productId );
if( oldValue == null ){
oldValue = 0;
}
if( oldValue > 0 ) {
orderCount.put( productId, oldValue - 1 );
}
notifyDataSetChanged();
}
} );
viewHolder.buttonUp.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick( View v ) {
Integer oldValue = orderCount.get( productId );
if(oldValue == null){
oldValue = 0;
}
orderCount.put( productId, oldValue + 1 );
notifyDataSetChanged();
}
} );
return convertView;
}
/**
*
* @return
*/
public List<Order> collectOrder(){
List<Order> orders = new ArrayList<>();
for( int i = 0; i < orderCount.size(); i++ ){
long productId = orderCount.keyAt( i );
Integer amount = orderCount.valueAt( i );
orders.add( new Order(vendorId, productId, amount, "TODO" ) );
}
return orders;
}
/**
* ViewHolder pattern
*/
private static class ViewHolder {
private final TextView textViewTitle;
private final TextView textViewCounter;
private final ImageView imageView;
private final View buttonDown;
private final View buttonUp;
private ViewHolder( View view ) {
textViewTitle = (TextView) view.findViewById( R.id.textViewTitle );
textViewCounter = (TextView) view.findViewById( R.id.textViewCounter );
imageView = (ImageView) view.findViewById( R.id.imageView );
buttonDown = view.findViewById( R.id.buttonDown );
buttonUp = view.findViewById( R.id.buttonUp );
}
}
}
| gpl-2.0 |
adamfisk/littleshoot-util | src/main/java/org/littleshoot/util/HttpParamKeys.java | 889 | package org.littleshoot.util;
public class HttpParamKeys
{
public static final String KEYWORDS = "keywords";
public static final String START_PAGE = "startPage";
public static final String ITEMS_PER_PAGE = "itemsPerPage";
public static final String OS = "os";
public static final String APPLICATIONS = "applications";
public static final String AUDIO = "audio";
public static final String DOCUMENTS = "documents";
public static final String IMAGES = "images";
public static final String VIDEO = "video";
public static final String USER_ID = "userId";
public static final String INSTANCE_ID = "instanceId";
public static final String GROUP_NAME = "groupName";
public static final String TIME_ZONE = "timeZone";
public static final String SIGNATURE = "signature";
public static final String KEY_ID = "keyId";
}
| gpl-2.0 |
as-ideas/crowdsource | crowdsource-integrationtests/src/test/java/de/asideas/crowdsource/testsupport/pageobjects/LogoutPage.java | 1258 | package de.asideas.crowdsource.testsupport.pageobjects;
import de.asideas.crowdsource.testsupport.selenium.SeleniumWait;
import de.asideas.crowdsource.testsupport.selenium.WebDriverProvider;
import de.asideas.crowdsource.testsupport.util.UrlProvider;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated;
@Component
public class LogoutPage {
@Autowired
private WebDriverProvider webDriverProvider;
@Autowired
private UrlProvider urlProvider;
@Autowired
private SeleniumWait wait;
@FindBy(className = "relogin")
private WebElement reloginLink;
public void waitForPageLoad() {
wait.until(presenceOfElementLocated(By.cssSelector(".logout-success")));
}
public void open() {
WebDriver webDriver = webDriverProvider.provideDriver();
// logout
webDriver.get(urlProvider.applicationUrl() + "/#/logout");
}
public void clickRelogin() {
reloginLink.click();
}
}
| gpl-2.0 |
Trugath/jdalvikvm | src/main/java/com/github/trugath/jdalvikvm/ChangeThreadException.java | 1348 | /*
* Developed by Koji Hisano <koji.hisano@eflow.jp>
*
* Copyright (C) 2009 eflow Inc. <http://www.eflow.jp/en/>
*
* This file is a part of Android Dalvik VM on Java.
* http://code.google.com/p/android-dalvik-vm-on-java/
*
* This project is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This project is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.github.trugath.jdalvikvm;
// This class is used to change threads and not used as a normal exception.
final class ChangeThreadException extends RuntimeException {
private final Throwable throwable;
ChangeThreadException() {
this(null);
}
ChangeThreadException(final Throwable throwable) {
this.throwable = throwable;
}
public Throwable getCause() {
return throwable;
}
}
| gpl-2.0 |
xuie0000/vlc-code-42fadbb | vlc-android/src/org/videolan/vlc/util/SubtitlesDownloader.java | 23901 | /*
* ************************************************************************
* SubtatlesDownloader.java
* *************************************************************************
* Copyright © 2016 VLC authors and VideoLAN
* Author: Geoffrey Métais
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*
* *************************************************************************
*/
package org.videolan.vlc.util;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import org.videolan.libvlc.util.AndroidUtil;
import org.videolan.vlc.BuildConfig;
import org.videolan.vlc.R;
import org.videolan.vlc.VLCApplication;
import org.videolan.vlc.gui.helpers.UiTools;
import org.videolan.vlc.media.MediaWrapper;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.Set;
import java.util.zip.GZIPInputStream;
import de.timroes.axmlrpc.XMLRPCClient;
import de.timroes.axmlrpc.XMLRPCException;
public class SubtitlesDownloader {
private static final int DIALOG_SHOW = 1;
private static final int DIALOG_HIDE = 2;
private static final int DIALOG_UPDATE_PROGRESS = 3;
private static final int DIALOG_UPDATE_MSG = 4;
private final String TAG = "VLC/SubtitlesDownloader";
private final String OpenSubtitlesAPIUrl = "http://api.opensubtitles.org/xml-rpc";
private final String HTTP_USER_AGENT = "VLSub";
private final String USER_AGENT = "VLSub 0.9";
private HashMap<String, Object> map = null;
private XMLRPCClient mClient;
private String mToken = null;
private Activity mContext;
private ProgressDialog mDialog;
private volatile boolean stop = false;
private AlertDialog mSumUpDialog;
public void setActivity(Activity activity) {
mContext = activity;
}
public void downloadSubs(final List<MediaWrapper> mediaList) {
stop = false;
Set<String> languages = Collections.singleton(Locale.getDefault().getISO3Language().toLowerCase());
if (AndroidUtil.isHoneycombOrLater()) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mContext);
languages = pref.getStringSet("languages_download_list", languages);
}
final ArrayList<String> finalLanguages = new ArrayList<>(languages);
VLCApplication.runBackground(new Runnable() {
@Override
public void run() {
if (logIn()){
getSubtitles(mediaList, finalLanguages);
}
mHandler.sendEmptyMessage(DIALOG_HIDE);
}
});
}
private void exit() {
logOut();
}
@SuppressWarnings("unchecked")
private boolean logIn() {
mHandler.sendEmptyMessage(DIALOG_SHOW);
try {
mClient = new XMLRPCClient(new URL(OpenSubtitlesAPIUrl));
map = ((HashMap<String, Object>) mClient.call("LogIn","","","fre",USER_AGENT));
mToken = (String) map.get("token");
} catch (XMLRPCException e) {
if (BuildConfig.DEBUG) Log.e(TAG, "logIn", e);
showSnackBar(R.string.service_unavailable);
mHandler.sendEmptyMessage(DIALOG_HIDE);
stop = true;
return false;
} catch (Throwable e){ //for various service outages
if (BuildConfig.DEBUG) Log.e(TAG, "logIn", e);
e.printStackTrace();
showSnackBar(R.string.service_unavailable);
mHandler.sendEmptyMessage(DIALOG_HIDE);
stop = true;
return false;
}
map = null;
return true;
}
@SuppressWarnings("unchecked")
private void logOut() {
if (mToken == null)
return;
try {
map = ((HashMap<String, Object>) mClient.call("LogOut", mToken));
} catch (Throwable e){ //for various service outages
Log.w("subtitles", "XMLRPCException", e);
}
mToken = null;
map = null;
}
@SuppressWarnings("unchecked")
private void getSubtitles(final List<MediaWrapper> mediaList, List<String> languages) {
mHandler.obtainMessage(DIALOG_UPDATE_MSG,R.string.downloading_subtitles, 0).sendToTarget();
for (String language : languages)
language = getCompliantLanguageID(language);
final boolean single = mediaList.size() == 1;
ArrayList<MediaWrapper> notFoundFiles = new ArrayList<>();
HashMap<String, String> index = new HashMap<>();
HashMap<String, ArrayList<String>> success = new HashMap<>();
HashMap<String, ArrayList<String>> fails = new HashMap<>();
ArrayList<HashMap<String, String>> videoSearchList = prepareRequestList(mediaList, languages, index, true);
Object[] subtitleMaps;
try {
map = (HashMap<String, Object>) mClient.call("SearchSubtitles", mToken, videoSearchList);
} catch (Throwable e) { //for various service outages
stop = true;
showSnackBar(R.string.service_unavailable);
return;
}
if(!stop && map.get("data") instanceof Object[]) {
subtitleMaps = ((Object[]) map.get("data"));
if (!single)
mHandler.obtainMessage(DIALOG_UPDATE_PROGRESS, mediaList.size(), 0).sendToTarget();
if (subtitleMaps.length > 0){
String srtFormat, movieHash, fileUrl, fileName, subLanguageID, subDownloadLink;
for (Object map : subtitleMaps){
if (stop)
break;
srtFormat = ((HashMap<String, String>) map).get("SubFormat");
movieHash = ((HashMap<String, String>) map).get("MovieHash");
subLanguageID = ((HashMap<String, String>) map).get("SubLanguageID");
subDownloadLink = ((HashMap<String, String>) map).get("SubDownloadLink");
fileUrl = index.get(movieHash);
fileName = fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
if (success.containsKey(fileName) && success.get(fileName).contains(subLanguageID)){
continue;
} else {
if (success.containsKey(fileName))
success.get(fileName).add(subLanguageID);
else {
ArrayList<String> newLanguage = new ArrayList<>();
newLanguage.add(subLanguageID);
success.put(fileName, newLanguage);
}
}
downloadSubtitles(subDownloadLink, fileUrl, fileName, srtFormat, subLanguageID);
if (!single)
mHandler.obtainMessage(DIALOG_UPDATE_PROGRESS, mediaList.size(), success.size()).sendToTarget();
}
}
}
if (videoSearchList != null)
videoSearchList.clear();
index.clear();
//Second pass
for (MediaWrapper media : mediaList){
String fileName = media.getUri().getLastPathSegment();
if (!success.containsKey(fileName))
notFoundFiles.add(media);
}
if (!stop && !notFoundFiles.isEmpty() &&
!(videoSearchList = prepareRequestList(notFoundFiles, languages, index, false)).isEmpty()) {
try {
map = (HashMap<String, Object>) mClient.call("SearchSubtitles", mToken,
videoSearchList);
} catch (Throwable e) { //for various service outages
stop = true;
showSnackBar(R.string.service_unavailable);
return;
}
if (map.get("data") instanceof Object[]) {
subtitleMaps = ((Object[]) map.get("data"));
if (subtitleMaps.length > 0) {
String srtFormat, fileUrl, fileName, subLanguageID, subDownloadLink;
HashMap<String, Object> resultMap;
Object[] paths = index.values().toArray();
for (int i = 0; i < subtitleMaps.length; ++i) {
if (stop)
break;
resultMap = (HashMap<String, Object>) subtitleMaps[i];
srtFormat = (String) resultMap.get("SubFormat");
Integer queryNumber = (Integer) resultMap.get("QueryNumber");
subLanguageID = (String) resultMap.get("SubLanguageID");
subDownloadLink = (String) resultMap.get("SubDownloadLink");
fileUrl = (String) paths[queryNumber.intValue()/languages.size()];
if (fileUrl == null) //we keep only result for exact matching name
continue;
fileName = fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
if (success.containsKey(fileName) && success.get(fileName).contains(subLanguageID)){
continue;
} else {
if (success.containsKey(fileName))
success.get(fileName).add(subLanguageID);
else {
ArrayList<String> newLanguage = new ArrayList<>();
newLanguage.add(subLanguageID);
success.put(fileName, newLanguage);
}
}
downloadSubtitles(subDownloadLink, fileUrl, fileName, srtFormat, subLanguageID);
if (!single)
mHandler.obtainMessage(DIALOG_UPDATE_PROGRESS, mediaList.size(), success.size()).sendToTarget();
}
}
}
}
//fill fails list
for (MediaWrapper media : mediaList){
String fileName;
fileName = media.getUri().getLastPathSegment();
if (!success.containsKey(fileName)){
ArrayList<String> langs = new ArrayList<>();
for (String language : languages) {
langs.add(getCompliantLanguageID(language));
}
fails.put(fileName, langs);
} else {
ArrayList<String> langs = new ArrayList<>();
for (String language : languages) {
String langID = getCompliantLanguageID(language);
if (!success.get(fileName).contains(langID)){
langs.add(langID);
}
}
if (!langs.isEmpty())
fails.put(fileName, langs);
}
}
if (!stop) {
if (single){
stop = true;
showSnackBar(buildSumup(success, fails, true));
} else {
showSumup(buildSumup(success, fails, false));
}
}
logOut();
}
private void downloadSubtitles(String subUrl, String path, String name, String subFormat, String language){
if (mToken == null || path == null)
return;
final File parent = new File(path).getParentFile();
boolean canWrite = !path.startsWith("smb://") && !path.startsWith("http://") && parent != null && parent.canWrite();
String fileUrl;
StringBuilder sb = new StringBuilder();
if (canWrite){
fileUrl = path;
sb.append(fileUrl.substring(0,fileUrl.lastIndexOf('.')+1)).append(language).append('.').append(subFormat);
} else{
fileUrl = name;
sb.append(VLCApplication.getAppContext().getFilesDir().getPath()).append('/').append(fileUrl).append('.').append(language).append('.').append(subFormat);
}
String srtURl = sb.toString();
FileOutputStream f = null;
InputStream in = null;
GZIPInputStream gzIS = null;
URL url;
HttpURLConnection urlConnection;
try {
url = new URL(subUrl);
urlConnection = (HttpURLConnection) url.openConnection();
// We get the first matching subtitle
f = new FileOutputStream(new File(srtURl));
//Base64 then gunzip uncompression
gzIS = new GZIPInputStream(urlConnection.getInputStream());
int length;
byte[] buffer = new byte[1024];
while ((length = gzIS.read(buffer)) != -1) {
f.write(buffer, 0, length);
}
// TODO Update the media database
} catch (IOException e) {
if (BuildConfig.DEBUG) Log.e(TAG, "download fail", e);
} catch (Throwable e) { //for various service outages
if (BuildConfig.DEBUG) Log.e(TAG, "download fail", e);
}finally{
Util.close(f);
Util.close(in);
Util.close(gzIS);
}
return;
}
private ArrayList<HashMap<String, String>> prepareRequestList(List<MediaWrapper> mediaList, List<String> languages, HashMap<String, String> index, boolean firstPass) {
ArrayList<HashMap<String, String>> videoSearchList = new ArrayList<>();
for (MediaWrapper media : mediaList) {
if (stop)
break;
String hash = null, tag = null;
long fileLength = 0;
Uri mediaUri = media.getUri();
if (firstPass) {
if (TextUtils.equals(mediaUri.getScheme(), "file") && FileUtils.canWrite(mediaUri.toString())) {
File videoFile = new File(mediaUri.getPath());
hash = FileUtils.computeHash(videoFile);
fileLength = videoFile.length();
} //TODO network files
if (hash == null)
continue;
} else { //Second pass, search by TAG (filename)
tag = mediaUri.getLastPathSegment();
}
HashMap<String, String> video;
for (String item : languages){
if (stop)
break;
String languageID = getCompliantLanguageID(item);
video = new HashMap<>();
video.put("sublanguageid", languageID);
if (firstPass){
index.put(hash, mediaUri.getPath());
video.put("moviehash", hash);
video.put("moviebytesize", String.valueOf(fileLength));
} else {
video.put("tag", tag);
int dotPos = tag.lastIndexOf('.');
if (dotPos > -1)
index.put(tag.substring(0, dotPos), mediaUri.getPath());
else
index.put(tag, mediaUri.getPath());
}
videoSearchList.add(video);
}
}
return videoSearchList;
}
private void showSumup(final String displayText) {
if (mContext == null)
return;
mHandler.post(new Runnable(){
public void run() {
mSumUpDialog = new AlertDialog.Builder(mContext).setTitle(R.string.dialog_subloader_sumup)
.setMessage(displayText)
.setCancelable(true)
.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
exit();
}
})
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
exit();
}
}).create();
//We catch these exceptions because context might disappear while loading/showing the dialog, no matter if we wipe it in onPause()
try{
mSumUpDialog.show();
} catch (IllegalArgumentException | WindowManager.BadTokenException e){
e.printStackTrace();
}
}
});
}
private String buildSumup(HashMap<String, ArrayList<String>> success, HashMap<String, ArrayList<String>> fails, boolean single) {
StringBuilder textToDisplay = new StringBuilder();
if (single){ // Text for the toast
for (Entry<String, ArrayList<String>> entry : success.entrySet()) {
textToDisplay.append(VLCApplication.getAppResources().getString(R.string.snack_subloader_sub_found));
if (entry.getValue().size() > 1)
textToDisplay.append(" ").append(entry.getValue().toString()).append("\n");
}
for (Entry<String, ArrayList<String>> entry : fails.entrySet()){
textToDisplay.append(VLCApplication.getAppResources().getString(R.string.snack_subloader_sub_not_found));
if (entry.getValue().size() > 1)
textToDisplay.append(" ").append(entry.getValue().toString()).append("\n");
}
} else { // Text for the dialog box
if (success.size()>0){
textToDisplay.append(VLCApplication.getAppResources().getString(R.string.dialog_subloader_success)).append("\n");
for (Entry<String, ArrayList<String>> entry : success.entrySet()){
ArrayList<String> langs = entry.getValue();
String filename = entry.getKey();
textToDisplay.append("\n- ").append(filename).append(" ").append(langs.toString());
}
if (fails.size()>0)
textToDisplay.append("\n\n");
}
if (fails.size()>0){
textToDisplay.append(VLCApplication.getAppResources().getString(R.string.dialog_subloader_fails)).append("\n");
for (Entry<String, ArrayList<String>> entry : fails.entrySet()){
ArrayList<String> langs = entry.getValue();
String filename = entry.getKey();
textToDisplay.append("\n- ").append(filename).append(" ").append(langs.toString());
}
}
}
return textToDisplay.toString();
}
// Locale ID Control, because of OpenSubtitle support of ISO639-2 codes
// e.g. French ID can be 'fra' or 'fre', OpenSubtitles considers 'fre' but Android Java Locale provides 'fra'
private String getCompliantLanguageID(String language){
if (language.equals("system"))
return getCompliantLanguageID(Locale.getDefault().getISO3Language());
if (language.equals("fra"))
return "fre";
if (language.equals("deu"))
return "ger";
if (language.equals("zho"))
return "chi";
if (language.equals("ces"))
return "cze";
if (language.equals("fas"))
return "per";
if (language.equals("nld"))
return "dut";
if (language.equals("ron"))
return "rum";
if (language.equals("slk"))
return "slo";
return language;
}
private void showSnackBar(int stringId) {
if (mContext == null)
return;
showSnackBar(VLCApplication.getAppResources().getString(stringId));
}
private void showSnackBar(final String text) {
if (mContext == null)
return;
if (mContext instanceof AppCompatActivity) {
mHandler.post(new Runnable() {
@Override
public void run() {
View v = mContext.findViewById(R.id.fragment_placeholder);
if (v == null)
v = mContext.getWindow().getDecorView();
UiTools.snacker(v, text);
}
});
} else {
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(mContext, text, Toast.LENGTH_SHORT).show();
}
});
}
}
Handler mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
if (mContext == null || mContext.isFinishing())
return;
switch (msg.what) {
case DIALOG_SHOW:
mDialog = ProgressDialog.show(mContext, "Subs download", "Connecting...", true);
mDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
stop = true;
}
});
break;
case DIALOG_HIDE:
if (mDialog != null && mDialog.isShowing())
try {
mDialog.dismiss();
} catch (IllegalArgumentException e) {
//Activity is lost, we remove references to prevent leaks
mDialog = null;
mContext = null;
}
break;
case DIALOG_UPDATE_PROGRESS:
if (mDialog != null && mDialog.isShowing()) {
try {
mDialog.setIndeterminate(false);
mDialog.setMax(msg.arg1);
mDialog.setProgress(msg.arg2);
} catch (IllegalArgumentException e) {
//Activity is lost, we remove references to prevent leaks
mDialog = null;
mContext = null;
}
}
break;
case DIALOG_UPDATE_MSG:
if (mDialog != null && mDialog.isShowing()) {
mDialog.setMessage(VLCApplication.getAppResources().getString(msg.arg1));
}
break;
}
}
};
}
| gpl-2.0 |
antoniofabio/iDMC | src/java/org/tsho/dmc2/ui/basin/BasinComponent.java | 7104 | /*
* iDMC the interactive Dynamical Model Calculator simulates and performs
* graphical and numerical analysis of systems of differential and
* difference equations.
*
* Copyright (C) 2004 Marji Lines and Alfredo Medio.
*
* Written by Daniele Pizzoni <auouo@tin.it>.
* Extended by Alexei Grigoriev <alexei_grigoriev@libero.it>.
*
*
*
* The software program was developed within a research project financed
* by the Italian Ministry of Universities, the Universities of Udine and
* Ca'Foscari of Venice, the Friuli-Venezia Giulia Region.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or 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.
*/
package org.tsho.dmc2.ui.basin;
import javax.swing.Action;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JToolBar;
import javax.swing.ButtonGroup;
import javax.swing.JRadioButtonMenuItem;
import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import org.jfree.data.Range;
import org.tsho.dmc2.core.chart.BasinRenderer;
import org.tsho.dmc2.core.VariableDoubles;
import org.tsho.dmc2.core.model.Model;
import org.tsho.dmc2.core.model.SimpleMap;
import org.tsho.dmc2.managers.BasinManager;
import org.tsho.dmc2.sm.Input;
import org.tsho.dmc2.ui.AbstractPlotComponent;
import org.tsho.dmc2.ui.MainFrame;
import org.tsho.dmc2.core.util.*;
import org.tsho.dmc2.core.chart.ColorSettings;
public class BasinComponent extends AbstractPlotComponent
implements BasinSMItf {
private final BasinControlForm2 privateControlForm;
private BasinManager manager;
private final Action startAction = new StartAction();
private final Action stopAction = new StopAction();
private final Action clearAction = new ClearAction();
private class ColorSettingsAction extends AbstractAction {
public ColorSettingsAction() {
putValue(NAME, "Color settings...");
putValue(MNEMONIC_KEY, new Integer(KeyEvent.VK_C));
putValue(SHORT_DESCRIPTION, "Edit color settings");
}
public void actionPerformed(ActionEvent ae) {
BasinRenderer plotRenderer = manager.getPlotRenderer();
ColorSettingsDialog csd = new ColorSettingsDialog(
plotRenderer.getColorSettings());
csd.show();
plotRenderer.setColorSettings(csd.getColorSettings());
if(plotRenderer.getGrid()!=null) {//some data already computed
plotRenderer.drawImage();
manager.getChartPanel().repaint();
}
}
};
private final Action colorSettingsAction = new ColorSettingsAction();
public BasinComponent(final SimpleMap model,MainFrame mainFrame) {
super(model,mainFrame);
privateControlForm = new BasinControlForm2(model,this);
controlForm = privateControlForm;
manager = new BasinManager(this);
init(manager,
new BasinFrameSM(this),
controlForm, "Basin of attraction");
stateMachine.addSensibleItem(controlForm);
stateMachine.parseInput(Input.go);
finishInit(controlForm);
}
protected JMenu createPlotMenu() {
JMenu menu;
menu = new JMenu("Plot");
ButtonGroup group;
group = new ButtonGroup();
JRadioButtonMenuItem menuItem = new JRadioButtonMenuItem("Fast algorithm");
menuItem.setMnemonic(KeyEvent.VK_F);
group.add(menuItem);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
//change flag in basin control form and in basin renderer
BasinRenderer plotRenderer=manager.getPlotRenderer();
plotRenderer.setType(BasinRenderer.FAST_ALGORITHM);
privateControlForm.setType(BasinRenderer.FAST_ALGORITHM);
controlForm.updateSamplesMenu();
}
});
menuItem.setSelected(true);
menuItem = new JRadioButtonMenuItem("Slow algorithm");
menuItem.setMnemonic(KeyEvent.VK_S);
group.add(menuItem);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
//change flag in basin control form and in basin renderer
BasinRenderer plotRenderer=manager.getPlotRenderer();
plotRenderer.setType(BasinRenderer.SLOW_ALGORITHM);
privateControlForm.setType(BasinRenderer.SLOW_ALGORITHM);
privateControlForm.updateSamplesMenu();
}
});
menu.addSeparator();
menu.add(colorSettingsAction);
return menu;
}
public JMenu createCommandMenu() {
JMenu menu;
JMenuItem menuItem;
/* Command menu */
menu = new JMenu("Command");
/* start */
menuItem = new JMenuItem();
menuItem.setAction(startAction);
menu.add(menuItem);
/* stop */
menuItem = new JMenuItem();
menuItem.setAction(stopAction);
menu.add(menuItem);
menuItem = new JMenuItem();
menuItem.setAction(clearAction);
menu.add(menuItem);
/* Plot menu */
//menu = createPlotMenu();
return menu;
}
public JToolBar createToolBar() {
JToolBar toolBar = new JToolBar();
JButton button;
button = new JButton(startAction);
toolBar.add(button);
button = new JButton(stopAction);
toolBar.add(button);
toolBar.addSeparator();
button = new JButton(clearAction);
toolBar.add(button);
return toolBar;
}
protected void fillDefaults(int index) {}
/**
* @return
*/
public Action getClearAction() {
return clearAction;
}
/**
* @return
*/
public Action getStartAction() {
return startAction;
}
/**
* @return
*/
public Action getStopAction() {
return stopAction;
}
public void callUponStart() {
}
public void changeType(BasinRenderer plotRenderer,BasinControlForm2 controlForm, int type){
}
/**
* @return the colorSettingsAction
*/
public Action getColorSettingsAction() {
return colorSettingsAction;
}
}
| gpl-2.0 |
andi-git/boatpos | boatpos-common/boatpos-common-test/src/test/java/org/boatpos/common/test/Deployments.java | 1362 | package org.boatpos.common.test;
import org.eu.ingwar.tools.arquillian.extension.suite.annotations.ArquillianSuiteDeployment;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import java.io.File;
import java.io.IOException;
@SuppressWarnings("unused")
@ArquillianSuiteDeployment
public class Deployments {
private static final String FOLDER_PERSISTENCE_XML_SOURCE = "src/test/resources";
private static final String FOLDER_PERSISTENCE_XML_TARGET = "META-INF";
private static final String FILE_ARQUILLIAN_EXTENSION_SOURCE = "src/main/resources/META-INF/services/org.jboss.arquillian.container.test.spi.RemoteLoadableExtension";
private static final String FILE_ARQUILLIAN_EXTENSION_TARGET = "META-INF/services/org.jboss.arquillian.container.test.spi.RemoteLoadableExtension";
@Deployment
public static WebArchive deploy() throws IOException {
return ShrinkWrap.create(WebArchive.class, "test.war")
.addAsLibraries(ArquillianHelper.getAllArquillianLibs())
.addAsWebInfResource("META-INF/beans.xml", "beans.xml")
.addAsResource(new File(FILE_ARQUILLIAN_EXTENSION_SOURCE), FILE_ARQUILLIAN_EXTENSION_TARGET)
.addPackages(true, "org.boatpos.common.test");
}
}
| gpl-2.0 |
alcmagalhaes/drogaria | src/br/com/drogaria/converter/FabricanteConverter.java | 1124 | package br.com.drogaria.converter;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import br.com.drogaria.dao.FabricanteDAO;
import br.com.drogaria.domain.Fabricante;
@FacesConverter("fabricanteConverter")
public class FabricanteConverter implements Converter{
// Quando da selecao de um item da lista
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String valor) {
try {
Long codigo = Long.parseLong(valor);
FabricanteDAO fabricanteDAO = new FabricanteDAO();
Fabricante fabricante = fabricanteDAO.buscarPorCodigo(codigo);
return fabricante;
} catch (RuntimeException e) {
return null;
}
}
// Quando da montagem da lista no combobox
@Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
try {
Fabricante fabricante = (Fabricante) object;
Long codigo = fabricante.getCodigo();
return codigo.toString();
} catch (RuntimeException e) {
return null;
}
}
}
| gpl-2.0 |
fjoncourt/jfwknop | src/main/java/com/cipherdyne/gui/wizard/views/GpgSignerIdView.java | 2280 | /*
* JFwknop is developed primarily by the people listed in the file 'AUTHORS'.
* Copyright (C) 2016 JFwknop developers and contributors.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package com.cipherdyne.gui.wizard.views;
import com.cipherdyne.gui.components.IFwknopVariable;
import com.cipherdyne.gui.components.JFwknopTextField;
import com.cipherdyne.gui.wizard.EnumWizardButton;
import com.cipherdyne.gui.wizard.EnumWizardVariable;
import com.cipherdyne.gui.wizard.EnumWizardView;
import java.util.Map;
import javax.swing.JButton;
/**
* Wizard view that displays basic Fwknop variables to set up in order to quickly run and SPA packet
*
* @author Franck Joncourt
*/
public class GpgSignerIdView extends AbstractView {
@Override
public void initialize(Map<EnumWizardVariable, IFwknopVariable> varMap, Map<EnumWizardButton, JButton> btnMap) {
varMap.put(EnumWizardVariable.GPG_SIGNER_ID, new JFwknopTextField(""));
varMap.put(EnumWizardVariable.GPG_SIGNER_PASSWORD, new JFwknopTextField(""));
btnMap.put(EnumWizardButton.BROWSE_FOR_GPG_SIGNER_ID, new JButton(EnumWizardButton.BROWSE_FOR_GPG_SIGNER_ID.getDescription()));
// Add object to the newly created panel
this.add(Utils.createItem(varMap, EnumWizardVariable.GPG_SIGNER_ID), "growx");
this.add(btnMap.get(EnumWizardButton.BROWSE_FOR_GPG_SIGNER_ID), "growx");
this.add(Utils.createItem(varMap, EnumWizardVariable.GPG_SIGNER_PASSWORD), "growx");
}
@Override
public EnumWizardView getNextPanel() {
return EnumWizardView.SETUP_GPG_RECIPIENT_ID;
}
}
| gpl-2.0 |
TrueElement/Java | Data Structures/Queues/Queue/Queue.java | 360 | package Queue;
import java.util.ArrayList;
/**
* Simple implementation of a generic Queue using an
* ArrayList.
* @author Tim Fleece
*@param <T>
*/
public class Queue<T> {
ArrayList<T> queue;
public Queue() {
queue = new ArrayList<T>();
}
public void enqueue(T obj) {
queue.add(obj);
}
public T dequeue() {
return queue.remove(0);
}
} | gpl-2.0 |
atkio/dbsk | gen/name/atkio/dev/android/dosbox/BuildConfig.java | 171 | /** Automatically generated file. DO NOT MODIFY */
package name.atkio.dev.android.dosbox;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | gpl-2.0 |
timoutwente/neighborhoodPSS | NeighborhoodPSS/src/main/java/org/visico/neighborhoodpss/gwt/server/project/db/Project.java | 4935 | package org.visico.neighborhoodpss.gwt.server.project.db;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
import java.util.HashSet;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.visico.neighborhoodpss.domain.project.BuildingDataTypeDTO;
import org.visico.neighborhoodpss.domain.project.ProjectDTO;
import org.visico.neighborhoodpss.domain.project.ScenarioDTO;
import org.visico.neighborhoodpss.domain.project.UserDTO;
@Entity
@Table(name="PROJECT")
public class Project implements Cloneable, Serializable
{
/**
*
*/
private static final long serialVersionUID = -1996881128129978288L;
@Id
@GeneratedValue
private int id;
@Column
private String name;
@Column
private double latitude;
@Column
private double longitude;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name="project_id")
Set<Scenario> parentScenarios = new HashSet<Scenario>();
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(
name="PROJECT_USER",
joinColumns=@JoinColumn(name="project_id"),
inverseJoinColumns=@JoinColumn(name="user_id")
)
Set<User> users = new HashSet<User>();
@ManyToMany
@JoinTable(
name="BUILDING_DATA_TYPE_PROJECT",
joinColumns=@JoinColumn(name="project_id"),
inverseJoinColumns=@JoinColumn(name="building_data_type_id")
)
Set<BuildingDataType> buildingDataTypes = new HashSet<BuildingDataType>();
@Transient
private ProjectDTO dto_object = null;
public Project()
{
}
public Project(ProjectDTO dto)
{
this.dto_object = dto;
this.id = dto.getId();
this.name = dto.getName();
this.latitude = dto.getLatitude();
this.longitude = dto.getLongitude();
Iterator<ScenarioDTO> it = this.dto_object.getParent_scenarios().iterator();
while(it.hasNext())
{
this.addParentScenario( new Scenario(it.next()));
}
Iterator<UserDTO> uit = this.dto_object.getUsers().iterator();
while(uit.hasNext())
{
this.addUser( new User(uit.next()));
}
for (BuildingDataTypeDTO type : this.dto_object.getBuildingDataTypes())
this.buildingDataTypes.add(new BuildingDataType(type));
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public Set<Scenario> getParentScenarios() {
return parentScenarios;
}
public void setParentScenarios(Set<Scenario> parentScenarios) {
this.parentScenarios = parentScenarios;
}
public void addParentScenario(Scenario s)
{
this.parentScenarios.add(s);
}
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
public void addUser(User u)
{
this.users.add(u);
}
public Set<BuildingDataType> getBuildingDataTypes() {
return buildingDataTypes;
}
public void setBuildingDataTypes(Set<BuildingDataType> buildingDataTypes) {
this.buildingDataTypes = buildingDataTypes;
}
public ProjectDTO getDto_object() {
if (dto_object == null)
{
dto_object = new ProjectDTO();
dto_object.setId(id);
dto_object.setLatitude(latitude);
dto_object.setLongitude(longitude);
dto_object.setName(name);
for (Scenario s : getParentScenarios())
{
dto_object.addParentScenario(s.getDto_object());
}
for (User u : getUsers())
{
dto_object.addUser(u.getDto_object());
}
for (BuildingDataType d : getBuildingDataTypes())
{
dto_object.getBuildingDataTypes().add(d.getDto_object());
}
}
return dto_object;
}
public void setDto_object(ProjectDTO dto_object) {
this.dto_object = dto_object;
}
public void update_dtoIds()
{
this.dto_object.setId(this.id);
Iterator<Scenario> sit = this.getParentScenarios().iterator();
while(sit.hasNext())
{
sit.next().update_dtoIds();
}
Iterator<User> uit = this.getUsers().iterator();
while(uit.hasNext())
{
uit.next().update_dtoIds();
}
for (BuildingDataType d : buildingDataTypes)
d.update_dtoIds();
}
public static ArrayList<ProjectDTO> getDTOList(ArrayList<Project> projects)
{
ArrayList<ProjectDTO> dtos = new ArrayList<ProjectDTO>();
for (Project p : projects)
dtos.add(p.getDto_object());
return dtos;
}
}
| gpl-2.0 |
gsitgithub/java-spring-code | webapp-template/src/main/java/dev/gsitgithub/webapp/entity/abstracts/IdUuidAuditableEntity.java | 1620 | package dev.gsitgithub.webapp.entity.abstracts;
import dev.gsitgithub.webapp.entity.User;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.hibernate.LazyInitializationException;
import org.springframework.data.jpa.domain.AbstractAuditable;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import java.util.UUID;
import static org.apache.commons.lang3.builder.ToStringStyle.SHORT_PREFIX_STYLE;
//@EqualsAndHashCode(of = "uuid", callSuper = false) commented because for MySql it causes java.lang.ClassCastException: com.fasterxml.classmate.types.ResolvedRecursiveType cannot be cast to com.fasterxml.classmate.types.ResolvedObjectType
@Setter
@Getter
@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
public class IdUuidAuditableEntity extends AbstractAuditable<User, Long> {
@Column(unique = true)
@Setter(AccessLevel.PROTECTED)
private String uuid = UUID.randomUUID().toString();
@Override
public String toString() {
try {
return ReflectionToStringBuilder.reflectionToString(this, SHORT_PREFIX_STYLE);
} catch (LazyInitializationException e) {
return new ToStringBuilder(this, SHORT_PREFIX_STYLE)
.append("id", getId())
.append("uuid", getUuid())
.toString();
}
}
}
| gpl-2.0 |
miguel-porto/flora-on-server | webadmin/src/main/java/pt/floraon/arangodriver/serializers/RectangleDeserializer.java | 995 | package pt.floraon.arangodriver.serializers;
import com.arangodb.velocypack.VPackDeserializationContext;
import com.arangodb.velocypack.VPackDeserializer;
import com.arangodb.velocypack.VPackSlice;
import com.arangodb.velocypack.exception.VPackBuilderException;
import com.arangodb.velocypack.exception.VPackException;
import pt.floraon.driver.datatypes.Rectangle;
public class RectangleDeserializer implements VPackDeserializer<Rectangle> {
@Override
public Rectangle deserialize(
final VPackSlice parent,
final VPackSlice vpack,
final VPackDeserializationContext context) throws VPackException {
final Rectangle obj;
if(vpack.isObject()) {
obj = new Rectangle(vpack.get("left").getAsLong(), vpack.get("right").getAsLong()
, vpack.get("top").getAsLong(), vpack.get("bottom").getAsLong());
} else
throw new VPackBuilderException("Expecting Rectangle object");
return obj;
}
}
| gpl-2.0 |
flyroom/PeerfactSimKOM_Clone | src/org/peerfact/impl/service/aggregation/skyeye/SkyNetEventObject.java | 2853 | /*
* Copyright (c) 2012-2013 Open Source Community - <http://www.peerfact.org>
* Copyright (c) 2011-2012 University of Paderborn - UPB
* Copyright (c) 2005-2011 KOM - Multimedia Communications Lab
*
* This file is part of PeerfactSim.KOM.
*
* PeerfactSim.KOM 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
* any later version.
*
* PeerfactSim.KOM 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 PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.peerfact.impl.service.aggregation.skyeye;
import org.peerfact.api.service.skyeye.SkyNetEventType;
/**
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
* This part of the Simulator is not maintained in the current version of
* PeerfactSim.KOM. There is no intention of the authors to fix this
* circumstances, since the changes needed are huge compared to overall benefit.
*
* If you want it to work correctly, you are free to make the specific changes
* and provide it to the community.
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!
*
* This class contains a <code>SkyNetEventType</code> as well as the timestamp
* of its creation. With both elements, one can determine, when the
* SkyNet-event, whose type is specified by <code>SkyNetEventType</code>, was
* created.
*
* @author Dominik Stingl <peerfact@kom.tu-darmstadt.de>
* @version 1.0, 04.12.2008
*
*/
public class SkyNetEventObject {
private SkyNetEventType type;
private long initTime;
private int metricsUpdateCounter;
public SkyNetEventObject(SkyNetEventType eventType, long initTime) {
// type = eventType;
// this.initTime = initTime;
// metricsUpdateCounter = -1;
this(eventType, initTime, -1);
}
public SkyNetEventObject(SkyNetEventType eventType, long initTime,
int metricsUpdateCounter) {
type = eventType;
this.initTime = initTime;
this.metricsUpdateCounter = metricsUpdateCounter;
}
/**
* Returns a <code>SkyNetEventType</code>, which contains the type of the
* created SkyNet-event.
*
* @return an instance of <code>SkyNetEventType</code>
*/
public SkyNetEventType getType() {
return type;
}
/**
* Returns the time, when the corresponding event was created.
*
* @return the timestamp of the created event
*/
public long getInitTime() {
return initTime;
}
public int getMetricsUpdateCounter() {
return metricsUpdateCounter;
}
}
| gpl-2.0 |
anicloud/octopus-object-client | object-agent/java/service-agent/src/main/java/com/ani/octopus/service/agent/service/account/AccountServiceImpl.java | 12091 | package com.ani.octopus.service.agent.service.account;
import com.ani.octopus.commons.accout.dto.AccountDto;
import com.ani.octopus.commons.accout.dto.AccountModifyDto;
import com.ani.octopus.commons.accout.dto.AccountRegisterDto;
import com.ani.octopus.commons.accout.dto.AccountType;
import com.ani.octopus.commons.accout.message.AccountHttpMessage;
import com.ani.octopus.commons.core.message.OctopusMessage;
import com.ani.octopus.service.agent.core.config.AnicelMeta;
import com.ani.octopus.service.agent.core.http.AbstractBaseService;
import com.ani.octopus.service.agent.core.validate.DomainObjectValidator;
import com.ani.octopus.service.agent.core.http.RestTemplateFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.util.UriComponentsBuilder;
import javax.xml.bind.ValidationException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collections;
/**
* The implementation of the AccountService and extends from AbstractBaseService. <br><br>
* <strong>Use Example:</strong><br>
* <pre>
* AnicelMeta anicelMeta = new AnicelMeta();
* // create the RestTemplateFactory
* RestTemplateFactory templateFactory = new RestTemplateFactory();
* // create AccountServiceImpl instance
* AccountService accountService = new AccountServiceImpl(
* anicelMeta,
* templateFactory,
* accessToken
* );
* // call the methods
* AccountRegisterDto accountDto = new AccountRegisterDto();
* accountGroupService.save(accountDto);
* ......
* </pre>
* <Strong>Notice:</Strong><br>
* When you want to register an account, you don't need the accessToken value, you just can set it <b>NULL</b>.
* <br><br>
* Created by zhaoyu on 15-10-31.
*/
public class AccountServiceImpl extends AbstractBaseService implements AccountService {
private static final Logger LOGGER = LoggerFactory.getLogger(AccountServiceImpl.class);
public AccountServiceImpl() {
}
public AccountServiceImpl(AnicelMeta anicelMeta, RestTemplateFactory restTemplateFactory, String accessToken) {
super(anicelMeta, restTemplateFactory, accessToken);
}
@Override
public AccountDto register(AccountRegisterDto account) throws ValidationException {
if (account.accountType == AccountType.ROOT) {
throw new ValidationException("Account Type cannot be Root");
}
if (!DomainObjectValidator.isDomainObjectValid(account)) {
throw new ValidationException("Invalid AccountRegisterDto Instance");
}
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder
.fromHttpUrl(anicelMeta.getOctopusServiceUrl() + anicelMeta.getAccountRegisterUrl());
LOGGER.info(uriComponentsBuilder.toUriString());
HttpEntity<AccountRegisterDto> requestEntity = new HttpEntity<>(account, httpHeaders);
AccountHttpMessage result = restTemplateFactory.getRestTemplate(new Class[]{AccountRegisterDto.class, AccountDto.class}).postForObject(
uriComponentsBuilder.toUriString(),
requestEntity,
AccountHttpMessage.class
);
if (result.getResultCode() == OctopusMessage.ResultCode.SUCCESS) {
return result.getReturnObj();
} else {
StringBuilder builder = new StringBuilder("message: ")
.append(result.getMsg())
.append(", error code:")
.append(result.getResultCode());
throw new RuntimeException(builder.toString());
}
}
@Override
public AccountDto modify(AccountModifyDto account) throws ValidationException {
if (account.accountType == AccountType.ROOT) {
throw new ValidationException("Account Type cannot be Root");
}
if (!DomainObjectValidator.isDomainObjectValid(account)) {
throw new ValidationException("Invalid AccountModifyDto Instance.");
}
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder
.fromHttpUrl(anicelMeta.getOctopusServiceUrl() + anicelMeta.getAccountModifyUrl())
.queryParam(RestTemplateFactory.ACCESS_TOKEN, accessToken);
HttpEntity<AccountModifyDto> requestEntity = new HttpEntity<>(account, httpHeaders);
AccountHttpMessage result = restTemplateFactory
.getRestTemplate(new Class[]{AccountRegisterDto.class, AccountDto.class})
.postForObject(uriComponentsBuilder.toUriString(), requestEntity, AccountHttpMessage.class);
if (result.getResultCode() == OctopusMessage.ResultCode.SUCCESS) {
return result.getReturnObj();
} else {
StringBuilder builder = new StringBuilder("message: ")
.append(result.getMsg())
.append(", error code:")
.append(result.getResultCode());
throw new RuntimeException(builder.toString());
}
}
@Override
public AccountDto getByAccountId(Long accountId) {
if (accountId == null) {
throw new NullPointerException("AccountId is Null.");
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(anicelMeta.getOctopusServiceUrl())
.append(anicelMeta.getAccountByAccountIdUrl())
.append("/")
.append(accountId);
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder
.fromHttpUrl(stringBuilder.toString())
.queryParam("access_token", accessToken);
AccountHttpMessage result = restTemplateFactory
.getRestTemplate(new Class[]{AccountRegisterDto.class, AccountDto.class})
.getForObject(uriComponentsBuilder.build().toUriString(), AccountHttpMessage.class);
if (result.getResultCode() == OctopusMessage.ResultCode.SUCCESS) {
return result.getReturnObj();
} else {
StringBuilder builder = new StringBuilder("message: ")
.append(result.getMsg())
.append(", error code:")
.append(result.getResultCode());
throw new RuntimeException(builder.toString());
}
}
@Override
public AccountDto getByEmail(String email) {
if (email == null) {
throw new NullPointerException("Email is Null.");
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(anicelMeta.getOctopusServiceUrl())
.append(anicelMeta.getAccountByEmailUrl());
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder
.fromHttpUrl(stringBuilder.toString())
.queryParam("email", email)
.queryParam("access_token", accessToken);
AccountHttpMessage result = restTemplateFactory
.getRestTemplate(new Class[]{AccountRegisterDto.class, AccountDto.class})
.getForObject(uriComponentsBuilder.build().toUriString(), AccountHttpMessage.class);
if (result.getResultCode() == OctopusMessage.ResultCode.SUCCESS) {
return result.getReturnObj();
} else {
StringBuilder builder = new StringBuilder("message: ")
.append(result.getMsg())
.append(", error code:")
.append(result.getResultCode());
throw new RuntimeException(builder.toString());
}
}
@Override
public AccountDto getByPhoneNumber(String phoneNumber) {
if (phoneNumber == null) {
throw new NullPointerException("PhoneNumber is Null.");
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(anicelMeta.getOctopusServiceUrl())
.append(anicelMeta.getAccountByPhoneUrl())
.append("/")
.append(phoneNumber);
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder
.fromHttpUrl(stringBuilder.toString())
.queryParam("access_token", accessToken);
AccountHttpMessage result = restTemplateFactory.getRestTemplate(new Class[]{AccountRegisterDto.class, AccountDto.class})
.getForObject(uriComponentsBuilder.build().toUriString(), AccountHttpMessage.class);
if (result.getResultCode() == OctopusMessage.ResultCode.SUCCESS) {
return result.getReturnObj();
} else {
StringBuilder builder = new StringBuilder("message: ")
.append(result.getMsg())
.append(", error code:")
.append(result.getResultCode());
throw new RuntimeException(builder.toString());
}
}
@Override
public AccountDto getByAccessToken() {
if (accessToken == null) {
throw new NullPointerException("accessToken is Null.");
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(anicelMeta.getOctopusServiceUrl())
.append(anicelMeta.getAccountByTokenUrl());
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder
.fromHttpUrl(stringBuilder.toString())
.queryParam("access_token", accessToken);
AccountHttpMessage result = restTemplateFactory.getRestTemplate(new Class[]{AccountRegisterDto.class, AccountDto.class})
.getForObject(uriComponentsBuilder.build().toUriString(), AccountHttpMessage.class);
if (result.getResultCode() == OctopusMessage.ResultCode.SUCCESS) {
return result.getReturnObj();
} else {
StringBuilder builder = new StringBuilder("message: ")
.append(result.getMsg())
.append(", error code:")
.append(result.getResultCode());
throw new RuntimeException(builder.toString());
}
}
@Override
public AccountDto addAccountInGroup(Long accountId, Long groupId) {
if (accountId == null || groupId == null) {
throw new NullPointerException("AccountId or GroupId is Null.");
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(anicelMeta.getOctopusServiceUrl())
.append(anicelMeta.getAccountAddInGroupUrl())
.append("/")
.append(accountId)
.append("/")
.append(groupId);
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder
.fromHttpUrl(stringBuilder.toString())
.queryParam("access_token", accessToken);
AccountHttpMessage result = restTemplateFactory.getRestTemplate(new Class[]{AccountRegisterDto.class, AccountDto.class})
.getForObject(uriComponentsBuilder.build().toUriString(), AccountHttpMessage.class);
if (result.getResultCode() == OctopusMessage.ResultCode.SUCCESS) {
return result.getReturnObj();
} else {
StringBuilder builder = new StringBuilder("message: ")
.append(result.getMsg())
.append(", error code:")
.append(result.getResultCode());
throw new RuntimeException(builder.toString());
}
}
@Override
public void setAccessToken(String accessToken) {
super.accessToken = accessToken;
}
}
| gpl-2.0 |
joezxh/DATAX-UI | eshbase-proxy/src/main/java/com/github/eswrapper/controller/BlackRequestController.java | 447 | package com.github.eswrapper.controller;
import org.guess.core.web.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.github.eswrapper.model.BlackRequest;
@Controller
@RequestMapping("/blackfilter")
public class BlackRequestController extends BaseController<BlackRequest>{
{
listView = "/es/blackfilter/list";
showView = "/es/blackfilter/show";
}
}
| gpl-2.0 |
jujaga/bxe2e | src/test/java/org/oscarehr/common/util/EntityModelUtils.java | 3588 | package org.oscarehr.common.util;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javassist.Modifier;
import javax.persistence.EmbeddedId;
import javax.persistence.Id;
import org.apache.log4j.Logger;
public class EntityModelUtils {
private static Logger log = Logger.getLogger(EntityModelUtils.class.getName());
public static void invokeMethodsForModelClass(Object model) {
Method m[] = model.getClass().getDeclaredMethods();
AccessibleObject.setAccessible(m, true);
for (Integer i = 0; i < m.length; i++) {
try {
// Setters
if(m[i].getName().startsWith("set")) {
Object[] args = {null};
m[i].invoke(model, args);
}
// Getters and Booleans
else if(m[i].getName().matches("^(get|is).*$")){
m[i].invoke(model);
}
} catch (Exception e) {
log.warn(e.toString() + " - " + m[i].getName());
}
}
}
public static Object generateTestDataForModelClass(Object model) {
Field f[] = model.getClass().getDeclaredFields();
AccessibleObject.setAccessible(f, true);
for (Integer i = 0; i < f.length; i++) {
Boolean isId = false;
Annotation annotations[] = f[i].getAnnotations();
for (Integer j = 0; j < annotations.length; j++) {
if(annotations[j].annotationType() == Id.class) {
isId = true;
}
if(annotations[j].annotationType() == EmbeddedId.class) {
isId = true;
}
}
if(isId)
continue;
Integer modifiers = f[i].getModifiers();
if((modifiers & Modifier.STATIC) == Modifier.STATIC) {
continue;
}
try {
if(f[i].getType() == String.class) {
f[i].set(model, f[i].getName() + ((int)(Math.random()*10000)));
}
else if(f[i].getType() == int.class || f[i].getType() == Integer.class) {
f[i].set(model,(int)(Math.random()*10000));
}
else if(f[i].getType() == long.class || f[i].getType() == Long.class) {
f[i].set(model,(long)(Math.random()*10000));
}
else if(f[i].getType() == float.class || f[i].getType() == Float.class) {
f[i].set(model,(float)(Math.random()*100));
}
else if(f[i].getType() == double.class || f[i].getType() == Double.class) {
f[i].set(model,Math.random()*100);
}
else if(f[i].getType() == Date.class) {
f[i].set(model,new Date());
}
else if(f[i].getType() == Timestamp.class) {
f[i].set(model,Timestamp.valueOf("2015-01-07 12:05:16"));
}
else if(f[i].getType() == Calendar.class) {
f[i].set(model,Calendar.getInstance());
}
else if(f[i].getType() == boolean.class || f[i].getType() == Boolean.class) {
f[i].set(model,true);
}
else if(f[i].getType() == byte.class || f[i].getType() == Byte.class) {
f[i].set(model,(byte)0xAA);
}
else if(f[i].getType() == char.class || f[i].getType() == Character.class) {
f[i].set(model,'A');
}
else if(f[i].getType() == Set.class || f[i].getType() == List.class || f[i].getType() == Map.class) {
// Ignore
}
else if(f[i].getType() == char.class || f[i].getType() == BigDecimal.class) {
BigDecimal bd = new BigDecimal(Math.random()*5000);
f[i].set(model,bd);
} else {
log.warn("Can't generate test data for class type:" + f[i].getType());
}
} catch (Exception e) {
log.warn(e.toString() + " - " + f[i].getName());
}
}
return model;
}
}
| gpl-2.0 |
csjx/realtime-data | src/main/java/edu/hawaii/soest/hioos/isus/ISUSFrame.java | 17850 | /**
* Copyright: 2010 Regents of the University of Hawaii and the
* School of Ocean and Earth Science and Technology
* Purpose: A class that represents a Satlantic ISUS V3 data sample
* from a binary StorX data file.
*
* Authors: Christopher Jones
*
* $HeadURL$
* $LastChangedDate$
* $LastChangedBy$
* $LastChangedRevision$
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.hawaii.soest.hioos.isus;
import java.io.UnsupportedEncodingException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.TimeZone;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* A class that represents a single (full) binary frame from a Satlantic ISUS V3
* nitrate concentration instrument. The class represents both light and dark
* frames, and provides access to the individual fields of the binary data
* sample as described in the ISUS V3 Operation Manual.
*/
public class ISUSFrame {
/* The Logger instance used to log system messages */
private static Log log = LogFactory.getLog(ISUSFrame.class);
/* A ISUS frame size in bytes as an integer */
private final int ISUS_FRAME_SIZE = 8192;
/* The date format for the timestamp applied to a ISUS frame (Julian day) */
private static final SimpleDateFormat FRAME_DATE_FORMAT = new SimpleDateFormat("yyyyDDDHHmmss");
/* The timezone used for the sample date */
private static final TimeZone TZ = TimeZone.getTimeZone("Pacific/Honolulu");
/* A ISUS frame as a ByteBuffer */
private ByteBuffer isusFrame = ByteBuffer.allocate(ISUS_FRAME_SIZE);
/*
* AS10 The frame header or synchronization string starts with 'SAT' for a
* Satlantic instrument, followed by three characters identifying the frame
* type. The last four characters are the instrument serial number.
*/
private ByteBuffer header = ByteBuffer.allocate(10);
/*
* BS4 The date field denotes the date at the time of the sample, using the
* year and Julian day. The format is YYYYDDD.
*/
private ByteBuffer sampleDate = ByteBuffer.allocate(4);
/*
* BD8 The time field gives the GMT/UTC time of the sample in decimal hours
* of the day.
*/
private ByteBuffer sampleTime = ByteBuffer.allocate(8);
/* BF4 The Nitrate concentration as calculated by the ISUS in μMol/L */
private ByteBuffer nitrogenConcentration = ByteBuffer.allocate(4);
/* BF4 The auxiliary 1 fitting result of the ISUS is reported. */
private ByteBuffer auxConcentration1 = ByteBuffer.allocate(4);
/* BF4 The auxiliary 2 fitting result of the ISUS is reported. */
private ByteBuffer auxConcentration2 = ByteBuffer.allocate(4);
/* BF4 The auxiliary 3 fitting result of the ISUS is reported. */
private ByteBuffer auxConcentration3 = ByteBuffer.allocate(4);
/*
* BF4 The Root Mean Square Error of the ISUS’ concentration calculation is
* given, in ASCII frames to 6 decimal places.
*/
private ByteBuffer rmsError = ByteBuffer.allocate(4);
/*
* BF4 The temperature inside the ISUS housing is given indegrees Celsius;
* in ASCII frames to 2 decimal places.
*/
private ByteBuffer insideTemperature = ByteBuffer.allocate(4);
/* BF4 The temperature of the spectrometer is given in degreesCelsius */
private ByteBuffer spectrometerTemperature = ByteBuffer.allocate(4);
/* BF4 The temperature of the lamp is given in degrees Celsius */
private ByteBuffer lampTemperature = ByteBuffer.allocate(4);
/* BU4 The lamp on-time of the current data acquisition in seconds. */
private ByteBuffer lampTime = ByteBuffer.allocate(4);
/*
* BF4 The humidity inside the instrument, given in percent. Increasing
* values of humidity indicate a slow leak.
*/
private ByteBuffer humidity = ByteBuffer.allocate(4);
/* BF4 The voltage of the lamp power supply. */
private ByteBuffer lampVoltage12 = ByteBuffer.allocate(4);
/* BF4 The voltage of the internal analog power supply. */
private ByteBuffer internalPowerVoltage5 = ByteBuffer.allocate(4);
/* BF4 The voltage of the main internal supply. */
private ByteBuffer mainPowerVoltage = ByteBuffer.allocate(4);
/* BF4 The average Reference Channel measurement during the sample time */
private ByteBuffer referenceAverage = ByteBuffer.allocate(4);
/* BF4 The variance of the Reference Channel measurements */
private ByteBuffer referenceVariance = ByteBuffer.allocate(4);
/* BF4 The Sea-Water Dark calculation in spectrometer counts. */
private ByteBuffer seaWaterDarkCounts = ByteBuffer.allocate(4);
/* BF4 The average value of all spectrometer channels */
private ByteBuffer spectrometerAverage = ByteBuffer.allocate(4);
/* BU2 The spectrometer counts of the channel wavelengths (256 total) */
private ByteBuffer channelWavelengths = ByteBuffer.allocate(2 * 256);
/* BU1 Binary frames only: A check sum validates binary frames. */
private ByteBuffer checksum = ByteBuffer.allocate(1);
/* A ISUS frame timestamp as a ByteBuffer */
private ByteBuffer timestamp = ByteBuffer.allocate(7);
public ISUSFrame(ByteBuffer isusFrame) {
this.isusFrame = isusFrame;
// parse each of the fields from the incoming byte buffer
byte[] twoBytes = new byte[2];
byte[] sixBytes = new byte[6];
byte[] sevenBytes = new byte[7];
byte[] fiveTwelveBytes = new byte[512];
try {
// set the header field
this.isusFrame.get(sixBytes);
this.header.put(sixBytes);
this.isusFrame.get(twoBytes);
this.header.put(twoBytes);
this.isusFrame.get(twoBytes);
this.header.put(twoBytes);
// set the sample date field
this.isusFrame.get(twoBytes);
this.sampleDate.put(twoBytes);
this.isusFrame.get(twoBytes);
this.sampleDate.put(twoBytes);
// set the sample time field
this.isusFrame.get(sixBytes);
this.sampleTime.put(sixBytes);
this.isusFrame.get(twoBytes);
this.sampleTime.put(twoBytes);
// set the nitrogen concentration field
this.isusFrame.get(twoBytes);
this.nitrogenConcentration.put(twoBytes);
this.isusFrame.get(twoBytes);
this.nitrogenConcentration.put(twoBytes);
// set the first auxillary concentration field
this.isusFrame.get(twoBytes);
this.auxConcentration1.put(twoBytes);
this.isusFrame.get(twoBytes);
this.auxConcentration1.put(twoBytes);
// set the second auxillary concentration field
this.isusFrame.get(twoBytes);
this.auxConcentration2.put(twoBytes);
this.isusFrame.get(twoBytes);
this.auxConcentration2.put(twoBytes);
// set the third auxillary concentration field
this.isusFrame.get(twoBytes);
this.auxConcentration3.put(twoBytes);
this.isusFrame.get(twoBytes);
this.auxConcentration3.put(twoBytes);
// set the root mean square error field
this.isusFrame.get(twoBytes);
this.rmsError.put(twoBytes);
this.isusFrame.get(twoBytes);
this.rmsError.put(twoBytes);
// set the inside temperature field
this.isusFrame.get(twoBytes);
this.insideTemperature.put(twoBytes);
this.isusFrame.get(twoBytes);
this.insideTemperature.put(twoBytes);
// set the spectrometer temperature field
this.isusFrame.get(twoBytes);
this.spectrometerTemperature.put(twoBytes);
this.isusFrame.get(twoBytes);
this.spectrometerTemperature.put(twoBytes);
// set the lamp temperature field
this.isusFrame.get(twoBytes);
this.lampTemperature.put(twoBytes);
this.isusFrame.get(twoBytes);
this.lampTemperature.put(twoBytes);
// set the lamp time field
this.isusFrame.get(twoBytes);
this.lampTime.put(twoBytes);
this.isusFrame.get(twoBytes);
this.lampTime.put(twoBytes);
// set the humdity field
this.isusFrame.get(twoBytes);
this.humidity.put(twoBytes);
this.isusFrame.get(twoBytes);
this.humidity.put(twoBytes);
// set the lamp voltage12 field
this.isusFrame.get(twoBytes);
this.lampVoltage12.put(twoBytes);
this.isusFrame.get(twoBytes);
this.lampVoltage12.put(twoBytes);
// set the internal power voltage5 field
this.isusFrame.get(twoBytes);
this.internalPowerVoltage5.put(twoBytes);
this.isusFrame.get(twoBytes);
this.internalPowerVoltage5.put(twoBytes);
// set the main power voltage field
this.isusFrame.get(twoBytes);
this.mainPowerVoltage.put(twoBytes);
this.isusFrame.get(twoBytes);
this.mainPowerVoltage.put(twoBytes);
// set the reference average field
this.isusFrame.get(twoBytes);
this.referenceAverage.put(twoBytes);
this.isusFrame.get(twoBytes);
this.referenceAverage.put(twoBytes);
// set the reference variance field
this.isusFrame.get(twoBytes);
this.referenceVariance.put(twoBytes);
this.isusFrame.get(twoBytes);
this.referenceVariance.put(twoBytes);
// set the sea water dark counts field
this.isusFrame.get(twoBytes);
this.seaWaterDarkCounts.put(twoBytes);
this.isusFrame.get(twoBytes);
this.seaWaterDarkCounts.put(twoBytes);
// set the average wavelength field
this.isusFrame.get(twoBytes);
this.spectrometerAverage.put(twoBytes);
this.isusFrame.get(twoBytes);
this.spectrometerAverage.put(twoBytes);
// set the channel wavelengths field
this.isusFrame.get(fiveTwelveBytes);
this.channelWavelengths.put(fiveTwelveBytes);
// set the checksum field
this.checksum.put(this.isusFrame.get());
// set the timestamp field
this.isusFrame.get(sixBytes);
this.timestamp.put(sixBytes);
this.timestamp.put(this.isusFrame.get());
} catch (BufferUnderflowException bue) {
bue.printStackTrace();
}
}
/*
* AS10 The frame header or synchronization string starts with SAT for a
* Satlantic instrument, followed by threecharacters identifying the frame
* type. The last four characters are the instrument serial number.
*/
public String getHeader() {
try {
return new String(this.header.array(), "US-ASCII");
} catch (UnsupportedEncodingException uee) {
log.debug("The string encoding was not recognized: " + uee.getMessage());
return null;
}
}
/*
* Get the frame serial number as a String
*
* @return frameSerialNumber - the serial number as a String
*/
public String getSerialNumber() {
try {
byte[] fourBytes = new byte[4];
this.header.position(6);
this.header.get(fourBytes);
this.header.flip();
return new String(fourBytes, "US-ASCII");
} catch (UnsupportedEncodingException uee) {
log.debug("The string encoding was not recognized: " + uee.getMessage());
return null;
}
}
/*
* BS4 The date field denotes the date at the time of the sample, using the
* year and Julian day. The format is YYYYDDD.
*/
public String getSampleDate() {
this.sampleDate.flip();
int dateStamp = this.sampleDate.getInt();
return String.format("%7d", dateStamp);
}
/*
* BD8 The time field gives the GMT/UTC time of the sample in decimal hours
* of the day.
*/
public String getSampleTime() {
this.sampleTime.flip();
double timeStamp = this.sampleTime.getDouble();
return String.format("%13.10f", timeStamp);
}
/*
* Return the sample date from the sampleDate and sampleTime fields
* combined.
*
* @return sampleDateTime - the sample date and time as a Java Date object
*/
public Date getSampleDateTime() {
SimpleDateFormat sampleDateFormat = new SimpleDateFormat("yyyyDDDHHmmss");
Date sampleDateTime = new Date(0L);
// get hours/minutes/seconds from the decimal hours time field
double decimalHour = new Double(getSampleTime()).doubleValue();
int wholeHour = new Double(decimalHour).intValue();
double fraction = decimalHour - wholeHour;
int minutes = new Double(fraction * 60d).intValue();
double secondsFraction = (fraction * 60d) - minutes;
int seconds = new Double(Math.round((secondsFraction * 60d))).intValue();
// create a string version of the date
String dateString = getSampleDate();
dateString += new Integer(wholeHour).toString();
dateString += new Integer(minutes).toString();
dateString += new Integer(seconds).toString();
// convert to a Java Date (instrument time is UTC)
try {
sampleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
sampleDateTime = sampleDateFormat.parse(dateString);
} catch (ParseException pe) {
log.debug(
"There was a problem parsing the sampleDateTime. The error " + "message was: " + pe.getMessage());
}
return sampleDateTime;
}
/* in ASCII frames to 2 decimal places. */
public double getNitrogenConcentration() {
this.nitrogenConcentration.flip();
return (new Float(this.nitrogenConcentration.getFloat())).doubleValue();
}
/* BF4 The first auxiliary fitting result of the ISUS is reported. */
public double getAuxConcentration1() {
this.auxConcentration1.flip();
return (new Float(this.auxConcentration1.getFloat())).doubleValue();
}
/* BF4 The second auxiliary fitting result of the ISUS is reported. */
public double getAuxConcentration2() {
this.auxConcentration2.flip();
return (new Float(this.auxConcentration2.getFloat())).doubleValue();
}
/* BF4 The first auxiliary fitting result of the ISUS is reported. */
public double getAuxConcentration3() {
this.auxConcentration3.flip();
return (new Float(this.auxConcentration3.getFloat())).doubleValue();
}
/*
* BF4 The Root Mean Square Error of the ISUS’ concentration calculation is
* given, in ASCII frames to 6 decimal places.
*/
public double getRmsError() {
this.rmsError.flip();
return (new Float(this.rmsError.getFloat())).doubleValue();
}
/* The temperature inside the housing in degrees Celcius. */
public double getInsideTemperature() {
this.insideTemperature.flip();
return (new Float(this.insideTemperature.getFloat())).doubleValue();
}
/* The temperature of the spectrometer in degrees Celcius. */
public double getSpectrometerTemperature() {
this.spectrometerTemperature.flip();
return (new Float(this.spectrometerTemperature.getFloat())).doubleValue();
}
/* The temperature of the lamp in degrees Celcius. */
public double getLampTemperature() {
this.lampTemperature.flip();
return (new Float(this.lampTemperature.getFloat())).doubleValue();
}
/* BU4 The lamp on-time of the current data acquisition in seconds. */
int getLampTime() {
this.lampTime.flip();
return this.lampTime.getInt();
}
/*
* BF4 The humidity inside the instrument, given in percent. Increasing
* values of humidity indicate a slow leak.
*/
public double getHumidity() {
this.humidity.flip();
return (new Float(this.humidity.getFloat())).doubleValue();
}
/* BF4 The voltage of the lamp power supply. */
public double getLampVoltage12() {
this.lampVoltage12.flip();
return (new Float(this.lampVoltage12.getFloat())).doubleValue();
}
/* BF4 The voltage of the internal analog power supply. */
public double getInternalPowerVoltage5() {
this.internalPowerVoltage5.flip();
return (new Float(this.internalPowerVoltage5.getFloat())).doubleValue();
}
/* BF4 The voltage of the main internal supply. */
public double getMainPowerVoltage() {
this.mainPowerVoltage.flip();
return (new Float(this.mainPowerVoltage.getFloat())).doubleValue();
}
/*
* BF4 The average Reference Channel measurement during thesample time, in
* ASCII mode to 2 decimal places.
*/
public double getReferenceAverage() {
this.referenceAverage.flip();
return (new Float(this.referenceAverage.getFloat())).doubleValue();
}
/*
* BF4 The variance of the Reference Channel measurements, inASCII mode to 2
* decimal places.
*/
public double getReferenceVariance() {
this.referenceVariance.flip();
return (new Float(this.referenceVariance.getFloat())).doubleValue();
}
/*
* BF4 An AF formatted field representing the Sea-Water Darkcalculation (to
* 2 decimal places), in spectrometer counts.
*/
public double getSeaWaterDarkCounts() {
this.seaWaterDarkCounts.flip();
return (new Float(this.seaWaterDarkCounts.getFloat())).doubleValue();
}
/*
* BF4 An AF formatted field representing the average value of all
* spectrometer channels, to 2 decimal places.
*/
public double getSpectrometerAverage() {
this.spectrometerAverage.flip();
return (new Float(this.spectrometerAverage.getFloat())).doubleValue();
}
/* BU2 The counts of the given channel wavelength of thespectrometer. */
public int getChannelWavelengthCounts(int wavelength) {
int position = (wavelength * 2) - 2;
short counts = this.channelWavelengths.getShort(position);
return new Short(counts).intValue();
}
/*
* BU1 Binary frames only: A check sum validates binary frames. Satlantic’s
* software rejects invalid frames.
*/
public int getChecksum() {
this.checksum.flip();
return this.checksum.get() & 0xFF;
}
/**
* Get the frame timestamp field as a byte array. The timestamp format is
* YYYYDDD from the first 3 bytes, and HHMMSS.SSS from the last four:
* Example: 1E AC CC = 2010316 (year 2010, julian day 316) 09 9D 3E 20 =
* 16:13:00.000 (4:13 pm)
*
* @return timestamp - the frame timestamp as a byte array
*/
public byte[] getTimestamp() {
this.timestamp.flip();
return this.timestamp.array();
}
}
| gpl-2.0 |
sergyegorov/OpenSpectrV | src/com/tl/osv/analit/method/AbstractMethod.java | 3028 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.tl.osv.analit.method;
import com.tl.osv.Common;
import com.tl.osv.util.StreamTools;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
/**
*
* @author root
*/
public abstract class AbstractMethod {
final private File baseFolder;
final private static String CLASS_FILE_NAME = "class.bin";
public AbstractMethod(File baseFolder) throws Exception{
this.baseFolder = baseFolder;//new File(Common.getDataDirectory(baseFolder.getAbsolutePath())+File.separator);
if(baseFolder.exists() == false)// && baseFolder.mkdir() == false)
throw new Exception("Folder '"+baseFolder.getAbsolutePath()+"' does not exists.");
//throw new Exception("Can't create '"+baseFolder.getAbsolutePath()+"' folder.");
StreamTools.saveClass(getFile(CLASS_FILE_NAME), this.getClass());
}
final public static AbstractMethod loadFrom(File baseFolder) throws Exception{
Class<?> cl = StreamTools.loadClass(new File(baseFolder+File.separator+CLASS_FILE_NAME));
Constructor<?> ctor = cl.getConstructor(File.class);
Object object = ctor.newInstance(new Object[] { baseFolder });
return (AbstractMethod)object;
}
final protected File getFile(String name){
if(name == null)
return baseFolder;
return new File(baseFolder.getAbsolutePath()+File.separator+name);
}
final public String getName(){
return baseFolder.getName();
}
private final static String DESCRIPTION_FILE_NAME = "description.txt";
String description;
public String getDescription() throws IOException{
if(description == null){
File fl = getFile(DESCRIPTION_FILE_NAME);
if(fl.exists() == false)
StreamTools.writeText(fl, "Just created. "+getClass().getName());
else
description = new String(Files.readAllBytes(
Paths.get(getFile(DESCRIPTION_FILE_NAME).getAbsolutePath())),
Common.DefaultTextChaset);
}
return description;
}
public void setDescription(String txt) throws IOException{
byte[] buffer = txt.getBytes(Common.DefaultTextChaset);
Files.write(
Paths.get(getFile(DESCRIPTION_FILE_NAME).getAbsolutePath()),
buffer,
StandardOpenOption.CREATE
);
description = txt;
}
abstract public AbstractMethodCalibr getCalibr();
abstract public AbstractMethodMeasuring getMeasuring();
@Override
public String toString(){
return getName();
}
}
| gpl-2.0 |
carlosthe19916/SistCoopEE_Rest | ejb-persona/src/test/java/org/softgreen/sistcoop/persona/ejb/models/jpa/PersonaJuridicaProviderTest.java | 8388 | package org.softgreen.sistcoop.persona.ejb.models.jpa;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.softgreen.sistcoop.persona.client.enums.Sexo;
import org.softgreen.sistcoop.persona.client.enums.TipoEmpresa;
import org.softgreen.sistcoop.persona.client.enums.TipoPersona;
import org.softgreen.sistcoop.persona.client.models.PersonaJuridicaModel;
import org.softgreen.sistcoop.persona.client.models.PersonaJuridicaProvider;
import org.softgreen.sistcoop.persona.client.models.PersonaNaturalModel;
import org.softgreen.sistcoop.persona.client.models.PersonaNaturalProvider;
import org.softgreen.sistcoop.persona.client.models.TipoDocumentoModel;
import org.softgreen.sistcoop.persona.client.models.TipoDocumentoProvider;
import org.softgreen.sistcoop.persona.client.models.util.ModelToRepresentation;
import org.softgreen.sistcoop.persona.client.models.util.RepresentationToModel;
import org.softgreen.sistcoop.persona.client.representations.idm.PersonaJuridicaRepresentation;
import org.softgreen.sistcoop.persona.client.representations.idm.PersonaNaturalRepresentation;
@RunWith(Arquillian.class)
public class PersonaJuridicaProviderTest {
private final static Logger log = Logger.getLogger(PersonaJuridicaProviderTest.class.getName());
@Inject
TipoDocumentoProvider tipoDocumentoProvider;
@Inject
PersonaNaturalProvider personaNaturalProvider;
@Inject
PersonaJuridicaProvider personaJuridicaProvider;
@Inject
RepresentationToModel representationToModel;
@Deployment
public static Archive<?> createTestArchive() throws IllegalArgumentException, ClassNotFoundException {
return ShrinkWrap.create(WebArchive.class, "test.war")
.addPackage("org.softgreen.sistcoop.persona.clien.enums")
.addPackage("org.softgreen.sistcoop.persona.client.models")
.addPackage("org.softgreen.sistcoop.persona.client.models.util")
.addPackage("org.softgreen.sistcoop.persona.client.providers")
.addPackage("org.softgreen.sistcoop.persona.client.representations.idm")
.addPackage("org.softgreen.sistcoop.persona.ejb.models.util")
.addPackage("org.softgreen.sistcoop.persona.ejb.models.jpa")
.addPackage("org.softgreen.sistcoop.persona.ejb.models.jpa.entities")
/***/
.addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml")
/** beans.xml **/
.addAsWebInfResource(EmptyAsset.INSTANCE, "META-INF/beans.xml")
/** deploy test DS **/
.addAsWebInfResource("test-ds.xml");
}
@Test
@InSequence(1)
public void add(){
String codigoPais = "PER";
TipoDocumentoModel tipoDocumentoRepresentante = tipoDocumentoProvider.addTipoDocumento("DNI", "Documento Nacional de Identidad", 8, TipoPersona.NATURAL);
String numeroDocumento = "46779354";
String apellidoPaterno = "Feria";
String apellidoMaterno = "Vila";
String nombres = "Carlos";
Date fechaNacimiento = Calendar.getInstance().getTime();
Sexo sexo = Sexo.MASCULINO;
PersonaNaturalModel representanteLegal = personaNaturalProvider.addPersonaNatural(codigoPais, tipoDocumentoRepresentante, numeroDocumento, apellidoPaterno, apellidoMaterno, nombres, fechaNacimiento, sexo);
TipoDocumentoModel tipoDocumentoModel = tipoDocumentoProvider.addTipoDocumento("RUC", "Registro Nacional de Contribuyentes", 8, TipoPersona.JURIDICA);
PersonaJuridicaModel model = personaJuridicaProvider.addPersonaJuridica(
representanteLegal,
"PE",
tipoDocumentoModel,
"12345678912",
"Softgreen S.A.C",
Calendar.getInstance().getTime(),
TipoEmpresa.PRIVADA,
true);
log.info(model.getId() + " creado");
}
@Test
@InSequence(2)
public void getById() throws Exception {
PersonaJuridicaModel model = personaJuridicaProvider.getPersonaJuridicaById(1L);
log.info(model.getId() + " found");
}
@Test
@InSequence(3)
public void getByTipoNumeroDoc() throws Exception {
TipoDocumentoModel tipoDocumento = tipoDocumentoProvider.getTipoDocumentoByAbreviatura("RUC");
PersonaJuridicaModel model = personaJuridicaProvider.getPersonaJuridicaByTipoNumeroDoc(tipoDocumento, "12345678912");
log.info(model.getId() + " found");
}
@Test
@InSequence(4)
public void getPersonas() throws Exception {
List<PersonaJuridicaModel> list = personaJuridicaProvider.getPersonasJuridicas();
log.info("getPersonasJuridicas()" + " size:" + list.size());
}
@Test
@InSequence(5)
public void getPersonasLimit() throws Exception {
List<PersonaJuridicaModel> list = personaJuridicaProvider.getPersonasJuridicas(0, 10);
log.info("getPersonasJuridicas()" + " size:" + list.size());
}
@Test
@InSequence(6)
public void getPersonasCount() throws Exception {
int count = personaJuridicaProvider.getPersonasJuridicasCount();
log.info("count:"+ count);
}
@Test
@InSequence(7)
public void searchForFilterText() throws Exception {
List<PersonaJuridicaModel> list = personaJuridicaProvider.searchForFilterText("sof");
log.info("searchForFilterText():"+ list.size());
}
@Test
@InSequence(8)
public void searchForFilterTextLimit() throws Exception {
List<PersonaJuridicaModel> list = personaJuridicaProvider.searchForFilterText("soft", 0, 10);
log.info("searchForFilterTextLimit():"+ list.size());
}
@Test
@InSequence(9)
public void searchForNumeroDocumento() throws Exception {
List<PersonaJuridicaModel> list = personaJuridicaProvider.searchForNumeroDocumento("123");
log.info("searchForNumeroDocumento():"+ list.size());
}
@Test
@InSequence(10)
public void searchForNumeroDocumentoLimit() throws Exception {
List<PersonaJuridicaModel> list = personaJuridicaProvider.searchForNumeroDocumento("123", 0, 10);
log.info("searchForNumeroDocumentoLimit():"+ list.size());
}
@Test
@InSequence(11)
public void modelToRepresentation() {
List<PersonaJuridicaModel> list = personaJuridicaProvider.getPersonasJuridicas();
if (list.size() < 1)
log.log(Level.WARNING, "ModelToRepresentation() size = 0");
for (PersonaJuridicaModel model : list) {
PersonaJuridicaRepresentation representation = ModelToRepresentation.toRepresentation(model);
log.info("Representation:" + representation.getId());
}
}
@Test
@InSequence(12)
public void representationToModel() {
PersonaJuridicaRepresentation representation = new PersonaJuridicaRepresentation();
representation.setCodigoPais("PER");
representation.setRazonSocial("Sistcoop sac");
representation.setNombreComercial("sistcop");
representation.setActividadPrincipal("voladdura de rocas");
representation.setFechaConstitucion(Calendar.getInstance().getTime());
representation.setCelular("966350507");
representation.setTelefono(null);
representation.setEmail(null);
representation.setTipoEmpresa(TipoEmpresa.PRIVADA.toString());
representation.setTipoDocumento("RUC");
representation.setNumeroDocumento("11111111111");
//representation.setNumeroDocumentoRepresentanteLegal("46779354");
//representation.setTipoDocumentoRepresentanteLegal("DNI");
/*PersonaNaturalModel representanteLegal = personaNaturalProvider.getPersonaNaturalByTipoNumeroDoc(
tipoDocumentoProvider.getTipoDocumentoByAbreviatura(representation.getTipoDocumentoRepresentanteLegal()),
representation.getNumeroDocumentoRepresentanteLegal());
PersonaJuridicaModel model = representationToModel.createPersonaJuridica(
representation,
tipoDocumentoProvider.getTipoDocumentoByAbreviatura(representation.getTipoDocumento()),
representanteLegal,
personaJuridicaProvider);*/
//log.info("representationToModel:" + model.getId());
}
@Test
@InSequence(13)
public void removePersonaNatural() throws Exception {
PersonaJuridicaModel model = personaJuridicaProvider.getPersonaJuridicaById(1L);
boolean result = personaJuridicaProvider.removePersonaJuridica(model);
log.info("removePersonaJuridica():"+ result);
}
}
| gpl-2.0 |
smarr/Truffle | substratevm/src/com.oracle.objectfile/src/com/oracle/objectfile/elf/dwarf/DwarfFrameSectionImpl.java | 14696 | /*
* Copyright (c) 2020, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 2020, Red Hat Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.objectfile.elf.dwarf;
import com.oracle.objectfile.LayoutDecision;
import com.oracle.objectfile.debugentry.ClassEntry;
import com.oracle.objectfile.debugentry.PrimaryEntry;
import com.oracle.objectfile.debugentry.Range;
import com.oracle.objectfile.debuginfo.DebugInfoProvider;
import org.graalvm.compiler.debug.DebugContext;
import java.util.List;
/**
* Section generic generator for debug_frame section.
*/
public abstract class DwarfFrameSectionImpl extends DwarfSectionImpl {
private static final int PADDING_NOPS_ALIGNMENT = 8;
public DwarfFrameSectionImpl(DwarfDebugInfo dwarfSections) {
super(dwarfSections);
}
@Override
public String getSectionName() {
return DwarfDebugInfo.DW_FRAME_SECTION_NAME;
}
@Override
public void createContent() {
assert !contentByteArrayCreated();
int pos = 0;
/*
* The frame section contains one CIE at offset 0 followed by an FIE for each method.
*/
pos = writeCIE(null, pos);
pos = writeMethodFrames(null, pos);
byte[] buffer = new byte[pos];
super.setContent(buffer);
}
@Override
public void writeContent(DebugContext context) {
assert contentByteArrayCreated();
byte[] buffer = getContent();
int size = buffer.length;
int pos = 0;
enableLog(context, pos);
/*
* There are entries for the prologue region where the stack is being built, the method body
* region(s) where the code executes with a fixed size frame and the epilogue region(s)
* where the stack is torn down.
*/
pos = writeCIE(buffer, pos);
pos = writeMethodFrames(buffer, pos);
if (pos != size) {
System.out.format("pos = 0x%x size = 0x%x", pos, size);
}
assert pos == size;
}
private int writeCIE(byte[] buffer, int p) {
/*
* We only need a vanilla CIE with default fields because we have to have at least one the
* layout is:
*
* <ul>
*
* <li><code>uint32 : length ............... length of remaining fields in this CIE</code>
*
* <li><code>uint32 : CIE_id ................ unique id for CIE == 0xffffff</code>
*
* <li><code>uint8 : version ................ == 1</code>
*
* <li><code>uint8[] : augmentation ......... == "" so always 1 byte</code>
*
* <li><code>ULEB : code_alignment_factor ... == 1 (could use 4 for Aarch64)</code>
*
* <li><code>ULEB : data_alignment_factor ... == -8</code>
*
* <li><code>byte : ret_addr reg id ......... x86_64 => 16 AArch64 => 30</code>
*
* <li><code>byte[] : initial_instructions .. includes pad to 8-byte boundary</code>
*
* </ul>
*/
int pos = p;
if (buffer == null) {
pos += putInt(0, scratch, 0);
pos += putInt(DwarfDebugInfo.DW_CFA_CIE_id, scratch, 0);
pos += putByte(DwarfDebugInfo.DW_CFA_CIE_version, scratch, 0);
pos += putByte((byte) 0, scratch, 0);
pos += putULEB(1, scratch, 0);
pos += putSLEB(-8, scratch, 0);
pos += putByte((byte) getReturnPCIdx(), scratch, 0);
/*
* Write insns to set up empty frame.
*/
pos = writeInitialInstructions(buffer, pos);
/*
* Pad to word alignment.
*/
pos = writePaddingNops(buffer, pos);
/*
* No need to write length.
*/
return pos;
} else {
int lengthPos = pos;
pos = putInt(0, buffer, pos);
pos = putInt(DwarfDebugInfo.DW_CFA_CIE_id, buffer, pos);
pos = putByte(DwarfDebugInfo.DW_CFA_CIE_version, buffer, pos);
pos = putByte((byte) 0, buffer, pos);
pos = putULEB(1, buffer, pos);
pos = putSLEB(-8, buffer, pos);
pos = putByte((byte) getReturnPCIdx(), buffer, pos);
/*
* write insns to set up empty frame
*/
pos = writeInitialInstructions(buffer, pos);
/*
* Pad to word alignment.
*/
pos = writePaddingNops(buffer, pos);
patchLength(lengthPos, buffer, pos);
return pos;
}
}
private int writeMethodFrames(byte[] buffer, int p) {
int pos = p;
/* write frames for normal methods */
for (ClassEntry classEntry : getPrimaryClasses()) {
for (PrimaryEntry primaryEntry : classEntry.getPrimaryEntries()) {
Range range = primaryEntry.getPrimary();
if (!range.isDeoptTarget()) {
long lo = range.getLo();
long hi = range.getHi();
int lengthPos = pos;
pos = writeFDEHeader((int) lo, (int) hi, buffer, pos);
pos = writeFDEs(primaryEntry.getFrameSize(), primaryEntry.getFrameSizeInfos(), buffer, pos);
pos = writePaddingNops(buffer, pos);
patchLength(lengthPos, buffer, pos);
}
}
}
/* now write frames for deopt targets */
for (ClassEntry classEntry : getPrimaryClasses()) {
for (PrimaryEntry primaryEntry : classEntry.getPrimaryEntries()) {
Range range = primaryEntry.getPrimary();
if (range.isDeoptTarget()) {
long lo = range.getLo();
long hi = range.getHi();
int lengthPos = pos;
pos = writeFDEHeader((int) lo, (int) hi, buffer, pos);
pos = writeFDEs(primaryEntry.getFrameSize(), primaryEntry.getFrameSizeInfos(), buffer, pos);
pos = writePaddingNops(buffer, pos);
patchLength(lengthPos, buffer, pos);
}
}
}
return pos;
}
protected abstract int writeFDEs(int frameSize, List<DebugInfoProvider.DebugFrameSizeChange> frameSizeInfos, byte[] buffer, int pos);
private int writeFDEHeader(int lo, int hi, byte[] buffer, int p) {
/*
* We only need a vanilla FDE header with default fields the layout is:
*
* <ul>
*
* <li><code>uint32 : length ............ length of remaining fields in this FDE</code>
*
* <li><code>uint32 : CIE_offset ........ always 0 i.e. identifies our only CIE
* header</code>
*
* <li><code>uint64 : initial_location .. i.e. method lo address</code>
*
* <li><code>uint64 : address_range ..... i.e. method hi - lo</code>
*
* <li><code>byte[] : instructions ...... includes pad to 8-byte boundary</code>
*
* </ul>
*/
int pos = p;
if (buffer == null) {
/* Dummy length. */
pos += putInt(0, scratch, 0);
/* CIE_offset */
pos += putInt(0, scratch, 0);
/* Initial address. */
pos += putLong(lo, scratch, 0);
/* Address range. */
return pos + putLong(hi - lo, scratch, 0);
} else {
/* Dummy length. */
pos = putInt(0, buffer, pos);
/* CIE_offset */
pos = putInt(0, buffer, pos);
/* Initial address. */
pos = putRelocatableCodeOffset(lo, buffer, pos);
/* Address range. */
return putLong(hi - lo, buffer, pos);
}
}
private int writePaddingNops(byte[] buffer, int p) {
int pos = p;
while ((pos & (PADDING_NOPS_ALIGNMENT - 1)) != 0) {
if (buffer == null) {
pos++;
} else {
pos = putByte(DwarfDebugInfo.DW_CFA_nop, buffer, pos);
}
}
return pos;
}
protected int writeDefCFA(int register, int offset, byte[] buffer, int p) {
int pos = p;
if (buffer == null) {
pos += putByte(DwarfDebugInfo.DW_CFA_def_cfa, scratch, 0);
pos += putSLEB(register, scratch, 0);
return pos + putULEB(offset, scratch, 0);
} else {
pos = putByte(DwarfDebugInfo.DW_CFA_def_cfa, buffer, pos);
pos = putULEB(register, buffer, pos);
return putULEB(offset, buffer, pos);
}
}
protected int writeDefCFAOffset(int offset, byte[] buffer, int p) {
int pos = p;
if (buffer == null) {
pos += putByte(DwarfDebugInfo.DW_CFA_def_cfa_offset, scratch, 0);
return pos + putULEB(offset, scratch, 0);
} else {
pos = putByte(DwarfDebugInfo.DW_CFA_def_cfa_offset, buffer, pos);
return putULEB(offset, buffer, pos);
}
}
protected int writeAdvanceLoc(int offset, byte[] buffer, int pos) {
if (offset <= 0x3f) {
return writeAdvanceLoc0((byte) offset, buffer, pos);
} else if (offset <= 0xff) {
return writeAdvanceLoc1((byte) offset, buffer, pos);
} else if (offset <= 0xffff) {
return writeAdvanceLoc2((short) offset, buffer, pos);
} else {
return writeAdvanceLoc4(offset, buffer, pos);
}
}
protected int writeAdvanceLoc0(byte offset, byte[] buffer, int pos) {
byte op = advanceLoc0Op(offset);
if (buffer == null) {
return pos + putByte(op, scratch, 0);
} else {
return putByte(op, buffer, pos);
}
}
protected int writeAdvanceLoc1(byte offset, byte[] buffer, int p) {
int pos = p;
byte op = DwarfDebugInfo.DW_CFA_advance_loc1;
if (buffer == null) {
pos += putByte(op, scratch, 0);
return pos + putByte(offset, scratch, 0);
} else {
pos = putByte(op, buffer, pos);
return putByte(offset, buffer, pos);
}
}
protected int writeAdvanceLoc2(short offset, byte[] buffer, int p) {
byte op = DwarfDebugInfo.DW_CFA_advance_loc2;
int pos = p;
if (buffer == null) {
pos += putByte(op, scratch, 0);
return pos + putShort(offset, scratch, 0);
} else {
pos = putByte(op, buffer, pos);
return putShort(offset, buffer, pos);
}
}
protected int writeAdvanceLoc4(int offset, byte[] buffer, int p) {
byte op = DwarfDebugInfo.DW_CFA_advance_loc4;
int pos = p;
if (buffer == null) {
pos += putByte(op, scratch, 0);
return pos + putInt(offset, scratch, 0);
} else {
pos = putByte(op, buffer, pos);
return putInt(offset, buffer, pos);
}
}
protected int writeOffset(int register, int offset, byte[] buffer, int p) {
byte op = offsetOp(register);
int pos = p;
if (buffer == null) {
pos += putByte(op, scratch, 0);
return pos + putULEB(offset, scratch, 0);
} else {
pos = putByte(op, buffer, pos);
return putULEB(offset, buffer, pos);
}
}
protected int writeRestore(int register, byte[] buffer, int p) {
byte op = restoreOp(register);
int pos = p;
if (buffer == null) {
return pos + putByte(op, scratch, 0);
} else {
return putByte(op, buffer, pos);
}
}
@SuppressWarnings("unused")
protected int writeRegister(int savedReg, int savedToReg, byte[] buffer, int p) {
int pos = p;
if (buffer == null) {
pos += putByte(DwarfDebugInfo.DW_CFA_register, scratch, 0);
pos += putULEB(savedReg, scratch, 0);
return pos + putULEB(savedToReg, scratch, 0);
} else {
pos = putByte(DwarfDebugInfo.DW_CFA_register, buffer, pos);
pos = putULEB(savedReg, buffer, pos);
return putULEB(savedToReg, buffer, pos);
}
}
protected abstract int getReturnPCIdx();
@SuppressWarnings("unused")
protected abstract int getSPIdx();
protected abstract int writeInitialInstructions(byte[] buffer, int pos);
/**
* The debug_frame section depends on debug_line section.
*/
private static final String TARGET_SECTION_NAME = DwarfDebugInfo.DW_LINE_SECTION_NAME;
@Override
public String targetSectionName() {
return TARGET_SECTION_NAME;
}
private final LayoutDecision.Kind[] targetSectionKinds = {
LayoutDecision.Kind.CONTENT,
LayoutDecision.Kind.SIZE
};
@Override
public LayoutDecision.Kind[] targetSectionKinds() {
return targetSectionKinds;
}
private static byte offsetOp(int register) {
assert (register >> 6) == 0;
return (byte) ((DwarfDebugInfo.DW_CFA_offset << 6) | register);
}
private static byte restoreOp(int register) {
assert (register >> 6) == 0;
return (byte) ((DwarfDebugInfo.DW_CFA_restore << 6) | register);
}
private static byte advanceLoc0Op(int offset) {
assert (offset >= 0 && offset <= 0x3f);
return (byte) ((DwarfDebugInfo.DW_CFA_advance_loc << 6) | offset);
}
}
| gpl-2.0 |
Zellith/Dropyard | Name.java | 801 |
public class Name {
//fields
private String first;
private String middle;
private String last;
//constructors
public Name(Name name){
this.first = name.getFirst();
this.middle = name.getMiddle();
this.last = name.getLast();
}
public Name(String first, String middle, String last){
this.first = first;
this.middle = middle;
this.last = last;
}
//setters and getters
public void setFirst(String first){
this.first = first;
}
public String getFirst() {
return first;
}
public String getMiddle() {
return middle;
}
public void setMiddle(String middle) {
this.middle = middle;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
public String toString(){
return (first+" "+middle+" "+last);
}
}
| gpl-2.0 |
camelCasee/OnlineShop | src/main/java/ru/ncedu/onlineshop/service/dao/orders/OrderDAO.java | 4568 | package ru.ncedu.onlineshop.service.dao.orders;
import org.springframework.stereotype.Repository;
import ru.ncedu.onlineshop.entity.order.Order;
import ru.ncedu.onlineshop.entity.order.OrderItem;
import ru.ncedu.onlineshop.entity.users.User;
import ru.ncedu.onlineshop.service.dao.GenericDAOImpl;
import javax.persistence.TypedQuery;
import java.util.ArrayList;
import java.util.List;
/**
* Created by ali on 30.12.14.
*/
@Repository("orderDAO")
public class OrderDAO extends GenericDAOImpl<Order> {
public OrderDAO() {super();}
public List<Order> getOrdersOfUser(User user){
TypedQuery<Order> query = entityManager.createNamedQuery("getOrdersOfUser", entityClass);
query.setParameter(1, user.getId());
query.setHint("org.hibernate.cacheable", true);
List<Order> res = query.getResultList();
// for (int i=0; i<res.size(); i++) {
// try {
// System.out.println(res.get(i).getUser().getAddresses().size());
// System.out.println(res.get(i).getUser().getEmails().size());
// System.out.println(res.get(i).getUser().getContactPhones().size());
// } catch (NullPointerException e){
//
// }
// for (int j=0; j<res.get(i).getOrderItemList().size(); j++)
// res.get(i).getOrderItemList().get(j).getProduct().getName(); // АХАХАХАХАХАХА ДОЛОЙ ИНКАПСУЛЯЦИЮ АХАХАХАХА
// }
return res;
// TypedQuery<Order> query = entityManager.createQuery("select o from Order o join fetch o.user where o.user.id = ?1", entityClass);
// query.setParameter(1, user.getId());
// return query.getResultList();
}
@Override
public List<Order> findAll() {
TypedQuery<Order> query = entityManager.createNamedQuery("selectAll", entityClass).setHint("org.hibernate.cacheable", true);
List<Order> res = query.getResultList();
// for (int i=0; i<res.size(); i++) {
// try {
// System.out.println(res.get(i).getUser().getAddresses().size());
// System.out.println(res.get(i).getUser().getEmails().size());
// System.out.println(res.get(i).getUser().getContactPhones().size());
// } catch (NullPointerException e){
//
// }
// for (int j=0; j<res.get(i).getOrderItemList().size(); j++)
// res.get(i).getOrderItemList().get(j).getProduct().getName(); // АХАХАХАХАХАХА ДОЛОЙ ИНКАПСУЛЯЦИЮ АХАХАХАХА
// }
return res;
// TypedQuery<Order> query = entityManager.createQuery(
// "select o from Order o left join fetch o.user", entityClass);
// return query.getResultList();
}
// public Order getOrderWithItems(Order order){
// TypedQuery<Order> query = entityManager.createQuery(
// "select o from Order o left join fetch o.user where o.id= ?1", entityClass);
// Order res = query.setParameter(1, order.getId()).getSingleResult();
// for (int j=0; j<res.getOrderItemList().size(); j++)
// res.getOrderItemList().get(j).getProduct().getName();
// return res;
// }
// @Override
// public Order save(Order order) {
// Order res = super.save(order);
// User user = res.getUser();
// try {
// System.out.println(user.getAddresses().size());
// System.out.println(user.getEmails().size());
// System.out.println(user.getContactPhones().size());
// } catch (NullPointerException e){
//
// }
//
// for (int j=0; j<res.getOrderItemList().size(); j++)
// res.getOrderItemList().get(j).getProduct().getName();
// return res;
// }
// public Order loadingOrderProducts(Order order){
//
// }
public Order getLastUserOrder(User user){
TypedQuery<Order> query = entityManager.createQuery(
"select o from Order o where o.user.id = ?1 and o.creationDate = " +
"(select max(or.creationDate) from Order or)", entityClass);
query.setParameter(1, user.getId());
return query.getSingleResult();
}
public Order clearOrderItems(Order order){
order.setOrderItemList(new ArrayList<OrderItem>());
return entityManager.merge(order);
}
public Order addOrderItem(Order order, OrderItem orderItem){
order.getOrderItemList().add(orderItem);
return entityManager.merge(order);
}
}
| gpl-2.0 |
KiyoungKim/Nabee | source/NabeeSAC/src/com/nabsys/resource/service/OutboundHandler.java | 2042 | package com.nabsys.resource.service;
import java.util.HashMap;
import com.nabsys.net.protocol.NBFields;
import com.nabsys.net.socket.channel.IChannelResult;
import com.nabsys.process.Context;
public class OutboundHandler extends ServiceHandler{
/**
*
*/
private static final long serialVersionUID = 1L;
private String telegramID = null;
public OutboundHandler(ServiceHandler parent, int x, int y, int width, int height) {
super(parent, x, y, width, height);
}
public void setData(String telegramID)
{
this.telegramID = telegramID;
((OnlineServiceHandler)getParent()).setOutboundTelegramID(telegramID);
}
public String getTelegramID()
{
return this.telegramID;
}
public void testExecute(Context ctx, HashMap<String, Object> map)
throws Exception {
}
protected void execute(Context ctx, HashMap<String, Object> map) throws Exception
{
if(ctx.isTest())
{
ctx.offerTestMessage(getHandlerID(), "Outbound Network : " + map + "", false, false);
}
else
{
//NBFields fields = setNBFields(map);
NBFields fields = (NBFields)map;
IChannelResult result = ctx.getChannel().write(fields);
if(!result.isSuccess())
{
try {
throw result.getCause();
} catch (Throwable e) {
throw new Exception(e.getMessage());
}
}
}
super.execute(ctx, map);
}
/*@SuppressWarnings("unchecked")
private NBFields setNBFields(HashMap<String, Object> map){
NBFields fields = new NBFields();
Iterator<String> itr = map.keySet().iterator();
while(itr.hasNext()){
String key = itr.next();
if((map.get(key) instanceof ArrayList))
{
ArrayList<Object> list = (ArrayList<Object>)map.get(key);
ArrayList<NBFields> listFields = new ArrayList<NBFields>();
for(int i=0; i<list.size(); i++)
{
HashMap<String, Object> listMap = (HashMap<String, Object>)list.get(i);
listFields.add(setNBFields(listMap));
}
fields.put(key, listFields);
}
else
{
fields.put(key, map.get(key));
}
}
return fields;
}*/
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/test/sun/security/krb5/auto/OneKDC.java | 6163 | /*
* Copyright 2008-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.Security;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import sun.security.krb5.Config;
/**
* This class starts a simple KDC with one realm, several typical principal
* names, generates delete-on-exit krb5.conf and keytab files, and setup
* system properties for them. There's also a helper method to generate a
* JAAS login config file that can be used for JAAS or JGSS apps.
* <p>
* Just call this line to start everything:
* <pre>
* new OneKDC(null).writeJaasConf();
* </pre>
*/
public class OneKDC extends KDC {
public static final String USER = "dummy";
public static final char[] PASS = "bogus".toCharArray();
public static final String KRB5_CONF = "localkdc-krb5.conf";
public static final String KTAB = "localkdc.ktab";
public static final String JAAS_CONF = "localkdc-jaas.conf";
public static final String REALM = "RABBIT.HOLE";
public static String SERVER = "server/host." + REALM.toLowerCase();
public static String BACKEND = "backend/host." + REALM.toLowerCase();
public static String KDCHOST = "kdc." + REALM.toLowerCase();
/**
* Creates the KDC and starts it.
* @param etype Encryption type, null if not specified
* @throws java.lang.Exception if there's anything wrong
*/
public OneKDC(String etype) throws Exception {
super(REALM, KDCHOST, 0, true);
addPrincipal(USER, PASS);
addPrincipalRandKey("krbtgt/" + REALM);
addPrincipalRandKey(SERVER);
addPrincipalRandKey(BACKEND);
KDC.saveConfig(KRB5_CONF, this,
"forwardable = true",
"default_keytab_name = " + KTAB,
etype == null ? "" : "default_tkt_enctypes=" + etype + "\ndefault_tgs_enctypes=" + etype);
System.setProperty("java.security.krb5.conf", KRB5_CONF);
// Whatever krb5.conf had been loaded before, we reload ours now.
Config.refresh();
writeKtab(KTAB);
new File(KRB5_CONF).deleteOnExit();
new File(KTAB).deleteOnExit();
}
/**
* Writes a JAAS login config file, which contains as many as useful
* entries, including JGSS style initiator/acceptor and normal JAAS
* entries with names using existing OneKDC principals.
* @throws java.lang.Exception if anything goes wrong
*/
public void writeJAASConf() throws IOException {
System.setProperty("java.security.auth.login.config", JAAS_CONF);
File f = new File(JAAS_CONF);
FileOutputStream fos = new FileOutputStream(f);
fos.write((
"com.sun.security.jgss.krb5.initiate {\n" +
" com.sun.security.auth.module.Krb5LoginModule required;\n};\n" +
"com.sun.security.jgss.krb5.accept {\n" +
" com.sun.security.auth.module.Krb5LoginModule required\n" +
" principal=\"" + SERVER + "\"\n" +
" useKeyTab=true\n" +
" isInitiator=false\n" +
" storeKey=true;\n};\n" +
"client {\n" +
" com.sun.security.auth.module.Krb5LoginModule required;\n};\n" +
"server {\n" +
" com.sun.security.auth.module.Krb5LoginModule required\n" +
" principal=\"" + SERVER + "\"\n" +
" useKeyTab=true\n" +
" storeKey=true;\n};\n" +
"backend {\n" +
" com.sun.security.auth.module.Krb5LoginModule required\n" +
" principal=\"" + BACKEND + "\"\n" +
" useKeyTab=true\n" +
" storeKey=true\n" +
" isInitiator=false;\n};\n"
).getBytes());
fos.close();
f.deleteOnExit();
Security.setProperty("auth.login.defaultCallbackHandler", "OneKDC$CallbackForClient");
}
/**
* The default callback handler for JAAS login. Note that this handler is
* hard coded to provide only info for USER1. If you need to provide info
* for another principal, please use Context.fromUserPass() instead.
*/
public static class CallbackForClient implements CallbackHandler {
public void handle(Callback[] callbacks) {
String user = OneKDC.USER;
char[] pass = OneKDC.PASS;
for (Callback callback : callbacks) {
if (callback instanceof NameCallback) {
System.out.println("Callback for name: " + user);
((NameCallback) callback).setName(user);
}
if (callback instanceof PasswordCallback) {
System.out.println("Callback for pass: "
+ new String(pass));
((PasswordCallback) callback).setPassword(pass);
}
}
}
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/corba/src/share/classes/javax/rmi/CORBA/Stub.java | 8820 | /*
* Copyright 1998-2004 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Licensed Materials - Property of IBM
* RMI-IIOP v1.0
* Copyright IBM Corp. 1998 1999 All Rights Reserved
*
*/
package javax.rmi.CORBA;
import org.omg.CORBA.ORB;
import org.omg.CORBA.INITIALIZE;
import org.omg.CORBA_2_3.portable.ObjectImpl;
import java.io.IOException;
import java.rmi.RemoteException;
import java.io.File;
import java.io.FileInputStream;
import java.net.MalformedURLException ;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Properties;
import java.rmi.server.RMIClassLoader;
import com.sun.corba.se.impl.orbutil.GetPropertyAction;
/**
* Base class from which all RMI-IIOP stubs must inherit.
*/
public abstract class Stub extends ObjectImpl
implements java.io.Serializable {
private static final long serialVersionUID = 1087775603798577179L;
// This can only be set at object construction time (no sync necessary).
private transient StubDelegate stubDelegate = null;
private static Class stubDelegateClass = null;
private static final String StubClassKey = "javax.rmi.CORBA.StubClass";
private static final String defaultStubImplName = "com.sun.corba.se.impl.javax.rmi.CORBA.StubDelegateImpl";
static {
Object stubDelegateInstance = (Object) createDelegateIfSpecified(StubClassKey, defaultStubImplName);
if (stubDelegateInstance != null)
stubDelegateClass = stubDelegateInstance.getClass();
}
/**
* Returns a hash code value for the object which is the same for all stubs
* that represent the same remote object.
* @return the hash code value.
*/
public int hashCode() {
if (stubDelegate == null) {
setDefaultDelegate();
}
if (stubDelegate != null) {
return stubDelegate.hashCode(this);
}
return 0;
}
/**
* Compares two stubs for equality. Returns <code>true</code> when used to compare stubs
* that represent the same remote object, and <code>false</code> otherwise.
* @param obj the reference object with which to compare.
* @return <code>true</code> if this object is the same as the <code>obj</code>
* argument; <code>false</code> otherwise.
*/
public boolean equals(java.lang.Object obj) {
if (stubDelegate == null) {
setDefaultDelegate();
}
if (stubDelegate != null) {
return stubDelegate.equals(this, obj);
}
return false;
}
/**
* Returns a string representation of this stub. Returns the same string
* for all stubs that represent the same remote object.
* @return a string representation of this stub.
*/
public String toString() {
if (stubDelegate == null) {
setDefaultDelegate();
}
String ior;
if (stubDelegate != null) {
ior = stubDelegate.toString(this);
if (ior == null) {
return super.toString();
} else {
return ior;
}
}
return super.toString();
}
/**
* Connects this stub to an ORB. Required after the stub is deserialized
* but not after it is demarshalled by an ORB stream. If an unconnected
* stub is passed to an ORB stream for marshalling, it is implicitly
* connected to that ORB. Application code should not call this method
* directly, but should call the portable wrapper method
* {@link javax.rmi.PortableRemoteObject#connect}.
* @param orb the ORB to connect to.
* @exception RemoteException if the stub is already connected to a different
* ORB, or if the stub does not represent an exported remote or local object.
*/
public void connect(ORB orb) throws RemoteException {
if (stubDelegate == null) {
setDefaultDelegate();
}
if (stubDelegate != null) {
stubDelegate.connect(this, orb);
}
}
/**
* Serialization method to restore the IOR state.
*/
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException {
if (stubDelegate == null) {
setDefaultDelegate();
}
if (stubDelegate != null) {
stubDelegate.readObject(this, stream);
}
}
/**
* Serialization method to save the IOR state.
* @serialData The length of the IOR type ID (int), followed by the IOR type ID
* (byte array encoded using ISO8859-1), followed by the number of IOR profiles
* (int), followed by the IOR profiles. Each IOR profile is written as a
* profile tag (int), followed by the length of the profile data (int), followed
* by the profile data (byte array).
*/
private void writeObject(java.io.ObjectOutputStream stream) throws IOException {
if (stubDelegate == null) {
setDefaultDelegate();
}
if (stubDelegate != null) {
stubDelegate.writeObject(this, stream);
}
}
private void setDefaultDelegate() {
if (stubDelegateClass != null) {
try {
stubDelegate = (javax.rmi.CORBA.StubDelegate) stubDelegateClass.newInstance();
} catch (Exception ex) {
// what kind of exception to throw
// delegate not set therefore it is null and will return default
// values
}
}
}
// Same code as in PortableRemoteObject. Can not be shared because they
// are in different packages and the visibility needs to be package for
// security reasons. If you know a better solution how to share this code
// then remove it from PortableRemoteObject. Also in Util.java
private static Object createDelegateIfSpecified(String classKey, String defaultClassName) {
String className = (String)
AccessController.doPrivileged(new GetPropertyAction(classKey));
if (className == null) {
Properties props = getORBPropertiesFile();
if (props != null) {
className = props.getProperty(classKey);
}
}
if (className == null) {
className = defaultClassName;
}
try {
return loadDelegateClass(className).newInstance();
} catch (ClassNotFoundException ex) {
INITIALIZE exc = new INITIALIZE( "Cannot instantiate " + className);
exc.initCause( ex ) ;
throw exc ;
} catch (Exception ex) {
INITIALIZE exc = new INITIALIZE( "Error while instantiating" + className);
exc.initCause( ex ) ;
throw exc ;
}
}
private static Class loadDelegateClass( String className ) throws ClassNotFoundException
{
try {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
return Class.forName(className, false, loader);
} catch (ClassNotFoundException e) {
// ignore, then try RMIClassLoader
}
try {
return RMIClassLoader.loadClass(className);
} catch (MalformedURLException e) {
String msg = "Could not load " + className + ": " + e.toString();
ClassNotFoundException exc = new ClassNotFoundException( msg ) ;
throw exc ;
}
}
/**
* Load the orb.properties file.
*/
private static Properties getORBPropertiesFile () {
return (Properties) AccessController.doPrivileged(new GetORBPropertiesFileAction());
}
}
| gpl-2.0 |
diging/quadriga | Quadriga/src/main/java/edu/asu/spring/quadriga/mapper/WorkspaceDTOMapper.java | 6264 | package edu.asu.spring.quadriga.mapper;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import edu.asu.spring.quadriga.domain.factory.workspace.IWorkspaceFactory;
import edu.asu.spring.quadriga.domain.workspace.IWorkspace;
import edu.asu.spring.quadriga.dto.ConceptCollectionDTO;
import edu.asu.spring.quadriga.dto.DictionaryDTO;
import edu.asu.spring.quadriga.dto.ProjectDTO;
import edu.asu.spring.quadriga.dto.WorkspaceConceptcollectionDTO;
import edu.asu.spring.quadriga.dto.WorkspaceConceptcollectionDTOPK;
import edu.asu.spring.quadriga.dto.WorkspaceDTO;
import edu.asu.spring.quadriga.dto.WorkspaceDictionaryDTO;
import edu.asu.spring.quadriga.dto.WorkspaceDictionaryDTOPK;
import edu.asu.spring.quadriga.dto.WorkspaceEditorDTO;
import edu.asu.spring.quadriga.dto.WorkspaceEditorDTOPK;
import edu.asu.spring.quadriga.exceptions.QuadrigaStorageException;
import edu.asu.spring.quadriga.mapper.workbench.IProjectShallowMapper;
import edu.asu.spring.quadriga.service.IUserManager;
@Service
public class WorkspaceDTOMapper extends BaseMapper {
@Autowired
private IWorkspaceFactory workspaceFactory;
@Autowired
private IProjectShallowMapper projectMapper;
@Autowired
private IUserManager userManager;
public WorkspaceDTO getWorkspaceDTO(IWorkspace iWorkSpace) {
WorkspaceDTO workspaceDTO = new WorkspaceDTO();
workspaceDTO.setWorkspacename(iWorkSpace.getWorkspaceName());
workspaceDTO.setDescription(iWorkSpace.getDescription());
workspaceDTO.setWorkspaceowner((getUserDTO(iWorkSpace.getOwner().getUserName())));
workspaceDTO.setIsarchived(false);
workspaceDTO.setIsdeactivated(false);
workspaceDTO.setUpdatedby(iWorkSpace.getOwner().getUserName());
workspaceDTO.setUpdateddate(new Date());
workspaceDTO.setCreatedby(iWorkSpace.getOwner().getUserName());
workspaceDTO.setCreateddate(new Date());
return workspaceDTO;
}
public IWorkspace getWorkSpace(WorkspaceDTO workspaceDTO) throws QuadrigaStorageException
{
IWorkspace workSpace = workspaceFactory.createWorkspaceObject();
workSpace.setWorkspaceName(workspaceDTO.getWorkspacename());
workSpace.setDescription(workspaceDTO.getDescription());
workSpace.setWorkspaceId(workspaceDTO.getWorkspaceid());
workSpace.setOwner(userManager.getUser(workspaceDTO.getWorkspaceowner().getUsername()));
ProjectDTO projectDto = workspaceDTO.getProjectWorkspaceDTO().getProjectDTO();
workSpace.setProject(projectMapper.getProject(projectDto));
return workSpace;
}
public List<IWorkspace> getWorkSpaceList(List<WorkspaceDTO> workspaceDTOList) throws QuadrigaStorageException
{
Iterator<WorkspaceDTO> workspaceItr = workspaceDTOList.listIterator();
List<IWorkspace> workspaceList = new ArrayList<IWorkspace>();
while(workspaceItr.hasNext())
{
WorkspaceDTO workspaceDTO = workspaceItr.next();
workspaceList.add(getWorkSpace(workspaceDTO));
}
return workspaceList;
}
/**
* This method associates editor with the workspace supplied
* @param workspace
* @param userName
* @return WorkspaceEditorDTO object
* @throws QuadrigaStorageException
*/
public WorkspaceEditorDTO getWorkspaceEditor(WorkspaceDTO workspace, String userName) throws QuadrigaStorageException
{
WorkspaceEditorDTO workspaceEditor = null;
WorkspaceEditorDTOPK workspaceEditorKey = null;
Date date = new Date();
workspaceEditor = new WorkspaceEditorDTO();
workspaceEditorKey = new WorkspaceEditorDTOPK(workspace.getWorkspaceid(),userName);
workspaceEditor.setWorkspaceEditorDTOPK(workspaceEditorKey);
workspaceEditor.setWorkspaceDTO(workspace);
workspaceEditor.setQuadrigaUserDTO(getUserDTO(userName));
workspaceEditor.setCreatedby(userName);
workspaceEditor.setCreateddate(date);
workspaceEditor.setUpdatedby(userName);
workspaceEditor.setUpdateddate(date);
return workspaceEditor;
}
/**
* This method associates the concept collection to the given workspace.
* @param workspace
* @param conceptCollection
* @param userName
* @return WorkspaceConceptCollectionDTO object
*/
public WorkspaceConceptcollectionDTO getWorkspaceConceptCollection(WorkspaceDTO workspace, ConceptCollectionDTO conceptCollection,String userName)
{
WorkspaceConceptcollectionDTO workspaceConceptCollection = null;
WorkspaceConceptcollectionDTOPK workspaceConceptCollectionKey = null;
Date date = new Date();
workspaceConceptCollectionKey = new WorkspaceConceptcollectionDTOPK(workspace.getWorkspaceid(),conceptCollection.getConceptCollectionid());
workspaceConceptCollection = new WorkspaceConceptcollectionDTO();
workspaceConceptCollection.setWorkspaceConceptcollectionDTOPK(workspaceConceptCollectionKey);
workspaceConceptCollection.setWorkspaceDTO(workspace);
workspaceConceptCollection.setConceptCollectionDTO(conceptCollection);
workspaceConceptCollection.setCreatedby(userName);
workspaceConceptCollection.setCreateddate(date);
workspaceConceptCollection.setUpdatedby(userName);
workspaceConceptCollection.setUpdateddate(date);
return workspaceConceptCollection;
}
/**
* This method associates the dictionary to the given workspace.
* @param workspace
* @param dictionary
* @param userName
* @return WorkspaceConceptCollectionDTO object
*/
public WorkspaceDictionaryDTO getWorkspaceDictionary(WorkspaceDTO workspace, DictionaryDTO dictionary, String userName)
{
WorkspaceDictionaryDTO workspaceDictionary = null;
WorkspaceDictionaryDTOPK workspaceDictionaryKey = null;
Date date = new Date();
workspaceDictionaryKey = new WorkspaceDictionaryDTOPK(workspace.getWorkspaceid(),dictionary.getDictionaryid());
workspaceDictionary = new WorkspaceDictionaryDTO();
workspaceDictionary.setWorkspaceDictionaryDTOPK(workspaceDictionaryKey);
workspaceDictionary.setCreatedby(userName);
workspaceDictionary.setCreateddate(date);
workspaceDictionary.setUpdatedby(userName);
workspaceDictionary.setUpdateddate(date);
workspaceDictionary.setDictionaryDTO(dictionary);
workspaceDictionary.setWorkspaceDTO(workspace);
return workspaceDictionary;
}
}
| gpl-2.0 |
mneedham/jvmtop | jvmtop/src/com/jvmtop/profiler/MethodStats.java | 2903 | /**
* jvmtop - java monitoring for the command-line
*
* Copyright (C) 2013 by Patric Rufflar. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package com.jvmtop.profiler;
import java.util.concurrent.atomic.AtomicLong;
/**
* Stores method invocations in a thread-safe manner.
*
* @author paru
*
*/
public class MethodStats implements Comparable<MethodStats>
{
private AtomicLong hits_ = new AtomicLong(0);
private String className_ = null;
private String methodName_ = null;
/**
* @param className
* @param methodName
*/
public MethodStats(String className, String methodName)
{
super();
className_ = className;
methodName_ = methodName;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result
+ ((className_ == null) ? 0 : className_.hashCode());
result = prime * result
+ ((methodName_ == null) ? 0 : methodName_.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
MethodStats other = (MethodStats) obj;
if (className_ == null)
{
if (other.className_ != null)
{
return false;
}
}
else if (!className_.equals(other.className_))
{
return false;
}
if (methodName_ == null)
{
if (other.methodName_ != null)
{
return false;
}
}
else if (!methodName_.equals(other.methodName_))
{
return false;
}
return true;
}
@Override
/**
* Compares a MethodStats object by its hits
*/
public int compareTo(MethodStats o)
{
return Long.valueOf(o.hits_.get()).compareTo(hits_.get());
}
public AtomicLong getHits()
{
return hits_;
}
public String getClassName()
{
return className_;
}
public String getMethodName()
{
return methodName_;
}
} | gpl-2.0 |
panbasten/imeta | imeta2.x/imeta-src/imeta/src/main/java/com/panet/imeta/job/entries/sftpput/JobEntrySFTPPUT.java | 19257 | /* Copyright (c) 2007 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho
* Data Integration. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.*/
package com.panet.imeta.job.entries.sftpput;
import static com.panet.imeta.job.entry.validator.AndValidator.putValidators;
import static com.panet.imeta.job.entry.validator.JobEntryValidatorUtils.andValidator;
import static com.panet.imeta.job.entry.validator.JobEntryValidatorUtils.fileExistsValidator;
import static com.panet.imeta.job.entry.validator.JobEntryValidatorUtils.integerValidator;
import static com.panet.imeta.job.entry.validator.JobEntryValidatorUtils.notBlankValidator;
import static com.panet.imeta.job.entry.validator.JobEntryValidatorUtils.notNullValidator;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileType;
import org.w3c.dom.Node;
import com.panet.imeta.cluster.SlaveServer;
import com.panet.imeta.core.CheckResultInterface;
import com.panet.imeta.core.Const;
import com.panet.imeta.core.Result;
import com.panet.imeta.core.ResultFile;
import com.panet.imeta.core.RowMetaAndData;
import com.panet.imeta.core.database.DatabaseMeta;
import com.panet.imeta.core.encryption.Encr;
import com.panet.imeta.core.exception.KettleDatabaseException;
import com.panet.imeta.core.exception.KettleException;
import com.panet.imeta.core.exception.KettleXMLException;
import com.panet.imeta.core.logging.LogWriter;
import com.panet.imeta.core.vfs.KettleVFS;
import com.panet.imeta.core.xml.XMLHandler;
import com.panet.imeta.job.Job;
import com.panet.imeta.job.JobEntryType;
import com.panet.imeta.job.JobMeta;
import com.panet.imeta.job.entries.sftp.SFTPClient;
import com.panet.imeta.job.entry.JobEntryBase;
import com.panet.imeta.job.entry.JobEntryInterface;
import com.panet.imeta.repository.Repository;
import com.panet.imeta.resource.ResourceEntry;
import com.panet.imeta.resource.ResourceReference;
import com.panet.imeta.resource.ResourceEntry.ResourceType;
import com.panet.imeta.shared.SharedObjectInterface;
/**
* This defines an SFTP put job entry.
*
* @author Matt
* @since 05-11-2003
*
*/
public class JobEntrySFTPPUT extends JobEntryBase implements Cloneable,
JobEntryInterface {
private String serverName;
private String serverPort;
private String userName;
private String password;
private String sftpDirectory;
private String localDirectory;
private String wildcard;
private boolean remove;
private boolean copyprevious;
private boolean addFilenameResut;
public JobEntrySFTPPUT(String n) {
super(n, "");
serverName = null;
serverPort = "22";
copyprevious = false;
addFilenameResut = false;
setID(-1L);
setJobEntryType(JobEntryType.SFTPPUT);
}
public JobEntrySFTPPUT() {
this("");
}
public JobEntrySFTPPUT(JobEntryBase jeb) {
super(jeb);
}
public Object clone() {
JobEntrySFTPPUT je = (JobEntrySFTPPUT) super.clone();
return je;
}
public String getXML() {
StringBuffer retval = new StringBuffer(300);
retval.append(super.getXML());
retval.append(" ").append(
XMLHandler.addTagValue("servername", serverName));
retval.append(" ").append(
XMLHandler.addTagValue("serverport", serverPort));
retval.append(" ").append(
XMLHandler.addTagValue("username", userName));
retval.append(" ").append(
XMLHandler.addTagValue("password", Encr
.encryptPasswordIfNotUsingVariables(password)));
retval.append(" ").append(
XMLHandler.addTagValue("sftpdirectory", sftpDirectory));
retval.append(" ").append(
XMLHandler.addTagValue("localdirectory", localDirectory));
retval.append(" ").append(
XMLHandler.addTagValue("wildcard", wildcard));
retval.append(" ")
.append(XMLHandler.addTagValue("remove", remove));
retval.append(" ").append(
XMLHandler.addTagValue("copyprevious", copyprevious));
retval.append(" ").append(
XMLHandler.addTagValue("addFilenameResut", addFilenameResut));
return retval.toString();
}
public void loadXML(Node entrynode, List<DatabaseMeta> databases,
List<SlaveServer> slaveServers, Repository rep)
throws KettleXMLException {
try {
super.loadXML(entrynode, databases, slaveServers);
serverName = XMLHandler.getTagValue(entrynode, "servername");
serverPort = XMLHandler.getTagValue(entrynode, "serverport");
userName = XMLHandler.getTagValue(entrynode, "username");
password = Encr.decryptPasswordOptionallyEncrypted(XMLHandler
.getTagValue(entrynode, "password"));
sftpDirectory = XMLHandler.getTagValue(entrynode, "sftpdirectory");
localDirectory = XMLHandler
.getTagValue(entrynode, "localdirectory");
wildcard = XMLHandler.getTagValue(entrynode, "wildcard");
remove = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode,
"remove"));
copyprevious = "Y".equalsIgnoreCase(XMLHandler.getTagValue(
entrynode, "copyprevious"));
addFilenameResut = "Y".equalsIgnoreCase(XMLHandler.getTagValue(
entrynode, "addFilenameResut"));
} catch (KettleXMLException xe) {
throw new KettleXMLException(
"Unable to load job entry of type 'SFTPPUT' from XML node",
xe);
}
}
public void setInfo(Map<String, String[]> p, String id,
List<? extends SharedObjectInterface> databases) {
serverName = JobEntryBase.parameterToString(p.get(id + ".serverName"));
serverPort = JobEntryBase.parameterToString(p.get(id + ".serverPort"));
userName = JobEntryBase.parameterToString(p.get(id + ".userName"));
password = JobEntryBase.parameterToString(p.get(id + ".password"));
sftpDirectory = JobEntryBase.parameterToString(p.get(id
+ ".sftpDirectory"));
localDirectory = JobEntryBase.parameterToString(p.get(id
+ ".localDirectory"));
remove = JobEntryBase.parameterToBoolean(p.get(id + ".remove"));
copyprevious = JobEntryBase.parameterToBoolean(p.get(id
+ ".copyprevious"));
addFilenameResut = JobEntryBase.parameterToBoolean(p.get(id
+ ".addFilenameResut"));
wildcard = JobEntryBase.parameterToString(p.get(id + ".wildcard"));
}
public void loadRep(Repository rep, long id_jobentry,
List<DatabaseMeta> databases, List<SlaveServer> slaveServers)
throws KettleException {
try {
super.loadRep(rep, id_jobentry, databases, slaveServers);
serverName = rep.getJobEntryAttributeString(id_jobentry,
"servername");
int intServerPort = (int) rep.getJobEntryAttributeInteger(
id_jobentry, "serverport");
serverPort = rep.getJobEntryAttributeString(id_jobentry,
"serverport"); // backward compatible.
if (intServerPort > 0 && Const.isEmpty(serverPort))
serverPort = Integer.toString(intServerPort);
userName = rep.getJobEntryAttributeString(id_jobentry, "username");
password = Encr.decryptPasswordOptionallyEncrypted(rep
.getJobEntryAttributeString(id_jobentry, "password"));
sftpDirectory = rep.getJobEntryAttributeString(id_jobentry,
"sftpdirectory");
localDirectory = rep.getJobEntryAttributeString(id_jobentry,
"localdirectory");
wildcard = rep.getJobEntryAttributeString(id_jobentry, "wildcard");
remove = rep.getJobEntryAttributeBoolean(id_jobentry, "remove");
copyprevious = rep.getJobEntryAttributeBoolean(id_jobentry,
"copyprevious");
addFilenameResut = rep.getJobEntryAttributeBoolean(id_jobentry,
"addFilenameResut");
} catch (KettleException dbe) {
throw new KettleException(
"Unable to load job entry of type 'SFTPPUT' from the repository for id_jobentry="
+ id_jobentry, dbe);
}
}
public void saveRep(Repository rep, long id_job) throws KettleException {
try {
super.saveRep(rep, id_job);
rep
.saveJobEntryAttribute(id_job, getID(), "servername",
serverName);
rep
.saveJobEntryAttribute(id_job, getID(), "serverport",
serverPort);
rep.saveJobEntryAttribute(id_job, getID(), "username", userName);
rep.saveJobEntryAttribute(id_job, getID(), "password", Encr
.encryptPasswordIfNotUsingVariables(password));
rep.saveJobEntryAttribute(id_job, getID(), "sftpdirectory",
sftpDirectory);
rep.saveJobEntryAttribute(id_job, getID(), "localdirectory",
localDirectory);
rep.saveJobEntryAttribute(id_job, getID(), "wildcard", wildcard);
rep.saveJobEntryAttribute(id_job, getID(), "remove", remove);
rep.saveJobEntryAttribute(id_job, getID(), "copyprevious",
copyprevious);
rep.saveJobEntryAttribute(id_job, getID(), "addFilenameResut",
addFilenameResut);
} catch (KettleDatabaseException dbe) {
throw new KettleException(
"Unable to load job entry of type 'SFTPPUT' to the repository for id_job="
+ id_job, dbe);
}
}
/**
* @return Returns the directory.
*/
public String getScpDirectory() {
return sftpDirectory;
}
/**
* @param directory
* The directory to set.
*/
public void setScpDirectory(String directory) {
this.sftpDirectory = directory;
}
/**
* @return Returns the password.
*/
public String getPassword() {
return password;
}
/**
* @param password
* The password to set.
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return Returns the serverName.
*/
public String getServerName() {
return serverName;
}
/**
* @param serverName
* The serverName to set.
*/
public void setServerName(String serverName) {
this.serverName = serverName;
}
/**
* @return Returns the userName.
*/
public String getUserName() {
return userName;
}
/**
* @param userName
* The userName to set.
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* @return Returns the wildcard.
*/
public String getWildcard() {
return wildcard;
}
/**
* @param wildcard
* The wildcard to set.
*/
public void setWildcard(String wildcard) {
this.wildcard = wildcard;
}
/**
* @return Returns the localdirectory.
*/
public String getLocalDirectory() {
return localDirectory;
}
/**
* @param localDirectory
* The localDirectory to set.
*/
public void setLocalDirectory(String localDirectory) {
this.localDirectory = localDirectory;
}
/**
* @param remove
* The remove to set.
*/
public void setRemove(boolean remove) {
this.remove = remove;
}
/**
* @return Returns the remove.
*/
public boolean getRemove() {
return remove;
}
public boolean isCopyPrevious() {
return copyprevious;
}
public void setCopyPrevious(boolean copyprevious) {
this.copyprevious = copyprevious;
}
public boolean isAddFilenameResut() {
return addFilenameResut;
}
public void setAddFilenameResut(boolean addFilenameResut) {
this.addFilenameResut = addFilenameResut;
}
public String getServerPort() {
return serverPort;
}
public void setServerPort(String serverPort) {
this.serverPort = serverPort;
}
public Result execute(Result previousResult, int nr, Repository rep,
Job parentJob) throws KettleException {
LogWriter log = LogWriter.getInstance();
Result result = previousResult;
List<RowMetaAndData> rows = result.getRows();
result.setResult(false);
if (log.isDetailed())
log.logDetailed(toString(), Messages
.getString("JobSFTPPUT.Log.StartJobEntry"));
ArrayList<FileObject> myFileList = new ArrayList<FileObject>();
if (copyprevious) {
if (rows.size() == 0) {
if (log.isDetailed())
log.logDetailed(toString(), Messages
.getString("JobSFTPPUT.ArgsFromPreviousNothing"));
result.setResult(true);
return result;
}
try {
RowMetaAndData resultRow = null;
// Copy the input row to the (command line) arguments
for (int iteration = 0; iteration < rows.size(); iteration++) {
resultRow = rows.get(iteration);
// Get file names
String file_previous = resultRow.getString(0, null);
if (!Const.isEmpty(file_previous)) {
FileObject file = KettleVFS
.getFileObject(file_previous);
if (!file.exists())
log.logError(toString(), Messages.getString(
"JobSFTPPUT.Log.FilefromPreviousNotFound",
file_previous));
else {
myFileList.add(file);
if (log.isDebug())
log.logDebug(toString(), Messages.getString(
"JobSFTPPUT.Log.FilenameFromResult",
file_previous));
}
}
}
} catch (Exception e) {
log.logError(toString(), Messages
.getString("JobSFTPPUT.Error.ArgFromPrevious"));
result.setNrErrors(1);
return result;
}
}
SFTPClient sftpclient = null;
// String substitution..
String realServerName = environmentSubstitute(serverName);
String realServerPort = environmentSubstitute(serverPort);
String realUsername = environmentSubstitute(userName);
String realPassword = environmentSubstitute(password);
String realSftpDirString = environmentSubstitute(sftpDirectory);
String realWildcard = environmentSubstitute(wildcard);
String realLocalDirectory = environmentSubstitute(localDirectory);
try {
// Create sftp client to host ...
sftpclient = new SFTPClient(InetAddress.getByName(realServerName),
Const.toInt(realServerPort, 22), realUsername);
if (log.isDetailed())
log.logDetailed(toString(), Messages.getString(
"JobSFTPPUT.Log.OpenedConnection", realServerName, ""
+ realServerPort, realUsername));
// login to ftp host ...
sftpclient.login(realPassword);
// Don't show the password in the logs, it's not good for security
// audits
// log.logDetailed(toString(), "logged in using password
// "+realPassword); // Logging this seems a bad idea! Oh well.
// move to spool dir ...
if (!Const.isEmpty(realSftpDirString)) {
sftpclient.chdir(realSftpDirString);
if (log.isDetailed())
log.logDetailed(toString(), Messages.getString(
"JobSFTPPUT.Log.ChangedDirectory",
realSftpDirString));
} // end if
if (!copyprevious) {
// Get all the files in the local directory...
myFileList = new ArrayList<FileObject>();
FileObject localFiles = KettleVFS
.getFileObject(realLocalDirectory);
FileObject[] children = localFiles.getChildren();
if (children != null) {
for (int i = 0; i < children.length; i++) {
// Get filename of file or directory
if (children[i].getType().equals(FileType.FILE)) {
// myFileList.add(children[i].getAbsolutePath());
myFileList.add(children[i]);
}
} // end for
}
}
if (myFileList == null || myFileList.size() == 0) {
log.logError(toString(), Messages
.getString("JobSFTPPUT.Error.NoFileToSend"));
result.setNrErrors(1);
return result;
}
if (log.isDetailed())
log.logDetailed(toString(), Messages.getString(
"JobSFTPPUT.Log.RowsFromPreviousResult", ""
+ myFileList.size()));
Pattern pattern = null;
if (!copyprevious) {
if (!Const.isEmpty(realWildcard)) {
pattern = Pattern.compile(realWildcard);
}
}
// Get the files in the list and execute sftp.put() for each file
for (int i = 0; i < myFileList.size() && !parentJob.isStopped(); i++) {
FileObject myFile = myFileList.get(i);
String localFilename = myFile.toString();
String destinationFilename = myFile.getName().getBaseName();
boolean getIt = true;
// First see if the file matches the regular expression!
if (pattern != null) {
Matcher matcher = pattern.matcher(destinationFilename);
getIt = matcher.matches();
}
if (getIt) {
if (log.isDebug())
log.logDebug(toString(), Messages.getString(
"JobSFTPPUT.Log.PuttingFile", localFilename,
realSftpDirString));
sftpclient.put(myFile, destinationFilename);
if (log.isDetailed())
log
.logDetailed(toString(), Messages.getString(
"JobSFTPPUT.Log.TransferedFile",
localFilename));
// Delete the file if this is needed!
if (remove) {
myFile.delete();
if (log.isDetailed())
log.logDetailed(toString(), Messages
.getString("JobSFTPPUT.Log.DeletedFile",
localFilename));
} else {
if (addFilenameResut) {
// Add to the result files...
ResultFile resultFile = new ResultFile(
ResultFile.FILE_TYPE_GENERAL, myFile,
parentJob.getJobname(), toString());
result.getResultFiles()
.put(resultFile.getFile().toString(),
resultFile);
if (log.isDetailed())
log
.logDetailed(
toString(),
Messages
.getString(
"JobSFTPPUT.Log.FilenameAddedToResultFilenames",
localFilename));
}
}
}
} // end for
result.setResult(true);
// JKU: no idea if this is needed...!
// result.setNrFilesRetrieved(filesRetrieved);
} // end try
catch (Exception e) {
result.setNrErrors(1);
log.logError(toString(), Messages.getString("JobSFTPPUT.Exception",
e.getMessage()));
log.logError(toString(), Const.getStackTracker(e));
} finally {
// close connection, if possible
try {
if (sftpclient != null)
sftpclient.disconnect();
} catch (Exception e) {
// just ignore this, makes no big difference
} // end catch
} // end finallly
return result;
} // JKU: end function execute()
public boolean evaluates() {
return true;
}
public List<ResourceReference> getResourceDependencies(JobMeta jobMeta) {
List<ResourceReference> references = super
.getResourceDependencies(jobMeta);
if (!Const.isEmpty(serverName)) {
String realServerName = jobMeta.environmentSubstitute(serverName);
ResourceReference reference = new ResourceReference(this);
reference.getEntries().add(
new ResourceEntry(realServerName, ResourceType.SERVER));
references.add(reference);
}
return references;
}
@Override
public void check(List<CheckResultInterface> remarks, JobMeta jobMeta) {
andValidator().validate(this,
"serverName", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$
andValidator()
.validate(
this,
"localDirectory", remarks, putValidators(notBlankValidator(), fileExistsValidator())); //$NON-NLS-1$
andValidator().validate(this,
"userName", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$
andValidator().validate(this,
"password", remarks, putValidators(notNullValidator())); //$NON-NLS-1$
andValidator().validate(this,
"serverPort", remarks, putValidators(integerValidator())); //$NON-NLS-1$
}
}
| gpl-2.0 |
akerigan/born-again-snark | src/main/java/org/torrent/snark/ShutdownListener.java | 1096 | /*
* ShutdownListener - Callback for end of shutdown sequence
*
* Copyright (C) 2003 Mark J. Wielaard
*
* This file is part of Snark.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.torrent.snark;
/**
* Callback for end of shutdown sequence.
*/
public interface ShutdownListener
{
/**
* Called when the SnarkShutdown hook has finished shutting down all
* subcomponents.
*/
void shutdown ();
}
| gpl-2.0 |
moio/spacewalk | java/code/src/com/redhat/rhn/domain/monitoring/command/IntegerValidator.java | 1814 | /**
* Copyright (c) 2009--2014 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package com.redhat.rhn.domain.monitoring.command;
import org.apache.commons.lang.StringUtils;
/**
* Validator for integer parameters
* @version $Rev$
*/
class IntegerValidator extends ParameterValidator {
public IntegerValidator(CommandParameter cp) {
super(cp);
}
/**
* {@inheritDoc}
*/
public boolean inRange(String value) {
if (value == null) {
return true;
}
int i = Integer.parseInt(value);
Integer min = getParam().getMinValue();
Integer max = getParam().getMaxValue();
return ((min == null || min.intValue() <= i) &&
(max == null || i <= max.intValue()));
}
/**
* {@inheritDoc}
*/
public String normalize(String value) {
value = super.normalize(value);
return StringUtils.stripToNull(value);
}
/**
* {@inheritDoc}
*/
public boolean isConvertible(String value) {
if (value == null) {
return true;
}
try {
Integer.parseInt(value);
return true;
}
catch (NumberFormatException e) {
return false;
}
}
}
| gpl-2.0 |
idclxvii/SharpFixAndroid | src/tk/idclxvii/sharpfixandroid/BootReceiver.java | 4227 | /*
* BootReceiver.java
* 1.1.2 Alpha Release Version
*
* Magarzo, Randolf Josef V.
* Copyright (c) 2013 Magarzo, Randolf Josef V.
* Project SharpFix Android
*
* SHARPFIX ANDROID FILE MANAGEMENT UTILITY 2014 - 2015
* Area of Computer Science College of Accountancy,
* Business Administration and Computer Studies
* San Sebastian College - Recoletos, Manila, Philippines
*
* 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 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 tk.idclxvii.sharpfixandroid;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.app.*;
import android.content.*;
import tk.idclxvii.sharpfixandroid.databasemodel.*;
import tk.idclxvii.sharpfixandroid.utils.AndroidUtils;
import tk.idclxvii.sharpfixandroid.utils.FileProperties;
/**
* This class is a sub class of {@link BroadcastReceiver} receiving broadcasts from
* the mobile device and waits for the intent {@link android.intent.action.BOOT_COMPLETED}
* before it starts its tasks
* <br />
* <br />
* Basically, this class sets the Alarm of the Services whenever the mobile device completed
* booting. All alarms get reset when the device is turned off, so the solution for that is
* to re-set the user preferred time of Alarm whenever the device has successfully completed
* booting.
*
* @version 1.1.2 Alpha Release Version
* @author Magarzo, Randolf Josef V.
*
*/
public class BootReceiver extends BroadcastReceiver {
/**
* The TAG to be used by {@link android.util.Log}
* when performing {@code Logcat} operations.
*/
private final String TAG = this.getClass().getSimpleName();
/**
* The List of Strings containing the logged operations
* @see {@link AndroidUtils#logProgressReport(Context, String[])}
*/
private List<String> logs = new ArrayList<String>();
@Override
public void onReceive(final Context context, Intent intent) {
final SQLiteHelper db = new SQLiteHelper(context);
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
logs.add(AndroidUtils.convertMillis(System.currentTimeMillis())+ TAG +
": Boot completed at: " + FileProperties.formatFileLastMod(System.currentTimeMillis()));
// Set the alarm here.
new GlobalAsyncTask<Void, Void, Void>(){
@Override
protected Void doTask(Void... params) throws Exception {
// TODO Auto-generated method stub
//android.os.Debug.waitForDebugger();
Calendar c = Calendar.getInstance();
c.setTimeInMillis(System.currentTimeMillis());
ModelPreferences mp = (ModelPreferences) db.selectAll(Tables.preferences, ModelPreferences.class, null)[0];
c.set(Calendar.HOUR_OF_DAY, mp.getSss_hh());
c.set(Calendar.MINUTE, mp.getSss_mm());
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, Alarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(),
/*((mp.getSss_repeat() != 7) ? AlarmManager.INTERVAL_DAY * 7 :*/ AlarmManager.INTERVAL_DAY
, pendingIntent);
logs.add(AndroidUtils.convertMillis(System.currentTimeMillis()) + TAG + ": Setting CPU Alarm at " +
mp.getSss_hh() + " : " + mp.getSss_mm());
AndroidUtils.logProgressReport(context, logs.toArray(new String[logs.size()]));
return null;
}
@Override
protected void onException(Exception e) {
// TODO Auto-generated method stub
}
}.executeOnExecutor(tk.idclxvii.sharpfixandroid.utils.AsyncTask.THREAD_POOL_EXECUTOR);
}
}
}
| gpl-2.0 |
PauloSantos13/android | src/com/owncloud/android/ui/activity/PassCodeActivity.java | 20720 | /**
* ownCloud Android client application
*
* @author Bartek Przybylski
* @author masensio
* @author David A. Velasco
* Copyright (C) 2011 Bartek Przybylski
* Copyright (C) 2016 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://www.gnu.org/licenses/>.
*
*/
package com.owncloud.android.ui.activity;
import java.util.Arrays;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.owncloud.android.BuildConfig;
import com.owncloud.android.R;
import com.owncloud.android.lib.common.utils.Log_OC;
public class PassCodeActivity extends AppCompatActivity {
private static final String TAG = PassCodeActivity.class.getSimpleName();
public final static String ACTION_REQUEST_WITH_RESULT = "ACTION_REQUEST_WITH_RESULT";
public final static String ACTION_CHECK_WITH_RESULT = "ACTION_CHECK_WITH_RESULT";
public final static String ACTION_CHECK = "ACTION_CHECK";
public final static String KEY_PASSCODE = "KEY_PASSCODE";
public final static String KEY_CHECK_RESULT = "KEY_CHECK_RESULT";
// NOTE: PREFERENCE_SET_PASSCODE must have the same value as preferences.xml-->android:key for passcode preference
public final static String PREFERENCE_SET_PASSCODE = "set_pincode";
public final static String PREFERENCE_PASSCODE_D = "PrefPinCode";
public final static String PREFERENCE_PASSCODE_D1 = "PrefPinCode1";
public final static String PREFERENCE_PASSCODE_D2 = "PrefPinCode2";
public final static String PREFERENCE_PASSCODE_D3 = "PrefPinCode3";
public final static String PREFERENCE_PASSCODE_D4 = "PrefPinCode4";
private Button mBCancel;
private TextView mPassCodeHdr;
private TextView mPassCodeHdrExplanation;
private EditText[] mPassCodeEditTexts = new EditText[4];
private String [] mPassCodeDigits = {"","","",""};
private static String KEY_PASSCODE_DIGITS = "PASSCODE_DIGITS";
private boolean mConfirmingPassCode = false;
private static String KEY_CONFIRMING_PASSCODE = "CONFIRMING_PASSCODE";
private boolean mBChange = true; // to control that only one blocks jump
/**
* Initializes the activity.
*
* An intent with a valid ACTION is expected; if none is found, an
* {@link IllegalArgumentException} will be thrown.
*
* @param savedInstanceState Previously saved state - irrelevant in this case
*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/// protection against screen recording
if (!BuildConfig.DEBUG) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
} // else, let it go, or taking screenshots & testing will not be possible
setContentView(R.layout.passcodelock);
mBCancel = (Button) findViewById(R.id.cancel);
mPassCodeHdr = (TextView) findViewById(R.id.header);
mPassCodeHdrExplanation = (TextView) findViewById(R.id.explanation);
mPassCodeEditTexts[0] = (EditText) findViewById(R.id.txt0);
mPassCodeEditTexts[0].requestFocus();
getWindow().setSoftInputMode(
android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
mPassCodeEditTexts[1] = (EditText) findViewById(R.id.txt1);
mPassCodeEditTexts[2] = (EditText) findViewById(R.id.txt2);
mPassCodeEditTexts[3] = (EditText) findViewById(R.id.txt3);
if (ACTION_CHECK.equals(getIntent().getAction())) {
/// this is a pass code request; the user has to input the right value
mPassCodeHdr.setText(R.string.pass_code_enter_pass_code);
mPassCodeHdrExplanation.setVisibility(View.INVISIBLE);
setCancelButtonEnabled(false); // no option to cancel
} else if (ACTION_REQUEST_WITH_RESULT.equals(getIntent().getAction())) {
if (savedInstanceState != null) {
mConfirmingPassCode = savedInstanceState.getBoolean(PassCodeActivity.KEY_CONFIRMING_PASSCODE);
mPassCodeDigits = savedInstanceState.getStringArray(PassCodeActivity.KEY_PASSCODE_DIGITS);
}
if(mConfirmingPassCode){
//the app was in the passcodeconfirmation
requestPassCodeConfirmation();
}else{
/// pass code preference has just been activated in Preferences;
// will receive and confirm pass code value
mPassCodeHdr.setText(R.string.pass_code_configure_your_pass_code);
//mPassCodeHdr.setText(R.string.pass_code_enter_pass_code);
// TODO choose a header, check iOS
mPassCodeHdrExplanation.setVisibility(View.VISIBLE);
setCancelButtonEnabled(true);
}
} else if (ACTION_CHECK_WITH_RESULT.equals(getIntent().getAction())) {
/// pass code preference has just been disabled in Preferences;
// will confirm user knows pass code, then remove it
mPassCodeHdr.setText(R.string.pass_code_remove_your_pass_code);
mPassCodeHdrExplanation.setVisibility(View.INVISIBLE);
setCancelButtonEnabled(true);
} else {
throw new IllegalArgumentException("A valid ACTION is needed in the Intent passed to "
+ TAG);
}
setTextListeners();
}
/**
* Enables or disables the cancel button to allow the user interrupt the ACTION
* requested to the activity.
*
* @param enabled 'True' makes the cancel button available, 'false' hides it.
*/
protected void setCancelButtonEnabled(boolean enabled){
if(enabled){
mBCancel.setVisibility(View.VISIBLE);
mBCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
} else {
mBCancel.setVisibility(View.GONE);
mBCancel.setVisibility(View.INVISIBLE);
mBCancel.setOnClickListener(null);
}
}
/**
* Binds the appropiate listeners to the input boxes receiving each digit of the pass code.
*/
protected void setTextListeners() {
/// First input field
mPassCodeEditTexts[0].addTextChangedListener(new PassCodeDigitTextWatcher(0, false));
/*------------------------------------------------
* SECOND BOX
-------------------------------------------------*/
mPassCodeEditTexts[1].addTextChangedListener(new PassCodeDigitTextWatcher(1, false));
mPassCodeEditTexts[1].setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL && mBChange) { // TODO WIP: event should be
// used to control what's exactly happening with DEL, not any custom field...
mPassCodeEditTexts[0].setText("");
mPassCodeEditTexts[0].requestFocus();
if (!mConfirmingPassCode)
mPassCodeDigits[0] = "";
mBChange = false;
} else if (!mBChange) {
mBChange = true;
}
return false;
}
});
mPassCodeEditTexts[1].setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
/// TODO WIP: should take advantage of hasFocus to reduce processing
if (mPassCodeEditTexts[0].getText().toString().equals("")) { // TODO WIP validation
// could be done in a global way, with a single OnFocusChangeListener for all the
// input fields
mPassCodeEditTexts[0].requestFocus();
}
}
});
/*------------------------------------------------
* THIRD BOX
-------------------------------------------------*/
mPassCodeEditTexts[2].addTextChangedListener(new PassCodeDigitTextWatcher(2, false));
mPassCodeEditTexts[2].setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL && mBChange) {
mPassCodeEditTexts[1].requestFocus();
if (!mConfirmingPassCode)
mPassCodeDigits[1] = "";
mPassCodeEditTexts[1].setText("");
mBChange = false;
} else if (!mBChange) {
mBChange = true;
}
return false;
}
});
mPassCodeEditTexts[2].setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (mPassCodeEditTexts[0].getText().toString().equals("")) {
mPassCodeEditTexts[0].requestFocus();
} else if (mPassCodeEditTexts[1].getText().toString().equals("")) {
mPassCodeEditTexts[1].requestFocus();
}
}
});
/*------------------------------------------------
* FOURTH BOX
-------------------------------------------------*/
mPassCodeEditTexts[3].addTextChangedListener(new PassCodeDigitTextWatcher(3, true));
mPassCodeEditTexts[3].setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL && mBChange) {
mPassCodeEditTexts[2].requestFocus();
if (!mConfirmingPassCode)
mPassCodeDigits[2] = "";
mPassCodeEditTexts[2].setText("");
mBChange = false;
} else if (!mBChange) {
mBChange = true;
}
return false;
}
});
mPassCodeEditTexts[3].setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (mPassCodeEditTexts[0].getText().toString().equals("")) {
mPassCodeEditTexts[0].requestFocus();
} else if (mPassCodeEditTexts[1].getText().toString().equals("")) {
mPassCodeEditTexts[1].requestFocus();
} else if (mPassCodeEditTexts[2].getText().toString().equals("")) {
mPassCodeEditTexts[2].requestFocus();
}
}
});
} // end setTextListener
/**
* Processes the pass code entered by the user just after the last digit was in.
*
* Takes into account the action requested to the activity, the currently saved pass code and
* the previously typed pass code, if any.
*/
private void processFullPassCode() {
if (ACTION_CHECK.equals(getIntent().getAction())) {
if (checkPassCode()) {
/// pass code accepted in request, user is allowed to access the app
hideSoftKeyboard();
finish();
} else {
showErrorAndRestart(R.string.pass_code_wrong, R.string.pass_code_enter_pass_code,
View.INVISIBLE);
}
} else if (ACTION_CHECK_WITH_RESULT.equals(getIntent().getAction())) {
if (checkPassCode()) {
Intent resultIntent = new Intent();
resultIntent.putExtra(KEY_CHECK_RESULT, true);
setResult(RESULT_OK, resultIntent);
hideSoftKeyboard();
finish();
} else {
showErrorAndRestart(R.string.pass_code_wrong, R.string.pass_code_enter_pass_code,
View.INVISIBLE);
}
} else if (ACTION_REQUEST_WITH_RESULT.equals(getIntent().getAction())) {
/// enabling pass code
if (!mConfirmingPassCode) {
requestPassCodeConfirmation();
} else if (confirmPassCode()) {
/// confirmed: user typed the same pass code twice
savePassCodeAndExit();
} else {
showErrorAndRestart(
R.string.pass_code_mismatch, R.string.pass_code_configure_your_pass_code, View.VISIBLE
);
}
}
}
private void hideSoftKeyboard() {
View focusedView = getCurrentFocus();
if (focusedView != null) {
InputMethodManager inputMethodManager =
(InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(
focusedView.getWindowToken(),
0
);
}
}
private void showErrorAndRestart(int errorMessage, int headerMessage,
int explanationVisibility) {
Arrays.fill(mPassCodeDigits, null);
CharSequence errorSeq = getString(errorMessage);
Toast.makeText(this, errorSeq, Toast.LENGTH_LONG).show();
mPassCodeHdr.setText(headerMessage); // TODO check if really needed
mPassCodeHdrExplanation.setVisibility(explanationVisibility); // TODO check if really needed
clearBoxes();
}
/**
* Ask to the user for retyping the pass code just entered before saving it as the current pass
* code.
*/
protected void requestPassCodeConfirmation(){
clearBoxes();
mPassCodeHdr.setText(R.string.pass_code_reenter_your_pass_code);
mPassCodeHdrExplanation.setVisibility(View.INVISIBLE);
mConfirmingPassCode = true;
}
/**
* Compares pass code entered by the user with the value currently saved in the app.
*
* @return 'True' if entered pass code equals to the saved one.
*/
protected boolean checkPassCode(){
SharedPreferences appPrefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
String savedPassCodeDigits[] = new String[4];
savedPassCodeDigits[0] = appPrefs.getString(PREFERENCE_PASSCODE_D1, null);
savedPassCodeDigits[1] = appPrefs.getString(PREFERENCE_PASSCODE_D2, null);
savedPassCodeDigits[2] = appPrefs.getString(PREFERENCE_PASSCODE_D3, null);
savedPassCodeDigits[3] = appPrefs.getString(PREFERENCE_PASSCODE_D4, null);
boolean result = true;
for (int i = 0; i < mPassCodeDigits.length && result; i++) {
result = (mPassCodeDigits[i] != null) &&
mPassCodeDigits[i].equals(savedPassCodeDigits[i]);
}
return result;
}
/**
* Compares pass code retyped by the user in the input fields with the value entered just
* before.
*
* @return 'True' if retyped pass code equals to the entered before.
*/
protected boolean confirmPassCode(){
mConfirmingPassCode = false;
boolean result = true;
for (int i = 0; i < mPassCodeEditTexts.length && result; i++) {
result = ((mPassCodeEditTexts[i].getText().toString()).equals(mPassCodeDigits[i]));
}
return result;
}
/**
* Sets the input fields to empty strings and puts the focus on the first one.
*/
protected void clearBoxes(){
for (int i=0; i < mPassCodeEditTexts.length; i++) {
mPassCodeEditTexts[i].setText("");
}
mPassCodeEditTexts[0].requestFocus();
}
/**
* Overrides click on the BACK arrow to correctly cancel ACTION_ENABLE or ACTION_DISABLE, while
* preventing than ACTION_CHECK may be worked around.
*
* @param keyCode Key code of the key that triggered the down event.
* @param event Event triggered.
* @return 'True' when the key event was processed by this method.
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount()== 0){
if (ACTION_REQUEST_WITH_RESULT.equals(getIntent().getAction()) ||
ACTION_CHECK_WITH_RESULT.equals(getIntent().getAction())) {
finish();
} // else, do nothing, but report that the key was consumed to stay alive
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* Saves the pass code input by the user as the current pass code.
*/
protected void savePassCodeAndExit() {
Intent resultIntent = new Intent();
resultIntent.putExtra(KEY_PASSCODE,
mPassCodeDigits[0] + mPassCodeDigits[1] + mPassCodeDigits[2] + mPassCodeDigits[3]);
setResult(RESULT_OK, resultIntent);
finish();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(PassCodeActivity.KEY_CONFIRMING_PASSCODE, mConfirmingPassCode);
outState.putStringArray(PassCodeActivity.KEY_PASSCODE_DIGITS, mPassCodeDigits);
}
private class PassCodeDigitTextWatcher implements TextWatcher {
private int mIndex = -1;
private boolean mLastOne = false;
/**
* Constructor
*
* @param index Position in the pass code of the input field that will be bound to
* this watcher.
* @param lastOne 'True' means that watcher corresponds to the last position of the
* pass code.
*/
public PassCodeDigitTextWatcher(int index, boolean lastOne) {
mIndex = index;
mLastOne = lastOne;
if (mIndex < 0) {
throw new IllegalArgumentException(
"Invalid index in " + PassCodeDigitTextWatcher.class.getSimpleName() +
" constructor"
);
}
}
private int next() {
return mLastOne ? 0 : mIndex + 1;
}
/**
* Performs several actions when the user types a digit in an input field:
* - saves the input digit to the state of the activity; this will allow retyping the
* pass code to confirm it.
* - moves the focus automatically to the next field
* - for the last field, triggers the processing of the full pass code
*
* @param s Changed text
*/
@Override
public void afterTextChanged(Editable s) {
if (s.length() > 0) {
if (!mConfirmingPassCode) {
mPassCodeDigits[mIndex] = mPassCodeEditTexts[mIndex].getText().toString();
}
mPassCodeEditTexts[next()].requestFocus();
if (mLastOne) {
processFullPassCode();
}
} else {
Log_OC.d(TAG, "Text box " + mIndex + " was cleaned");
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// nothing to do
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// nothing to do
}
}
}
| gpl-2.0 |
ZhangBohan/jiajiaohello | src/main/java/com/jiajiaohello/core/audit/package-info.java | 203 | /**
* 这个包用于保存审核处理相关的内容
*
* 例如:教员身份审核、发布信息处理
*
* User: bohan
* Date: 11/8/14
* Time: 3:25 PM
*/
package com.jiajiaohello.core.audit; | gpl-2.0 |
mosscode/posix-fifo-sockets | src/test/java/com/moss/posixfifosockets/PosixFifoMiscTest.java | 2374 | /**
* Copyright (C) 2013, Moss Computing Inc.
*
* This file is part of posix-fifo-sockets.
*
* posix-fifo-sockets is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* posix-fifo-sockets 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 posix-fifo-sockets; see the file COPYING. If not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* Linking this library statically or dynamically with other modules is
* making a combined work based on this library. Thus, the terms and
* conditions of the GNU General Public License cover the whole
* combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent
* modules, and to copy and distribute the resulting executable under
* terms of your choice, provided that you also meet, for each linked
* independent module, the terms and conditions of the license of that
* module. An independent module is a module which is not derived from
* or based on this library. If you modify this library, you may extend
* this exception to your version of the library, but you are not
* obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
package com.moss.posixfifosockets;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import com.moss.fskit.TempDir;
import com.moss.posixfifosockets.util.PosixFifoMisc;
import junit.framework.TestCase;
public class PosixFifoMiscTest extends TestCase {
private final Log log = LogFactory.getLog(getClass());
public void testRun(){
assertNotNull(PosixFifoMisc.sendFifoSocketMessageBashFunction());
}
}
| gpl-2.0 |
Norkart/NK-VirtualGlobe | Xj3D/test/org/web3d/x3d/jaxp/dom/TestX3DDocument.java | 4732 | /*****************************************************************************
* Web3d.org Copyright (c) 2001
* Java Source
*
* This source is licensed under the GNU LGPL v2.1
* Please read http://www.gnu.org/copyleft/lgpl.html for more information
*
* This software comes with the standard NO WARRANTY disclaimer for any
* purpose. Use it at your own risk. If there's a problem you get to fix it.
*
****************************************************************************/
//------------------------------------------------------------
package org.web3d.x3d.jaxp.dom;
import org.w3c.dom.*;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
/**
* A test case to check the functionality of the X3DDocument
* implementation.
* <p>
* The document class is quite complex so this test has a lot of test
* cases to implement to fully verify that everything is working.
*
*/
public class TestX3DDocument extends TestCase {
/** The listing of all the elements that we should be able to create */
private static final String[] ELEMENT_LIST = {
"Anchor", "Appearance", "AudioClip",
"Background", "Box",
"Collision", "Color", "ColorInterpolator", "Coordinate",
"CoordinateInterpolator", "Cylinder", "CylinderSensor",
"DirectionalLight",
"ElevationGrid", "EventIn", "EventOut", "Extrusion",
"Field", "Fog", "FontStyle",
"Group",
"ImageTexture", "IndexedFaceSet", "Inline",
"Material", "MovieTexture",
"NavigationInfo", "Normal", "NormalInterpolator",
"OrientationInterpolator",
"PlaneSensor", "PointLight", "PositionInterpolator",
"Proto", "ProtoUse", "ProximitySensor",
"Route",
"ScalarInterpolator", "Scene", "Shape", "Sound",
"Sphere", "SphereSensor", "SpotLight", "Switch",
"Text", "TextureCoordinate", "TextureTransform",
"TimeSensor", "TouchSensor", "Transform",
"ViewPoint", "VisibilitySensor", "WorldInfo"
};
/** The document under test */
private Document document;
/**
* Create an instance of the test case for this particular test
* name.
*
* @param name The name of the test method to be run
*/
public TestX3DDocument(String name) {
super(name);
}
/**
* Fetch the suite of tests for this test class to perform.
*
* @return A collection of all the tests to be run
*/
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTest(new TestX3DDocument("testCreateElement"));
suite.addTest(new TestX3DDocument("testCreateAttribute"));
suite.addTest(new TestX3DDocument("testCreateEntity"));
return suite;
}
/**
* Setup the environment for this test.
*/
protected void setUp() {
document = new X3DDocument();
}
/**
* Test that we can create an element of the named type. This is a generic
* test and does not look at dealing with child elements or attributes. We
* Loop through all of the elements that should be able to be created from
* this document and make sure they can all be created.
*/
public void testCreateElement() {
Element el;
for(int i = 0; i < ELEMENT_LIST.length; i++) {
el = document.createElement(ELEMENT_LIST[i]);
assertNotNull("Failed to create " + ELEMENT_LIST[i], el);
assertEquals("Name not correct for " + ELEMENT_LIST[i],
el.getTagName(),
ELEMENT_LIST[i]);
assertNull("Namespace not null", el.getNamespaceURI());
}
}
/**
* Test creating a standalone attribute. Make sure that all the right
* flags are set when the attribute has been created.
*/
public void testCreateAttribute() {
Attr attr = document.createAttribute("Color");
assertNotNull("Could not create Color attribute", attr);
assertEquals("Name is not set", "Color", attr.getName());
// Now test the parts of the attribute
assertNull("Namespace not null", attr.getNamespaceURI());
assertNull("Local name not null", attr.getLocalName());
assertNull("Prefix not null", attr.getPrefix());
assertEquals("Value is not empty", "", attr.getValue());
// set a value and make sure it is the same when fetched
attr.setValue("blah");
assertEquals("Value not set", "blah", attr.getValue());
}
/**
* Test creating the various entity types. They are all wrapped up in
* this one test.
*/
public void testCreateEntity() {
EntityReference ent = document.createEntityReference("entity");
assertNotNull("Could not create entity", ent);
}
/**
* Main method to kick everything off with.
*/
public static void main(String[] argv) {
TestRunner.run(suite());
}
}
| gpl-2.0 |
peterbartha/j2eecm | edu.bme.vik.iit.j2eecm.diagram.webcontainer/src/web/container/diagram/edit/policies/ModelTextSelectionEditPolicy.java | 5035 | package web.container.diagram.edit.policies;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.FigureListener;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.RectangleFigure;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.editpolicies.SelectionEditPolicy;
import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel;
import org.eclipse.gmf.tooling.runtime.edit.policies.labels.IRefreshableFeedbackEditPolicy;
/**
* @generated
*/
public class ModelTextSelectionEditPolicy extends SelectionEditPolicy implements
IRefreshableFeedbackEditPolicy {
/**
* @generated
*/
private IFigure selectionFeedbackFigure;
/**
* @generated
*/
private IFigure focusFeedbackFigure;
/**
* @generated
*/
private FigureListener hostPositionListener;
/**
* @generated
*/
protected void showPrimarySelection() {
if (getHostFigure() instanceof WrappingLabel) {
((WrappingLabel) getHostFigure()).setSelected(true);
((WrappingLabel) getHostFigure()).setFocus(true);
} else {
showSelection();
showFocus();
}
}
/**
* @generated
*/
protected void showSelection() {
if (getHostFigure() instanceof WrappingLabel) {
((WrappingLabel) getHostFigure()).setSelected(true);
((WrappingLabel) getHostFigure()).setFocus(false);
} else {
hideSelection();
addFeedback(selectionFeedbackFigure = createSelectionFeedbackFigure());
getHostFigure().addFigureListener(getHostPositionListener());
refreshSelectionFeedback();
hideFocus();
}
}
/**
* @generated
*/
protected void hideSelection() {
if (getHostFigure() instanceof WrappingLabel) {
((WrappingLabel) getHostFigure()).setSelected(false);
((WrappingLabel) getHostFigure()).setFocus(false);
} else {
if (selectionFeedbackFigure != null) {
removeFeedback(selectionFeedbackFigure);
getHostFigure().removeFigureListener(getHostPositionListener());
selectionFeedbackFigure = null;
}
hideFocus();
}
}
/**
* @generated
*/
protected void showFocus() {
if (getHostFigure() instanceof WrappingLabel) {
((WrappingLabel) getHostFigure()).setFocus(true);
} else {
hideFocus();
addFeedback(focusFeedbackFigure = createFocusFeedbackFigure());
refreshFocusFeedback();
}
}
/**
* @generated
*/
protected void hideFocus() {
if (getHostFigure() instanceof WrappingLabel) {
((WrappingLabel) getHostFigure()).setFocus(false);
} else {
if (focusFeedbackFigure != null) {
removeFeedback(focusFeedbackFigure);
focusFeedbackFigure = null;
}
}
}
/**
* @generated
*/
protected Rectangle getFeedbackBounds() {
Rectangle bounds;
if (getHostFigure() instanceof Label) {
bounds = ((Label) getHostFigure()).getTextBounds();
bounds.intersect(getHostFigure().getBounds());
} else {
bounds = getHostFigure().getBounds().getCopy();
}
getHostFigure().getParent().translateToAbsolute(bounds);
getFeedbackLayer().translateToRelative(bounds);
return bounds;
}
/**
* @generated
*/
protected IFigure createSelectionFeedbackFigure() {
if (getHostFigure() instanceof Label) {
Label feedbackFigure = new Label();
feedbackFigure.setOpaque(true);
feedbackFigure
.setBackgroundColor(ColorConstants.menuBackgroundSelected);
feedbackFigure
.setForegroundColor(ColorConstants.menuForegroundSelected);
return feedbackFigure;
} else {
RectangleFigure feedbackFigure = new RectangleFigure();
feedbackFigure.setFill(false);
return feedbackFigure;
}
}
/**
* @generated
*/
protected IFigure createFocusFeedbackFigure() {
return new Figure() {
protected void paintFigure(Graphics graphics) {
graphics.drawFocus(getBounds().getResized(-1, -1));
}
};
}
/**
* @generated
*/
protected void updateLabel(Label target) {
Label source = (Label) getHostFigure();
target.setText(source.getText());
target.setTextAlignment(source.getTextAlignment());
target.setFont(source.getFont());
}
/**
* @generated
*/
protected void refreshSelectionFeedback() {
if (selectionFeedbackFigure != null) {
if (selectionFeedbackFigure instanceof Label) {
updateLabel((Label) selectionFeedbackFigure);
selectionFeedbackFigure.setBounds(getFeedbackBounds());
} else {
selectionFeedbackFigure.setBounds(getFeedbackBounds().expand(5,
5));
}
}
}
/**
* @generated
*/
protected void refreshFocusFeedback() {
if (focusFeedbackFigure != null) {
focusFeedbackFigure.setBounds(getFeedbackBounds());
}
}
/**
* @generated
*/
public void refreshFeedback() {
refreshSelectionFeedback();
refreshFocusFeedback();
}
/**
* @generated
*/
private FigureListener getHostPositionListener() {
if (hostPositionListener == null) {
hostPositionListener = new FigureListener() {
public void figureMoved(IFigure source) {
refreshFeedback();
}
};
}
return hostPositionListener;
}
}
| gpl-2.0 |
azadmanesh/sl-tracer | truffle/com.oracle.truffle.dsl.processor/src/com/oracle/truffle/dsl/processor/expression/DSLExpression.java | 12489 | /*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.truffle.dsl.processor.expression;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
public abstract class DSLExpression {
private TypeMirror resolvedTargetType;
private DSLExpression() {
}
public static DSLExpression parse(String input) {
return Parser.parse(input);
}
public final Set<VariableElement> findBoundVariableElements() {
final Set<VariableElement> variables = new HashSet<>();
this.accept(new AbstractDSLExpressionVisitor() {
@Override
public void visitVariable(Variable variable) {
if (variable.getReceiver() == null) {
variables.add(variable.getResolvedVariable());
}
}
});
return variables;
}
public final Set<Variable> findBoundVariables() {
final Set<Variable> variables = new HashSet<>();
this.accept(new AbstractDSLExpressionVisitor() {
@Override
public void visitVariable(Variable variable) {
if (variable.getReceiver() == null) {
variables.add(variable);
}
}
});
return variables;
}
public Object resolveConstant() {
return null;
}
public boolean containsComparisons() {
final AtomicBoolean found = new AtomicBoolean();
this.accept(new AbstractDSLExpressionVisitor() {
@Override
public void visitBinary(Binary binary) {
if (binary.isComparison()) {
found.set(true);
}
}
});
return found.get();
}
public void setResolvedTargetType(TypeMirror resolvedTargetType) {
this.resolvedTargetType = resolvedTargetType;
}
public TypeMirror getResolvedTargetType() {
return resolvedTargetType;
}
public abstract TypeMirror getResolvedType();
public abstract void accept(DSLExpressionVisitor visitor);
public static final class Negate extends DSLExpression {
private final DSLExpression receiver;
public Negate(DSLExpression receiver) {
this.receiver = receiver;
}
@Override
public void accept(DSLExpressionVisitor visitor) {
receiver.accept(visitor);
visitor.visitNegate(this);
}
public DSLExpression getReceiver() {
return receiver;
}
@Override
public TypeMirror getResolvedType() {
return receiver.getResolvedType();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Negate) {
return receiver.equals(((Negate) obj).receiver);
}
return false;
}
@Override
public int hashCode() {
return receiver.hashCode();
}
}
public static final class Binary extends DSLExpression {
private final String operator;
private final DSLExpression left;
private final DSLExpression right;
private TypeMirror resolvedType;
public Binary(String operator, DSLExpression left, DSLExpression right) {
this.operator = operator;
this.left = left;
this.right = right;
}
public boolean isComparison() {
return DSLExpressionResolver.COMPARABLE_OPERATORS.contains(operator) || DSLExpressionResolver.IDENTITY_OPERATORS.contains(operator);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Binary) {
Binary other = (Binary) obj;
return operator.equals(other.operator) && left.equals(other.left) && right.equals(other.right);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(operator, left, right);
}
public String getOperator() {
return operator;
}
public DSLExpression getLeft() {
return left;
}
public DSLExpression getRight() {
return right;
}
@Override
public void accept(DSLExpressionVisitor visitor) {
left.accept(visitor);
right.accept(visitor);
visitor.visitBinary(this);
}
@Override
public TypeMirror getResolvedType() {
return resolvedType;
}
public void setResolvedType(TypeMirror resolvedType) {
this.resolvedType = resolvedType;
}
@Override
public String toString() {
return "Binary [left=" + left + ", operator=" + operator + ", right=" + right + ", resolvedType=" + resolvedType + "]";
}
}
public static final class Call extends DSLExpression {
private final DSLExpression receiver;
private final String name;
private final List<DSLExpression> parameters;
private ExecutableElement resolvedMethod;
public Call(DSLExpression receiver, String name, List<DSLExpression> parameters) {
this.receiver = receiver;
this.name = name;
this.parameters = parameters;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Call) {
Call other = (Call) obj;
return Objects.equals(receiver, other.receiver) && name.equals(other.name) && parameters.equals(other.parameters);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(receiver, name, parameters);
}
public DSLExpression getReceiver() {
return receiver;
}
public String getName() {
return name;
}
public List<DSLExpression> getParameters() {
return parameters;
}
@Override
public void accept(DSLExpressionVisitor visitor) {
if (receiver != null) {
receiver.accept(visitor);
}
for (DSLExpression parameter : getParameters()) {
parameter.accept(visitor);
}
visitor.visitCall(this);
}
@Override
public TypeMirror getResolvedType() {
if (resolvedMethod == null) {
return null;
}
if (resolvedMethod.getKind() == ElementKind.CONSTRUCTOR) {
return resolvedMethod.getEnclosingElement().asType();
} else {
return resolvedMethod.getReturnType();
}
}
public ExecutableElement getResolvedMethod() {
return resolvedMethod;
}
public void setResolvedMethod(ExecutableElement resolvedMethod) {
this.resolvedMethod = resolvedMethod;
}
@Override
public String toString() {
return "Call [receiver=" + receiver + ", name=" + name + ", parameters=" + parameters + ", resolvedMethod=" + resolvedMethod + "]";
}
}
public static final class Variable extends DSLExpression {
private final DSLExpression receiver;
private final String name;
private VariableElement resolvedVariable;
public Variable(DSLExpression receiver, String name) {
this.receiver = receiver;
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Variable) {
Variable other = (Variable) obj;
return Objects.equals(receiver, other.receiver) && name.equals(other.name);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(receiver, name);
}
public DSLExpression getReceiver() {
return receiver;
}
public String getName() {
return name;
}
@Override
public void accept(DSLExpressionVisitor visitor) {
if (receiver != null) {
receiver.accept(visitor);
}
visitor.visitVariable(this);
}
@Override
public TypeMirror getResolvedType() {
return resolvedVariable != null ? resolvedVariable.asType() : null;
}
public void setResolvedVariable(VariableElement resolvedVariable) {
this.resolvedVariable = resolvedVariable;
}
public VariableElement getResolvedVariable() {
return resolvedVariable;
}
@Override
public String toString() {
return "Variable [receiver=" + receiver + ", name=" + name + ", resolvedVariable=" + resolvedVariable + "]";
}
}
public static final class IntLiteral extends DSLExpression {
private final String literal;
private int resolvedValueInt;
private TypeMirror resolvedType;
public IntLiteral(String literal) {
this.literal = literal;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof IntLiteral) {
IntLiteral other = (IntLiteral) obj;
return resolvedValueInt == other.resolvedValueInt;
}
return false;
}
@Override
public Object resolveConstant() {
return resolvedValueInt;
}
@Override
public int hashCode() {
return resolvedValueInt;
}
public String getLiteral() {
return literal;
}
public int getResolvedValueInt() {
return resolvedValueInt;
}
public void setResolvedValueInt(int resolved) {
this.resolvedValueInt = resolved;
}
@Override
public TypeMirror getResolvedType() {
return resolvedType;
}
public void setResolvedType(TypeMirror resolvedType) {
this.resolvedType = resolvedType;
}
@Override
public void accept(DSLExpressionVisitor visitor) {
visitor.visitIntLiteral(this);
}
@Override
public String toString() {
return "IntLiteral [literal=" + literal + ", resolvedValueInt=" + resolvedValueInt + ", resolvedType=" + resolvedType + "]";
}
}
public abstract class AbstractDSLExpressionVisitor implements DSLExpressionVisitor {
public void visitBinary(Binary binary) {
}
public void visitCall(Call binary) {
}
public void visitIntLiteral(IntLiteral binary) {
}
public void visitNegate(Negate negate) {
}
public void visitVariable(Variable binary) {
}
}
public interface DSLExpressionVisitor {
void visitBinary(Binary binary);
void visitNegate(Negate negate);
void visitCall(Call binary);
void visitVariable(Variable binary);
void visitIntLiteral(IntLiteral binary);
}
}
| gpl-2.0 |
consulo/jdi | jdwpgen/src/main/java/build/tools/jdwpgen/OutNode.java | 4884 | /*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package build.tools.jdwpgen;
import java.util.*;
import java.io.*;
class OutNode extends AbstractTypeListNode {
String cmdName;
void set(String kind, List<Node> components, int lineno) {
super.set(kind, components, lineno);
components.add(0, new NameNode("Out"));
}
void constrain(Context ctx) {
super.constrain(ctx.commandWritingSubcontext());
CommandNode cmd = (CommandNode)parent;
cmdName = cmd.name;
}
void genProcessMethod(PrintWriter writer, int depth) {
writer.println();
indent(writer, depth);
writer.print(
"public static " + cmdName + " process(VirtualMachineImpl vm");
for (Node node : components) {
TypeNode tn = (TypeNode)node;
writer.println(", ");
indent(writer, depth+5);
writer.print(tn.javaParam());
}
writer.println(")");
indent(writer, depth+6);
writer.println("throws JDWPException {");
indent(writer, depth+1);
writer.print("PacketStream ps = enqueueCommand(vm");
for (Node node : components) {
TypeNode tn = (TypeNode)node;
writer.print(", ");
writer.print(tn.name());
}
writer.println(");");
indent(writer, depth+1);
writer.println("return waitForReply(vm, ps);");
indent(writer, depth);
writer.println("}");
}
void genEnqueueMethod(PrintWriter writer, int depth) {
writer.println();
indent(writer, depth);
writer.print(
"static PacketStream enqueueCommand(VirtualMachineImpl vm");
for (Node node : components) {
TypeNode tn = (TypeNode)node;
writer.println(", ");
indent(writer, depth+5);
writer.print(tn.javaParam());
}
writer.println(") {");
indent(writer, depth+1);
writer.println(
"PacketStream ps = new PacketStream(vm, COMMAND_SET, COMMAND);");
if (Main.genDebug) {
indent(writer, depth+1);
writer.println(
"if ((vm.traceFlags & VirtualMachineImpl.TRACE_SENDS) != 0) {");
indent(writer, depth+2);
writer.print(
"vm.printTrace(\"Sending Command(id=\" + ps.pkt.id + \") ");
writer.print(parent.context.whereJava);
writer.println(
"\"+(ps.pkt.flags!=0?\", FLAGS=\" + ps.pkt.flags:\"\"));");
indent(writer, depth+1);
writer.println("}");
}
genJavaWrites(writer, depth+1);
indent(writer, depth+1);
writer.println("ps.send();");
indent(writer, depth+1);
writer.println("return ps;");
indent(writer, depth);
writer.println("}");
}
void genWaitMethod(PrintWriter writer, int depth) {
writer.println();
indent(writer, depth);
writer.println(
"static " + cmdName + " waitForReply(VirtualMachineImpl vm, " +
"PacketStream ps)");
indent(writer, depth+6);
writer.println("throws JDWPException {");
indent(writer, depth+1);
writer.println("ps.waitForReply();");
indent(writer, depth+1);
writer.println("return new " + cmdName + "(vm, ps);");
indent(writer, depth);
writer.println("}");
}
void genJava(PrintWriter writer, int depth) {
genJavaPreDef(writer, depth);
super.genJava(writer, depth);
genProcessMethod(writer, depth);
genEnqueueMethod(writer, depth);
genWaitMethod(writer, depth);
}
}
| gpl-2.0 |
mizadri/java_tp | 5pr/src/tp/pr4/mv/Main.java | 9035 | package tp.pr4.mv;
import java.io.IOException;
import java.util.Scanner;
import org.apache.commons.cli.*;
import tp.pr4.mv.commands.*;
import tp.pr4.mv.controllers.BatchController;
import tp.pr4.mv.controllers.Controller;
import tp.pr4.mv.controllers.GUIController;
import tp.pr4.mv.controllers.InteractiveController;
import tp.pr4.mv.exceptions.*;
import tp.pr4.mv.gui.views.BatchView;
import tp.pr4.mv.gui.views.InteractiveView;
import tp.pr4.mv.gui.views.MainWindow;
import tp.pr4.mv.inout.*;
import tp.pr4.mv.observers.Observable;
import tp.pr4.mv.observers.StackObserver;
/**
* Clase principal que ejecuta el programa.
* @author Adrian Garcia y Omar Gaytan
*
*/
public class Main {
private static final int _BATCH_MODE = 0;
private static final int _INTER_MODE = 1;
private static final int _WINDOW_MODE = 2;
private static int exeMode = _INTER_MODE;
private static String asmFileName = null;
private static String inFileName = null;
private static String modeName = null;
private static String outFileName = null;
private static CommandLine cmdLine = null;
private static CPU cpu;
private static ProgramMV prog;
private static Scanner sc;
public static void main(String[] args) {
//----------------------------------------Codigo para configurar el uso de la Commons CLI----------------------------------------
CommandLineParser parser = new BasicParser();
Options options = new Options();
options.addOption("a", "asm", true, "Fichero con el codigo en ASM del programa a ejecutar. Obligatorio en modo batch.");
options.addOption("h", "help", false, "Muestra esta ayuda");
options.addOption("i", "in", true, "Entrada del programa de la maquina-p.");
options.addOption("o", "out", true , "Fichero donde se guarda la salida del programa de la maquina-p.");
options.addOption("m", "mode", true, "Modo de funcionamiento (batch | interactive). Por defecto, batch.");
// ------------------CODIGO main--------------
sc = new Scanner(System.in);//(Colocado aqui para cerrarlo en el finally)Usado en caso de leer programa de entrada y para leer comandos.
try {
// ----------------------------------------------------------------------------------------------
// --You can modify the start options in cmd or in Eclipse->Run->Run Counfigurations->Arguments--
// ----------------------------------------------------------------------------------------------
parser = new BasicParser();
cmdLine = parser.parse(options, args);
if (cmdLine.hasOption("h")) {
System.out.println("Execute this assignment with these parameters:");
new HelpFormatter().printHelp(Main.class.getCanonicalName()+ " [-a <asmfile>] [-h] [-i <infile>] [-m <mode>] [-o <outfile>]", options);
} else {
cpu = new CPU();
prog = new ProgramMV();
defineInMethod();
defineOutMethod();
defineMode();
defineProgramReading();
cpu.loadProgram(prog);
CPU.getInStrat().open();
try {
CPU.getOutStrat().open();
} catch (IOException e1) {
e1.printStackTrace();
}
switch(exeMode){
case _BATCH_MODE:
exeBatch();break;
case _INTER_MODE:
exeInteractive();break;
case _WINDOW_MODE:
exeWindow();break;
}
}//end else(parametro distinto a help)
}
catch (org.apache.commons.cli.ParseException ex) {
System.err.println("Error: Invalid usage: "+ ex.getMessage() +". Use --help for more information");
System.exit(1);
}
catch (java.lang.NumberFormatException ex) {
new HelpFormatter().printHelp(Main.class.getCanonicalName(),options);
}
finally{
if(exeMode != _WINDOW_MODE){
sc.close();
CPU.getInStrat().close();
CPU.getOutStrat().close();
}
}
}//end main
/**
* Ejecuta la MV en el modo Batch.
*/
@SuppressWarnings("unused")
public static void exeBatch(){
BatchController ctrl = new BatchController(cpu);
BatchView view = new BatchView(cpu);
ctrl.start();
}
/**
* Ejecuta la MV en el modo interactivo.
*/
@SuppressWarnings("unused")
public static void exeInteractive(){
System.out.println(prog.toString());
System.out.print('>');
CommandInterpreter.configureCommandInterpreter(cpu);
InteractiveController ctrl = new InteractiveController(cpu);
InteractiveView view = new InteractiveView(cpu);
ctrl.start();
}
/**
* Ejecuta la MV en el modo ventana.
*/
@SuppressWarnings("unused")
public static void exeWindow(){
Observable<StackObserver<Integer>> stack = null ;
Controller ctrl = new GUIController(cpu);
MainWindow mwindow = new MainWindow(ctrl, cpu, cpu.getOperandStack(),cpu.getMemory());
ctrl.start();
}
/**
* Define el modo de entrada de la MV.
*/
private static void defineInMethod(){
try {
CPU.setInStrat(new InStrategyNada());
CPU.setOutStrat(new OutStrategyNada());
} catch (MVException e) {
System.err.println(e.getMessage());
}
if(cmdLine.hasOption("i")||cmdLine.hasOption("in")){
if (cmdLine.hasOption("i")) inFileName = cmdLine.getOptionValue("i");
else if (cmdLine.hasOption("in")) inFileName = cmdLine.getOptionValue("in");
if(inFileName==null){
System.err.println("Uso incorrecto: Fichero IN no especificado.");
System.err.println("Use -h|--help para mas detalles.");
System.exit(1);
}else if(inFileName.equalsIgnoreCase("std")){
try {
CPU.setInStrat(new InStrategyStd());
} catch (MVException e) {
System.err.println(e.getMessage());
}
}else {
try {
CPU.setInStrat(new InStrategyFile(inFileName));
} catch (MVException e) {
System.err.println(e.getMessage());
}
}
}
}
/**
* Define el metodo de salida de la MV.
*/
private static void defineOutMethod(){
if(cmdLine.hasOption("o")||cmdLine.hasOption("out")){
if (cmdLine.hasOption("o")) outFileName = cmdLine.getOptionValue("o");
else if (cmdLine.hasOption("out")) outFileName = cmdLine.getOptionValue("out");
if(outFileName==null){
System.err.println("Uso incorrecto: Fichero OUT no especificado.");
System.err.println("Use -h|--help para mas detalles.");
System.exit(1);
}else if(outFileName.equalsIgnoreCase("std")){
try {
CPU.setOutStrat(new OutStrategyStd());
} catch (MVException e) {
System.err.println(e.getMessage());
}
}else {
try {
CPU.setOutStrat(new OutStrategyFile(outFileName));
} catch (MVException e) {
System.err.println(e.getMessage());
}
}
}
}
/**
* Define el modo de ejecucion de la MV.
*/
private static void defineMode(){
if(cmdLine.hasOption("m")||cmdLine.hasOption("mode")){
if (cmdLine.hasOption("m")) modeName = cmdLine.getOptionValue("m");
else if (cmdLine.hasOption("mode")) modeName = cmdLine.getOptionValue("mode");
if(modeName == null){
System.err.println("Uso incorrecto: Modo de ejecucion no especificado.");
System.err.println("Use -h|--help para mas detalles.");
System.exit(1);
}else if(modeName.equalsIgnoreCase("interactive")||modeName.equalsIgnoreCase("batch")||modeName.equalsIgnoreCase("window")){
if(modeName.equalsIgnoreCase("batch")){
exeMode = _BATCH_MODE;
if(inFileName == null){
try {
CPU.setInStrat(new InStrategyStd());
} catch (MVException e) {
System.err.println(e.getMessage());
}
}
if(outFileName == null){
try {
CPU.setOutStrat(new OutStrategyStd());
} catch (MVException e) {
System.err.println(e.getMessage());
}
}
}
else if(modeName.equalsIgnoreCase("window")) exeMode = _WINDOW_MODE;
}else {
System.err.println("Uso incorrecto: Modo incorrecto (parametro -m|--mode)");
System.err.println("Use -h|--help para mas detalles.");
System.exit(1);
}
}
}
/**
* Define el tipo de lectura de programa.
*/
public static void defineProgramReading(){
if(cmdLine.hasOption("a")||cmdLine.hasOption("asm")){
if (cmdLine.hasOption("a")) asmFileName = cmdLine.getOptionValue("a");
else if (cmdLine.hasOption("asm")) asmFileName = cmdLine.getOptionValue("asm");
if(asmFileName==null){
System.err.println("Uso incorrecto: Fichero OUT no especificado.");
System.err.println("Use -h|--help para mas detalles.");
System.exit(1);
}
try {
prog.readProgram(asmFileName);
} catch (IOException e) {
e.printStackTrace();
} catch(WrongInstructionFormatException e){
System.err.println(e.getMessage());
System.exit(1);
}
}else{
if(exeMode == _BATCH_MODE){
System.err.println("Uso incorrecto: En modo Batch es necesario especificar fichero de programa ASM");
System.exit(1);
}
prog.readProgram(sc);
}
}
}
| gpl-2.0 |
guod08/druid | processing/src/main/java/io/druid/segment/incremental/IncrementalIndex.java | 19407 | /*
* Druid - a distributed column store.
* Copyright (C) 2012, 2013 Metamarkets Group Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package io.druid.segment.incremental;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
import com.metamx.common.IAE;
import com.metamx.common.ISE;
import com.metamx.common.logger.Logger;
import io.druid.data.input.InputRow;
import io.druid.data.input.MapBasedRow;
import io.druid.data.input.Row;
import io.druid.data.input.impl.SpatialDimensionSchema;
import io.druid.granularity.QueryGranularity;
import io.druid.query.aggregation.Aggregator;
import io.druid.query.aggregation.AggregatorFactory;
import io.druid.query.aggregation.PostAggregator;
import io.druid.segment.ColumnSelectorFactory;
import io.druid.segment.DimensionSelector;
import io.druid.segment.FloatColumnSelector;
import io.druid.segment.ObjectColumnSelector;
import io.druid.segment.TimestampColumnSelector;
import io.druid.segment.serde.ComplexMetricExtractor;
import io.druid.segment.serde.ComplexMetricSerde;
import io.druid.segment.serde.ComplexMetrics;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
/**
*/
public class IncrementalIndex implements Iterable<Row>
{
private static final Logger log = new Logger(IncrementalIndex.class);
private static final Joiner JOINER = Joiner.on(",");
private final long minTimestamp;
private final QueryGranularity gran;
private final AggregatorFactory[] metrics;
private final Map<String, Integer> metricIndexes;
private final Map<String, String> metricTypes;
private final ImmutableList<String> metricNames;
private final LinkedHashMap<String, Integer> dimensionOrder;
private final CopyOnWriteArrayList<String> dimensions;
private final List<SpatialDimensionSchema> spatialDimensions;
private final SpatialDimensionRowFormatter spatialDimensionRowFormatter;
private final DimensionHolder dimValues;
private final ConcurrentSkipListMap<TimeAndDims, Aggregator[]> facts;
private volatile AtomicInteger numEntries = new AtomicInteger();
// This is modified on add() in a critical section.
private InputRow in;
public IncrementalIndex(IncrementalIndexSchema incrementalIndexSchema)
{
this.minTimestamp = incrementalIndexSchema.getMinTimestamp();
this.gran = incrementalIndexSchema.getGran();
this.metrics = incrementalIndexSchema.getMetrics();
final ImmutableList.Builder<String> metricNamesBuilder = ImmutableList.builder();
final ImmutableMap.Builder<String, Integer> metricIndexesBuilder = ImmutableMap.builder();
final ImmutableMap.Builder<String, String> metricTypesBuilder = ImmutableMap.builder();
for (int i = 0; i < metrics.length; i++) {
final String metricName = metrics[i].getName().toLowerCase();
metricNamesBuilder.add(metricName);
metricIndexesBuilder.put(metricName, i);
metricTypesBuilder.put(metricName, metrics[i].getTypeName());
}
metricNames = metricNamesBuilder.build();
metricIndexes = metricIndexesBuilder.build();
metricTypes = metricTypesBuilder.build();
this.dimensionOrder = Maps.newLinkedHashMap();
this.dimensions = new CopyOnWriteArrayList<String>();
int index = 0;
for (String dim : incrementalIndexSchema.getDimensions()) {
dimensionOrder.put(dim, index++);
dimensions.add(dim);
}
this.spatialDimensions = incrementalIndexSchema.getSpatialDimensions();
this.spatialDimensionRowFormatter = new SpatialDimensionRowFormatter(spatialDimensions);
this.dimValues = new DimensionHolder();
this.facts = new ConcurrentSkipListMap<TimeAndDims, Aggregator[]>();
}
public IncrementalIndex(
long minTimestamp,
QueryGranularity gran,
final AggregatorFactory[] metrics
)
{
this(
new IncrementalIndexSchema.Builder().withMinTimestamp(minTimestamp)
.withQueryGranularity(gran)
.withMetrics(metrics)
.build()
);
}
/**
* Adds a new row. The row might correspond with another row that already exists, in which case this will
* update that row instead of inserting a new one.
* <p/>
* This is *not* thread-safe. Calls to add() should always happen on the same thread.
*
* @param row the row of data to add
*
* @return the number of rows in the data set after adding the InputRow
*/
public int add(InputRow row)
{
row = spatialDimensionRowFormatter.formatRow(row);
if (row.getTimestampFromEpoch() < minTimestamp) {
throw new IAE("Cannot add row[%s] because it is below the minTimestamp[%s]", row, new DateTime(minTimestamp));
}
final List<String> rowDimensions = row.getDimensions();
String[][] dims;
List<String[]> overflow = null;
synchronized (dimensionOrder) {
dims = new String[dimensionOrder.size()][];
for (String dimension : rowDimensions) {
dimension = dimension.toLowerCase();
List<String> dimensionValues = row.getDimension(dimension);
Integer index = dimensionOrder.get(dimension);
if (index == null) {
dimensionOrder.put(dimension, dimensionOrder.size());
dimensions.add(dimension);
if (overflow == null) {
overflow = Lists.newArrayList();
}
overflow.add(getDimVals(dimValues.add(dimension), dimensionValues));
} else {
dims[index] = getDimVals(dimValues.get(dimension), dimensionValues);
}
}
}
if (overflow != null) {
// Merge overflow and non-overflow
String[][] newDims = new String[dims.length + overflow.size()][];
System.arraycopy(dims, 0, newDims, 0, dims.length);
for (int i = 0; i < overflow.size(); ++i) {
newDims[dims.length + i] = overflow.get(i);
}
dims = newDims;
}
TimeAndDims key = new TimeAndDims(Math.max(gran.truncate(row.getTimestampFromEpoch()), minTimestamp), dims);
Aggregator[] aggs = facts.get(key);
if (aggs == null) {
aggs = new Aggregator[metrics.length];
for (int i = 0; i < metrics.length; ++i) {
final AggregatorFactory agg = metrics[i];
aggs[i] =
agg.factorize(
new ColumnSelectorFactory()
{
@Override
public TimestampColumnSelector makeTimestampColumnSelector()
{
return new TimestampColumnSelector()
{
@Override
public long getTimestamp()
{
return in.getTimestampFromEpoch();
}
};
}
@Override
public FloatColumnSelector makeFloatColumnSelector(String columnName)
{
final String metricName = columnName.toLowerCase();
return new FloatColumnSelector()
{
@Override
public float get()
{
return in.getFloatMetric(metricName);
}
};
}
@Override
public ObjectColumnSelector makeObjectColumnSelector(String column)
{
final String typeName = agg.getTypeName();
final String columnName = column.toLowerCase();
if (typeName.equals("float")) {
return new ObjectColumnSelector<Float>()
{
@Override
public Class classOfObject()
{
return Float.TYPE;
}
@Override
public Float get()
{
return in.getFloatMetric(columnName);
}
};
}
final ComplexMetricSerde serde = ComplexMetrics.getSerdeForType(typeName);
if (serde == null) {
throw new ISE("Don't know how to handle type[%s]", typeName);
}
final ComplexMetricExtractor extractor = serde.getExtractor();
return new ObjectColumnSelector()
{
@Override
public Class classOfObject()
{
return extractor.extractedClass();
}
@Override
public Object get()
{
return extractor.extractValue(in, columnName);
}
};
}
@Override
public DimensionSelector makeDimensionSelector(String dimension)
{
// we should implement this, but this is going to be rewritten soon anyways
throw new UnsupportedOperationException(
"Incremental index aggregation does not support dimension selectors"
);
}
}
);
}
Aggregator[] prev = facts.putIfAbsent(key, aggs);
if (prev != null) {
aggs = prev;
} else {
numEntries.incrementAndGet();
}
}
synchronized (this) {
in = row;
for (Aggregator agg : aggs) {
agg.aggregate();
}
in = null;
}
return numEntries.get();
}
public boolean isEmpty()
{
return numEntries.get() == 0;
}
public int size()
{
return numEntries.get();
}
public long getMinTimeMillis()
{
return facts.firstKey().getTimestamp();
}
public long getMaxTimeMillis()
{
return facts.lastKey().getTimestamp();
}
private String[] getDimVals(final DimDim dimLookup, final List<String> dimValues)
{
final String[] retVal = new String[dimValues.size()];
int count = 0;
for (String dimValue : dimValues) {
String canonicalDimValue = dimLookup.get(dimValue);
if (canonicalDimValue == null) {
canonicalDimValue = dimValue;
dimLookup.add(dimValue);
}
retVal[count] = canonicalDimValue;
count++;
}
Arrays.sort(retVal);
return retVal;
}
public AggregatorFactory[] getMetricAggs()
{
return metrics;
}
public List<String> getDimensions()
{
return dimensions;
}
public List<SpatialDimensionSchema> getSpatialDimensions()
{
return spatialDimensions;
}
public SpatialDimensionRowFormatter getSpatialDimensionRowFormatter()
{
return spatialDimensionRowFormatter;
}
public String getMetricType(String metric)
{
return metricTypes.get(metric);
}
public long getMinTimestamp()
{
return minTimestamp;
}
public QueryGranularity getGranularity()
{
return gran;
}
public Interval getInterval()
{
return new Interval(minTimestamp, isEmpty() ? minTimestamp : gran.next(getMaxTimeMillis()));
}
public DateTime getMinTime()
{
return isEmpty() ? null : new DateTime(getMinTimeMillis());
}
public DateTime getMaxTime()
{
return isEmpty() ? null : new DateTime(getMaxTimeMillis());
}
DimDim getDimension(String dimension)
{
return isEmpty() ? null : dimValues.get(dimension);
}
Integer getDimensionIndex(String dimension)
{
return dimensionOrder.get(dimension);
}
List<String> getMetricNames()
{
return metricNames;
}
Integer getMetricIndex(String metricName)
{
return metricIndexes.get(metricName);
}
ConcurrentSkipListMap<TimeAndDims, Aggregator[]> getFacts()
{
return facts;
}
ConcurrentNavigableMap<TimeAndDims, Aggregator[]> getSubMap(TimeAndDims start, TimeAndDims end)
{
return facts.subMap(start, end);
}
@Override
public Iterator<Row> iterator()
{
return iterableWithPostAggregations(null).iterator();
}
public Iterable<Row> iterableWithPostAggregations(final List<PostAggregator> postAggs)
{
return new Iterable<Row>()
{
@Override
public Iterator<Row> iterator()
{
return Iterators.transform(
facts.entrySet().iterator(),
new Function<Map.Entry<TimeAndDims, Aggregator[]>, Row>()
{
@Override
public Row apply(final Map.Entry<TimeAndDims, Aggregator[]> input)
{
final TimeAndDims timeAndDims = input.getKey();
final Aggregator[] aggregators = input.getValue();
String[][] theDims = timeAndDims.getDims();
Map<String, Object> theVals = Maps.newLinkedHashMap();
for (int i = 0; i < theDims.length; ++i) {
String[] dim = theDims[i];
if (dim != null && dim.length != 0) {
theVals.put(dimensions.get(i), dim.length == 1 ? dim[0] : Arrays.asList(dim));
}
}
for (int i = 0; i < aggregators.length; ++i) {
theVals.put(metrics[i].getName(), aggregators[i].get());
}
if (postAggs != null) {
for (PostAggregator postAgg : postAggs) {
theVals.put(postAgg.getName(), postAgg.compute(theVals));
}
}
return new MapBasedRow(timeAndDims.getTimestamp(), theVals);
}
}
);
}
};
}
static class DimensionHolder
{
private final Map<String, DimDim> dimensions;
DimensionHolder()
{
dimensions = Maps.newConcurrentMap();
}
void reset()
{
dimensions.clear();
}
DimDim add(String dimension)
{
DimDim holder = dimensions.get(dimension);
if (holder == null) {
holder = new DimDim();
dimensions.put(dimension, holder);
} else {
throw new ISE("dimension[%s] already existed even though add() was called!?", dimension);
}
return holder;
}
DimDim get(String dimension)
{
return dimensions.get(dimension);
}
}
static class TimeAndDims implements Comparable<TimeAndDims>
{
private final long timestamp;
private final String[][] dims;
TimeAndDims(
long timestamp,
String[][] dims
)
{
this.timestamp = timestamp;
this.dims = dims;
}
long getTimestamp()
{
return timestamp;
}
String[][] getDims()
{
return dims;
}
@Override
public int compareTo(TimeAndDims rhs)
{
int retVal = Longs.compare(timestamp, rhs.timestamp);
if (retVal == 0) {
retVal = Ints.compare(dims.length, rhs.dims.length);
}
int index = 0;
while (retVal == 0 && index < dims.length) {
String[] lhsVals = dims[index];
String[] rhsVals = rhs.dims[index];
if (lhsVals == null) {
if (rhsVals == null) {
++index;
continue;
}
return -1;
}
if (rhsVals == null) {
return 1;
}
retVal = Ints.compare(lhsVals.length, rhsVals.length);
int valsIndex = 0;
while (retVal == 0 && valsIndex < lhsVals.length) {
retVal = lhsVals[valsIndex].compareTo(rhsVals[valsIndex]);
++valsIndex;
}
++index;
}
return retVal;
}
@Override
public String toString()
{
return "TimeAndDims{" +
"timestamp=" + new DateTime(timestamp) +
", dims=" + Lists.transform(
Arrays.asList(dims), new Function<String[], Object>()
{
@Override
public Object apply(@Nullable String[] input)
{
if (input == null || input.length == 0) {
return Arrays.asList("null");
}
return Arrays.asList(input);
}
}
) +
'}';
}
}
static class DimDim
{
private final Map<String, String> poorMansInterning = Maps.newConcurrentMap();
private final Map<String, Integer> falseIds;
private final Map<Integer, String> falseIdsReverse;
private volatile String[] sortedVals = null;
public DimDim()
{
BiMap<String, Integer> biMap = Maps.synchronizedBiMap(HashBiMap.<String, Integer>create());
falseIds = biMap;
falseIdsReverse = biMap.inverse();
}
public String get(String value)
{
return value == null ? null : poorMansInterning.get(value);
}
public int getId(String value)
{
return falseIds.get(value);
}
public String getValue(int id)
{
return falseIdsReverse.get(id);
}
public int size()
{
return poorMansInterning.size();
}
public Set<String> keySet()
{
return poorMansInterning.keySet();
}
public synchronized void add(String value)
{
poorMansInterning.put(value, value);
falseIds.put(value, falseIds.size());
}
public int getSortedId(String value)
{
assertSorted();
return Arrays.binarySearch(sortedVals, value);
}
public String getSortedValue(int index)
{
assertSorted();
return sortedVals[index];
}
public void sort()
{
if (sortedVals == null) {
sortedVals = new String[falseIds.size()];
int index = 0;
for (String value : falseIds.keySet()) {
sortedVals[index++] = value;
}
Arrays.sort(sortedVals);
}
}
private void assertSorted()
{
if (sortedVals == null) {
throw new ISE("Call sort() before calling the getSorted* methods.");
}
}
}
}
| gpl-2.0 |
proyectos-fiuba-romera/nilledom | src/main/java/com/nilledom/ui/diagram/ClassDialog.java | 34188 | package com.nilledom.ui.diagram;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.intellij.uiDesigner.core.Spacer;
import com.nilledom.model.*;
import com.nilledom.ui.AppFrame;
import com.nilledom.umldraw.clazz.ClassElement;
import com.nilledom.util.Msg;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
public class ClassDialog extends JDialog {
private static final int CLASS_INDEX = 0;
private static final int MEMBERS_INDEX = 1;
private DefaultTableModel stereotypeTableModel;
private UmlClass classModel;
private ClassElement classElement;
private JPanel contentPane;
private JButton buttonOK;
private JButton buttonCancel;
private JPanel footer;
private JPanel mainPanel;
private JTabbedPane tabbedPanel;
private JPanel classPanel;
private JPanel membersPanel;
private JPanel methodsPanel;
private JPanel namePanel;
private JLabel classNameLabel;
private JTextField classNameField;
private JCheckBox classAbstractCheckbox;
private JPanel stereotypePanel;
private JButton addStereotypeButton;
private JButton removeStereotypeButton;
private JPanel stereotypesLeft;
private JPanel stereotypesRight;
private JButton upStereotypeButton;
private JButton downStereotypeButton;
private JPanel docPanel;
private JTextArea documentationArea;
private JTable attributesTable;
private JButton addAttributeButton;
private JButton deleteAttributeButton;
private JButton moveUpAttributeButton;
private JButton moveDownAttributeButton;
private JPanel attributesPanel;
private JTable methodsTable;
private JButton addMethodButton;
private JButton deleteMethodButton;
private JButton moveUpMethodButton;
private JButton moveDownMethodButton;
private JPanel attributesButtonPanel;
private JPanel attributesTablePanel;
private JPanel methodsTablePanel;
private JPanel methodsButtonPanel;
private JTable stereotypeTable;
private JScrollPane stereotypeScroll;
private boolean ok = false;
public ClassDialog(Window parent, ClassElement aClassElement) {
super(parent, ModalityType.APPLICATION_MODAL);
setContentPane(contentPane);
setModal(true);
this.classElement = aClassElement;
this.classModel = (UmlClass) aClassElement.getModelElement();
getRootPane().setDefaultButton(buttonOK);
tabbedPanel.setTitleAt(CLASS_INDEX, Msg.get("classeditor.tab.class"));
tabbedPanel.setTitleAt(MEMBERS_INDEX, Msg.get("classeditor.tab.members"));
classNameLabel.setText(Msg.get("classeditor.className"));
classAbstractCheckbox.setText(Msg.get("classeditor.isAbstract"));
((TitledBorder) stereotypePanel.getBorder()).setTitle(Msg.get("classeditor.stereotypes"));
addStereotypeButton.setText(Msg.get("classeditor.add"));
removeStereotypeButton.setText(Msg.get("classeditor.remove"));
upStereotypeButton.setText(Msg.get("classeditor.moveUp"));
downStereotypeButton.setText(Msg.get("classeditor.moveDown"));
((TitledBorder) docPanel.getBorder()).setTitle(Msg.get("classeditor.documentation"));
stereotypeTableModel = new DefaultTableModel();
stereotypeTableModel.addColumn("");
for (int i = 0; i < classModel.getStereotypes().size(); i++) {
UmlStereotype umlStereotype = classModel.getStereotypes().get(i);
stereotypeTableModel.addRow(new Object[]{umlStereotype.getName().substring(2, umlStereotype.getName().length() - 2)});
}
stereotypeTable.setModel(stereotypeTableModel);
stereotypeTable.setTableHeader(null);
classNameField.setText(classModel.getName());
classAbstractCheckbox.setSelected(classModel.isAbstract());
documentationArea.setText(classModel.getDocumentation());
///////////////////// ATTRIBUTES //////////////////////////
((TitledBorder) attributesPanel.getBorder()).setTitle(Msg.get("classeditor.attributes"));
String typeAttColumnName = Msg.get("classeditor.type");
String nameAttColumnName = Msg.get("classeditor.nameColumn");
String visibleAttColumnName = Msg.get("classeditor.visible");
final DefaultTableModel attributesTableModel = new DefaultTableModel() {
@Override
public Class<?> getColumnClass(int index) {
if (index == 2)
return Boolean.class;
return String.class;
}
};
attributesTableModel.addColumn(typeAttColumnName);
attributesTableModel.addColumn(nameAttColumnName);
attributesTableModel.addColumn(visibleAttColumnName);
attributesTable.setModel(attributesTableModel);
attributesTable.getColumn(typeAttColumnName).setPreferredWidth(100);
attributesTable.getColumn(nameAttColumnName).setPreferredWidth(400);
attributesTable.getColumn(visibleAttColumnName).setPreferredWidth(60);
List<UmlAttribute> attributes = classModel.getAttributes();
for (int i = 0; i < attributes.size(); i++) {
Object[] row = new Object[3];
row[0] = attributes.get(i).getName().split(":")[1];
row[1] = attributes.get(i).getName().split(":")[0].substring(1);
row[2] = classElement.getAttributesVisibility().get(i);
attributesTableModel.addRow(row);
}
addAttributeButton.setText(Msg.get("classeditor.add"));
deleteAttributeButton.setText(Msg.get("classeditor.remove"));
moveUpAttributeButton.setText(Msg.get("classeditor.moveUp"));
moveDownAttributeButton.setText(Msg.get("classeditor.moveDown"));
///////////////////// METHODS //////////////////////////
((TitledBorder) methodsPanel.getBorder()).setTitle(Msg.get("classeditor.methods"));
String returnTypeColumnName = Msg.get("classeditor.returnType");
String nameMethodColumnName = Msg.get("classeditor.nameColumn");
String argsMethodColumnName = Msg.get("classeditor.arguments");
String visibleMethodColumnName = Msg.get("classeditor.visible");
final DefaultTableModel methodsTableModel = new DefaultTableModel() {
@Override
public Class<?> getColumnClass(int index) {
if (index == 3)
return Boolean.class;
return String.class;
}
};
methodsTableModel.addColumn(returnTypeColumnName);
methodsTableModel.addColumn(nameMethodColumnName);
methodsTableModel.addColumn(argsMethodColumnName);
methodsTableModel.addColumn(visibleMethodColumnName);
methodsTable.setModel(methodsTableModel);
methodsTable.getColumn(returnTypeColumnName).setPreferredWidth(80);
methodsTable.getColumn(nameMethodColumnName).setPreferredWidth(120);
methodsTable.getColumn(argsMethodColumnName).setPreferredWidth(300);
methodsTable.getColumn(visibleMethodColumnName).setPreferredWidth(60);
List<UmlMethod> methods = classModel.getMethods();
for (int i = 0; i < methods.size(); i++) {
Object[] row = new Object[4];
String[] splitted = methods.get(i).getName().split(":");
row[0] = splitted[splitted.length - 1];
row[1] = methods.get(i).getName().split("\\(")[0].substring(1);
String args = methods.get(i).getName().split("[\\(\\)]")[1];
row[2] = args == null ? "" : args;
row[3] = classElement.getMethodVisibility().get(i);
methodsTableModel.addRow(row);
}
addMethodButton.setText(Msg.get("classeditor.add"));
deleteMethodButton.setText(Msg.get("classeditor.remove"));
moveUpMethodButton.setText(Msg.get("classeditor.moveUp"));
moveDownMethodButton.setText(Msg.get("classeditor.moveDown"));
buttonOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onOK();
}
});
buttonCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onCancel();
}
});
// call onCancel() when cross is clicked
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
onCancel();
}
});
// call onCancel() on ESCAPE
contentPane.registerKeyboardAction(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onCancel();
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
addStereotypeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
stereotypeTableModel.addRow(new Object[]{"new stereotype"});
stereotypeTable.setRowSelectionInterval(stereotypeTableModel.getRowCount() - 1, stereotypeTableModel.getRowCount() - 1);
}
});
removeStereotypeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
deleteFromTable(stereotypeTable);
}
});
upStereotypeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
moveUpFromTable(stereotypeTable);
}
});
downStereotypeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
moveDownFromTable(stereotypeTable);
}
});
addAttributeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
attributesTableModel.addRow(new Object[]{"int", "newAttribute", true});
}
});
deleteAttributeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
deleteFromTable(attributesTable);
}
});
moveUpAttributeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
moveUpFromTable(attributesTable);
}
});
moveDownAttributeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
moveDownFromTable(attributesTable);
}
});
addMethodButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
methodsTableModel.addRow(new Object[]{"int", "newMethod", "value1:int,value2:int", true});
}
});
deleteMethodButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
deleteFromTable(methodsTable);
}
});
moveUpMethodButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
moveUpFromTable(methodsTable);
}
});
moveDownMethodButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
moveDownFromTable(methodsTable);
}
});
pack();
}
private void deleteFromTable(JTable table) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
int selected = table.getSelectedRow();
if (selected == -1)
return;
model.removeRow(selected);
}
private void moveUpFromTable(JTable table) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
int selected = table.getSelectedRow();
if (selected == -1 || selected == 0)
return;
Vector rows = model.getDataVector();
Object rowSelected = rows.get(selected);
Object rowAbove = rows.get(selected - 1);
rows.setElementAt(rowSelected, selected - 1);
rows.setElementAt(rowAbove, selected);
table.setRowSelectionInterval(selected - 1, selected - 1);
}
private void moveDownFromTable(JTable table) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
int selected = table.getSelectedRow();
if (selected == -1 || selected == model.getRowCount() - 1)
return;
Vector rows = model.getDataVector();
Object rowSelected = rows.get(selected);
Object rowBelow = rows.get(selected + 1);
rows.setElementAt(rowSelected, selected + 1);
rows.setElementAt(rowBelow, selected);
table.setRowSelectionInterval(selected + 1, selected + 1);
}
private void onOK() {
ArrayList<UmlAttribute> attributes = new ArrayList<>();
ArrayList<Boolean> attributesVisibility = new ArrayList<>();
ArrayList<UmlMethod> methods = new ArrayList<>();
ArrayList<Boolean> methodsVisbility = new ArrayList<>();
Vector attributesMatrix = ((DefaultTableModel) attributesTable.getModel()).getDataVector();
for (Vector row : (Vector<Vector>) attributesMatrix) {
UmlAttribute attribute = (UmlAttribute) UmlAttribute.getPrototype().clone();
String attName;
if (row.get(1) == null || ((String) row.get(1)).isEmpty() || row.get(0) == null || ((String) row.get(0)).isEmpty())
continue;
attName = "-" + row.get(1) + ":" + row.get(0);
attribute.setName(attName);
attributes.add(attribute);
attributesVisibility.add((Boolean) row.get(2));
}
Vector methodsMatrix = ((DefaultTableModel) methodsTable.getModel()).getDataVector();
for (Vector row : (Vector<Vector>) methodsMatrix) {
UmlMethod method = (UmlMethod) UmlMethod.getPrototype().clone();
String methodName;
if (row.get(1) == null || ((String) row.get(1)).isEmpty())
continue;
methodName = "+" + row.get(1) + "(";
if (row.get(2) != null)
methodName += row.get(2);
if (row.get(0) == null || ((String) row.get(0)).isEmpty())
methodName += "):void";
else
methodName += "):" + row.get(0);
method.setName(methodName);
methods.add(method);
methodsVisbility.add((Boolean) row.get(3));
}
classModel.setAttributes(attributes);
classModel.setMethods(methods);
classElement.setAttributeVisibility(attributesVisibility);
classElement.setMethodVisibility(methodsVisbility);
classModel.setName(classNameField.getText());
classModel.setAbstract(classAbstractCheckbox.isSelected());
ArrayList<UmlStereotype> stereotypes = new ArrayList<>();
for (int i = 0; i < stereotypeTableModel.getRowCount(); i++) {
UmlStereotype stereotype = (UmlStereotype) UmlStereotype.getPrototype().clone();
stereotype.setName("<<" + ((Vector<Vector>) stereotypeTableModel.getDataVector()).elementAt(i).elementAt(0) + ">>");
stereotypes.add(stereotype);
}
classModel.setStereotypes(stereotypes);
classModel.setDocumentation(documentationArea.getText());
ok = true;
dispose();
}
private void onCancel() {
// add your code here if necessary
dispose();
}
public static void main(String[] args) {
ClassElement element = (ClassElement) ClassElement.getPrototype().clone();
UmlModelElement model = (UmlModelElement) UmlBoundary.getPrototype().clone();
model.setName("MiClase");
element.setModelElement(model);
ClassDialog dialog = new ClassDialog(AppFrame.get(), element);
dialog.pack();
dialog.setVisible(true);
System.exit(0);
}
public boolean isOk() {
return ok;
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$();
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
contentPane = new JPanel();
contentPane.setLayout(new GridLayoutManager(2, 1, new Insets(10, 10, 10, 10), -1, -1));
footer = new JPanel();
footer.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));
contentPane.add(footer, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false));
final Spacer spacer1 = new Spacer();
footer.add(spacer1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
final JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1, true, false));
footer.add(panel1, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
buttonOK = new JButton();
buttonOK.setText("OK");
panel1.add(buttonOK, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
buttonCancel = new JButton();
buttonCancel.setText("Cancel");
panel1.add(buttonCancel, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
mainPanel = new JPanel();
mainPanel.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
contentPane.add(mainPanel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(700, 500), null, 0, false));
tabbedPanel = new JTabbedPane();
mainPanel.add(tabbedPanel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(200, 200), null, 0, false));
classPanel = new JPanel();
classPanel.setLayout(new GridLayoutManager(3, 1, new Insets(10, 10, 10, 10), -1, -1));
tabbedPanel.addTab("Untitled", classPanel);
namePanel = new JPanel();
namePanel.setLayout(new GridLayoutManager(1, 3, new Insets(20, 20, 20, 20), -1, -1));
classPanel.add(namePanel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
namePanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), null, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font(namePanel.getFont().getName(), namePanel.getFont().getStyle(), namePanel.getFont().getSize()), new Color(-4473925)));
classNameLabel = new JLabel();
classNameLabel.setText("Label");
namePanel.add(classNameLabel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
classNameField = new JTextField();
namePanel.add(classNameField, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
classAbstractCheckbox = new JCheckBox();
classAbstractCheckbox.setText("CheckBox");
namePanel.add(classAbstractCheckbox, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
stereotypePanel = new JPanel();
stereotypePanel.setLayout(new GridLayoutManager(1, 2, new Insets(10, 20, 10, 20), -1, -1));
stereotypePanel.setEnabled(true);
classPanel.add(stereotypePanel, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_NORTH, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(-1, 100), null, 0, false));
stereotypePanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), null, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, new Color(-16777216)));
stereotypesLeft = new JPanel();
stereotypesLeft.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
stereotypePanel.add(stereotypesLeft, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_NORTH, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(-1, 70), new Dimension(-1, 70), 0, false));
stereotypeScroll = new JScrollPane();
stereotypeScroll.setAutoscrolls(true);
stereotypesLeft.add(stereotypeScroll, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_NORTH, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(-1, 60), new Dimension(-1, 60), 0, false));
stereotypeTable = new JTable();
stereotypeTable.setShowVerticalLines(false);
stereotypeScroll.setViewportView(stereotypeTable);
stereotypesRight = new JPanel();
stereotypesRight.setLayout(new GridLayoutManager(2, 2, new Insets(0, 0, 0, 0), -1, -1));
stereotypePanel.add(stereotypesRight, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_NORTH, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(200, 60), new Dimension(-1, 60), 0, false));
addStereotypeButton = new JButton();
addStereotypeButton.setText("Button");
stereotypesRight.add(addStereotypeButton, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
removeStereotypeButton = new JButton();
removeStereotypeButton.setText("Button");
stereotypesRight.add(removeStereotypeButton, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
upStereotypeButton = new JButton();
upStereotypeButton.setText("Button");
stereotypesRight.add(upStereotypeButton, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
downStereotypeButton = new JButton();
downStereotypeButton.setText("Button");
stereotypesRight.add(downStereotypeButton, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
docPanel = new JPanel();
docPanel.setLayout(new GridLayoutManager(1, 1, new Insets(10, 20, 10, 20), -1, -1));
classPanel.add(docPanel, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
docPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), null));
final JScrollPane scrollPane1 = new JScrollPane();
docPanel.add(scrollPane1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
documentationArea = new JTextArea();
scrollPane1.setViewportView(documentationArea);
membersPanel = new JPanel();
membersPanel.setLayout(new GridLayoutManager(3, 1, new Insets(10, 10, 10, 10), -1, -1));
tabbedPanel.addTab("Untitled", membersPanel);
attributesPanel = new JPanel();
attributesPanel.setLayout(new GridLayoutManager(2, 2, new Insets(5, 5, 5, 5), -1, -1));
membersPanel.add(attributesPanel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
attributesPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "title"));
attributesTablePanel = new JPanel();
attributesTablePanel.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
attributesPanel.add(attributesTablePanel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final JScrollPane scrollPane2 = new JScrollPane();
attributesTablePanel.add(scrollPane2, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
attributesTable = new JTable();
attributesTable.setCellSelectionEnabled(true);
attributesTable.setEditingRow(-1);
attributesTable.setFocusCycleRoot(false);
scrollPane2.setViewportView(attributesTable);
attributesButtonPanel = new JPanel();
attributesButtonPanel.setLayout(new GridLayoutManager(5, 1, new Insets(0, 0, 0, 0), -1, -1));
attributesPanel.add(attributesButtonPanel, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(100, -1), null, 0, false));
addAttributeButton = new JButton();
addAttributeButton.setText("Button");
attributesButtonPanel.add(addAttributeButton, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final Spacer spacer2 = new Spacer();
attributesButtonPanel.add(spacer2, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
deleteAttributeButton = new JButton();
deleteAttributeButton.setText("Button");
attributesButtonPanel.add(deleteAttributeButton, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
moveUpAttributeButton = new JButton();
moveUpAttributeButton.setText("Button");
attributesButtonPanel.add(moveUpAttributeButton, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
moveDownAttributeButton = new JButton();
moveDownAttributeButton.setText("Button");
attributesButtonPanel.add(moveDownAttributeButton, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
methodsPanel = new JPanel();
methodsPanel.setLayout(new GridLayoutManager(1, 2, new Insets(5, 5, 5, 5), -1, -1));
membersPanel.add(methodsPanel, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
methodsPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "title"));
methodsTablePanel = new JPanel();
methodsTablePanel.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
methodsPanel.add(methodsTablePanel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final JScrollPane scrollPane3 = new JScrollPane();
methodsTablePanel.add(scrollPane3, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
methodsTable = new JTable();
scrollPane3.setViewportView(methodsTable);
methodsButtonPanel = new JPanel();
methodsButtonPanel.setLayout(new GridLayoutManager(5, 1, new Insets(0, 0, 0, 0), -1, -1));
methodsPanel.add(methodsButtonPanel, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(100, -1), null, 0, false));
addMethodButton = new JButton();
addMethodButton.setText("Button");
methodsButtonPanel.add(addMethodButton, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
deleteMethodButton = new JButton();
deleteMethodButton.setText("Button");
methodsButtonPanel.add(deleteMethodButton, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
moveUpMethodButton = new JButton();
moveUpMethodButton.setText("Button");
methodsButtonPanel.add(moveUpMethodButton, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
moveDownMethodButton = new JButton();
moveDownMethodButton.setText("Button");
methodsButtonPanel.add(moveDownMethodButton, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final Spacer spacer3 = new Spacer();
methodsButtonPanel.add(spacer3, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return contentPane;
}
}
| gpl-2.0 |
meyerjp3/jmetrik | src/main/java/com/itemanalysis/jmetrik/commandbuilder/RepeatedOption.java | 694 | /**
* Copyright 2014 J. Patrick Meyer
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.itemanalysis.jmetrik.commandbuilder;
public class RepeatedOption {
}
| gpl-2.0 |
callakrsos/Gargoyle | redmine-models/src/main/java/com/kyj/redmine/utils/ReportDataConverter.java | 4475 | /********************************
* 프로젝트 : redmine-models
* 패키지 : com.kyj.redmine.utils
* 작성일 : 2019. 4. 11.
* 작성자 : KYJ (callakrsos@naver.com)
*******************************/
package com.kyj.redmine.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import org.json.simple.JSONObject;
import com.kyj.fx.commons.utils.DateUtil;
import com.kyj.fx.commons.utils.ValueUtil;
/**
* @author KYJ (callakrsos@naver.com)
*
*/
public class ReportDataConverter implements Function<JSONObject, List<Map<String, Object>>> {
@Override
public List<Map<String, Object>> apply(JSONObject json) {
ArrayList<Map<String, Object>> arrayList = new ArrayList<>();
int index = 1;
for (Map<String, Object> from : (List<Map<String, Object>>) json.get("issues")) {
Map<String, Object> map = new LinkedHashMap<>();
Map<String, Object> mProject = (Map<String, Object>) from.get("project");
Map<String, Object> mTracker = (Map<String, Object>) from.get("tracker");
Map<String, Object> mAssignTo = (Map<String, Object>) from.get("assigned_to");
Map<String, Object> mStatus = (Map<String, Object>) from.get("status");
List<Map<String, Object>> mCustomField = (List<Map<String, Object>>) from.get("custom_fields");
// if (1.0 == (double) mProject.get("id"))
// continue;
map.put("Seq", index++);
// map.put("이슈 번호", from.get("id"));
map.put("업무명", from.get("subject"));
map.put("VOC 번호", from.get("id"));
map.put("담당 업무", "공통");
map.put("업무 구분", mTracker.get("name"));
map.put("담당자", mAssignTo == null ? "" : mAssignTo.get("name"));
map.put("상태", mStatus == null ? "" : mStatus.get("name"));
Object oStartDate = from.get("start_date");
// Object oDueDate = from.get("due_date");
Object oCloseOn = from.get("closed_on");
map.put("시작일", oStartDate);
if (ValueUtil.isNotEmpty(oCloseOn)) {
String strCloseOn = toString(toDate(oCloseOn.toString(), DateUtil.SYSTEM_DATEFORMAT_YYYY_MM_DD),
DateUtil.SYSTEM_DATEFORMAT_YYYY_MM_DD);
map.put("완료일", strCloseOn);
} else
map.put("완료일", "");
if (ValueUtil.isNotEmpty(oStartDate) && ValueUtil.isNotEmpty(oCloseOn)) {
Date start = toDate(oStartDate.toString(), DateUtil.SYSTEM_DATEFORMAT_YYYY_MM_DD);
Date end = toDate(oCloseOn.toString(), DateUtil.SYSTEM_DATEFORMAT_YYYY_MM_DD);
int s = getField(start, Calendar.DAY_OF_MONTH);
int e = getField(end, Calendar.DAY_OF_MONTH);
int calc = ((e - s) * 8) + 8;
map.put("소요시간", calc);
} else
map.put("소요시간", "N/A");
if(mCustomField == null)
{
map.put("난이도", "중");
}
else {
Optional<Map<String, Object>> issueLevel = mCustomField.stream()
.filter(m -> m.get("id")!=null)
.filter(m -> {
return "난이도".equals(m.get("name"));
}).findFirst();
if (issueLevel.isPresent()) {
map.put("난이도", issueLevel.get().get("value"));
} else {
map.put("난이도", "중");
}
}
map.put("비고", "");
// map.put("Project Name", mProject.get("name"));
// map.putAll(from);
arrayList.add(map);
}
return arrayList;
}
/**
* @작성자 : KYJ (callakrsos@naver.com)
* @작성일 : 2019. 4. 12.
* @param date
* @param format
* @return
*/
private Date toDate(String date, String format) {
try {
return new SimpleDateFormat(format).parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* @작성자 : KYJ (callakrsos@naver.com)
* @작성일 : 2019. 4. 12.
* @param date
* @param format
* @return
*/
private String toString(Date date, String format) {
return new SimpleDateFormat(format).format(date);
}
/**
* @작성자 : KYJ (callakrsos@naver.com)
* @작성일 : 2019. 4. 12.
* @param date
* @param calendarField
* @return
*/
private int getField(Date date, int calendarField) {
Calendar instance = Calendar.getInstance();
instance.setTime(date);
return instance.get(calendarField);
}
}
| gpl-2.0 |
gspd/iSPD | src/main/java/gspd/ispd/fxgui/workload/dag/icons/SynchronizeIcon.java | 2062 | package gspd.ispd.fxgui.workload.dag.icons;
import gspd.ispd.fxgui.commons.Icon;
import gspd.ispd.commons.ISPDType;
import gspd.ispd.fxgui.commons.IconEditor;
import gspd.ispd.fxgui.commons.NodeIcon;
import gspd.ispd.fxgui.workload.dag.editor.SynchronizeEditor;
import gspd.ispd.fxgui.workload.dag.shapes.SynchronizeShape;
import javafx.scene.paint.Color;
import javafx.util.Builder;
public class SynchronizeIcon extends NodeIcon {
public static final ISPDType SYNCHRONIZE_TYPE = ISPDType.type(NODE_TYPE, "SYNCHRONIZE_TYPE");
////////////////////////////////////////////
///////////// CONSTRUCTOR //////////////////
////////////////////////////////////////////
public SynchronizeIcon(boolean selected, double centerX, double centerY) {
super(SynchronizeShape::new, selected, centerX, centerY);
setType(SYNCHRONIZE_TYPE);
}
public SynchronizeIcon(double centerX, double centerY) {
this(false, centerX, centerY);
}
public SynchronizeIcon(boolean selected) {
this(selected, 0.0, 0.0);
}
public SynchronizeIcon() {
this(false, 0.0, 0.0);
}
//////////////////////////////////////////////
/////////////// OVERRIDE /////////////////////
//////////////////////////////////////////////
private static final Builder<SynchronizeIcon> SYNCHRONIZE_BUILDER = SynchronizeIcon::new;
@Override
public Builder<? extends Icon> iconBuilder() {
return SYNCHRONIZE_BUILDER;
}
private static final SynchronizeEditor SYNCHRONIZE_EDITOR = new SynchronizeEditor();
@Override
protected IconEditor editor() {
SYNCHRONIZE_EDITOR.setIcon(this);
return SYNCHRONIZE_EDITOR;
}
@Override
protected void updateIcon() {
SynchronizeShape shape = (SynchronizeShape) getContent();
if (isSelected()) {
shape.setFill(Color.MEDIUMBLUE);
shape.setStroke(Color.DARKBLUE);
} else {
shape.setFill(Color.BLACK);
shape.setStroke(Color.BLACK);
}
}
}
| gpl-2.0 |
eubon/biodiversity-portal | dataset-search-portal/EBPCoreBeans/src/com/ibm/gbs/ebp/core/exception/NotFoundException.java | 367 | package com.ibm.gbs.ebp.core.exception;
public class NotFoundException extends Exception {
/**
*
*/
private static final long serialVersionUID = -8074972544460523454L;
//Parameterless Constructor
public NotFoundException() {}
//Constructor that accepts a message
public NotFoundException(String message)
{
super(message);
}
}
| gpl-2.0 |
vertexclique/travertine | libsmi/test/dumps/jax/RpMauEntryImpl.java | 2214 | /*
* This Java file has been generated by smidump 0.4.5. It
* is intended to be edited by the application programmer and
* to be used within a Java AgentX sub-agent environment.
*
* $Id: RpMauEntryImpl.java 4432 2006-05-29 16:21:11Z strauss $
*/
/**
This class extends the Java AgentX (JAX) implementation of
the table row rpMauEntry defined in MAU-MIB.
*/
import jax.AgentXOID;
import jax.AgentXSetPhase;
import jax.AgentXResponsePDU;
import jax.AgentXEntry;
public class RpMauEntryImpl extends RpMauEntry
{
// constructor
public RpMauEntryImpl(int rpMauGroupIndex,
int rpMauPortIndex,
int rpMauIndex)
{
super(rpMauGroupIndex,
rpMauPortIndex,
rpMauIndex);
}
public int get_rpMauGroupIndex()
{
return rpMauGroupIndex;
}
public int get_rpMauPortIndex()
{
return rpMauPortIndex;
}
public int get_rpMauIndex()
{
return rpMauIndex;
}
public AgentXOID get_rpMauType()
{
return rpMauType;
}
public int get_rpMauStatus()
{
return rpMauStatus;
}
public int set_rpMauStatus(AgentXSetPhase phase, int value)
{
switch (phase.getPhase()) {
case AgentXSetPhase.TEST_SET:
break;
case AgentXSetPhase.COMMIT:
undo_rpMauStatus = rpMauStatus;
rpMauStatus = value;
break;
case AgentXSetPhase.UNDO:
rpMauStatus = undo_rpMauStatus;
break;
case AgentXSetPhase.CLEANUP:
break;
default:
return AgentXResponsePDU.PROCESSING_ERROR;
}
return AgentXResponsePDU.NO_ERROR;
}
public int get_rpMauMediaAvailable()
{
return rpMauMediaAvailable;
}
public long get_rpMauMediaAvailableStateExits()
{
return rpMauMediaAvailableStateExits;
}
public int get_rpMauJabberState()
{
return rpMauJabberState;
}
public long get_rpMauJabberingStateEnters()
{
return rpMauJabberingStateEnters;
}
public long get_rpMauFalseCarriers()
{
return rpMauFalseCarriers;
}
}
| gpl-2.0 |
shellposhy/cms | src/main/java/cn/com/cms/data/util/DataUtil.java | 10448 | package cn.com.cms.data.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.sql.Blob;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.sql.rowset.serial.SerialException;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML.Attribute;
import javax.swing.text.html.HTML.Tag;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumericField;
import cn.com.cms.data.model.DataField;
import cn.com.cms.framework.base.CmsData;
import cn.com.cms.framework.base.table.FieldCodes;
import cn.com.cms.framework.config.SystemConstant;
import cn.com.cms.library.constant.EDataType;
import cn.com.people.data.util.DateTimeUtil;
import cn.com.people.data.util.HtmlUtil;
import cn.com.pepper.common.PepperResult;
import cn.com.pepper.comparator.base.PepperSortField.FieldType;
/**
* 数据工具类
*
* @author shishb
* @version 1.0
*/
public class DataUtil {
/**
* 根据数值和数据类型获得数据对象
*
* @param value
* 数据值
* @param dataType
* 数据类型
* @return
* @throws ParseException
* @throws SerialException
* @throws SQLException
* @throws UnsupportedEncodingException
*/
public static Object getDataTypeObject(String value, EDataType dataType) {
switch (dataType) {
case Date:
case DateTime:
case Time:
if (null == value || value.isEmpty()) {
return null;
} else {
return DateTimeUtil.parse(value);
}
case Short:
return Short.valueOf(value);
case Int:
if (null == value || value.isEmpty()) {
return 0;
} else {
return Integer.valueOf(value);
}
case Long:
return Long.valueOf(value);
case Float:
return Float.valueOf(value);
case Double:
case Numeric:
return Double.valueOf(value);
case Bool:
return Boolean.valueOf(value);
case Blob:
case MediumBlob:
// return new SerialBlob(value.getBytes("utf-8"));
case Char:
case Varchar:
case UUID:
default:
return value;
}
}
/**
* 根据数据类型获得数据对象的字符串
*
* @param object
* @param dataType
* @return
*/
public static String getDataTypeString(Object object, EDataType dataType) {
switch (dataType) {
case Date:
case DateTime:
case Time:
if ("".equals(object)) {
return "";
} else {
return DateTimeUtil.formatDateTime((Date) object);
}
default:
return null == object ? "" : object.toString();
}
}
/**
* 获取数据类型的默认值
*
* @param dataType
* 数据类型
* @param isNotNull
* 可否为空
* @return
*/
public static Object getDefaultValue(EDataType dataType, boolean isNotNull) {
switch (dataType) {
case Date:
case DateTime:
case Time:
return isNotNull ? DateTimeUtil.getCurrentDateTime() : null;
case Short:
return (short) 0;
case Int:
return 0;
case Long:
return (long) 0;
case Float:
return (float) 0;
case Double:
case Numeric:
return (double) 0;
case Bool:
return false;
case Blob:
case MediumBlob:
case Char:
case Varchar:
case UUID:
default:
return "";
}
}
/**
* 布尔值转字符串
*
* @param blob
* @return
* @throws UnsupportedEncodingException
* @throws SQLException
* @throws IOException
*/
public static String getString(Blob blob) throws UnsupportedEncodingException, SQLException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(blob.getBinaryStream(), "utf-8"));
String s = null;
StringBuilder sb = new StringBuilder();
while ((s = br.readLine()) != null) {
sb.append(s);
}
return sb.toString();
}
/**
* 索引搜索结果转PeopleData列表
*
* @param pepperResult
* @param fieldList
* @return
*/
public static List<CmsData> getPeopleDataList(PepperResult pepperResult, List<DataField> fieldList) {
List<CmsData> result = new ArrayList<CmsData>();
if (null != pepperResult && null != pepperResult.documents) {
for (Document doc : pepperResult.documents) {
result.add(getPeopleData(doc, fieldList));
}
}
return result;
}
/**
* 索引文档转PeopleData
*
* @param doc
* @param fieldList
* @return
*/
public static CmsData getPeopleData(Document doc, List<DataField> fieldList) {
CmsData peopleData = new CmsData();
peopleData.setId(Integer.parseInt(doc.get(FieldCodes.ID)));
peopleData.setTableId(Integer.parseInt(doc.get(FieldCodes.TABLE_ID)));
peopleData.setBaseId(Integer.parseInt(doc.get(FieldCodes.BASE_ID)));
for (DataField df : fieldList) {
if (null == doc.get(df.getCode())) {
peopleData.put(df.getCode(), "");
} else {
switch (df.getDataType()) {
case Date:
case Time:
case DateTime:
peopleData.put(df.getCode(), DateTimeUtil.parse(doc.get(df.getCode()), "yyyyMMddHHmmss"));
break;
default:
peopleData.put(df.getCode(), getDataTypeObject(doc.get(df.getCode()), df.getDataType()));
break;
}
}
}
return peopleData;
}
/**
* 数据对象转换索引文档
*
* @param data
* 数据对象
* @param fieldList
* 字段列表
* @return
* @throws IOException
*/
public static Document getIndexDoc(CmsData data, List<DataField> fieldList) throws IOException {
NumericField nField = null;
Date now = new Date();
Document doc = new Document();
// TABLE_ID
nField = new NumericField(FieldCodes.TABLE_ID, Field.Store.YES, true);
nField.setIntValue(data.getTableId());
doc.add(nField);
// BASE_ID
nField = new NumericField(FieldCodes.BASE_ID, Field.Store.YES, true);
nField.setIntValue(data.getBaseId());
doc.add(nField);
// Index_Time
nField = new NumericField(FieldCodes.INDEX_TIME, Field.Store.YES, true);
nField.setLongValue(Long.parseLong(getIndexDateTimeStr(now)));
doc.add(nField);
Field.Index indexType = null;
Field.Store store = null;
String fieldCode = null;
boolean toIndex = true;
for (DataField df : fieldList) {
toIndex = true;
switch (df.getIndexType()) {
case Analyzed:
indexType = Field.Index.ANALYZED;
break;
case AnalyzedNoNorms:
indexType = Field.Index.ANALYZED_NO_NORMS;
break;
case No:
indexType = Field.Index.NO;
toIndex = false;
break;
case NotAnalyzed:
indexType = Field.Index.NOT_ANALYZED;
break;
case NotAnalyzedNoNorms:
indexType = Field.Index.NOT_ANALYZED_NO_NORMS;
break;
}
if (df.isIndexStore()) {
store = Field.Store.YES;
} else {
store = Field.Store.NO;
}
fieldCode = df.getCode();
Object value = null;
value = data.get(fieldCode);
if (!(store == Field.Store.NO && indexType == Field.Index.NO) && value != null) {
switch (df.getDataType()) {
case UUID:
case Char:
case Varchar:
case Blob:
case MediumBlob:
case Bool:
try {
doc.add(new Field(df.getCode(), HtmlUtil.getText(String.valueOf(value)), store, indexType));
} catch (Exception e) {
e.printStackTrace();
}
break;
case Short:
case IntAutoIncrement:
case Int:
nField = new NumericField(fieldCode, store, toIndex);
nField.setIntValue(Integer.parseInt(value.toString()));
doc.add(nField);
break;
case Long:
nField = new NumericField(fieldCode, store, toIndex);
nField.setLongValue(Long.parseLong(value.toString()));
doc.add(nField);
break;
case Float:
nField = new NumericField(fieldCode, store, toIndex);
nField.setFloatValue(Float.parseFloat(value.toString()));
doc.add(nField);
break;
case Double:
case Numeric:
nField = new NumericField(fieldCode, store, toIndex);
nField.setDoubleValue(Double.parseDouble(value.toString()));
doc.add(nField);
break;
case Date:
case Time:
case DateTime:
nField = new NumericField(fieldCode, store, toIndex);
nField.setLongValue(Long.parseLong(getIndexDateTimeStr((Date) value)));
doc.add(nField);
break;
}
}
}
return doc;
}
/**
* 日期转字符串
*
* @param date
* @return
*/
public static String getIndexDateTimeStr(Date date) {
return DateTimeUtil.format(date, SystemConstant.INDEX_DATE_FORMAT);
}
/**
* 数据类型转索引类型
*
* @param dataType
* @return
*/
public static String dataType2LuceneType(EDataType dataType) {
String luceneType = "";
if (dataType.equals(EDataType.Int) || dataType.equals(EDataType.IntAutoIncrement)
|| dataType.equals(EDataType.Short) || dataType.equals(EDataType.Numeric)) {
luceneType = "#int#";
} else if (dataType.equals(EDataType.Long)) {
luceneType = "#long#";
} else if (dataType.equals(EDataType.Float)) {
luceneType = "#float#";
} else if (dataType.equals(EDataType.Double)) {
luceneType = "#double#";
}
return luceneType;
}
/**
* 数据类型转排序类型
*
* @param dataType
* @return
*/
public static FieldType dataType2SortType(EDataType dataType) {
switch (dataType) {
case Int:
case IntAutoIncrement:
return FieldType.Int;
case Long:
return FieldType.Long;
case Float:
return FieldType.Float;
case Double:
return FieldType.Double;
case Time:
case DateTime:
return FieldType.StringVal;
// return FieldType.Long;
default:
return FieldType.StringVal;
}
}
/**
* 获取html里的所有img的src
*
* @param html
* @return
* @throws IOException
*/
public static List<String> getImgs(final String html) throws IOException {
final List<String> imgs = new LinkedList<String>();
if (null == html || html.isEmpty()) {
return imgs;
}
final Reader r = new StringReader(html);
ParserDelegator pd = new ParserDelegator();
pd.parse(r, new HTMLEditorKit.ParserCallback() {
@Override
public void handleSimpleTag(Tag t, MutableAttributeSet a, int pos) {
if (Tag.IMG.equals(t)) {
imgs.add((String) a.getAttribute(Attribute.SRC));
}
}
}, false);
r.close();
if (imgs.size() > 0) {
return imgs;
} else {
return null;
}
}
}
| gpl-2.0 |
palomagc/MovieChatter | src/icaro/aplicaciones/recursos/comunicacionChat/imp/ComunicacionChatImp.java | 4666 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package icaro.aplicaciones.recursos.comunicacionChat.imp;
import icaro.aplicaciones.recursos.comunicacionChat.imp.util.IrcException;
import icaro.aplicaciones.recursos.comunicacionChat.imp.util.NickAlreadyInUseException;
import icaro.aplicaciones.recursos.comunicacionChat.imp.util.ConexionIrc;
import icaro.infraestructura.entidadesBasicas.comunicacion.ComunicacionAgentes;
import icaro.infraestructura.entidadesBasicas.comunicacion.MensajeSimple;
import icaro.infraestructura.entidadesBasicas.excepciones.ExcepcionEnComponente;
import icaro.infraestructura.entidadesBasicas.interfaces.InterfazUsoAgente;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author FGarijo
*/
public class ComunicacionChatImp extends ConexionIrc {
private String identRecurso;
private String url = null;
private String nickname = null;
private String chanel = "#kiwiirc-movies";
private Boolean conectado = false;
public InterfazUsoAgente itfUsoAgenteGestDialogo;
private String identificadorAgenteGestorDialogo;
private ComunicacionAgentes comunicator;
private MensajeSimple mensajeAenviar;
public ComunicacionChatImp(String identRecurso, String url, String nickname) {
this.url = url;
this.nickname = nickname;
this.setName(this.nickname);
comunicator = new ComunicacionAgentes(this.identRecurso);
}
public void setItfUsoAgenteGestorDialogo(InterfazUsoAgente itfUsoAgenteDialogo) {
this.itfUsoAgenteGestDialogo = itfUsoAgenteDialogo;
}
public synchronized final void setIdentAgenteGestorDialogo(String identAgenteDialogo) {
this.identificadorAgenteGestorDialogo = identAgenteDialogo;
}
public synchronized final String getIdentAgenteGestorDialogo() {
return identificadorAgenteGestorDialogo;
}
public Boolean conectar() {
this.setVerbose(true); // Debugging -> false
conectado = isConnected();
while (!conectado) {
try {
this.connect(url);
this.joinChannel(chanel);
this.changeNick(nickname);
conectado = true;
// this.sendMessage("movieBot", "hola hola");
} catch (IOException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IrcException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
} catch (NickAlreadyInUseException ex) {
Logger.getLogger(ComunicacionChatImp.class.getName()).log(Level.SEVERE, null, ex);
}
}
return conectado;
}
public Boolean nuevaConexion(String urlNueva, String canal, String nick) {
if (conectado) {
if (this.url.equals(urlNueva))
if (!this.chanel.equals(canal))
this.chanel = canal;
return true;
}
this.url = urlNueva;
this.chanel = canal;
this.nickname = nick;
return this.conectar();
}
@Override
public void onPrivateMessage(String sender, String login, String hostname, String message) {
// if(message.matches("Hola"))
// {
// sendRawLine("PRIVMSG "+sender+" :Hola, "+sender+"!");
// }else
// {
// sendRawLine("PRIVMSG "+sender+" :Lo siento pero no entiendo lo que dices");
// }
// String agteReceptor = getIdentAgenteGestorDialogo();
if (getIdentAgenteGestorDialogo() != null) {
mensajeAenviar = new MensajeSimple(message, sender, getIdentAgenteGestorDialogo());
comunicator.enviarMsgaOtroAgente(mensajeAenviar);
} else
try {
throw new ExcepcionEnComponente(
"El identificador del Gestor de dialogo no esta definido", this.getClass()
.getSimpleName(), null);
} catch (ExcepcionEnComponente ex) {
Logger.getLogger(ComunicacionChatImp.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void onMessage(String chanel, String sender, String login, String hostname,
String message) {
this.log("chanel:" + chanel + " Sender :" + sender + "hostname: " + hostname + "mensaje :"
+ message);
if (getIdentAgenteGestorDialogo() != null)
comunicator.enviarInfoAotroAgente(sender + message, getIdentAgenteGestorDialogo());
else
try {
throw new ExcepcionEnComponente(
"El identificador del Gestor de dialogo no esta definido", this.getClass()
.getSimpleName(), null);
} catch (ExcepcionEnComponente ex) {
Logger.getLogger(ComunicacionChatImp.class.getName()).log(Level.SEVERE, null, ex);
}
// if(message.matches("hola"))
// {
// sendRawLine("PRIVMSG "+sender+" :Hola, "+sender+"!");
// }else
// {
// sendRawLine("PRIVMSG "+sender+" :Lo siento pero no entiendo lo que dices");
// }
}
}
| gpl-2.0 |
mateli/OpenCyclos | src/main/java/nl/strohalm/cyclos/entities/access/PrincipalAttributeConverter.java | 466 | package nl.strohalm.cyclos.entities.access;
import nl.strohalm.cyclos.entities.converters.StringValuedEnumAttributeConverter;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter(autoApply = true)
public class PrincipalAttributeConverter extends StringValuedEnumAttributeConverter<Channel.Principal>
/* https://bugs.eclipse.org/bugs/show_bug.cgi?id=415296 */ implements AttributeConverter<Channel.Principal, String> {
}
| gpl-2.0 |
ia-toki/judgels | judgels-backends/jerahmeel/jerahmeel-app/src/main/java/judgels/jerahmeel/hibernate/StatsUserProblemHibernateDao.java | 6832 | package judgels.jerahmeel.hibernate;
import com.google.common.collect.ImmutableMap;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.persistence.Tuple;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import judgels.gabriel.api.Verdict;
import judgels.jerahmeel.persistence.StatsUserProblemDao;
import judgels.jerahmeel.persistence.StatsUserProblemModel;
import judgels.jerahmeel.persistence.StatsUserProblemModel_;
import judgels.persistence.FilterOptions;
import judgels.persistence.api.SelectionOptions;
import judgels.persistence.hibernate.HibernateDao;
import judgels.persistence.hibernate.HibernateDaoData;
public class StatsUserProblemHibernateDao extends HibernateDao<StatsUserProblemModel> implements StatsUserProblemDao {
@Inject
public StatsUserProblemHibernateDao(HibernateDaoData data) {
super(data);
}
@Override
public Optional<StatsUserProblemModel> selectByUserJidAndProblemJid(String userJid, String problemJid) {
return selectByUniqueColumns(ImmutableMap.of(
StatsUserProblemModel_.userJid, userJid,
StatsUserProblemModel_.problemJid, problemJid));
}
@Override
public List<StatsUserProblemModel> selectAllByUserJidAndProblemJids(String userJid, Set<String> problemJids) {
return selectAll(new FilterOptions.Builder<StatsUserProblemModel>()
.putColumnsEq(StatsUserProblemModel_.userJid, userJid)
.putColumnsIn(StatsUserProblemModel_.problemJid, problemJids)
.build());
}
@Override
public List<StatsUserProblemModel> selectAllByUserJidsAndProblemJids(
Set<String> userJids,
Set<String> problemJids) {
return selectAll(new FilterOptions.Builder<StatsUserProblemModel>()
.putColumnsIn(StatsUserProblemModel_.userJid, userJids)
.putColumnsIn(StatsUserProblemModel_.problemJid, problemJids)
.build());
}
@Override
public List<StatsUserProblemModel> selectAllByProblemJid(String problemJid, SelectionOptions options) {
return selectAll(new FilterOptions.Builder<StatsUserProblemModel>()
.putColumnsEq(StatsUserProblemModel_.problemJid, problemJid)
.build(), options);
}
@Override
public List<StatsUserProblemModel> selectAllAcceptedByProblemJid(String problemJid, SelectionOptions options) {
return selectAll(new FilterOptions.Builder<StatsUserProblemModel>()
.putColumnsEq(StatsUserProblemModel_.problemJid, problemJid)
.putColumnsEq(StatsUserProblemModel_.verdict, Verdict.ACCEPTED.getCode())
.build(), options);
}
@Override
public Map<String, Long> selectTotalScoresByProblemJids(Set<String> problemJids) {
if (problemJids.isEmpty()) {
return Collections.emptyMap();
}
CriteriaBuilder cb = currentSession().getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<StatsUserProblemModel> root = cq.from(getEntityClass());
cq.select(cb.tuple(
root.get(StatsUserProblemModel_.problemJid),
cb.sum(root.get(StatsUserProblemModel_.score))));
cq.where(
root.get(StatsUserProblemModel_.problemJid).in(problemJids));
cq.groupBy(
root.get(StatsUserProblemModel_.problemJid));
return currentSession().createQuery(cq).getResultList()
.stream()
.collect(Collectors.toMap(tuple -> tuple.get(0, String.class), tuple -> tuple.get(1, Long.class)));
}
@Override
public Map<String, Long> selectCountsAcceptedByProblemJids(Set<String> problemJids) {
if (problemJids.isEmpty()) {
return Collections.emptyMap();
}
CriteriaBuilder cb = currentSession().getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<StatsUserProblemModel> root = cq.from(getEntityClass());
cq.select(cb.tuple(
root.get(StatsUserProblemModel_.problemJid),
cb.count(root)));
cq.where(
cb.equal(root.get(StatsUserProblemModel_.verdict), Verdict.ACCEPTED.getCode()),
root.get(StatsUserProblemModel_.problemJid).in(problemJids));
cq.groupBy(
root.get(StatsUserProblemModel_.problemJid));
return currentSession().createQuery(cq).getResultList()
.stream()
.collect(Collectors.toMap(tuple -> tuple.get(0, String.class), tuple -> tuple.get(1, Long.class)));
}
@Override
public Map<String, Long> selectCountsTriedByProblemJids(Set<String> problemJids) {
if (problemJids.isEmpty()) {
return Collections.emptyMap();
}
CriteriaBuilder cb = currentSession().getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<StatsUserProblemModel> root = cq.from(getEntityClass());
cq.select(cb.tuple(
root.get(StatsUserProblemModel_.problemJid),
cb.count(root)));
cq.where(
root.get(StatsUserProblemModel_.problemJid).in(problemJids));
cq.groupBy(
root.get(StatsUserProblemModel_.problemJid));
return currentSession().createQuery(cq).getResultList()
.stream()
.collect(Collectors.toMap(tuple -> tuple.get(0, String.class), tuple -> tuple.get(1, Long.class)));
}
@Override
public long selectCountTriedByUserJid(String userJid) {
return selectCount(new FilterOptions.Builder<StatsUserProblemModel>()
.putColumnsEq(StatsUserProblemModel_.userJid, userJid)
.build());
}
@Override
public Map<String, Long> selectCountsVerdictByUserJid(String userJid) {
CriteriaBuilder cb = currentSession().getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<StatsUserProblemModel> root = cq.from(getEntityClass());
cq.select(cb.tuple(
root.get(StatsUserProblemModel_.verdict),
cb.count(root)));
cq.where(
cb.equal(root.get(StatsUserProblemModel_.userJid), userJid));
cq.groupBy(
root.get(StatsUserProblemModel_.verdict));
return currentSession().createQuery(cq).getResultList()
.stream()
.collect(Collectors.toMap(tuple -> tuple.get(0, String.class), tuple -> tuple.get(1, Long.class)));
}
}
| gpl-2.0 |
loveyoupeng/rt | modules/graphics/src/main/java/com/sun/scenario/effect/impl/state/BoxRenderState.java | 25286 | /*
* Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.scenario.effect.impl.state;
import com.sun.javafx.geom.Rectangle;
import com.sun.javafx.geom.transform.BaseTransform;
import com.sun.javafx.geom.transform.NoninvertibleTransformException;
import com.sun.scenario.effect.Color4f;
import com.sun.scenario.effect.Effect;
import com.sun.scenario.effect.FilterContext;
import com.sun.scenario.effect.Filterable;
import com.sun.scenario.effect.ImageData;
import com.sun.scenario.effect.impl.BufferUtil;
import com.sun.scenario.effect.impl.EffectPeer;
import com.sun.scenario.effect.impl.Renderer;
import java.nio.FloatBuffer;
/**
* The RenderState for a box filter kernel that can be applied using a
* standard linear convolution kernel.
* A box filter has a size that represents how large of an area around a
* given pixel should be averaged. If the size is 1.0 then just the pixel
* itself should be averaged and the operation is a NOP. Values smaller
* than that are automatically treated as 1.0/NOP.
* For any odd size, the kernel weights the center pixel and an equal number
* of pixels on either side of it equally, so the weights for size 2N+1 are:
* [ {N copes of 1.0} 1.0 {N more copies of 1.0} ]
* As the size grows past that integer size, we must then add another kernel
* weight entry on both sides of the existing array of 1.0 weights and give
* them a fractional weight of half of the amount we exceeded the last odd
* size, so the weights for some size (2N+1)+e (e for epsilon) are:
* [ e/2.0 {2*N+1 copies of 1.0} e/2.0 ]
* As the size continues to grow, when it reaches the next even size, we get
* weights for size 2*N+1+1 to be:
* [ 0.5 {2*N+1 copies of 1.0} 0.5 ]
* and as the size continues to grow and approaches the next odd number, we
* see that 2(N+1)+1 == 2N+2+1 == 2N+1 + 2, so (e) approaches 2 and the
* numbers on each end of the weights array approach e/2.0 == 1.0 and we end
* up back at the pattern for an odd size again:
* [ 1.0 {2*N+1 copies of 1.0} 1.0 ]
*
* ***************************
* SOFTWARE LIMITATION CAVEAT:
* ***************************
*
* Note that the highly optimized software filters for BoxBlur/Shadow will
* actually do a very optimized "running sum" operation that is only currently
* implemented for equal weighted kernels. Also, until recently we had always
* been rounding down the size by casting it to an integer at a high level (in
* the FX layer peer synchronization code), so for now the software filters
* may only implement a subset of the above theory and new optimized loops that
* allow partial sums on the first and last values will need to be written.
* Until then we will be rounding the sizes to an odd size, but only in the
* sw loops.
*/
public class BoxRenderState extends LinearConvolveRenderState {
private static final int MAX_BOX_SIZES[] = {
getMaxSizeForKernelSize(MAX_KERNEL_SIZE, 0),
getMaxSizeForKernelSize(MAX_KERNEL_SIZE, 1),
getMaxSizeForKernelSize(MAX_KERNEL_SIZE, 2),
getMaxSizeForKernelSize(MAX_KERNEL_SIZE, 3),
};
private final boolean isShadow;
private final int blurPasses;
private final float spread;
private Color4f shadowColor;
private EffectCoordinateSpace space;
private BaseTransform inputtx;
private BaseTransform resulttx;
private final float inputSizeH;
private final float inputSizeV;
private final int spreadPass;
private float samplevectors[];
private int validatedPass;
private float passSize;
private FloatBuffer weights;
private float weightsValidSize;
private float weightsValidSpread;
private boolean swCompatible; // true if we can use the sw peers
public static int getMaxSizeForKernelSize(int kernelSize, int blurPasses) {
if (blurPasses == 0) {
return Integer.MAX_VALUE;
}
// Kernel sizes are always odd, so if the supplied ksize is even then
// we need to use ksize-1 to compute the max as that is actually the
// largest kernel we will be able to produce that is no larger than
// ksize for any given pass size.
int passSize = (kernelSize - 1) | 1;
passSize = ((passSize - 1) / blurPasses) | 1;
assert getKernelSize(passSize, blurPasses) <= kernelSize;
return passSize;
}
public static int getKernelSize(int passSize, int blurPasses) {
int kernelSize = (passSize < 1) ? 1 : passSize;
kernelSize = (kernelSize-1) * blurPasses + 1;
kernelSize |= 1;
return kernelSize;
}
public BoxRenderState(float hsize, float vsize, int blurPasses, float spread,
boolean isShadow, Color4f shadowColor, BaseTransform filtertx)
{
/*
* The operation starts as a description of the size of a (pair of)
* box filter kernels measured relative to that user space coordinate
* system and to be applied horizontally and vertically in that same
* space. The presence of a filter transform can mean that the
* direction we apply the box convolutions could change as well
* as the new size of the box summations relative to the pixels
* produced under that transform.
*
* Since the box filter is best described by the summation of a range
* of discrete pixels horizontally and vertically, and since the
* software algorithms vastly prefer applying the sums horizontally
* and vertically to groups of whole pixels using an incremental "add
* the next pixel at the front edge of the box and subtract the pixel
* that is at the back edge of the box" technique, we will constrain
* our box size to an integer size and attempt to force the inputs
* to produce an axis aligned intermediate image. But, in the end,
* we must be prepared for an arbitrary transform on the input image
* which essentially means being able to back off to an arbitrary
* invocation on the associated LinearConvolvePeer from the software
* hand-written Box peers.
*
* We will track the direction and size of the box as we traverse
* different coordinate spaces with the intent that eventually we
* will perform the math of the convolution with weights calculated
* for one sample per pixel in the indicated direction and applied as
* closely to the intended final filter transform as we can achieve
* with the following caveats (very similar to the caveats for the
* more general GaussianRenderState):
*
* - There is a maximum kernel size that the hardware pixel shaders
* can apply so we will try to keep the scaling of the filtered
* pixels low enough that we do not exceed that data limitation.
*
* - Software vastly prefers to apply these weights along horizontal
* and vertical vectors, but can apply them in an arbitrary direction
* if need be by backing off to the generic LinearConvolvePeer.
*
* - If the box is large enough, then applying a smaller box kernel
* to a downscaled input is close enough to applying the larger box
* to a larger scaled input. Our maximum kernel size is large enough
* for this effect to be hidden if we max out the kernel.
*
* - We can tell the inputs what transform we want them to use, but
* they can always produce output under a different transform and
* then return a result with a "post-processing" trasnform to be
* applied (as we are doing here ourselves). Thus, we can plan
* how we want to apply the convolution weights and samples here,
* but we will have to reevaluate our actions when the actual
* input pixels are created later.
*
* - We will try to blur at a nice axis-aligned orientation (which is
* preferred for the software versions of the shaders) and perform
* any rotation and skewing in the final post-processing result
* transform as that amount of blurring will quite effectively cover
* up any distortion that would occur by not rendering at the
* appropriate angles.
*
* To achieve this we start out with untransformed sample vectors
* which are unit vectors along the X and Y axes. We transform them
* into the requested filter space, adjust the kernel size and see
* if we can support that kernel size. If it is too large of a
* projected kernel, then we request the input at a smaller scale
* and perform a maximum kernel convolution on it and then indicate
* that this result will need to be scaled by the caller. When this
* method is done we will have computed what we need to do to the
* input pixels when they come in if the inputtx was honored, otherwise
* we may have to adjust the values further in {@link @validateInput()}.
*/
this.isShadow = isShadow;
this.shadowColor = shadowColor;
this.spread = spread;
this.blurPasses = blurPasses;
if (filtertx == null) filtertx = BaseTransform.IDENTITY_TRANSFORM;
double txScaleX = Math.hypot(filtertx.getMxx(), filtertx.getMyx());
double txScaleY = Math.hypot(filtertx.getMxy(), filtertx.getMyy());
float fSizeH = (float) (hsize * txScaleX);
float fSizeV = (float) (vsize * txScaleY);
int maxPassSize = MAX_BOX_SIZES[blurPasses];
if (fSizeH > maxPassSize) {
txScaleX = maxPassSize / hsize;
fSizeH = maxPassSize;
}
if (fSizeV > maxPassSize) {
txScaleY = maxPassSize / vsize;
fSizeV = maxPassSize;
}
this.inputSizeH = fSizeH;
this.inputSizeV = fSizeV;
this.spreadPass = (fSizeV > 1) ? 1 : 0;
// We always want to use an unrotated space to do our filtering, so
// we interpose our scaled-only space in all cases, but we do check
// if it happens to be equivalent (ignoring translations) to the
// original filtertx so we can avoid introducing extra layers of
// transforms.
boolean custom = (txScaleX != filtertx.getMxx() ||
0.0 != filtertx.getMyx() ||
txScaleY != filtertx.getMyy() ||
0.0 != filtertx.getMxy());
if (custom) {
this.space = EffectCoordinateSpace.CustomSpace;
this.inputtx = BaseTransform.getScaleInstance(txScaleX, txScaleY);
this.resulttx = filtertx
.copy()
.deriveWithScale(1.0 / txScaleX, 1.0 / txScaleY, 1.0);
} else {
this.space = EffectCoordinateSpace.RenderSpace;
this.inputtx = filtertx;
this.resulttx = BaseTransform.IDENTITY_TRANSFORM;
}
// assert inputtx.mxy == inputtx.myx == 0.0
}
public int getBoxPixelSize(int pass) {
float size = passSize;
if (size < 1.0f) size = 1.0f;
int boxsize = ((int) Math.ceil(size)) | 1;
return boxsize;
}
public int getBlurPasses() {
return blurPasses;
}
public float getSpread() {
return spread;
}
@Override
public boolean isShadow() {
return isShadow;
}
@Override
public Color4f getShadowColor() {
return shadowColor;
}
@Override
public float[] getPassShadowColorComponents() {
return (validatedPass == 0)
? BLACK_COMPONENTS
: shadowColor.getPremultipliedRGBComponents();
}
@Override
public EffectCoordinateSpace getEffectTransformSpace() {
return space;
}
@Override
public BaseTransform getInputTransform(BaseTransform filterTransform) {
return inputtx;
}
@Override
public BaseTransform getResultTransform(BaseTransform filterTransform) {
return resulttx;
}
@Override
public EffectPeer<BoxRenderState> getPassPeer(Renderer r, FilterContext fctx) {
if (isPassNop()) {
return null;
}
int ksize = getPassKernelSize();
int psize = getPeerSize(ksize);
Effect.AccelType actype = r.getAccelType();
String name;
switch (actype) {
case NONE:
case SIMD:
if (swCompatible && spread == 0.0f) {
name = isShadow() ? "BoxShadow" : "BoxBlur";
break;
}
/* FALLS THROUGH */
default:
name = isShadow() ? "LinearConvolveShadow" : "LinearConvolve";
break;
}
EffectPeer peer = r.getPeerInstance(fctx, name, psize);
return peer;
}
@Override
public Rectangle getInputClip(int i, Rectangle filterClip) {
if (filterClip != null) {
int klenh = getInputKernelSize(0);
int klenv = getInputKernelSize(1);
if ((klenh | klenv) > 1) {
filterClip = new Rectangle(filterClip);
// We actually want to grow them by (klen-1)/2, but since we
// have forced the klen sizes to be odd above, a simple integer
// divide by 2 is enough...
filterClip.grow(klenh/2, klenv/2);
}
}
return filterClip;
}
@Override
public ImageData validatePassInput(ImageData src, int pass) {
this.validatedPass = pass;
BaseTransform srcTx = src.getTransform();
samplevectors = new float[2];
samplevectors[pass] = 1.0f;
float iSize = (pass == 0) ? inputSizeH : inputSizeV;
if (srcTx.isTranslateOrIdentity()) {
this.swCompatible = true;
this.passSize = iSize;
} else {
// The input produced a texture that requires transformation,
// reevaluate our box sizes.
// First (inverse) transform our sample vectors from the intended
// srcTx space back into the actual pixel space of the src texture.
// Then evaluate their length and attempt to absorb as much of any
// implicit scaling that would happen into our final pixelSizes,
// but if we overflow the maximum supportable pass size then we will
// just have to sample sparsely with a longer than unit vector.
// REMIND: we should also downsample the texture by powers of
// 2 if our sampling will be more sparse than 1 sample per 2
// pixels.
try {
srcTx.inverseDeltaTransform(samplevectors, 0, samplevectors, 0, 1);
} catch (NoninvertibleTransformException ex) {
this.passSize = 0.0f;
samplevectors[0] = samplevectors[1] = 0.0f;
this.swCompatible = true;
return src;
}
double srcScale = Math.hypot(samplevectors[0], samplevectors[1]);
float pSize = (float) (iSize * srcScale);
pSize *= srcScale;
int maxPassSize = MAX_BOX_SIZES[blurPasses];
if (pSize > maxPassSize) {
pSize = maxPassSize;
srcScale = maxPassSize / iSize;
}
this.passSize = pSize;
// For a pixelSize that was less than maxPassSize, the following
// lines renormalize the un-transformed vector back into a unit
// vector in the proper direction and we absorbed its length
// into the pixelSize that we will apply for the box filter weights.
// If we clipped the pixelSize to maxPassSize, then it will not
// actually end up as a unit vector, but it will represent the
// proper sampling deltas for the indicated box size (which should
// be maxPassSize in that case).
samplevectors[0] /= srcScale;
samplevectors[1] /= srcScale;
// If we are still sampling by an axis aligned unit vector, then the
// optimized software filters can still do their "incremental sum"
// magic.
// REMIND: software loops could actually do an infinitely sized
// kernel with only memory requirements getting in the way, but
// the values being tested here are constrained by the limits of
// the hardware peers. It is not clear how to fix this since we
// have to choose how to proceed before we have enough information
// to know if the inputs will be cooperative enough to assume
// software limits, and then once we get here, we may have already
// constrained ourselves into a situation where we must use the
// hardware peers. Still, there may be more "fighting" we can do
// to hold on to compatibility with the software loops perhaps?
Rectangle srcSize = src.getUntransformedBounds();
if (pass == 0) {
this.swCompatible = nearOne(samplevectors[0], srcSize.width)
&& nearZero(samplevectors[1], srcSize.width);
} else {
this.swCompatible = nearZero(samplevectors[0], srcSize.height)
&& nearOne(samplevectors[1], srcSize.height);
}
}
Filterable f = src.getUntransformedImage();
samplevectors[0] /= f.getPhysicalWidth();
samplevectors[1] /= f.getPhysicalHeight();
return src;
}
@Override
public Rectangle getPassResultBounds(Rectangle srcdimension, Rectangle outputClip) {
// Note that the pass vector and the pass radius may be adjusted for
// a transformed input, but our output will be in the untransformed
// "filter" coordinate space so we need to use the "input" values that
// are in that same coordinate space.
// The srcdimension is padded by the amount of extra data we produce
// for this pass.
// The outputClip is padded by the amount of extra input data we will
// need for subsequent passes to do their work.
Rectangle ret = new Rectangle(srcdimension);
if (validatedPass == 0) {
ret.grow(getInputKernelSize(0) / 2, 0);
} else {
ret.grow(0, getInputKernelSize(1) / 2);
}
if (outputClip != null) {
if (validatedPass == 0) {
outputClip = new Rectangle(outputClip);
outputClip.grow(0, getInputKernelSize(1) / 2);
}
ret.intersectWith(outputClip);
}
return ret;
}
@Override
public float[] getPassVector() {
float xoff = samplevectors[0];
float yoff = samplevectors[1];
int ksize = getPassKernelSize();
int center = ksize / 2;
float ret[] = new float[4];
ret[0] = xoff;
ret[1] = yoff;
ret[2] = -center * xoff;
ret[3] = -center * yoff;
return ret;
}
@Override
public int getPassWeightsArrayLength() {
validateWeights();
return weights.limit() / 4;
}
@Override
public FloatBuffer getPassWeights() {
validateWeights();
weights.rewind();
return weights;
}
private void validateWeights() {
float pSize;
if (blurPasses == 0) {
pSize = 1.0f;
} else {
pSize = passSize;
// 1.0f is the minimum size and is a NOP (each pixel averaged
// over itself)
if (pSize < 1.0f) pSize = 1.0f;
}
float passSpread = (validatedPass == spreadPass) ? spread : 0f;
if (weights != null &&
weightsValidSize == pSize &&
weightsValidSpread == passSpread)
{
return;
}
// round klen up to a full pixel size and make sure it is odd so
// that we center the kernel around each pixel center (1.0 of the
// total size/weight is centered on the current pixel and then
// the remainder is split (size-1.0)/2 on each side.
// If the size is 2, then we don't want to average each pair of
// pixels together (weights: 0.5, 0.5), instead we want to take each
// pixel and average in half of each of its neighbors with it
// (weights: 0.25, 0.5, 0.25).
int klen = ((int) Math.ceil(pSize)) | 1;
int totalklen = klen;
for (int p = 1; p < blurPasses; p++) {
totalklen += klen - 1;
}
double ik[] = new double[totalklen];
for (int i = 0; i < klen; i++) {
ik[i] = 1.0;
}
// The sum of the ik[] array is now klen, but we want the sum to
// be size. The worst case difference will be less than 2.0 since
// the klen length is the ceil of the actual size possibly bumped up
// to an odd number. Thus it can have been bumped up by no more than
// 2.0. If there is an excess, we need to take half of it out of each
// of the two end weights (first and last).
double excess = klen - pSize;
if (excess > 0.0) {
// assert (excess * 0.5 < 1.0)
ik[0] = ik[klen-1] = 1.0 - excess * 0.5;
}
int filledklen = klen;
for (int p = 1; p < blurPasses; p++) {
filledklen += klen - 1;
int i = filledklen - 1;
while (i > klen) {
double sum = ik[i];
for (int k = 1; k < klen; k++) {
sum += ik[i-k];
}
ik[i--] = sum;
}
while (i > 0) {
double sum = ik[i];
for (int k = 0; k < i; k++) {
sum += ik[k];
}
ik[i--] = sum;
}
}
// assert (filledklen == totalklen == ik.length)
double sum = 0.0;
for (int i = 0; i < ik.length; i++) {
sum += ik[i];
}
// We need to apply the spread on only one pass
// Prefer pass1 if r1 is not trivial
// Otherwise use pass 0 so that it doesn't disappear
sum += (1.0 - sum) * passSpread;
if (weights == null) {
// peersize(MAX_KERNEL_SIZE) rounded up to the next multiple of 4
int maxbufsize = getPeerSize(MAX_KERNEL_SIZE);
maxbufsize = (maxbufsize + 3) & (~3);
weights = BufferUtil.newFloatBuffer(maxbufsize);
}
weights.clear();
for (int i = 0; i < ik.length; i++) {
weights.put((float) (ik[i] / sum));
}
int limit = getPeerSize(ik.length);
while (weights.position() < limit) {
weights.put(0f);
}
weights.limit(limit);
weights.rewind();
}
@Override
public int getInputKernelSize(int pass) {
float size = (pass == 0) ? inputSizeH : inputSizeV;
if (size < 1.0f) size = 1.0f;
int klen = ((int) Math.ceil(size)) | 1;
int totalklen = 1;
for (int p = 0; p < blurPasses; p++) {
totalklen += klen - 1;
}
return totalklen;
}
@Override
public int getPassKernelSize() {
float size = passSize;
if (size < 1.0f) size = 1.0f;
int klen = ((int) Math.ceil(size)) | 1;
int totalklen = 1;
for (int p = 0; p < blurPasses; p++) {
totalklen += klen - 1;
}
return totalklen;
}
@Override
public boolean isNop() {
if (isShadow) return false;
return (blurPasses == 0
|| (inputSizeH <= 1.0f && inputSizeV <= 1.0f));
}
@Override
public boolean isPassNop() {
if (isShadow && validatedPass == 1) return false;
return (blurPasses == 0 || (passSize) <= 1.0f);
}
}
| gpl-2.0 |
as-ideas/crowdsource | crowdsource-core/src/test/java/de/asideas/crowdsource/controller/usercontroller/GetCurrentUserControllerIT.java | 2584 | package de.asideas.crowdsource.controller.usercontroller;
import de.asideas.crowdsource.domain.model.prototypecampaign.FinancingRoundEntity;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.test.web.servlet.MvcResult;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class GetCurrentUserControllerIT extends AbstractUserControllerIT {
@Test
public void getCurrentUser_shouldReturnUserSuccessfully() throws Exception {
when(financingRoundRepository.findActive(any())).thenReturn(new FinancingRoundEntity());
MvcResult mvcResult = mockMvc.perform(get("/user/current")
.principal(new UsernamePasswordAuthenticationToken(ACTIVATED_USER_MAIL_ADDRESS, "somepassword"))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
assertThat(mvcResult.getResponse().getContentAsString(),
is("{\"email\":\"existing.and.activated@crowd.source.de\",\"roles\":[\"ROLE_USER\"],\"budget\":500,\"name\":\"Karl Ranseier\"}"));
}
@Test
public void getCurrentUser_shouldReturnNoBudgetIfTheFinancingRoundIsOver() throws Exception {
when(financingRoundRepository.findActive(any())).thenReturn(null);
MvcResult mvcResult = mockMvc.perform(get("/user/current")
.principal(new UsernamePasswordAuthenticationToken(ACTIVATED_USER_MAIL_ADDRESS, "somepassword"))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
assertThat(mvcResult.getResponse().getContentAsString(),
is("{\"email\":\"existing.and.activated@crowd.source.de\",\"roles\":[\"ROLE_USER\"],\"budget\":0,\"name\":\"Karl Ranseier\"}"));
}
@Test
public void getCurrentUser_shouldRespondWith401IfUserWasNotFound() throws Exception {
mockMvc.perform(get("/user/current")
.principal(new UsernamePasswordAuthenticationToken("unknown@user.com", "somepassword"))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isUnauthorized());
}
}
| gpl-2.0 |
Blaez/ZiosGram | TMessagesProj/src/main/java/org/telegram/ui/Components/PhotoCropView.java | 10471 | /*
* This is the source code of ZiosGram for Android v. 3.x.x
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2017.
*/
package org.blaez.ui.Components;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.RectF;
import android.os.Build;
import android.view.Gravity;
import android.widget.FrameLayout;
import org.blaez.ziosgram.AndroidUtilities;
import org.blaez.ui.Components.Crop.CropRotationWheel;
import org.blaez.ui.Components.Crop.CropView;
public class PhotoCropView extends FrameLayout {
public interface PhotoCropViewDelegate {
void needMoveImageTo(float x, float y, float s, boolean animated);
Bitmap getBitmap();
void onChange(boolean reset);
}
private boolean freeformCrop = true;
private float rectSizeX = 600;
private float rectSizeY = 600;
private int draggingState = 0;
private int orientation;
private float oldX = 0, oldY = 0;
private int bitmapWidth = 1, bitmapHeight = 1, bitmapX, bitmapY;
private float rectX = -1, rectY = -1;
private float bitmapGlobalScale = 1;
private float bitmapGlobalX = 0;
private float bitmapGlobalY = 0;
private PhotoCropViewDelegate delegate;
private Bitmap bitmapToEdit;
private boolean showOnSetBitmap;
private RectF animationStartValues;
private RectF animationEndValues;
private Runnable animationRunnable;
private CropView cropView;
private CropRotationWheel wheelView;
public PhotoCropView(Context context) {
super(context);
}
public void setBitmap(Bitmap bitmap, int rotation, boolean freeform) {
bitmapToEdit = bitmap;
rectSizeX = 600;
rectSizeY = 600;
draggingState = 0;
oldX = 0;
oldY = 0;
bitmapWidth = 1;
bitmapHeight = 1;
rectX = -1;
rectY = -1;
freeformCrop = freeform;
orientation = rotation;
requestLayout();
if (cropView == null) {
cropView = new CropView(getContext());
cropView.setListener(new CropView.CropViewListener() {
@Override
public void onChange(boolean reset) {
if (delegate != null) {
delegate.onChange(reset);
}
}
@Override
public void onAspectLock(boolean enabled) {
wheelView.setAspectLock(enabled);
}
});
cropView.setBottomPadding(AndroidUtilities.dp(64));
addView(cropView);
wheelView = new CropRotationWheel(getContext());
wheelView.setListener(new CropRotationWheel.RotationWheelListener() {
@Override
public void onStart() {
cropView.onRotationBegan();
}
@Override
public void onChange(float angle) {
cropView.setRotation(angle);
if (delegate != null) {
delegate.onChange(false);
}
}
@Override
public void onEnd(float angle) {
cropView.onRotationEnded();
}
@Override
public void aspectRatioPressed() {
cropView.showAspectRatioDialog();
}
@Override
public void rotate90Pressed() {
wheelView.reset();
cropView.rotate90Degrees();
}
});
addView(wheelView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER | Gravity.BOTTOM, 0, 0, 0, 0));
}
cropView.setVisibility(VISIBLE);
cropView.setBitmap(bitmap, rotation, freeform);
if (showOnSetBitmap) {
showOnSetBitmap = false;
cropView.show();
}
wheelView.setFreeform(freeform);
wheelView.reset();
}
public void setOrientation(int rotation) {
orientation = rotation;
rectX = -1;
rectY = -1;
rectSizeX = 600;
rectSizeY = 600;
delegate.needMoveImageTo(0, 0, 1, false);
requestLayout();
}
public boolean isReady() {
return cropView.isReady();
}
public void reset() {
wheelView.reset();
cropView.reset();
}
public void onAppear() {
if (cropView != null) {
cropView.willShow();
}
}
public void onAppeared() {
if (cropView != null) {
cropView.show();
} else {
showOnSetBitmap = true;
}
}
public void onDisappear() {
cropView.hide();
}
public float getRectX() {
return cropView.getCropLeft() - AndroidUtilities.dp(14);
}
public float getRectY() {
return cropView.getCropTop() - AndroidUtilities.dp(14) - (Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0);
}
public float getRectSizeX() {
return cropView.getCropWidth();
}
public float getRectSizeY() {
return cropView.getCropHeight();
}
public float getBitmapX() {
return bitmapX - AndroidUtilities.dp(14);
}
public float getBitmapY() {
float additionalY = (Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0);
return bitmapY - AndroidUtilities.dp(14) - additionalY;
}
public float getLimitX() {
return rectX - Math.max(0, (float) Math.ceil((getWidth() - bitmapWidth * bitmapGlobalScale) / 2));
}
public float getLimitY() {
float additionalY = (Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0);
return rectY - Math.max(0, (float) Math.ceil((getHeight() - bitmapHeight * bitmapGlobalScale + additionalY) / 2));
}
public float getLimitWidth() {
return getWidth() - AndroidUtilities.dp(14) - rectX - (int) Math.max(0, Math.ceil((getWidth() - AndroidUtilities.dp(28) - bitmapWidth * bitmapGlobalScale) / 2)) - rectSizeX;
}
public float getLimitHeight() {
float additionalY = (Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0);
return getHeight() - AndroidUtilities.dp(14) - additionalY - rectY - (int) Math.max(0, Math.ceil((getHeight() - AndroidUtilities.dp(28) - bitmapHeight * bitmapGlobalScale - additionalY) / 2)) - rectSizeY;
}
public Bitmap getBitmap() {
if (cropView != null) {
return cropView.getResult();
}
return null;
}
public void setBitmapParams(float scale, float x, float y) {
bitmapGlobalScale = scale;
bitmapGlobalX = x;
bitmapGlobalY = y;
}
public void startAnimationRunnable() {
if (animationRunnable != null) {
return;
}
animationRunnable = new Runnable() {
@Override
public void run() {
if (animationRunnable == this) {
animationRunnable = null;
moveToFill(true);
}
}
};
AndroidUtilities.runOnUIThread(animationRunnable, 1500);
}
public void cancelAnimationRunnable() {
if (animationRunnable != null) {
AndroidUtilities.cancelRunOnUIThread(animationRunnable);
animationRunnable = null;
animationStartValues = null;
animationEndValues = null;
}
}
public void setAnimationProgress(float animationProgress) {
if (animationStartValues != null) {
if (animationProgress == 1) {
rectX = animationEndValues.left;
rectY = animationEndValues.top;
rectSizeX = animationEndValues.right;
rectSizeY = animationEndValues.bottom;
animationStartValues = null;
animationEndValues = null;
} else {
rectX = animationStartValues.left + (animationEndValues.left - animationStartValues.left) * animationProgress;
rectY = animationStartValues.top + (animationEndValues.top - animationStartValues.top) * animationProgress;
rectSizeX = animationStartValues.right + (animationEndValues.right - animationStartValues.right) * animationProgress;
rectSizeY = animationStartValues.bottom + (animationEndValues.bottom - animationStartValues.bottom) * animationProgress;
}
invalidate();
}
}
public void moveToFill(boolean animated) {
float scaleToX = bitmapWidth / rectSizeX;
float scaleToY = bitmapHeight / rectSizeY;
float scaleTo = scaleToX > scaleToY ? scaleToY : scaleToX;
if (scaleTo > 1 && scaleTo * bitmapGlobalScale > 3) {
scaleTo = 3 / bitmapGlobalScale;
} else if (scaleTo < 1 && scaleTo * bitmapGlobalScale < 1) {
scaleTo = 1 / bitmapGlobalScale;
}
float newSizeX = rectSizeX * scaleTo;
float newSizeY = rectSizeY * scaleTo;
float additionalY = (Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0);
float newX = (getWidth() - newSizeX) / 2;
float newY = (getHeight() - newSizeY + additionalY) / 2;
animationStartValues = new RectF(rectX, rectY, rectSizeX, rectSizeY);
animationEndValues = new RectF(newX, newY, newSizeX, newSizeY);
float newBitmapGlobalX = newX + getWidth() / 2 * (scaleTo - 1) + (bitmapGlobalX - rectX) * scaleTo;
float newBitmapGlobalY = newY + (getHeight() + additionalY) / 2 * (scaleTo - 1) + (bitmapGlobalY - rectY) * scaleTo;
delegate.needMoveImageTo(newBitmapGlobalX, newBitmapGlobalY, bitmapGlobalScale * scaleTo, animated);
}
public void setDelegate(PhotoCropViewDelegate delegate) {
this.delegate = delegate;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
Bitmap newBitmap = delegate.getBitmap();
if (newBitmap != null) {
bitmapToEdit = newBitmap;
}
if (cropView != null) {
cropView.updateLayout();
}
}
}
| gpl-2.0 |
titokone/titotrainer | tests/src/fi/helsinki/cs/titotrainer/framework/controller/AbstractControllerTest.java | 3139 | package fi.helsinki.cs.titotrainer.framework.controller;
import static org.junit.Assert.*;
import java.util.Collection;
import java.util.LinkedList;
import org.hibernate.Session;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import fi.helsinki.cs.titotrainer.app.request.TitoRequest;
import fi.helsinki.cs.titotrainer.app.request.TitoRequestAttribs;
import fi.helsinki.cs.titotrainer.framework.request.RequestInvalidity;
import fi.helsinki.cs.titotrainer.framework.response.Response;
public class AbstractControllerTest {
public static class TestRequest extends TitoRequest {
private final boolean valid;
public TestRequest(boolean valid) {
this.valid = valid;
}
@Override
public Collection<RequestInvalidity> validate() {
Collection<RequestInvalidity> ret = new LinkedList<RequestInvalidity>();
if (!valid)
ret.add(new RequestInvalidity("Testing invalid request"));
return ret;
}
@Override
public TitoRequestAttribs getAttribs() {
return Mockito.mock(TitoRequestAttribs.class);
}
}
private static class TestController extends AbstractController<TestRequest> {
public int handleValidCalls = 0;
public int handleInvalidCalls = 0;
@Override
protected Response handleValid(TestRequest req, Session hs) throws Exception {
++this.handleValidCalls;
return new Response() {
@Override
public int getStatusCode() {
return 200;
}
};
}
@Override
protected Response handleInvalid(TestRequest req, Session hs, Collection<RequestInvalidity> invalidities) throws Exception {
++this.handleInvalidCalls;
return super.handleInvalid(req, hs, invalidities);
}
@Override
protected boolean useTransaction() {
return false;
}
@Override
public Class<TestRequest> getRequestType() {
return TestRequest.class;
}
}
private TestController testController;
@Before
public void setUp() {
this.testController = new TestController();
}
@Test
public void shouldCallHandleValidIfRequestIsValid() throws Exception {
TestRequest tr = new TestRequest(true);
this.testController.handle(tr);
assertEquals(1, this.testController.handleValidCalls);
}
@Test
public void shouldCallHandleInvalidIfRequestIsNotValid() throws Exception {
TestRequest tr = new TestRequest(false);
this.testController.handle(tr);
assertEquals(1, this.testController.handleInvalidCalls);
}
@Test
public void handleInvalidShouldReturn404ByDefault() throws Exception {
TestRequest tr = new TestRequest(false);
assertEquals(404, this.testController.handleInvalid(tr, null, tr.validate()).getStatusCode());
}
}
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest20125.java | 1912 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark 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, version 2.
*
* The Benchmark 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
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest20125")
public class BenchmarkTest20125 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = request.getQueryString();
String bar = doSomething(param);
double stuff = new java.util.Random().nextGaussian();
response.getWriter().println("Weak Randomness Test java.util.Random.nextGaussian() executed");
} // end doPost
private static String doSomething(String param) throws ServletException, IOException {
String bar = param.split(" ")[0];
return bar;
}
}
| gpl-2.0 |
rogiermars/mt4j-core | src/org/mt4j/util/font/fontFactories/AngelCodeFont.java | 6776 | package org.mt4j.util.font.fontFactories;
import java.util.HashMap;
import java.util.List;
import org.mt4j.util.MTColor;
import org.mt4j.util.font.FontManager;
import org.mt4j.util.font.IFont;
import org.mt4j.util.font.IFontCharacter;
import org.mt4j.util.font.ITextureFont;
import org.mt4j.util.logging.ILogger;
import org.mt4j.util.logging.MTLoggerFactory;
import org.mt4j.util.opengl.GL10;
import org.mt4j.util.opengl.GLTexture;
import processing.core.PImage;
public class AngelCodeFont implements IFont, ITextureFont {
private static final ILogger logger = MTLoggerFactory.getLogger(AngelCodeFont.class.getName());
static{
// logger.setLevel(ILogger.ERROR);
// logger.setLevel(ILogger.WARN);
logger.setLevel(ILogger.DEBUG);
}
private AngelCodeFontCharacter[] characters;
/** The default horizontal adv x. */
private int defaultHorizontalAdvX;
/** The font family. */
private String fontFamily;
/** The original font size. */
private int originalFontSize;
/** The font max ascent. */
private int fontMaxAscent;
/** The font max descent. */
private int fontMaxDescent;
/** The units per em. */
private int unitsPerEM;
/** The font file name. */
private String fontFileName;
/** The uni code to char. */
private HashMap<String, AngelCodeFontCharacter> uniCodeToChar;
/** The char name to char. */
private HashMap<String, AngelCodeFontCharacter> charNameToChar;
/** The fill color. */
private MTColor fillColor;
// /** The stroke color. */
// private MTColor strokeColor;
private boolean antiAliased;
private PImage fontImage;
private int hieroPadding;
//TODO make class AbstractFont with destroy method, getters, setters
public AngelCodeFont(PImage fontImage, AngelCodeFontCharacter[] characters, int defaultHorizontalAdvX, String fontFileName, String fontFamily, int fontMaxAscent, int fontMaxDescent, int unitsPerEm, int originalFontSize,
MTColor fillColor,
boolean antiAliased, int hieroPadding
) {
this.fontImage = fontImage;
this.characters = characters;
this.defaultHorizontalAdvX = defaultHorizontalAdvX;
this.fontFileName = fontFileName;
this.fontFamily = fontFamily;
this.originalFontSize = originalFontSize;
this.fillColor = fillColor;
this.antiAliased = antiAliased;
this.fontMaxAscent = fontMaxAscent;
this.fontMaxDescent = fontMaxDescent;
this.unitsPerEM = unitsPerEm;
this.hieroPadding = hieroPadding;
//Put characters in hashmaps for quick access
uniCodeToChar = new HashMap<String, AngelCodeFontCharacter>();
charNameToChar = new HashMap<String, AngelCodeFontCharacter>();
for (AngelCodeFontCharacter currentChar : characters) {
uniCodeToChar.put(currentChar.getUnicode(), currentChar);
charNameToChar.put(currentChar.getName(), currentChar);
}
}
public IFontCharacter getFontCharacterByName(String characterName){
IFontCharacter returnChar = charNameToChar.get(characterName);
if (returnChar == null)
logger.warn("Font couldnt load charactername: " + characterName);
return returnChar;
}
@Override
public IFontCharacter getFontCharacterByUnicode(String unicode) {
IFontCharacter returnChar = uniCodeToChar.get(unicode);
if (returnChar == null){
logger.warn("Font couldnt load characterunicode: '" + unicode + "'");
}
return returnChar;
}
@Override
public IFontCharacter[] getCharacters() {
return this.characters;
}
@Override
public String getFontFamily() {
return this.fontFamily;
}
@Override
public int getDefaultHorizontalAdvX() {
return this.defaultHorizontalAdvX;
}
@Override
public int getFontMaxAscent() {
return this.fontMaxAscent;
}
@Override
public int getFontMaxDescent() {
return this.fontMaxDescent;
}
@Override
public int getFontAbsoluteHeight() {
return ((Math.abs(this.getFontMaxAscent())) + (Math.abs(this.getFontMaxDescent())));
}
@Override
public int getUnitsPerEM() {
return this.unitsPerEM;
}
/* (non-Javadoc)
* @see org.mt4j.components.visibleComponents.font.IFont#getFontFileName()
*/
public String getFontFileName() {
return this.fontFileName;
}
/* (non-Javadoc)
* @see org.mt4j.components.visibleComponents.font.IFont#getOriginalFontSize()
*/
public int getOriginalFontSize() {
return this.originalFontSize;
}
/* (non-Javadoc)
* @see org.mt4j.components.visibleComponents.font.IFont#getFillColor()
*/
public MTColor getFillColor() {
return fillColor;
}
public void setFillColor(MTColor color){
this.fillColor = color;
}
/* (non-Javadoc)
* @see org.mt4j.components.visibleComponents.font.IFont#isAntiAliased()
*/
public boolean isAntiAliased() {
return this.antiAliased;
}
/* (non-Javadoc)
* @see org.mt4j.components.visibleComponents.font.IFont#destroy()
*/
public void destroy() {
IFontCharacter[] characters = this.getCharacters();
for (IFontCharacter iFontCharacter : characters) {
iFontCharacter.destroy();
}
FontManager.getInstance().removeFromCache(this);
}
@Override
public void beginBatchRenderGL(GL10 gl, IFont font) {
MTColor fillColor = font.getFillColor();
gl.glColor4f(fillColor.getR()/255f, fillColor.getG()/255f, fillColor.getB()/255f, fillColor.getAlpha()/255f);
GLTexture tex = (GLTexture)this.fontImage;
int textureTarget = tex.getTextureTarget();
gl.glEnable(textureTarget);
//Enable Pointers, set vertex array pointer
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glBindTexture(textureTarget, tex.getTextureID());
}
@Override
public void endBatchRenderGL(GL10 gl, IFont font) {
GLTexture tex = (GLTexture)this.fontImage;
int textureTarget = tex.getTextureTarget();
gl.glBindTexture(textureTarget, 0);//Unbind texture
gl.glDisable(textureTarget);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
public PImage getFontImage() {
return fontImage;
}
public AngelCodeFont getCopy(){
return new AngelCodeFont(fontImage, characters, defaultHorizontalAdvX, fontFileName, fontFamily, fontMaxAscent , fontMaxDescent , unitsPerEM, originalFontSize, fillColor, /*bf.getStrokeColor(),*/ antiAliased, getHieroPadding());
}
public boolean isEqual(IFont font){
if (font instanceof AngelCodeFont) {
AngelCodeFont af = (AngelCodeFont) font;
if (
font.getFontFileName().equalsIgnoreCase(getFontFileName())
&&
font.getOriginalFontSize() == getOriginalFontSize()
&&
font.isAntiAliased() == antiAliased
&&
af.getHieroPadding() == getHieroPadding()
){
return true;
}
}
return false;
}
public int getHieroPadding() {
return hieroPadding;
}
}
| gpl-2.0 |
LarsDenBakker/LBAccounting | src/main/java/nl/larsdenbakker/accounting/product/Product.java | 925 | package nl.larsdenbakker.accounting.product;
import java.util.UUID;
import nl.larsdenbakker.app.Module;
import nl.larsdenbakker.conversion.ConversionModule;
import nl.larsdenbakker.property.PropertyHolder;
import nl.larsdenbakker.storage.Storage;
/**
*
* @author Lars den Bakker <larsdenbakker at gmail.com>
*/
public class Product extends PropertyHolder<UUID> {
public final ProductProperties PROPERTIES;
public Product(Module parentModule, ConversionModule conversionHandler, Storage storage, ProductProperties PROPERTIES) {
super(parentModule, conversionHandler, storage);
this.PROPERTIES = PROPERTIES;
}
@Override
public ProductProperties getProperties() {
return PROPERTIES;
}
@Override
public UUID getKey() {
return getPropertyValue(PROPERTIES.UUID);
}
@Override
public String getDescription() {
return getPropertyValue(PROPERTIES.NAME);
}
}
| gpl-2.0 |
zenovalle/tn5250j | src/org/tn5250j/framework/transport/SSL/SSLImplementation.java | 6593 | package org.tn5250j.framework.transport.SSL;
/*
* @(#)SSLImplementation.java
* @author Stephen M. Kennedy
*
* Copyright: Copyright (c) 2001
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, 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 software; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.Socket;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import javax.swing.JOptionPane;
import org.tn5250j.GlobalConfigure;
import org.tn5250j.framework.transport.SSLInterface;
import org.tn5250j.tools.logging.TN5250jLogFactory;
import org.tn5250j.tools.logging.TN5250jLogger;
/**
* <p>
* This class implements the SSLInterface and is used to create SSL socket
* instances.
* </p>
*
* @author Stephen M. Kennedy <skennedy@tenthpowertech.com>
*
*/
public class SSLImplementation implements SSLInterface, X509TrustManager {
SSLContext sslContext = null;
KeyStore userks = null;
private String userKsPath;
private char[] userksPassword = "changeit".toCharArray();
KeyManagerFactory userkmf = null;
TrustManagerFactory usertmf = null;
TrustManager[] userTrustManagers = null;
X509Certificate[] acceptedIssuers;
TN5250jLogger logger;
public SSLImplementation() {
logger = TN5250jLogFactory.getLogger(getClass());
}
public void init(String sslType) {
try {
logger.debug("Initializing User KeyStore");
userKsPath = System.getProperty("user.home") + File.separator
+ GlobalConfigure.TN5250J_FOLDER + File.separator + "keystore";
File userKsFile = new File(userKsPath);
userks = KeyStore.getInstance(KeyStore.getDefaultType());
userks.load(userKsFile.exists() ? new FileInputStream(userKsFile)
: null, userksPassword);
logger.debug("Initializing User Key Manager Factory");
userkmf = KeyManagerFactory.getInstance(KeyManagerFactory
.getDefaultAlgorithm());
userkmf.init(userks, userksPassword);
logger.debug("Initializing User Trust Manager Factory");
usertmf = TrustManagerFactory.getInstance(TrustManagerFactory
.getDefaultAlgorithm());
usertmf.init(userks);
userTrustManagers = usertmf.getTrustManagers();
logger.debug("Initializing SSL Context");
sslContext = SSLContext.getInstance(sslType);
sslContext.init(userkmf.getKeyManagers(), new TrustManager[] {this}, null);
} catch (Exception ex) {
logger.error("Error initializing SSL [" + ex.getMessage() + "]");
}
}
public Socket createSSLSocket(String destination, int port) {
if (sslContext == null)
throw new IllegalStateException("SSL Context Not Initialized");
SSLSocket socket = null;
try {
socket = (SSLSocket) sslContext.getSocketFactory().createSocket(
destination, port);
} catch (Exception e) {
logger.error("Error creating ssl socket [" + e.getMessage() + "]");
}
return socket;
}
// X509TrustManager Methods
/*
* (non-Javadoc)
*
* @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
*/
public X509Certificate[] getAcceptedIssuers() {
return acceptedIssuers;
}
/*
* (non-Javadoc)
*
* @see
* javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert.
* X509Certificate[], java.lang.String)
*/
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
throw new SecurityException("checkClientTrusted unsupported");
}
/*
* (non-Javadoc)
*
* @see
* javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.
* X509Certificate[], java.lang.String)
*/
public void checkServerTrusted(X509Certificate[] chain, String type)
throws CertificateException {
try {
for (int i = 0; i < userTrustManagers.length; i++) {
if (userTrustManagers[i] instanceof X509TrustManager) {
X509TrustManager trustManager = (X509TrustManager) userTrustManagers[i];
X509Certificate[] calist = trustManager
.getAcceptedIssuers();
if (calist.length > 0) {
trustManager.checkServerTrusted(chain, type);
} else {
throw new CertificateException(
"Empty list of accepted issuers (a.k.a. root CA list).");
}
}
}
return;
} catch (CertificateException ce) {
X509Certificate cert = chain[0];
String certInfo = "Version: " + cert.getVersion() + "\n";
certInfo = certInfo.concat("Serial Number: "
+ cert.getSerialNumber() + "\n");
certInfo = certInfo.concat("Signature Algorithm: "
+ cert.getSigAlgName() + "\n");
certInfo = certInfo.concat("Issuer: "
+ cert.getIssuerDN().getName() + "\n");
certInfo = certInfo.concat("Valid From: " + cert.getNotBefore()
+ "\n");
certInfo = certInfo
.concat("Valid To: " + cert.getNotAfter() + "\n");
certInfo = certInfo.concat("Subject DN: "
+ cert.getSubjectDN().getName() + "\n");
certInfo = certInfo.concat("Public Key: "
+ cert.getPublicKey().getFormat() + "\n");
int accept = JOptionPane
.showConfirmDialog(null, certInfo, "Unknown Certificate - Do you accept it?",
javax.swing.JOptionPane.YES_NO_OPTION);
if (accept != JOptionPane.YES_OPTION) {
throw new java.security.cert.CertificateException(
"Certificate Rejected");
}
int save = JOptionPane.showConfirmDialog(null,
"Remember this certificate?", "Save Certificate",
javax.swing.JOptionPane.YES_NO_OPTION);
if (save == JOptionPane.YES_OPTION) {
try {
userks.setCertificateEntry(cert.getSubjectDN().getName(),
cert);
userks.store(new FileOutputStream(userKsPath),
userksPassword);
} catch (Exception e) {
logger.error("Error saving certificate [" + e.getMessage()
+ "]");
e.printStackTrace();
}
}
}
}
}
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest16023.java | 2747 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark 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, version 2.
*
* The Benchmark 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
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest16023")
public class BenchmarkTest16023 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = "";
java.util.Enumeration<String> headers = request.getHeaders("foo");
if (headers.hasMoreElements()) {
param = headers.nextElement(); // just grab first element
}
String bar = doSomething(param);
try {
javax.crypto.Cipher c = javax.crypto.Cipher.getInstance("DES/CBC/PKCS5Padding");
} catch (java.security.NoSuchAlgorithmException e) {
System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String) Test Case");
throw new ServletException(e);
} catch (javax.crypto.NoSuchPaddingException e) {
System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String) Test Case");
throw new ServletException(e);
}
response.getWriter().println("Crypto Test javax.crypto.Cipher.getInstance(java.lang.String) executed");
} // end doPost
private static String doSomething(String param) throws ServletException, IOException {
java.util.List<String> valuesList = new java.util.ArrayList<String>( );
valuesList.add("safe");
valuesList.add( param );
valuesList.add( "moresafe" );
valuesList.remove(0); // remove the 1st safe value
String bar = valuesList.get(0); // get the param value
return bar;
}
}
| gpl-2.0 |
juanger/jaguar | src/jaguar/util/Debug.java | 2160 | /**
** <Debug.java> -- To send debug messages
**
** Copyright (C) 2002 by Ivan Hernández Serrano
**
** This file is part of JAGUAR
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the GNU General Public License
** as published by the Free Software Foundation; either version 2
** of the License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
**
** Author: Ivan Hernández Serrano <ivanx@users.sourceforge.net>
**
**/
/*
** <Debug.java> ---- Para Debugear
**
** Copyright (C) 2000 by Free Software Foundation, Inc.
**
** Author: <ivanx@localhost.localdomain>
** Commentary:
*/
package jaguar.util;
import java.util.Hashtable;
import java.util.Enumeration;
public class Debug{
public static final int DEBUG_ON = 1;
public static final int DEBUG_OFF = 2;
static public void println(String str, int debug_level){
if(debug_level == DEBUG_ON)
System.err.println(str);
}
static public void println(String str){
println(str,DEBUG_ON);
}
static public void print(String str, int debug_level){
if(debug_level == DEBUG_ON)
System.err.print(str);
}
static public void print(String str){
print(str,DEBUG_ON);
}
static public void println(String s, Hashtable d, int debug_level){
if(debug_level == DEBUG_OFF)
return;
System.err.println(s);
for (Enumeration e = d.keys() ; e.hasMoreElements() ;) {
System.err.println(e.nextElement());
}
System.err.println("");
}
static public void println(String s, Hashtable d){
println( s, d, DEBUG_ON);
}
}
/* Debug.java ends here */
| gpl-2.0 |
nologic/nabs | client/trunk/shared/libraries/je-3.2.44/src/com/sleepycat/collections/CurrentTransaction.java | 15596 | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2000,2007 Oracle. All rights reserved.
*
* $Id: CurrentTransaction.java,v 1.46.2.2 2007/04/12 16:13:16 mark Exp $
*/
package com.sleepycat.collections;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.WeakHashMap;
import com.sleepycat.compat.DbCompat;
import com.sleepycat.je.Cursor;
import com.sleepycat.je.CursorConfig;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.Transaction;
import com.sleepycat.je.TransactionConfig;
import com.sleepycat.util.RuntimeExceptionWrapper;
/**
* Provides access to the current transaction for the current thread within the
* context of a Berkeley DB environment. This class provides explicit
* transaction control beyond that provided by the {@link TransactionRunner}
* class. However, both methods of transaction control manage per-thread
* transactions.
*
* @author Mark Hayes
*/
public class CurrentTransaction {
/* For internal use, this class doubles as an Environment wrapper. */
private static WeakHashMap envMap = new WeakHashMap();
private LockMode writeLockMode;
private boolean cdbMode;
private boolean txnMode;
private boolean lockingMode;
private Environment env;
private ThreadLocal localTrans = new ThreadLocal();
private ThreadLocal localCdbCursors;
/**
* Gets the CurrentTransaction accessor for a specified Berkeley DB
* environment. This method always returns the same reference when called
* more than once with the same environment parameter.
*
* @param env is an open Berkeley DB environment.
*
* @return the CurrentTransaction accessor for the given environment, or
* null if the environment is not transactional.
*/
public static CurrentTransaction getInstance(Environment env) {
CurrentTransaction currentTxn = getInstanceInternal(env);
return currentTxn.isTxnMode() ? currentTxn : null;
}
/**
* Gets the CurrentTransaction accessor for a specified Berkeley DB
* environment. Unlike getInstance(), this method never returns null.
*
* @param env is an open Berkeley DB environment.
*/
static CurrentTransaction getInstanceInternal(Environment env) {
synchronized (envMap) {
CurrentTransaction myEnv = null;
WeakReference myEnvRef = (WeakReference) envMap.get(env);
if (myEnvRef != null) {
myEnv = (CurrentTransaction) myEnvRef.get();
}
if (myEnv == null) {
myEnv = new CurrentTransaction(env);
envMap.put(env, new WeakReference(myEnv));
}
return myEnv;
}
}
private CurrentTransaction(Environment env) {
this.env = env;
try {
EnvironmentConfig config = env.getConfig();
txnMode = config.getTransactional();
lockingMode = DbCompat.getInitializeLocking(config);
if (txnMode || lockingMode) {
writeLockMode = LockMode.RMW;
} else {
writeLockMode = LockMode.DEFAULT;
}
cdbMode = DbCompat.getInitializeCDB(config);
if (cdbMode) {
localCdbCursors = new ThreadLocal();
}
} catch (DatabaseException e) {
throw new RuntimeExceptionWrapper(e);
}
}
/**
* Returns whether environment is configured for locking.
*/
final boolean isLockingMode() {
return lockingMode;
}
/**
* Returns whether this is a transactional environment.
*/
final boolean isTxnMode() {
return txnMode;
}
/**
* Returns whether this is a Concurrent Data Store environment.
*/
final boolean isCdbMode() {
return cdbMode;
}
/**
* Return the LockMode.RMW or null, depending on whether locking is
* enabled. LockMode.RMW will cause an error if passed when locking
* is not enabled. Locking is enabled if locking or transactions were
* specified for this environment.
*/
final LockMode getWriteLockMode() {
return writeLockMode;
}
/**
* Returns the underlying Berkeley DB environment.
*/
public final Environment getEnvironment() {
return env;
}
/**
* Returns the transaction associated with the current thread for this
* environment, or null if no transaction is active.
*/
public final Transaction getTransaction() {
Trans trans = (Trans) localTrans.get();
return (trans != null) ? trans.txn : null;
}
/**
* Returns whether auto-commit may be performed by the collections API.
* True is returned if no collections API transaction is currently active,
* and no XA transaction is currently active.
*/
boolean isAutoCommitAllowed()
throws DatabaseException {
return getTransaction() == null &&
DbCompat.getThreadTransaction(env) == null;
}
/**
* Begins a new transaction for this environment and associates it with
* the current thread. If a transaction is already active for this
* environment and thread, a nested transaction will be created.
*
* @param config the transaction configuration used for calling
* {@link Environment#beginTransaction}, or null to use the default
* configuration.
*
* @return the new transaction.
*
* @throws DatabaseException if the transaction cannot be started, in which
* case any existing transaction is not affected.
*
* @throws IllegalStateException if a transaction is already active and
* nested transactions are not supported by the environment.
*/
public final Transaction beginTransaction(TransactionConfig config)
throws DatabaseException {
Trans trans = (Trans) localTrans.get();
if (trans != null) {
if (trans.txn != null) {
if (!DbCompat.NESTED_TRANSACTIONS) {
throw new IllegalStateException(
"Nested transactions are not supported");
}
Transaction parentTxn = trans.txn;
trans = new Trans(trans, config);
trans.txn = env.beginTransaction(parentTxn, config);
localTrans.set(trans);
} else {
trans.txn = env.beginTransaction(null, config);
trans.config = config;
}
} else {
trans = new Trans(null, config);
trans.txn = env.beginTransaction(null, config);
localTrans.set(trans);
}
return trans.txn;
}
/**
* Commits the transaction that is active for the current thread for this
* environment and makes the parent transaction (if any) the current
* transaction.
*
* @return the parent transaction or null if the committed transaction was
* not nested.
*
* @throws DatabaseException if an error occurs committing the transaction.
* The transaction will still be closed and the parent transaction will
* become the current transaction.
*
* @throws IllegalStateException if no transaction is active for the
* current thread for this environment.
*/
public final Transaction commitTransaction()
throws DatabaseException, IllegalStateException {
Trans trans = (Trans) localTrans.get();
if (trans != null && trans.txn != null) {
Transaction parent = closeTxn(trans);
trans.txn.commit();
return parent;
} else {
throw new IllegalStateException("No transaction is active");
}
}
/**
* Aborts the transaction that is active for the current thread for this
* environment and makes the parent transaction (if any) the current
* transaction.
*
* @return the parent transaction or null if the aborted transaction was
* not nested.
*
* @throws DatabaseException if an error occurs aborting the transaction.
* The transaction will still be closed and the parent transaction will
* become the current transaction.
*
* @throws IllegalStateException if no transaction is active for the
* current thread for this environment.
*/
public final Transaction abortTransaction()
throws DatabaseException, IllegalStateException {
Trans trans = (Trans) localTrans.get();
if (trans != null && trans.txn != null) {
Transaction parent = closeTxn(trans);
trans.txn.abort();
return parent;
} else {
throw new IllegalStateException("No transaction is active");
}
}
/**
* Returns whether the current transaction is a readUncommitted
* transaction.
*/
final boolean isReadUncommitted() {
Trans trans = (Trans) localTrans.get();
if (trans != null && trans.config != null) {
return trans.config.getReadUncommitted();
} else {
return false;
}
}
private Transaction closeTxn(Trans trans) {
localTrans.set(trans.parent);
return (trans.parent != null) ? trans.parent.txn : null;
}
private static class Trans {
private Trans parent;
private Transaction txn;
private TransactionConfig config;
private Trans(Trans parent, TransactionConfig config) {
this.parent = parent;
this.config = config;
}
}
/**
* Opens a cursor for a given database, dup'ing an existing CDB cursor if
* one is open for the current thread.
*/
Cursor openCursor(Database db, CursorConfig cursorConfig,
boolean writeCursor, Transaction txn)
throws DatabaseException {
if (cdbMode) {
CdbCursors cdbCursors = null;
WeakHashMap cdbCursorsMap = (WeakHashMap) localCdbCursors.get();
if (cdbCursorsMap == null) {
cdbCursorsMap = new WeakHashMap();
localCdbCursors.set(cdbCursorsMap);
} else {
cdbCursors = (CdbCursors) cdbCursorsMap.get(db);
}
if (cdbCursors == null) {
cdbCursors = new CdbCursors();
cdbCursorsMap.put(db, cdbCursors);
}
/*
* In CDB mode the cursorConfig specified by the user is ignored
* and only the writeCursor parameter is honored. This is the only
* meaningful cursor attribute for CDB, and here we count on
* writeCursor flag being set correctly by the caller.
*/
List cursors;
CursorConfig cdbConfig;
if (writeCursor) {
if (cdbCursors.readCursors.size() > 0) {
/*
* Although CDB allows opening a write cursor when a read
* cursor is open, a self-deadlock will occur if a write is
* attempted for a record that is read-locked; we should
* avoid self-deadlocks at all costs
*/
throw new IllegalStateException(
"cannot open CDB write cursor when read cursor is open");
}
cursors = cdbCursors.writeCursors;
cdbConfig = new CursorConfig();
DbCompat.setWriteCursor(cdbConfig, true);
} else {
cursors = cdbCursors.readCursors;
cdbConfig = null;
}
Cursor cursor;
if (cursors.size() > 0) {
Cursor other = ((Cursor) cursors.get(0));
cursor = other.dup(false);
} else {
cursor = db.openCursor(null, cdbConfig);
}
cursors.add(cursor);
return cursor;
} else {
return db.openCursor(txn, cursorConfig);
}
}
/**
* Duplicates a cursor for a given database.
*
* @param writeCursor true to open a write cursor in a CDB environment, and
* ignored for other environments.
*
* @param samePosition is passed through to Cursor.dup().
*
* @return the open cursor.
*
* @throws DatabaseException if a database problem occurs.
*/
Cursor dupCursor(Cursor cursor, boolean writeCursor, boolean samePosition)
throws DatabaseException {
if (cdbMode) {
WeakHashMap cdbCursorsMap = (WeakHashMap) localCdbCursors.get();
if (cdbCursorsMap != null) {
Database db = cursor.getDatabase();
CdbCursors cdbCursors = (CdbCursors) cdbCursorsMap.get(db);
if (cdbCursors != null) {
List cursors = writeCursor ? cdbCursors.writeCursors
: cdbCursors.readCursors;
if (cursors.contains(cursor)) {
Cursor newCursor = cursor.dup(samePosition);
cursors.add(newCursor);
return newCursor;
}
}
}
throw new IllegalStateException("cursor to dup not tracked");
} else {
return cursor.dup(samePosition);
}
}
/**
* Closes a cursor.
*
* @param cursor the cursor to close.
*
* @throws DatabaseException if a database problem occurs.
*/
void closeCursor(Cursor cursor)
throws DatabaseException {
if (cursor == null) {
return;
}
if (cdbMode) {
WeakHashMap cdbCursorsMap = (WeakHashMap) localCdbCursors.get();
if (cdbCursorsMap != null) {
Database db = cursor.getDatabase();
CdbCursors cdbCursors = (CdbCursors) cdbCursorsMap.get(db);
if (cdbCursors != null) {
if (cdbCursors.readCursors.remove(cursor) ||
cdbCursors.writeCursors.remove(cursor)) {
cursor.close();
return;
}
}
}
throw new IllegalStateException(
"closing CDB cursor that was not known to be open");
} else {
cursor.close();
}
}
/**
* Returns true if a CDB cursor is open and therefore a Database write
* operation should not be attempted since a self-deadlock may result.
*/
boolean isCDBCursorOpen(Database db)
throws DatabaseException {
if (cdbMode) {
WeakHashMap cdbCursorsMap = (WeakHashMap) localCdbCursors.get();
if (cdbCursorsMap != null) {
CdbCursors cdbCursors = (CdbCursors) cdbCursorsMap.get(db);
if (cdbCursors != null &&
(cdbCursors.readCursors.size() > 0 ||
cdbCursors.writeCursors.size() > 0)) {
return true;
}
}
}
return false;
}
static final class CdbCursors {
List writeCursors = new ArrayList();
List readCursors = new ArrayList();
}
}
| gpl-2.0 |
FilipStamenkovic/SenseWatcher | app/src/main/java/nos/elfak/rs/sensewatcher/MainActivity.java | 1825 | package nos.elfak.rs.sensewatcher;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity
{
Communication communication;
public static ArrayList<AnomalyData> anomalies = new ArrayList<>();
boolean listening = false;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
communication = Communication.getCommunication();
}
public void seeResults(View view)
{
Intent i = new Intent(this, ResultsActivity.class);
startActivity(i);
}
public void startListening(View view)
{
listening = !listening;
if(listening)
{
Intent i = new Intent(this, AnomaliesActivity.class);
startActivity(i);
new Thread(new Runnable()
{
@Override
public void run()
{
while (listening)
{
anomalies.add(communication.listenForAnomalies());
}
}
}).start();
}else
{
communication.closeSocket();
anomalies.clear();
((Button) view).setText(Constants.listenLabel);
}
}
public void seeAnomalies(View view)
{
Intent i = new Intent(this, RequestAnomalies.class);
startActivity(i);
}
}
| gpl-2.0 |
BiglySoftware/BiglyBT | uis/src/com/biglybt/ui/swt/skin/SWTSkinObjectSeparator.java | 1481 | /*
* Copyright (C) Azureus Software, Inc, All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details ( see the LICENSE file ).
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.biglybt.ui.swt.skin;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
public class SWTSkinObjectSeparator
extends SWTSkinObjectBasic
{
private Label separator;
public SWTSkinObjectSeparator(SWTSkin skin, SWTSkinProperties properties,
String sid, String configID, SWTSkinObject parent) {
super(skin, properties, sid, configID, "separator", parent);
Composite createOn;
if (parent == null) {
createOn = skin.getShell();
} else {
createOn = (Composite) parent.getControl();
}
separator = new Label(createOn, SWT.SEPARATOR | SWT.HORIZONTAL);
setControl(separator);
}
} | gpl-2.0 |
pmarches/bitcoop | unittest/bcoop/crypto/CryptoTest.java | 2546 | package bcoop.crypto;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.IvParameterSpec;
import mockObject.MockBlocks;
import mockObject.MockIdentityManager;
import junit.framework.TestCase;
public class CryptoTest extends TestCase {
SecretKey secretKey = MockIdentityManager.CLIENT_LOCAL_ID.getEncryptionKey();
public void testEncryptDecryptBlock() throws IllegalBlockSizeException, BadPaddingException, ShortBufferException {
Encryptor encryptor = new Encryptor(secretKey);
byte[] encrypted0 = encryptor.encrypt(MockBlocks.CLEAR_DATABLOCK[0].getBlockData());
byte[] encrypted1 = encryptor.encrypt(MockBlocks.CLEAR_DATABLOCK[1].getBlockData());
assertNotSame(encrypted0, MockBlocks.CLEAR_DATABLOCK[0].getBlockData());
assertTrue(MockBlocks.CLEAR_DATABLOCK[0].getBlockData().length < encrypted0.length);
assertFalse(Arrays.equals(MockBlocks.CLEAR_DATABLOCK[0].getBlockData(), encrypted0));
Decryptor decryptor = new Decryptor(secretKey, encryptor.getIV());
byte[] clearText0 = decryptor.decrypt(encrypted0);
byte[] clearText1 = decryptor.decrypt(encrypted1);
assertTrue(Arrays.equals(MockBlocks.CLEAR_DATABLOCK[0].getBlockData(), clearText0));
assertTrue(Arrays.equals(MockBlocks.CLEAR_DATABLOCK[1].getBlockData(), clearText1));
}
public void xtestCryptoSequence() throws Exception {
Cipher encrpytionCypher = Cipher.getInstance("AES/CBC/PKCS5Padding");
encrpytionCypher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] clearText1 = "Une premiere ligne pour moi!".getBytes();
byte[] clearText2 = "Plus de données font de beaux enfants!".getBytes();
byte[] cipherText1 = encrpytionCypher.update(clearText1);
byte[] cipherText2 = encrpytionCypher.doFinal(clearText2);
Cipher decryptionCypher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivParamSpec = new IvParameterSpec(encrpytionCypher.getIV());
decryptionCypher.init(Cipher.DECRYPT_MODE, this.secretKey, ivParamSpec);
byte[] recoveredText1 = decryptionCypher.update(cipherText1);
byte[] recoveredText2 = decryptionCypher.doFinal(cipherText2);
System.out.println(new String(recoveredText1));
System.out.println(new String(recoveredText2));
assertTrue(Arrays.equals(clearText1, recoveredText1));
assertTrue(Arrays.equals(clearText2, recoveredText2));
}
}
| gpl-2.0 |
shahora/kurdishgram1 | TMeesagesProj/src/main/java/org/vidogram/messenger/exoplayer2/source/smoothstreaming/SsMediaSource.java | 12120 | package org.vidogram.messenger.exoplayer2.source.smoothstreaming;
import android.net.Uri;
import android.os.Handler;
import android.os.SystemClock;
import java.io.IOException;
import java.util.ArrayList;
import org.vidogram.messenger.exoplayer2.C;
import org.vidogram.messenger.exoplayer2.ParserException;
import org.vidogram.messenger.exoplayer2.Timeline;
import org.vidogram.messenger.exoplayer2.source.AdaptiveMediaSourceEventListener;
import org.vidogram.messenger.exoplayer2.source.AdaptiveMediaSourceEventListener.EventDispatcher;
import org.vidogram.messenger.exoplayer2.source.MediaPeriod;
import org.vidogram.messenger.exoplayer2.source.MediaSource;
import org.vidogram.messenger.exoplayer2.source.MediaSource.Listener;
import org.vidogram.messenger.exoplayer2.source.SinglePeriodTimeline;
import org.vidogram.messenger.exoplayer2.source.smoothstreaming.manifest.SsManifest;
import org.vidogram.messenger.exoplayer2.source.smoothstreaming.manifest.SsManifest.StreamElement;
import org.vidogram.messenger.exoplayer2.source.smoothstreaming.manifest.SsManifestParser;
import org.vidogram.messenger.exoplayer2.upstream.Allocator;
import org.vidogram.messenger.exoplayer2.upstream.DataSource;
import org.vidogram.messenger.exoplayer2.upstream.DataSource.Factory;
import org.vidogram.messenger.exoplayer2.upstream.Loader;
import org.vidogram.messenger.exoplayer2.upstream.Loader.Callback;
import org.vidogram.messenger.exoplayer2.upstream.LoaderErrorThrower;
import org.vidogram.messenger.exoplayer2.upstream.LoaderErrorThrower.Dummy;
import org.vidogram.messenger.exoplayer2.upstream.ParsingLoadable;
import org.vidogram.messenger.exoplayer2.util.Assertions;
import org.vidogram.messenger.exoplayer2.util.Util;
public final class SsMediaSource
implements MediaSource, Loader.Callback<ParsingLoadable<SsManifest>>
{
public static final long DEFAULT_LIVE_PRESENTATION_DELAY_MS = 30000L;
public static final int DEFAULT_MIN_LOADABLE_RETRY_COUNT = 3;
private static final int MINIMUM_MANIFEST_REFRESH_PERIOD_MS = 5000;
private static final long MIN_LIVE_DEFAULT_START_POSITION_US = 5000000L;
private final SsChunkSource.Factory chunkSourceFactory;
private final AdaptiveMediaSourceEventListener.EventDispatcher eventDispatcher;
private final long livePresentationDelayMs;
private SsManifest manifest;
private DataSource manifestDataSource;
private final DataSource.Factory manifestDataSourceFactory;
private long manifestLoadStartTimestamp;
private Loader manifestLoader;
private LoaderErrorThrower manifestLoaderErrorThrower;
private final SsManifestParser manifestParser;
private Handler manifestRefreshHandler;
private final Uri manifestUri;
private final ArrayList<SsMediaPeriod> mediaPeriods;
private final int minLoadableRetryCount;
private MediaSource.Listener sourceListener;
public SsMediaSource(Uri paramUri, DataSource.Factory paramFactory, SsChunkSource.Factory paramFactory1, int paramInt, long paramLong, Handler paramHandler, AdaptiveMediaSourceEventListener paramAdaptiveMediaSourceEventListener)
{
this(paramUri, paramFactory, new SsManifestParser(), paramFactory1, paramInt, paramLong, paramHandler, paramAdaptiveMediaSourceEventListener);
}
public SsMediaSource(Uri paramUri, DataSource.Factory paramFactory, SsChunkSource.Factory paramFactory1, Handler paramHandler, AdaptiveMediaSourceEventListener paramAdaptiveMediaSourceEventListener)
{
this(paramUri, paramFactory, paramFactory1, 3, 30000L, paramHandler, paramAdaptiveMediaSourceEventListener);
}
public SsMediaSource(Uri paramUri, DataSource.Factory paramFactory, SsManifestParser paramSsManifestParser, SsChunkSource.Factory paramFactory1, int paramInt, long paramLong, Handler paramHandler, AdaptiveMediaSourceEventListener paramAdaptiveMediaSourceEventListener)
{
this(null, paramUri, paramFactory, paramSsManifestParser, paramFactory1, paramInt, paramLong, paramHandler, paramAdaptiveMediaSourceEventListener);
}
private SsMediaSource(SsManifest paramSsManifest, Uri paramUri, DataSource.Factory paramFactory, SsManifestParser paramSsManifestParser, SsChunkSource.Factory paramFactory1, int paramInt, long paramLong, Handler paramHandler, AdaptiveMediaSourceEventListener paramAdaptiveMediaSourceEventListener)
{
boolean bool;
if ((paramSsManifest == null) || (!paramSsManifest.isLive))
{
bool = true;
Assertions.checkState(bool);
this.manifest = paramSsManifest;
if (paramUri != null)
break label101;
paramSsManifest = null;
}
while (true)
{
this.manifestUri = paramSsManifest;
this.manifestDataSourceFactory = paramFactory;
this.manifestParser = paramSsManifestParser;
this.chunkSourceFactory = paramFactory1;
this.minLoadableRetryCount = paramInt;
this.livePresentationDelayMs = paramLong;
this.eventDispatcher = new AdaptiveMediaSourceEventListener.EventDispatcher(paramHandler, paramAdaptiveMediaSourceEventListener);
this.mediaPeriods = new ArrayList();
return;
bool = false;
break;
label101: paramSsManifest = paramUri;
if (Util.toLowerInvariant(paramUri.getLastPathSegment()).equals("manifest"))
continue;
paramSsManifest = Uri.withAppendedPath(paramUri, "Manifest");
}
}
public SsMediaSource(SsManifest paramSsManifest, SsChunkSource.Factory paramFactory, int paramInt, Handler paramHandler, AdaptiveMediaSourceEventListener paramAdaptiveMediaSourceEventListener)
{
this(paramSsManifest, null, null, null, paramFactory, paramInt, 30000L, paramHandler, paramAdaptiveMediaSourceEventListener);
}
public SsMediaSource(SsManifest paramSsManifest, SsChunkSource.Factory paramFactory, Handler paramHandler, AdaptiveMediaSourceEventListener paramAdaptiveMediaSourceEventListener)
{
this(paramSsManifest, paramFactory, 3, paramHandler, paramAdaptiveMediaSourceEventListener);
}
private void processManifest()
{
int i = 0;
while (i < this.mediaPeriods.size())
{
((SsMediaPeriod)this.mediaPeriods.get(i)).updateManifest(this.manifest);
i += 1;
}
long l1;
long l2;
Object localObject;
long l4;
long l3;
if (this.manifest.isLive)
{
l1 = 9223372036854775807L;
l2 = -9223372036854775808L;
i = 0;
while (i < this.manifest.streamElements.length)
{
localObject = this.manifest.streamElements[i];
l4 = l2;
l3 = l1;
if (((SsManifest.StreamElement)localObject).chunkCount > 0)
{
l3 = Math.min(l1, ((SsManifest.StreamElement)localObject).getStartTimeUs(0));
l4 = Math.max(l2, ((SsManifest.StreamElement)localObject).getStartTimeUs(((SsManifest.StreamElement)localObject).chunkCount - 1) + ((SsManifest.StreamElement)localObject).getChunkDurationUs(((SsManifest.StreamElement)localObject).chunkCount - 1));
}
i += 1;
l2 = l4;
l1 = l3;
}
if (l1 == 9223372036854775807L)
{
localObject = new SinglePeriodTimeline(-9223372036854775807L, false);
this.sourceListener.onSourceInfoRefreshed((Timeline)localObject, this.manifest);
return;
}
if ((this.manifest.dvrWindowLengthUs == -9223372036854775807L) || (this.manifest.dvrWindowLengthUs <= 0L))
break label344;
l1 = Math.max(l1, l2 - this.manifest.dvrWindowLengthUs);
}
label344:
while (true)
{
l4 = l2 - l1;
l3 = l4 - C.msToUs(this.livePresentationDelayMs);
l2 = l3;
if (l3 < 5000000L)
l2 = Math.min(5000000L, l4 / 2L);
localObject = new SinglePeriodTimeline(-9223372036854775807L, l4, l1, l2, true, true);
break;
if (this.manifest.durationUs != -9223372036854775807L);
for (boolean bool = true; ; bool = false)
{
localObject = new SinglePeriodTimeline(this.manifest.durationUs, bool);
break;
}
}
}
private void scheduleManifestRefresh()
{
if (!this.manifest.isLive)
return;
long l = Math.max(0L, this.manifestLoadStartTimestamp + 5000L - SystemClock.elapsedRealtime());
this.manifestRefreshHandler.postDelayed(new Runnable()
{
public void run()
{
SsMediaSource.this.startLoadingManifest();
}
}
, l);
}
private void startLoadingManifest()
{
ParsingLoadable localParsingLoadable = new ParsingLoadable(this.manifestDataSource, this.manifestUri, 4, this.manifestParser);
long l = this.manifestLoader.startLoading(localParsingLoadable, this, this.minLoadableRetryCount);
this.eventDispatcher.loadStarted(localParsingLoadable.dataSpec, localParsingLoadable.type, l);
}
public MediaPeriod createPeriod(int paramInt, Allocator paramAllocator, long paramLong)
{
if (paramInt == 0);
for (boolean bool = true; ; bool = false)
{
Assertions.checkArgument(bool);
paramAllocator = new SsMediaPeriod(this.manifest, this.chunkSourceFactory, this.minLoadableRetryCount, this.eventDispatcher, this.manifestLoaderErrorThrower, paramAllocator);
this.mediaPeriods.add(paramAllocator);
return paramAllocator;
}
}
public void maybeThrowSourceInfoRefreshError()
{
this.manifestLoaderErrorThrower.maybeThrowError();
}
public void onLoadCanceled(ParsingLoadable<SsManifest> paramParsingLoadable, long paramLong1, long paramLong2, boolean paramBoolean)
{
this.eventDispatcher.loadCompleted(paramParsingLoadable.dataSpec, paramParsingLoadable.type, paramLong1, paramLong2, paramParsingLoadable.bytesLoaded());
}
public void onLoadCompleted(ParsingLoadable<SsManifest> paramParsingLoadable, long paramLong1, long paramLong2)
{
this.eventDispatcher.loadCompleted(paramParsingLoadable.dataSpec, paramParsingLoadable.type, paramLong1, paramLong2, paramParsingLoadable.bytesLoaded());
this.manifest = ((SsManifest)paramParsingLoadable.getResult());
this.manifestLoadStartTimestamp = (paramLong1 - paramLong2);
processManifest();
scheduleManifestRefresh();
}
public int onLoadError(ParsingLoadable<SsManifest> paramParsingLoadable, long paramLong1, long paramLong2, IOException paramIOException)
{
boolean bool = paramIOException instanceof ParserException;
this.eventDispatcher.loadError(paramParsingLoadable.dataSpec, paramParsingLoadable.type, paramLong1, paramLong2, paramParsingLoadable.bytesLoaded(), paramIOException, bool);
if (bool)
return 3;
return 0;
}
public void prepareSource(MediaSource.Listener paramListener)
{
this.sourceListener = paramListener;
if (this.manifest != null)
{
this.manifestLoaderErrorThrower = new LoaderErrorThrower.Dummy();
processManifest();
return;
}
this.manifestDataSource = this.manifestDataSourceFactory.createDataSource();
this.manifestLoader = new Loader("Loader:Manifest");
this.manifestLoaderErrorThrower = this.manifestLoader;
this.manifestRefreshHandler = new Handler();
startLoadingManifest();
}
public void releasePeriod(MediaPeriod paramMediaPeriod)
{
((SsMediaPeriod)paramMediaPeriod).release();
this.mediaPeriods.remove(paramMediaPeriod);
}
public void releaseSource()
{
this.sourceListener = null;
this.manifest = null;
this.manifestDataSource = null;
this.manifestLoadStartTimestamp = 0L;
if (this.manifestLoader != null)
{
this.manifestLoader.release();
this.manifestLoader = null;
}
if (this.manifestRefreshHandler != null)
{
this.manifestRefreshHandler.removeCallbacksAndMessages(null);
this.manifestRefreshHandler = null;
}
}
}
/* Location: C:\Documents and Settings\soran\Desktop\s\classes.jar
* Qualified Name: org.vidogram.messenger.exoplayer2.source.smoothstreaming.SsMediaSource
* JD-Core Version: 0.6.0
*/ | gpl-2.0 |
magsilva/jortho | src/com/inet/jorthodictionaries/BookGenerator_fr.java | 1654 | /*
* JOrtho
*
* Copyright (C) 2005-2008 by i-net software
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
* Created on 13.12.2007
*/
package com.inet.jorthodictionaries;
/**
*
* @author Volker Berlin
*/
public class BookGenerator_fr extends BookGenerator {
/**
* Create a new BookGenerator and add some special words.
*/
public BookGenerator_fr() {
// Compound words with a single character
addWord( "m'a" );
addWord( "m'y" );
addWord( "n'a" );
addWord( "n'y" );
addWord( "l'a" );
addWord( "l'y" );
addWord( "qu'a" );
addWord( "qu'y" );
addWord( "s'y" );
}
@Override
boolean isValidLanguage( String word, String wikiText ) {
if( wikiText.indexOf( "{{langue|fr}}" ) < 0 && wikiText.indexOf("{{=fr=}}") < 0){
return false;
}
return true;
}
}
| gpl-2.0 |
andreformento/my-money | my-money-repository-default/src/main/java/br/com/formento/mymoney/repository/config/RepositoryConfig.java | 3840 | package br.com.formento.mymoney.repository.config;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import br.com.formento.mymoney.repository.dao.UserDao;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@PropertySource({"classpath:hibernate.properties"})
@ComponentScan(basePackageClasses = UserDao.class)
public class RepositoryConfig {
@Value("${jdbc.driverClassName}")
private String driverClassName;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Value("${hibernate.dialect}")
private String hibernateDialect;
@Value("${hibernate.show_sql}")
private String hibernateShowSql;
@Value("${hibernate.hbm2ddl.auto}")
private String hibernateHbm2ddlAuto;
@Value("${hibernate.ejb.naming_strategy}")
private String namingStrategy;
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[]{"br.com.formento.mymoney.core.model", "br.com.formento.mymoney.repository.dao"});
// em.setPackagesToScan(new String[]{"br.com.formento.mymoney.core.model"});
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor;
persistenceExceptionTranslationPostProcessor = new PersistenceExceptionTranslationPostProcessor();
return persistenceExceptionTranslationPostProcessor;
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.dialect", hibernateDialect);
properties.setProperty("hibernate.show_sql", hibernateShowSql);
properties.setProperty("hibernate.hbm2ddl.auto", hibernateHbm2ddlAuto);
properties.setProperty("hibernate.ejb.naming_strategy", namingStrategy);
return properties;
}
}
| gpl-2.0 |
maiklos-mirrors/jfx78 | modules/base/src/test/java/javafx/binding/BindingsArrayTest.java | 57546 | /*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javafx.binding;
import javafx.beans.binding.*;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import com.sun.javafx.binding.ErrorLoggingUtiltity;
import javafx.collections.ObservableFloatArray;
import javafx.collections.ObservableIntegerArray;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*/
public class BindingsArrayTest {
private static final double EPSILON_DOUBLE = 1e-12;
private static final float EPSILON_FLOAT = 1e-5f;
private static final Object data1 = new Object();
private static final Object data2 = new Object();
private static final ErrorLoggingUtiltity log = new ErrorLoggingUtiltity();
private ListProperty<Object> property;
private ObservableList<Object> list1;
private ObservableList<Object> list2;
private IntegerProperty index;
@BeforeClass
public static void setUpClass() {
log.start();
}
@AfterClass
public static void tearDownClass() {
log.stop();
}
@Before
public void setUp() {
property = new SimpleListProperty<Object>();
list1 = FXCollections.<Object>observableArrayList(data1, data2);
list2 = FXCollections.<Object>observableArrayList();
index = new SimpleIntegerProperty();
}
@Test
public void testSize() {
final IntegerBinding size = Bindings.size(property);
DependencyUtils.checkDependencies(size.getDependencies(), property);
assertEquals(0, size.get());
property.set(list1);
assertEquals(2, size.get());
list1.remove(data2);
assertEquals(1, size.get());
property.set(list2);
assertEquals(0, size.get());
property.addAll(data2, data2);
assertEquals(2, size.get());
property.set(null);
assertEquals(0, size.get());
}
@Test(expected = NullPointerException.class)
public void testSize_Null() {
Bindings.size((ObservableList<Object>) null);
}
@Test
public void testIsEmpty() {
final BooleanBinding empty = Bindings.isEmpty(property);
DependencyUtils.checkDependencies(empty.getDependencies(), property);
assertTrue(empty.get());
property.set(list1);
assertFalse(empty.get());
list1.remove(data2);
assertFalse(empty.get());
property.set(list2);
assertTrue(empty.get());
property.addAll(data2, data2);
assertFalse(empty.get());
property.set(null);
assertTrue(empty.get());
}
@Test(expected = NullPointerException.class)
public void testIsEmpty_Null() {
Bindings.isEmpty((ObservableList<Object>) null);
}
@Test
public void testIsNotEmpty() {
final BooleanBinding notEmpty = Bindings.isNotEmpty(property);
DependencyUtils.checkDependencies(notEmpty.getDependencies(), property);
assertFalse(notEmpty.get());
property.set(list1);
assertTrue(notEmpty.get());
list1.remove(data2);
assertTrue(notEmpty.get());
property.set(list2);
assertFalse(notEmpty.get());
property.addAll(data2, data2);
assertTrue(notEmpty.get());
property.set(null);
assertFalse(notEmpty.get());
}
@Test(expected = NullPointerException.class)
public void testIsNotEmpty_Null() {
Bindings.isNotEmpty((ObservableList<Object>) null);
}
@Ignore("RT-27128")
@Test
public void testValueAt_Constant() {
synchronized (log) {
log.reset();
final ObjectBinding<Object> binding0 = Bindings.valueAt(property, 0);
final ObjectBinding<Object> binding1 = Bindings.valueAt(property, 1);
final ObjectBinding<Object> binding2 = Bindings.valueAt(property, 2);
DependencyUtils.checkDependencies(binding0.getDependencies(), property);
DependencyUtils.checkDependencies(binding1.getDependencies(), property);
DependencyUtils.checkDependencies(binding2.getDependencies(), property);
assertNull(binding0.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertNull(binding1.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertNull(binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
property.set(list1);
assertEquals(data1, binding0.get());
assertEquals(data2, binding1.get());
assertNull(binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
property.remove(data2);
assertEquals(data1, binding0.get());
assertNull(binding1.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertNull(binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
property.set(list2);
assertNull(binding0.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertNull(binding1.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertNull(binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
property.addAll(data2, data2);
assertEquals(data2, binding0.get());
assertEquals(data2, binding1.get());
assertNull(binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
property.set(null);
assertNull(binding0.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertNull(binding1.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertNull(binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
}
}
@Test(expected = NullPointerException.class)
public void testValueAt_Constant_Null() {
Bindings.valueAt(null, 0);
}
@Test(expected = IllegalArgumentException.class)
public void testValueAt_Constant_NegativeIndex() {
Bindings.valueAt(property, -1);
}
@Ignore("RT-27128")
@Test
public void testValueAt_Variable() {
synchronized (log) {
log.reset();
final ObjectBinding<Object> binding = Bindings.valueAt(property, index);
DependencyUtils.checkDependencies(binding.getDependencies(), property, index);
index.set(-1);
assertNull(binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertNull(binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
property.set(list1);
index.set(-1);
assertNull(binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(data1, binding.get());
index.set(1);
assertEquals(data2, binding.get());
index.set(2);
assertNull(binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
property.remove(data2);
index.set(-1);
assertNull(binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(data1, binding.get());
index.set(1);
assertNull(binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
property.set(list2);
index.set(-1);
assertNull(binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertNull(binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
property.addAll(data2, data2);
index.set(-1);
assertNull(binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(data2, binding.get());
index.set(1);
assertEquals(data2, binding.get());
index.set(2);
assertNull(binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
property.set(null);
index.set(-1);
assertNull(binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertNull(binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
}
}
@Test(expected = NullPointerException.class)
public void testValueAt_Variable_Null() {
Bindings.valueAt((ObservableList<Object>)null, index);
}
@Test(expected = NullPointerException.class)
public void testValueAt_Variable_NullIndex() {
Bindings.valueAt(property, null);
}
@Ignore("RT-27128")
@Test
public void testBooleanValueAt_Constant() {
synchronized (log) {
log.reset();
final boolean defaultData = false;
final boolean localData1 = false;
final boolean localData2 = true;
final ListProperty<Boolean> localProperty = new SimpleListProperty<Boolean>();
final ObservableList<Boolean> localList1 = FXCollections.observableArrayList(localData1, localData2);
final ObservableList<Boolean> localList2 = FXCollections.observableArrayList();
final BooleanBinding binding0 = Bindings.booleanValueAt(localProperty, 0);
final BooleanBinding binding1 = Bindings.booleanValueAt(localProperty, 1);
final BooleanBinding binding2 = Bindings.booleanValueAt(localProperty, 2);
DependencyUtils.checkDependencies(binding0.getDependencies(), localProperty);
DependencyUtils.checkDependencies(binding1.getDependencies(), localProperty);
DependencyUtils.checkDependencies(binding2.getDependencies(), localProperty);
assertEquals(defaultData, binding0.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding1.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList1);
assertEquals(localData1, binding0.get());
assertEquals(localData2, binding1.get());
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.remove(1);
assertEquals(localData1, binding0.get());
assertEquals(defaultData, binding1.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList2);
assertEquals(defaultData, binding0.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding1.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.addAll(localData2, localData2);
assertEquals(localData2, binding0.get());
assertEquals(localData2, binding1.get());
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(null);
assertEquals(defaultData, binding0.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding1.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
}
}
@Test(expected = NullPointerException.class)
public void testBooleanValueAt_Constant_Null() {
Bindings.booleanValueAt(null, 0);
}
@Test(expected = IllegalArgumentException.class)
public void testBooleanValueAt_Constant_NegativeIndex() {
final ListProperty<Boolean> localProperty = new SimpleListProperty<Boolean>();
Bindings.booleanValueAt(localProperty, -1);
}
@Ignore("RT-27128")
@Test
public void testBooleanValueAt_Variable() {
synchronized (log) {
log.reset();
final boolean defaultData = false;
final boolean localData1 = false;
final boolean localData2 = true;
final ListProperty<Boolean> localProperty = new SimpleListProperty<Boolean>();
final ObservableList<Boolean> localList1 = FXCollections.observableArrayList(localData1, localData2);
final ObservableList<Boolean> localList2 = FXCollections.observableArrayList();
final BooleanBinding binding = Bindings.booleanValueAt(localProperty, index);
DependencyUtils.checkDependencies(binding.getDependencies(), localProperty, index);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList1);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(localData1, binding.get());
index.set(1);
assertEquals(localData2, binding.get());
index.set(2);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.remove(1);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(localData1, binding.get());
index.set(1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(0, null);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(defaultData, binding.get());
log.check(0, "INFO", "NullPointerException");
index.set(1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList2);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.addAll(localData2, localData2);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(localData2, binding.get());
index.set(1);
assertEquals(localData2, binding.get());
index.set(2);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(null);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
}
}
@Test(expected = NullPointerException.class)
public void testBooleanValueAt_Variable_Null() {
Bindings.booleanValueAt((ObservableList<Boolean>)null, index);
}
@Test(expected = NullPointerException.class)
public void testBooleanValueAt_Variable_NullIndex() {
final ListProperty<Boolean> localProperty = new SimpleListProperty<Boolean>();
Bindings.booleanValueAt(localProperty, null);
}
@Ignore("RT-27128")
@Test
public void testDoubleValueAt_Constant() {
synchronized (log) {
log.reset();
final double defaultData = 0.0;
final double localData1 = Math.PI;
final double localData2 = -Math.E;
final ListProperty<Double> localProperty = new SimpleListProperty<Double>();
final ObservableList<Double> localList1 = FXCollections.observableArrayList(localData1, localData2);
final ObservableList<Double> localList2 = FXCollections.observableArrayList();
final DoubleBinding binding0 = Bindings.doubleValueAt(localProperty, 0);
final DoubleBinding binding1 = Bindings.doubleValueAt(localProperty, 1);
final DoubleBinding binding2 = Bindings.doubleValueAt(localProperty, 2);
DependencyUtils.checkDependencies(binding0.getDependencies(), localProperty);
DependencyUtils.checkDependencies(binding1.getDependencies(), localProperty);
DependencyUtils.checkDependencies(binding2.getDependencies(), localProperty);
assertEquals(defaultData, binding0.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding1.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList1);
assertEquals(localData1, binding0.get(), EPSILON_DOUBLE);
assertEquals(localData2, binding1.get(), EPSILON_DOUBLE);
assertEquals(defaultData, binding2.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.remove(1);
assertEquals(localData1, binding0.get(), EPSILON_DOUBLE);
assertEquals(defaultData, binding1.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList2);
assertEquals(defaultData, binding0.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding1.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.addAll(localData2, localData2);
assertEquals(localData2, binding0.get(), EPSILON_DOUBLE);
assertEquals(localData2, binding1.get(), EPSILON_DOUBLE);
assertEquals(defaultData, binding2.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(null);
assertEquals(defaultData, binding0.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding1.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
}
}
@Test(expected = NullPointerException.class)
public void testDoubleValueAt_Constant_Null() {
Bindings.doubleValueAt(null, 0);
}
@Test(expected = IllegalArgumentException.class)
public void testDoubleValueAt_Constant_NegativeIndex() {
final ListProperty<Double> localProperty = new SimpleListProperty<Double>();
Bindings.doubleValueAt(localProperty, -1);
}
@Ignore("RT-27128")
@Test
public void testDoubleValueAt_Variable() {
synchronized (log) {
log.reset();
final double defaultData = 0.0;
final double localData1 = -Math.PI;
final double localData2 = Math.E;
final ListProperty<Double> localProperty = new SimpleListProperty<Double>();
final ObservableList<Double> localList1 = FXCollections.observableArrayList(localData1, localData2);
final ObservableList<Double> localList2 = FXCollections.observableArrayList();
final DoubleBinding binding = Bindings.doubleValueAt(localProperty, index);
DependencyUtils.checkDependencies(binding.getDependencies(), localProperty, index);
index.set(-1);
assertEquals(defaultData, binding.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(defaultData, binding.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList1);
index.set(-1);
assertEquals(defaultData, binding.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(localData1, binding.get(), EPSILON_DOUBLE);
index.set(1);
assertEquals(localData2, binding.get(), EPSILON_DOUBLE);
index.set(2);
assertEquals(defaultData, binding.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.remove(1);
index.set(-1);
assertEquals(defaultData, binding.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(localData1, binding.get(), EPSILON_DOUBLE);
index.set(1);
assertEquals(defaultData, binding.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(0, null);
index.set(-1);
assertEquals(defaultData, binding.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(defaultData, binding.get(), EPSILON_DOUBLE);
log.check(0, "INFO", "NullPointerException");
index.set(1);
assertEquals(defaultData, binding.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList2);
index.set(-1);
assertEquals(defaultData, binding.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(defaultData, binding.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.addAll(localData2, localData2);
index.set(-1);
assertEquals(defaultData, binding.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(localData2, binding.get(), EPSILON_DOUBLE);
index.set(1);
assertEquals(localData2, binding.get(), EPSILON_DOUBLE);
index.set(2);
assertEquals(defaultData, binding.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(null);
index.set(-1);
assertEquals(defaultData, binding.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(defaultData, binding.get(), EPSILON_DOUBLE);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
}
}
@Test(expected = NullPointerException.class)
public void testDoubleValueAt_Variable_Null() {
Bindings.doubleValueAt((ObservableList<Double>)null, index);
}
@Test(expected = NullPointerException.class)
public void testDoubleValueAt_Variable_NullIndex() {
final ListProperty<Double> localProperty = new SimpleListProperty<Double>();
Bindings.doubleValueAt(localProperty, null);
}
@Ignore("RT-27128")
@Test
public void testFloatValueAt_Constant() {
synchronized (log) {
log.reset();
final float defaultData = 0.0f;
final float localData1 = (float)Math.PI;
final float localData2 = (float)-Math.E;
final ListProperty<Float> localProperty = new SimpleListProperty<Float>();
final ObservableList<Float> localList1 = FXCollections.observableArrayList(localData1, localData2);
final ObservableList<Float> localList2 = FXCollections.observableArrayList();
final FloatBinding binding0 = Bindings.floatValueAt(localProperty, 0);
final FloatBinding binding1 = Bindings.floatValueAt(localProperty, 1);
final FloatBinding binding2 = Bindings.floatValueAt(localProperty, 2);
DependencyUtils.checkDependencies(binding0.getDependencies(), localProperty);
DependencyUtils.checkDependencies(binding1.getDependencies(), localProperty);
DependencyUtils.checkDependencies(binding2.getDependencies(), localProperty);
assertEquals(defaultData, binding0.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding1.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList1);
assertEquals(localData1, binding0.get(), EPSILON_FLOAT);
assertEquals(localData2, binding1.get(), EPSILON_FLOAT);
assertEquals(defaultData, binding2.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.remove(1);
assertEquals(localData1, binding0.get(), EPSILON_FLOAT);
assertEquals(defaultData, binding1.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList2);
assertEquals(defaultData, binding0.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding1.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.addAll(localData2, localData2);
assertEquals(localData2, binding0.get(), EPSILON_FLOAT);
assertEquals(localData2, binding1.get(), EPSILON_FLOAT);
assertEquals(defaultData, binding2.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(null);
assertEquals(defaultData, binding0.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding1.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
}
}
@Test(expected = NullPointerException.class)
public void testFloatValueAt_Constant_Null() {
Bindings.floatValueAt((ObservableFloatArray) null, 0);
}
@Test(expected = IllegalArgumentException.class)
public void testFloatValueAt_Constant_NegativeIndex() {
final ListProperty<Float> localProperty = new SimpleListProperty<Float>();
Bindings.floatValueAt(localProperty, -1);
}
@Ignore("RT-27128")
@Test
public void testFloatValueAt_Variable() {
synchronized (log) {
log.reset();
final float defaultData = 0.0f;
final float localData1 = (float)-Math.PI;
final float localData2 = (float)Math.E;
final ListProperty<Float> localProperty = new SimpleListProperty<Float>();
final ObservableList<Float> localList1 = FXCollections.observableArrayList(localData1, localData2);
final ObservableList<Float> localList2 = FXCollections.observableArrayList();
final FloatBinding binding = Bindings.floatValueAt(localProperty, index);
DependencyUtils.checkDependencies(binding.getDependencies(), localProperty, index);
index.set(-1);
assertEquals(defaultData, binding.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(defaultData, binding.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList1);
index.set(-1);
assertEquals(defaultData, binding.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(localData1, binding.get(), EPSILON_FLOAT);
index.set(1);
assertEquals(localData2, binding.get(), EPSILON_FLOAT);
index.set(2);
assertEquals(defaultData, binding.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.remove(1);
index.set(-1);
assertEquals(defaultData, binding.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(localData1, binding.get(), EPSILON_FLOAT);
index.set(1);
assertEquals(defaultData, binding.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(0, null);
index.set(-1);
assertEquals(defaultData, binding.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(defaultData, binding.get(), EPSILON_FLOAT);
log.check(0, "INFO", "NullPointerException");
index.set(1);
assertEquals(defaultData, binding.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList2);
index.set(-1);
assertEquals(defaultData, binding.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(defaultData, binding.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.addAll(localData2, localData2);
index.set(-1);
assertEquals(defaultData, binding.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(localData2, binding.get(), EPSILON_FLOAT);
index.set(1);
assertEquals(localData2, binding.get(), EPSILON_FLOAT);
index.set(2);
assertEquals(defaultData, binding.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(null);
index.set(-1);
assertEquals(defaultData, binding.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(defaultData, binding.get(), EPSILON_FLOAT);
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
}
}
@Test(expected = NullPointerException.class)
public void testFloatValueAt_Variable_Null() {
Bindings.floatValueAt((ObservableList<Float>)null, index);
}
@Test(expected = NullPointerException.class)
public void testFloatValueAt_Variable_NullIndex() {
final ListProperty<Float> localProperty = new SimpleListProperty<Float>();
Bindings.floatValueAt(localProperty, null);
}
@Ignore("RT-27128")
@Test
public void testIntegerValueAt_Constant() {
synchronized (log) {
log.reset();
final int defaultData = 0;
final int localData1 = 42;
final int localData2 = -7;
final ListProperty<Integer> localProperty = new SimpleListProperty<Integer>();
final ObservableList<Integer> localList1 = FXCollections.observableArrayList(localData1, localData2);
final ObservableList<Integer> localList2 = FXCollections.observableArrayList();
final IntegerBinding binding0 = Bindings.integerValueAt(localProperty, 0);
final IntegerBinding binding1 = Bindings.integerValueAt(localProperty, 1);
final IntegerBinding binding2 = Bindings.integerValueAt(localProperty, 2);
DependencyUtils.checkDependencies(binding0.getDependencies(), localProperty);
DependencyUtils.checkDependencies(binding1.getDependencies(), localProperty);
DependencyUtils.checkDependencies(binding2.getDependencies(), localProperty);
assertEquals(defaultData, binding0.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding1.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList1);
assertEquals(localData1, binding0.get());
assertEquals(localData2, binding1.get());
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.remove(1);
assertEquals(localData1, binding0.get());
assertEquals(defaultData, binding1.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList2);
assertEquals(defaultData, binding0.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding1.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.addAll(localData2, localData2);
assertEquals(localData2, binding0.get());
assertEquals(localData2, binding1.get());
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(null);
assertEquals(defaultData, binding0.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding1.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
}
}
@Test(expected = NullPointerException.class)
public void testIntegerValueAt_Constant_Null() {
Bindings.integerValueAt((ObservableIntegerArray) null, 0);
}
@Test(expected = IllegalArgumentException.class)
public void testIntegerValueAt_Constant_NegativeIndex() {
final ListProperty<Integer> localProperty = new SimpleListProperty<Integer>();
Bindings.integerValueAt(localProperty, -1);
}
@Ignore("RT-27128")
@Test
public void testIntegerValueAt_Variable() {
synchronized (log) {
log.reset();
final int defaultData = 0;
final int localData1 = 42;
final int localData2 = -7;
final ListProperty<Integer> localProperty = new SimpleListProperty<Integer>();
final ObservableList<Integer> localList1 = FXCollections.observableArrayList(localData1, localData2);
final ObservableList<Integer> localList2 = FXCollections.observableArrayList();
final IntegerBinding binding = Bindings.integerValueAt(localProperty, index);
DependencyUtils.checkDependencies(binding.getDependencies(), localProperty, index);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList1);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(localData1, binding.get());
index.set(1);
assertEquals(localData2, binding.get());
index.set(2);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.remove(1);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(localData1, binding.get());
index.set(1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(0, null);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(defaultData, binding.get());
log.check(0, "INFO", "NullPointerException");
index.set(1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList2);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.addAll(localData2, localData2);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(localData2, binding.get());
index.set(1);
assertEquals(localData2, binding.get());
index.set(2);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(null);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
}
}
@Test(expected = NullPointerException.class)
public void testIntegerValueAt_Variable_Null() {
Bindings.integerValueAt((ObservableList<Integer>)null, index);
}
@Test(expected = NullPointerException.class)
public void testIntegerValueAt_Variable_NullIndex() {
final ListProperty<Integer> localProperty = new SimpleListProperty<Integer>();
Bindings.integerValueAt(localProperty, null);
}
@Ignore("RT-27128")
@Test
public void testLongValueAt_Constant() {
synchronized (log) {
log.reset();
final long defaultData = 0L;
final long localData1 = 1234567890987654321L;
final long localData2 = -987654321987654321L;
final ListProperty<Long> localProperty = new SimpleListProperty<Long>();
final ObservableList<Long> localList1 = FXCollections.observableArrayList(localData1, localData2);
final ObservableList<Long> localList2 = FXCollections.observableArrayList();
final LongBinding binding0 = Bindings.longValueAt(localProperty, 0);
final LongBinding binding1 = Bindings.longValueAt(localProperty, 1);
final LongBinding binding2 = Bindings.longValueAt(localProperty, 2);
DependencyUtils.checkDependencies(binding0.getDependencies(), localProperty);
DependencyUtils.checkDependencies(binding1.getDependencies(), localProperty);
DependencyUtils.checkDependencies(binding2.getDependencies(), localProperty);
assertEquals(defaultData, binding0.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding1.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList1);
assertEquals(localData1, binding0.get());
assertEquals(localData2, binding1.get());
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.remove(1);
assertEquals(localData1, binding0.get());
assertEquals(defaultData, binding1.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList2);
assertEquals(defaultData, binding0.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding1.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.addAll(localData2, localData2);
assertEquals(localData2, binding0.get());
assertEquals(localData2, binding1.get());
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(null);
assertEquals(defaultData, binding0.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding1.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
}
}
@Test(expected = NullPointerException.class)
public void testLongValueAt_Constant_Null() {
Bindings.longValueAt(null, 0);
}
@Test(expected = IllegalArgumentException.class)
public void testLongValueAt_Constant_NegativeIndex() {
final ListProperty<Long> localProperty = new SimpleListProperty<Long>();
Bindings.longValueAt(localProperty, -1);
}
@Ignore("RT-27128")
@Test
public void testLongValueAt_Variable() {
synchronized (log) {
log.reset();
final long defaultData = 0;
final long localData1 = 98765432123456789L;
final long localData2 = -1234567890123456789L;
final ListProperty<Long> localProperty = new SimpleListProperty<Long>();
final ObservableList<Long> localList1 = FXCollections.observableArrayList(localData1, localData2);
final ObservableList<Long> localList2 = FXCollections.observableArrayList();
final LongBinding binding = Bindings.longValueAt(localProperty, index);
DependencyUtils.checkDependencies(binding.getDependencies(), localProperty, index);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList1);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(localData1, binding.get());
index.set(1);
assertEquals(localData2, binding.get());
index.set(2);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.remove(1);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(localData1, binding.get());
index.set(1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(0, null);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(defaultData, binding.get());
log.check(0, "INFO", "NullPointerException");
index.set(1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList2);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.addAll(localData2, localData2);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(localData2, binding.get());
index.set(1);
assertEquals(localData2, binding.get());
index.set(2);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(null);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
}
}
@Test(expected = NullPointerException.class)
public void testLongValueAt_Variable_Null() {
Bindings.longValueAt((ObservableList<Long>)null, index);
}
@Test(expected = NullPointerException.class)
public void testLongValueAt_Variable_NullIndex() {
final ListProperty<Long> localProperty = new SimpleListProperty<Long>();
Bindings.longValueAt(localProperty, null);
}
@Ignore("RT-27128")
@Test
public void testStringValueAt_Constant() {
synchronized (log) {
log.reset();
final String defaultData = null;
final String localData1 = "Hello World";
final String localData2 = "Goodbye World";
final ListProperty<String> localProperty = new SimpleListProperty<String>();
final ObservableList<String> localList1 = FXCollections.observableArrayList(localData1, localData2);
final ObservableList<String> localList2 = FXCollections.observableArrayList();
final StringBinding binding0 = Bindings.stringValueAt(localProperty, 0);
final StringBinding binding1 = Bindings.stringValueAt(localProperty, 1);
final StringBinding binding2 = Bindings.stringValueAt(localProperty, 2);
DependencyUtils.checkDependencies(binding0.getDependencies(), localProperty);
DependencyUtils.checkDependencies(binding1.getDependencies(), localProperty);
DependencyUtils.checkDependencies(binding2.getDependencies(), localProperty);
assertEquals(defaultData, binding0.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding1.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList1);
assertEquals(localData1, binding0.get());
assertEquals(localData2, binding1.get());
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.remove(1);
assertEquals(localData1, binding0.get());
assertEquals(defaultData, binding1.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList2);
assertEquals(defaultData, binding0.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding1.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.addAll(localData2, localData2);
assertEquals(localData2, binding0.get());
assertEquals(localData2, binding1.get());
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(null);
assertEquals(defaultData, binding0.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding1.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
assertEquals(defaultData, binding2.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
}
}
@Test(expected = NullPointerException.class)
public void testStringValueAt_Constant_Null() {
Bindings.stringValueAt(null, 0);
}
@Test(expected = IllegalArgumentException.class)
public void testStringValueAt_Constant_NegativeIndex() {
final ListProperty<String> localProperty = new SimpleListProperty<String>();
Bindings.stringValueAt(localProperty, -1);
}
@Ignore("RT-27128")
@Test
public void testStringValueAt_Variable() {
synchronized (log) {
log.reset();
final String defaultData = null;
final String localData1 = "Goodbye";
final String localData2 = "Hello";
final ListProperty<String> localProperty = new SimpleListProperty<String>();
final ObservableList<String> localList1 = FXCollections.observableArrayList(localData1, localData2);
final ObservableList<String> localList2 = FXCollections.observableArrayList();
final StringBinding binding = Bindings.stringValueAt(localProperty, index);
DependencyUtils.checkDependencies(binding.getDependencies(), localProperty, index);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList1);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(localData1, binding.get());
index.set(1);
assertEquals(localData2, binding.get());
index.set(2);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.remove(1);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(localData1, binding.get());
index.set(1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(localList2);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.addAll(localData2, localData2);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(localData2, binding.get());
index.set(1);
assertEquals(localData2, binding.get());
index.set(2);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
localProperty.set(null);
index.set(-1);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
index.set(0);
assertEquals(defaultData, binding.get());
log.check(0, "WARNING", 1, "IndexOutOfBoundsException");
}
}
@Test(expected = NullPointerException.class)
public void testStringValueAt_Variable_Null() {
Bindings.stringValueAt((ObservableList<String>)null, index);
}
@Test(expected = NullPointerException.class)
public void testStringValueAt_Variable_NullIndex() {
final ListProperty<String> localProperty = new SimpleListProperty<String>();
Bindings.stringValueAt(localProperty, null);
}
}
| gpl-2.0 |
loveluckystar/spiderTest | src/main/java/com/spiderTest/domain/SpiderZiroomProduct.java | 1627 | package com.spiderTest.domain;
/**
* @Description: ×ÔÈç×¥È¡Ò³Ãæ ʵÌåÀà
* @ClassName: SpiderZiroomProduct
*/
public class SpiderZiroomProduct {
private long autoid;
private String city ;//³ÇÊÐ
private String origin;//Êý¾ÝÀ´Ô´Ò³Ãæurl
private String productid = "";//Â¥ÅÌid
public long getAutoid() {
return autoid;
}
public void setAutoid(long autoid) {
this.autoid = autoid;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getOrigin() {
return origin;
}
public void setOrigin(String origin) {
this.origin = origin;
}
public String getProductid() {
return productid;
}
public void setProductid(String productid) {
this.productid = productid;
}
public String getProductlink() {
return productlink;
}
public void setProductlink(String productlink) {
this.productlink = productlink;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getSubway() {
return subway;
}
public void setSubway(String subway) {
this.subway = subway;
}
private String productlink = "";//Â¥ÅÌÁ´½Ó
private String name = "";//Â¥ÅÌÃû
private String price = "";//¼Û¸ñ
private String district = "";//ÇøÓò
private String subway = "";//µØÌúÇé¿ö
}
| gpl-2.0 |
SampleSizeShop/WebServiceCommon | src/edu/ucdenver/bios/webservice/common/domain/CategoryList.java | 3407 | /*
* Web service utility functions for managing hibernate, json, etc.
*
* Copyright (C) 2010 Regents of the University of Colorado.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
package edu.ucdenver.bios.webservice.common.domain;
import java.util.ArrayList;
import java.util.List;
// TO-DO: Auto-generated Javadoc
/**
* List of category objects to work around Jackson serializaiton issues.
*
* @author Uttara Sakhadeo
*
*/
public class CategoryList {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The uuid. */
private byte[] uuid = null;
/** The category list. */
private List<Category> categoryList = null;
/*--------------------
* Constructors
*--------------------*/
/**
* Instantiates a new category list.
*/
public CategoryList() {
}
/**
* Instantiates a new category list.
*
* @param uuid
* the uuid
*/
public CategoryList(final byte[] uuid) {
this.uuid = uuid;
}
/**
* Instantiates a new category list.
*
* @param size
* the size
*/
public CategoryList(final int size) {
this.categoryList = new ArrayList<Category>(size);
}
/**
* Instantiates a new category list.
*
* @param list
* the list
*/
public CategoryList(final List<Category> list) {
this.categoryList = list;
}
/**
* Instantiates a new category list.
*
* @param uuid
* the uuid
* @param list
* the list
*/
public CategoryList(final byte[] uuid, final List<Category> list) {
this.categoryList = list;
this.uuid = uuid;
}
/*--------------------
* Getter/Setter Methods
*--------------------*/
/**
* Gets the uuid.
*
* @return the uuid
*/
public final byte[] getUuid() {
return uuid;
}
/**
* Sets the uuid.
*
* @param uuid
* the new uuid
*/
public final void setUuid(final byte[] uuid) {
this.uuid = uuid;
}
/**
* Gets the category list.
*
* @return the category list
*/
public final List<Category> getCategoryList() {
return categoryList;
}
/**
* Sets the category list.
*
* @param categoryList
* the new category list
*/
public final void setCategoryList(final List<Category> categoryList) {
this.categoryList = categoryList;
}
}
| gpl-2.0 |
set92/Small-Programs | Java/CFGS/Interfaces-Ejercicios/Libro/sergio/ejer336.java | 215 | package sergio;
/* Ejercicio 6. Pag 33
* Autor: Sergio Tobal
* Fecha: 25-11-2011
*/
public class ejer336 {
public static void main(String[] args) {
int i=0x100;
i >>>= 1;
System.out.println(i);
}
}
| gpl-2.0 |
jonathanmcelroy/DataCommunicationsProgram456 | twitter4j/twitter4j-spdy-support/src/main/java/twitter4j/VersionSPDY.java | 1200 | /*
* Copyright 2007 Yusuke Yamamoto
*
* 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 twitter4j;
/**
* @author Hiroaki Takeuchi - takke30 at gmail.com
* @since Twitter4J 3.0.6
*/
public final class VersionSPDY {
private static final String VERSION = "4.0.2";
private static final String TITLE = "Twitter4J SPDY Support";
private VersionSPDY() {
throw new AssertionError();
}
public static String getVersion() {
return VERSION;
}
/**
* prints the version string
*
* @param args will be just ignored.
*/
public static void main(String[] args) {
System.out.println(TITLE + " " + VERSION);
}
}
| gpl-2.0 |
leomarkfc/sisec | fratello-ejb/src/main/java/br/org/osgefic/fratello/dominio/GradeCurricular.java | 1294 | package br.org.osgefic.fratello.dominio;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "grade_curricular")
public class GradeCurricular implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String tema;
private String descricao;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof GradeCurricular))
return false;
GradeCurricular other = (GradeCurricular) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
public String getTema() {
return tema;
}
public void setTema(String tema) {
this.tema = tema;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
} | gpl-2.0 |
GarciaPL/TrafficCity | src/main/java/pl/garciapl/trafficcity/dao/transport/TransportRequest.java | 2102 | package pl.garciapl.trafficcity.dao.transport;
import java.util.List;
/**
* Created by lukasz on 06.12.14.
*/
public class TransportRequest {
private Coordinates coordinates;
private Zoom zoom;
private Size size;
private String format;
private List<Layers> layers;
public TransportRequest(Coordinates coordinates, Zoom zoom, Size size, String format, List<Layers> layers) {
this.coordinates = coordinates;
this.zoom = zoom;
this.size = size;
this.format = format;
this.layers = layers;
}
public Coordinates getCoordinates() {
return coordinates;
}
public TransportRequest setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
return this;
}
public Zoom getZoom() {
return zoom;
}
public TransportRequest setZoom(Zoom zoom) {
this.zoom = zoom;
return this;
}
public Size getSize() {
return size;
}
public TransportRequest setSize(Size size) {
this.size = size;
return this;
}
public String getFormat() {
return format;
}
public TransportRequest setFormat(Format format) {
this.format = format.getFormat();
return this;
}
public List<Layers> getLayers() {
return layers;
}
public String getLayersAll() {
String all_layers = "";
for (int i = 0; i < this.layers.size(); i++) {
all_layers += this.layers.get(i).getLayer();
if (i + 1 < this.layers.size()) {
all_layers += ",";
}
}
return all_layers;
}
public TransportRequest setLayers(List<Layers> layers) {
this.layers = layers;
return this;
}
@Override
public String toString() {
return "TransportRequest{" +
"coordinates=" + coordinates +
", zoom=" + zoom +
", size=" + size +
", format='" + format + '\'' +
", layers=" + layers +
'}';
}
}
| gpl-2.0 |
hmsiccbl/screensaver | web/src/main/java/edu/harvard/med/screensaver/ui/screenresults/CollationOrder.java | 2765 | package edu.harvard.med.screensaver.ui.screenresults;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
public class CollationOrder implements Iterable<PlateOrderingGroup>
{
private List<PlateOrderingGroup> _ordering;
// a mapping to be used to easily input these orderings from a command line
public static Map<String,CollationOrder> orderings = Maps.newHashMap();
static {
orderings.put("PQCR", new CollationOrder(ImmutableList.of(PlateOrderingGroup.Plates,
PlateOrderingGroup.Quadrants, PlateOrderingGroup.Conditions, PlateOrderingGroup.Replicates, PlateOrderingGroup.Readouts)));
orderings.put("PQRC", new CollationOrder(ImmutableList.of(PlateOrderingGroup.Plates,
PlateOrderingGroup.Quadrants, PlateOrderingGroup.Replicates, PlateOrderingGroup.Conditions, PlateOrderingGroup.Readouts)));
orderings.put("CPQR", new CollationOrder(ImmutableList.of(PlateOrderingGroup.Conditions,
PlateOrderingGroup.Plates, PlateOrderingGroup.Quadrants, PlateOrderingGroup.Replicates, PlateOrderingGroup.Readouts)));
orderings.put("CRPQ", new CollationOrder(ImmutableList.of(PlateOrderingGroup.Conditions,
PlateOrderingGroup.Replicates, PlateOrderingGroup.Plates, PlateOrderingGroup.Quadrants, PlateOrderingGroup.Readouts)));
orderings.put("RPQC", new CollationOrder(ImmutableList.of(PlateOrderingGroup.Replicates,
PlateOrderingGroup.Plates, PlateOrderingGroup.Quadrants, PlateOrderingGroup.Conditions, PlateOrderingGroup.Readouts)));
orderings.put("RCPQ", new CollationOrder(ImmutableList.of(PlateOrderingGroup.Replicates,
PlateOrderingGroup.Conditions, PlateOrderingGroup.Plates, PlateOrderingGroup.Quadrants, PlateOrderingGroup.Readouts)));
}
public static CollationOrder getOrder(String ordering)
{
return orderings.get(ordering.toUpperCase());
}
public CollationOrder(List<PlateOrderingGroup> ordering)
{
_ordering = ordering;
}
public List<PlateOrderingGroup> getOrdering() { return _ordering; }
@Override
public String toString()
{
return Joiner.on(" \u2192 ").join(_ordering);
}
public String toShortString() {
String shortString = "";
for(PlateOrderingGroup p:this) {
shortString += p.toString().charAt(0);
}
return shortString;
}
@Override
public Iterator<PlateOrderingGroup> iterator()
{
return _ordering.iterator();
}
@Override
public int hashCode()
{
return _ordering.hashCode();
}
@Override
public boolean equals(Object other)
{
if (other instanceof CollationOrder) {
return _ordering.equals(((CollationOrder) other)._ordering);
}
return false;
}
}
| gpl-2.0 |
mooman219/AnotherRPG | src/main/java/com/gmail/mooman219/aaa/packet/Packet.java | 1587 | package com.gmail.mooman219.aaa.packet;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public abstract class Packet {
private static final List<Byte> packets = new ArrayList<Byte>();
public static Packet next(ObjectInputStream in) throws IOException {
byte id = in.readByte();
switch(id) {
case 0:
return new Packet0Equation().read(in);
case 1:
return new Packet1Answer().read(in);
case 2:
return new Packet2Text().read(in);
}
return null;
}
public static void send(ObjectOutputStream out, Packet p) {
if(packets.contains(p.getId())) {
try {
out.writeByte(p.getId());
p.write(out);
out.flush();
} catch(IOException ex) {
ex.printStackTrace();
}
} else {
throw new IllegalStateException("Packet ID does not exist..");
}
}
public static void registerPacket(byte id) {
if(packets.contains(id)) {
throw new IllegalStateException("Packet ID already exists.");
} else {
packets.add(id);
}
}
protected abstract void write(ObjectOutputStream out) throws IOException;
protected abstract Packet read(ObjectInputStream in) throws IOException;
public abstract byte getId();
}
| gpl-2.0 |
ablyx/teammates | src/main/java/teammates/ui/pagedata/InstructorCourseEnrollPageData.java | 821 | package teammates.ui.pagedata;
import teammates.common.datatransfer.attributes.AccountAttributes;
/**
* PageData: this is page data for 'Enroll' page for a course of an instructor
*/
public class InstructorCourseEnrollPageData extends PageData {
private String courseId;
private String enrollStudents;
public InstructorCourseEnrollPageData(AccountAttributes account, String courseId, String enrollStudents) {
super(account);
this.courseId = courseId;
this.enrollStudents = enrollStudents;
}
public String getCourseId() {
return courseId;
}
public String getEnrollStudents() {
return enrollStudents;
}
public String getInstructorCourseEnrollSaveLink() {
return getInstructorCourseEnrollSaveLink(courseId);
}
}
| gpl-2.0 |
cylong1016/NJULily | src/main/java/blservice/recordblservice/BusinessStateInputInfo.java | 876 | package blservice.recordblservice;
import dataenum.BillType;
import dataenum.Storage;
public class BusinessStateInputInfo {
/** 起始时间 */
public String beginDate;
/** 结束时间 */
public String endDate;
/** 客户名 */
public String clientName;
/** 业务员 */
public String salesman;
/** 仓库 */
public Storage storage;
/** 单据类型 */
public BillType billType;
/**
* 经营历程表的筛选条件
* @param beginDate
* @param endDate
* @param billType
* @param clientName
* @param salesman
* @param storage
*/
public BusinessStateInputInfo(String beginDate, String endDate, BillType billType, String clientName, String salesman, Storage storage) {
this.beginDate = beginDate;
this.endDate = endDate;
this.billType = billType;
this.clientName = clientName;
this.salesman = salesman;
this.storage = storage;
}
}
| gpl-2.0 |
besuikerd/AutoLogistics | src/main/java/com/besuikerd/autologistics/client/lib/gui/texture/scalable/ScalableTextureVerticalScroller.java | 2313 | package com.besuikerd.autologistics.client.lib.gui.texture.scalable;
import com.besuikerd.autologistics.common.lib.util.tuple.Vector4;
public enum ScalableTextureVerticalScroller implements IScalableTexture{
NORMAL(new Vector4(74, 1, 81, 2), new Vector4(74, 0, 81, 0), new Vector4(82, 1, 83, 3), new Vector4(74, 3, 81, 4), new Vector4(72, 1, 73, 3), new Vector4(72, 0, 73, 0), new Vector4(82, 0, 83, 0), new Vector4(82, 3, 83, 4), new Vector4(72, 3, 73, 4)),
ACTIVATED(new Vector4(74, 6, 81, 7), new Vector4(74, 5, 81, 5), new Vector4(82, 6, 83, 8), new Vector4(74, 8, 81, 9), new Vector4(72, 6, 73, 8), new Vector4(72, 5, 73, 5), new Vector4(82, 5, 83, 5), new Vector4(82, 8, 83, 9), new Vector4(72, 8, 73, 9)),
DISABLED(new Vector4(74, 11, 81, 12), new Vector4(74, 10, 81, 10), new Vector4(82, 11, 83, 13), new Vector4(74, 13, 81, 14), new Vector4(72, 11, 73, 13), new Vector4(72, 10, 73, 10), new Vector4(82, 10, 83, 10), new Vector4(72, 13, 73, 14), new Vector4(82, 13, 83, 14))
;
protected Vector4 background;
protected Vector4 edgeTop;
protected Vector4 edgeRight;
protected Vector4 edgeBottom;
protected Vector4 edgeLeft;
protected Vector4 cornerTL;
protected Vector4 cornerTR;
protected Vector4 cornerBR;
protected Vector4 cornerBL;
private ScalableTextureVerticalScroller(Vector4 background, Vector4 edgeTop, Vector4 edgeRight, Vector4 edgeBottom, Vector4 edgeLeft, Vector4 cornerTL, Vector4 cornerTR, Vector4 cornerBR, Vector4 cornerBL) {
this.background = background;
this.edgeTop = edgeTop;
this.edgeRight = edgeRight;
this.edgeBottom = edgeBottom;
this.edgeLeft = edgeLeft;
this.cornerTL = cornerTL;
this.cornerTR = cornerTR;
this.cornerBR = cornerBR;
this.cornerBL = cornerBL;
}
@Override
public Vector4 getTexture() {
return background;
}
@Override
public Vector4 edgeTop() {
return edgeTop;
}
@Override
public Vector4 edgeRight() {
return edgeRight;
}
@Override
public Vector4 edgeBottom() {
return edgeBottom;
}
@Override
public Vector4 edgeLeft() {
return edgeLeft;
}
@Override
public Vector4 cornerTL() {
return cornerTL;
}
@Override
public Vector4 cornerTR() {
return cornerTR;
}
@Override
public Vector4 cornerBR() {
return cornerBR;
}
@Override
public Vector4 cornerBL() {
return cornerBL;
}
}
| gpl-2.0 |
Vaculik/creatures-hunting | WebAppLayer/src/main/java/cz/muni/fi/pa165/hateoas/WeaponEfficiencyResourceAssembler.java | 1485 | package cz.muni.fi.pa165.hateoas;
import cz.muni.fi.pa165.controllers.WeaponEfficiencyRestController;
import cz.muni.fi.pa165.dto.WeaponEfficiencyDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.EntityLinks;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.mvc.ResourceAssemblerSupport;
import org.springframework.stereotype.Component;
/**
* @author Karel Vaculik
*/
@Component
public class WeaponEfficiencyResourceAssembler
extends ResourceAssemblerSupport<WeaponEfficiencyDTO, WeaponEfficiencyResource> {
private static final Logger logger = LoggerFactory.getLogger(WeaponEfficiencyResourceAssembler.class);
@Autowired
private EntityLinks entityLinks;
public WeaponEfficiencyResourceAssembler() {
super(WeaponEfficiencyRestController.class, WeaponEfficiencyResource.class);
}
@Override
public WeaponEfficiencyResource toResource(WeaponEfficiencyDTO weaponEfficiencyDTO) {
WeaponEfficiencyResource resource = new WeaponEfficiencyResource(weaponEfficiencyDTO);
Long id = weaponEfficiencyDTO.getId();
try {
Link self = entityLinks.linkToSingleResource(WeaponEfficiencyDTO.class, id).withSelfRel();
resource.add(self);
} catch (Exception ex) {
logger.error("Failed to create links.");
}
return resource;
}
}
| gpl-2.0 |
rollenholt/iConfig | iConfig-client/src/main/java/ren/wenchao/iconfig/Application.java | 682 | package ren.wenchao.iconfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
/**
* @author rollenholt
*/
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
| gpl-2.0 |
adamfisk/littleshoot-client | common/download/src/main/java/org/lastbamboo/common/download/LaunchFileTrackerAdapter.java | 838 | package org.lastbamboo.common.download;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.lang.math.LongRange;
/**
* Adapter class for file launchers. Can be used a stub for failed downloaders
* or for anything else.
*/
public class LaunchFileTrackerAdapter implements LaunchFileTracker
{
public int getActiveWriteCalls()
{
return 0;
}
public void onDownloadStopped()
{
}
public void onFailure()
{
}
public void onFileComplete()
{
}
public void waitForLaunchersToComplete()
{
}
public void write(OutputStream os, boolean cancelOnStreamClose)
throws IOException
{
}
public void onRangeComplete(LongRange range)
{
}
}
| gpl-2.0 |
identityxx/penrose-server | core/src/java/org/safehaus/penrose/schema/matchingRule/SubstringsMatchingRule.java | 3592 | /**
* Copyright 2009 Red Hat, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.safehaus.penrose.schema.matchingRule;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.safehaus.penrose.filter.SubstringFilter;
import java.util.Map;
import java.util.TreeMap;
import java.util.Collection;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
* @author Endi S. Dewata
*/
public class SubstringsMatchingRule {
public Logger log = LoggerFactory.getLogger(getClass());
public final static String CASE_IGNORE = "caseIgnoreSubstringsMatch";
public final static String CASE_EXACT = "caseExactSubstringsMatch";
public final static String NUMERIC_STRING = "numericStringSubstringsMatch";
public final static String OCTET_STRING = "octetStringSubstringsMatch";
public final static SubstringsMatchingRule DEFAULT = new SubstringsMatchingRule();
public static Map<String,SubstringsMatchingRule> instances = new TreeMap<String,SubstringsMatchingRule>();
static {
instances.put(CASE_IGNORE, DEFAULT);
instances.put(CASE_EXACT, DEFAULT);
instances.put(NUMERIC_STRING, DEFAULT);
instances.put(OCTET_STRING, DEFAULT);
}
public static SubstringsMatchingRule getInstance(String name) {
if (name == null) return DEFAULT;
SubstringsMatchingRule substringsMatchingRule = instances.get(name);
if (substringsMatchingRule == null) return DEFAULT;
return substringsMatchingRule;
}
public boolean compare(Object object, Collection<Object> substrings) {
log.debug("comparing ["+object+"] with "+substrings);
if (object == null) return false;
StringBuilder sb = new StringBuilder();
sb.append("^");
for (Object o : substrings) {
if (o.equals(SubstringFilter.STAR)) {
sb.append(".*");
} else {
String substring = (String) o;
sb.append(escape(substring));
}
}
sb.append("$");
Pattern pattern = Pattern.compile(sb.toString(), Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(object.toString());
return matcher.find();
}
public static String escape(String s) {
StringBuilder sb = new StringBuilder(s);
int i = 0;
while (i<sb.length()) {
char c = sb.charAt(i);
if (c == '\\' || c == '.' || c == '?' || c == '*'
|| c == '^' || c == '$' || c == '{' || c == '}'
|| c == '[' || c == ']' || c == '(' || c == ')') {
sb.replace(i, i+1, "\\"+c);
i += 2;
continue;
}
i++;
}
return sb.toString();
}
}
| gpl-2.0 |
damico/yapea | YapeaAndroid/src/org/jdamico/yapea/commons/Utils.java | 13490 | package org.jdamico.yapea.commons;
/*
* This file is part of YAPEA.
*
* YAPEA 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.
*
* YAPEA 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 YAPEA. If not, see <http://www.gnu.org/licenses/>.
*/
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.jdamico.yapea.crypto.CryptoUtils;
import org.jdamico.yapea.dataobjects.ConfigObj;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Environment;
import android.telephony.TelephonyManager;
public class Utils {
private static Utils INSTANCE = null;
private Utils(){}
public static Utils getInstance(){
if(null == INSTANCE) INSTANCE = new Utils();
return INSTANCE;
}
static final byte[] HEX_CHAR_TABLE = {
(byte)'0', (byte)'1', (byte)'2', (byte)'3',
(byte)'4', (byte)'5', (byte)'6', (byte)'7',
(byte)'8', (byte)'9', (byte)'a', (byte)'b',
(byte)'c', (byte)'d', (byte)'e', (byte)'f'
};
public ConfigObj getConfigFile(Context context) throws YapeaException{
ConfigObj ret = null;
File file = new File(context.getFilesDir(), Constants.CONFIG_FILE);
if(file.exists()){
ret = configFileToConfigObj(file);
}
return ret;
}
public ConfigObj configFileToConfigObj(File fXmlFile) throws YapeaException {
ConfigObj configObj = null;
DocumentBuilderFactory dbFactory = null;
DocumentBuilder dBuilder = null;
try {
dbFactory = DocumentBuilderFactory.newInstance();
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
String hash = (String) getDomTagAttribute(doc, Constants.XML_CONFIG_KEY_TAG, Constants.XML_CONFIG_KEY_HASH_ATTRIB);
String algo = (String) getDomTagAttribute(doc, Constants.XML_CONFIG_ALGO_TAG, Constants.XML_CONFIG_ALGO_TYPE_ATTRIB);
String panicPassword = (String) getDomTagAttribute(doc, Constants.XML_CONFIG_KEY_TAG, Constants.XML_CONFIG_KEY_PANICPASSWD_ATTRIB);
int panicNumber = Integer.parseInt( (String) getDomTagAttribute(doc, Constants.XML_CONFIG_KEY_TAG, Constants.XML_CONFIG_KEY_PANICNUMBER_ATTRIB) );
configObj = new ConfigObj(algo, hash, false, panicPassword, panicNumber);
} catch (NumberFormatException e) {
throw new YapeaException(e);
} catch (ParserConfigurationException e) {
throw new YapeaException(e);
} catch (SAXException e) {
throw new YapeaException(e);
} catch (IOException e) {
throw new YapeaException(e);
}
return configObj;
}
public void configObjToConfigFile(ConfigObj configObj, File file) throws YapeaException{
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
sb.append("<"+Constants.XML_CONFIG_ROOT_TAG+">\n");
sb.append("<"+Constants.XML_CONFIG_KEY_TAG+" "+Constants.XML_CONFIG_KEY_HASH_ATTRIB+"=\""+configObj.getHashedKey()+"\" "+Constants.XML_CONFIG_KEY_PANICPASSWD_ATTRIB+"=\""+configObj.getPanicPassword()+"\" "+Constants.XML_CONFIG_KEY_PANICNUMBER_ATTRIB+"=\""+configObj.getPanicNumber()+"\"/>\n");
sb.append("<"+Constants.XML_CONFIG_ALGO_TAG+" "+Constants.XML_CONFIG_ALGO_TYPE_ATTRIB+"=\""+configObj.getEncAlgo()+"\"/>\n");
sb.append("</"+Constants.XML_CONFIG_ROOT_TAG+">\n");
writeTextToFile(file, sb.toString());
}
public Object getDomTagAttribute(Document doc, String tag, String attribute) {
Object ret = null;
NodeList nList = doc.getElementsByTagName(tag);
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
ret = eElement.getAttribute(attribute);
}
}
return ret;
}
public boolean isAuthenticated(Context context, String passwd) {
boolean isAuthenticated = false;
String typedHash = null;
String storedHash = null;
if(context!=null){
File file = new File(context.getFilesDir(), Constants.CONFIG_FILE);
try {
typedHash = byteArrayToHexString(CryptoUtils.getInstance().getKeyHash(context, passwd.toCharArray()));
storedHash = configFileToConfigObj(file).getHashedKey();
} catch (Exception e) {e.printStackTrace();}
if(typedHash!=null && storedHash!=null && (typedHash.equals(storedHash)))isAuthenticated = true;
}
return isAuthenticated;
}
public void changeConfig(Context context, String oldPasswd, String newPasswd_a, String newPasswd_b, String algo, String panicPassword, int panicNumber) throws YapeaException {
if(context!=null){
File file = new File(context.getFilesDir(), Constants.CONFIG_FILE);
if(isAuthenticated(context, oldPasswd)){
if(null != newPasswd_a && null != newPasswd_b && (newPasswd_a.equals(newPasswd_b)) ){
byte[] hash = CryptoUtils.getInstance().getKeyHash(context, newPasswd_a.toCharArray());
String hashedKey;
try {
hashedKey = byteArrayToHexString(hash);
} catch (UnsupportedEncodingException e) {
throw new YapeaException(AppMessages.getInstance().getMessage("Utils.createConfig.failedToTransformKeyHash"), e);
}
if(panicPassword == null || panicPassword.length() == 0){
panicPassword = "null";
panicNumber = 0;
}else{
hash = CryptoUtils.getInstance().getKeyHash(context, panicPassword.toCharArray());
try {
panicPassword = byteArrayToHexString(hash);
} catch (UnsupportedEncodingException e) {
throw new YapeaException(AppMessages.getInstance().getMessage("Utils.createConfig.failedToTransformKeyHash"), e);
}
}
configObjToConfigFile(new ConfigObj(algo, hashedKey, false, panicPassword, panicNumber), file);
}else throw new YapeaException(AppMessages.getInstance().getMessage("Utils.changeConfig.diffPasswd"));
}else throw new YapeaException(AppMessages.getInstance().getMessage("Utils.changeConfig.wrongPasswd"));
}else throw new YapeaException(AppMessages.getInstance().getMessage("Utils.changeConfig.nullContext"));
}
public void createConfig(Context context, String oldPasswd, String newPasswd_a, String newPasswd_b, String algo, String panicPassword, int panicNumber) throws YapeaException {
File file = new File(context.getFilesDir(), Constants.CONFIG_FILE);
ConfigObj configObj = new ConfigObj();
if(context != null){
if(newPasswd_a.equals(newPasswd_b)){
byte[] hash = CryptoUtils.getInstance().getKeyHash(context, newPasswd_a.toCharArray());
try {
configObj.setHashedKey(byteArrayToHexString(hash));
} catch (UnsupportedEncodingException e) {
throw new YapeaException(AppMessages.getInstance().getMessage("Utils.createConfig.failedToTransformKeyHash"), e);
}
if(panicPassword == null || panicPassword.length() == 0){
panicPassword = "null";
panicNumber = 0;
}else{
hash = CryptoUtils.getInstance().getKeyHash(context, panicPassword.toCharArray());
try {
panicPassword = byteArrayToHexString(hash);
} catch (UnsupportedEncodingException e) {
throw new YapeaException(AppMessages.getInstance().getMessage("Utils.createConfig.failedToTransformKeyHash"), e);
}
}
configObj.setPanicPassword(panicPassword);
configObj.setPanicNumber(panicNumber);
}else throw new YapeaException(AppMessages.getInstance().getMessage("Utils.createConfig.diffPasswd"));
configObj.setEncAlgo(algo);
configObjToConfigFile(configObj, file);
}
}
public String getDeviceData(){
StringBuffer deviceData = new StringBuffer();
deviceData.append(Build.CPU_ABI+" ");
deviceData.append(Build.DEVICE+" ");
deviceData.append(Build.MANUFACTURER+" ");
deviceData.append(Build.MODEL+" ");
deviceData.append(Build.HARDWARE+" ");
return deviceData.toString();
}
public String getIMEI(Context context){
//<uses-permission android:name="android.permission.READ_PHONE_STATE" />
String imei = null;
try {
TelephonyManager mngr = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
imei = mngr.getDeviceId();
} catch (Exception e) {}
return imei;
}
public String byteArrayToHexString(byte[] raw) throws UnsupportedEncodingException
{
byte[] hex = new byte[2 * raw.length];
int index = 0;
for (byte b : raw) {
int v = b & 0xFF;
hex[index++] = HEX_CHAR_TABLE[v >>> 4];
hex[index++] = HEX_CHAR_TABLE[v & 0xF];
}
return new String(hex, "ASCII");
}
public void writeTextToFile(File file, String text) throws YapeaException {
FileWriter fw = null;
BufferedWriter out = null;
try {
fw = new FileWriter(file);
out = new BufferedWriter(fw);
out.write(text+"\n");
out.close();
} catch (IOException e) {
throw new YapeaException(AppMessages.getInstance().getMessage("Utils.writeTextToFile.failToWriteFile"), e);
} finally {
if(null != fw) try { fw.close(); } catch (IOException e) { throw new YapeaException(AppMessages.getInstance().getMessage("Utils.writeTextToFile.failToWriteFile"), e); }
if(null != out) try { out.close(); } catch (IOException e) { throw new YapeaException(AppMessages.getInstance().getMessage("Utils.writeTextToFile.failToWriteFile"), e); }
}
}
public String getYapeaImageDir() {
return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/.yapea/";
}
public String getCurrentDateTimeFormated(String format){
Date date = new Date();
Format formatter = new SimpleDateFormat(format);
String stime = formatter.format(date);
return stime;
}
public byte[] getBytesFromFile(File file) throws YapeaException {
InputStream is = null;
long length = file.length();
if (length > Integer.MAX_VALUE) {
throw new YapeaException(AppMessages.getInstance().getMessage("Utils.getBytesFromFile.fileTooLArge"));
}
byte[] bytes = new byte[(int)length];
int offset = 0;
int numRead = 0;
try {
is = new FileInputStream(file);
while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
} catch (IOException e) {
throw new YapeaException(e);
}finally{
if(null != is) try { is.close(); } catch (IOException e) { throw new YapeaException(e); }
}
if (offset < bytes.length) {
throw new YapeaException(new IOException("Could not completely read file "+file.getName()));
}
return bytes;
}
public void byteArrayToFile(byte[] bytes, String strFilePath) throws YapeaException{
FileOutputStream fos = null;
try {
fos = new FileOutputStream(strFilePath);
fos.write(bytes);
} catch (FileNotFoundException e) {
throw new YapeaException(e);
} catch (IOException e) {
throw new YapeaException(e);
} finally {
if(null!=fos)
try {
fos.close();
} catch (IOException e) {
throw new YapeaException(e);
}
}
}
public Bitmap byteArrayToBitmap(byte[] source){
return BitmapFactory.decodeByteArray(source , 0, source.length);
}
public void dumpAppData(Context context) {
clearCache();
deleteAllPictures();
File file = new File(context.getFilesDir(), Constants.CONFIG_FILE);
file.delete();
}
public void clearCache(){
if(StaticObj.KEY != null) StaticObj.KEY = null;
}
public byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
return data;
}
public int isPanicAuthenticated(Context context, String passwd, int countPanic) {
int ret = 0;
String typedHash = null;
String storedHash = null;
ConfigObj cfg = null;
if(context!=null){
File file = new File(context.getFilesDir(), Constants.CONFIG_FILE);
try {
cfg = configFileToConfigObj(file);
typedHash = byteArrayToHexString(CryptoUtils.getInstance().getKeyHash(context, passwd.toCharArray()));
storedHash = cfg.getPanicPassword();
} catch (Exception e) {e.printStackTrace();}
if(typedHash!=null && storedHash!=null && (typedHash.equals(storedHash))){
ret = 1;
if(countPanic+1 == cfg.getPanicNumber()) deleteAllPictures();
}
}
return ret;
}
private void deleteAllPictures() {
String yapeaDir = getYapeaImageDir();
File imageDir = new File(yapeaDir);
if(imageDir.exists()){
String[] contents = imageDir.list();
for (int i = 0; i < contents.length; i++) {
File f = new File(yapeaDir+contents[i]);
f.delete();
}
imageDir.delete();
}
}
}
| gpl-2.0 |
rebeca-lang/org.rebecalang.compiler | src/main/java/org/rebecalang/compiler/modelcompiler/corerebeca/objectmodel/TermPrimary.java | 4515 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-146
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2021.05.29 at 10:12:22 PM IRDT
//
package org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for TermPrimary complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="TermPrimary">
* <complexContent>
* <extension base="{http://rebecalang.org/compiler/modelcompiler/corerebecaexpression}PrimaryExpression">
* <sequence>
* <element name="label" type="{http://rebecalang.org/compiler/modelcompiler/corerebecaexpression}Label"/>
* <element name="parentSuffixPrimary" type="{http://rebecalang.org/compiler/modelcompiler/corerebecaexpression}ParentSuffixPrimary"/>
* <element name="indices" type="{http://rebecalang.org/compiler/modelcompiler/corerebecaexpression}Expression" maxOccurs="unbounded"/>
* </sequence>
* <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TermPrimary", namespace = "http://rebecalang.org/compiler/modelcompiler/corerebecaexpression", propOrder = {
"label",
"parentSuffixPrimary",
"indices"
})
public class TermPrimary
extends PrimaryExpression
{
@XmlElement(required = true)
protected Label label;
@XmlElement(required = true)
protected ParentSuffixPrimary parentSuffixPrimary;
@XmlElement(required = true)
protected List<Expression> indices;
@XmlAttribute(name = "name")
protected String name;
/**
* Gets the value of the label property.
*
* @return
* possible object is
* {@link Label }
*
*/
public Label getLabel() {
return label;
}
/**
* Sets the value of the label property.
*
* @param value
* allowed object is
* {@link Label }
*
*/
public void setLabel(Label value) {
this.label = value;
}
/**
* Gets the value of the parentSuffixPrimary property.
*
* @return
* possible object is
* {@link ParentSuffixPrimary }
*
*/
public ParentSuffixPrimary getParentSuffixPrimary() {
return parentSuffixPrimary;
}
/**
* Sets the value of the parentSuffixPrimary property.
*
* @param value
* allowed object is
* {@link ParentSuffixPrimary }
*
*/
public void setParentSuffixPrimary(ParentSuffixPrimary value) {
this.parentSuffixPrimary = value;
}
/**
* Gets the value of the indices property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the indices property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getIndices().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Expression }
*
*
*/
public List<Expression> getIndices() {
if (indices == null) {
indices = new ArrayList<Expression>();
}
return this.indices;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
}
| gpl-2.0 |
phantamanta44/SpacialResonance | src/main/java/io/github/phantamanta44/spaceres/block/base/ItemBlockState.java | 366 | package io.github.phantamanta44.spaceres.block.base;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public @interface ItemBlockState {
}
| gpl-2.0 |
palomagc/MovieChatter | src/icaro/aplicaciones/agentes/AgenteAplicacionGuia/tareas/DeducirGenero.java | 6770 | package icaro.aplicaciones.agentes.AgenteAplicacionGuia.tareas;
import icaro.aplicaciones.agentes.AgenteAplicacionGuia.objetivos.ObtenerActor;
import icaro.aplicaciones.informacion.Notificacion;
import icaro.aplicaciones.informacion.Vocabulario;
import icaro.aplicaciones.recursos.comunicacionChat.ItfUsoComunicacionChat;
import icaro.aplicaciones.recursos.comunicacionTMDB.ItfUsoComunicacionTMDB;
import icaro.aplicaciones.recursos.comunicacionTMDB.model.Genre;
import icaro.aplicaciones.recursos.comunicacionTMDB.model.Movie;
import icaro.aplicaciones.recursos.recursoUsuario.model.Valoracion;
import icaro.infraestructura.entidadesBasicas.NombresPredefinidos;
import icaro.infraestructura.entidadesBasicas.procesadorCognitivo.Objetivo;
import icaro.infraestructura.entidadesBasicas.procesadorCognitivo.TareaSincrona;
import icaro.infraestructura.recursosOrganizacion.recursoTrazas.imp.componentes.InfoTraza;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class DeducirGenero extends TareaSincrona {
/**
* Constructor
*
* @param Description
* of the Parameter
* @param Description
* of the Parameter
*/
// private Objetivo contextoEjecucionTarea = null;
@Override
public void ejecutar(Object... params) {
try {
// Objetivo
Objetivo obj = (Objetivo) params[0];
// Si hay un filtro con generos
if (Vocabulario.busqueda.getGenres().size() > 0) {
Notificacion notif = new Notificacion();
notif.setTipoNotificacion(Vocabulario.NombreTipoNotificacionComprobarDatosBusqueda);
getComunicator()
.enviarInfoAotroAgente(notif, Vocabulario.IdentAgenteAplicacionGuia);
}
// Si no hay generos en la busqueda actual intentamos deducir alguno, si no le
// preguntamos al usuario
else {
// Intentar deducir generos.
HashMap<Integer, Integer> historial = historialGenerosVistos(5);
boolean encontrado = false;
ArrayList<Integer> listaGenerosMasVistos = dameGenerosMasVistos(historial, 3);
encontrado = listaGenerosMasVistos.size() > 0;
if (encontrado) {
// TODO HAS DEDUCIDO UN GENERO: GUARDAR listaGenerosMasVistos EN LA LISTA PARA
// BUSCAR PELIS. (ADICIONALMENTE PODRIAMOS MOSTRAR UN MENSAJE AL USUARIO PARA
// QUE SEPA QUE LO HEMOS DEDUCIDO)
// TODO LANZAR UN OBJETIVO POR EJEMPLO EL DE PREGUNTAR SI QUIERE FILTRAR POR
// ALGUN ACTOR.
this.getEnvioHechos().actualizarHecho(new ObtenerActor());
} else {
// Si no se ha podido deducir un genero. Preguntamos al usuario.
// String identDeEstaTarea = this.getIdentTarea();
// String identAgenteOrdenante = this.getIdentAgente();
try {
// Se busca la interfaz del recurso en el repositorio de interfaces.
ItfUsoComunicacionChat recComunicacionChat = (ItfUsoComunicacionChat) NombresPredefinidos.REPOSITORIO_INTERFACES_OBJ
.obtenerInterfazUso(Vocabulario.IdentRecursoComunicacionChat);
if (recComunicacionChat != null) {
recComunicacionChat.comenzar(Vocabulario.IdentAgenteAplicacionGuia);
// Preguntar el genero que le apetece ver
String mensajeAenviar = Vocabulario.EligeGenero;
recComunicacionChat.enviarMensagePrivado(mensajeAenviar);
obj.setSolving(); // ObtenerGenero
this.getEnvioHechos().actualizarHecho(obj); // TODO OJO AQUI
// ACTUALIZAMOS OBJ A
// SOLVING!!!
}
} catch (Exception e) {
e.printStackTrace();
trazas.aceptaNuevaTraza(new InfoTraza(this.getIdentAgente(),
Vocabulario.ErrorEjecucionTarea + this.getIdentTarea() + e,
InfoTraza.NivelTraza.error));
}
}
}
} catch (Exception e) {
e.printStackTrace();
trazas.aceptaNuevaTraza(new InfoTraza(this.getIdentAgente(),
Vocabulario.ErrorEjecucionTarea + this.getIdentTarea() + e,
InfoTraza.NivelTraza.error));
}
}
private HashMap<Integer, Integer> historialGenerosVistos(int maximoNumeroPeliculasProcesar)
throws Exception {
ArrayList<Valoracion> listaValoraciones = Vocabulario.usuario.getValoraciones();
Iterator<Valoracion> itValoraciones = listaValoraciones.iterator();
// Vamos a utilizar el recurso TMDB para buscar las películas y acceder a su informacion.
ItfUsoComunicacionTMDB itfUsoComunicacionTMDB = (ItfUsoComunicacionTMDB) NombresPredefinidos.REPOSITORIO_INTERFACES_OBJ
.obtenerInterfazUso(Vocabulario.IdentRecursoComunicacionTMDB);
// Guardaremos para cada genero un contador de apariciones.
HashMap<Integer, Integer> historial = new HashMap<Integer, Integer>();
// TODO Las valoraciones de películas (caso: ya la he visto y le pongo X nota), deberían
// introducirse al final de la lista.
while (itValoraciones.hasNext() && maximoNumeroPeliculasProcesar > 0) { // Recorremos las
// valoraciones para
// saber las
// películas que ha
// visto, y por
// tanto sus generos
// asociados.
int idPelicula = Integer.parseInt(itValoraciones.next().getIdPelicula());
Movie movie = itfUsoComunicacionTMDB.getMovie(idPelicula, null); // language = NULL !!!
// ??? !!!
List<Genre> genres = movie.getGenres();
Iterator<Genre> itGenre = genres.iterator();
while (itGenre.hasNext()) {
int genreId = itGenre.next().getId();
if (historial.containsKey(genreId)) { // Si ya hay una peli que tenía un género lo
// aumentamos.
int count = historial.get(genreId);
count++;
historial.put(genreId, count);
} else {
historial.put(genreId, 1);
}
}
maximoNumeroPeliculasProcesar--;
}
return historial;
}
private ArrayList<Integer> dameGenerosMasVistos(HashMap<Integer, Integer> historialGeneros,
int vecesMinimas) {
ArrayList<Integer> masVistos = new ArrayList<Integer>();
int loMasVisto = 0;
Iterator<Map.Entry<Integer, Integer>> itHistorial = historialGeneros.entrySet().iterator();
while (itHistorial.hasNext()) { // Recorremos el historial de generos.
Map.Entry<Integer, Integer> movie = itHistorial.next();
if (movie.getValue() >= vecesMinimas && movie.getValue() >= loMasVisto) { // Si el
// numero de
// apariciones
// es >= que
// vecesMinimas.
if (movie.getValue() > loMasVisto) { // Si es > que el mas visto lo añadimos y
// borramos todo lo anterior.
masVistos = new ArrayList<Integer>(); // Creamos un array nuevo para borrar lo
// anterior.
}
masVistos.add(movie.getKey()); // Añadimos el id del género.
}
}
return masVistos;
}
}
| gpl-2.0 |
benjaminy/STuneLite | OldJavaImplementation/poi-3.2-FINAL/src/scratchpad/src/org/apache/poi/hwpf/usermodel/DocumentPosition.java | 1186 | /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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.
==================================================================== */
/**
* @author Ryan Ackley
*/
package org.apache.poi.hwpf.usermodel;
import org.apache.poi.hwpf.HWPFDocument;
public class DocumentPosition
extends Range
{
public DocumentPosition(HWPFDocument doc, int pos)
{
super(pos, pos, doc);
}
} | gpl-2.0 |
rafaelkalan/metastone | src/main/java/net/demilich/metastone/game/events/DrawCardEvent.java | 686 | package net.demilich.metastone.game.events;
import net.demilich.metastone.game.GameContext;
import net.demilich.metastone.game.cards.Card;
import net.demilich.metastone.game.entities.Entity;
public class DrawCardEvent extends GameEvent {
private final Card card;
private final int playerId;
public DrawCardEvent(GameContext context, int playerId, Card card) {
super(context);
this.playerId = playerId;
this.card = card;
}
public Card getCard() {
return card;
}
@Override
public Entity getEventTarget() {
return card;
}
@Override
public GameEventType getEventType() {
return GameEventType.DRAW_CARD;
}
public int getPlayerId() {
return playerId;
}
}
| gpl-2.0 |
PetoMichalak/iotPower | PATH2iot/PATHfinder/src/main/java/eu/uk/ncl/di/pet5o/PATH2iot/input/dataStreams/InputStreamEntryProperty.java | 1309 | package eu.uk.ncl.di.pet5o.PATH2iot.input.dataStreams;
/**
* Created by peto on 20/02/2017.
*
* Most inner class of input_streams json.
*/
public class InputStreamEntryProperty {
private String name;
private String asName;
private String type;
public InputStreamEntryProperty() {}
public InputStreamEntryProperty(String name, String type) {
this.name = name;
this.asName = name;
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
// attempt to follow same types as DotExpression is
// if (type.equals("String")) {
// return "java.lang.String";
// } else if (type.equals("Integer")) {
// return "java.lang.Integer";
// } else if (type.equals("Double")) {
// return "java.lang.Double";
// } else if (type.equals("Long")) {
// return "java.lang.Long";
// } else {
// return "unknown";
// }
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAsName() {
return asName;
}
public void setAsName(String asName) {
this.asName = asName;
}
}
| gpl-2.0 |
ferrybig/Minecraft-Overview-Mapper | src/main/java/me/ferrybig/java/minecraft/overview/mapper/textures/Cube.java | 3441 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package me.ferrybig.java.minecraft.overview.mapper.textures;
import java.util.Objects;
import javax.annotation.Nullable;
public class Cube {
private final Vector3d from;
private final Vector3d to;
private final @Nullable
Face down;
private final @Nullable
Face up;
private final @Nullable
Face north;
private final @Nullable
Face south;
private final @Nullable
Face west;
private final @Nullable
Face east;
private final Rotation rotation;
private final boolean shade;
public Cube(Vector3d from, Vector3d to, Face down, Face up, Face north, Face south, Face west, Face east, Rotation rotation) {
this(from, to, down, up, north, south, west, east, rotation, true);
}
public Cube(Vector3d from, Vector3d to, Face down, Face up, Face north, Face south, Face west, Face east, Rotation rotation, boolean shade) {
this.from = from;
this.to = to;
this.down = down;
this.up = up;
this.north = north;
this.south = south;
this.west = west;
this.east = east;
this.rotation = rotation;
this.shade = shade;
}
public Vector3d getFrom() {
return from;
}
public Vector3d getTo() {
return to;
}
public Face getDown() {
return down;
}
public Face getUp() {
return up;
}
public Face getNorth() {
return north;
}
public Face getSouth() {
return south;
}
public Face getWest() {
return west;
}
public Face getEast() {
return east;
}
public Rotation getRotation() {
return rotation;
}
public boolean isShade() {
return shade;
}
@Override
public String toString() {
return "Cube{" + "from=" + from + ", to=" + to + ", down=" + down + ", up=" + up + ", north=" + north + ", south=" + south + ", west=" + west + ", east=" + east + ", rotation=" + rotation + ", shade=" + shade + '}';
}
@Override
public int hashCode() {
int hash = 7;
hash = 41 * hash + Objects.hashCode(this.from);
hash = 41 * hash + Objects.hashCode(this.to);
hash = 41 * hash + Objects.hashCode(this.down);
hash = 41 * hash + Objects.hashCode(this.up);
hash = 41 * hash + Objects.hashCode(this.north);
hash = 41 * hash + Objects.hashCode(this.south);
hash = 41 * hash + Objects.hashCode(this.west);
hash = 41 * hash + Objects.hashCode(this.east);
hash = 41 * hash + Objects.hashCode(this.rotation);
hash = 41 * hash + (this.shade ? 1 : 0);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Cube other = (Cube) obj;
if (this.shade != other.shade) {
return false;
}
if (!Objects.equals(this.from, other.from)) {
return false;
}
if (!Objects.equals(this.to, other.to)) {
return false;
}
if (!Objects.equals(this.down, other.down)) {
return false;
}
if (!Objects.equals(this.up, other.up)) {
return false;
}
if (!Objects.equals(this.north, other.north)) {
return false;
}
if (!Objects.equals(this.south, other.south)) {
return false;
}
if (!Objects.equals(this.west, other.west)) {
return false;
}
if (!Objects.equals(this.east, other.east)) {
return false;
}
if (!Objects.equals(this.rotation, other.rotation)) {
return false;
}
return true;
}
}
| gpl-2.0 |
bhupal4all/jsf-practice | JsfAjax/src/main/java/com/ranga/jsf/bean/HelloBean.java | 282 | package com.ranga.jsf.bean;
import javax.faces.bean.ManagedBean;
@ManagedBean(name = "helloBean", eager = true)
public class HelloBean {
String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
} | gpl-2.0 |
jurkov/j-algo-mod | src/org/jalgo/module/avl/algorithm/CompareKey.java | 1985 | /*
* j-Algo - j-Algo is an algorithm visualization tool, especially useful for
* students and lecturers of computer science. It is written in Java and platform
* independent. j-Algo is developed with the help of Dresden University of
* Technology.
*
* Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jalgo.module.avl.algorithm;
import org.jalgo.module.avl.datastructure.*;
/**
* @author Ulrike Fischer
*
* The class <code>CompareKey</code> compares two keys with eacher other.
*/
public class CompareKey
extends Command {
private WorkNode wn;
/**
* @param wn reference to the position in the tree, holds the new key
*/
public CompareKey(WorkNode wn) {
super();
this.wn = wn;
}
/**
* Gets the WorkNode and compares its key with the key of the <code>nextToMe
* </code>
* node, returns 0 if the keys are the same, -1 if the key of the WorkNode
* is smaller and 1 otherwise.
*/
@SuppressWarnings("unchecked")
public void perform() {
Integer worknodekey = wn.getKey();
Integer nexttomekey = wn.getNextToMe().getKey();
results.add(worknodekey.compareTo(nexttomekey));
}
/**
* method is empty, undo not necessary
*/
public void undo() {
// this method has no effect
}
} | gpl-2.0 |
thc202/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest01171.java | 2349 | /**
* OWASP Benchmark Project v1.2beta
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The OWASP Benchmark 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, version 2.
*
* The OWASP Benchmark 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.
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest01171")
public class BenchmarkTest01171 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String param = "";
java.util.Enumeration<String> headers = request.getHeaders("vector");
if (headers.hasMoreElements()) {
param = headers.nextElement(); // just grab first element
}
String bar = new Test().doSomething(param);
Object[] obj = { "a", "b" };
response.getWriter().format(java.util.Locale.US,bar,obj);
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar = param;
if (param != null && param.length() > 1) {
StringBuilder sbxyz46134 = new StringBuilder(param);
bar = sbxyz46134.replace(param.length()-"Z".length(), param.length(),"Z").toString();
}
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| gpl-2.0 |
nhnb/marauroa | src/marauroa/server/game/dbcommand/LoadActiveCharacterCommand.java | 2737 | /***************************************************************************
* (C) Copyright 2009-2013 - Marauroa *
***************************************************************************
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
package marauroa.server.game.dbcommand;
import java.io.IOException;
import java.sql.SQLException;
import marauroa.common.Log4J;
import marauroa.common.Logger;
import marauroa.common.net.Channel;
import marauroa.server.db.DBTransaction;
import marauroa.server.game.db.CharacterDAO;
import marauroa.server.game.db.DAORegister;
import marauroa.server.game.messagehandler.DelayedEventHandler;
/**
* asynchronously loads a charcater's RPObject if the character is active
* and belongs to the account.
*
* @author hendrik
*/
public class LoadActiveCharacterCommand extends LoadCharacterCommand {
private static Logger logger = Log4J.getLogger(LoadActiveCharacterCommand.class);
/**
* Creates a new LoadCharacterCommand
*
* @param username name of account
* @param character name of character
*/
public LoadActiveCharacterCommand(String username, String character) {
super(username, character);
}
/**
* Creates a new LoadCharacterCommand
*
* @param username name of account
* @param character name of character
* @param callback DelayedEventHandler
* @param clientid optional parameter available to the callback
* @param channel optional parameter available to the callback
* @param protocolVersion version of protocol
*/
public LoadActiveCharacterCommand(String username, String character,
DelayedEventHandler callback, int clientid, Channel channel, int protocolVersion) {
super(username, character, callback, clientid, channel, protocolVersion);
}
@Override
public void execute(DBTransaction transaction) throws SQLException, IOException {
if (DAORegister.get().get(CharacterDAO.class).hasActiveCharacter(transaction, getUsername(), getCharacterName())) {
super.execute(transaction);
} else {
logger.warn("Trying to load a non active character. username: " + getUsername() + " charactername: " + getCharacterName());
}
}
}
| gpl-2.0 |
vishwaAbhinav/OpenNMS | opennms-services/src/test/java/org/opennms/netmgt/linkd/LinkdTest.java | 13126 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2010-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) 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.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.linkd;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.opennms.core.test.OpenNMSJUnit4ClassRunner;
import org.opennms.core.test.snmp.annotations.JUnitSnmpAgent;
import org.opennms.core.test.snmp.annotations.JUnitSnmpAgents;
import org.opennms.core.utils.LogUtils;
import org.opennms.netmgt.config.LinkdConfig;
import org.opennms.netmgt.config.linkd.Package;
import org.opennms.netmgt.dao.DataLinkInterfaceDao;
import org.opennms.netmgt.dao.NodeDao;
import org.opennms.netmgt.dao.db.JUnitConfigurationEnvironment;
import org.opennms.netmgt.dao.db.JUnitTemporaryDatabase;
import org.opennms.netmgt.model.DataLinkInterface;
import org.opennms.netmgt.model.NetworkBuilder;
import org.opennms.netmgt.model.OnmsNode;
import org.opennms.test.mock.MockLogAppender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
@RunWith(OpenNMSJUnit4ClassRunner.class)
@ContextConfiguration(locations= {
"classpath:/META-INF/opennms/applicationContext-dao.xml",
"classpath:/META-INF/opennms/applicationContext-commonConfigs.xml",
"classpath:/META-INF/opennms/applicationContext-daemon.xml",
"classpath:/META-INF/opennms/applicationContext-proxy-snmp.xml",
"classpath:/META-INF/opennms/mockEventIpcManager.xml",
"classpath:/META-INF/opennms/applicationContext-databasePopulator.xml",
"classpath:/META-INF/opennms/applicationContext-setupIpLike-enabled.xml",
"classpath:/META-INF/opennms/applicationContext-linkd.xml",
"classpath:/META-INF/opennms/applicationContext-minimal-conf.xml",
"classpath:/applicationContext-minimal-conf.xml",
"classpath:/applicationContext-linkd-test.xml"
})
@JUnitConfigurationEnvironment
@JUnitTemporaryDatabase
public class LinkdTest {
@Autowired
private Linkd m_linkd;
@Autowired
private NodeDao m_nodeDao;
@Autowired
private DataLinkInterfaceDao m_dataLinkInterfaceDao;
@Autowired
private LinkdConfig m_linkdConfig;
@Before
public void setUp() throws Exception {
// MockLogAppender.setupLogging(true);
Properties p = new Properties();
p.setProperty("log4j.logger.org.hibernate.SQL", "WARN");
MockLogAppender.setupLogging(p);
NetworkBuilder nb = new NetworkBuilder();
nb.addNode("test.example.com").setForeignSource("linkd").setForeignId("1").setSysObjectId(".1.3.6.1.4.1.1724.81").setType("A");
nb.addInterface("192.168.1.10").setIsSnmpPrimary("P").setIsManaged("M");
m_nodeDao.save(nb.getCurrentNode());
nb.addNode("laptop").setForeignSource("linkd").setForeignId("laptop").setSysObjectId(".1.3.6.1.4.1.8072.3.2.255").setType("A");
nb.addInterface("10.1.1.2").setIsSnmpPrimary("P").setIsManaged("M")
.addSnmpInterface(10).setIfType(6).setCollectionEnabled(true).setIfSpeed(1000000000).setPhysAddr("065568ae696c");
m_nodeDao.save(nb.getCurrentNode());
nb.addNode("cisco7200a").setForeignSource("linkd").setForeignId("cisco7200a").setSysObjectId(".1.3.6.1.4.1.9.1.222").setType("A");
nb.addInterface("10.1.1.1").setIsSnmpPrimary("P").setIsManaged("M")
.addSnmpInterface(3).setIfType(6).setCollectionEnabled(true).setIfSpeed(1000000000).setPhysAddr("ca0497a80038");
nb.addInterface("10.1.2.1").setIsSnmpPrimary("S").setIsManaged("M")
.addSnmpInterface(2).setIfType(6).setCollectionEnabled(false).setIfSpeed(100000000).setPhysAddr("ca0497a8001c");
m_nodeDao.save(nb.getCurrentNode());
nb.addNode("cisco7200b").setForeignSource("linkd").setForeignId("cisco7200b").setSysObjectId(".1.3.6.1.4.1.9.1.222").setType("A");
nb.addInterface("10.1.2.2").setIsSnmpPrimary("P").setIsManaged("M")
.addSnmpInterface(4).setIfType(6).setCollectionEnabled(true).setIfSpeed(10000000).setPhysAddr("ca0597a80038");
nb.addInterface("10.1.3.1").setIsSnmpPrimary("S").setIsManaged("M")
.addSnmpInterface(2).setIfType(6).setCollectionEnabled(false).setIfSpeed(100000000).setPhysAddr("ca0597a8001c");
nb.addInterface("10.1.4.1").setIsSnmpPrimary("S").setIsManaged("M")
.addSnmpInterface(1).setIfType(6).setCollectionEnabled(false).setIfSpeed(100000000).setPhysAddr("ca0597a80000");
m_nodeDao.save(nb.getCurrentNode());
nb.addNode("cisco3700").setForeignSource("linkd").setForeignId("cisco3700").setSysObjectId(".1.3.6.1.4.1.9.1.122").setType("A");
nb.addInterface("10.1.3.2").setIsSnmpPrimary("P").setIsManaged("M")
.addSnmpInterface(1).setIfType(6).setCollectionEnabled(true).setIfSpeed(10000000).setPhysAddr("c20197a50000");
nb.addInterface("10.1.6.1").setIsSnmpPrimary("S").setIsManaged("M")
.addSnmpInterface(3).setIfType(6).setCollectionEnabled(false).setIfSpeed(1000000000).setPhysAddr("c20197a50001");
m_nodeDao.save(nb.getCurrentNode());
nb.addNode("cisco2691").setForeignSource("linkd").setForeignId("cisco2691").setSysObjectId(".1.3.6.1.4.1.9.1.122").setType("A");
nb.addInterface("10.1.4.2").setIsSnmpPrimary("P").setIsManaged("M")
.addSnmpInterface(4).setIfType(6).setCollectionEnabled(false).setIfSpeed(10000000).setPhysAddr("c00397a70001");
nb.addInterface("10.1.5.1").setIsSnmpPrimary("S").setIsManaged("M")
.addSnmpInterface(2).setIfType(6).setCollectionEnabled(false).setIfSpeed(100000000).setPhysAddr("c00397a70000");
nb.addInterface("10.1.7.1").setIsSnmpPrimary("S").setIsManaged("M")
.addSnmpInterface(1).setIfType(6).setCollectionEnabled(false).setIfSpeed(100000000).setPhysAddr("c00397a70010");
m_nodeDao.save(nb.getCurrentNode());
nb.addNode("cisco1700").setForeignSource("linkd").setForeignId("cisco1700").setSysObjectId(".1.3.6.1.4.1.9.1.200").setType("A");
nb.addInterface("10.1.5.2").setIsSnmpPrimary("P").setIsManaged("M")
.addSnmpInterface(2).setIfType(6).setCollectionEnabled(true).setIfSpeed(100000000).setPhysAddr("d00297a60000");
m_nodeDao.save(nb.getCurrentNode());
/*
nb.addNode("cisco1700b").setForeignSource("linkd").setForeignId("cisco1700b").setSysObjectId(".1.3.6.1.4.1.9.1.200").setType("A");
nb.addInterface("10.1.5.1").setIsSnmpPrimary("P").setIsManaged("M")
.addSnmpInterface(2).setIfType(6).setCollectionEnabled(true).setIfSpeed(100000000).setPhysAddr("c00397a70000");
m_nodeDao.save(nb.getCurrentNode());
*/
nb.addNode("cisco3600").setForeignSource("linkd").setForeignId("cisco3600").setSysObjectId(".1.3.6.1.4.1.9.1.122").setType("A");
nb.addInterface("10.1.6.2").setIsSnmpPrimary("P").setIsManaged("M")
.addSnmpInterface(1).setIfType(6).setCollectionEnabled(true).setIfSpeed(100000000).setPhysAddr("cc0097a30000");
nb.addInterface("10.1.7.2").setIsSnmpPrimary("S").setIsManaged("M")
.addSnmpInterface(2).setIfType(6).setCollectionEnabled(false).setIfSpeed(100000000).setPhysAddr("cc0097a30010");
m_nodeDao.save(nb.getCurrentNode());
m_nodeDao.flush();
for (Package pkg : Collections.list(m_linkdConfig.enumeratePackage())) {
pkg.setForceIpRouteDiscoveryOnEthernet(true);
}
}
@After
public void tearDown() throws Exception {
for (final OnmsNode node : m_nodeDao.findAll()) {
m_nodeDao.delete(node);
}
m_nodeDao.flush();
}
@Test
@Ignore
@JUnitSnmpAgents(value={
@JUnitSnmpAgent(host="10.1.5.1", port=161, resource="classpath:linkd/cisco1700b.properties"),
@JUnitSnmpAgent(host="10.1.5.2", port=161, resource="classpath:linkd/cisco1700.properties")
})
public void testSimpleConnection() throws Exception {
m_nodeDao.delete(m_nodeDao.findByForeignId("linkd", "cisco2691"));
m_nodeDao.flush();
final NetworkBuilder nb = new NetworkBuilder();
nb.addNode("cisco1700b").setForeignSource("linkd").setForeignId("cisco1700b").setSysObjectId(".1.3.6.1.4.1.9.1.200").setType("A");
nb.addInterface("10.1.5.1").setIsSnmpPrimary("P").setIsManaged("M")
.addSnmpInterface(2).setIfType(6).setCollectionEnabled(false).setIfSpeed(100000000).setPhysAddr("c00397a70000");
m_nodeDao.save(nb.getCurrentNode());
m_nodeDao.flush();
final OnmsNode cisco1700 = m_nodeDao.findByForeignId("linkd", "cisco1700");
final OnmsNode cisco1700b = m_nodeDao.findByForeignId("linkd", "cisco1700b");
LogUtils.debugf(this, "cisco1700 = %s", cisco1700);
LogUtils.debugf(this, "cisco1700b = %s", cisco1700b);
assertTrue(m_linkd.scheduleNodeCollection(cisco1700.getId()));
assertTrue(m_linkd.scheduleNodeCollection(cisco1700b.getId()));
assertTrue(m_linkd.runSingleCollection(cisco1700.getId()));
assertTrue(m_linkd.runSingleCollection(cisco1700b.getId()));
final List<DataLinkInterface> ifaces = m_dataLinkInterfaceDao.findAll();
assertEquals("we should have found 2 data link", 2, ifaces.size());
}
@Test
@Ignore
@JUnitSnmpAgents(value={
@JUnitSnmpAgent(host="10.1.1.1", port=161, resource="classpath:linkd/cisco7200a.properties"),
@JUnitSnmpAgent(host="10.1.1.2", port=161, resource="classpath:linkd/laptop.properties"),
@JUnitSnmpAgent(host="10.1.2.2", port=161, resource="classpath:linkd/cisco7200b.properties"),
@JUnitSnmpAgent(host="10.1.3.2", port=161, resource="classpath:linkd/cisco3700.properties"),
@JUnitSnmpAgent(host="10.1.4.2", port=161, resource="classpath:linkd/cisco2691.properties"),
@JUnitSnmpAgent(host="10.1.5.2", port=161, resource="classpath:linkd/cisco1700.properties"),
@JUnitSnmpAgent(host="10.1.6.2", port=161, resource="classpath:linkd/cisco3600.properties")
})
public void testFakeCiscoNetwork() throws Exception {
final OnmsNode laptop = m_nodeDao.findByForeignId("linkd", "laptop");
final OnmsNode cisco7200a = m_nodeDao.findByForeignId("linkd", "cisco7200a");
final OnmsNode cisco7200b = m_nodeDao.findByForeignId("linkd", "cisco7200b");
final OnmsNode cisco3700 = m_nodeDao.findByForeignId("linkd", "cisco3700");
final OnmsNode cisco2691 = m_nodeDao.findByForeignId("linkd", "cisco2691");
final OnmsNode cisco1700 = m_nodeDao.findByForeignId("linkd", "cisco1700");
final OnmsNode cisco3600 = m_nodeDao.findByForeignId("linkd", "cisco3600");
assertTrue(m_linkd.scheduleNodeCollection(laptop.getId()));
assertTrue(m_linkd.scheduleNodeCollection(cisco7200a.getId()));
assertTrue(m_linkd.scheduleNodeCollection(cisco7200b.getId()));
assertTrue(m_linkd.scheduleNodeCollection(cisco3700.getId()));
assertTrue(m_linkd.scheduleNodeCollection(cisco2691.getId()));
assertTrue(m_linkd.scheduleNodeCollection(cisco1700.getId()));
assertTrue(m_linkd.scheduleNodeCollection(cisco3600.getId()));
assertTrue(m_linkd.runSingleCollection(laptop.getId()));
assertTrue(m_linkd.runSingleCollection(cisco7200a.getId()));
assertTrue(m_linkd.runSingleCollection(cisco7200b.getId()));
assertTrue(m_linkd.runSingleCollection(cisco3700.getId()));
assertTrue(m_linkd.runSingleCollection(cisco2691.getId()));
assertTrue(m_linkd.runSingleCollection(cisco1700.getId()));
assertTrue(m_linkd.runSingleCollection(cisco3600.getId()));
final List<DataLinkInterface> ifaces = m_dataLinkInterfaceDao.findAll();
assertEquals("we should have found 6 data links", 6, ifaces.size());
}
}
| gpl-2.0 |