answer
stringlengths
17
10.2M
package com.skelril.aurora.shard.instance.GoldRush; import com.sk89q.worldedit.blocks.BlockID; import com.sk89q.worldedit.blocks.ItemID; import com.sk89q.worldedit.bukkit.BukkitPlayer; import com.sk89q.worldedit.bukkit.BukkitUtil; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.World; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import com.skelril.aurora.economic.store.AdminStoreComponent; import com.skelril.aurora.items.custom.CustomItemCenter; import com.skelril.aurora.items.custom.CustomItems; import com.skelril.aurora.modifier.ModifierType; import com.skelril.aurora.shard.instance.BukkitShardInstance; import com.skelril.aurora.util.*; import com.skelril.aurora.util.item.ItemUtil; import com.skelril.aurora.util.player.PlayerRespawnProfile_1_7_10; import net.milkbowl.vault.economy.Economy; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.block.Chest; import org.bukkit.block.Sign; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.material.Lever; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import static com.sk89q.commandbook.CommandBook.inst; import static com.skelril.aurora.modifier.ModifierComponent.getModifierManager; import static com.zachsthings.libcomponents.bukkit.BasePlugin.server; public class GoldRushInstance extends BukkitShardInstance<GoldRushShard> implements Runnable { // Constants private static final double FEE_MINIMUM = 100; private static final double FEE_MULTIPLIER = .005; private CuboidRegion roomOne, roomTwo; private CuboidRegion doorOne, doorTwo; // Block - Should be flipped private ConcurrentHashMap<Location, Boolean> leverBlocks = new ConcurrentHashMap<>(); private List<Location> floodBlocks = new ArrayList<>(); private List<Location> chestBlocks = new ArrayList<>(); // Block - Is unlocked private List<Location> locks = new ArrayList<>(); private Location rewardChest; // Session private long startTime = -1; private Map<UUID, Double> origonalCharge = new HashMap<>(); private double lootSplit = 0; private int playerMod = 0; private int floodBlockType = BlockID.WATER; private boolean keysTriggered = false; private boolean checkingKeys = true; private boolean leversTriggered = false; private boolean checkingLevers = true; private long lastLeverSwitch = System.currentTimeMillis(); private long lastFlood = System.currentTimeMillis(); public GoldRushInstance(GoldRushShard shard, World world, ProtectedRegion region) { super(shard, world, region); setup(); remove(); } private void setup() { com.sk89q.worldedit.Vector offset = getRegion().getMinimumPoint(); rewardChest = new Location(getBukkitWorld(), offset.getX() + 15, offset.getY() + 2, offset.getZ() + 6); roomOne = new CuboidRegion(offset.add(1, 1, 36), offset.add(29, 7, 74)); roomTwo = new CuboidRegion(offset.add(11, 1, 17), offset.add(19, 7, 35)); doorOne = new CuboidRegion(offset.add(14, 1, 36), offset.add(16, 3, 36)); doorTwo = new CuboidRegion(offset.add(14, 1, 16), offset.add(16, 3, 16)); findChestAndKeys(); // Setup room one findLeversAndFloodBlocks(); // Setup room two } @Override public void prepare() { resetChestAndKeys(); resetLevers(); resetFloodType(); drainAll(); setDoor(doorOne, BlockID.IRON_BLOCK); setDoor(doorTwo, BlockID.IRON_BLOCK); } @Override public void cleanUp() { resetChestAndKeys(); super.cleanUp(); } public void start() { startTime = System.currentTimeMillis(); // Reset start clock populateChest(); // Add content } public boolean isLocked() { return startTime != -1; } public boolean isComplete() { return checkKeys() && checkLevers(); } private void findChestAndKeys() { com.sk89q.worldedit.Vector min = roomOne.getMinimumPoint(); com.sk89q.worldedit.Vector max = roomOne.getMaximumPoint(); int minX = min.getBlockX(); int minZ = min.getBlockZ(); int minY = min.getBlockY(); int maxX = max.getBlockX(); int maxZ = max.getBlockZ(); int maxY = max.getBlockY(); BlockState block; for (int x = minX; x <= maxX; x++) { for (int z = minZ; z <= maxZ; z++) { for (int y = maxY; y >= minY; --y) { block = getBukkitWorld().getBlockAt(x, y, z).getState(); if (!block.getChunk().isLoaded()) block.getChunk().load(); if (block.getTypeId() == BlockID.CHEST) { ((Chest) block).getInventory().clear(); block.update(true); chestBlocks.add(block.getLocation()); } else if (block.getTypeId() == BlockID.WALL_SIGN) { ((Sign) block).setLine(2, "- Locked -"); ((Sign) block).setLine(3, "Unlocked"); block.update(true); locks.add(block.getLocation()); } } } } } private static final ItemStack[] keys = new ItemStack[]{ new ItemStack(BlockID.CLOTH, 1, (short) 11), new ItemStack(BlockID.CLOTH, 1, (short) 14) }; public ItemStack getBlueKey() { return keys[0].clone(); } public ItemStack getRedKey() { return keys[1].clone(); } private void populateChest() { for (Location chest : chestBlocks) { if (chest.getBlock().getTypeId() != BlockID.CHEST) continue; Chest chestState = (Chest) chest.getBlock().getState(); Inventory inventory = chestState.getBlockInventory(); int iterationTimes = ChanceUtil.getRandom(27); for (int i = iterationTimes; i > 0; --i) { ItemStack targetStack; if (ChanceUtil.getChance(1000)) { targetStack = CustomItemCenter.build(CustomItems.PHANTOM_GOLD, ChanceUtil.getRandom(6)); } else { targetStack = new ItemStack(ItemID.GOLD_BAR, ChanceUtil.getRandom(3)); } inventory.setItem(ChanceUtil.getRandom(inventory.getSize()) - 1, targetStack); } if (ChanceUtil.getChance(300 / iterationTimes)) { inventory.addItem(CustomItemCenter.build(CustomItems.PIXIE_DUST, ChanceUtil.getRandom(12))); } if (ChanceUtil.getChance(10000 / iterationTimes)) { inventory.addItem(CustomItemCenter.build(CustomItems.PHANTOM_HYMN)); } chestState.update(true); } for (int i = 0; i < 2; i++) { Block block = CollectionUtil.getElement(chestBlocks).getBlock(); Chest chest = (Chest) block.getState(); chest.getInventory().setItem(ChanceUtil.getRandom(chest.getBlockInventory().getSize() - 1), keys[i].clone()); chest.update(true); } } private void resetChestAndKeys() { Chest chestState; for (Location chest : chestBlocks) { if (chest.getBlock().getTypeId() != BlockID.CHEST) continue; chestState = (Chest) chest.getBlock().getState(); chestState.getBlockInventory().clear(); chestState.update(true); } Sign signState; for (Location lock : locks) { signState = (Sign) lock.getBlock().getState(); signState.setLine(2, "- Locked -"); signState.setLine(3, "Unlocked"); signState.update(true); } keysTriggered = false; checkingKeys = true; } private void findLeversAndFloodBlocks() { com.sk89q.worldedit.Vector min = roomTwo.getMinimumPoint(); com.sk89q.worldedit.Vector max = roomTwo.getMaximumPoint(); int minX = min.getBlockX(); int minZ = min.getBlockZ(); int minY = min.getBlockY(); int maxX = max.getBlockX(); int maxZ = max.getBlockZ(); int maxY = max.getBlockY(); BlockState block; for (int x = minX; x <= maxX; x++) { for (int z = minZ; z <= maxZ; z++) { for (int y = maxY; y >= minY; --y) { block = getBukkitWorld().getBlockAt(x, y, z).getState(); if (!block.getChunk().isLoaded()) block.getChunk().load(); if (block.getTypeId() == BlockID.LEVER) { Lever lever = (Lever) block.getData(); lever.setPowered(false); block.setData(lever); block.update(true); leverBlocks.put(block.getLocation(), !ChanceUtil.getChance(3)); for (int i = y; i < maxY; i++) { block = getBukkitWorld().getBlockAt(x, i, z).getState(); if (block.getTypeId() == BlockID.AIR) { floodBlocks.add(block.getLocation()); break; } } break; // One lever a column only } } } } } public boolean checkLevers() { if (!checkingLevers) { return leversTriggered; } for (Map.Entry<Location, Boolean> lever : leverBlocks.entrySet()) { Lever aLever = (Lever) lever.getKey().getBlock().getState().getData(); if (aLever.isPowered() != lever.getValue()) return false; } return true; } public void unlockLevers() { drainAll(); setDoor(doorTwo, BlockID.AIR); leversTriggered = true; checkingLevers = false; } private void resetLevers() { leversTriggered = false; checkingLevers = true; BlockState state; for (Location entry : leverBlocks.keySet()) { state = entry.getBlock().getState(); Lever lever = (Lever) state.getData(); lever.setPowered(false); state.setData(lever); state.update(true); leverBlocks.put(entry, !ChanceUtil.getChance(3)); } } public Location getRewardChestLoc() { return rewardChest; } @Override public void expirePlayers() { if (isComplete()) { getContained(Player.class).stream().forEach(this::payPlayer); } else { getContained(Player.class).stream().forEach(p -> p.setHealth(0)); } } @Override public void teleportTo(com.sk89q.worldedit.entity.Player... players) { for (com.sk89q.worldedit.entity.Player player : players) { if (player instanceof BukkitPlayer) { Player aPlayer = ((BukkitPlayer) player).getPlayer(); double balance = getMaster().getEcon().getBalance(aPlayer); double fee = Math.min(balance, Math.max(FEE_MINIMUM, balance * FEE_MULTIPLIER)); if (fee > balance) { ChatUtil.sendError(aPlayer, "You don't have enough money to join this instance."); continue; } else { ChatUtil.sendWarning(aPlayer, "[Partner] Ey kid, I'm going to take some cash from ya."); ChatUtil.sendNotice(aPlayer, "[Partner] Ya know, just in case you get caught or somethin..."); ChatUtil.sendNotice(aPlayer, "[Partner] Thief's honor, I swear!"); } getMaster().getEcon().withdrawPlayer(aPlayer, fee); origonalCharge.put(player.getUniqueId(), fee); // Teleport Location location; do { do { location = BukkitUtil.toLocation( getBukkitWorld(), LocationUtil.pickLocation( roomOne.getMinimumPoint(), roomOne.getMaximumPoint() ) ); location.setY(roomOne.getMinimumPoint().getBlockY()); } while (location.getBlock().getTypeId() != BlockID.AIR); aPlayer.teleport(location); } while (!contains(aPlayer)); // Reset vitals aPlayer.setHealth(aPlayer.getMaxHealth()); aPlayer.setFoodLevel(20); aPlayer.setSaturation(20F); aPlayer.setExhaustion(0F); getMaster().getManager().setRespawnProfile( new PlayerRespawnProfile_1_7_10( aPlayer, 0, KeepAction.KEEP, KeepAction.KEEP, KeepAction.KEEP, KeepAction.KEEP ) ); aPlayer.getInventory().setArmorContents(null); aPlayer.getInventory().clear(); // Partner talk server().getScheduler().runTaskLater(inst(), () -> { ChatUtil.sendNotice(aPlayer, "[Partner] I've disabled the security systems for now."); server().getScheduler().runTaskLater(inst(), () -> { ChatUtil.sendWarning(aPlayer, "[Partner] For your sake kid I hope you can move quickly."); }, 20); }, 20); } } Collection<Player> cPlayers = getContained(Player.class); Iterator<Player> it = cPlayers.iterator(); while (it.hasNext()) { Player next = it.next(); Double origCharge = origonalCharge.get(next.getUniqueId()); if (origCharge == null) { getMaster().getManager().leaveInstance(next); it.remove(); continue; } lootSplit += Math.max(ChanceUtil.getRangedRandom(11.52, 34.56), origCharge * .3); } lootSplit /= cPlayers.size(); playerMod = Math.max(1, cPlayers.size() / 2); if (ChanceUtil.getChance(35)) lootSplit *= 10; if (ChanceUtil.getChance(15)) lootSplit *= 2; if (getModifierManager().isActive(ModifierType.QUAD_GOLD_RUSH)) lootSplit *= 4; start(); } @Override public void run() { if (!isLocked()) return; // If it's not locked things haven't been started yet if (System.currentTimeMillis() - startTime > TimeUnit.MINUTES.toMillis(7) || isEmpty()) { expire(); return; } equalize(); if (checkKeys()) { unlockKeys(); if (LocationUtil.containsPlayer(getBukkitWorld(), roomOne)) { setDoor(doorOne, BlockID.AIR); } else { setDoor(doorOne, BlockID.IRON_BLOCK); if (checkLevers()) { unlockLevers(); } else { randomizeLevers(); checkFloodType(); flood(); } } } } public void equalize() { getContained(org.bukkit.entity.Player.class).forEach(getMaster().getAdmin()::standardizePlayer); } public void refundPlayer(Player player) { Double fee = origonalCharge.get(player.getUniqueId()); // They didn't pay, CHEATER!!! if (fee == null) return; getMaster().getEcon().depositPlayer(player, fee); getMaster().getManager().leaveInstance(player); ChatUtil.sendNotice(player, "[Partner] These @$#&!@# restarts... Here, have your bail money..."); } public boolean payPlayer(Player player) { Double fee = origonalCharge.get(player.getUniqueId()); // They didn't pay, CHEATER!!! if (fee == null) return false; Economy econ = getMaster().getEcon(); ItemStack[] itemStacks = player.getInventory().getContents(); double goldValue = 0; double itemValue = 0; for (ItemStack is : itemStacks) { if (is == null) continue; // Static values switch (is.getTypeId()) { case ItemID.GOLD_NUGGET: ++goldValue; case ItemID.GOLD_BAR: if (ItemUtil.isItem(is, CustomItems.PHANTOM_GOLD)) { goldValue += 100; } else { goldValue += 9; } continue; case BlockID.GOLD_BLOCK: goldValue += 81; continue; default: double mkVal = AdminStoreComponent.priceCheck(is, true); if (mkVal > 0) { itemValue += mkVal; } } } ChatUtil.sendNotice(player, "You obtain: "); ChatUtil.sendNotice(player, " - Bail: " + ChatUtil.makeCountString(ChatColor.YELLOW, econ.format(fee), ".")); ChatUtil.sendNotice(player, " - Split: " + ChatUtil.makeCountString(ChatColor.YELLOW, econ.format(lootSplit), ".")); if (goldValue > 0) { ChatUtil.sendNotice(player, " - Gold: " + ChatUtil.makeCountString(ChatColor.YELLOW, econ.format(goldValue), ".")); } if (itemValue > 0) { ChatUtil.sendNotice(player, " - Items: " + ChatUtil.makeCountString(ChatColor.YELLOW, econ.format(itemValue), ".")); } getMaster().getEcon().depositPlayer(player, fee + lootSplit + goldValue + itemValue); getMaster().getManager().leaveInstance(player); return true; } public List<Location> getLockLocations() { return locks; } public boolean checkKeys() { if (!checkingKeys) { return keysTriggered; } for (Location lock : locks) { Sign aSign = (Sign) lock.getBlock().getState(); if (aSign.getLine(2).startsWith("-")) return false; } return true; } public void unlockKeys() { keysTriggered = true; checkingKeys = false; } private void setDoor(CuboidRegion door, int typeId) { com.sk89q.worldedit.Vector min = door.getMinimumPoint(); com.sk89q.worldedit.Vector max = door.getMaximumPoint(); int minX = min.getBlockX(); int minZ = min.getBlockZ(); int minY = min.getBlockY(); int maxX = max.getBlockX(); int maxZ = max.getBlockZ(); int maxY = max.getBlockY(); for (int x = minX; x <= maxX; x++) { for (int z = minZ; z <= maxZ; z++) { for (int y = minY; y <= maxY; y++) { Block block = getBukkitWorld().getBlockAt(x, y, z); if (!block.getChunk().isLoaded()) block.getChunk().load(); block.setTypeId(typeId); } } } } private void drainAll() { com.sk89q.worldedit.Vector min = roomTwo.getMinimumPoint(); com.sk89q.worldedit.Vector max = roomTwo.getMaximumPoint(); int minX = min.getBlockX(); int minZ = min.getBlockZ(); int minY = min.getBlockY(); int maxX = max.getBlockX(); int maxZ = max.getBlockZ(); int maxY = max.getBlockY(); for (int x = minX; x <= maxX; x++) { for (int z = minZ; z <= maxZ; z++) { for (int y = maxY; y >= minY; --y) { Block block = getBukkitWorld().getBlockAt(x, y, z); if (EnvironmentUtil.isLiquid(block.getTypeId())) { block.setTypeId(BlockID.AIR); } } } } } private void randomizeLevers() { BlockState state; Location mutable; if (System.currentTimeMillis() - lastLeverSwitch >= TimeUnit.SECONDS.toMillis(14)) { for (Location entry : leverBlocks.keySet()) { state = entry.getBlock().getState(); Lever lever = (Lever) state.getData(); lever.setPowered(false); state.setData(lever); state.update(true); leverBlocks.put(entry, !ChanceUtil.getChance(3)); } lastLeverSwitch = System.currentTimeMillis(); randomizeLevers(); } else if (System.currentTimeMillis() - lastLeverSwitch == 0) { for (Map.Entry<Location, Boolean> entry : leverBlocks.entrySet()) { mutable = entry.getKey().clone(); mutable.add(0, -1, 0); state = mutable.getBlock().getState(); state.setTypeId(BlockID.REDSTONE_LAMP_OFF); state.update(true); } server().getScheduler().runTaskLater(inst(), () -> { BlockState aState; Location aMutable; for (Map.Entry<Location, Boolean> entry : leverBlocks.entrySet()) { aMutable = entry.getKey().clone(); aMutable.add(0, -1, 0); aState = aMutable.getBlock().getState(); if (entry.getValue()) aState.setTypeId(BlockID.REDSTONE_LAMP_ON); else aState.setTypeId(BlockID.REDSTONE_LAMP_OFF); aState.update(true); } server().getScheduler().runTaskLater(inst(), this::randomizeLevers, 15); }, 15); } else { for (Location entry : leverBlocks.keySet()) { mutable = entry.clone(); mutable.add(0, -1, 0); state = mutable.getBlock().getState(); state.setTypeId(BlockID.REDSTONE_LAMP_OFF); state.update(true); } } } private void checkFloodType() { for (org.bukkit.entity.Player player : getContained(org.bukkit.entity.Player.class)) { if (ItemUtil.findItemOfName(player.getInventory().getContents(), CustomItems.PHANTOM_HYMN.toString())) { if (floodBlockType != BlockID.LAVA) { drainAll(); // Force away all water floodBlockType = BlockID.LAVA; } break; } } } private void flood() { if (System.currentTimeMillis() - startTime >= TimeUnit.SECONDS.toMillis((3 * 60) / playerMod)) { for (Location floodBlock : floodBlocks) { floodBlock.getBlock().setTypeId(floodBlockType); } if (System.currentTimeMillis() - lastFlood >= TimeUnit.SECONDS.toMillis(30 / Math.max(1, playerMod))) { com.sk89q.worldedit.Vector min = roomTwo.getMinimumPoint(); com.sk89q.worldedit.Vector max = roomTwo.getMaximumPoint(); int minX = min.getBlockX(); int minZ = min.getBlockZ(); int minY = min.getBlockY(); int maxX = max.getBlockX(); int maxZ = max.getBlockZ(); int maxY = max.getBlockY(); for (int x = minX; x <= maxX; x++) { for (int z = minZ; z <= maxZ; z++) { for (int y = minY; y <= maxY; y++) { Block block = getBukkitWorld().getBlockAt(x, y, z); if (!block.getChunk().isLoaded()) block.getChunk().load(); if (block.getTypeId() == BlockID.AIR) { block.setTypeIdAndData(floodBlockType, (byte) 0, false); break; } } } } lastFlood = System.currentTimeMillis(); } } } private void resetFloodType() { floodBlockType = BlockID.WATER; } }
package com.squareup.cascading2.serialization; import cascading.tuple.Comparison; import cascading.tuple.StreamComparator; import cascading.tuple.hadoop.io.BufferedInputStream; import com.google.protobuf.CodedInputStream; import com.google.protobuf.Message; import com.squareup.cascading2.util.Util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Comparator; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.io.WritableComparator; import org.apache.hadoop.io.serializer.Deserializer; import org.apache.hadoop.io.serializer.Serialization; import org.apache.hadoop.io.serializer.Serializer; import sun.reflect.generics.reflectiveObjects.NotImplementedException; public class ProtobufSerialization<T extends Message> extends Configured implements Serialization<T>, Comparison<T> { @Override public boolean accept(Class<?> aClass) { return Message.class.isAssignableFrom(aClass); } @Override public Serializer<T> getSerializer(Class<T> messageClass) { return new ProtobufSerializer(); } @Override public Deserializer<T> getDeserializer(Class<T> messageClass) { return new ProtobufDeserializer(messageClass); } @Override public Comparator<T> getComparator(Class<T> messageClass) { return new ProtobufComparator(); } private static class ProtobufSerializer<T extends Message> implements Serializer<T> { private OutputStream outputStream; @Override public void open(OutputStream outputStream) throws IOException { this.outputStream = outputStream; } @Override public void serialize(T message) throws IOException { message.writeDelimitedTo(outputStream); outputStream.flush(); } @Override public void close() throws IOException { outputStream.close(); } } private static class ProtobufDeserializer<T extends Message> implements Deserializer<T> { private InputStream inputStream; private final Message.Builder builder; public ProtobufDeserializer(Class<T> messageClass) { builder = Util.builderFromMessageClass(messageClass.getName()); } @Override public void open(InputStream inputStream) throws IOException { this.inputStream = inputStream; } @Override public T deserialize(T message) throws IOException { builder.clear(); builder.mergeDelimitedFrom(inputStream); return (T)builder.build(); } @Override public void close() throws IOException { inputStream.close(); } } private static class ProtobufComparator<T extends Message> implements Comparator<T>, StreamComparator<BufferedInputStream> { @Override public int compare(T message, T message1) { try { ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); message.writeTo(baos1); ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); message1.writeTo(baos2); byte[] b1 = baos1.toByteArray(); byte[] b2 = baos2.toByteArray(); return WritableComparator.compareBytes(b1, 0, b1.length, b2, 0, b2.length); } catch (IOException e) { throw new RuntimeException(e); } } @Override public int compare(BufferedInputStream lhs, BufferedInputStream rhs) { CodedInputStream clhs = CodedInputStream.newInstance(lhs); CodedInputStream crhs = CodedInputStream.newInstance(rhs); try { int lhsLen = clhs.readRawVarint32(); // byte[] lhsBytes = new byte[lhsLen]; // lhs.read(lhsBytes, 0, lhsLen); int rhsLen = crhs.readRawVarint32(); // byte[] rhsBytes = new byte[lhsLen]; // lhs.read(rhsBytes, 0, rhsLen); // return WritableComparator.compareBytes(lhsBytes, 0, lhsLen, rhsBytes, 0, rhsLen); return WritableComparator.compareBytes(lhs.getBuffer(), lhs.getPosition(), lhsLen, rhs.getBuffer(), rhs.getPosition(), rhsLen); } catch (IOException e) { throw new RuntimeException(e); } } } }
package com.thinkbiganalytics.scheduler.quartz; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.scheduling.quartz.CronTriggerFactoryBean; import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean; import java.util.UUID; /** * Configures Quartz to run a job with one step */ public class SimpleSchedulerSetup implements InitializingBean { @Autowired private QuartzScheduler quartzScheduler; @Autowired private ApplicationContext applicationContext; private Object jobRunner; private String cronExpression; private String targetMethod; private String jobName; private String groupName; /** * Configure the quartz scheduler * @param jobRunner the target job runner (implementing a run() method) * @param cronExpression a cron expression for the schedule */ public SimpleSchedulerSetup(Object jobRunner, String cronExpression) { this(jobRunner, "run", cronExpression); } /** * Configure the quartz scheduler * @param jobRunner the target job runner * @param targetMethod the method to invoke on the job runner * @param cronExpression a cron expression for the schedule * */ public SimpleSchedulerSetup(Object jobRunner, String targetMethod, String cronExpression) { this.jobRunner = jobRunner; this.cronExpression = cronExpression; this.targetMethod = targetMethod; } @Override public void afterPropertiesSet() throws Exception { MethodInvokingJobDetailFactoryBean jobDetailFactory = new MethodInvokingJobDetailFactoryBean(); jobDetailFactory.setTargetObject(this.jobRunner); jobDetailFactory.setTargetMethod(this.targetMethod); jobDetailFactory.setName(this.jobName); jobDetailFactory.setGroup(this.groupName); applicationContext.getAutowireCapableBeanFactory().initializeBean(jobDetailFactory, UUID.randomUUID().toString()); CronTriggerFactoryBean triggerFactoryBean = new CronTriggerFactoryBean(); triggerFactoryBean.setCronExpression(cronExpression); triggerFactoryBean.setJobDetail(jobDetailFactory.getObject()); triggerFactoryBean.setGroup(this.groupName); if(this.jobName != null) { triggerFactoryBean.setName("trigger_" + this.jobName); } applicationContext.getAutowireCapableBeanFactory().initializeBean(triggerFactoryBean, UUID.randomUUID().toString()); quartzScheduler.scheduleJob(jobDetailFactory, triggerFactoryBean); } public void setJobName(String jobName) { this.jobName = jobName; } public void setGroupName(String groupName) { this.groupName = groupName; } }
package com.urbanairship.datacube.dbharnesses; import com.codahale.metrics.Histogram; import com.codahale.metrics.Timer; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.urbanairship.datacube.Address; import com.urbanairship.datacube.BoxedByteArray; import com.urbanairship.datacube.Op; import com.urbanairship.datacube.metrics.Metrics; import org.apache.hadoop.hbase.client.HTableInterface; import org.apache.hadoop.hbase.client.HTablePool; import org.apache.hadoop.hbase.client.Increment; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Row; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; /** * Package private class implementing all the batch increment operations accomplished by the hbase dbharness * * @param <T> */ class HbaseBatchIncrementer<T extends Op> { private final HTablePool pool; private final IncrementerMetrics incrementerMetrics; private final BlockingIO<Address, BoxedByteArray> serializer; private HbaseDbHarnessConfiguration configuration; interface BlockingIO<I, O> { O apply(I i) throws InterruptedException, IOException; } HbaseBatchIncrementer(HbaseDbHarnessConfiguration configuration, HTablePool pool, BlockingIO<Address, BoxedByteArray> serializer) { this.configuration = configuration; this.pool = pool; this.serializer = serializer; this.incrementerMetrics = new IncrementerMetrics(HBaseDbHarness.class, configuration.metricsScope); } /** * Slices up the batch map into batches of a reasonable size to send to the database, interprets the results * (include partial failures where only a part of the batch succeeded, and an exception was thrown) and updates * the success map and list with the results. It then rethrows whatever exception resulted from the HBase * interaction. * * @param batchMap The write operations to accomplish * @param successfulAddresses The datacube address whose writes succeeded * @param successfulRows A map from HBase row key to the value in the row after completion of the increment * operation * * @throws IOException * @throws InterruptedException */ public void batchIncrement(Map<Address, T> batchMap, List<Address> successfulAddresses, Map<byte[], byte[]> successfulRows) throws IOException, InterruptedException { Iterable<List<Map.Entry<Address, T>>> partitions = Iterables.partition(batchMap.entrySet(), configuration.batchSize); Map<BoxedByteArray, byte[]> successes = new HashMap<>(); int batchesPerFlush = 0; Map<BoxedByteArray, Address> backwards = new HashMap<>(); Exception caughtException = null; try { for (List<Map.Entry<Address, T>> entries : partitions) { Map<BoxedByteArray, T> increments = new HashMap<>(); batchesPerFlush++; final long nanoTimeBeforeWrite = System.nanoTime(); for (Map.Entry<Address, T> entry : entries) { final Address address = entry.getKey(); final BoxedByteArray rowKey = serializer.apply(address); increments.put(rowKey, entry.getValue()); backwards.put(rowKey, address); } List<Map.Entry<BoxedByteArray, T>> entriesList = ImmutableList.copyOf(increments.entrySet()); Object[] objects = new Object[entriesList.size()]; try { hbaseIncrement(entriesList, objects); } catch (InterruptedException | IOException e) { caughtException = e; } finally { successes.putAll(processBatchCallresults(entriesList, objects)); long writeDurationNanos = System.nanoTime() - nanoTimeBeforeWrite; incrementerMetrics.batchWritesTimer.update(writeDurationNanos, TimeUnit.NANOSECONDS); } } } catch (Exception e) { caughtException = e; } finally { incrementerMetrics.batchesPerFlush.update(batchesPerFlush); for (Map.Entry<BoxedByteArray, byte[]> entry : successes.entrySet()) { successfulAddresses.add(backwards.get(entry.getKey())); successfulRows.put(entry.getKey().bytes, entry.getValue()); } int failures = batchMap.size() - successfulAddresses.size(); if (failures > 0 || (caughtException != null)) { incrementerMetrics.incrementFailuresPerFlush.update(failures); if (caughtException != null) { // the implementation prior to the addition of the batch increment code assumes any failed increment // operation results in an io exception. This matches that expectation. throw new IOException(String.format("Some writes failed (%s of %s attempted); queueing retry", failures, batchMap.size()), caughtException); } } } } private void hbaseIncrement(List<Map.Entry<BoxedByteArray, T>> entriesList, Object[] objects) throws IOException, InterruptedException { List<Row> rows = new ArrayList<>(); for (Map.Entry<BoxedByteArray, T> entry : entriesList) { long amount = Bytes.toLong(entry.getValue().serialize()); Increment increment = new Increment(entry.getKey().bytes); increment.addColumn(configuration.cf, HBaseDbHarness.QUALIFIER, amount); incrementerMetrics.incrementSize.update(amount); rows.add(increment); } HTableInterface table = pool.getTable(configuration.tableName); table.batch(rows, objects); } /** * Converts the datacube request objects and an array of objects returned from an hbase batch call into the map we * use to track success. * * @param entries The map entries we used to construct the increment request against hbase. * @param objects The response to the batch operation * * @return A map from the serialized {@link Address} to the bytes in the column after completion of the operation. */ private Map<BoxedByteArray, byte[]> processBatchCallresults(List<Map.Entry<BoxedByteArray, T>> entries, Object[] objects) { Map<BoxedByteArray, byte[]> successes = new HashMap<>(); for (int i = 0; i < objects.length; ++i) { if (objects[i] != null && objects[i] instanceof Result) { Result result = (Result) objects[i]; byte[] value = result.getValue(configuration.cf, HBaseDbHarness.QUALIFIER); successes.put(entries.get(i).getKey(), value); } } return successes; } private class IncrementerMetrics { private final Histogram incrementSize; private final Histogram incrementFailuresPerFlush; private final Histogram batchesPerFlush; private final Timer batchWritesTimer; public IncrementerMetrics(Class clazz, String metricsScope) { incrementSize = Metrics.histogram(clazz, "incrementSize", metricsScope); incrementFailuresPerFlush = Metrics.histogram(clazz, "failuresPerFlush", metricsScope); batchesPerFlush = Metrics.histogram(clazz, "batchesPerFlush", metricsScope); batchWritesTimer = Metrics.timer(clazz, "batchWrites", metricsScope); } } }
package hudson.plugins.warnings.parser.jcreportparser; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.commons.digester3.Digester; import org.apache.commons.digester3.binder.DigesterLoader; import org.apache.commons.lang.StringUtils; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import hudson.Extension; import hudson.plugins.analysis.util.model.FileAnnotation; import hudson.plugins.analysis.util.model.Priority; import hudson.plugins.warnings.parser.AbstractWarningsParser; import hudson.plugins.warnings.parser.Messages; import hudson.plugins.warnings.parser.ParsingCanceledException; import hudson.plugins.warnings.parser.Warning; import hudson.util.IOException2; /** * JcReportParser-Class. This class parses from the jcReport.xml and creates warnings from its content. * * @author Johann Vierthaler, johann.vierthaler@web.de */ @Extension public class JcReportParser extends AbstractWarningsParser { /** * Generated document field serialVersionUID. */ private static final long serialVersionUID = -1302787609831475403L; /** * Creates a new instance of JcReportParser. * * @author Johann Vierthaler, johann.vierthaler@web.de * @NOTE: Only the Super-Constructor is called with 3 Localizables. */ public JcReportParser() { super(Messages._Warnings_JCReport_ParserName(), Messages._Warnings_JCReport_LinkName(), Messages ._Warnings_JCReport_TrendName()); } /** * Inherited from the super-class. * * @author Johann Vierthaler, johann.vierthaler@web.de This overwritten method passes the reader to createReport() * and starts adding all the warnings to the Collection that will be returned at the end of the method. * @return warnings -> the collection of Warnings parsed from the Report. * @param reader * -> the reader that parses from the source-file. * @exception IOException * -> thrown by createReport() * @exception ParsingCanceledException * -> thrown by createReport() */ @Override public Collection<FileAnnotation> parse(final Reader reader) throws IOException, ParsingCanceledException { final Report report = createReport(reader); List<FileAnnotation> warnings = new ArrayList<FileAnnotation>(); for (int i = 0; i < report.getFiles().size(); i++) { final File file = report.getFiles().get(i); for (int j = 0; j < file.getItems().size(); j++) { final Item item = file.getItems().get(j); final Warning warning = createWarning(file.getName(), getLineNumber(item.getLine()), item.getFindingtype(), item.getMessage(), getPriority(item.getSeverity())); warning.setOrigin(item.getOrigin()); warning.setPackageName(file.getPackageName()); warning.setPathName(file.getSrcdir()); warning.setColumnPosition(getLineNumber(item.getColumn()), getLineNumber(item.getEndcolumn())); warnings.add(warning); } } return warnings; } /** * The severity-level parsed from the JcReport will be matched with a priority. * * @author Johann Vierthaler, johann.vierthaler@web.de * @return priority -> the priority-enum matching with the issueLevel. * @param issueLevel * -> the severity-level parsed from the JcReport. */ private Priority getPriority(final String issueLevel) { if (StringUtils.isEmpty(issueLevel)) { return Priority.HIGH; } if (issueLevel.contains("CriticalError")) { return Priority.HIGH; } else if (issueLevel.contains("Error")) { return Priority.HIGH; } else if (issueLevel.contains("CriticalWarning")) { return Priority.HIGH; } else if (issueLevel.contains("Warning")) { return Priority.NORMAL; } else { return Priority.LOW; } } /** * Creates a Report-Object out of the content within the JcReport.xml. * * @param source * -> the Reader-object that is the source to build the Report-Object. * @return report -> the finished Report-Object that creates the Warnings. * @throws IOException * -> due to digester.parse(new InputSource(source)) */ public Report createReport(final Reader source) throws IOException { try { final DigesterLoader digesterLoader = DigesterLoader.newLoader(new JcReportModule()); final Digester digester = digesterLoader.newDigester(); return digester.parse(new InputSource(source)); } catch (SAXException exception) { throw new IOException2(exception); } } }
package gr.iti.mklab.framework.common.domain.collections; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import org.mongodb.morphia.annotations.Entity; import gr.iti.mklab.framework.common.domain.Account; import gr.iti.mklab.framework.common.domain.JSONable; import gr.iti.mklab.framework.common.domain.Location; import gr.iti.mklab.framework.common.domain.Source; import gr.iti.mklab.framework.common.domain.feeds.AccountFeed; import gr.iti.mklab.framework.common.domain.feeds.Feed; import gr.iti.mklab.framework.common.domain.feeds.KeywordsFeed; import gr.iti.mklab.framework.common.domain.feeds.LocationFeed; import gr.iti.mklab.framework.common.domain.feeds.RssFeed; /** * @author Manos Schinas - manosetro@iti.gr * */ @Entity(noClassnameStored = true) public class Collection extends JSONable { private static final long serialVersionUID = -8830711950312367090L; public Collection() { } public Collection(String id, Date date) { this.id = id; this.creationDate = date.getTime(); this.updateDate = date.getTime(); } // The creation date of the Topic protected Long creationDate; // The date that the Topic was last updated protected Long updateDate; //The title of the Topic, set by the user protected String title; // The user that created the Topic protected String ownerId; // The group id of the use that created the Topic protected String groupId; // The group id of the use that created the Topic protected String privacy = "private"; // private - protected - public protected Long lastRunningTime; // Fields that used for collection and retrieval of items // Keywords used to collect items protected List<Keyword> keywords = new ArrayList<Keyword>(); // Accounts to follow protected List<Account> accounts = new ArrayList<Account>(); // Locations that used for the collection of Items private List<Location> nearLocations = new ArrayList<Location>(); // Exclude specific keywords from the collection private List<String> keywordsToExclude = new ArrayList<String>(); // Exclude specific items from the collection during retrieval private Set<String> itemsToExclude = new HashSet<String>(); // Retrieve items in time range [since- until] protected long since; protected String status = "running"; //running/stopped public String getId() { return id; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; } public String geOwnertId() { return ownerId; } public void setId(String id) { this.id = id; } public Date getCreationDate() { return new Date(creationDate); } public void setCreationDate(Date creationDate) { this.creationDate = creationDate.getTime(); } public long getSinceDate() { return since; } public void setSinceDate(long sinceDate) { this.since = sinceDate; } public String getTitle() { return title; } public void setTitle(String Title) { this.title = Title; } public List<Account> getAccounts() { return accounts; } public void setAccounts(List<Account> accounts) { this.accounts = accounts; } public Date getUpdateDate() { return new Date(updateDate); } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate.getTime(); } public Long getLastRunningTime() { return lastRunningTime; } public void setLastRunningTime(Long lastRunningTime) { this.lastRunningTime = lastRunningTime; } public void setKeywords(List<Keyword> keywords) { this.keywords = keywords; } public List<Keyword> getKeywords() { return this.keywords; } public List<Location> getNearLocations() { return nearLocations; } public void setNearLocations(List<Location> nearLocations) { this.nearLocations = nearLocations; } public void setKeywordsToExclude(List<String> keywordsToExclude) { this.keywordsToExclude = keywordsToExclude; } public List<String> getKeywordsToExclude() { return this.keywordsToExclude; } public Set<String> getItemsToExclude() { return itemsToExclude; } public void setItemsToExclude(Set<String> itemsToExclude) { this.itemsToExclude = itemsToExclude; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public List<Feed> getFeeds() { List<Feed> feeds = new ArrayList<Feed>(); if(keywords != null) { for(Keyword keyword : keywords) { String[] sources = keyword.getSources(); if(sources == null) { sources = Arrays.toString(Source.values()).replaceAll("^.|.$", "").split(", "); } for(String source : sources) { String id = source + "#" + keyword.getKeyword(); Feed feed = new KeywordsFeed(id, keyword.getKeyword(), since, source); feeds.add(feed); } } } if(accounts != null) { for(Account account : accounts) { String source = account.getSource().name(); if(source.equals("RSS")) { RssFeed feed = new RssFeed(account.getId(), account.getUsername(), since); feed.setName(account.getName()); feeds.add((Feed) feed); } else { AccountFeed feed = new AccountFeed(account.getId(), account.getUsername(), since, source); feeds.add((Feed) feed); } } } if(nearLocations != null) { for(Location location : nearLocations) { Feed feed = new LocationFeed(null, location, since, null); feeds.add(feed); } } return feeds; } public static void main(String[] args) { Collection collection = new Collection(); collection.setId("randomid_userid_timestamp"); collection.setCreationDate(new Date()); collection.setSinceDate(System.currentTimeMillis() - (7 * 24 * 3600 * 1000l)); collection.setOwnerId("1234567890"); collection.setTitle("ISIS Attacks"); String[] sources = {"Twitter", "Youtube", "GooglePlus" }; List<Keyword> k = new ArrayList<Keyword>(); k.add(new Keyword("isis", sources)); k.add(new Keyword("raqqa", sources)); k.add(new Keyword("paris attacks", sources)); collection.setKeywords(k); List<Account> accounts = new ArrayList<Account>(); Account a = new Account(); a.setId("xxxx"); a.setName("politico"); a.setSource("Twitter"); accounts.add(a); collection.setAccounts(accounts); System.out.println(collection.toString()); } public static class Keyword { private String keyword; private String[] sources; public Keyword() { } public Keyword(String keyword) { this.keyword = keyword; } public Keyword(String keyword, String[] sources) { this.keyword = keyword; this.sources = sources; } public String[] getSources() { return sources; } public void setSources(String[] sources) { this.sources = sources; } public String getKeyword() { return keyword; } public void setKeyword(String keyword) { this.keyword = keyword; } public String toString() { return keyword; } } }
package gov.nih.nci.calab.ui.security; import gov.nih.nci.calab.dto.common.UserBean; import gov.nih.nci.calab.service.login.LoginService; import gov.nih.nci.calab.service.login.PasswordService; import gov.nih.nci.calab.ui.core.AbstractBaseAction; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.validator.DynaValidatorForm; /** * The LoginAction authenticates a user into the caLAB system. * * @author doswellj */ public class LoginAction extends AbstractBaseAction { public ActionForward executeTask(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = null; HttpSession session = request.getSession(); DynaValidatorForm theForm = (DynaValidatorForm) form; String strLoginId = (String) theForm.get("loginId"); String strPassword = (String) theForm.get("password"); // Encrypt the password. String strEncryptedPass = PasswordService.getInstance().encrypt( strPassword); // Call CSM to authenticate the user. LoginService loginservice = new LoginService("calab"); Boolean blnAuthenticated = loginservice.login(strLoginId, strEncryptedPass); if (blnAuthenticated == true) { // Invalidate the current session and create a new one. session = request.getSession(false); session.invalidate(); session = request.getSession(true); // Save authenticated user information into User DTO. UserBean userBean = new UserBean(); userBean.setLoginId(strLoginId); session.setAttribute("user", userBean); forward = mapping.findForward("success"); } return forward; } public boolean loginRequired() { return false; } }
package io.github.hsyyid.essentialcmds.listeners; import io.github.hsyyid.essentialcmds.EssentialCmds; import io.github.hsyyid.essentialcmds.utils.Mail; import io.github.hsyyid.essentialcmds.utils.Utils; import org.spongepowered.api.data.manipulator.mutable.entity.JoinData; import org.spongepowered.api.entity.Transform; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.network.ClientConnectionEvent; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.channel.MessageChannel; import org.spongepowered.api.text.format.TextColors; import org.spongepowered.api.text.serializer.TextSerializers; import org.spongepowered.api.world.World; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Objects; import java.util.TimeZone; import java.util.stream.Collectors; public class PlayerJoinListener { @Listener public void onPlayerJoin(ClientConnectionEvent.Join event) { Player player = event.getTargetEntity(); if (player.get(JoinData.class).isPresent() && player.getJoinData().firstPlayed().get().equals(player.getJoinData().lastPlayed().get())) { Transform<World> spawn = Utils.getSpawn(); if (spawn != null) { if (!Objects.equals(player.getWorld().getUniqueId(), spawn.getExtent().getUniqueId())) { player.transferToWorld(spawn.getExtent().getUniqueId(), spawn.getPosition()); player.setTransform(spawn); } else { player.setTransform(spawn); } } Text firstJoinMsg = TextSerializers.formattingCode('&').deserialize(Utils.getFirstJoinMsg().replaceAll("@p", player.getName())); MessageChannel.TO_ALL.send(firstJoinMsg); } Calendar cal = Calendar.getInstance(); SimpleDateFormat format = new SimpleDateFormat("dd MMM yyyy HH:mm:ss"); format.setTimeZone(TimeZone.getTimeZone("GMT")); Utils.setLastTimePlayerJoined(player.getUniqueId(), format.format(cal.getTime())); player.sendMessage(TextSerializers.formattingCode('&').deserialize(Utils.getJoinMsg())); ArrayList<Mail> newMail = (ArrayList<Mail>) Utils.getMail().stream().filter(mail -> mail.getRecipientName().equals(player.getName())).collect(Collectors.toList()); if (newMail.size() > 0) { player.sendMessage(Text.of(TextColors.GOLD, "[Mail]: ", TextColors.GRAY, "While you were away, you received new mail to view it do ", TextColors.RED, "/listmail")); } EssentialCmds.recentlyJoined.add(event.getTargetEntity()); // Remove previous AFK, so player does not join as AFK. if (EssentialCmds.afkList.containsKey(player.getUniqueId())) { EssentialCmds.afkList.remove(player.getUniqueId()); } String loginMessage = Utils.getLoginMessage(); if (loginMessage != null && !loginMessage.equals("")) { loginMessage = loginMessage.replaceAll("@p", player.getName()); Text newMessage = TextSerializers.formattingCode('&').deserialize(loginMessage); event.setMessage(newMessage); } Utils.savePlayerInventory(player, player.getWorld().getUniqueId()); } }
package example; //-*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: //@homepage@ import java.awt.*; import java.util.*; import javax.swing.*; import javax.swing.plaf.basic.BasicSpinnerUI; public final class MainPanel extends JPanel { private final JSpinner spinner0 = new JSpinner(new SpinnerNumberModel(10, 0, 1000, 1)); private final JSpinner spinner1 = new JSpinner(new SpinnerNumberModel(10, 0, 1000, 1)); private final JSpinner spinner2 = new JSpinner(new SpinnerNumberModel(10, 0, 1000, 1)) { @Override public void updateUI() { super.updateUI(); setUI(new BasicSpinnerUI() { @Override protected LayoutManager createLayout() { return new SpinnerLayout(); } }); } }; private final JSpinner spinner3 = new JSpinner(new SpinnerNumberModel(10, 0, 1000, 1)) { @Override public void setLayout(LayoutManager mgr) { super.setLayout(new SpinnerLayout()); } }; public MainPanel() { super(new BorderLayout()); spinner1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); Box box = Box.createVerticalBox(); box.add(makePanel("Default", spinner0)); box.add(makePanel("RIGHT_TO_LEFT", spinner1)); box.add(makePanel("L(Prev), R(Next)", spinner2)); box.add(makePanel("L(Prev), R(Next)", spinner3)); add(box, BorderLayout.NORTH); setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); setPreferredSize(new Dimension(320, 240)); } private static JPanel makePanel(String title, JComponent c) { JPanel p = new JPanel(new BorderLayout()); p.setBorder(BorderFactory.createTitledBorder(title)); p.add(c); return p; } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class SpinnerLayout extends BorderLayout { private final Map<Object, Object> layoutMap; protected SpinnerLayout() { super(); layoutMap = new HashMap<>(); layoutMap.put("Editor", "Center"); layoutMap.put("Next", "East"); layoutMap.put("Previous", "West"); } @Override public void addLayoutComponent(Component comp, Object constraints) { Object cons = Optional.ofNullable(layoutMap.get(constraints)).orElse(constraints); super.addLayoutComponent(comp, cons); } }
package io.github.jdaapplications.guildbot.executor; import gnu.trove.map.TLongObjectMap; import gnu.trove.map.hash.TLongObjectHashMap; import io.github.jdaapplications.guildbot.GuildBot; import io.github.jdaapplications.guildbot.executor.executable.Command; import io.github.jdaapplications.guildbot.executor.executable.Method; import io.github.jdaapplications.guildbot.executor.executable.Variables; import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.JDA; import net.dv8tion.jda.core.MessageBuilder; import net.dv8tion.jda.core.OnlineStatus; import net.dv8tion.jda.core.entities.*; import net.dv8tion.jda.core.events.ReconnectedEvent; import net.dv8tion.jda.core.events.channel.text.GenericTextChannelEvent; import net.dv8tion.jda.core.events.channel.text.TextChannelCreateEvent; import net.dv8tion.jda.core.events.channel.text.TextChannelDeleteEvent; import net.dv8tion.jda.core.events.channel.text.update.TextChannelUpdateNameEvent; import net.dv8tion.jda.core.events.channel.text.update.TextChannelUpdateTopicEvent; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; import net.dv8tion.jda.core.events.message.guild.GuildMessageDeleteEvent; import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent; import net.dv8tion.jda.core.events.message.guild.GuildMessageUpdateEvent; import net.dv8tion.jda.core.hooks.SubscribeEvent; import net.dv8tion.jda.core.managers.Presence; import net.dv8tion.jda.core.requests.RestAction; import org.hjson.JsonObject; import org.hjson.JsonValue; import javax.script.Bindings; import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.SimpleBindings; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.*; import java.util.function.Consumer; import java.util.stream.Collectors; /** * @author Aljoscha Grebe */ public class CommandExecutor { private Map<String, Command> commands; private final GuildBot guildBot; private Map<String, Method> methods; private Map<String, Variables> vars; private final Bindings globalStore; public CommandExecutor(final GuildBot guildBot) { this.guildBot = guildBot; this.globalStore = new SimpleBindings(); guildBot.getThreadPool().execute(this::init); } public Map<String, Command> getCommands() { return Collections.unmodifiableMap(this.commands); } public GuildBot getGuildBot() { return this.guildBot; } public Map<String, Method> getMethods() { return Collections.unmodifiableMap(this.methods); } public Map<String, Variables> getVars() { return Collections.unmodifiableMap(this.vars); } @SubscribeEvent private void onGuildMessageDelete(final GuildMessageDeleteEvent event) { this.update(event.getChannel()); } @SubscribeEvent private void onGuildMessageReceived(final GuildMessageReceivedEvent event) { this.update(event.getChannel()); } @SubscribeEvent private void onGuildMessageUpdate(final GuildMessageUpdateEvent event) { this.update(event.getChannel()); } @SubscribeEvent private void onMessageReceived(final MessageReceivedEvent event) { final String prefix = this.guildBot.getConfig().getString("prefix", this.guildBot.getJDA().getSelfUser().getAsMention() + ' '); String content = event.getMessage().getRawContent(); if (!content.startsWith(prefix)) return; content = content.substring(prefix.length()); final String[] split = content.split("\\s+", 2); final String commandName = split[0].toLowerCase(); final Command command = this.commands.get(commandName); if (command == null) return; final String args = split.length > 1 ? split[1] : ""; this.execute(command, event, args); } @SubscribeEvent private void onReconnect(final ReconnectedEvent event) { this.reload(); } @SubscribeEvent private void onTextChannelCreate(final TextChannelCreateEvent event) { this.update(event.getChannel()); } @SubscribeEvent private void onTextChannelDelete(final TextChannelDeleteEvent event) { this.delete(event, event.getChannel().getName()); } @SubscribeEvent private void onTextChannelUpdateName(final TextChannelUpdateNameEvent event) { this.delete(event, event.getOldName()); this.update(event.getChannel()); } @SubscribeEvent private void onTextChannelUpdateTopic(final TextChannelUpdateTopicEvent event) { this.update(event.getChannel()); } private synchronized void update(final TextChannel channel) { if (channel.getGuild().getIdLong() != this.guildBot.getConfig().getLong("guildId", 0)) return; if (!CommandExecutor.isScriptChannel(channel)) return; try { final JsonObject config = CommandExecutor.readConfig(channel); Consumer<String> consumer; if (channel.getName().startsWith("mthd-")) { consumer = script -> { final String name = channel.getName().substring(5); this.methods.put(name, new Method(this.guildBot, config, name, script)); }; } else if (channel.getName().startsWith("vars-")) { consumer = script -> { final String name = channel.getName().substring(5); this.vars.put(name, new Variables(this.guildBot, config, script)); }; } else { consumer = script -> { final Command command = new Command(this.guildBot, channel.getIdLong(), config, script); for (final String name : channel.getName().substring(4).split("-")) this.commands.put(name, command); }; } channel.getHistory().retrievePast(config.getInt("length", 1)).queue(l -> { Collections.reverse(l); final String script = l.stream() .map(Message::getRawContent) .collect(Collectors.joining("\n")); consumer.accept(script); }); } catch (final Exception e) { final String message = "An error occurred while updating " + channel.getName(); GuildBot.log.error(message, e); this.guildBot.handleThrowable(e, message); this.delete(channel); } } private synchronized void delete(final GenericTextChannelEvent event, final String name) { this.delete(event.getGuild().getIdLong(), name); } private synchronized void delete(final long guildId, final String name) { if (guildId != this.guildBot.getConfig().getLong("guildId", 0)) return; if (name.startsWith("mthd-")) this.methods.remove(name.substring(5)); else if (name.startsWith("vars-")) this.vars.remove(name.substring(5)); else if (name.startsWith("cmd-")) for (final String cName : name.substring(4).split("\\-")) this.commands.remove(cName); } private synchronized void delete(final TextChannel channel) { this.delete(channel.getGuild().getIdLong(), channel.getName()); } public synchronized void reload() { Guild guild = this.guildBot.getJDA().getGuildById(this.guildBot.getConfig().getLong("guildId", 0)); if (guild == null) return; this.guildBot.getThreadPool().execute(() -> guild.getTextChannels().forEach(this::update)); } private synchronized void execute(final Command command, final MessageReceivedEvent event, final String args) { final EngineMap scriptEngines = new EngineMap(); final ScriptContext context = scriptEngines.getContext(); final Bindings bindings = context.getBindings(ScriptContext.ENGINE_SCOPE); bindings.put("event", event); bindings.put("args", args == null ? "" : args); bindings.put("guildBot", this.guildBot); bindings.put("global", this.globalStore); final ScheduledExecutorService pool = this.guildBot.getThreadPool(); for (final Entry<String, Variables> entry : this.vars.entrySet()) { final Variables variables = entry.getValue(); final ScriptEngine engine = scriptEngines.get(variables.getEngine()); try { final Future<?> future = pool.submit(() -> engine.eval(variables.getExecutableScript())); future.get(variables.getConfig().getInt("timeout", this.guildBot.getConfig().getInt("timeout", 5)), TimeUnit.SECONDS); } catch (final Exception e) { final String varName = entry.getKey(); GuildBot.log.error("An error occurred while evaluating the vars \"{}\"\n{}\n{}", varName, variables.getExecutableScript(), e); final String varContext = String.format("Trying to evaluate var: %#s", event.getJDA().getTextChannelById(varName)); this.guildBot.handleThrowable(e, varContext); } } for (final Entry<String, Method> methodEntry : this.methods.entrySet()) { final String methodName = methodEntry.getKey(); final Method method = methodEntry.getValue(); bindings.put(methodName, method.getInvokeableMethod(context)); for (final Entry<Engine, ScriptEngine> engineEntry : scriptEngines.entrySet()) { final Engine engine = engineEntry.getKey(); final String script = method.getExecutableScript(engine); if (script != null) try { engineEntry.getValue().eval(method.getExecutableScript(engine)); } catch (final Exception e) { GuildBot.log.error("An error occurred while evaluating the method \"{}\"\n{}\n{}", methodName, method.getExecutableScript(engine), e); final String methodContext = String.format("Trying to evaluate method: %#s", event.getJDA().getTextChannelById(methodName)); this.guildBot.handleThrowable(e, methodContext); } } } final Future<?> future = pool.submit(() -> scriptEngines.get(command.getEngine()).eval(command.getExecutableScript())); Object result; try { result = future.get(command.getConfig().getInt("timeout", this.guildBot.getConfig().getInt("timeout", 5)), TimeUnit.SECONDS); } catch (final ExecutionException e) { result = e; } catch (TimeoutException | InterruptedException e) { future.cancel(true); result = e; } catch (final Exception e) { result = e; } if (result instanceof RestAction<?>) ((RestAction<?>) result).queue(); else if (result instanceof String) event.getChannel().sendMessage((String) result).queue(); else if (result instanceof Message) event.getChannel().sendMessage((Message) result).queue(); else if (result instanceof MessageEmbed) event.getChannel().sendMessage((MessageEmbed) result).queue(); else if (result instanceof MessageBuilder) event.getChannel().sendMessage(((MessageBuilder) result).build()).queue(); else if (result instanceof EmbedBuilder) event.getChannel().sendMessage(((EmbedBuilder) result).build()).queue(); else if (result instanceof Throwable) { GuildBot.log.error("An error occurred while execution a command\n{}\n{}", command.getExecutableScript(), result); final String commandContext = String.format("Trying to evaluate command: %#s", event.getJDA().getTextChannelById(command.getChannelId())); this.guildBot.handleThrowable((Throwable) result, commandContext); event.getChannel().sendMessage("An error occurred").queue(); } } private synchronized void init() { final JsonObject config = this.guildBot.getConfig(); final long guildId = config.getLong("guildId", 0); final JDA jda = this.guildBot.getJDA(); final Guild guild = jda.getGuildById(guildId); if (guild == null) { GuildBot.log.error("Could not find a guild with id " + guildId + ", shutting bot down"); jda.shutdown(); return; } // get all relevant channels final List<TextChannel> channels = guild.getTextChannels().stream() .filter(CommandExecutor::isScriptChannel) .collect(Collectors.toList()); final int channelCount = channels.size(); // get configs in channel topic final TLongObjectMap<JsonObject> configs = new TLongObjectHashMap<>(channelCount); channels.forEach(c -> configs.put(c.getIdLong(), CommandExecutor.readConfig(c))); // get messages final CountDownLatch latch = new CountDownLatch(channelCount); final TLongObjectMap<String> messages = new TLongObjectHashMap<>(channelCount); channels.forEach(c -> c.getHistory().retrievePast(configs.get(c.getIdLong()).getInt("length", 1)).queue(l -> { Collections.reverse(l); messages.put(c.getIdLong(), l.stream() .map(Message::getRawContent) .collect(Collectors.joining("\n"))); latch.countDown(); }, t -> { GuildBot.log.error("An error occurred while retrieving the messages of channel \"" + c.getName() + "\"", t); this.guildBot.handleThrowable(t, "RestAction failure trying to retrieve history"); latch.countDown(); })); try { latch.await(); } catch (final InterruptedException e) { e.printStackTrace(); } this.methods = new ConcurrentHashMap<>(); channels.stream().filter(c -> c.getName().startsWith("mthd-")).forEach(c -> { try { final String name = c.getName().substring(5); this.methods.put(name, new Method(this.guildBot, configs.get(c.getIdLong()), name, messages.get(c.getIdLong()))); } catch (final Exception e) { this.delete(c); GuildBot.log.error("An error occurred while initialising " + c.getName(), e); this.guildBot.handleThrowable(e, "Setup for methods"); } }); this.vars = new ConcurrentHashMap<>(); channels.stream().filter(c -> c.getName().startsWith("vars-")).forEach(c -> { try { final String name = c.getName().substring(5); this.vars.put(name, new Variables(this.guildBot, configs.get(c.getIdLong()), messages.get(c.getIdLong()))); } catch (final Exception e) { this.delete(c); GuildBot.log.error("An error occurred while initialising " + c.getName(), e); this.guildBot.handleThrowable(e, "Setup for vars"); } }); this.commands = new ConcurrentHashMap<>(); channels.stream().filter(c -> c.getName().startsWith("cmd-")).forEach(c -> { try { final Command command = new Command(this.guildBot, c.getIdLong(), configs.get(c.getIdLong()), messages.get(c.getIdLong())); for (final String name : c.getName().substring(4).split("-")) this.commands.put(name, command); } catch (final Exception e) { this.delete(c); GuildBot.log.error("An error occurred while initialising " + c.getName(), e); this.guildBot.handleThrowable(e, "Setup for commands"); } }); GuildBot.log.info("Accepting commands now"); Presence presence = jda.getPresence(); Game game = Game.of(config.getString("prefix", jda.getSelfUser().getAsMention() + ' ') + "help"); presence.setPresence(OnlineStatus.ONLINE, game); jda.addEventListener(this); } private static boolean isScriptChannel(final TextChannel channel) { return channel.getName().startsWith("cmd-") || channel.getName().startsWith("mthd-") || channel.getName().startsWith("vars-"); } private static JsonObject readConfig(final TextChannel channel) { return channel.getTopic() == null || channel.getTopic().isEmpty() ? new JsonObject() : JsonValue.readHjson(channel.getTopic()).asObject(); } }
package whelk.importer; import whelk.Document; import whelk.Whelk; import whelk.history.History; import whelk.history.Ownership; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.File; import java.io.IOException; import java.util.*; import static whelk.util.Jackson.mapper; public class Merge { /* Merge rules are placed in files and look something like this: { "rules": [ { "operation": "replace", "path": ["@graph", 1, "hasTitle", "@type=Title", "subtitle"], "priority": { "Utb1": 10, "Utb2": 11 } }, { "operation": "add_if_none", "path": ["@graph", 1, "hasTitle"] } ] } The "paths" in use here work the same way PostgresSQL paths do, but with some exceptions. 1. Other than the surrounding @graph list (@graph,X), it is not possible to specify list indexes. So for example: ["@graph", 1, "hasTitle", 0, "subtitle"] is not allowed (the "0" being the problem). 2. It is however allowed to target elements in lists using type specifiers. So for example ["@graph", 1, "hasTitle", "@type=Title", "subtitle"] is ok, BUT WILL ONLY WORK if there is exactly one title with @type=Title in both existing and incoming records. If either record has more than one (or none) of these, there is no way to identify which one is being targeted. */ // Contains paths where we're allowed to add things that don't already exist private Set<List<Object>> m_pathAddRules = null; // Maps a path to a sigel priority list. private Map<List<Object>, Map> m_pathReplaceRules = null; private final Logger logger = LogManager.getLogger(this.getClass()); public Merge(File ruleFile) throws IOException { m_pathAddRules = new HashSet<>(); m_pathReplaceRules = new HashMap<>(); Map rulesMap = mapper.readValue(ruleFile, Map.class); List rules = (List) rulesMap.get("rules"); for (Object rule : rules) { Map ruleMap = (Map) rule; String op = (String) ruleMap.get("operation"); List path = (List) ruleMap.get("path"); Map prioMap = (Map) ruleMap.get("priority"); if (op.equals("replace")) m_pathReplaceRules.put(path, prioMap); else if (op.equals("add_if_none")) m_pathAddRules.add(path); else throw new RuntimeException("Malformed import rule, no such operation: " + op); } } public void merge(Document base, Document incoming, String incomingAgent, Whelk whelk) { History baseHistory = new History(whelk.getStorage().loadDocumentHistory(base.getShortId()), whelk.getJsonld()); List<Object> baseGraphList = (List<Object>) base.data.get("@graph"); List<Object> incomingGraphList = (List<Object>) incoming.data.get("@graph"); for (int i = 0; i < Integer.min(baseGraphList.size(), incomingGraphList.size()); ++i) { List<Object> path = new ArrayList<>(); path.add("@graph"); path.add(i); mergeInternal( baseGraphList.get(i), baseGraphList, incomingGraphList.get(i), path, incomingAgent, baseHistory, base.getShortId() ); } } /** * Get the sigel priority list for replacements that applies at this path, if any exists. * this will be the most specific one of all rules, with that operation, that cover this path. */ public Map getReplaceRuleForPath(List<Object> path) { List<Object> temp = new ArrayList<>(path); while (!temp.isEmpty()) { Map prioMap = m_pathReplaceRules.get(temp); if ( prioMap != null ) return prioMap; temp.remove(temp.size()-1); } return null; } public boolean existsAddRuleForPath(List<Object> path) { List<Object> temp = new ArrayList<>(path); while (!temp.isEmpty()) { if (m_pathAddRules.contains(path)) return true; temp.remove(temp.size()-1); } return false; } private void mergeInternal(Object base, Object baseParent, Object correspondingIncoming, List<Object> path, String incomingAgent, History baseHistory, String loggingForID) { Map replacePriority = getReplaceRuleForPath(path); if (replacePriority != null) { // Determine priority for the incoming version int incomingPriorityHere = 0; if (replacePriority.get(incomingAgent) != null) { incomingPriorityHere = (Integer) replacePriority.get(incomingAgent); } // Determine (the maximum) priority for any part of the already existing subtree (below 'path') int basePriorityHere = 0; boolean baseContainsHandEdits = false; Set<Ownership> baseOwners = baseHistory.getSubtreeOwnerships(path); for (Ownership baseOwnership : baseOwners) { if (baseOwnership.m_manualEditTime != null) baseContainsHandEdits = true; String baseAgent = baseOwnership.m_systematicEditor; if (replacePriority.get(baseAgent) != null) { int priority = (Integer) replacePriority.get(baseAgent); if (priority > basePriorityHere) basePriorityHere = priority; } } // Execute replacement if appropriate if (!baseContainsHandEdits && incomingPriorityHere >= basePriorityHere && !subtreeContainsLinks(base)) { if (baseParent instanceof Map) { Map parentMap = (Map) baseParent; parentMap.put(path.get(path.size()-1), correspondingIncoming); } else if (baseParent instanceof List) { List parentList = (List) baseParent; String typeToReplace = ((String) path.get(path.size()-1)).substring(6); // Strip away the @type= for (int i = 0; i < parentList.size(); ++i) { if (parentList.get(0) instanceof Map) { Map m = (Map) parentList.get(0); if (m.containsKey("@type") && m.get("@type").equals(typeToReplace)) { parentList.set(i, correspondingIncoming); break; } } } } logger.info("Merge of " + loggingForID + ": replaced " + path + ". Max existing subtree priority was: " + basePriorityHere + " and incoming priority was: " + incomingPriorityHere); return; // scan no further (we've just replaced everything below us) } } if (base instanceof Map && correspondingIncoming instanceof Map) { for (Object key : ((Map) correspondingIncoming).keySet() ) { // Does the incoming record have properties here that we don't have and are allowed to add? List<Object> childPath = new ArrayList(path); childPath.add(key); if ( ((Map) base).get(key) == null ) { if (existsAddRuleForPath(childPath)) { ((Map) base).put(key, ((Map) correspondingIncoming).get(key)); logger.info("Merge of " + loggingForID + ": added object at " + childPath); } } // Keep scanning further down the tree! else { mergeInternal( ((Map) base).get(key), base, ((Map) correspondingIncoming).get(key), childPath, incomingAgent, baseHistory, loggingForID); } } } else if (base instanceof List && correspondingIncoming instanceof List) { // The idea here, is that if a list contains only a single element (per type) // In both existing and incoming records, then we can allow ourselves to assume // that those elements represent the same entity. If however there are more than // one, then no such assumptions can be made. // So for example given existing @graph,1,hasTitle : // [ { "@type":"Title", mainTitle:"A" }, { "@type":"SpineTitle", mainTitle:"B" } ] // and an incoming @graph,1,hasTitle : // [ { "@type":"Title", mainTitle:"C" }, { "@type":"SpineTitle", mainTitle:"D" } ] // We will allow the "path" @graph,1,hasTitle,@type=Title,mainTitle (with a type // specification instead of list index) to specify the one and only title entity with // that type. // Only exact type matches are considered, inheritance is meaningless in this context! List baseList = (List) base; List incomingList = (List) correspondingIncoming; Set<String> singleInstanceTypes = findSingleInstanceTypesInBoth(baseList, incomingList); // For each type of which there is exactly one instance in each list for (String type : singleInstanceTypes) { // Find the one instance of that type in each list Map baseChild = null; Map incomingChild = null; for (Object o : baseList) { if (o instanceof Map) { Map m = (Map) o; if (m.containsKey("@type") && m.get("@type").equals(type)) baseChild = m; } } for (Object o : incomingList) { if (o instanceof Map) { Map m = (Map) o; if (m.containsKey("@type") && m.get("@type").equals(type)) incomingChild = m; } } // Keep scanning List<Object> childPath = new ArrayList(path); childPath.add("@type="+type); mergeInternal( baseChild, incomingList, incomingChild, childPath, incomingAgent, baseHistory, loggingForID); } } } /** * Find the types of which there are exactly one instance in each list */ private Set<String> findSingleInstanceTypesInBoth(List a, List b) { HashMap<String, Integer> typeCountsA = countTypes(a); HashMap<String, Integer> typeCountsB = countTypes(b); Set<String> singleInstanceTypes = new HashSet<>(); for (String type : typeCountsA.keySet()) { if (typeCountsB.containsKey(type) && typeCountsA.get(type) == 1 && typeCountsB.get(type) == 1) { singleInstanceTypes.add(type); } } return singleInstanceTypes; } private HashMap<String, Integer> countTypes(List list) { HashMap<String, Integer> typeCounts = new HashMap<>(); for (Object o : list) { if (o instanceof Map) { Map map = (Map) o; if (map.get("@type") != null) { String type = (String) map.get("@type"); if (!typeCounts.containsKey(type)) { typeCounts.put(type, 1); } else { typeCounts.put(type, typeCounts.get(type) + 1); } } } } return typeCounts; } private boolean subtreeContainsLinks(Object object) { if (object instanceof List) { for (Object element : (List) object) { if (subtreeContainsLinks(element)) return true; } } else if (object instanceof Map) { Map map = (Map) object; if (map.keySet().size() == 1 && map.get("@id") != null) { return true; } else { for (Object key : map.keySet()) { if (subtreeContainsLinks(map.get(key))) { return true; } } } } return false; } }
package info.curtbinder.reefangel.service; public final class XMLTags { // XML Tags used by controller public static final String Status = "RA"; public static final String Memory = "MEM"; public static final String MemorySingle = "M"; public static final String DateTime = "D"; public static final String Version = "V"; public static final String Mode = "MODE"; public static final String T1 = "T1"; public static final String T2 = "T2"; public static final String T3 = "T3"; public static final String PH = "PH"; public static final String ATOLow = "ATOLOW"; public static final String ATOHigh = "ATOHIGH"; public static final String Salinity = "SAL"; public static final String ORP = "ORP"; public static final String PWMDaylight = "PWMD"; public static final String PWMActinic = "PWMA"; public static final String PWMExpansion = "PWME"; public static final String Relay = "R"; public static final String RelayMaskOn = "RON"; public static final String RelayMaskOff = "ROFF"; public static final String LogDate = "LOGDATE"; public static final String LabelTempBegin = "T"; public static final String LabelEnd = "N"; public static final String RelayExpansionModules = "REM"; public static final String ExpansionModules = "EM"; public static final String AIWhite = "AIW"; public static final String AIBlue = "AIB"; public static final String AIRoyalBlue = "AIRB"; public static final String RFMode = "RFM"; public static final String RFSpeed = "RFS"; public static final String RFDuration = "RFD"; public static final String RFWhite = "RFW"; public static final String RFRoyalBlue = "RFRB"; public static final String RFRed = "RFR"; public static final String RFGreen = "RFG"; public static final String RFBlue = "RFB"; public static final String RFIntensity = "RFI"; public static final String IO = "IO"; public static final String Custom = "C"; public static final String PHExpansion = "PHE"; public static final String WaterLevel = "WL"; public static final String WaterLevel1 = "WL1"; public static final String WaterLevel2 = "WL2"; public static final String WaterLevel3 = "WL3"; public static final String WaterLevel4 = "WL4"; public static final String Humidity = "HUM"; public static final String LeakDetector = "LEAK"; public static final String Override = "O"; public static final String MyReefAngelID = "MYREEFANGELID"; public static final String Hour = "HR"; public static final String Minute = "MIN"; public static final String Month = "MON"; public static final String Day = "DAY"; public static final String Year = "YR"; public static final String Ok = "OK"; public static final String Err = "ERR"; }
package net.finmath.marketdata.model.volatilities; import java.time.LocalDate; import java.util.HashMap; import net.finmath.marketdata.model.curves.DiscountCurveInterface; import net.finmath.marketdata.model.volatilities.VolatilitySurfaceInterface.QuotingConvention; import net.finmath.marketdata.model.AnalyticModelInterface; /** * An option quote surface with the ability to query option quotes for different strikes and maturities. * * The surface is constructed as a collection of smiles. The choice of this dimension is convenient in view of calibration via FFT methods. * * This class does not perform any interpolation of market quotes. It merely represents a container of information. * * The class provides also the ability to perform the conversion among different quoting conventions and hence can be used both for a calibration on prices or implied volatilities. * * The class currently does not cover normal volatilities. Lognormal volatilities are more common in the equity space. The extension is not problematic. * * @author Alessandro Gnoatto * */ public class OptionSurfaceData{ private final String underlying; private final LocalDate referenceDate; private final DiscountCurveInterface discountCurve; //\exp(-r*T) needed e.g. for application of the B&S formula private final DiscountCurveInterface equityForwardCurve; //S0*\exp((r-d)*T) private final QuotingConvention convention; //either price or volatility (lognormal/normal) private final HashMap<Double, OptionSmileData>surface; private final double[] maturities; /** * This is a very restrictive constructor that assumes that for each maturity we have the same number of option quotes. * * @param underlying The name of the underlying of this surface. * @param referenceDate The reference date for this market data (t=0). * @param strikes The vector of strikes. * @param maturities The vector of maturities. * @param values The matrix of values per (strike, maturity) * @param convention The quoting convention (@see net.finmath.marketdata.model.volatilities.VolatilitySurfaceInterface.QuotingConvention). * @param discountCurve A discount curve for discounting (funding/collateral rate). * @param equityForwardCurve A the discount curve for forwarding (repo rate (e.g. funding minus dividents). */ public OptionSurfaceData(String underlying, LocalDate referenceDate, double[] strikes, double[] maturities, double[][] values, QuotingConvention convention,DiscountCurveInterface discountCurve, DiscountCurveInterface equityForwardCurve) { if(strikes.length != values.length || maturities.length != values[0].length ) { throw new IllegalArgumentException("Inconsistent number of strikes, maturities or values"); }else { surface = new HashMap<Double,OptionSmileData>(); for(int j = 0; j< maturities.length; j++) { double[] valuesOfInterest = new double[strikes.length]; for(int i= 0; i< strikes.length; i++) { valuesOfInterest[i] = values[i][j]; } OptionSmileData jthSmile = new OptionSmileData(underlying, referenceDate, strikes, maturities[j], valuesOfInterest, convention); surface.put(maturities[j],jthSmile); } this.underlying = underlying; this.referenceDate = referenceDate; this.discountCurve = discountCurve; this.equityForwardCurve = equityForwardCurve; this.convention = convention; this.maturities = maturities; } } /** * Creates an equity option surface from an array of smiles. * * @param smiles The option smile data. * @param discountCurve A discount curve for discounting (funding/collateral rate). * @param equityForwardCurve A the discount curve for forwarding (repo rate (e.g. funding minus dividents). */ public OptionSurfaceData(OptionSmileData[] smiles, DiscountCurveInterface discountCurve, DiscountCurveInterface equityForwardCurve) { OptionSmileData firstSmile = smiles[0]; String myUnderlying = firstSmile.getUnderlying(); LocalDate myReferenceDate = firstSmile.getReferenceDate(); QuotingConvention myConvention = firstSmile.getSmile().get(firstSmile.getStrikes()[0]).getConvention(); HashMap<Double, OptionSmileData> mySurface = new HashMap<Double, OptionSmileData>(); double[] mats = new double[smiles.length]; for(int t = 0; t<smiles.length;t++) { double maturity = smiles[t].getMaturity(); mats[t] = maturity; if(!(smiles[t].getReferenceDate().equals(myReferenceDate))) throw new IllegalArgumentException("All reference dates must be equal"); if(!(smiles[t].getUnderlying().equals(myUnderlying))) throw new IllegalArgumentException("Option must be written on the same underlying"); QuotingConvention testConvention = smiles[t].getSmile().get(smiles[t].getStrikes()[0]).getConvention(); if(!(testConvention.equals(myConvention))) throw new IllegalArgumentException("Convention must be the same for all points in the surface"); mySurface.put(maturity, smiles[t]); } this.underlying = myUnderlying; this.referenceDate = myReferenceDate; this.discountCurve = discountCurve; this.equityForwardCurve = equityForwardCurve; this.surface = mySurface; this.convention = myConvention; this.maturities = mats; } public DiscountCurveInterface getDiscountCurve() { return this.discountCurve; } public DiscountCurveInterface getEquityForwardCurve() { return this.equityForwardCurve; } public String getName() { return this.underlying; } public LocalDate getReferenceDate() { return this.referenceDate; } public QuotingConvention getQuotingConvention() { return this.convention; } public HashMap<Double, OptionSmileData> getSurface(){ return this.surface; } public double[] getMaturities() { return this.maturities; } public double getValue(double maturity, double strike){ return getValue(maturity, strike, this.convention); } public double getValue(double maturity, double strike, QuotingConvention quotingConvention) { return getValue(null,maturity,strike,quotingConvention); } public double getValue(AnalyticModelInterface model, double maturity, double strike, QuotingConvention quotingConvention) { if(quotingConvention.equals(this.convention)) { OptionSmileData relevantSmile = this.surface.get(maturity); return relevantSmile.getSmile().get(strike).getValue(); }else { if(quotingConvention == QuotingConvention.PRICE && this.convention == QuotingConvention.VOLATILITYLOGNORMAL) { double forwardPrice = equityForwardCurve.getValue(maturity); double discountBond = discountCurve.getValue(maturity); OptionSmileData relevantSmile = this.surface.get(maturity); double volatility = relevantSmile.getSmile().get(strike).getValue(); return net.finmath.functions.AnalyticFormulas.blackScholesGeneralizedOptionValue(forwardPrice, volatility, maturity, strike, discountBond); }else if(quotingConvention == QuotingConvention.VOLATILITYLOGNORMAL && this.convention == QuotingConvention.PRICE) { double forwardPrice = equityForwardCurve.getValue(maturity); double discountBond = discountCurve.getValue(maturity); OptionSmileData relevantSmile = this.surface.get(maturity); double price = relevantSmile.getSmile().get(strike).getValue(); return net.finmath.functions.AnalyticFormulas.blackScholesOptionImpliedVolatility(forwardPrice,maturity,strike,discountBond,price); } return 0.0; } } public OptionSmileData getSmile(double maturity) { return surface.get(maturity); } }
package org.xins.server; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.znerd.xmlenc.XMLOutputter; /** * Base class for API implementation classes. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) */ public abstract class API extends Object implements DefaultReturnCodes { // Class fields /** * Checks if the specified value is <code>null</code> or an empty string. * Only if it is then <code>true</code> is returned. * * @param value * the value to check. * * @return * <code>true</code> if and only if <code>value != null &amp;&amp; * value.length() != 0</code>. */ protected final static boolean isMissing(String value) { return value == null || value.length() == 0; } // Class functions // Constructors /** * Constructs a new <code>API</code> object. */ protected API() { _functionsByName = new HashMap(); } // Fields /** * Map that maps function names to <code>Function</code> instances. * Contains all functions associated with this API. * * <p />This field is initialised to a non-<code>null</code> value by the * constructor. */ private final Map _functionsByName; // Methods /** * Initialises this API. * * <p />The implementation of this method in class {@link API} is empty. * * @param properties * the properties, can be <code>null</code>. * * @throws Throwable * if the initialisation fails. */ public void init(Properties properties) throws Throwable { // empty } /** * Callback method invoked when a function is constructed. * * @param function * the function that is added, not <code>null</code>. * * @throws NullPointerException * if <code>function == null</code>. */ final void functionAdded(Function function) { _functionsByName.put(function.getName(), function); } /** * Returns the function with the specified name. * * @param name * the name of the function, will not be checked if it is * <code>null</code>. * * @return * the function with the specified name, or <code>null</code> if there * is no match. */ public final Function getFunction(String name) { return (Function) _functionsByName.get(name); } /** * Forwards a call to the <code>handleCall(CallContext)</code> method. * * @param out * the output stream to write to, not <code>null</code>. * * @param map * the parameters, not <code>null</code>. * * @throws IOException * if an I/O error occurs. */ final void handleCall(PrintWriter out, Map map) throws IOException { // Reset the XMLOutputter StringWriter stringWriter = new StringWriter(); XMLOutputter xmlOutputter = new XMLOutputter(stringWriter, "UTF-8"); // Create a new call context CallContext context = new CallContext(xmlOutputter, map); // Forward the call boolean exceptionThrown = true; boolean success; String code; try { handleCall(context); success = context.getSuccess(); code = context.getCode(); exceptionThrown = false; } catch (Throwable exception) { success = false; code = INTERNAL_ERROR; xmlOutputter.reset(out, "UTF-8"); xmlOutputter.startTag("result"); xmlOutputter.attribute("success", "false"); xmlOutputter.attribute("code", code); xmlOutputter.startTag("param"); xmlOutputter.attribute("name", "_exception.class"); xmlOutputter.pcdata(exception.getClass().getName()); String message = exception.getMessage(); if (message != null && message.length() > 0) { xmlOutputter.endTag(); xmlOutputter.startTag("param"); xmlOutputter.attribute("name", "_exception.message"); xmlOutputter.pcdata(message); } StringWriter stWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stWriter); exception.printStackTrace(printWriter); String stackTrace = stWriter.toString(); if (stackTrace != null && stackTrace.length() > 0) { xmlOutputter.endTag(); xmlOutputter.startTag("param"); xmlOutputter.attribute("name", "_exception.stacktrace"); xmlOutputter.pcdata(stackTrace); } xmlOutputter.close(); } if (!exceptionThrown) { out.print(stringWriter.toString()); } Function f = getFunction(context.getFunction()); long start = context.getStart(); long duration = System.currentTimeMillis() - start; f.performedCall(start, duration, success, code); out.flush(); } /** * Handles a call to this API. * * @param context * the context for this call, never <code>null</code>. * * @throws Throwable * if anything goes wrong. */ protected abstract void handleCall(CallContext context) throws Throwable; /** * Callback method invoked when a function throws an exception. This method * will be invoked if and only if {@link #handleCall(CallContext)} throws * an exception of some sort. * * @param function * the name of the function, will not be <code>null</code>. * * @param start * the timestamp indicating when the call was started, as a number of * milliseconds since midnight January 1, 1970 UTC. * * @param duration * the duration of the function call, as a number of milliseconds. * * @param code * the function result code, or <code>null</code>. */ protected void callFailed(String function, long start, long duration, String code) { Function f = getFunction(function); if (f == null) { // TODO: Should we throw an exception? Probably just log an error return; } f.performedCall(start, duration, false, code); } }
package edu.umd.cs.findbugs.bluej; import org.apache.bcel.classfile.JavaClass; import edu.umd.cs.findbugs.BugCollection; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugPattern; import edu.umd.cs.findbugs.TextUIBugReporter; import edu.umd.cs.findbugs.classfile.ClassDescriptor; public class MyReporter extends TextUIBugReporter { BugCollection bugs; MyReporter(BugCollection bugs) { this.bugs = bugs; } @Override protected void doReportBug(BugInstance bugInstance) { BugPattern bugPattern = bugInstance.getBugPattern(); if (bugInstance.getBugRank() <= 14 && bugPattern.getCategory().equals("CORRECTNESS") && ! bugPattern.getType().startsWith("DE_") && ! bugPattern.getType().startsWith("HE_") && ! bugPattern.getType().startsWith("SE_") ) bugs.add(bugInstance); } public void finish() { // TODO Auto-generated method stub } public void observeClass(JavaClass javaClass) { // TODO Auto-generated method stub } public void observeClass(ClassDescriptor classDescriptor) { // TODO Auto-generated method stub } public BugCollection getBugCollection() { return bugs; } }
package org.xins.server; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.TimeZone; import javax.servlet.ServletRequest; import org.xins.logdoc.LogStatistics; import org.xins.types.Type; import org.xins.types.TypeValueException; import org.xins.types.standard.Text; import org.xins.util.MandatoryArgumentChecker; import org.xins.util.collections.BasicPropertyReader; import org.xins.util.collections.InvalidPropertyValueException; import org.xins.util.collections.MissingRequiredPropertyException; import org.xins.util.collections.PropertyReader; import org.xins.util.collections.PropertyReaderUtils; import org.xins.util.collections.PropertiesPropertyReader; import org.xins.util.collections.expiry.ExpiryFolder; import org.xins.util.collections.expiry.ExpiryStrategy; import org.xins.util.io.FastStringWriter; import org.xins.util.manageable.BootstrapException; import org.xins.util.manageable.DeinitializationException; import org.xins.util.manageable.InitializationException; import org.xins.util.manageable.Manageable; import org.xins.util.text.DateConverter; import org.xins.util.text.FastStringBuffer; import org.xins.util.text.ParseException; import org.znerd.xmlenc.XMLOutputter; /** * Base class for API implementation classes. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) */ public abstract class API extends Manageable implements DefaultResultCodes { // Class fields /** * String returned by the function <code>_GetStatistics</code> when certain * information is not available. */ private static final String NOT_AVAILABLE = "N/A"; /** * Successful empty call result. */ private static final CallResult SUCCESSFUL_RESULT = new BasicCallResult(true, null, null, null); /** * The runtime (init) property that contains the ACL descriptor. */ private static final String ACL_PROPERTY = "org.xins.server.acl"; // Class functions // Constructors protected API(String name) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("name", name); if (name.length() < 1) { throw new IllegalArgumentException("name.length() (" + name.length() + " < 1"); } // Initialize fields _name = name; _startupTimestamp = System.currentTimeMillis(); _manageableObjects = new ArrayList(); _functionsByName = new HashMap(); _functionList = new ArrayList(); _resultCodesByName = new HashMap(); _resultCodeList = new ArrayList(); } // Fields /** * The name of this API. Cannot be <code>null</code> and cannot be an empty * string. */ private final String _name; /** * Flag that indicates if this API is session-based. */ private boolean _sessionBased; /** * List of registered manageable objects. See {@link #add(Manageable)}. * * <p />This field is initialized to a non-<code>null</code> value by the * constructor. */ private final List _manageableObjects; /** * Expiry strategy for <code>_sessionsByID</code>. * * <p />For session-based APIs, this field is initialized to a * non-<code>null</code> value by the initialization method * {@link #init(PropertyReader)}. */ private ExpiryStrategy _sessionExpiryStrategy; /** * Collection that maps session identifiers to <code>Session</code> * instances. Contains all sessions associated with this API. * * <p />For session-based APIs, this field is initialized to a * non-<code>null</code> value by the initialization method * {@link #init(PropertyReader)}. */ private ExpiryFolder _sessionsByID; /** * Map that maps function names to <code>Function</code> instances. * Contains all functions associated with this API. * * <p />This field is initialized to a non-<code>null</code> value by the * constructor. */ private final Map _functionsByName; /** * List of all functions. This field cannot be <code>null</code>. */ private final List _functionList; /** * Map that maps result code names to <code>ResultCode</code> instances. * Contains all result codes associated with this API. * * <p />This field is initialized to a non-<code>null</code> value by the * constructor. */ private final Map _resultCodesByName; /** * List of all result codes. This field cannot be <code>null</code>. */ private final List _resultCodeList; /** * The build-time settings. This field is initialized exactly once by * {@link #bootstrap(PropertyReader)}. It can be <code>null</code> before * that. */ private PropertyReader _buildSettings; /** * The runtime-time settings. This field is initialized by * {@link #init(PropertyReader)}. It can be <code>null</code> before that. */ private PropertyReader _runtimeSettings; /** * The type that applies for session identifiers. For session-based APIs * this will be set in {@link #init(PropertyReader)}. */ private SessionIDType _sessionIDType; /** * The session ID generator. For session-based APIs this will be set in * {@link #init(PropertyReader)}. */ private SessionIDType.Generator _sessionIDGenerator; /** * Flag that indicates if the shutdown sequence has been initiated. */ private boolean _shutDown; // TODO: Use a state for this /** * Timestamp indicating when this API instance was created. */ private final long _startupTimestamp; /** * Host name for the machine that was used for this build. */ private String _buildHost; /** * Time stamp that indicates when this build was done. */ private String _buildTime; /** * XINS version used to build the web application package. */ private String _buildVersion; /** * The time zone used when generating dates for output. */ private TimeZone _timeZone; /** * The access rule list. */ private AccessRuleList _accessRuleList; // Methods /** * Gets the name of this API. * * @return * the name of this API, never <code>null</code> and never an empty * string. */ public final String getName() { return _name; } /** * Gets the timestamp that indicates when this <code>API</code> instance * was created. * * @return * the time this instance was constructed, as a number of milliseconds * since midnight January 1, 1970. */ public final long getStartupTimestamp() { return _startupTimestamp; } /** * Returns the applicable time zone. * * @return * the time zone, not <code>null</code>. * * @since XINS 0.95 */ public final TimeZone getTimeZone() { return _timeZone; } public final int getCurrentSessions() throws IllegalStateException { // Check preconditions if (! _sessionBased) { throw new IllegalStateException("This API is not session-based."); } return _sessionsByID.size(); } /** * Checks if response validation is enabled. * * @return * <code>true</code> if response validation is enabled, * <code>false</code> otherwise. * * @since XINS 0.98 * * @deprecated * Deprecated since XINS 0.157, with no replacement. This method always * returns <code>false</code>. */ public final boolean isResponseValidationEnabled() { return false; } /** * Bootstraps this API (wrapper method). This method calls * {@link #bootstrapImpl2(PropertyReader)}. * * @param buildSettings * the build-time configuration properties, not <code>null</code>. * * @throws MissingRequiredPropertyException * if a required property is not given. * * @throws InvalidPropertyValueException * if a property has an invalid value. * * @throws BootstrapException * if the bootstrap fails. */ protected final void bootstrapImpl(PropertyReader buildSettings) throws MissingRequiredPropertyException, InvalidPropertyValueException, BootstrapException { // Log the time zone // TODO: Why log the time zone? _timeZone = TimeZone.getDefault(); String tzShortName = _timeZone.getDisplayName(false, TimeZone.SHORT); String tzLongName = _timeZone.getDisplayName(false, TimeZone.LONG); Log.log_4004(tzShortName, tzLongName); // Store the build-time settings _buildSettings = buildSettings; // Check if this API is session-based _sessionBased = PropertyReaderUtils.getBooleanProperty(buildSettings, "org.xins.api.sessionBased", false); if (_sessionBased) { Log.log_2013(); } else { Log.log_2014(); } // XXX: Allow configuration of session ID type ? // Initialize session-based API if (_sessionBased) { Log.log_2015(); // Initialize session ID type _sessionIDType = new BasicSessionIDType(this); _sessionIDGenerator = _sessionIDType.getGenerator(); // Determine session time-out duration and precision (in seconds) int timeOut = PropertyReaderUtils.getIntProperty(buildSettings, "org.xins.api.sessionTimeOut"); int precision = PropertyReaderUtils.getIntProperty(buildSettings, "org.xins.api.sessionTimeOutPrecision"); Log.log_2017(timeOut, precision); // Create expiry strategy and folder final long MINUTE_IN_MS = 60000L; _sessionExpiryStrategy = new ExpiryStrategy(timeOut * MINUTE_IN_MS, precision * MINUTE_IN_MS); _sessionsByID = new ExpiryFolder("sessionsByID", // name of folder (for logging) _sessionExpiryStrategy, // expiry strategy false, // strict thread sync checking? (TODO) 5000L); // max queue wait time in ms (TODO) Log.log_2016(); } // Get build-time properties _buildHost = _buildSettings.get("org.xins.api.build.host"); _buildTime = _buildSettings.get("org.xins.api.build.time"); _buildVersion = _buildSettings.get("org.xins.api.build.version"); Log.log_2018(_buildHost, _buildTime, _buildVersion); // Let the subclass perform initialization bootstrapImpl2(buildSettings); // Bootstrap all instances int count = _manageableObjects.size(); for (int i = 0; i < count; i++) { Manageable m = (Manageable) _manageableObjects.get(i); String className = m.getClass().getName(); Log.log_2019(className, _name); try { m.bootstrap(_buildSettings); Log.log_2020(_name, className); } catch (MissingRequiredPropertyException exception) { Log.log_2021(_name, className, exception.getPropertyName()); throw exception; } catch (InvalidPropertyValueException exception) { Log.log_2022(_name, className, exception.getPropertyName(), exception.getPropertyValue()); throw exception; } catch (BootstrapException exception) { Log.log_2023(_name, className, exception.getMessage()); throw exception; } catch (Throwable exception) { Log.log_2024(exception, _name, className); throw new BootstrapException(exception); } } // Bootstrap all functions count = _functionList.size(); for (int i = 0; i < count; i++) { Function f = (Function) _functionList.get(i); String functionName = f.getName(); Log.log_2027(_name, functionName); try { f.bootstrap(_buildSettings); Log.log_2028(_name, functionName); } catch (MissingRequiredPropertyException exception) { Log.log_2029(_name, functionName, exception.getPropertyName()); throw exception; } catch (InvalidPropertyValueException exception) { Log.log_2030(_name, functionName, exception.getPropertyName(), exception.getPropertyValue()); throw exception; } catch (BootstrapException exception) { Log.log_2031(_name, functionName, exception.getMessage()); throw exception; } catch (Throwable exception) { Log.log_2032(exception, _name, functionName); throw new BootstrapException(exception); } } } /** * Bootstraps this API (implementation method). * * <p />The implementation of this method in class {@link API} is empty. * Custom subclasses can perform any necessary bootstrapping in this * class. * * <p />Note that bootstrapping and initialization are different. Bootstrap * includes only the one-time configuration of the API based on the * build-time settings, while the initialization * * <p />The {@link #add(Manageable)} may be called from this method, * and from this method <em>only</em>. * * @param buildSettings * the build-time properties, guaranteed not to be <code>null</code>. * * @throws MissingRequiredPropertyException * if a required property is not given. * * @throws InvalidPropertyValueException * if a property has an invalid value. * * @throws BootstrapException * if the bootstrap fails. */ protected void bootstrapImpl2(PropertyReader buildSettings) throws MissingRequiredPropertyException, InvalidPropertyValueException, BootstrapException { // empty } /** * Initializes this API. * * @param runtimeSettings * the runtime configuration settings, cannot be <code>null</code>. * * @throws MissingRequiredPropertyException * if a required property is missing. * * @throws InvalidPropertyValueException * if a property has an invalid value. * * @throws InitializationException * if the initialization failed for some other reason. */ protected final void initImpl(PropertyReader runtimeSettings) throws MissingRequiredPropertyException, InvalidPropertyValueException, InitializationException { // TODO: Check state // TODO: Perform rollback if initialization fails at some point Log.log_4005(_name); // Store runtime settings _runtimeSettings = runtimeSettings; // Initialize ACL subsystem String acl = runtimeSettings.get(ACL_PROPERTY); if (acl == null || acl.trim().length() < 1) { _accessRuleList = AccessRuleList.EMPTY; Log.log_4031(ACL_PROPERTY); } else { try { _accessRuleList = AccessRuleList.parseAccessRuleList(acl); int ruleCount = _accessRuleList.getRuleCount(); Log.log_4034(ruleCount); } catch (ParseException exception) { Log.log_4035(ACL_PROPERTY, acl, exception.getMessage()); throw new InvalidPropertyValueException(ACL_PROPERTY, acl, exception.getMessage()); } } // Initialize all instances int count = _manageableObjects.size(); for (int i = 0; i < count; i++) { Manageable m = (Manageable) _manageableObjects.get(i); String className = m.getClass().getName(); Log.log_4019(_name, className); try { m.init(runtimeSettings); Log.log_4020(_name, className); } catch (MissingRequiredPropertyException exception) { Log.log_4021(_name, className, exception.getPropertyName()); throw exception; } catch (InvalidPropertyValueException exception) { Log.log_4022(_name, className, exception.getPropertyName(), exception.getPropertyValue()); throw exception; } catch (InitializationException exception) { Log.log_4023(_name, className, exception.getMessage()); throw exception; } catch (Throwable exception) { Log.log_4024(exception, _name, className); throw new InitializationException(exception); } } // Initialize all functions count = _functionList.size(); for (int i = 0; i < count; i++) { Function f = (Function) _functionList.get(i); String functionName = f.getName(); Log.log_4025(_name, functionName); try { f.init(runtimeSettings); Log.log_4026(_name, functionName); } catch (MissingRequiredPropertyException exception) { Log.log_4027(_name, functionName, exception.getPropertyName()); throw exception; } catch (InvalidPropertyValueException exception) { Log.log_4028(_name, functionName, exception.getPropertyName(), exception.getPropertyValue()); throw exception; } catch (InitializationException exception) { Log.log_4029(_name, functionName, exception.getMessage()); throw exception; } catch (Throwable exception) { Log.log_4030(exception, _name, functionName); throw new InitializationException(exception); } } // TODO: Call initImpl2(PropertyReader) ? Log.log_4006(_name); } protected final void add(Manageable m) throws IllegalStateException, IllegalArgumentException { // Check state Manageable.State state = getState(); if (getState() != BOOTSTRAPPING) { // TODO: Log throw new IllegalStateException("State is " + state + " instead of " + BOOTSTRAPPING + '.'); } // Check preconditions MandatoryArgumentChecker.check("m", m); String className = m.getClass().getName(); Log.log_2025(_name, className); // Store the manageable object in the list _manageableObjects.add(m); Log.log_2026(_name, className); } /** * Performs shutdown of this XINS API. This method will never throw any * exception. */ protected final void deinitImpl() { _shutDown = true; // Stop expiry strategy _sessionExpiryStrategy.stop(); // Destroy all sessions Log.log_6003(_sessionsByID.size()); _sessionsByID = null; // Deinitialize instances int count = _manageableObjects.size(); for (int i = 0; i < count; i++) { Manageable m = (Manageable) _manageableObjects.get(i); String className = m.getClass().getName(); Log.log_6004(_name, className); try { m.deinit(); Log.log_6005(_name, className); } catch (DeinitializationException exception) { Log.log_6006(_name, className, exception.getMessage()); } catch (Throwable exception) { Log.log_6007(exception, _name, className); } } // Deinitialize functions count = _functionList.size(); for (int i = 0; i < count; i++) { Function f = (Function) _functionList.get(i); String functionName = f.getName(); Log.log_6008(_name, functionName); try { f.deinit(); Log.log_6009(_name, functionName); } catch (DeinitializationException exception) { Log.log_6010(_name, functionName, exception.getMessage()); } catch (Throwable exception) { Log.log_6011(exception, _name, functionName); } } } /** * Returns the name of the default function, if any. * * @return * the name of the default function, or <code>null</code> if there is * none. * * @deprecated * This method is deprecated since XINS 0.157, with no replacement. This * method will always return <code>null</code>. */ public String getDefaultFunctionName() { return null; } public boolean isSessionBased() throws IllegalStateException { assertUsable(); return _sessionBased; } public final SessionIDType getSessionIDType() throws IllegalStateException { // Check preconditions assertUsable(); if (! _sessionBased) { throw new IllegalStateException("This API is not session-based."); } return _sessionIDType; } final Session createSession() throws IllegalStateException { // Check preconditions assertUsable(); if (! _sessionBased) { throw new IllegalStateException("This API is not session-based."); } // Generate a session ID that does not yet exist Object sessionID; int count = 0; do { sessionID = _sessionIDGenerator.generateSessionID(); count++; } while (_sessionsByID.get(sessionID) != null); // Construct a Session object... Session session = new Session(this, sessionID); // ...store it... _sessionsByID.put(sessionID, session); // ...log it... Log.log_5010(sessionID, count); // ...and then return it return session; } final Session getSession(Object id) throws IllegalStateException { // Check preconditions assertUsable(); if (! _sessionBased) { throw new IllegalStateException("This API is not session-based."); } return (Session) _sessionsByID.get(id); } final Session getSessionByString(String idString) throws IllegalStateException, TypeValueException { // Check preconditions assertUsable(); if (! _sessionBased) { throw new IllegalStateException("This API is not session-based."); } return getSession(_sessionIDType.fromString(idString)); } /** * Callback method invoked when a function is constructed. * * @param function * the function that is added, not <code>null</code>. * * @throws NullPointerException * if <code>function == null</code>. */ final void functionAdded(Function function) throws NullPointerException { // TODO: Check the state here? _functionsByName.put(function.getName(), function); _functionList.add(function); } /** * Callback method invoked when a result code is constructed. * * @param resultCode * the result code that is added, not <code>null</code>. * * @throws NullPointerException * if <code>resultCode == null</code>. */ final void resultCodeAdded(ResultCode resultCode) throws NullPointerException { _resultCodesByName.put(resultCode.getName(), resultCode); _resultCodeList.add(resultCode); } /** * Returns the function with the specified name. * * @param name * the name of the function, will not be checked if it is * <code>null</code>. * * @return * the function with the specified name, or <code>null</code> if there * is no match. */ final Function getFunction(String name) { return (Function) _functionsByName.get(name); } /** * Forwards a call to a function. The call will actually be handled by * {@link Function#handleCall(long,ServletRequest)}. * * @param start * the start time of the request, in milliseconds since midnight January * 1, 1970. * * @param request * the original servlet request, not <code>null</code>. * * @return * the result of the call, never <code>null</code>. * * @throws NullPointerException * if <code>request == null</code>. * * @throws NoSuchFunctionException * if there is no matching function for the specified request. * * @throws AccessDeniedException * if access is denied for the specified combination of IP address and * function name. */ final CallResult handleCall(long start, ServletRequest request) throws NullPointerException, NoSuchFunctionException, AccessDeniedException { // Determine the function name String functionName = request.getParameter("_function"); if (functionName == null || functionName.length() == 0) { functionName = request.getParameter("function"); } if (functionName == null || functionName.length() == 0) { functionName = getDefaultFunctionName(); } // The function name is required if (functionName == null || functionName.length() == 0) { throw new NoSuchFunctionException(null); } // Check the access rule list String ip = request.getRemoteAddr(); boolean allow; try { allow = _accessRuleList.allow(ip, functionName); } catch (ParseException exception) { throw new Error("Malformed IP address: " + ip + '.'); } if (allow == false) { throw new AccessDeniedException(ip, functionName); } // Detect special functions if (functionName.charAt(0) == '_') { if ("_NoOp".equals(functionName)) { return SUCCESSFUL_RESULT; } else if ("_PerformGC".equals(functionName)) { return doPerformGC(); } else if ("_GetFunctionList".equals(functionName)) { return doGetFunctionList(); } else if ("_GetStatistics".equals(functionName)) { return doGetStatistics(); } else if ("_GetLogStatistics".equals(functionName)) { return doGetLogStatistics(); } else if ("_GetVersion".equals(functionName)) { return doGetVersion(); } else if ("_GetSettings".equals(functionName)) { return doGetSettings(); } else if ("_DisableFunction".equals(functionName)) { return doDisableFunction(request); } else if ("_EnableFunction".equals(functionName)) { return doEnableFunction(request); } else if ("_ResetStatistics".equals(functionName)) { return doResetStatistics(); } else { throw new NoSuchFunctionException(functionName); } } // Short-circuit if we are shutting down if (_shutDown) { // TODO: Add message return new BasicCallResult(false, "InternalError", null, null); } // Get the function object Function function = getFunction(functionName); if (function == null) { throw new NoSuchFunctionException(functionName); } // Forward the call to the function return function.handleCall(start, request); } /** * Performs garbage collection. * * @return * the call result, never <code>null</code>. */ private final CallResult doPerformGC() { System.gc(); return SUCCESSFUL_RESULT; } /** * Returns a list of all functions in this API. Per function the name and * the version are returned. * * @return * the call result, never <code>null</code>. */ private final CallResult doGetFunctionList() { // Initialize a builder CallResultBuilder builder = new CallResultBuilder(); int count = _functionList.size(); for (int i = 0; i < count; i++) { Function function = (Function) _functionList.get(i); builder.startTag("function"); builder.attribute("name", function.getName()); builder.attribute("version", function.getVersion()); builder.attribute("enabled", function.isEnabled() ? "true" : "false"); builder.endTag(); } return builder; } /** * Returns the call statistics for all functions in this API. * * @return * the call result, never <code>null</code>. */ private final CallResult doGetStatistics() { // Initialize a builder CallResultBuilder builder = new CallResultBuilder(); builder.param("startup", DateConverter.toDateString(_timeZone, _startupTimestamp)); builder.param("now", DateConverter.toDateString(_timeZone, System.currentTimeMillis())); // Currently available processors Runtime rt = Runtime.getRuntime(); try { builder.param("availableProcessors", String.valueOf(rt.availableProcessors())); } catch (NoSuchMethodError error) { // ignore: Runtime.availableProcessors() is not available in Java 1.3 } // Heap memory statistics builder.startTag("heap"); long free = rt.freeMemory(); long total = rt.totalMemory(); builder.attribute("used", String.valueOf(total - free)); builder.attribute("free", String.valueOf(free)); builder.attribute("total", String.valueOf(total)); try { builder.attribute("max", String.valueOf(rt.maxMemory())); } catch (NoSuchMethodError error) { // ignore: Runtime.maxMemory() is not available in Java 1.3 } builder.endTag(); // heap // Function-specific statistics int count = _functionList.size(); for (int i = 0; i < count; i++) { Function function = (Function) _functionList.get(i); FunctionStatistics stats = function.getStatistics(); long successfulCalls = stats.getSuccessfulCalls(); long unsuccessfulCalls = stats.getUnsuccessfulCalls(); long successfulDuration = stats.getSuccessfulDuration(); long unsuccessfulDuration = stats.getUnsuccessfulDuration(); String successfulAverage; String successfulMin; String successfulMinStart; String successfulMax; String successfulMaxStart; String lastSuccessfulStart; String lastSuccessfulDuration; if (successfulCalls == 0) { successfulAverage = NOT_AVAILABLE; successfulMin = NOT_AVAILABLE; successfulMinStart = NOT_AVAILABLE; successfulMax = NOT_AVAILABLE; successfulMaxStart = NOT_AVAILABLE; lastSuccessfulStart = NOT_AVAILABLE; lastSuccessfulDuration = NOT_AVAILABLE; } else if (successfulDuration == 0) { successfulAverage = "0"; successfulMin = String.valueOf(stats.getSuccessfulMin()); successfulMinStart = DateConverter.toDateString(_timeZone, stats.getSuccessfulMinStart()); successfulMax = String.valueOf(stats.getSuccessfulMax()); successfulMaxStart = DateConverter.toDateString(_timeZone, stats.getSuccessfulMaxStart()); lastSuccessfulStart = DateConverter.toDateString(_timeZone, stats.getLastSuccessfulStart()); lastSuccessfulDuration = String.valueOf(stats.getLastSuccessfulDuration()); } else { successfulAverage = String.valueOf(successfulDuration / successfulCalls); successfulMin = String.valueOf(stats.getSuccessfulMin()); successfulMinStart = DateConverter.toDateString(_timeZone, stats.getSuccessfulMinStart()); successfulMax = String.valueOf(stats.getSuccessfulMax()); successfulMaxStart = DateConverter.toDateString(_timeZone, stats.getSuccessfulMaxStart()); lastSuccessfulStart = DateConverter.toDateString(_timeZone, stats.getLastSuccessfulStart()); lastSuccessfulDuration = String.valueOf(stats.getLastSuccessfulDuration()); } String unsuccessfulAverage; String unsuccessfulMin; String unsuccessfulMinStart; String unsuccessfulMax; String unsuccessfulMaxStart; String lastUnsuccessfulStart; String lastUnsuccessfulDuration; if (unsuccessfulCalls == 0) { unsuccessfulAverage = NOT_AVAILABLE; unsuccessfulMin = NOT_AVAILABLE; unsuccessfulMinStart = NOT_AVAILABLE; unsuccessfulMax = NOT_AVAILABLE; unsuccessfulMaxStart = NOT_AVAILABLE; lastUnsuccessfulStart = NOT_AVAILABLE; lastUnsuccessfulDuration = NOT_AVAILABLE; } else if (unsuccessfulDuration == 0) { unsuccessfulAverage = "0"; unsuccessfulMin = String.valueOf(stats.getUnsuccessfulMin()); unsuccessfulMinStart = DateConverter.toDateString(_timeZone, stats.getUnsuccessfulMinStart()); unsuccessfulMax = String.valueOf(stats.getUnsuccessfulMax()); unsuccessfulMaxStart = DateConverter.toDateString(_timeZone, stats.getUnsuccessfulMaxStart()); lastUnsuccessfulStart = DateConverter.toDateString(_timeZone, stats.getLastUnsuccessfulStart()); lastUnsuccessfulDuration = String.valueOf(stats.getLastUnsuccessfulDuration()); } else { unsuccessfulAverage = String.valueOf(unsuccessfulDuration / unsuccessfulCalls); unsuccessfulMin = String.valueOf(stats.getUnsuccessfulMin()); unsuccessfulMinStart = DateConverter.toDateString(_timeZone, stats.getUnsuccessfulMinStart()); unsuccessfulMax = String.valueOf(stats.getUnsuccessfulMax()); unsuccessfulMaxStart = DateConverter.toDateString(_timeZone, stats.getUnsuccessfulMaxStart()); lastUnsuccessfulStart = DateConverter.toDateString(_timeZone, stats.getLastUnsuccessfulStart()); lastUnsuccessfulDuration = String.valueOf(stats.getLastUnsuccessfulDuration()); } builder.startTag("function"); builder.attribute("name", function.getName()); // Successful builder.startTag("successful"); builder.attribute("count", String.valueOf(successfulCalls)); builder.attribute("average", successfulAverage); builder.startTag("min"); builder.attribute("start", successfulMinStart); builder.attribute("duration", successfulMin); builder.endTag(); // min builder.startTag("max"); builder.attribute("start", successfulMaxStart); builder.attribute("duration", successfulMax); builder.endTag(); // max builder.startTag("last"); builder.attribute("start", lastSuccessfulStart); builder.attribute("duration", lastSuccessfulDuration); builder.endTag(); // last builder.endTag(); // successful // Unsuccessful builder.startTag("unsuccessful"); builder.attribute("count", String.valueOf(unsuccessfulCalls)); builder.attribute("average", unsuccessfulAverage); builder.startTag("min"); builder.attribute("start", unsuccessfulMinStart); builder.attribute("duration", unsuccessfulMin); builder.endTag(); // min builder.startTag("max"); builder.attribute("start", unsuccessfulMaxStart); builder.attribute("duration", unsuccessfulMax); builder.endTag(); // max builder.startTag("last"); builder.attribute("start", lastUnsuccessfulStart); builder.attribute("duration", lastUnsuccessfulDuration); builder.endTag(); // last builder.endTag(); // unsuccessful builder.endTag(); // function } return builder; } /** * Returns the log statistics for all functions in this API. * * @return * the call result, never <code>null</code>. */ private final CallResult doGetLogStatistics() { // Initialize a builder CallResultBuilder builder = new CallResultBuilder(); builder.startTag("statistics"); LogStatistics.Entry[] entries = Log.getStatistics().getEntries(); int entryCount = entries.length; for (int i = 0; i < entryCount; i++) { LogStatistics.Entry entry = entries[i]; builder.startTag("entry"); builder.attribute("id", entry.getID()); builder.attribute("count", String.valueOf(entry.getCount())); builder.endTag(); // entry } builder.endTag(); // statistics return builder; } /** * Returns the XINS version. * * @return * the call result, never <code>null</code>. */ private final CallResult doGetVersion() { CallResultBuilder builder = new CallResultBuilder(); builder.param("java.version", System.getProperty("java.version")); builder.param("xmlenc.version", org.znerd.xmlenc.Library.getVersion()); builder.param("xins.version", Library.getVersion()); return builder; } /** * Returns the settings. * * @return * the call result, never <code>null</code>. */ private final CallResult doGetSettings() { CallResultBuilder builder = new CallResultBuilder(); // Build settings Iterator names = _buildSettings.getNames(); builder.startTag("build"); while (names.hasNext()) { String key = (String) names.next(); String value = _buildSettings.get(key); builder.startTag("property"); builder.attribute("name", key); builder.pcdata(value); builder.endTag(); } builder.endTag(); // Runtime settings names = _runtimeSettings.getNames(); builder.startTag("runtime"); while (names.hasNext()) { String key = (String) names.next(); String value = _runtimeSettings.get(key); builder.startTag("property"); builder.attribute("name", key); builder.pcdata(value); builder.endTag(); } builder.endTag(); // System properties Enumeration e = System.getProperties().propertyNames(); builder.startTag("system"); while (e.hasMoreElements()) { String key = (String) e.nextElement(); String value = System.getProperty(key); if (key != null && value != null && key.length() > 0 && value.length() > 0) { builder.startTag("property"); builder.attribute("name", key); builder.pcdata(value); builder.endTag(); } } builder.endTag(); return builder; } /** * Enables a function. * * @param request * the servlet request, cannot be <code>null</code>. * * @return * the call result, never <code>null</code>. * * @throws NullPointerException * if <code>request == null</code>. */ private final CallResult doEnableFunction(ServletRequest request) throws NullPointerException { // Get the name of the function to enable String functionName = request.getParameter("functionName"); if (functionName == null || functionName.length() < 1) { return new BasicCallResult(false, "MissingParameters", null, null); } // Get the Function object Function function = getFunction(functionName); if (function == null) { return new BasicCallResult(false, "InvalidParameters", null, null); } // Enable or disable the function function.setEnabled(true); return SUCCESSFUL_RESULT; } /** * Disables a function. * * @param request * the servlet request, cannot be <code>null</code>. * * @return * the call result, never <code>null</code>. * * @throws NullPointerException * if <code>request == null</code>. */ private final CallResult doDisableFunction(ServletRequest request) throws NullPointerException { // Get the name of the function to disable String functionName = request.getParameter("functionName"); if (functionName == null || functionName.length() < 1) { return new BasicCallResult(false, "MissingParameters", null, null); } // Get the Function object Function function = getFunction(functionName); if (function == null) { return new BasicCallResult(false, "InvalidParameters", null, null); } // Enable or disable the function function.setEnabled(false); return SUCCESSFUL_RESULT; } /** * Resets the statistics. * * @return * the call result, never <code>null</code>. */ private final CallResult doResetStatistics() { // Function-specific statistics int count = _functionList.size(); for (int i = 0; i < count; i++) { Function function = (Function) _functionList.get(i); function.getStatistics().resetStatistics(); } return SUCCESSFUL_RESULT; } }
package ai.h2o.automl; import ai.h2o.automl.strategies.initial.InitModel; import ai.h2o.automl.utils.AutoMLUtils; import hex.Model; import hex.ModelBuilder; import hex.ScoreKeeper; import hex.StackedEnsembleModel; import hex.deeplearning.DeepLearningModel; import hex.glm.GLMModel; import hex.grid.Grid; import hex.grid.GridSearch; import hex.grid.HyperSpaceSearchCriteria; import hex.tree.SharedTreeModel; import hex.tree.drf.DRFModel; import hex.tree.gbm.GBMModel; import water.*; import water.api.schemas3.ImportFilesV3; import water.api.schemas3.KeyV3; import water.exceptions.H2OAbstractRuntimeException; import water.fvec.Frame; import water.fvec.Vec; import water.parser.ParseDataset; import water.parser.ParseSetup; import water.util.IcedHashMapGeneric; import water.util.Log; import java.util.*; import static water.Key.make; /** * Initial draft of AutoML * * AutoML is a node-local driver class that is responsible for managing concurrent * strategies of execution in an effort to discover an optimal supervised model for some * given (dataset, response, loss) combo. */ public final class AutoML extends Lockable<AutoML> implements TimedH2ORunnable { private final boolean verifyImmutability = true; // check that trainingFrame hasn't been messed with private AutoMLBuildSpec buildSpec; // all parameters for doing this AutoML build private Frame origTrainingFrame; // untouched original training frame public AutoMLBuildSpec getBuildSpec() { return buildSpec; } public Frame getTrainingFrame() { return trainingFrame; } public Frame getValidationFrame() { return validationFrame; } public Vec getResponseColumn() { return responseColumn; } public FrameMetadata getFrameMetadata() { return frameMetadata; } private Frame trainingFrame; // munged training frame: can add and remove Vecs, but not mutate Vec data in place private Frame validationFrame; // optional validation frame private Vec responseColumn; FrameMetadata frameMetadata; // metadata for trainingFrame // TODO: remove dead code private Key<Grid> gridKey; // Grid key from GridSearch private boolean isClassification; private long stopTimeMs; private Job job; // the Job object for the build of this AutoML. TODO: can we have > 1? // TODO: make non-transient private transient ArrayList<Job> jobs; /** * Identifier for models that should be grouped together in the leaderboard * (e.g., "airlines" and "iris"). */ private String project; private Leaderboard leaderboard; // check that we haven't messed up the original Frame private Vec[] originalTrainingFrameVecs; private String[] originalTrainingFrameNames; private long[] originalTrainingFrameChecksums; // TODO: UGH: this should be dynamic, and it's easy to make it so public enum algo { RF, GBM, GLM, GLRM, DL, KMEANS } // consider EnumSet public AutoML() { super(null); } public AutoML(Key<AutoML> key, AutoMLBuildSpec buildSpec) { super(key); this.buildSpec = buildSpec; this.origTrainingFrame = DKV.getGet(buildSpec.input_spec.training_frame); this.validationFrame = DKV.getGet(buildSpec.input_spec.validation_frame); if (null == buildSpec.input_spec.training_frame && null != buildSpec.input_spec.training_path) this.origTrainingFrame = importParseFrame(buildSpec.input_spec.training_path, buildSpec.input_spec.parse_setup); if (null == buildSpec.input_spec.validation_frame && null != buildSpec.input_spec.validation_path) this.validationFrame = importParseFrame(buildSpec.input_spec.validation_path, buildSpec.input_spec.parse_setup); if (null == this.origTrainingFrame) throw new IllegalArgumentException("No training frame; user specified training_path: " + buildSpec.input_spec.training_path + " and training_frame: " + buildSpec.input_spec.training_frame); this.trainingFrame = new Frame(origTrainingFrame); DKV.put(this.trainingFrame); this.responseColumn = trainingFrame.vec(buildSpec.input_spec.response_column); if (verifyImmutability) { // check that we haven't messed up the original Frame originalTrainingFrameVecs = origTrainingFrame.vecs().clone(); originalTrainingFrameNames = origTrainingFrame.names().clone(); originalTrainingFrameChecksums = new long[originalTrainingFrameVecs.length]; for (int i = 0; i < originalTrainingFrameVecs.length; i++) originalTrainingFrameChecksums[i] = originalTrainingFrameVecs[i].checksum(); } // TODO: allow the user to set the project via the buildspec String[] path = this.origTrainingFrame._key.toString().split("/"); project = path[path.length - 1] .replace(".hex", "") .replace(".CSV", "") .replace(".XLS", "") .replace(".XSLX", "") .replace(".SVMLight", "") .replace(".ARFF", "") .replace(".ORC", "") .replace(".csv", "") .replace(".xls", "") .replace(".xslx", "") .replace(".svmlight", "") .replace(".arff", "") .replace(".orc", ""); leaderboard = new Leaderboard(project); /* TODO if( excludeAlgos!=null ) { HashSet<algo> m = new HashSet<>(); Collections.addAll(m,excludeAlgos); _excludeAlgos = m.toArray(new algo[m.size()]); } else _excludeAlgos =null; _allowMutations=tryMutations; */ this.jobs = new ArrayList<>(); } /* public AutoML(Key<AutoML> key, String datasetName, Frame fr, Frame[] relations, String responseName, String loss, long maxTime, double minAccuracy, boolean ensemble, algo[] excludeAlgos, boolean tryMutations ) { this(key,datasetName,fr,relations,fr.find(responseName),loss,maxTime,minAccuracy,ensemble,excludeAlgos,tryMutations); } */ public static AutoML makeAutoML(Key<AutoML> key, AutoMLBuildSpec buildSpec) { // if (buildSpec.input_spec.parse_setup == null) // buildSpec.input_spec.parse_setup = ParseSetup.guessSetup(); // use defaults! AutoML autoML = new AutoML(key, buildSpec); if (null == autoML.trainingFrame) throw new IllegalArgumentException("No training data has been specified, either as a path or a key."); /* TODO: joins Frame[] relations = null==relationPaths?null:new Frame[relationPaths.length]; if( null!=relationPaths ) for(int i=0;i<relationPaths.length;++i) relations[i] = importParseFrame(relationPaths[i]); */ return autoML; } private static Frame importParseFrame(ImportFilesV3.ImportFiles importFiles, ParseSetup userSetup) { ArrayList<String> files = new ArrayList(); ArrayList<String> keys = new ArrayList(); ArrayList<String> fails = new ArrayList(); ArrayList<String> dels = new ArrayList(); H2O.getPM().importFiles(importFiles.path, null, files, keys, fails, dels); importFiles.files = files.toArray(new String[0]); importFiles.destination_frames = keys.toArray(new String[0]); importFiles.fails = fails.toArray(new String[0]); importFiles.dels = dels.toArray(new String[0]); String datasetName = importFiles.path.split("\\.(?=[^\\.]+$)")[0]; Key[] realKeys = new Key[keys.size()]; for (int i = 0; i < keys.size(); i++) realKeys[i] = make(keys.get(i)); // TODO: we always have to tell guessSetup about single quotes?! ParseSetup guessedParseSetup = ParseSetup.guessSetup(realKeys, false, ParseSetup.GUESS_HEADER); return ParseDataset.parse(make(datasetName), realKeys, true, guessedParseSetup); } // used to launch the AutoML asynchronously @Override public void run() { stopTimeMs = System.currentTimeMillis() + Math.round(1000 * buildSpec.build_control.stopping_criteria.max_runtime_secs()); try { learn(); } catch (AutoMLDoneException e) { // pass :) } } @Override public void stop() { if (null == jobs) return; // already stopped for (Job j : jobs) j.stop(); for (Job j : jobs) j.get(); // Hold until they all completely stop. jobs = null; // TODO: add a failsafe, if we haven't marked off as much work as we originally intended? // If we don't, we end up with an exceptional completion. } public long getStopTimeMs() { return stopTimeMs; } public long timeRemainingMs() { long remaining = getStopTimeMs() - System.currentTimeMillis(); return Math.max(0, remaining); } @Override public boolean keepRunning() { return timeRemainingMs() > 0; } public void pollAndUpdateProgress(String name, long workContribution, Job parentJob, Job subJob) { if (null == subJob) { parentJob.update(workContribution, "SKIPPED: " + name); return; } Log.info(name + " started"); jobs.add(subJob); long lastWorkedSoFar = 0; long cumulative = 0; while (subJob.isRunning()) { long workedSoFar = Math.round(subJob.progress() * workContribution); cumulative += workedSoFar; parentJob.update(Math.round(workedSoFar - lastWorkedSoFar), name); try { Thread.currentThread().sleep(1000); } catch (InterruptedException e) { // keep going } lastWorkedSoFar = workedSoFar; } // add remaining work parentJob.update(workContribution - lastWorkedSoFar); Log.info(name + " complete"); try { jobs.remove(subJob); } catch (NullPointerException npe) {} // stop() can null jobs; can't just do a pre-check, because there's a race } /** * Helper for hex.ModelBuilder. * @return */ public Job trainModel(Key<Model> key, String algoURLName, Model.Parameters parms) { String algoName = ModelBuilder.algoName(algoURLName); if (null == key) key = ModelBuilder.defaultKey(algoName); Job job = new Job<>(key,ModelBuilder.javaName(algoURLName), algoName); ModelBuilder builder = ModelBuilder.make(algoURLName, job, key); if (builder._parms._max_runtime_secs == 0) builder._parms._max_runtime_secs = Math.round(timeRemainingMs() / 1000.0); else builder._parms._max_runtime_secs = Math.min(builder._parms._max_runtime_secs, Math.round(timeRemainingMs() / 1000.0)); builder._parms = parms; builder.init(false); // validate parameters // TODO: handle error_count and messages return builder.trainModel(); } /** * Do a random hyperparameter search. Caller must eventually do a <i>get()</i> * on the returned Job to ensure that it's complete. * @param algoName * @param baseParms * @param searchParms * @return the started hyperparameter search job */ public Job<Grid> hyperparameterSearch(String algoName, Model.Parameters baseParms, Map<String, Object[]> searchParms) { if (0.0 == baseParms._max_runtime_secs) { Log.info("AutoML: out of time; skipping " + algoName + " hyperparameter search"); return null; } Log.info("AutoML: starting " + algoName + " hyperparameter search"); HyperSpaceSearchCriteria.RandomDiscreteValueSearchCriteria searchCriteria = (HyperSpaceSearchCriteria.RandomDiscreteValueSearchCriteria)buildSpec.build_control.stopping_criteria.clone(); if (searchCriteria.max_runtime_secs() == 0) searchCriteria.set_max_runtime_secs(this.timeRemainingMs() / 1000.0); else searchCriteria.set_max_runtime_secs(Math.min(searchCriteria.max_runtime_secs(), this.timeRemainingMs() / 1000.0)); Job<Grid> gridJob = GridSearch.startGridSearch(gridKey, baseParms, searchParms, new GridSearch.SimpleParametersBuilderFactory(), searchCriteria); return gridJob; } Job<DRFModel>defaultRandomForest() { if (0.0 == timeRemainingMs()) { Log.info("AutoML: out of time; skipping XRT"); return null; } DRFModel.DRFParameters drfParameters = new DRFModel.DRFParameters(); drfParameters._train = trainingFrame._key; if (null != validationFrame) drfParameters._valid = validationFrame._key; drfParameters._response_column = buildSpec.input_spec.response_column; drfParameters._ignored_columns = buildSpec.input_spec.ignored_columns; // required for stacking: drfParameters._nfolds = 5; drfParameters._fold_assignment = Model.Parameters.FoldAssignmentScheme.Modulo; drfParameters._keep_cross_validation_predictions = true; Job randomForestJob = trainModel(null, "drf", drfParameters); return randomForestJob; } Job<DRFModel>defaultExtremelyRandomTrees() { if (0.0 == timeRemainingMs()) { Log.info("AutoML: out of time; skipping XRT"); return null; } DRFModel.DRFParameters drfParameters = new DRFModel.DRFParameters(); drfParameters._train = trainingFrame._key; if (null != validationFrame) drfParameters._valid = validationFrame._key; drfParameters._response_column = buildSpec.input_spec.response_column; drfParameters._ignored_columns = buildSpec.input_spec.ignored_columns; drfParameters._histogram_type = SharedTreeModel.SharedTreeParameters.HistogramType.Random; // required for stacking: drfParameters._nfolds = 5; drfParameters._fold_assignment = Model.Parameters.FoldAssignmentScheme.Modulo; drfParameters._keep_cross_validation_predictions = true; Job randomForestJob = trainModel(ModelBuilder.defaultKey("XRT"), "drf", drfParameters); return randomForestJob; } public Job<Grid> defaultSearchGLM() { // do a random hyperparameter search with GLM // TODO: convert to using the REST API Key<Grid> gridKey = Key.make("GLM_grid_default_" + this._key.toString()); HyperSpaceSearchCriteria.RandomDiscreteValueSearchCriteria searchCriteria = buildSpec.build_control.stopping_criteria; // TODO: put this into a Provider, which can return multiple searches GLMModel.GLMParameters glmParameters = new GLMModel.GLMParameters(); glmParameters._train = trainingFrame._key; if (null != validationFrame) glmParameters._valid = validationFrame._key; glmParameters._response_column = buildSpec.input_spec.response_column; glmParameters._ignored_columns = buildSpec.input_spec.ignored_columns; glmParameters._lambda_search = true; // required for stacking: glmParameters._nfolds = 5; glmParameters._fold_assignment = Model.Parameters.FoldAssignmentScheme.Modulo; glmParameters._keep_cross_validation_predictions = true; // TODO: wire through from buildSpec glmParameters._stopping_metric = ScoreKeeper.StoppingMetric.AUTO; glmParameters._stopping_tolerance = 0.0001; glmParameters._stopping_rounds = 3; glmParameters._max_runtime_secs = this.timeRemainingMs() / 1000; glmParameters._family = getResponseColumn().isBinary() ? GLMModel.GLMParameters.Family.binomial : getResponseColumn().isCategorical() ? GLMModel.GLMParameters.Family.multinomial : GLMModel.GLMParameters.Family.gaussian; // TODO: other continuous distributions! Map<String, Object[]> searchParams = new HashMap<>(); glmParameters._alpha = new double[] {0.0, 0.2, 0.4, 0.6, 0.8, 1.0}; // Note: standard GLM parameter is an array; don't use searchParams! searchParams.put("_missing_values_handling", new DeepLearningModel.DeepLearningParameters.MissingValuesHandling[] {DeepLearningModel.DeepLearningParameters.MissingValuesHandling.MeanImputation, DeepLearningModel.DeepLearningParameters.MissingValuesHandling.Skip}); Log.info("About to run GLM for: " + glmParameters._max_runtime_secs + "S"); Job<Grid>glmJob = hyperparameterSearch("GLM", glmParameters, searchParams); return glmJob; } public Job<Grid> defaultSearchGBM() { // do a random hyperparameter search with GBM // TODO: convert to using the REST API Key<Grid> gridKey = Key.make("GBM_grid_default_" + this._key.toString()); HyperSpaceSearchCriteria.RandomDiscreteValueSearchCriteria searchCriteria = buildSpec.build_control.stopping_criteria; // TODO: put this into a Provider, which can return multiple searches GBMModel.GBMParameters gbmParameters = new GBMModel.GBMParameters(); gbmParameters._train = trainingFrame._key; if (null != validationFrame) gbmParameters._valid = validationFrame._key; gbmParameters._response_column = buildSpec.input_spec.response_column; gbmParameters._ignored_columns = buildSpec.input_spec.ignored_columns; // required for stacking: gbmParameters._nfolds = 5; gbmParameters._fold_assignment = Model.Parameters.FoldAssignmentScheme.Modulo; gbmParameters._keep_cross_validation_predictions = true; gbmParameters._score_tree_interval = 5; // TODO: wire through from buildSpec gbmParameters._stopping_metric = ScoreKeeper.StoppingMetric.AUTO; gbmParameters._stopping_tolerance = 0.0001; gbmParameters._stopping_rounds = 3; gbmParameters._max_runtime_secs = this.timeRemainingMs() / 1000; gbmParameters._histogram_type = SharedTreeModel.SharedTreeParameters.HistogramType.AUTO; Map<String, Object[]> searchParams = new HashMap<>(); searchParams.put("_ntrees", new Integer[]{10000}); searchParams.put("_max_depth", new Integer[]{3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}); searchParams.put("_min_rows", new Integer[]{1, 5, 10, 15, 30, 100}); searchParams.put("_learn_rate", new Double[]{0.001, 0.005, 0.008, 0.01, 0.05, 0.08, 0.1, 0.5, 0.8}); searchParams.put("_sample_rate", new Double[]{0.50, 0.60, 0.70, 0.80, 0.90, 1.00}); searchParams.put("_col_sample_rate", new Double[]{ 0.4, 0.7, 1.0}); searchParams.put("_col_sample_rate_per_tree", new Double[]{ 0.4, 0.7, 1.0}); searchParams.put("_min_split_improvement", new Double[]{1e-4, 1e-5}); /* if (trainingFrame.numCols() > 1000 && responseVec.isCategorical() && responseVec.cardinality() > 2) searchParams.put("col_sample_rate_per_tree", new Double[]{0.4, 0.6, 0.8, 1.0}); */ Log.info("About to run GBM for: " + gbmParameters._max_runtime_secs + "S"); Job<Grid>gbmJob = hyperparameterSearch("GBM", gbmParameters, searchParams); return gbmJob; } Job<StackedEnsembleModel>stack(Key<Model>[]... modelKeyArrays) { List<Key<Model>> allModelKeys = new ArrayList<>(); for (Key<Model>[] modelKeyArray : modelKeyArrays) allModelKeys.addAll(Arrays.asList(modelKeyArray)); StackedEnsembleModel.StackedEnsembleParameters stackedEnsembleParameters = new StackedEnsembleModel.StackedEnsembleParameters(); stackedEnsembleParameters._base_models = allModelKeys.toArray(new Key[0]); stackedEnsembleParameters._selection_strategy = StackedEnsembleModel.StackedEnsembleParameters.SelectionStrategy.choose_all; stackedEnsembleParameters._train = trainingFrame._key; if (null != validationFrame) stackedEnsembleParameters._valid = validationFrame._key; stackedEnsembleParameters._response_column = buildSpec.input_spec.response_column; Job ensembleJob = trainModel(null, "stackedensemble", stackedEnsembleParameters); return ensembleJob; } // manager thread: // 1. Do extremely cursory pass over data and gather only the most basic information. // During this pass, AutoML will learn how timely it will be to do more info // gathering on _fr. There's already a number of interesting stats available // thru the rollups, so no need to do too much too soon. // 2. Build a very dumb RF (with stopping_rounds=1, stopping_tolerance=0.01) // 3. TODO: refinement passes and strategy selection public void learn() { // gather initial frame metadata and guess the problem type // TODO: Nishant says sometimes frameMetadata is null, so maybe we need to wait for it? // null FrameMetadata arises when delete() is called without waiting for start() to finish. frameMetadata = new FrameMetadata(trainingFrame, trainingFrame.find(buildSpec.input_spec.response_column), trainingFrame.toString()).computeFrameMetaPass1(); HashMap<String, Object> frameMeta = FrameMetadata.makeEmptyFrameMeta(); frameMetadata.fillSimpleMeta(frameMeta); job.update(20, "Computed dataset metadata"); isClassification = frameMetadata.isClassification(); // build a fast RF with default settings... Job<DRFModel>defaultRandomForestJob = defaultRandomForest(); pollAndUpdateProgress("Default Random Forest build", 50, this.job(), defaultRandomForestJob); DRFModel defaultDRF = (DRFModel)defaultRandomForestJob.get(); leaderboard.addModel(defaultDRF); // ... and another with "XRT" / extratrees settings Job<DRFModel>defaultExtremelyRandomTreesJob = defaultExtremelyRandomTrees(); pollAndUpdateProgress("Default Extremely Random Trees (XRT) build", 50, this.job(), defaultExtremelyRandomTreesJob); DRFModel defaultXRT = (DRFModel)defaultExtremelyRandomTreesJob.get(); leaderboard.addModel(defaultXRT); // build GLMs with the default search parameters // TODO: run for only part of the remaining time? Job<Grid>glmJob = defaultSearchGLM(); pollAndUpdateProgress("GLM hyperparameter search", 100, this.job(), glmJob); Grid glmGrid = DKV.getGet(glmJob._result); leaderboard.addModels(glmGrid.getModelKeys()); // build GBMs with the default search parameters // TODO: run for only part of the remaining time? Job<Grid>gbmJob = defaultSearchGBM(); pollAndUpdateProgress("GBM hyperparameter search", 700, this.job(), gbmJob); Grid gbmGrid = DKV.getGet(gbmJob._result); leaderboard.addModels(gbmGrid.getModelKeys()); // (optionally) build StackedEnsemble Model m = gbmGrid.getModels()[0]; if (m._output.isClassifier() && ! m._output.isBinomialClassifier()) { // nada this.job.update(100, "Multinomial classifier: StackedEnsemble build skipped"); Log.info("Multinomial classifier: StackedEnsemble build skipped"); } else { // stack all models // Also stack models from other AutoML runs, by using the Leaderboard! (but don't stack stacks) Model[] all = leaderboard().models(); int nonEnsembleCount = 0; for (Model aModel : all) if (! (aModel instanceof StackedEnsembleModel)) nonEnsembleCount++; Key<Model>[] notEnsembles = new Key[nonEnsembleCount]; int notEnsembleIndex = 0; for (Model aModel : all) if (! (aModel instanceof StackedEnsembleModel)) notEnsembles[notEnsembleIndex++] = aModel._key; Job<StackedEnsembleModel>ensembleJob = stack(notEnsembles); pollAndUpdateProgress("StackedEnsemble build", 100, this.job(), ensembleJob); StackedEnsembleModel ensemble = (StackedEnsembleModel)ensembleJob.get(); leaderboard.addModel(ensemble); } Log.info("AutoML: build done"); Log.info(leaderboard.toString("\n")); possiblyVerifyImmutability(); // gather more data? build more models? start applying transforms? what next ...? stop(); } /** * Instantiate an AutoML object and start it running. Progress can be tracked via its job(). * * @param buildSpec * @return */ public static AutoML startAutoML(AutoMLBuildSpec buildSpec) { // TODO: name this job better AutoML aml = AutoML.makeAutoML(Key.<AutoML>make(), buildSpec); DKV.put(aml); startAutoML(aml); return aml; } /** * Takes in an AutoML instance and starts running it. Progress can be tracked via its job(). * @param aml * @return */ public static void startAutoML(AutoML aml) { // Currently AutoML can only run one job at a time if (aml.job == null || !aml.job.isRunning()) { Job job = new /* Timed */ H2OJob(aml, aml._key, aml.timeRemainingMs()).start(); aml.job = job; // job._max_runtime_msecs = Math.round(1000 * aml.buildSpec.build_control.stopping_criteria.max_runtime_secs()); // job work: // import/parse (30), Frame metadata (20), GBM grid (900), StackedEnsemble (50) job._work = 1000; DKV.put(aml); job.update(30, "Data import and parse complete"); } } /** * Holds until AutoML's job is completed, if a job exists. */ public void get() { if (job != null) job.get(); } /** * Delete the AutoML-related objects, but leave the grids and models that it built. */ public void delete() { //if (frameMetadata != null) frameMetadata.delete(); //TODO: We shouldn't have to worry about FrameMetadata being null AutoMLUtils.cleanup_adapt(trainingFrame, origTrainingFrame); leaderboard.delete(); remove(); } /** * Same as delete() but also deletes all Objects made from this instance. */ public void deleteWithChildren() { leaderboard.deleteWithChildren(); delete(); // is it safe to do leaderboard.delete() now? if (gridKey != null) gridKey.remove(); // If the Frame was made here (e.g. buildspec contained a path, then it will be deleted if (buildSpec.input_spec.training_frame == null) { origTrainingFrame.delete(); } if (buildSpec.input_spec.validation_frame == null && buildSpec.input_spec.validation_path != null) { validationFrame.delete(); } } private ModelBuilder selectInitial(FrameMetadata fm) { // may use _isClassification so not static method // TODO: handle validation frame if present Frame[] trainTest = AutoMLUtils.makeTrainTestFromWeight(fm._fr, fm.weights()); ModelBuilder mb = InitModel.initRF(trainTest[0], trainTest[1], fm.response()._name); mb._parms._ignored_columns = fm.ignoredCols(); return mb; } // all model builds by AutoML call into this // TODO: who is the caller?! // TODO: remove this restriction! // expected to only ever have a single AutoML instance going at a time Model build(ModelBuilder mb) { Job j; if (null == jobs) throw new AutoMLDoneException(); jobs.add(j = mb.trainModel()); Model m = (Model) j.get(); // save the weights, drop the frames! // TODO: don't munge the original Frame! trainingFrame.remove("weight"); trainingFrame.delete(); if (null != validationFrame) { validationFrame.remove("weight"); validationFrame.delete(); } if (null == jobs) throw new AutoMLDoneException(); jobs.remove(j); leaderboard.addModel(m); return m; } public Job job() { if (null == this.job) return null; return DKV.getGet(this.job._key); } public Leaderboard leaderboard() { return leaderboard._key.get(); } // satisfy typing for job return type... public static class AutoMLKeyV3 extends KeyV3<Iced, AutoMLKeyV3, AutoML> { public AutoMLKeyV3() { } public AutoMLKeyV3(Key<AutoML> key) { super(key); } } @Override public Class<AutoMLKeyV3> makeSchema() { return AutoMLKeyV3.class; } private class AutoMLDoneException extends H2OAbstractRuntimeException { public AutoMLDoneException() { this("done", "done"); } public AutoMLDoneException(String msg, String dev_msg) { super(msg, dev_msg, new IcedHashMapGeneric.IcedHashMapStringObject()); } } public boolean possiblyVerifyImmutability() { boolean warning = false; if (verifyImmutability) { // check that we haven't messed up the original Frame Log.info("Verifying training frame immutability. . ."); Vec[] vecsRightNow = origTrainingFrame.vecs(); String[] namesRightNow = origTrainingFrame.names(); if (originalTrainingFrameVecs.length != vecsRightNow.length) { Log.warn("Training frame vec count has changed from: " + originalTrainingFrameVecs.length + " to: " + vecsRightNow.length); warning = true; } if (originalTrainingFrameNames.length != namesRightNow.length) { Log.warn("Training frame vec count has changed from: " + originalTrainingFrameNames.length + " to: " + namesRightNow.length); warning = true; } for (int i = 0; i < originalTrainingFrameVecs.length; i++) { if (!originalTrainingFrameVecs[i].equals(vecsRightNow[i])) { Log.warn("Training frame vec number " + i + " has changed keys. Was: " + originalTrainingFrameVecs[i] + " , now: " + vecsRightNow[i]); warning = true; } if (!originalTrainingFrameNames[i].equals(namesRightNow[i])) { Log.warn("Training frame vec number " + i + " has changed names. Was: " + originalTrainingFrameNames[i] + " , now: " + namesRightNow[i]); warning = true; } if (originalTrainingFrameChecksums[i] != vecsRightNow[i].checksum()) { Log.warn("Training frame vec number " + i + " has changed checksum. Was: " + originalTrainingFrameChecksums[i] + " , now: " + vecsRightNow[i].checksum()); warning = true; } } Log.info(". . . training frame was mutated: " + warning); } else { Log.info("Not verifying training frame immutability. . . This is turned off for efficiency."); } return warning; } }
// samskivert library - useful routines for java programs // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.jdbc; import java.sql.*; import com.samskivert.Log; import com.samskivert.io.PersistenceException; import com.samskivert.util.StringUtil; /** * The simple repository should be used for a repository that only needs access to a single JDBC * connection instance to perform its persistence services. */ public class SimpleRepository extends Repository { /** See {@link #setExecutePreCondition}. */ public static interface PreCondition { /** See {@link #setExecutePreCondition}. */ public boolean validate (String dbident, Operation op); } /** * Configures an operation that will be invoked prior to the execution of every database * operation to validate whether some pre-condition is met. This mainly exists for systems that * wish to ensure that all database operations take place on a particular thread (or not on a * particular thread) as database operations are generally slow and blocking. */ public static void setExecutePreCondition (PreCondition condition) { _precond = condition; } /** * Creates and initializes a simple repository which will access the database identified by the * supplied database identifier. * * @param provider the connection provider which will be used to obtain our database * connection. * @param dbident the identifier of the database that will be accessed by this repository or * null if the derived class will call {@link #configureDatabaseIdent} by hand later. */ public SimpleRepository (ConnectionProvider provider, String dbident) { super(provider); if (dbident != null) { configureDatabaseIdent(dbident); } } /** * This is called automatically if a dbident is provided at construct time, but a derived class * can pass null to its constructor and then call this method itself later if it wishes to * obtain its database identifier from an overridable method which could not otherwise be * called at construct time. */ protected void configureDatabaseIdent (String dbident) { _dbident = dbident; // give the repository a chance to do any schema migration before things get further // underway try { executeUpdate(new Operation<Object>() { public Object invoke (Connection conn, DatabaseLiaison liaison) throws SQLException, PersistenceException { migrateSchema(conn, liaison); return null; } }); } catch (PersistenceException pe) { Log.warning("Failure migrating schema [dbident=" + _dbident + "]."); Log.logStackTrace(pe); } } /** * Executes the supplied read-only operation. In the event of a transient failure, the * repository will attempt to reestablish the database connection and try the operation again. * * @return whatever value is returned by the invoked operation. */ protected <V> V execute (Operation<V> op) throws PersistenceException { return execute(op, true, true); } /** * Executes the supplied read-write operation. In the event of a transient failure, the * repository will attempt to reestablish the database connection and try the operation again. * * @return whatever value is returned by the invoked operation. */ protected <V> V executeUpdate (Operation<V> op) throws PersistenceException { return execute(op, true, false); } /** * Executes the supplied operation followed by a call to <code>commit()</code> on the * connection unless a <code>PersistenceException</code> or runtime error occurs, in which case * a call to <code>rollback()</code> is executed on the connection. * * @param retryOnTransientFailure if true and the operation fails due to a transient failure * (like losing the connection to the database or deadlock detection), the connection to the * database will be reestablished (if necessary) and the operation attempted once more. * @param readOnly whether or not to request a read-only connection. * * @return whatever value is returned by the invoked operation. */ protected <V> V execute (Operation<V> op, boolean retryOnTransientFailure, boolean readOnly) throws PersistenceException { Connection conn = null; DatabaseLiaison liaison = null; V rv = null; boolean supportsTransactions = false; boolean attemptedOperation = false; Boolean oldAutoCommit = null; // check our pre-condition if (_precond != null && !_precond.validate(_dbident, op)) { Log.warning("Repository operation failed pre-condition check! [dbident=" + _dbident + ", op=" + op + "]."); Thread.dumpStack(); } // obtain our database connection and associated goodies conn = _provider.getConnection(_dbident, readOnly); // make sure that no one else performs a database operation using the same connection until // we're done synchronized (conn) { try { liaison = LiaisonRegistry.getLiaison(conn); // find out if we support transactions DatabaseMetaData dmd = conn.getMetaData(); if (dmd != null) { supportsTransactions = dmd.supportsTransactions(); } // turn off auto-commit if (supportsTransactions) { oldAutoCommit = conn.getAutoCommit(); conn.setAutoCommit(false); } // let derived classes do any got-connection processing gotConnection(conn); // invoke the operation attemptedOperation = true; rv = op.invoke(conn, liaison); // commit the transaction if (supportsTransactions) { conn.commit(); } // return the operation result return rv; } catch (SQLException sqe) { if (attemptedOperation) { // back out our changes if something got hosed (but not if the hosage was a // result of losing our connection) try { if (supportsTransactions && !conn.isClosed()) { conn.rollback(); } } catch (SQLException rbe) { Log.warning("Unable to roll back operation [err=" + sqe + ", rberr=" + rbe + "]."); } } if (conn != null) { // let the provider know that the connection failed _provider.connectionFailed(_dbident, readOnly, conn, sqe); // clear out the reference so that we don't release it later conn = null; } if (!retryOnTransientFailure || liaison == null || !liaison.isTransientException(sqe)) { String err = "Operation invocation failed"; throw new PersistenceException(err, sqe); } // the MySQL JDBC driver has the annoying habit of including the embedded exception // stack trace in the message of their outer exception; if I want a fucking stack // trace, I'll call printStackTrace() thanksverymuch String msg = StringUtil.split("" + sqe, "\n")[0]; Log.info("Transient failure executing operation, retrying [error=" + msg + "]."); } catch (PersistenceException pe) { // back out our changes if something got hosed try { if (supportsTransactions && !conn.isClosed()) { conn.rollback(); } } catch (SQLException rbe) { Log.warning("Unable to roll back operation [origerr=" + pe + ", rberr=" + rbe + "]."); } throw pe; } catch (RuntimeException rte) { // back out our changes if something got hosed try { if (supportsTransactions && conn != null && !conn.isClosed()) { conn.rollback(); } } catch (SQLException rbe) { Log.warning("Unable to roll back operation [origerr=" + rte + ", rberr=" + rbe + "]."); } throw rte; } finally { if (conn != null) { // restore our auto-commit settings if (oldAutoCommit != null && !conn.isClosed()) { try { conn.setAutoCommit(oldAutoCommit); } catch (SQLException sace) { Log.warning("Unable to restore auto-commit [err=" + sace + "]."); } } // release the database connection _provider.releaseConnection(_dbident, readOnly, conn); } } } // we'll only fall through here if the above code failed due to a transient exception (the // connection was closed for being idle, for example) and we've been asked to retry; so // let's do so return execute(op, false, readOnly); } /** * Executes the supplied update query in this repository, returning the number of rows * modified. */ protected int update (final String query) throws PersistenceException { return executeUpdate(new Operation<Integer>() { public Integer invoke (Connection conn, DatabaseLiaison liaison) throws SQLException, PersistenceException { Statement stmt = null; try { stmt = conn.createStatement(); return stmt.executeUpdate(query); } finally { JDBCUtil.close(stmt); } } }); } /** * Executes the supplied update query in this repository, throwing an exception if the * modification count is not equal to the specified count. */ protected void checkedUpdate (final String query, final int count) throws PersistenceException { executeUpdate(new Operation<Object>() { public Object invoke (Connection conn, DatabaseLiaison liaison) throws SQLException, PersistenceException { Statement stmt = null; try { stmt = conn.createStatement(); JDBCUtil.checkedUpdate(stmt, query, 1); } finally { JDBCUtil.close(stmt); } return null; } }); } /** * Executes the supplied update query in this repository, logging a warning if the modification * count is not equal to the specified count. */ protected void warnedUpdate (final String query, final int count) throws PersistenceException { executeUpdate(new Operation<Object>() { public Object invoke (Connection conn, DatabaseLiaison liaison) throws SQLException, PersistenceException { Statement stmt = null; try { stmt = conn.createStatement(); JDBCUtil.warnedUpdate(stmt, query, 1); } finally { JDBCUtil.close(stmt); } return null; } }); } /** * Instructs MySQL to perform table maintenance on the specified table. * * @param action <code>analyze</code> recomputes the distribution of the keys for the specified * table. This can help certain joins to be performed more efficiently. <code>optimize</code> * instructs MySQL to coalesce fragmented records and reclaim space left by deleted records. * This can improve a tables efficiency but can take a long time to run on large tables. */ protected void maintenance (final String action, final String table) throws PersistenceException { executeUpdate(new Operation<Object>() { public Object invoke (Connection conn, DatabaseLiaison liaison) throws SQLException, PersistenceException { Statement stmt = null; try { stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(action + " table " + table); while (rs.next()) { String result = rs.getString("Msg_text"); if (result == null || (result.indexOf("up to date") == -1 && !result.equals("OK"))) { Log.info("Table maintenance [" + SimpleRepository.toString(rs) + "]."); } } } finally { JDBCUtil.close(stmt); } return null; } }); } /** * Derived classes can override this method and perform any schema migration they might need * (using the idempotent {@link JDBCUtil} schema migration methods). This is called during the * repository's constructor and will thus take place before derived classes (like the {@link * JORARepository} introspect on the schema to match it up to associated Java classes). */ protected void migrateSchema (Connection conn, DatabaseLiaison liaison) throws SQLException, PersistenceException { } /** * Called when we fetch a connection from the provider. This gives derived classes an * opportunity to configure whatever internals they might be using with the connection that was * fetched. */ protected void gotConnection (Connection conn) { } /** * Converts a row of a result set to a string, prepending each column with the column name from * the result set metadata. */ protected static String toString (ResultSet rs) throws SQLException { ResultSetMetaData md = rs.getMetaData(); int ccount = md.getColumnCount(); StringBuilder buf = new StringBuilder(); for (int ii = 1; ii <= ccount; ii++) { if (buf.length() > 0) { buf.append(", "); } buf.append(md.getColumnName(ii)).append("="); buf.append(rs.getObject(ii)); } return buf.toString(); } protected String _dbident; protected static PreCondition _precond; }
package org.apache.ibatis.session.defaults; import org.apache.ibatis.exceptions.ExceptionFactory; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.executor.ErrorContext; import org.apache.ibatis.logging.Log; import org.apache.ibatis.logging.LogFactory; import org.apache.ibatis.logging.jdbc.ConnectionLogger; import org.apache.ibatis.mapping.Environment; import org.apache.ibatis.session.*; import org.apache.ibatis.transaction.Transaction; import org.apache.ibatis.transaction.TransactionFactory; import org.apache.ibatis.transaction.managed.ManagedTransactionFactory; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; public class DefaultSqlSessionFactory implements SqlSessionFactory { private static final Log log = LogFactory.getLog(Connection.class); private final Configuration configuration; private final TransactionFactory managedTransactionFactory; public DefaultSqlSessionFactory(Configuration configuration) { this.configuration = configuration; this.managedTransactionFactory = new ManagedTransactionFactory(); } public SqlSession openSession() { return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false); } public SqlSession openSession(boolean autoCommit) { return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, autoCommit); } public SqlSession openSession(ExecutorType execType) { return openSessionFromDataSource(execType, null, false); } public SqlSession openSession(TransactionIsolationLevel level) { return openSessionFromDataSource(configuration.getDefaultExecutorType(), level, false); } public SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level) { return openSessionFromDataSource(execType, level, false); } public SqlSession openSession(ExecutorType execType, boolean autoCommit) { return openSessionFromDataSource(execType, null, autoCommit); } public SqlSession openSession(Connection connection) { return openSessionFromConnection(configuration.getDefaultExecutorType(), connection); } public SqlSession openSession(ExecutorType execType, Connection connection) { return openSessionFromConnection(execType, connection); } public Configuration getConfiguration() { return configuration; } private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) { Connection connection = null; try { final Environment environment = configuration.getEnvironment(); final DataSource dataSource = getDataSourceFromEnvironment(environment); TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment); connection = dataSource.getConnection(); if (level != null) { connection.setTransactionIsolation(level.getLevel()); } connection = wrapConnection(connection); Transaction tx = transactionFactory.newTransaction(connection, autoCommit); Executor executor = configuration.newExecutor(tx, execType); return new DefaultSqlSession(configuration, executor, autoCommit); } catch (Exception e) { closeConnection(connection); throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e); } finally { ErrorContext.instance().reset(); } } private SqlSession openSessionFromConnection(ExecutorType execType, Connection connection) { try { boolean autoCommit; try { autoCommit = connection.getAutoCommit(); } catch (SQLException e) { // Failover to true, as most poor drivers // or databases won't support transactions autoCommit = true; } connection = wrapConnection(connection); final Environment environment = configuration.getEnvironment(); final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment); Transaction tx = transactionFactory.newTransaction(connection, autoCommit); Executor executor = configuration.newExecutor(tx, execType); return new DefaultSqlSession(configuration, executor, autoCommit); } catch (Exception e) { throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e); } finally { ErrorContext.instance().reset(); } } private DataSource getDataSourceFromEnvironment(Environment environment) { if (environment == null || environment.getDataSource() == null) { throw new SqlSessionException("Configuration does not include an environment with a DataSource, so session cannot be created unless a connection is passed in."); } return environment.getDataSource(); } private TransactionFactory getTransactionFactoryFromEnvironment(Environment environment) { if (environment == null || environment.getTransactionFactory() == null) { return managedTransactionFactory; } return environment.getTransactionFactory(); } private Connection wrapConnection(Connection connection) { if (log.isDebugEnabled()) { return ConnectionLogger.newInstance(connection); } else { return connection; } } private void closeConnection(Connection connection) { if (connection != null) { try { connection.close(); } catch (SQLException e1) { // Intentionally ignore. Prefer previous error. } } } }
// $Id: Invoker.java,v 1.10 2003/08/18 21:38:07 mdb Exp $ package com.threerings.presents.util; import java.util.HashMap; import java.util.Iterator; import com.samskivert.util.Histogram; import com.samskivert.util.LoopingThread; import com.samskivert.util.Queue; import com.samskivert.util.StringUtil; import com.threerings.presents.Log; import com.threerings.presents.server.PresentsDObjectMgr; import com.threerings.presents.server.PresentsServer.Reporter; import com.threerings.presents.server.PresentsServer; /** * The invoker is used to invoke self-contained units of code on an * invoking thread. Each invoker is associated with its own thread and * that thread is used to invoke all of the units posted to that invoker * in the order in which they were posted. The invoker also provides a * convenient mechanism for processing the result of an invocation back on * the dobjmgr thread. * * <p> The invoker is a useful tool for services that need to block and * therefore cannot be run on the distributed object thread. For example, * a user of the Presents system might provide an invoker on which to run * database queries. * * <p> Bear in mind that each invoker instance runs units on its own * thread and care must be taken to ensure that code running on separate * invokers properly synchronizes access to shared information. Where * possible, complete isolation of the services provided by a particular * invoker is desirable. */ public class Invoker extends LoopingThread implements Reporter { /** * The unit encapsulates a unit of executable code that will be run on * the invoker thread. It also provides facilities for additional code * to be run on the dobjmgr thread once the primary code has completed * on the invoker thread. */ public static abstract class Unit implements Runnable { /** * This method is called on the invoker thread and should be used * to perform the primary function of the unit. It can return true * to cause the <code>handleResult</code> method to be * subsequently invoked on the dobjmgr thread (generally to allow * the results of the invocation to be acted upon back in the * context of the distributed object world) or false to indicate * that no further processing should be performed. * * <p> Note that an invocation unit can do things like post events * from the invoker thread (which includes modification of * distributed object fields) and need not jump over to the * dobjmgr thread to do so. However, it cannot <em>read</em> * distributed object fields from the invoker thread. Any field * values needed during the course of the invocation should be * provided from the dobjmgr thread at the time that the * invocation unit is created and posted. * * @return true if the <code>handleResult</code> method should be * invoked on the dobjmgr thread, false if not. */ public abstract boolean invoke (); /** * Invocation unit implementations can implement this function to * perform any post-unit-invocation processing back on the dobjmgr * thread. It will be invoked if <code>invoke</code> returns true. */ public void handleResult () { // do nothing by default } // we want to be a runnable to make the dobjmgr happy, but we'd // like for invocation unit implementations to be able to put // their result handling code into an aptly named method public void run () { handleResult(); } } /** * Creates an invoker that will post results to the supplied * distributed object manager. */ public Invoker (PresentsDObjectMgr omgr) { super("presents.Invoker"); _omgr = omgr; if (PERF_TRACK) { PresentsServer.registerReporter(this); } } /** * Posts a unit to this invoker for subsequent invocation on the * invoker's thread. */ public void postUnit (Unit unit) { // simply append it to the queue _queue.append(unit); } // documentation inherited public void iterate () { // pop the next item off of the queue Unit unit = (Unit) _queue.get(); long start; if (PERF_TRACK) { start = System.currentTimeMillis(); _unitsRun++; } try { if (unit.invoke()) { // if it returned true, we post it to the dobjmgr // thread to invoke the result processing _omgr.postUnit(unit); } // track some performance metrics if (PERF_TRACK) { long duration = System.currentTimeMillis() - start; Object key = unit.getClass(); Histogram histo = (Histogram)_tracker.get(key); if (histo == null) { // track in buckets of 50ms up to 500ms _tracker.put(key, histo = new Histogram(0, 50, 10)); } histo.addValue((int)duration); } } catch (Exception e) { Log.warning("Invocation unit failed [unit=" + unit + "]."); Log.logStackTrace(e); } } /** * Will do a sophisticated shutdown of both itself and the DObjectManager * thread. */ public void shutdown () { _queue.append(new ShutdownUnit()); } // documentation inherited from interface public void appendReport (StringBuffer buffer, long now, long sinceLast) { buffer.append("* presents.util.Invoker:\n"); buffer.append("- Units executed: ").append(_unitsRun).append("\n"); _unitsRun = 0; for (Iterator iter = _tracker.keySet().iterator(); iter.hasNext(); ) { Class key = (Class)iter.next(); Histogram histo = (Histogram)_tracker.get(key); buffer.append(" "); buffer.append(StringUtil.shortClassName(key)).append(": "); buffer.append(histo.summarize()).append("\n"); histo.clear(); } } /** * This unit gets posted back and forth between the invoker and DObjectMgr * until both of their queues are empty and they can both be safely * shutdown. */ protected class ShutdownUnit extends Unit { // run on the invoker thread public boolean invoke () { if (checkLoops()) { return false; // if the invoker queue is not empty, we put ourselves back on it } else if (_queue.hasElements()) { _loopCount++; postUnit(this); return false; } else { // the invoker is empty, let's go over to the omgr _loopCount = 0; _passCount++; return true; } } // run on the dobj thread public void handleResult () { if (checkLoops()) { return; // if the queue isn't empty, re-post } else if (!_omgr.queueIsEmpty()) { _loopCount++; _omgr.postUnit(this); // if the invoker still has stuff and we're still under the pass // limit, go ahead and pass it back to the invoker } else if (_queue.hasElements() && (_passCount < MAX_PASSES)) { // pass the buck back to the invoker _loopCount = 0; postUnit(this); } else { // otherwise end it, and complain if we're ending it // because of passes if (_passCount >= MAX_PASSES) { Log.warning("Shutdown Unit passed 50 times without " + "finishing, shutting down harshly."); } doShutdown(); } } /** * Check to make sure we haven't looped too many times. */ protected boolean checkLoops () { if (_loopCount > MAX_LOOPS) { Log.warning("Shutdown Unit looped on one thread 100 times " + "without finishing, shutting down harshly."); doShutdown(); return true; } return false; } /** * Do the actual shutdown. */ protected void doShutdown () { _omgr.harshShutdown(); // end the dobj thread // end the invoker thread postUnit(new Unit() { public boolean invoke () { _running = false; return false; } }); } /** The number of times we've been passed to the object manager. */ protected int _passCount = 0; /** How many times we've looped on the thread we're currently on. */ protected int _loopCount = 0; /** The maximum number of passes we allow before just ending things. */ protected static final int MAX_PASSES = 50; /** The maximum number of loops we allow before just ending things. */ protected static final int MAX_LOOPS = 100; } /** The invoker's queue of units to be executed. */ protected Queue _queue = new Queue(); /** The object manager with which we're working. */ protected PresentsDObjectMgr _omgr; /** Tracks the counts of invocations by unit's class. */ protected HashMap _tracker = new HashMap(); /** The total number of invoker units run since the last report. */ protected int _unitsRun; /** Whether or not to track invoker unit performance. */ protected static final boolean PERF_TRACK = true; }
package org.cytoscape.commandDialog.internal.tasks; import org.cytoscape.work.AbstractTask; import org.cytoscape.work.ProvidesTitle; import org.cytoscape.work.TaskMonitor; import org.cytoscape.work.Tunable; public class SleepCommandTask extends AbstractEmptyObservableTask { @ProvidesTitle public String getTitle() { return "Sleeping..."; } @Tunable(description="Duration of sleep in seconds", longDescription="Enter the time in seconds to sleep", exampleStringValue="5") public double duration; public SleepCommandTask() { super(); } @Override public void run(TaskMonitor arg0) throws Exception { if (duration != 0d) { arg0.showMessage(TaskMonitor.Level.INFO, "Sleeping for "+duration+" seconds"); Thread.sleep((long)duration*1000); arg0.showMessage(TaskMonitor.Level.INFO, "Slept for "+duration+" seconds"); } } }
package org.jfrog.hudson.maven3; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.maven.MavenModuleSet; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Action; import hudson.model.BuildListener; import hudson.model.Computer; import hudson.model.Hudson; import hudson.model.Result; import hudson.remoting.Which; import hudson.slaves.SlaveComputer; import hudson.tasks.BuildWrapper; import hudson.tasks.BuildWrapperDescriptor; import net.sf.json.JSONObject; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.jfrog.build.client.ClientProperties; import org.jfrog.build.extractor.maven.BuildInfoRecorder; import org.jfrog.hudson.ArtifactoryBuilder; import org.jfrog.hudson.ArtifactoryServer; import org.jfrog.hudson.ResolverOverrider; import org.jfrog.hudson.ServerDetails; import org.jfrog.hudson.action.ActionableHelper; import org.jfrog.hudson.util.CredentialResolver; import org.jfrog.hudson.util.Credentials; import org.jfrog.hudson.util.PluginDependencyHelper; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Collection; import java.util.List; import java.util.Map; /** * @author Tomer Cohen */ public class ArtifactoryMaven3NativeConfigurator extends BuildWrapper implements ResolverOverrider { private final ServerDetails details; private final Credentials overridingResolverCredentials; @DataBoundConstructor public ArtifactoryMaven3NativeConfigurator(ServerDetails details, Credentials overridingResolverCredentials) { this.details = details; this.overridingResolverCredentials = overridingResolverCredentials; } public ServerDetails getDetails() { return details; } public String getDownloadRepositoryKey() { return details != null ? details.downloadRepositoryKey : null; } public String getArtifactoryName() { return details != null ? details.artifactoryName : null; } public String getRepositoryKey() { return details != null ? details.repositoryKey : null; } @Override public Collection<? extends Action> getProjectActions(AbstractProject project) { return ActionableHelper.getArtifactoryProjectAction(details.artifactoryName, project); } public boolean isOverridingDefaultResolver() { return getOverridingResolverCredentials() != null; } public Credentials getOverridingResolverCredentials() { return overridingResolverCredentials; } @Override public Environment setUp(final AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { final MavenModuleSet project = (MavenModuleSet) build.getProject(); final File classWorldsFile = File.createTempFile("classworlds", "conf"); build.setResult(Result.SUCCESS); return new Environment() { @Override public void buildEnvVars(Map<String, String> env) { super.buildEnvVars(env); try { project.setMavenOpts(appendNewMavenOpts(project)); } catch (IOException e) { throw new RuntimeException("Unable to manipulate maven_opts for project: " + project, e); } URL resource = getClass().getClassLoader().getResource("org/jfrog/hudson/maven3/classworlds-native.conf"); String classworldsConfPath; if (Computer.currentComputer() instanceof SlaveComputer) { try { FilePath remoteClassworlds = build.getWorkspace().createTextTempFile("classworlds", "conf", "", false); remoteClassworlds.copyFrom(resource); classworldsConfPath = remoteClassworlds.getRemote(); } catch (Exception e) { throw new RuntimeException(e); } } else { classworldsConfPath = classWorldsFile.getAbsolutePath(); File classWorldsConf = new File(resource.getFile()); try { FileUtils.copyFile(classWorldsConf, classWorldsFile); } catch (IOException e) { build.setResult(Result.FAILURE); throw new RuntimeException( "Unable to copy classworlds file: " + classWorldsConf.getAbsolutePath() + " to: " + classWorldsFile.getAbsolutePath(), e); } } env.put("classworlds.conf", classworldsConfPath); final ArtifactoryServer artifactoryServer = getArtifactoryServer(); Credentials preferredResolver = CredentialResolver .getPreferredResolver(ArtifactoryMaven3NativeConfigurator.this, artifactoryServer); env.put(ClientProperties.PROP_CONTEXT_URL, artifactoryServer.getUrl()); env.put(ClientProperties.PROP_RESOLVE_REPOKEY, getDownloadRepositoryKey()); env.put(ClientProperties.PROP_RESOLVE_USERNAME, preferredResolver.getUsername()); env.put(ClientProperties.PROP_RESOLVE_PASSWORD, preferredResolver.getPassword()); } @Override public boolean tearDown(AbstractBuild build, BuildListener listener) throws IOException, InterruptedException { FileUtils.deleteQuietly(classWorldsFile); return super.tearDown(build, listener); } private String appendNewMavenOpts(MavenModuleSet project) throws IOException { StringBuilder mavenOpts = new StringBuilder(); String opts = project.getMavenOpts(); if (StringUtils.isNotBlank(opts)) { mavenOpts.append(opts); } if (!StringUtils.contains(opts, "-Dm3plugin.lib")) { File maven3ExtractorJar = Which.jarFile(BuildInfoRecorder.class); try { FilePath actualDependencyDirectory = PluginDependencyHelper.getActualDependencyDirectory(build, maven3ExtractorJar); mavenOpts.append(" -Dm3plugin.lib=").append(actualDependencyDirectory.getRemote()); } catch (InterruptedException e) { throw new RuntimeException(e); } } return mavenOpts.toString(); } }; } public ArtifactoryServer getArtifactoryServer() { List<ArtifactoryServer> servers = getDescriptor().getArtifactoryServers(); for (ArtifactoryServer server : servers) { if (server.getName().equals(getArtifactoryName())) { return server; } } return null; } @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl) super.getDescriptor(); } @Extension(optional = true) public static class DescriptorImpl extends BuildWrapperDescriptor { public DescriptorImpl() { super(ArtifactoryMaven3NativeConfigurator.class); load(); } @Override public boolean isApplicable(AbstractProject<?, ?> item) { return MavenModuleSet.class.equals(item.getClass()); } @Override public String getDisplayName() { return "Resolve artifacts from Artifactory"; } @Override public String getHelpFile() { return "/plugin/artifactory/help/ArtifactoryMaven3NativeConfigurator/help.html"; } @Override public boolean configure(StaplerRequest req, JSONObject json) throws FormException { req.bindParameters(this, "maven"); save(); return true; } /** * Returns the list of {@link org.jfrog.hudson.ArtifactoryServer} configured. * * @return can be empty but never null. */ public List<ArtifactoryServer> getArtifactoryServers() { ArtifactoryBuilder.DescriptorImpl descriptor = (ArtifactoryBuilder.DescriptorImpl) Hudson.getInstance().getDescriptor(ArtifactoryBuilder.class); return descriptor.getArtifactoryServers(); } } }
package edu.cs4460.msd.visual.circles; import java.awt.Color; import java.awt.Rectangle; import java.awt.geom.Rectangle2D; import processing.core.PApplet; import processing.core.PConstants; import ch.randelshofer.tree.NodeInfo; import ch.randelshofer.tree.circlemap.CirclemapNode; import ch.randelshofer.tree.circlemap.CirclemapTree; import edu.cs4460.msd.backend.visual_abstract.ProcessingCirclemapDraw; import edu.cs4460.msd.visual.main.VisBase; public class CirclemapDraw implements ProcessingCirclemapDraw { private CirclemapNode root; private CirclemapNode drawRoot; private NodeInfo info; private double cx = VisBase.DEFAULT_X + VisBase.DEFAULT_WIDTH / 2, cy = VisBase.DEFAULT_Y + VisBase.DEFAULT_HEIGHT / 2; private double radius = 96; private double scaleFactor = 1; private int maxDepth = Integer.MAX_VALUE; Rectangle clipBounds; public CirclemapDraw(CirclemapTree model) { this(model.getRoot(), model.getInfo()); } public CirclemapDraw(CirclemapNode root, NodeInfo info) { this.root = this.drawRoot = root; this.info = info; } /* * Getters and Setters */ public double getCX() { return cx; } public void setCX(double newValue) { cx = newValue; } public double getCY() { return cy; } public void setCY(double newValue) { cy = newValue; } public double getRadius() { return radius; } public void setRadius(double newValue) { radius = newValue; } public NodeInfo getInfo() { return info; } public CirclemapNode getRoot() { return root; } public CirclemapNode getDrawRoot() { return drawRoot; } public void setDrawRoot(CirclemapNode newValue) { this.drawRoot = newValue; } public void setMaxDepth(int newValue) { maxDepth = newValue; } public int getMaxDepth() { return maxDepth; } public void setClipBounds(Rectangle bounds) { this.clipBounds = bounds; } /* * Draw functions */ @Override public void drawTree(PApplet par) { scaleFactor = radius/drawRoot.radius; double sx = 0; double sy = 0; CirclemapNode node = drawRoot; int depth = 1; while (node != null) { sx -= node.getCX(); sy -= node.getCY(); node = node.getParent(); depth } if (clipBounds == null) { clipBounds = new Rectangle(0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE); } drawTree0(par, root, depth, sx, sy, scaleFactor, clipBounds); } @Override public void drawTree0(PApplet par, CirclemapNode node, int depth, double px, double py, double sf, Rectangle clipBounds) { drawNode(par, node, depth, px, py, sf); if (node.radius * sf > 1 && node.children().size() > 0) { double r = node.getRadius() * sf; Rectangle2D.Double bounds = new Rectangle2D.Double( cx + sf * px - r, cy + sf*py - r, r*2, r*2); if (depth < maxDepth && clipBounds.intersects(bounds)) { for (CirclemapNode child: node.children()) { drawTree0(par, child, depth + 1, px + child.getCX(), py + child.getCY(), sf, clipBounds); } } } } @Override public void drawNode(PApplet par, CirclemapNode node, int depth, double px, double py, double sf) { double r = node.getRadius() * sf; double x = cx + px * sf; double y = cy + py * sf; Color c = info.getColor(node.getDataNodePath()); Color cd = c.darker(); if (node.isLeaf()) { par.noFill(); par.stroke(cd.getRed(), cd.getGreen(), cd.getBlue(), cd.getAlpha()); par.smooth(); par.ellipseMode(PConstants.RADIUS); par.ellipse((float)x, (float)y, (float)r, (float)r); } else if (depth == maxDepth) { double r2 = node.getWeightRadius(info); par.fill(c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha()); par.stroke(cd.getRed(), c.getGreen(), c.getBlue(), c.getAlpha()); par.smooth(); par.ellipseMode(PConstants.RADIUS); par.ellipse((float)x, (float)y, (float)r2, (float)r2); } else { par.fill(255, 255, 255); par.noStroke(); par.ellipseMode(PConstants.RADIUS); par.ellipse((float)x, (float)y, (float)r, (float)r); par.fill(c.getRed(), c.getGreen(), c.getBlue(), 50); par.stroke(cd.getRed(), c.getGreen(), c.getBlue(), c.getAlpha()); par.smooth(); par.ellipseMode(PConstants.RADIUS); par.ellipse((float)x, (float)y, (float)r, (float)r); } } public void drawNodeBounds(PApplet par, CirclemapNode selectedNode, Color color) { double r = selectedNode.getRadius() * scaleFactor; double scx = 0; double scy = 0; CirclemapNode node = selectedNode; while (node != null) { scx += node.getCX(); scy += node.getCY(); node = node.getParent(); } node = drawRoot; while (node != null) { scx -= node.getCX(); scy -= node.getCY(); node = node.getParent(); } double px = scx * scaleFactor + cx; double py = scy * scaleFactor + cy; par.stroke(color.getRed(), color.getGreen(), color.getBlue()); par.strokeWeight(2); par.noFill(); par.smooth(); par.ellipseMode(PConstants.RADIUS); par.ellipse((float)px, (float)py, (float)r, (float)r); par.strokeWeight(1); } @Override public CirclemapNode getNodeAt(int px, int py) { return getNodeAt((px - cx) / scaleFactor, (py - cy) / scaleFactor); } @Override public CirclemapNode getNodeAt(double px, double py) { CirclemapNode parent = drawRoot; int depth = 1; while (parent != null) { px += parent.getCX(); py += parent.getCY(); parent = parent.getParent(); depth } if (root.contains(px, py)) { CirclemapNode found = root; parent = found; do { parent = found; px -= parent.cx; py -= parent.cy; for (CirclemapNode node : parent.children()) { if (node.contains(px, py)) { found = node; depth++; break; } } } while (found != parent && depth < maxDepth); return found; } else { return null; } } @Override public void drawLabel(PApplet par, CirclemapNode node, int depth, double px, double py, double sf) { } }
package org.ngsutils.cli.fastq; import java.io.IOException; import org.ngsutils.NGSUtilsException; import org.ngsutils.cli.AbstractOutputCommand; import org.ngsutils.cli.Command; import org.ngsutils.fastq.Fastq; import org.ngsutils.fastq.FastqRead; import org.ngsutils.fastq.FastqReader; import org.ngsutils.support.Counter; import com.lexicalscope.jewel.cli.CommandLineInterface; import com.lexicalscope.jewel.cli.Option; import com.lexicalscope.jewel.cli.Unparsed; @CommandLineInterface(application = "ngsutilsj fastq-separate") @Command(name = "fastq-separate", desc = "Splits an interleaved FASTQ file by read number.", cat="fastq") public class FastqSeparate extends AbstractOutputCommand { private String filename = null; private boolean readOne = false; private boolean readTwo = false; public FastqSeparate() { } @Unparsed(name = "FILE") public void setFilename(String filename) throws IOException { this.filename = filename; } @Option(description = "Export read 1", shortName = "1", longName="read1") public void setReadOne(boolean value) { this.readOne = value; } @Option(description = "Export read 2", shortName = "2", longName="read2") public void setReadTwo(boolean value) { this.readTwo = value; } @Override public void exec() throws IOException, NGSUtilsException { if ((!readOne && !readTwo) || (readOne && readTwo)) { throw new NGSUtilsException("You must specify at one (and only one) read to export (-1 or -2)"); } if (verbose) { System.err.println("Spliting file:" + filename); if (readOne) { System.err.println("Exporting read 1"); } else { System.err.println("Exporting read 2"); } } FastqReader reader = Fastq.open(filename); Counter counter = new Counter(); boolean isRead1 = true; for (FastqRead read : reader) { if (readOne && isRead1) { counter.incr(); read.write(out); } else if (readTwo && !isRead1) { counter.incr(); read.write(out); } isRead1 = !isRead1; } if (verbose) { System.err.println("Total reads: " + counter.getValue()); } reader.close(); close(); } }
package org.orbeon.oxf.xforms; import org.dom4j.Document; import org.dom4j.Element; import org.orbeon.oxf.common.OXFException; import org.orbeon.oxf.common.ValidationException; import org.orbeon.oxf.pipeline.api.PipelineContext; import org.orbeon.oxf.xforms.control.XFormsControl; import org.orbeon.oxf.xforms.control.XFormsControlFactory; import org.orbeon.oxf.xforms.control.controls.*; import org.orbeon.oxf.xforms.event.XFormsEventTarget; import org.orbeon.oxf.xforms.event.events.XFormsDeselectEvent; import org.orbeon.oxf.xforms.event.events.XFormsSelectEvent; import org.orbeon.oxf.xforms.processor.XFormsServer; import org.orbeon.oxf.xml.dom4j.Dom4jUtils; import org.orbeon.oxf.xml.dom4j.ExtendedLocationData; import org.orbeon.oxf.xml.dom4j.LocationData; import org.orbeon.saxon.functions.FunctionLibrary; import org.orbeon.saxon.om.NodeInfo; import org.xml.sax.Locator; import java.util.*; /** * Represents all this XForms containing document controls and the context in which they operate. * * TODO: It would be nice to separate the context stack code from here. */ public class XFormsControls { private Locator locator; private boolean initialized; private ControlsState initialControlsState; private ControlsState currentControlsState; private SwitchState initialSwitchState; private SwitchState currentSwitchState; private DialogState initialDialogState; private DialogState currentDialogState; private boolean dirty; private XFormsContainingDocument containingDocument; private Document controlsDocument; protected Stack contextStack = new Stack(); private FunctionLibrary functionLibrary = new XFormsFunctionLibrary(this); private static final Map groupingControls = new HashMap(); private static final Map valueControls = new HashMap(); private static final Map noValueControls = new HashMap(); private static final Map leafControls = new HashMap(); private static final Map actualControls = new HashMap(); private static final Map mandatorySingleNodeControls = new HashMap(); private static final Map optionalSingleNodeControls = new HashMap(); private static final Map noSingleNodeControls = new HashMap(); private static final Map mandatoryNodesetControls = new HashMap(); private static final Map noNodesetControls = new HashMap(); static { groupingControls.put("group", ""); groupingControls.put("repeat", ""); groupingControls.put("switch", ""); groupingControls.put("case", ""); groupingControls.put("dialog", ""); valueControls.put("input", ""); valueControls.put("secret", ""); valueControls.put("textarea", ""); valueControls.put("output", ""); valueControls.put("upload", ""); valueControls.put("range", ""); valueControls.put("select", ""); valueControls.put("select1", ""); noValueControls.put("submit", ""); noValueControls.put("trigger", ""); leafControls.putAll(valueControls); leafControls.putAll(noValueControls); actualControls.putAll(groupingControls); actualControls.putAll(leafControls); mandatorySingleNodeControls.putAll(valueControls); mandatorySingleNodeControls.remove("output"); mandatorySingleNodeControls.put("filename", ""); mandatorySingleNodeControls.put("mediatype", ""); mandatorySingleNodeControls.put("setvalue", ""); optionalSingleNodeControls.putAll(noValueControls); optionalSingleNodeControls.put("output", ""); // can have @value attribute optionalSingleNodeControls.put("value", ""); // can have inline text optionalSingleNodeControls.put("label", ""); // can have linking or inline text optionalSingleNodeControls.put("help", ""); // can have linking or inline text optionalSingleNodeControls.put("hint", ""); // can have linking or inline text optionalSingleNodeControls.put("alert", ""); // can have linking or inline text optionalSingleNodeControls.put("copy", ""); optionalSingleNodeControls.put("load", ""); // can have linking optionalSingleNodeControls.put("message", ""); // can have linking or inline text optionalSingleNodeControls.put("group", ""); optionalSingleNodeControls.put("switch", ""); noSingleNodeControls.put("choices", ""); noSingleNodeControls.put("item", ""); noSingleNodeControls.put("case", ""); noSingleNodeControls.put("toggle", ""); mandatoryNodesetControls.put("repeat", ""); mandatoryNodesetControls.put("itemset", ""); mandatoryNodesetControls.put("insert", ""); mandatoryNodesetControls.put("delete", ""); noNodesetControls.putAll(mandatorySingleNodeControls); noNodesetControls.putAll(optionalSingleNodeControls); noNodesetControls.putAll(noSingleNodeControls); } public XFormsControls(XFormsContainingDocument containingDocument, Document controlsDocument, Element repeatIndexesElement) { this.containingDocument = containingDocument; this.controlsDocument = controlsDocument; // Build minimal state with repeat indexes so that index() function works in XForms models // initialization initializeMinimal(repeatIndexesElement); } private void initializeMinimal(Element repeatIndexesElement) { // Set initial repeat index if (controlsDocument != null) { final ControlsState result = new ControlsState(); getDefaultRepeatIndexes(result); initialControlsState = result; currentControlsState = initialControlsState; } // Set repeat index state if any setRepeatIndexState(repeatIndexesElement); } public boolean isDirty() { return dirty; } public void markDirty() { this.dirty = true; this.currentControlsState.markDirty(); } /** * Iterate statically through controls and set the default repeat index for xforms:repeat. * * @param controlsState ControlsState to update with setDefaultRepeatIndex() */ private void getDefaultRepeatIndexes(final ControlsState controlsState) { visitAllControlStatic(new ControlElementVisitorListener() { private Stack repeatStack = new Stack(); public boolean startVisitControl(Element controlElement, String effectiveControlId) { if (controlElement.getName().equals("repeat")) { // Create control without parent, just to hold iterations final XFormsRepeatControl repeatControl = new XFormsRepeatControl(containingDocument, null, controlElement, controlElement.getName(), effectiveControlId); // Set initial index controlsState.setDefaultRepeatIndex(repeatControl.getRepeatId(), repeatControl.getStartIndex()); // Keep control on stack repeatStack.push(repeatControl); } return true; } public boolean endVisitControl(Element controlElement, String effectiveControlId) { return true; } public void startRepeatIteration(int iteration) { // One more iteration in current repeat final XFormsRepeatControl repeatControl = (XFormsRepeatControl) repeatStack.peek(); repeatControl.addChild(new RepeatIterationControl(containingDocument, repeatControl, iteration)); } public void endRepeatIteration(int iteration) { } }); } /** * Initialize the controls if needed. This is usually called upon initial creation of the engine. * * @param pipelineContext current PipelineContext */ public void initialize(PipelineContext pipelineContext) { initializeState(pipelineContext, null, null); } /** * Initialize the controls if needed, passing initial state information. This is called if the state of the engine * needs to be rebuilt. * * @param pipelineContext current PipelineContext * @param divsElement current div elements, or null * @param repeatIndexesElement current repeat indexes, or null */ public void initializeState(PipelineContext pipelineContext, Element divsElement, Element repeatIndexesElement) { if (controlsDocument != null) { if (initialized) { // Use existing controls state initialControlsState = currentControlsState; initialSwitchState = currentSwitchState; initialDialogState = currentDialogState; } else { // Build controls state // Get initial controls state information initialControlsState = buildControlsState(pipelineContext); currentControlsState = initialControlsState; initialSwitchState = new SwitchState(initialControlsState.getSwitchIdToSelectedCaseIdMap()); currentSwitchState = initialSwitchState; initialDialogState = new DialogState(initialControlsState.getDialogIdToVisibleMap()); currentDialogState = initialDialogState; // Set switch state if necessary if (divsElement != null) { for (Iterator i = divsElement.elements().iterator(); i.hasNext();) { final Element divElement = (Element) i.next(); final String id = divElement.attributeValue("id"); final String visibilityString = divElement.attributeValue("visibility"); final boolean visibility = "visible".equals(visibilityString); if (currentControlsState.getDialogIdToVisibleMap().get(id) != null) { // xxforms:dialog currentDialogState.showHide(id, visibility); } else { // xforms:switch/xforms:case currentSwitchState.initializeState(id, initialControlsState, visibility); } } } // Handle repeat indexes if needed if (initialControlsState.isHasRepeat()) { // Get default xforms:repeat indexes beforehand getDefaultRepeatIndexes(initialControlsState); // Set external updates setRepeatIndexState(repeatIndexesElement); // Adjust repeat indexes XFormsIndexUtils.adjustIndexes(pipelineContext, XFormsControls.this, initialControlsState); } } // We are now clean dirty = false; initialControlsState.dirty = false; } resetBindingContext(); initialized = true; } private void setRepeatIndexState(Element repeatIndexesElement) { if (repeatIndexesElement != null) { for (Iterator i = repeatIndexesElement.elements().iterator(); i.hasNext();) { final Element repeatIndexElement = (Element) i.next(); final String repeatId = repeatIndexElement.attributeValue("id"); final String index = repeatIndexElement.attributeValue("index"); initialControlsState.updateRepeatIndex(repeatId, Integer.parseInt(index)); } } } /** * Reset the binding context to the root of the containing document. */ public void resetBindingContext() { resetBindingContext(containingDocument.getModel("")); } public void resetBindingContext(XFormsModel xformsModel) { // Clear existing stack contextStack.clear(); // Push the default context final List defaultNodeset = Arrays.asList(new Object[]{xformsModel.getDefaultInstance().getInstanceRootElementInfo()}); contextStack.push(new BindingContext(null, xformsModel, defaultNodeset, 1, null, true, null)); } public XFormsContainingDocument getContainingDocument() { return containingDocument; } public static boolean isValueControl(String controlName) { return valueControls.get(controlName) != null; } public static boolean isGroupingControl(String controlName) { return groupingControls.get(controlName) != null; } public static boolean isLeafControl(String controlName) { return leafControls.get(controlName) != null; } public static boolean isActualControl(String controlName) { return actualControls.get(controlName) != null; } /** * Set the binding context to the current control. * * @param pipelineContext current PipelineContext * @param xformsControl control to bind */ public void setBinding(PipelineContext pipelineContext, XFormsControl xformsControl) { // Create ancestors-or-self list final List ancestorsOrSelf = new ArrayList(); BindingContext controlBindingContext = xformsControl.getBindingContext(); while (controlBindingContext != null) { ancestorsOrSelf.add(controlBindingContext); controlBindingContext = controlBindingContext.getParent(); } Collections.reverse(ancestorsOrSelf); // Bind up to the specified element contextStack.clear(); contextStack.addAll(ancestorsOrSelf); } private void pushBinding(PipelineContext pipelineContext, XFormsControl XFormsControl) { final Element bindingElement = XFormsControl.getControlElement(); if (!(XFormsControl instanceof RepeatIterationControl)) { // Regular XFormsControl backed by an element final String ref = bindingElement.attributeValue("ref"); final String context = bindingElement.attributeValue("context"); final String nodeset = bindingElement.attributeValue("nodeset"); final String modelId = XFormsUtils.namespaceId(containingDocument, bindingElement.attributeValue("model")); final String bindId = XFormsUtils.namespaceId(containingDocument, bindingElement.attributeValue("bind")); final Map bindingElementNamespaceContext = (ref != null || nodeset != null) ? Dom4jUtils.getNamespaceContextNoDefault(bindingElement) : null; pushBinding(pipelineContext, ref, context, nodeset, modelId, bindId, bindingElement, bindingElementNamespaceContext); } else { // RepeatIterationInfo final XFormsControl repeatXFormsControl = XFormsControl.getParent(); final List repeatChildren = repeatXFormsControl.getChildren(); final BindingContext currentBindingContext = getCurrentBindingContext(); final List currentNodeset = currentBindingContext.getNodeset(); final int repeatChildrenSize = (repeatChildren == null) ? 0 : repeatChildren.size(); final int currentNodesetSize = (currentNodeset == null) ? 0 : currentNodeset.size(); if (repeatChildrenSize != currentNodesetSize) throw new IllegalStateException("repeatChildren and newNodeset have different sizes."); // Push "artificial" binding with just current node in nodeset final XFormsModel newModel = currentBindingContext.getModel(); final int position = ((RepeatIterationControl) XFormsControl).getIteration(); contextStack.push(new BindingContext(currentBindingContext, newModel, currentNodeset, position, XFormsControl.getParent().getOriginalId(), true, null)); } } /** * Push an element containing either single-node or nodeset binding attributes. */ public void pushBinding(PipelineContext pipelineContext, Element bindingElement) { pushBinding(pipelineContext, bindingElement, null); } /** * Push an element containing either single-node or nodeset binding attributes. * * @param pipelineContext current PipelineContext * @param bindingElement current element containing node binding attributes * @param model if specified, overrides a potential @model attribute on the element */ public void pushBinding(PipelineContext pipelineContext, Element bindingElement, String model) { final String ref = bindingElement.attributeValue("ref"); final String context = bindingElement.attributeValue("context"); final String nodeset = bindingElement.attributeValue("nodeset"); if (model == null) model = XFormsUtils.namespaceId(containingDocument, bindingElement.attributeValue("model")); final String bind = XFormsUtils.namespaceId(containingDocument, bindingElement.attributeValue("bind")); pushBinding(pipelineContext, ref, context, nodeset, model, bind, bindingElement, (ref != null || nodeset != null) ? Dom4jUtils.getNamespaceContextNoDefault(bindingElement) : null); } public void pushBinding(PipelineContext pipelineContext, String ref, String context, String nodeset, String modelId, String bindId, Element bindingElement, Map bindingElementNamespaceContext) { // Check for mandatory and optional bindings if (bindingElement != null && XFormsConstants.XFORMS_NAMESPACE_URI.equals(bindingElement.getNamespaceURI())) { final String controlName = bindingElement.getName(); if (mandatorySingleNodeControls.get(controlName) != null && !(bindingElement.attribute("ref") != null || bindingElement.attribute("bind") != null)) { throw new OXFException("Missing mandatory single node binding for element: " + bindingElement.getQualifiedName()); } if (noSingleNodeControls.get(controlName) != null && (bindingElement.attribute("ref") != null || bindingElement.attribute("bind") != null)) { throw new OXFException("Single node binding is prohibited for element: " + bindingElement.getQualifiedName()); } if (mandatoryNodesetControls.get(controlName) != null && !(bindingElement.attribute("nodeset") != null || bindingElement.attribute("bind") != null)) { throw new OXFException("Missing mandatory nodeset binding for element: " + bindingElement.getQualifiedName()); } if (noNodesetControls.get(controlName) != null && bindingElement.attribute("nodeset") != null) { throw new OXFException("Node-set binding is prohibited for element: " + bindingElement.getQualifiedName()); } } // Determine current context final BindingContext currentBindingContext = getCurrentBindingContext(); // Handle model final XFormsModel newModel; final boolean isNewModel; if (modelId != null) { newModel = containingDocument.getModel(modelId); if (newModel == null) throw new ValidationException("Invalid model id: " + modelId, (bindingElement == null) ? null : (LocationData) bindingElement.getData()); isNewModel = true; } else { newModel = currentBindingContext.getModel(); isNewModel = false; } // Handle nodeset final List newNodeset; { if (bindId != null) { // Resolve the bind id to a nodeset final ModelBind modelBind = newModel.getModelBindById(bindId); if (modelBind == null) throw new OXFException("Cannot find bind for id: " + bindId); newNodeset = newModel.getBindNodeset(pipelineContext, modelBind); } else if (ref != null || nodeset != null) { // Check whether there is an optional context if (nodeset != null && context != null) { pushBinding(pipelineContext, null, null, context, modelId, null, null, bindingElementNamespaceContext); } // Evaluate new XPath in context if (isNewModel) { // Model was switched final NodeInfo currentSingleNodeForModel = getCurrentSingleNode(newModel.getEffectiveId()); if (currentSingleNodeForModel != null) { // Temporarily update the context so that the function library's instance() function works final BindingContext modelBindingContext = getCurrentBindingContextForModel(newModel.getEffectiveId()); if (modelBindingContext != null) contextStack.push(new BindingContext(currentBindingContext, newModel, modelBindingContext.getNodeset(), modelBindingContext.getPosition(), null, false, null)); else contextStack.push(new BindingContext(currentBindingContext, newModel, getCurrentNodeset(newModel.getEffectiveId()), 1, null, false, null)); // Evaluate new node-set newNodeset = containingDocument.getEvaluator().evaluate(pipelineContext, currentSingleNodeForModel, ref != null ? ref : nodeset, bindingElementNamespaceContext, null, functionLibrary, null); // Restore context contextStack.pop(); } else { newNodeset = Collections.EMPTY_LIST; } } else { // Simply evaluate new node-set final NodeInfo currentSingleNode = getCurrentSingleNode(); if (currentSingleNode != null) { newNodeset = containingDocument.getEvaluator().evaluate(pipelineContext, currentSingleNode, ref != null ? ref : nodeset, bindingElementNamespaceContext, null, functionLibrary, null); } else { newNodeset = Collections.EMPTY_LIST; } } // Restore optional context if (nodeset != null && context != null) { popBinding(); } } else if (isNewModel) { // Only the model has changed final NodeInfo currentSingleNodeForModel = getCurrentSingleNode(newModel.getEffectiveId()); if (currentSingleNodeForModel != null) { newNodeset = Collections.singletonList(currentSingleNodeForModel); } else { newNodeset = Collections.EMPTY_LIST; } } else { // No change to current nodeset newNodeset = currentBindingContext.getNodeset(); } } // Push new context final boolean isNewBind = newNodeset != currentBindingContext.getNodeset();// TODO: this is used only in one place later; check final String id = (bindingElement == null) ? null : bindingElement.attributeValue("id"); contextStack.push(new BindingContext(currentBindingContext, newModel, newNodeset, isNewBind ? 1 : currentBindingContext.getPosition(), id, isNewBind, bindingElement)); } /** * NOTE: Not sure this should be exposed. */ public Stack getContextStack() { return contextStack; } /** * NOTE: Not sure this should be exposed. */ public BindingContext getCurrentBindingContext() { return (BindingContext) contextStack.peek(); } public BindingContext popBinding() { if (contextStack.size() == 1) throw new OXFException("Attempt to clear XForms controls context stack."); return (BindingContext) contextStack.pop(); } /** * Get the current node-set binding for the given model id. */ public BindingContext getCurrentBindingContextForModel(String modelId) { for (int i = contextStack.size() - 1; i >= 0; i final BindingContext currentBindingContext = (BindingContext) contextStack.get(i); final String currentModelId = currentBindingContext.getModel().getEffectiveId(); if ((currentModelId == null && modelId == null) || (modelId != null && modelId.equals(currentModelId))) return currentBindingContext; } return null; } /** * Get the current node-set binding for the given model id. */ public List getCurrentNodeset(String modelId) { final BindingContext bindingContext = getCurrentBindingContextForModel(modelId); // If a context exists, return its node-set if (bindingContext != null) return bindingContext.getNodeset(); // If not found, return the document element of the model's default instance final XFormsInstance defaultInstance = containingDocument.getModel(modelId).getDefaultInstance(); if (defaultInstance == null) throw new OXFException("Cannot find default instance in model: " + modelId); return Collections.singletonList(defaultInstance.getInstanceRootElementInfo()); } /** * Get the current single node binding for the given model id. */ public NodeInfo getCurrentSingleNode(String modelId) { final List currentNodeset = getCurrentNodeset(modelId); return (NodeInfo) ((currentNodeset == null || currentNodeset.size() == 0) ? null : currentNodeset.get(0)); } /** * Get the current single node binding, if any. */ public NodeInfo getCurrentSingleNode() { return getCurrentBindingContext().getSingleNode(); } public String getCurrentSingleNodeValue() { final NodeInfo currentSingleNode = getCurrentSingleNode(); if (currentSingleNode != null) return XFormsInstance.getValueForNode(currentSingleNode); else return null; } /** * Get the current nodeset binding, if any. */ public List getCurrentNodeset() { return getCurrentBindingContext().getNodeset(); } /** * Get the current position in current nodeset binding. */ public int getCurrentPosition() { return getCurrentBindingContext().getPosition(); } /** * Return the single node associated with the iteration of the repeat specified. If a null * repeat id is passed, return the single node associated with the closest enclosing repeat * iteration. * * @param repeatId enclosing repeat id, or null * @return the single node */ public NodeInfo getRepeatCurrentSingleNode(String repeatId) { for (int i = contextStack.size() - 1; i >= 0; i final BindingContext currentBindingContext = (BindingContext) contextStack.get(i); final Element bindingElement = currentBindingContext.getControlElement(); final String repeatIdForIteration = currentBindingContext.getIdForContext(); if (bindingElement == null && repeatIdForIteration != null) { if (repeatId == null || repeatId.equals(repeatIdForIteration)) { // Found binding context for relevant repeat iteration return currentBindingContext.getSingleNode(); } } } // It is required that there is a relevant enclosing xforms:repeat if (repeatId == null) throw new OXFException("Enclosing xforms:repeat not found."); else throw new OXFException("Enclosing xforms:repeat not found for id: " + repeatId); } /** * For the given case id and the current binding, try to find an effective case id. * * The effective case id is for now the effective case id following repeat branches. This can be improved in the * future. * * @param caseId a case id * @return an effective case id if possible */ public String findEffectiveCaseId(String caseId) { return getCurrentControlsState().findEffectiveControlId(caseId); } /** * Return the context node-set based on the enclosing xforms:repeat, xforms:group or * xforms:switch, either the closest one if no argument is passed, or context at the level of * the element with the given id passed. * * @param contextId enclosing context id, or null * @return the node-set */ public List getContextForId(String contextId) { for (int i = contextStack.size() - 1; i >= 0; i final BindingContext currentBindingContext = (BindingContext) contextStack.get(i); final Element bindingElement = currentBindingContext.getControlElement(); final String idForContext = currentBindingContext.getIdForContext(); if (bindingElement != null && idForContext != null) { if (contextId == null || contextId.equals(idForContext)) { // Found binding context for relevant repeat iteration return currentBindingContext.getNodeset(); } } } // It is required that there is a relevant enclosing xforms:repeat if (contextId == null) throw new OXFException("Enclosing XForms element not found."); else throw new OXFException("Enclosing XForms element not found for id: " + contextId); } /** * Return the currrent model for the current nodeset binding. */ public XFormsModel getCurrentModel() { return getCurrentBindingContext().getModel(); } /** * Return the current instance for the current nodeset binding. * * This method goes up the context stack until it finds a node, and returns the instance associated with that node. */ public XFormsInstance getCurrentInstance() { for (int i = contextStack.size() - 1; i >= 0; i final BindingContext currentBindingContext = (BindingContext) contextStack.get(i); final NodeInfo currentSingleNode = currentBindingContext.getSingleNode(); if (currentSingleNode != null) return getContainingDocument().getInstanceForNode(currentSingleNode); } return null; } public FunctionLibrary getFunctionLibrary() { return functionLibrary; } private ControlsState buildControlsState(final PipelineContext pipelineContext) { final long startTime; if (XFormsServer.logger.isDebugEnabled()) { XFormsServer.logger.debug("XForms - building controls state start."); startTime = System.currentTimeMillis(); } else { startTime = 0; } final ControlsState result = new ControlsState(); final XFormsControl rootXFormsControl = new RootControl(containingDocument);// this is temporary and won't be stored final Map idsToXFormsControls = new HashMap(); final Map switchIdToSelectedCaseIdMap = new HashMap(); final Map dialogIdToVisibleMap = new HashMap(); visitAllControlsHandleRepeat(pipelineContext, new XFormsControls.ControlElementVisitorListener() { private XFormsControl currentControlsContainer = rootXFormsControl; public boolean startVisitControl(Element controlElement, String effectiveControlId) { if (effectiveControlId == null) throw new OXFException("Control element doesn't have an id: " + controlElement.getQualifiedName()); final String controlName = controlElement.getName(); // Create XFormsControl with basic information final XFormsControl xformsControl = XFormsControlFactory.createXFormsControl(containingDocument, currentControlsContainer, controlElement, controlName, effectiveControlId); if (xformsControl instanceof XFormsRepeatControl) result.setHasRepeat(true); else if (xformsControl instanceof XFormsUploadControl) result.setHasUpload(true); // Make sure there are no duplicate ids if (idsToXFormsControls.get(effectiveControlId) != null) throw new ValidationException("Duplicate id for XForms control: " + effectiveControlId, new ExtendedLocationData((LocationData) controlElement.getData(), "analyzing control element", controlElement, new String[] { "id", effectiveControlId })); idsToXFormsControls.put(effectiveControlId, xformsControl); // Handle xforms:case if (controlName.equals("case")) { if (!(currentControlsContainer.getName().equals("switch"))) throw new OXFException("xforms:case with id '" + effectiveControlId + "' is not directly within an xforms:switch container."); final String switchId = currentControlsContainer.getEffectiveId(); if (switchIdToSelectedCaseIdMap.get(switchId) == null) { // If case is not already selected for this switch and there is a select attribute, set it final String selectedAttribute = controlElement.attributeValue("selected"); if ("true".equals(selectedAttribute)) switchIdToSelectedCaseIdMap.put(switchId, effectiveControlId); } } // Handle xxforms:dialog if (controlName.equals("dialog")) { dialogIdToVisibleMap.put(effectiveControlId, Boolean.valueOf(false)); } // Handle xforms:itemset // TODO: We don't need to do this every time, only when we need to produce output, right? if (xformsControl instanceof XFormsSelectControl || xformsControl instanceof XFormsSelect1Control) { ((XFormsSelect1Control) xformsControl).evaluateItemsets(pipelineContext); } // Set current binding for control element final BindingContext currentBindingContext = getCurrentBindingContext(); final List currentNodeSet = currentBindingContext.getNodeset(); // Bind the control to the binding context xformsControl.setBindingContext(currentBindingContext); // Update MIPs on control // TODO: we don't need to set these values until we produce output, right? if (!(xformsControl instanceof XFormsRepeatControl && currentNodeSet != null && currentNodeSet.size() == 0)) { final NodeInfo currentNode = currentBindingContext.getSingleNode(); if (currentNode != null) { // Control is bound to a node - get model item properties final InstanceData instanceData = XFormsUtils.getInstanceDataUpdateInherited(currentNode); if (instanceData != null) { xformsControl.setReadonly(instanceData.getInheritedReadonly().get()); xformsControl.setRequired(instanceData.getRequired().get()); xformsControl.setRelevant(instanceData.getInheritedRelevant().get()); xformsControl.setValid(instanceData.getValid().get()); final String typeAsString = instanceData.getType().getAsString(); if (typeAsString != null) { xformsControl.setType(typeAsString); } } // Handle global read-only setting if (containingDocument.isReadonly()) xformsControl.setReadonly(true); } else { // Control is not bound to a node - it becomes non-relevant xformsControl.setReadonly(false); xformsControl.setRequired(false); xformsControl.setRelevant(false); xformsControl.setValid(true);// by default, a control is not invalid xformsControl.setType(null); } } // Add to current controls container currentControlsContainer.addChild(xformsControl); // Current grouping control becomes the current controls container if (isGroupingControl(controlName)) { currentControlsContainer = xformsControl; } return true; } public boolean endVisitControl(Element controlElement, String effectiveControlId) { final String controlName = controlElement.getName(); // Handle xforms:switch if (controlName.equals("switch")) { if (switchIdToSelectedCaseIdMap.get(effectiveControlId) == null) { // No case was selected, select first case id final List children = currentControlsContainer.getChildren(); if (children != null && children.size() > 0) switchIdToSelectedCaseIdMap.put(effectiveControlId, ((XFormsControl) children.get(0)).getEffectiveId()); } } // Handle grouping controls if (isGroupingControl(controlName)) { if (controlName.equals("repeat")) { // Store number of repeat iterations for the effective id final List children = currentControlsContainer.getChildren(); if (children == null || children.size() == 0) { // Current index is 0 result.setRepeatIterations(effectiveControlId, 0); } else { // Number of iterations is number of children result.setRepeatIterations(effectiveControlId, children.size()); } } currentControlsContainer = currentControlsContainer.getParent(); } return true; } public void startRepeatIteration(int iteration) { final XFormsControl repeatIterationXForms = new RepeatIterationControl(containingDocument, currentControlsContainer, iteration); currentControlsContainer.addChild(repeatIterationXForms); currentControlsContainer = repeatIterationXForms; // Set current binding for control element final BindingContext currentBindingContext = getCurrentBindingContext(); // Bind the control to the binding context repeatIterationXForms.setBindingContext(currentBindingContext); // Set current binding for control element final NodeInfo currentNode = currentBindingContext.getSingleNode(); // Get model item properties final InstanceData instanceData = XFormsUtils.getInstanceDataUpdateInherited(currentNode); if (instanceData != null) { repeatIterationXForms.setReadonly(instanceData.getInheritedReadonly().get()); repeatIterationXForms.setRequired(instanceData.getRequired().get()); repeatIterationXForms.setRelevant(instanceData.getInheritedRelevant().get()); repeatIterationXForms.setValid(instanceData.getValid().get()); } // Handle global read-only setting if (containingDocument.isReadonly()) repeatIterationXForms.setReadonly(true); } public void endRepeatIteration(int iteration) { currentControlsContainer = currentControlsContainer.getParent(); } }); // Make it so that all the root XFormsControl don't have a parent final List rootChildren = rootXFormsControl.getChildren(); if (rootChildren != null) { for (Iterator i = rootChildren.iterator(); i.hasNext();) { final XFormsControl currentXFormsControl = (XFormsControl) i.next(); currentXFormsControl.detach(); } } result.setChildren(rootChildren); result.setIdsToXFormsControls(idsToXFormsControls); result.setSwitchIdToSelectedCaseIdMap(switchIdToSelectedCaseIdMap); result.setDialogIdToVisibleMap(dialogIdToVisibleMap); // Evaluate all controls for (Iterator i = idsToXFormsControls.entrySet().iterator(); i.hasNext();) { final Map.Entry currentEntry = (Map.Entry) i.next(); final XFormsControl currentControl = (XFormsControl) currentEntry.getValue(); currentControl.evaluate(pipelineContext); } if (XFormsServer.logger.isDebugEnabled()) { XFormsServer.logger.debug("XForms - building controls state end: " + (System.currentTimeMillis() - startTime) + " ms."); } return result; } /** * Get the ControlsState computed in the initialize() method. */ public ControlsState getInitialControlsState() { return initialControlsState; } /** * Get the last computed ControlsState. */ public ControlsState getCurrentControlsState() { return currentControlsState; } /** * Get the SwitchState computed in the initialize() method. */ public SwitchState getInitialSwitchState() { return initialSwitchState; } /** * Get the last computed SwitchState. */ public SwitchState getCurrentSwitchState() { return currentSwitchState; } public DialogState getInitialDialogState() { return initialDialogState; } public DialogState getCurrentDialogState() { return currentDialogState; } /** * Activate a switch case by case id. * * @param pipelineContext current PipelineContext * @param caseId case id to activate */ public void activateCase(PipelineContext pipelineContext, String caseId) { if (initialSwitchState == currentSwitchState) currentSwitchState = new SwitchState(new HashMap(initialSwitchState.getSwitchIdToSelectedCaseIdMap())); getCurrentSwitchState().updateSwitchInfo(pipelineContext, containingDocument, getCurrentControlsState(), caseId); } public void showHideDialog(String dialogId, boolean show) { // Make sure the id refers to an existing xxforms:dialog final Object object = getObjectById(dialogId); if (object == null || !(object instanceof XXFormsDialogControl)) return; // Update state if (initialDialogState == currentDialogState) currentDialogState = new DialogState(new HashMap(initialDialogState.getDialogIdToVisibleMap())); currentDialogState.showHide(dialogId, show); } /** * Rebuild the current controls state information if needed. */ public boolean rebuildCurrentControlsStateIfNeeded(PipelineContext pipelineContext) { // Don't do anything if we are clean if (!currentControlsState.isDirty()) return false; // Rebuild rebuildCurrentControlsState(pipelineContext); // Everything is clean initialControlsState.dirty = false; currentControlsState.dirty = false; return true; } /** * Rebuild the current controls state information. */ public void rebuildCurrentControlsState(PipelineContext pipelineContext) { // Remember current state final ControlsState currentControlsState = this.currentControlsState; // Create new controls state final ControlsState result = buildControlsState(pipelineContext); // Transfer some of the previous information final Map currentRepeatIdToIndex = currentControlsState.getRepeatIdToIndex(); if (currentRepeatIdToIndex.size() != 0) { // Keep repeat index information result.setRepeatIdToIndex(currentRepeatIdToIndex); // Adjust repeat indexes if necessary XFormsIndexUtils.adjustIndexes(pipelineContext, XFormsControls.this, result); } // Update xforms;switch information: use new values, except where old values are available final Map oldSwitchIdToSelectedCaseIdMap = getCurrentSwitchState().getSwitchIdToSelectedCaseIdMap(); final Map newSwitchIdToSelectedCaseIdMap = result.getSwitchIdToSelectedCaseIdMap(); { for (Iterator i = newSwitchIdToSelectedCaseIdMap.entrySet().iterator(); i.hasNext();) { final Map.Entry entry = (Map.Entry) i.next(); final String switchId = (String) entry.getKey(); // Keep old switch state final String oldSelectedCaseId = (String) oldSwitchIdToSelectedCaseIdMap.get(switchId); if (oldSelectedCaseId != null) { entry.setValue(oldSelectedCaseId); } } this.currentSwitchState = new SwitchState(newSwitchIdToSelectedCaseIdMap); } // Update xxforms:dialog information // NOP! // Update current state this.currentControlsState = result; // Handle relevance of controls that are no longer bound to instance data nodes final Map[] eventsToDispatch = new Map[] { currentControlsState.getEventsToDispatch() } ; findSpecialRelevanceChanges(currentControlsState.getChildren(), result.getChildren(), eventsToDispatch); this.currentControlsState.setEventsToDispatch(eventsToDispatch[0]); } /** * Perform a refresh of the controls for a given model */ public void refreshForModel(final PipelineContext pipelineContext, final XFormsModel model) { // NOP } /** * Return the current repeat index for the given xforms:repeat id, -1 if the id is not found. */ public int getRepeatIdIndex(String repeatId) { final Map repeatIdToIndex = currentControlsState.getRepeatIdToIndex(); final Integer currentIndex = (Integer) repeatIdToIndex.get(repeatId); return (currentIndex == null) ? -1 : currentIndex.intValue(); } public Locator getLocator() { return locator; } public void setLocator(Locator locator) { this.locator = locator; } /** * Get the object with the id specified, null if not found. */ public Object getObjectById(String controlId) { return currentControlsState.getIdToControl().get(controlId); } /** * Visit all the effective controls elements. */ public void visitAllControlsHandleRepeat(PipelineContext pipelineContext, ControlElementVisitorListener controlElementVisitorListener) { resetBindingContext(); handleControls(pipelineContext, controlElementVisitorListener, controlsDocument.getRootElement(), ""); } private boolean handleControls(PipelineContext pipelineContext, ControlElementVisitorListener controlElementVisitorListener, Element container, String idPostfix) { boolean doContinue = true; for (Iterator i = container.elements().iterator(); i.hasNext();) { final Element controlElement = (Element) i.next(); final String controlName = controlElement.getName(); final String controlId = controlElement.attributeValue("id"); final String effectiveControlId = controlId + (idPostfix.equals("") ? "" : XFormsConstants.REPEAT_HIERARCHY_SEPARATOR_1 + idPostfix); if (controlName.equals("repeat")) { // Handle xforms:repeat // Push binding for xforms:repeat pushBinding(pipelineContext, controlElement); try { final BindingContext currentBindingContext = getCurrentBindingContext(); // Visit xforms:repeat element doContinue = controlElementVisitorListener.startVisitControl(controlElement, effectiveControlId); // Iterate over current xforms:repeat nodeset final List currentNodeSet = getCurrentNodeset(); if (currentNodeSet != null) { for (int currentPosition = 1; currentPosition <= currentNodeSet.size(); currentPosition++) { // Push "artificial" binding with just current node in nodeset contextStack.push(new BindingContext(currentBindingContext, currentBindingContext.getModel(), currentNodeSet, currentPosition, controlId, true, null)); try { // Handle children of xforms:repeat if (doContinue) { controlElementVisitorListener.startRepeatIteration(currentPosition); final String newIdPostfix = idPostfix.equals("") ? Integer.toString(currentPosition) : (idPostfix + XFormsConstants.REPEAT_HIERARCHY_SEPARATOR_2 + currentPosition); doContinue = handleControls(pipelineContext, controlElementVisitorListener, controlElement, newIdPostfix); controlElementVisitorListener.endRepeatIteration(currentPosition); } } finally { contextStack.pop(); } if (!doContinue) break; } } doContinue = doContinue && controlElementVisitorListener.endVisitControl(controlElement, effectiveControlId); } finally { popBinding(); } } else if (isGroupingControl(controlName)) { // Handle XForms grouping controls pushBinding(pipelineContext, controlElement); try { doContinue = controlElementVisitorListener.startVisitControl(controlElement, effectiveControlId); if (doContinue) doContinue = handleControls(pipelineContext, controlElementVisitorListener, controlElement, idPostfix); doContinue = doContinue && controlElementVisitorListener.endVisitControl(controlElement, effectiveControlId); } finally { popBinding(); } } else if (isLeafControl(controlName)) { // Handle leaf control pushBinding(pipelineContext, controlElement); try { doContinue = controlElementVisitorListener.startVisitControl(controlElement, effectiveControlId); doContinue = doContinue && controlElementVisitorListener.endVisitControl(controlElement, effectiveControlId); } finally { popBinding(); } } if (!doContinue) break; } return doContinue; } /** * Visit all the control elements without handling repeats or looking at the binding contexts. */ public void visitAllControlStatic(ControlElementVisitorListener controlElementVisitorListener) { handleControlsStatic(controlElementVisitorListener, controlsDocument.getRootElement()); } private boolean handleControlsStatic(ControlElementVisitorListener controlElementVisitorListener, Element container) { boolean doContinue = true; for (Iterator i = container.elements().iterator(); i.hasNext();) { final Element controlElement = (Element) i.next(); final String controlName = controlElement.getName(); final String controlId = controlElement.attributeValue("id"); if (isGroupingControl(controlName)) { // Handle XForms grouping controls doContinue = controlElementVisitorListener.startVisitControl(controlElement, controlId); if (doContinue) doContinue = handleControlsStatic(controlElementVisitorListener, controlElement); doContinue = doContinue && controlElementVisitorListener.endVisitControl(controlElement, controlId); } else if (isLeafControl(controlName)) { // Handle leaf control doContinue = controlElementVisitorListener.startVisitControl(controlElement, controlId); doContinue = doContinue && controlElementVisitorListener.endVisitControl(controlElement, controlId); } if (!doContinue) break; } return doContinue; } /** * Visit all the current XFormsControls. */ public void visitAllControls(XFormsControlVisitorListener xformsControlVisitorListener) { handleControl(xformsControlVisitorListener, currentControlsState.getChildren()); } /** * Visit all the children of the given XFormsControl. */ public void visitAllControls(XFormsControlVisitorListener xformsControlVisitorListener, XFormsControl currentXFormsControl) { handleControl(xformsControlVisitorListener, currentXFormsControl.getChildren()); } private void handleControl(XFormsControlVisitorListener xformsControlVisitorListener, List children) { if (children != null && children.size() > 0) { for (Iterator i = children.iterator(); i.hasNext();) { final XFormsControl XFormsControl = (XFormsControl) i.next(); xformsControlVisitorListener.startVisitControl(XFormsControl); handleControl(xformsControlVisitorListener, XFormsControl.getChildren()); xformsControlVisitorListener.endVisitControl(XFormsControl); } } } public static class BindingContext { private BindingContext parent; private XFormsModel model; private List nodeset; private int position = 1; private String idForContext; private boolean newBind; private Element controlElement; public BindingContext(BindingContext parent, XFormsModel model, List nodeSet, int position, String idForContext, boolean newBind, Element controlElement) { this.parent = parent; this.model = model; this.nodeset = nodeSet; this.position = position; this.idForContext = idForContext; this.newBind = newBind; this.controlElement = controlElement; if (nodeset != null && nodeset.size() > 0) { for (Iterator i = nodeset.iterator(); i.hasNext();) { final Object currentItem = i.next(); if (!(currentItem instanceof NodeInfo)) throw new OXFException("A reference to a node (such as text, element, or attribute) is required in a binding. Attempted to bind to the invalid item type: " + currentItem.getClass()); } } } public BindingContext getParent() { return parent; } public XFormsModel getModel() { return model; } public List getNodeset() { return nodeset; } public int getPosition() { return position; } public String getIdForContext() { return idForContext; } public boolean isNewBind() { return newBind; } public Element getControlElement() { return controlElement; } /** * Get the current single node binding, if any. */ public NodeInfo getSingleNode() { if (nodeset == null || nodeset.size() == 0) return null; return (NodeInfo) nodeset.get(position - 1); } } public static interface ControlElementVisitorListener { public boolean startVisitControl(Element controlElement, String effectiveControlId); public boolean endVisitControl(Element controlElement, String effectiveControlId); public void startRepeatIteration(int iteration); public void endRepeatIteration(int iteration); } public static interface XFormsControlVisitorListener { public void startVisitControl(XFormsControl xformsControl); public void endVisitControl(XFormsControl xformsControl); } /** * Represents the state of repeat indexes. */ // public static class RepeatIndexesState { // public RepeatIndexesState() { /** * Represents the state of switches. */ public static class SwitchState { private Map switchIdToSelectedCaseIdMap; public SwitchState(Map switchIdToSelectedCaseIdMap) { this.switchIdToSelectedCaseIdMap = switchIdToSelectedCaseIdMap; } public Map getSwitchIdToSelectedCaseIdMap() { return switchIdToSelectedCaseIdMap; } /** * Update xforms:switch/xforms:case information with newly selected case id. */ public void updateSwitchInfo(PipelineContext pipelineContext, XFormsContainingDocument containingDocument, ControlsState controlsState, String selectedCaseId) { // Find SwitchXFormsControl final XFormsControl caseXFormsControl = (XFormsControl) controlsState.getIdToControl().get(selectedCaseId); if (caseXFormsControl == null) throw new OXFException("No XFormsControl found for case id '" + selectedCaseId + "'."); final XFormsControl switchXFormsControl = (XFormsControl) caseXFormsControl.getParent(); if (switchXFormsControl == null) throw new OXFException("No SwitchXFormsControl found for case id '" + selectedCaseId + "'."); final String currentSelectedCaseId = (String) getSwitchIdToSelectedCaseIdMap().get(switchXFormsControl.getEffectiveId()); if (!selectedCaseId.equals(currentSelectedCaseId)) { // A new selection occurred on this switch // "This action adjusts all selected attributes on the affected cases to reflect the // new state, and then performs the following:" getSwitchIdToSelectedCaseIdMap().put(switchXFormsControl.getEffectiveId(), selectedCaseId); // "1. Dispatching an xforms-deselect event to the currently selected case." containingDocument.dispatchEvent(pipelineContext, new XFormsDeselectEvent((XFormsEventTarget) controlsState.getIdToControl().get(currentSelectedCaseId))); // "2. Dispatching an xform-select event to the case to be selected." containingDocument.dispatchEvent(pipelineContext, new XFormsSelectEvent((XFormsEventTarget) controlsState.getIdToControl().get(selectedCaseId))); } } /** * Update switch info state for the given case id. */ public void initializeState(String caseId, ControlsState controlsState, boolean visible) { // Find SwitchXFormsControl final XFormsControl caseControl = (XFormsControl) controlsState.getIdToControl().get(caseId); if (caseControl == null) throw new OXFException("No XFormsControl found for case id '" + caseId + "'."); final XFormsControl switchControl = (XFormsControl) caseControl.getParent(); if (switchControl == null) throw new OXFException("No XFormsSwitchControl found for case id '" + caseId + "'."); // Update currently selected case id if (visible) { getSwitchIdToSelectedCaseIdMap().put(switchControl.getEffectiveId(), caseId); } } } /** * Represents the state of dialogs. */ public static class DialogState { private Map dialogIdToVisibleMap; public DialogState(Map dialogIdToVisibleMap) { this.dialogIdToVisibleMap = dialogIdToVisibleMap; } public Map getDialogIdToVisibleMap() { return dialogIdToVisibleMap; } public void showHide(String dialogId, boolean show) { dialogIdToVisibleMap.put(dialogId, Boolean.valueOf(show)); } } /** * Represents the state of a tree of XForms controls. */ public static class ControlsState { private List children; private Map idsToXFormsControls; private Map defaultRepeatIdToIndex; private Map repeatIdToIndex; private Map effectiveRepeatIdToIterations; private Map switchIdToSelectedCaseIdMap; private Map dialogIdToVisibleMap; private boolean hasRepeat; private boolean hasUpload; private boolean dirty; private Map eventsToDispatch; public ControlsState() { } public boolean isDirty() { return dirty; } public void markDirty() { this.dirty = true; } public Map getEventsToDispatch() { return eventsToDispatch; } public void setEventsToDispatch(Map eventsToDispatch) { this.eventsToDispatch = eventsToDispatch; } public void setChildren(List children) { this.children = children; } public void setIdsToXFormsControls(Map idsToXFormsControls) { this.idsToXFormsControls = idsToXFormsControls; } public Map getDefaultRepeatIdToIndex() { return defaultRepeatIdToIndex; } public void setDefaultRepeatIndex(String controlId, int index) { if (defaultRepeatIdToIndex == null) defaultRepeatIdToIndex = new HashMap(); defaultRepeatIdToIndex.put(controlId, new Integer(index)); } public void updateRepeatIndex(String controlId, int index) { if (controlId.indexOf(XFormsConstants.REPEAT_HIERARCHY_SEPARATOR_1) != -1) throw new OXFException("Invalid repeat id provided: " + controlId); if (repeatIdToIndex == null) repeatIdToIndex = new HashMap(defaultRepeatIdToIndex); repeatIdToIndex.put(controlId, new Integer(index)); } public void setRepeatIdToIndex(Map repeatIdToIndex) { this.repeatIdToIndex = new HashMap(repeatIdToIndex); } public void setRepeatIterations(String effectiveControlId, int iterations) { if (effectiveRepeatIdToIterations == null) effectiveRepeatIdToIterations = new HashMap(); effectiveRepeatIdToIterations.put(effectiveControlId, new Integer(iterations)); } public List getChildren() { return children; } public Map getIdToControl() { return idsToXFormsControls; } public Map getRepeatIdToIndex() { if (repeatIdToIndex == null){ if (defaultRepeatIdToIndex != null) repeatIdToIndex = new HashMap(defaultRepeatIdToIndex); else // In this case there is no repeat return Collections.EMPTY_MAP; } return repeatIdToIndex; } public Map getEffectiveRepeatIdToIterations() { return effectiveRepeatIdToIterations; } public Map getSwitchIdToSelectedCaseIdMap() { return switchIdToSelectedCaseIdMap; } public void setSwitchIdToSelectedCaseIdMap(Map switchIdToSelectedCaseIdMap) { this.switchIdToSelectedCaseIdMap = switchIdToSelectedCaseIdMap; } public Map getDialogIdToVisibleMap() { return dialogIdToVisibleMap; } public void setDialogIdToVisibleMap(Map dialogIdToVisibleMap) { this.dialogIdToVisibleMap = dialogIdToVisibleMap; } public boolean isHasRepeat() { return hasRepeat; } public void setHasRepeat(boolean hasRepeat) { this.hasRepeat = hasRepeat; } public boolean isHasUpload() { return hasUpload; } public void setHasUpload(boolean hasUpload) { this.hasUpload = hasUpload; } /** * Return the list of repeat ids descendent of a given repeat id, null if none. */ public List getNestedRepeatIds(XFormsControls xformsControls, final String repeatId) { final List result = new ArrayList(); xformsControls.visitAllControlStatic(new ControlElementVisitorListener() { private boolean found; public boolean startVisitControl(Element controlElement, String effectiveControlId) { if (controlElement.getName().equals("repeat")) { if (!found) { // Not found yet if (repeatId.equals(controlElement.attributeValue("id"))) found = true; } else { // We are within the searched repeat id result.add(controlElement.attributeValue("id")); } } return true; } public boolean endVisitControl(Element controlElement, String effectiveControlId) { if (found) { if (repeatId.equals(controlElement.attributeValue("id"))) found = false; } return true; } public void startRepeatIteration(int iteration) { } public void endRepeatIteration(int iteration) { } }); return result; } /** * Return a map of repeat ids -> RepeatXFormsControl objects, following the branches of the * current indexes of the repeat elements. */ public Map getRepeatIdToRepeatXFormsControl() { final Map result = new HashMap(); visitRepeatHierarchy(result); return result; } private void visitRepeatHierarchy(Map result) { visitRepeatHierarchy(result, this.children); } private void visitRepeatHierarchy(Map result, List children) { for (Iterator i = children.iterator(); i.hasNext();) { final XFormsControl currentXFormsControl = (XFormsControl) i.next(); if (currentXFormsControl instanceof XFormsRepeatControl) { final XFormsRepeatControl currentRepeatXFormsControl = (XFormsRepeatControl) currentXFormsControl; final String repeatId = currentRepeatXFormsControl.getRepeatId(); final int index = ((Integer) getRepeatIdToIndex().get(repeatId)).intValue(); result.put(repeatId, currentXFormsControl); if (index > 0) { final List newChildren = currentXFormsControl.getChildren(); if (newChildren != null && newChildren.size() > 0) visitRepeatHierarchy(result, Collections.singletonList(newChildren.get(index - 1))); } } else { final List newChildren = currentXFormsControl.getChildren(); if (newChildren != null) visitRepeatHierarchy(result, newChildren); } } } /** * Visit all the XFormsControl elements by following the current repeat indexes and setting * current bindings. */ public void visitControlsFollowRepeats(PipelineContext pipelineContext, XFormsControls xformsControls, XFormsControlVisitorListener xformsControlVisitorListener) { // Don't iterate if we don't have controls if (this.children == null) return; xformsControls.resetBindingContext(); visitControlsFollowRepeats(pipelineContext, xformsControls, this.children, xformsControlVisitorListener); } private void visitControlsFollowRepeats(PipelineContext pipelineContext, XFormsControls xformsControls, List children, XFormsControlVisitorListener xformsControlVisitorListener) { for (Iterator i = children.iterator(); i.hasNext();) { final XFormsControl currentXFormsControl = (XFormsControl) i.next(); xformsControls.pushBinding(pipelineContext, currentXFormsControl); xformsControlVisitorListener.startVisitControl(currentXFormsControl); { if (currentXFormsControl instanceof XFormsRepeatControl) { final XFormsRepeatControl currentRepeatXFormsControl = (XFormsRepeatControl) currentXFormsControl; final String repeatId = currentRepeatXFormsControl.getRepeatId(); final int index = ((Integer) getRepeatIdToIndex().get(repeatId)).intValue(); if (index > 0) { final List newChildren = currentXFormsControl.getChildren(); if (newChildren != null && newChildren.size() > 0) visitControlsFollowRepeats(pipelineContext, xformsControls, Collections.singletonList(newChildren.get(index - 1)), xformsControlVisitorListener); } } else { final List newChildren = currentXFormsControl.getChildren(); if (newChildren != null) visitControlsFollowRepeats(pipelineContext, xformsControls, newChildren, xformsControlVisitorListener); } } xformsControlVisitorListener.endVisitControl(currentXFormsControl); xformsControls.popBinding(); } } /** * Find an effective control id based on a control id, following the branches of the * current indexes of the repeat elements. */ public String findEffectiveControlId(String controlId) { // Don't iterate if we don't have controls if (this.children == null) return null; return findEffectiveControlId(controlId, this.children); } private String findEffectiveControlId(String controlId, List children) { for (Iterator i = children.iterator(); i.hasNext();) { final XFormsControl currentXFormsControl = (XFormsControl) i.next(); final String originalControlId = currentXFormsControl.getOriginalId(); if (controlId.equals(originalControlId)) { return currentXFormsControl.getEffectiveId(); } else if (currentXFormsControl instanceof XFormsRepeatControl) { final XFormsRepeatControl currentRepeatXFormsControl = (XFormsRepeatControl) currentXFormsControl; final String repeatId = currentRepeatXFormsControl.getRepeatId(); final int index = ((Integer) getRepeatIdToIndex().get(repeatId)).intValue(); if (index > 0) { final List newChildren = currentXFormsControl.getChildren(); if (newChildren != null && newChildren.size() > 0) { final String result = findEffectiveControlId(controlId, Collections.singletonList(newChildren.get(index - 1))); if (result != null) return result; } } } else { final List newChildren = currentXFormsControl.getChildren(); if (newChildren != null) { final String result = findEffectiveControlId(controlId, newChildren); if (result != null) return result; } } } // Not found return null; } } /** * Analyze differences of relevance for controls getting bound and unbound to nodes. */ private void findSpecialRelevanceChanges(List state1, List state2, Map[] eventsToDispatch) { // Trivial case if (state1 == null && state2 == null) return; // Both lists must have the same size if present; state1 can be null if (state1 != null && state2 != null && state1.size() != state2.size()) { throw new IllegalStateException("Illegal state when comparing controls."); } final Iterator j = (state1 == null) ? null : state1.iterator(); final Iterator i = (state2 == null) ? null : state2.iterator(); final Iterator leadingIterator = (i != null) ? i : j; while (leadingIterator.hasNext()) { final XFormsControl xformsControl1 = (state1 == null) ? null : (XFormsControl) j.next(); final XFormsControl xformsControl2 = (state2 == null) ? null : (XFormsControl) i.next(); final XFormsControl leadingControl = (xformsControl2 != null) ? xformsControl2 : xformsControl1; // never null // 1: Check current control if (!(leadingControl instanceof XFormsRepeatControl)) { // xforms:repeat doesn't need to be handled independently, iterations do it String foundControlId = null; XFormsControl targetControl = null; int eventType = 0; if (xformsControl1 != null && xformsControl2 != null) { final NodeInfo boundNode1 = xformsControl1.getBoundNode(); final NodeInfo boundNode2 = xformsControl2.getBoundNode(); if (boundNode1 != null && xformsControl1.isRelevant() && boundNode2 == null) { // A control was bound to a node and relevant, but has become no longer bound to a node foundControlId = xformsControl2.getEffectiveId(); eventType = XFormsModel.EventSchedule.RELEVANT_BINDING; } else if (boundNode1 == null && boundNode2 != null && xformsControl2.isRelevant()) { // A control was not bound to a node, but has now become bound and relevant foundControlId = xformsControl2.getEffectiveId(); eventType = XFormsModel.EventSchedule.RELEVANT_BINDING; } else if (boundNode1 != null && boundNode2 != null && !boundNode1.isSameNodeInfo(boundNode2)) { // The control is now bound to a different node // In this case, we schedule the control to dispatch all the events // NOTE: This is not really proper according to the spec, but it does help applications to // force dispatching in such cases foundControlId = xformsControl2.getEffectiveId(); eventType = XFormsModel.EventSchedule.ALL; } } else if (xformsControl2 != null) { final NodeInfo boundNode2 = xformsControl2.getBoundNode(); if (boundNode2 != null && xformsControl2.isRelevant()) { // A control was not bound to a node, but has now become bound and relevant foundControlId = xformsControl2.getEffectiveId(); eventType = XFormsModel.EventSchedule.RELEVANT_BINDING; } } else if (xformsControl1 != null) { final NodeInfo boundNode1 = xformsControl1.getBoundNode(); if (boundNode1 != null && xformsControl1.isRelevant()) { // A control was bound to a node and relevant, but has become no longer bound to a node foundControlId = xformsControl1.getEffectiveId(); // NOTE: This is the only case where we must dispatch the event to an obsolete control targetControl = xformsControl1; eventType = XFormsModel.EventSchedule.RELEVANT_BINDING; } } // Remember that we need to dispatch information about this control if (foundControlId != null) { if (eventsToDispatch[0] == null) eventsToDispatch[0] = new HashMap(); eventsToDispatch[0].put(foundControlId, new XFormsModel.EventSchedule(foundControlId, eventType, targetControl)); } } // 2: Check children if any if (XFormsControls.isGroupingControl(leadingControl.getName()) || leadingControl instanceof RepeatIterationControl) { final List children1 = (xformsControl1 == null) ? null : xformsControl1.getChildren(); final List children2 = (xformsControl2 == null) ? null : xformsControl2.getChildren(); final int size1 = children1 == null ? 0 : children1.size(); final int size2 = children2 == null ? 0 : children2.size(); if (leadingControl instanceof XFormsRepeatControl) { // Special case of repeat update if (size1 == size2) { // No add or remove of children findSpecialRelevanceChanges(children1, children2, eventsToDispatch); } else if (size2 > size1) { // Size has grown // Diff the common subset findSpecialRelevanceChanges(children1, children2.subList(0, size1), eventsToDispatch); // Issue new values for new iterations findSpecialRelevanceChanges(null, children2.subList(size1, size2), eventsToDispatch); } else if (size2 < size1) { // Size has shrunk // Diff the common subset findSpecialRelevanceChanges(children1.subList(0, size2), children2, eventsToDispatch); // Issue new values for new iterations findSpecialRelevanceChanges(children1.subList(size2, size1), null, eventsToDispatch); } } else { // Other grouping controls findSpecialRelevanceChanges(size1 == 0 ? null : children1, size2 == 0 ? null : children2, eventsToDispatch); } } } } }
package com.rtg.reader; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import com.rtg.mode.DNA; import com.rtg.mode.DNAFastaSymbolTable; import com.rtg.mode.Protein; import com.rtg.mode.ProteinFastaSymbolTable; import com.rtg.mode.SequenceType; import com.rtg.reader.FastqSequenceDataSource.FastQScoreType; import com.rtg.util.StringUtils; import com.rtg.util.diagnostic.Diagnostic; import com.rtg.util.diagnostic.DiagnosticEvent; import com.rtg.util.diagnostic.DiagnosticListener; import com.rtg.util.diagnostic.ErrorType; import com.rtg.util.diagnostic.NoTalkbackSlimException; import com.rtg.util.diagnostic.SlimException; import com.rtg.util.diagnostic.WarningEvent; import com.rtg.util.diagnostic.WarningType; import com.rtg.util.intervals.LongRange; import com.rtg.util.test.FileHelper; import junit.framework.Assert; import junit.framework.TestCase; public class SequencesWriterTest extends TestCase { private File mDir = null; @Override public void setUp() throws Exception { mDir = FileHelper.createTempDirectory(); Diagnostic.setLogStream(); } @Override public void tearDown() { FileHelper.deleteAll(mDir); mDir = null; } public void testLabels() throws Exception { final FastaSequenceDataSource ds = getDataSource(">\u007fharrred\nactg"); final SequencesWriter sw = new SequencesWriter(ds, mDir, 20, PrereadType.UNKNOWN, false); //assertEquals(20, sw.getSizeLimit()); try { sw.processSequences(); fail(); } catch (NoTalkbackSlimException e) { assertEquals(ErrorType.BAD_CHARS_NAME, e.getErrorType()); assertTrue(e.getMessage().contains("\u007fharrred")); } } private static boolean sHandled = false; private static void setHandled() { sHandled = true; } public void testEmptySequence() throws Exception { final FastaSequenceDataSource ds = getDataSource(""); final SequencesWriter sw = new SequencesWriter(ds, mDir, 20, PrereadType.UNKNOWN, false); final DiagnosticListener dl = new DiagnosticListener() { @Override public void handleDiagnosticEvent(final DiagnosticEvent<?> event) { if (sHandled) { Assert.fail(); } Assert.assertTrue(event instanceof WarningEvent); Assert.assertEquals(WarningType.NOT_FASTA_FILE, event.getType()); setHandled(); } @Override public void close() { } }; Diagnostic.addListener(dl); try { sw.processSequences(); } finally { Diagnostic.removeListener(dl); } assertTrue(sHandled); } public void testNoSequence() throws Exception { final DiagnosticListener dl = new DiagnosticListener() { int mCount = -1; @Override public void handleDiagnosticEvent(final DiagnosticEvent<?> event) { if (event.getType() != WarningType.INFO_WARNING) { switch (++mCount) { case 0: Assert.assertEquals(WarningType.NO_SEQUENCE, event.getType()); Assert.assertEquals("The sequence \"rrred\" has no data.", event.getMessage()); break; case 1: case 2: Assert.assertEquals(WarningType.NO_NAME, event.getType()); Assert.assertEquals("Sequence with no name was assigned name \"Unnamed_sequence_" + (mCount - 1) + "\".", event.getMessage()); break; case 3: Assert.assertEquals(WarningType.BAD_CHAR_WARNINGS, event.getType()); break; default: fail(); break; } } } @Override public void close() { } }; Diagnostic.addListener(dl); try { final FastaSequenceDataSource ds = getDataSource(">rrred\n>\nactg\n>\ntgac"); final SequencesWriter sw = new SequencesWriter(ds, mDir, 20, PrereadType.UNKNOWN, false); sw.processSequences(); final SequencesReader dsr = SequencesReaderFactory.createDefaultSequencesReader(mDir); assertEquals(3, dsr.numberSequences()); //blank sequence still makes a sequence - so that paired end data still matches up } finally { Diagnostic.removeListener(dl); } } public void testErrors() throws Exception { try { new SequencesWriter(null, null, 20, PrereadType.UNKNOWN, false); fail("Should throw NullPointerException"); } catch (final NullPointerException e) { assertTrue(e.getMessage(), e.getMessage().contains("Provided data source was null.")); } final String seq = ">123456789012345678901\nacgtgtgtgtcttagggctcactggtcatgca\n>bob the buuilder\ntagttcagcatcgatca\n>hobos r us\naccccaccccacaaacccaa"; FastaSequenceDataSource ds = getDataSource(seq); try { try { new SequencesWriter(ds, null, 20, PrereadType.UNKNOWN, false); fail("Should throw NullPointerException"); } catch (final NullPointerException e) { } final File f = FileHelper.createTempFile(); try { new SequencesWriter(ds, f, 20, PrereadType.UNKNOWN, false); fail("Should throw SlimException"); } catch (final SlimException e) { } finally { assertTrue(f.delete()); } try { new SequencesWriter(ds, mDir, 19, PrereadType.UNKNOWN, false).processSequences(); fail("Should throw IllegalArgumentException"); } catch (final IllegalArgumentException e) { assertEquals("Size limit of: " + 19 + " is not within bounds of: " + SdfWriter.MIN_SIZE_LIMIT + " and " + SdfWriter.MAX_SIZE_LIMIT, e.getMessage()); } ds = getDataSource(seq); long limit = 1024L * 1024 * 1024 * 1024 + 1; try { new SequencesWriter(ds, mDir, limit, PrereadType.UNKNOWN, false).processSequences(); fail("Should throw IllegalArgumentException"); } catch (final IllegalArgumentException e) { assertEquals("Size limit of: " + limit + " is not within bounds of: " + SdfWriter.MIN_SIZE_LIMIT + " and " + SdfWriter.MAX_SIZE_LIMIT, e.getMessage()); } ds = getDataSource(seq); limit = (long) Integer.MAX_VALUE + 1; try { final SequencesWriter sw = new SequencesWriter(ds, mDir, limit, PrereadType.UNKNOWN, false); sw.processSequences(); fail("Should throw IllegalArgumentException"); } catch (final IllegalArgumentException e) { assertEquals("Currently only support int pointers", e.getMessage()); } } finally { ds.close(); } } private InputStream createStream(final String data) { return new ByteArrayInputStream(data.getBytes()); } public void testPointerRoll() throws IOException { final ArrayList<InputStream> al = new ArrayList<>(); al.add(createStream(">1\na\n>2\nc\n>3\ng\n>4\nt\n>5\na\n>6\nc\n>7\ng\n>8\nt\n")); final FastaSequenceDataSource ds = new FastaSequenceDataSource(al, new DNAFastaSymbolTable()); final SequencesWriter sw = new SequencesWriter(ds, mDir, 20, PrereadType.UNKNOWN, false); assertEquals(0, sw.getTotalLength()); assertEquals(Long.MAX_VALUE, sw.getMinLength()); assertEquals(Long.MIN_VALUE, sw.getMaxLength()); assertEquals(0, sw.getNumberOfSequences()); //assertEquals(0, sw.getChunkNumber()); //doesn't use chunks (progress related) assertEquals(20, sw.getSizeLimit()); sw.processSequences(); try (SequencesReader dsr = SequencesReaderFactory.createDefaultSequencesReader(mDir)) { //dsr.globalIntegrity(); assertEquals(mDir, dsr.path()); final SequencesIterator it = dsr.iterator(); //assertTrue(dsr.nextSequence()); final String[] labels = {"1", "2", "3", "4", "5", "6", "7", "8"}; final byte[][] expected = {{1}, {2}, {3}, {4}, {1}, {2}, {3}, {4}}; for (int i = 0; i < expected.length; i++) { assertTrue(it.nextSequence()); assertEquals(labels[i], it.currentName()); checkEquals(it, expected[i]); } assertTrue(!it.nextSequence()); } final File[] files = mDir.listFiles(new FilenameFilter() { @Override public boolean accept(final File dir, final String name) { if (name.startsWith(SdfFileUtils.SEQUENCE_POINTER_FILENAME)) { return true; } if (name.startsWith(SdfFileUtils.LABEL_POINTER_FILENAME)) { return true; } return false; } }); assertNotNull(files); Arrays.sort(files); assertEquals(4, files.length); assertEquals(20, files[0].length()); assertEquals(12, files[1].length()); assertEquals(20, files[2].length()); assertEquals(21, files[3].length()); } public void testHistogram() throws IOException { final String seq = "" + ">1" + StringUtils.LS + "a" + StringUtils.LS + ">2" + StringUtils.LS + "c" + StringUtils.LS + ">3" + StringUtils.LS + "g" + StringUtils.LS + ">4" + StringUtils.LS + "t" + StringUtils.LS + ">5" + StringUtils.LS + "a" + StringUtils.LS + ">6" + StringUtils.LS + "c" + StringUtils.LS + ">7" + StringUtils.LS + "g" + StringUtils.LS + ">8" + StringUtils.LS + "t" + StringUtils.LS; final SequencesWriter sw = new SequencesWriter(getDataSource(seq), mDir, 20, PrereadType.UNKNOWN, false); sw.processSequences(); try (SequencesReader dsr = SequencesReaderFactory.createDefaultSequencesReader(mDir)) { final long[] histogram = dsr.histogram(); assertEquals(8, histogram[0]); for (int i = 1; i < histogram.length; i++) { assertEquals(0, histogram[i]); } } } public void testHistogram2() throws IOException { final String seq = "" + ">a=1" + StringUtils.LS + "acgt" + StringUtils.LS + ">b=1" + StringUtils.LS + "ncgt" + StringUtils.LS + ">c=1" + StringUtils.LS + "antc" + StringUtils.LS + ">d=1" + StringUtils.LS + "acnt" + StringUtils.LS + ">e=1" + StringUtils.LS + "acgn" + StringUtils.LS + ">f=1" + StringUtils.LS + "nngt" + StringUtils.LS + ">g=1" + StringUtils.LS + "annt" + StringUtils.LS + ">h=1" + StringUtils.LS + "acnn" + StringUtils.LS + ">i=1" + StringUtils.LS + "nnnt" + StringUtils.LS + ">j=1" + StringUtils.LS + "annn" + StringUtils.LS + ">k=1" + StringUtils.LS + "nnnn" + StringUtils.LS; final SequencesWriter sw = new SequencesWriter(getDataSource(seq), mDir, 20, PrereadType.UNKNOWN, false); sw.processSequences(); try (SequencesReader dsr = SequencesReaderFactory.createDefaultSequencesReader(mDir)) { final long[] histogram = dsr.histogram(); assertEquals(1, histogram[0]); assertEquals(4, histogram[1]); assertEquals(3, histogram[2]); assertEquals(2, histogram[3]); assertEquals(1, histogram[4]); assertEquals(10, dsr.nBlockCount()); assertEquals(4, dsr.longestNBlock()); } } public void testHistogram3() throws Exception { final String seq = "" + "@12345" + StringUtils.LS + "acgtgt" + StringUtils.LS + "+12345" + StringUtils.LS + "IIIIII" + StringUtils.LS; final ArrayList<InputStream> al = new ArrayList<>(); al.add(createStream(seq)); final FastqSequenceDataSource ds = new FastqSequenceDataSource(al, FastQScoreType.PHRED); final SequencesWriter sw = new SequencesWriter(ds, mDir, 20, PrereadType.UNKNOWN, false); sw.processSequences(); try (SequencesReader dsr = SequencesReaderFactory.createDefaultSequencesReader(mDir)) { final SequencesIterator it = dsr.iterator(); assertTrue(it.nextSequence()); assertEquals("12345", it.currentName()); final byte[] q = new byte[6]; it.readCurrentQuality(q); assertTrue(Arrays.equals(new byte[]{'I' - 33, 'I' - 33, 'I' - 33, 'I' - 33, 'I' - 33, 'I' - 33}, q)); for (int i = 0; i < 6; i++) { assertEquals(1.0E-4, dsr.positionQualityAverage()[i]); } assertEquals(0.0, dsr.positionQualityAverage()[7]); } } public static void checkEquals(final SequencesIterator r, final byte[] expected) throws IOException { final byte[] t = new byte[expected.length]; assertEquals(expected.length, r.readCurrent(t)); assertTrue(Arrays.equals(expected, t)); } public static void checkQualityEquals(final SequencesIterator r, final byte[] expected) throws IOException { final byte[] t = new byte[expected.length]; assertEquals(expected.length, r.readCurrentQuality(t)); assertTrue(Arrays.equals(expected, t)); } public void testRoll() throws Exception { //create data source //mDir = new File("/home2/david/cgltest"); final ArrayList<InputStream> al = new ArrayList<>(); al.add(createStream(">123456789012345678901\nacgtgtgtgtcttagggctcactggtcatgca\n>bob the buuilder\ntagttcagcatcgatca\n>hobos r us\naccccaccccacaaacccaa")); final FastaSequenceDataSource ds = new FastaSequenceDataSource(al, new DNAFastaSymbolTable()); final SequencesWriter sw = new SequencesWriter(ds, mDir, 20, PrereadType.UNKNOWN, false); sw.processSequences(); assertEquals(3, sw.getNumberOfSequences()); assertEquals(0, sw.getNumberOfExcludedSequences()); assertEquals(17, sw.getMinLength()); assertEquals(32, sw.getMaxLength()); assertEquals(69, sw.getTotalLength()); //expected files: //main index //seqdata0, size 20 //seqdata1, size 20 //seqdata2, size 20 //seqdata3, size 9 //seqpointer0, size 4 //seqpointer1, size 4 //seqpointer2, size 4 //seqpointer3, size 0 //namedata0, size 5 //namedata1, size 17 //namedata2, size 11 //namepointer0, size 4 //namepointer1, size 4, //namepointer2, size 4 try (SequencesReader dsr = SequencesReaderFactory.createDefaultSequencesReader(mDir)) { assertEquals(mDir, dsr.path()); final SequencesIterator it = dsr.iterator(); assertTrue(it.nextSequence()); assertEquals("1234567890123456789", it.currentName()); assertEquals(32, it.currentLength()); checkEquals(it, new byte[]{1, 2, 3, 4, 3, 4, 3, 4, 3, 4, 2, 4, 4, 1, 3, 3, 3, 2, 4, 2, 1, 2, 4, 3, 3, 4, 2, 1, 4, 3, 2, 1}); assertTrue(it.nextSequence()); assertEquals("bob", it.currentName()); assertEquals(17, it.currentLength()); checkEquals(it, new byte[]{4, 1, 3, 4, 4, 2, 1, 3, 2, 1, 4, 2, 3, 1, 4, 2, 1}); assertTrue(it.nextSequence()); assertEquals("hobos", it.currentName()); assertEquals(20, it.currentLength()); checkEquals(it, new byte[]{1, 2, 2, 2, 2, 1, 2, 2, 2, 2, 1, 2, 1, 1, 1, 2, 2, 2, 1, 1}); } } public void testRollWithQuality() throws Exception { checkRollWithQuality(false); checkRollWithQuality(true); } public void checkRollWithQuality(boolean compress) throws Exception { //create data source //mDir = new File("/home2/david/cgltest"); createQualityData(compress); //expected files: //main index //seqdata0, size 20 //seqdata1, size 20 //seqdata2, size 20 //seqdata3, size 9 //qualdata0, size 20 //qualdata1, size 20 //qualdata2, size 20 //qualdata3, size 9 //seqpointer0, size 4 //seqpointer1, size 4 //seqpointer2, size 4 //seqpointer3, size 0 //namedata0, size 0 //namedata1, size 20 //namedata2, size 10 //namepointer0, size 4 //namepointer1, size 4, //namepointer2, size 4 if (!compress) { assertEquals(20, SdfFileUtils.sequenceDataFile(mDir, 0).length()); assertEquals(20, SdfFileUtils.sequenceDataFile(mDir, 1).length()); assertEquals(20, SdfFileUtils.sequenceDataFile(mDir, 2).length()); assertEquals(9, SdfFileUtils.sequenceDataFile(mDir, 3).length()); assertEquals(20, SdfFileUtils.qualityDataFile(mDir, 0).length()); assertEquals(20, SdfFileUtils.qualityDataFile(mDir, 1).length()); assertEquals(20, SdfFileUtils.qualityDataFile(mDir, 2).length()); assertEquals(9, SdfFileUtils.qualityDataFile(mDir, 3).length()); assertEquals(6, SdfFileUtils.sequencePointerFile(mDir, 0).length()); assertEquals(6, SdfFileUtils.sequencePointerFile(mDir, 1).length()); assertEquals(6, SdfFileUtils.sequencePointerFile(mDir, 2).length()); assertEquals(2, SdfFileUtils.sequencePointerFile(mDir, 3).length()); assertEquals(0, SdfFileUtils.labelDataFile(mDir, 0).length()); //tries to fit in current but cannot assertEquals(20, SdfFileUtils.labelDataFile(mDir, 1).length()); //cannot fit in brand new so truncates at max file size assertEquals(12, SdfFileUtils.labelDataFile(mDir, 2).length()); //2nd and 3rd written normally assertEquals(0, SdfFileUtils.labelPointerFile(mDir, 0).length()); assertEquals(4, SdfFileUtils.labelPointerFile(mDir, 1).length()); assertEquals(8, SdfFileUtils.labelPointerFile(mDir, 2).length()); } try (SequencesReader dsr = SequencesReaderFactory.createDefaultSequencesReader(mDir)) { final SequencesIterator it = dsr.iterator(); assertTrue(dsr.hasQualityData()); assertEquals(mDir, dsr.path()); assertTrue(it.nextSequence()); assertEquals("1234567890123456789", it.currentName()); assertEquals(32, it.currentLength()); checkEquals(it, new byte[]{1, 2, 3, 4, 3, 4, 3, 4, 3, 4, 2, 4, 4, 1, 3, 3, 3, 2, 4, 2, 1, 2, 4, 3, 3, 4, 2, 1, 4, 3, 2, 1}); byte[] qualExp = new byte[32]; for (int i = 0; i < 32; i++) { final char c = "!!ASDFFSAFASHSKFSDIUR<<SA><>S<<<".charAt(i); qualExp[i] = (byte) (c - '!'); if (qualExp[i] > 63) { qualExp[i] = 63; } } checkQualityEquals(it, qualExp); assertTrue(it.nextSequence()); assertEquals("bob", it.currentName()); assertEquals(17, it.currentLength()); qualExp = new byte[17]; for (int i = 0; i < 17; i++) { final char c = "!ADSFG<<{()))[[[]".charAt(i); qualExp[i] = (byte) (c - '!'); if (qualExp[i] > 63) { qualExp[i] = 63; } } checkEquals(it, new byte[]{4, 1, 3, 4, 4, 2, 1, 3, 2, 1, 4, 2, 3, 1, 4, 2, 1}); checkQualityEquals(it, qualExp); assertTrue(it.nextSequence()); assertEquals("hobos-r", it.currentName()); assertEquals(20, it.currentLength()); qualExp = new byte[20]; for (int i = 0; i < 20; i++) { final char c = "ADSFAD[[<<<><<[[;;FS".charAt(i); qualExp[i] = (byte) (c - '!'); if (qualExp[i] > 63) { qualExp[i] = 63; } } checkEquals(it, new byte[]{1, 2, 2, 2, 2, 1, 2, 2, 2, 2, 1, 2, 1, 1, 1, 2, 2, 2, 1, 1}); checkQualityEquals(it, qualExp); } } private void createQualityData(boolean compress) throws IOException { final ArrayList<InputStream> al = new ArrayList<>(); al.add(createStream("@123456789012345678901\nacgtgtgtgtcttagggctcactggtcatgca\n" + "+123456789012345678901\n!!ASDFFSAFASHSKFSDIUR<<SA><>S<<<\n" + "@bob the buuilder\ntagttcagcatcgatca\n" + "+bob the buuilder\n!ADSFG<<{()))[[[]\n" + "@hobos-r us\naccccaccccacaaacccaa\n" + "+hobos-r us\nADSFAD[[<<<><<[[;;FS\n")); final FastqSequenceDataSource ds = new FastqSequenceDataSource(al, FastQScoreType.PHRED); final SequencesWriter sw = new SequencesWriter(ds, mDir, 20, PrereadType.SOLEXA, compress); sw.processSequences(); } /*private void createQualDataCG() { InputStream cc = new ArrayList<>(); cc.add(createStream("GTTTC" + StringUtils.LS); FastqSequenceDataSource ds = new FastqSequenceDataSource(al, false); // set mDir SequencesWriter sw = new SequencesWriter(ds, mDir, 20, InputFormat.SOLEXA); sw.processSequences(); }*/ public void testWrite() throws Exception { //create data source final ArrayList<InputStream> al = new ArrayList<>(); al.add(createStream(">test\nac\n tg\ntnGh\n\n\t \n>xxbaddog\r\nFFF\n>test2\r\nATGC")); final FastaSequenceDataSource ds = new FastaSequenceDataSource(al, new DNAFastaSymbolTable()); final ArrayList<String> sup = new ArrayList<>(); sup.add("baddog"); final SequencesWriter sw = new SequencesWriter(ds, mDir, 1024, sup, PrereadType.UNKNOWN, false, null); assertEquals(0, sw.getNumberOfExcludedSequences()); sw.processSequences(); //check files try (DataInputStream dis = new DataInputStream(new FileInputStream(new File(mDir, SdfFileUtils.INDEX_FILENAME)))) { assertEquals(13, dis.readLong()); assertEquals(1024, dis.readLong()); assertEquals(SequenceType.DNA.ordinal(), dis.readInt()); assertEquals(1, sw.getNumberOfExcludedSequences()); } try (FileInputStream fis = new FileInputStream(new File(mDir, SdfFileUtils.SEQUENCE_DATA_FILENAME + "0"))) { final DNA[] expected = {DNA.A, DNA.C, DNA.T, DNA.G, DNA.T, DNA.N, DNA.G, DNA.N, DNA.A, DNA.T, DNA.G, DNA.C}; int i = 0; int d; while ((d = fis.read()) != -1 && i < expected.length) { assertEquals("Index: " + i, expected[i++].ordinal(), d); } assertEquals(expected.length, i); } try (DataInputStream dis2 = new DataInputStream(new FileInputStream(new File(mDir, SdfFileUtils.SEQUENCE_POINTER_FILENAME + "0")))) { dis2.read(); assertEquals(0, dis2.readInt()); dis2.read(); assertEquals(8, dis2.readInt()); try { dis2.readInt(); fail("Should be eof"); } catch (final EOFException e) { } } //This tests it is read correctly, of course this relies on the fact that the reader works :/ try (SequencesReader dsr = SequencesReaderFactory.createDefaultSequencesReader(mDir)) { final SequencesIterator it = dsr.iterator(); assertEquals(12, dsr.totalLength()); assertEquals(8, dsr.maxLength()); assertEquals(4, dsr.minLength()); assertFalse(dsr.hasQualityData()); assertFalse(dsr.hasQualityData()); assertTrue(it.nextSequence()); assertTrue(it.nextSequence()); assertFalse(it.nextSequence()); assertFalse(dsr.hasQualityData()); } } public void testWriteProtein() throws Exception { //create data source final ArrayList<InputStream> al = new ArrayList<>(); al.add(createStream(">test\naH\n tg\ntXGj\n\n\t \n>test2\r\nATGC")); final FastaSequenceDataSource ds = new FastaSequenceDataSource(al, new ProteinFastaSymbolTable()); final SequencesWriter sw = new SequencesWriter(ds, mDir, 1024, PrereadType.UNKNOWN, false); sw.processSequences(); //check files try (DataInputStream dis = new DataInputStream(new FileInputStream(new File(mDir, SdfFileUtils.INDEX_FILENAME)))) { assertEquals(13, dis.readLong()); assertEquals(1024, dis.readLong()); assertEquals(SequenceType.PROTEIN.ordinal(), dis.readInt()); } try (FileInputStream fis = new FileInputStream(new File(mDir, SdfFileUtils.SEQUENCE_DATA_FILENAME + "0"))) { final Protein[] expected = {Protein.A, Protein.H, Protein.T, Protein.G, Protein.T, Protein.X, Protein.G, Protein.X, Protein.A, Protein.T, Protein.G, Protein.C}; int i = 0; int d; while ((d = fis.read()) != -1 && i < expected.length) { assertEquals("Index: " + i, expected[i++].ordinal(), d); } assertEquals(expected.length, i); } try (DataInputStream dis2 = new DataInputStream(new FileInputStream(new File(mDir, SdfFileUtils.SEQUENCE_POINTER_FILENAME + "0")))) { dis2.read(); assertEquals(0, dis2.readInt()); dis2.read(); assertEquals(8, dis2.readInt()); try { dis2.readInt(); fail("Should be eof"); } catch (final EOFException e) { } } } public void testProteinWarning() throws Exception { final FastaSequenceDataSource fsds = getProteinDataSource(">totally_a_protein\nacgttcagtantatcgaattgcagn"); final boolean[] gotWarning = new boolean[1]; final DiagnosticListener dl = new DiagnosticListener() { @Override public void handleDiagnosticEvent(final DiagnosticEvent<?> event) { if (event.getMessage().length() > 0) { assertTrue(event.getType() == WarningType.POSSIBLY_NOT_PROTEIN); gotWarning[0] = true; } } @Override public void close() { } }; Diagnostic.addListener(dl); try { final SequencesWriter sw = new SequencesWriter(fsds, mDir, 10000000, PrereadType.UNKNOWN, false); sw.processSequences(); } finally { Diagnostic.removeListener(dl); } assertTrue(gotWarning[0]); } private FastaSequenceDataSource getDataSource(final String sequence) { final ArrayList<InputStream> al = new ArrayList<>(); al.add(createStream(sequence)); return new FastaSequenceDataSource(al, new DNAFastaSymbolTable()); } private FastaSequenceDataSource getProteinDataSource(final String sequence) { final ArrayList<InputStream> al = new ArrayList<>(); al.add(createStream(sequence)); return new FastaSequenceDataSource(al, new ProteinFastaSymbolTable()); } public void testBadSeqNames() { assertTrue(AbstractSdfWriter.SequenceNameHandler.fixSequenceName("a=b", new StringBuilder())); assertTrue(AbstractSdfWriter.SequenceNameHandler.fixSequenceName("a=", new StringBuilder())); assertFalse(AbstractSdfWriter.SequenceNameHandler.fixSequenceName("=b", new StringBuilder())); assertFalse(AbstractSdfWriter.SequenceNameHandler.fixSequenceName("*b", new StringBuilder())); assertTrue(AbstractSdfWriter.SequenceNameHandler.fixSequenceName("a*b", new StringBuilder())); } public void testBadCharsWarning() throws Exception { final FastaSequenceDataSource fsds = getDataSource(">=1\nacgt\n>=1\nacgt\n>=1\nacgt\n>=1\nacgt\n>=1\nacgt\n>=1\nacgt\n>=1\nacgt\n"); final SequencesWriter sw = new SequencesWriter(fsds, mDir, 10000000, PrereadType.UNKNOWN, false); try { sw.processSequences(); fail(); } catch (NoTalkbackSlimException e) { assertEquals(ErrorType.BAD_CHARS_NAME, e.getErrorType()); assertTrue(e.getMessage().contains("=1")); } } public void testType() throws Exception { createQualityData(false); try (SequencesReader dsr = SequencesReaderFactory.createDefaultSequencesReader(mDir)) { assertEquals(PrereadArm.UNKNOWN, dsr.getArm()); assertEquals(PrereadType.SOLEXA, dsr.getPrereadType()); assertTrue(dsr.getSdfId().available()); } } public void testZeroLengthRead() throws Exception { try (FastaSequenceDataSource fsds = getDataSource(">null\n\n")) { final SequencesWriter sw = new SequencesWriter(fsds, mDir, 10000000, PrereadType.UNKNOWN, false); sw.processSequences(); } SequencesReaderFactory.createDefaultSequencesReader(mDir); try (SequencesReader sr = SequencesReaderFactory.createMemorySequencesReaderCheckEmpty(mDir, true, true, LongRange.NONE)) { assertEquals(1, sr.numberSequences()); assertEquals(0, sr.length(0)); } } public void testTwoZeroLengthReads() throws Exception { try (FastaSequenceDataSource fsds = getDataSource(">null1\n\n>null\n\n")) { final SequencesWriter sw = new SequencesWriter(fsds, mDir, 10000000, PrereadType.UNKNOWN, false); sw.processSequences(); } SequencesReaderFactory.createDefaultSequencesReader(mDir); try (SequencesReader sr = SequencesReaderFactory.createMemorySequencesReaderCheckEmpty(mDir, true, true, LongRange.NONE)) { assertEquals(2, sr.numberSequences()); assertEquals(0, sr.length(0)); assertEquals(0, sr.length(1)); } } private void checkZeroLengthReadWithOtherReadsFirst(final LongRange range) throws Exception { try (FastaSequenceDataSource fsds = getDataSource(">read\nACGT\n>null\n\n")) { final SequencesWriter sw = new SequencesWriter(fsds, mDir, 10000000, PrereadType.UNKNOWN, false); sw.processSequences(); } SequencesReader sr = SequencesReaderFactory.createDefaultSequencesReader(mDir); try { try { assertEquals(2, sr.numberSequences()); final SequencesIterator it = sr.iterator(); it.nextSequence(); assertEquals(4, it.currentLength()); it.nextSequence(); assertEquals(0, it.currentLength()); } finally { sr.close(); } sr = SequencesReaderFactory.createMemorySequencesReaderCheckEmpty(mDir, true, true, range); final SequencesIterator it = sr.iterator(); assertEquals(2, sr.numberSequences()); it.nextSequence(); assertEquals(4, it.currentLength()); it.nextSequence(); assertEquals(0, it.currentLength()); } finally { sr.close(); } } public void testZeroLengthReadWithOtherReadsFirst() throws Exception { checkZeroLengthReadWithOtherReadsFirst(LongRange.NONE); } public void testZeroLengthReadWithOtherReadsFirstNoEnd() throws Exception { checkZeroLengthReadWithOtherReadsFirst(new LongRange(0, LongRange.MISSING)); } public void testZeroLengthReadWithOtherReadsFirstRange() throws Exception { checkZeroLengthReadWithOtherReadsFirst(new LongRange(0, 2)); } public void testZeroLengthReadWithOtherReadsAfter() throws Exception { try (FastaSequenceDataSource fsds = getDataSource(">null\n\n>read\nACGT\n")) { final SequencesWriter sw = new SequencesWriter(fsds, mDir, 10000000, PrereadType.UNKNOWN, false); sw.processSequences(); } SequencesReaderFactory.createDefaultSequencesReader(mDir); try (SequencesReader sr = SequencesReaderFactory.createMemorySequencesReaderCheckEmpty(mDir, true, true, LongRange.NONE)) { assertEquals(2, sr.numberSequences()); final SequencesIterator it = sr.iterator(); it.nextSequence(); assertEquals(0, it.currentLength()); it.nextSequence(); assertEquals(4, it.currentLength()); } } public void testZeroLengthReadWithOtherReadsBeforeAndAfter() throws Exception { try (FastaSequenceDataSource fsds = getDataSource(">read1\nACGTG\n>null\n\n>read\nACGT\n")) { final SequencesWriter sw = new SequencesWriter(fsds, mDir, 10000000, PrereadType.UNKNOWN, false); sw.processSequences(); } SequencesReaderFactory.createDefaultSequencesReader(mDir); try (SequencesReader sr = SequencesReaderFactory.createMemorySequencesReaderCheckEmpty(mDir, true, true, LongRange.NONE)) { assertEquals(3, sr.numberSequences()); final SequencesIterator it = sr.iterator(); it.nextSequence(); assertEquals(5, it.currentLength()); it.nextSequence(); assertEquals(0, it.currentLength()); it.nextSequence(); assertEquals(4, it.currentLength()); } } public void testTrim() throws Exception { final ArrayList<InputStream> al = new ArrayList<>(); al.add(createStream("@123456789012345678901\nacgtgtgtgtcttagggctcactggtcatgca\n" + "+123456789012345678901\n!!ASDFFSAFASHSKFSDIUR<<SA><>S<<<\n" + "@bob the buuilder\ntagttcagcatcgatca\n" + "+bob the buuilder\n!ADSFG<<{()))[[[]\n" + "@hobos-r us\naccccaccccacaaacccaa\n" + "+hobos-r us\nADSFAD[[<<<><<[[;;FS\n")); final FastqSequenceDataSource ds = new FastqSequenceDataSource(al, FastQScoreType.PHRED); final SequencesWriter sw = new SequencesWriter(ds, mDir, 100000, null, PrereadType.SOLEXA, false, 50); final SequencesReader sr = sw.processSequencesInMemory(null, true, null, null, LongRange.NONE); assertEquals(3, sr.numberSequences()); assertEquals(0, sr.length(0)); assertEquals(17, sr.length(1)); assertEquals(20, sr.length(2)); } public void testNoTrimNoQuals() throws Exception { final ArrayList<InputStream> al = new ArrayList<>(); al.add(createStream(">123456789012345678901\n" + "acgtgtgtgtcttagggctcactggtcatgca\n" + ">bob the buuilder\n" + "tagttcagcatcgatca\n" + ">hobos-r us" + "\naccccaccccacaaacccaa\n")); final FastaSequenceDataSource ds = new FastaSequenceDataSource(al, new DNAFastaSymbolTable()); final SequencesWriter sw = new SequencesWriter(ds, mDir, 100000, null, PrereadType.SOLEXA, false, 50); final File proxy = new File("proxy"); final SequencesReader sr = sw.processSequencesInMemory(proxy, true, null, null, LongRange.NONE); assertEquals(3, sr.numberSequences()); assertEquals(32, sr.length(0)); assertEquals(17, sr.length(1)); assertEquals(20, sr.length(2)); assertEquals(proxy, sr.path()); } }
package javacommon.xsqlbuilder; import java.lang.reflect.InvocationTargetException; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.PropertyUtils; class MapAndObjectHolder implements Map { Map map; Object bean; public MapAndObjectHolder(Map map, Object bean) { super(); this.map = map; this.bean = bean; } static Pattern ERROR_METHOD_PATTERN = Pattern.compile("^[^a-zA-Z_].*"); Object getProperty(Object key) { Object result = null; if (map != null) { result = map.get(key); } if(result == null && bean != null && bean instanceof Map) { result = ((Map)bean).get(key); } if (result == null && bean != null && key instanceof String) { String prop = (String)key; if(ERROR_METHOD_PATTERN.matcher(prop).matches()) { return null; } try { result = PropertyUtils.getProperty(bean, prop); } catch (IllegalAccessException e) { throw new IllegalStateException( "cannot get property value by property:" + key + " on class:" + bean.getClass(), e); } catch (InvocationTargetException e) { throw new IllegalStateException( "cannot get property value by property:" + key + " on class:" + bean.getClass(), e); } catch (NoSuchMethodException e) { return null; } } return result; } public void clear() { throw new UnsupportedOperationException(); } public boolean containsKey(Object key) { throw new UnsupportedOperationException(); } public boolean containsValue(Object value) { throw new UnsupportedOperationException(); } public Set entrySet() { throw new UnsupportedOperationException(); } public Object get(Object key) { return getProperty(key); } public boolean isEmpty() { throw new UnsupportedOperationException(); } public Set keySet() { throw new UnsupportedOperationException(); } public Object put(Object key, Object value) { throw new UnsupportedOperationException(); } public void putAll(Map m) { throw new UnsupportedOperationException(); } public Object remove(Object key) { throw new UnsupportedOperationException(); } public int size() { throw new UnsupportedOperationException(); } public Collection values() { throw new UnsupportedOperationException(); } }
package org.ow2.proactive.workflow_catalog.rest.util; import com.google.common.base.Optional; import com.google.common.collect.ImmutableMap; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.events.XMLEvent; import java.io.InputStream; import java.util.function.BiConsumer; /** * @author ActiveEon Team */ public final class WorkflowParser { private static final String ATTRIBUTE_JOB_NAME = "name"; private static final String ATTRIBUTE_JOB_PROJECT_NAME = "projectName"; private static final String ATTRIBUTE_GENERIC_INFORMATION_NAME = "name"; private static final String ATTRIBUTE_GENERIC_INFORMATION_VALUE = "value"; private static final String ATTRIBUTE_VARIABLE_NAME = "name"; private static final String ATTRIBUTE_VARIABLE_VALUE = "value"; private static final String ELEMENT_GENERIC_INFORMATION = "genericInformation"; private static final String ELEMENT_GENERIC_INFORMATION_INFO = "info"; private static final String ELEMENT_JOB = "job"; private static final String ELEMENT_VARIABLE = "variable"; private static final String ELEMENT_VARIABLES = "variables"; private final XMLStreamReader xmlStreamReader; /* * Variables indicating which parts of the document have been parsed. * Thanks to these information, parsing can be stopped once required * information have been extracted. */ private boolean jobHandled = false; private boolean variablesHandled = false; private boolean genericInformationHandled = false; /* Below are instance variables containing values which are extracted */ private String jobName; private String projectName; private ImmutableMap<String, String> genericInformation; private ImmutableMap<String, String> variables; private static final class XmlInputFactoryLazyHolder { private static final XMLInputFactory INSTANCE = XMLInputFactory.newInstance(); } public WorkflowParser(InputStream inputStream) throws XMLStreamException { this.xmlStreamReader = XmlInputFactoryLazyHolder.INSTANCE.createXMLStreamReader(inputStream); } public void parse() throws XMLStreamException { int eventType; ImmutableMap.Builder<String, String> genericInformation = ImmutableMap.builder(); ImmutableMap.Builder<String, String> variables = ImmutableMap.builder(); try { while (xmlStreamReader.hasNext() && !allElementHandled()) { eventType = xmlStreamReader.next(); switch (eventType) { case XMLEvent.START_ELEMENT: String elementLocalPart = xmlStreamReader.getName().getLocalPart(); switch (elementLocalPart) { case ELEMENT_JOB: handleJobElement(); break; case ELEMENT_GENERIC_INFORMATION_INFO: handleGenericInformationElement(genericInformation); break; case ELEMENT_VARIABLE: handleVariableElement(variables); break; } break; case XMLEvent.END_ELEMENT: elementLocalPart = xmlStreamReader.getName().getLocalPart(); if (elementLocalPart.equals(ELEMENT_GENERIC_INFORMATION)) { this.genericInformationHandled = true; } else if (elementLocalPart.equals(ELEMENT_VARIABLES)) { this.variablesHandled = true; } break; default: break; } } } finally { this.xmlStreamReader.close(); this.genericInformation = genericInformation.build(); this.variables = variables.build(); } } private void handleGenericInformationElement(ImmutableMap.Builder<String, String> genericInformation) { handleElementWithMultipleValues( genericInformation, ATTRIBUTE_GENERIC_INFORMATION_NAME, ATTRIBUTE_GENERIC_INFORMATION_VALUE); } private void handleJobElement() { iterateOverAttributes( (attributeName, attributeValue) -> { if (attributeName.equals(ATTRIBUTE_JOB_NAME)) { this.jobName = attributeValue; } else if (attributeName.equals(ATTRIBUTE_JOB_PROJECT_NAME)) { this.projectName = attributeValue; } } ); jobHandled = true; } private void handleVariableElement(ImmutableMap.Builder<String, String> variables) { handleElementWithMultipleValues( variables, ATTRIBUTE_VARIABLE_NAME, ATTRIBUTE_VARIABLE_VALUE); } private void handleElementWithMultipleValues(ImmutableMap.Builder<String, String> store, String attributeNameForKey, String attributeNameForValue) { String[] key = new String[1]; String[] value = new String[1]; iterateOverAttributes( (attributeName, attributeValue) -> { if (attributeName.equals(attributeNameForKey)) { key[0] = attributeValue; } else if (attributeName.equals(attributeNameForValue)) { value[0] = attributeValue; } } ); store.put(key[0], value[0]); } private void iterateOverAttributes(BiConsumer<String, String> attribute) { for (int i = 0; i < xmlStreamReader.getAttributeCount(); i++) { String attributeName = xmlStreamReader.getAttributeName(i).getLocalPart(); String attributeValue = xmlStreamReader.getAttributeValue(i); attribute.accept(attributeName, attributeValue); } } private boolean allElementHandled() { return this.jobHandled && this.genericInformationHandled && this.variablesHandled; } public Optional<String> getJobName() { return Optional.fromNullable(jobName); } public Optional<String> getProjectName() { return Optional.fromNullable(projectName); } public ImmutableMap<String, String> getGenericInformation() { return genericInformation; } public ImmutableMap<String, String> getVariables() { return variables; } }
package org.support.project.knowledge.control.open; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.Cookie; import org.support.project.common.exception.ParseException; import org.support.project.common.log.Log; import org.support.project.common.log.LogFactory; import org.support.project.common.util.StringUtils; import org.support.project.di.DI; import org.support.project.di.Instance; import org.support.project.knowledge.control.KnowledgeControlBase; import org.support.project.knowledge.dao.CommentsDao; import org.support.project.knowledge.dao.KnowledgeHistoriesDao; import org.support.project.knowledge.dao.KnowledgeItemValuesDao; import org.support.project.knowledge.dao.LikesDao; import org.support.project.knowledge.dao.TagsDao; import org.support.project.knowledge.dao.TemplateMastersDao; import org.support.project.knowledge.entity.CommentsEntity; import org.support.project.knowledge.entity.KnowledgeHistoriesEntity; import org.support.project.knowledge.entity.KnowledgeItemValuesEntity; import org.support.project.knowledge.entity.KnowledgesEntity; import org.support.project.knowledge.entity.LikesEntity; import org.support.project.knowledge.entity.TagsEntity; import org.support.project.knowledge.entity.TemplateItemsEntity; import org.support.project.knowledge.entity.TemplateMastersEntity; import org.support.project.knowledge.logic.DiffLogic; import org.support.project.knowledge.logic.GroupLogic; import org.support.project.knowledge.logic.KeywordLogic; import org.support.project.knowledge.logic.KnowledgeLogic; import org.support.project.knowledge.logic.MarkdownLogic; import org.support.project.knowledge.logic.TagLogic; import org.support.project.knowledge.logic.TargetLogic; import org.support.project.knowledge.logic.TemplateLogic; import org.support.project.knowledge.logic.UploadedFileLogic; import org.support.project.knowledge.vo.LikeCount; import org.support.project.knowledge.vo.MarkDown; import org.support.project.knowledge.vo.UploadFile; import org.support.project.web.bean.LabelValue; import org.support.project.web.bean.LoginedUser; import org.support.project.web.boundary.Boundary; import org.support.project.web.common.HttpStatus; import org.support.project.web.control.service.Get; import org.support.project.web.control.service.Post; import org.support.project.web.dao.GroupsDao; import org.support.project.web.dao.UsersDao; import org.support.project.web.entity.GroupsEntity; import org.support.project.web.entity.UsersEntity; import org.support.project.web.exception.InvalidParamException; @DI(instance=Instance.Prototype) public class KnowledgeControl extends KnowledgeControlBase { private static final int COOKIE_COUNT = 5; private static Log LOG = LogFactory.getLog(KnowledgeControl.class); public static final int PAGE_LIMIT = 50; public static final int FAV_PAGE_LIMIT = 10; public static final int COOKIE_AGE = 60 * 60 * 24 * 31; private static final String COOKIE_SEPARATOR = "-"; /** * * @return * @throws InvalidParamException * @throws ParseException */ @Get public Boundary view() throws InvalidParamException, ParseException { setViewParam(); Long knowledgeId = super.getPathLong(Long.valueOf(-1)); KnowledgeLogic knowledgeLogic = KnowledgeLogic.get(); // Cookie try { List<String> ids = new ArrayList<String>(); ids.add(String.valueOf(knowledgeId)); Cookie[] cookies = getRequest().getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("KNOWLEDGE_HISTORY")) { String history = cookie.getValue(); if (history.indexOf(",") != -1) { history = history.replaceAll(",", "-"); } else { history = URLDecoder.decode(history, "UTF-8"); } if (history.indexOf(COOKIE_SEPARATOR) != -1) { String[] historyIds = history.split(COOKIE_SEPARATOR); for (int i = 0; i < historyIds.length; i++) { if (!ids.contains(historyIds[i]) && StringUtils.isLong(historyIds[i])) { ids.add(historyIds[i]); } if (ids.size() >= COOKIE_COUNT) { break; } } } else { if (!ids.contains(history)) { ids.add(history); } } break; } } String cookieHistory = String.join(COOKIE_SEPARATOR, ids); cookieHistory = URLEncoder.encode(cookieHistory, "UTF-8"); Cookie cookie = new Cookie("KNOWLEDGE_HISTORY", cookieHistory); cookie.setPath(getRequest().getContextPath()); cookie.setMaxAge(COOKIE_AGE); getResponse().addCookie(cookie); } } catch (UnsupportedEncodingException e) { LOG.error("Cokkie error.", e); } KnowledgesEntity entity = knowledgeLogic.selectWithTags(knowledgeId, getLoginedUser()); if (entity == null) { return sendError(HttpStatus.SC_404_NOT_FOUND, "NOT FOUND"); } //Markdown entity.setTitle(sanitize(entity.getTitle())); MarkDown markDown = MarkdownLogic.get().markdownToHtml(entity.getContent()); entity.setContent(markDown.getHtml()); setAttributeOnProperty(entity); String offset = super.getParam("offset", String.class); if (StringUtils.isEmpty(offset)) { offset = "0"; } setAttribute("offset", offset); UploadedFileLogic fileLogic = UploadedFileLogic.get(); List<UploadFile> files = fileLogic.selectOnKnowledgeId(knowledgeId, getRequest().getContextPath()); setAttribute("files", files); knowledgeLogic.addViewHistory(knowledgeId, getLoginedUser()); LikesDao likesDao = LikesDao.get(); Long count = likesDao.countOnKnowledgeId(knowledgeId); setAttribute("like_count", count); CommentsDao commentsDao = CommentsDao.get(); List<CommentsEntity> comments = commentsDao.selectOnKnowledgeId(knowledgeId); // Markdown for (CommentsEntity commentsEntity : comments) { MarkDown markDown2 = MarkdownLogic.get().markdownToHtml(commentsEntity.getComment()); commentsEntity.setComment(markDown2.getHtml()); } setAttribute("comments", comments); //List<GroupsEntity> groups = GroupLogic.get().selectGroupsOnKnowledgeId(knowledgeId); List<LabelValue> groups = TargetLogic.get().selectTargetsOnKnowledgeId(knowledgeId); setAttribute("groups", groups); List<LabelValue> editors = TargetLogic.get().selectEditorsOnKnowledgeId(knowledgeId); setAttribute("editors", editors); LoginedUser loginedUser = super.getLoginedUser(); boolean edit = knowledgeLogic.isEditor(loginedUser, entity, editors); setAttribute("edit", edit); ArrayList<Long> knowledgeIds = new ArrayList<Long>(); knowledgeIds.add(entity.getKnowledgeId()); TargetLogic targetLogic = TargetLogic.get(); Map<Long, ArrayList<LabelValue>> targets = targetLogic.selectTargetsOnKnowledgeIds(knowledgeIds, loginedUser); setAttribute("targets", targets); return forward("view.jsp"); } /** * * @return * @throws Exception */ @Get public Boundary list() throws Exception { LOG.trace("Call list"); Integer offset = super.getPathInteger(0); setAttribute("offset", offset); String keyword = getParam("keyword"); setAttribute("searchKeyword", keyword); setViewParam(); TagsDao tagsDao = TagsDao.get(); GroupsDao groupsDao = GroupsDao.get(); KnowledgeLogic knowledgeLogic = KnowledgeLogic.get(); KeywordLogic keywordLogic = KeywordLogic.get(); LoginedUser loginedUser = super.getLoginedUser(); String tag = getParam("tag"); String group = getParam("group"); String user = getParam("user"); String tagNames = getParam("tagNames"); String groupNames = getParam("groupNames"); List<KnowledgesEntity> knowledges = new ArrayList<>(); if (StringUtils.isInteger(tag)) { LOG.trace("show on Tag"); knowledges.addAll(knowledgeLogic.showKnowledgeOnTag(tag, loginedUser, offset * PAGE_LIMIT, PAGE_LIMIT)); TagsEntity tagsEntity = tagsDao.selectOnKey(new Integer(tag)); setAttribute("selectedTag", tagsEntity); } else if (StringUtils.isInteger(group)) { LOG.trace("show on Group"); knowledges.addAll(knowledgeLogic.showKnowledgeOnGroup(group, loginedUser, offset * PAGE_LIMIT, PAGE_LIMIT)); GroupsEntity groupsEntity = groupsDao.selectOnKey(new Integer(group)); setAttribute("selectedGroup", groupsEntity); } else if (StringUtils.isNotEmpty(user) && StringUtils.isInteger(user)) { LOG.trace("show on User"); int userId = Integer.parseInt(user); knowledges.addAll(knowledgeLogic.showKnowledgeOnUser(userId, loginedUser, offset * PAGE_LIMIT, PAGE_LIMIT)); UsersEntity usersEntity = UsersDao.get().selectOnKey(userId); if (user != null) { usersEntity.setPassword(""); setAttribute("selectedUser", usersEntity); } } else if (StringUtils.isNotEmpty(tagNames) || StringUtils.isNotEmpty(groupNames)) { LOG.trace("show on Tags and Groups and keyword"); String[] taglist = tagNames.split(","); List<TagsEntity> tags = new ArrayList<>(); for (String string : taglist) { String tagname = string.trim(); if (tagname.startsWith(" ") && tagname.length() > " ".length()) { tagname = tagname.substring(" ".length()); } TagsEntity tagsEntity = tagsDao.selectOnTagName(tagname); if (tagsEntity != null) { tags.add(tagsEntity); } } List<GroupsEntity> groups = new ArrayList<>(); if (loginedUser != null) { String[] grouplist = groupNames.split(","); for (String string : grouplist) { String groupname = string.trim(); if (groupname.startsWith(" ") && groupname.length() > " ".length()) { groupname = groupname.substring(" ".length()); } GroupsEntity groupsEntity = groupsDao.selectOnGroupName(groupname); if (groupsEntity != null) { groups.add(groupsEntity); } } } setAttribute("searchTags", tags); setAttribute("searchGroups", groups); knowledges.addAll(knowledgeLogic.searchKnowledge(keyword, tags, groups, loginedUser, offset * PAGE_LIMIT, PAGE_LIMIT)); } else { LOG.trace("search"); List<GroupsEntity> groups = null; List<TagsEntity> tags = null; if (loginedUser != null) { String groupKeyword = keywordLogic.parseQuery("groups", keyword); if (groupKeyword != null) { groups = new ArrayList<GroupsEntity>(); for (String groupName : groupKeyword.split(",")) { GroupsEntity groupsEntity = groupsDao.selectOnGroupName(groupName); if (groupsEntity != null) { groups.add(groupsEntity); } } setAttribute("searchGroups", groups); } } String tagKeyword = keywordLogic.parseQuery("tags", keyword); if (tagKeyword != null) { tags = new ArrayList<TagsEntity>(); for (String tagName : tagKeyword.split(",")) { TagsEntity tagsEntity = tagsDao.selectOnTagName(tagName); if (tagsEntity != null) { tags.add(tagsEntity); } } setAttribute("searchTags", tags); } keyword = keywordLogic.parseKeyword(keyword); setAttribute("keyword", keyword); knowledges.addAll(knowledgeLogic.searchKnowledge(keyword, tags, groups, loginedUser, offset * PAGE_LIMIT, PAGE_LIMIT)); } setAttribute("knowledges", knowledges); LOG.trace(""); ArrayList<Long> knowledgeIds = new ArrayList<Long>(); for (KnowledgesEntity knowledgesEntity : knowledges) { knowledgeIds.add(knowledgesEntity.getKnowledgeId()); } TargetLogic targetLogic = TargetLogic.get(); Map<Long, ArrayList<LabelValue>> targets = targetLogic.selectTargetsOnKnowledgeIds(knowledgeIds, loginedUser); setAttribute("targets", targets); int previous = offset -1; if (previous < 0) { previous = 0; } if (loginedUser != null && loginedUser.isAdmin()) { List<TagsEntity> tags = tagsDao.selectTagsWithCount(0, FAV_PAGE_LIMIT); setAttribute("tags", tags); List<GroupsEntity> groups = groupsDao.selectGroupsWithCount(0, FAV_PAGE_LIMIT); setAttribute("groups", groups); } else { TagLogic tagLogic = TagLogic.get(); List<TagsEntity> tags = tagLogic.selectTagsWithCount(loginedUser, 0, FAV_PAGE_LIMIT); setAttribute("tags", tags); if (loginedUser != null) { GroupLogic groupLogic = GroupLogic.get(); List<GroupsEntity> groups = groupLogic.selectMyGroup(loginedUser, 0, FAV_PAGE_LIMIT); setAttribute("groups", groups); } } LOG.trace(""); // History // TODO try { Cookie[] cookies = getRequest().getCookies(); List<String> historyIds = new ArrayList<>(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("KNOWLEDGE_HISTORY")) { String history = cookie.getValue(); if (history.indexOf(",") != -1) { history = history.replaceAll(",", "-"); } else { history = URLDecoder.decode(history, "UTF-8"); } LOG.debug("history: " + history); if (history.indexOf(COOKIE_SEPARATOR) != -1) { String[] splits = history.split(COOKIE_SEPARATOR); for (String string : splits) { if (StringUtils.isLong(string)) { historyIds.add(string); } } } else { if (StringUtils.isLong(history)) { historyIds.add(history); } } break; } } } List<KnowledgesEntity> histories = knowledgeLogic.getKnowledges(historyIds, loginedUser); LOG.trace(""); setAttribute("histories", histories); } catch (UnsupportedEncodingException e) { LOG.error("Cokkie error.", e); } setAttribute("offset", offset); setAttribute("previous", previous); setAttribute("next", offset + 1); return forward("list.jsp"); } /** * * @return * @throws InvalidParamException */ @Get public Boundary like() throws InvalidParamException { Long knowledgeId = super.getPathLong(Long.valueOf(-1)); KnowledgeLogic knowledgeLogic = KnowledgeLogic.get(); Long count = knowledgeLogic.addLike(knowledgeId, getLoginedUser()); LikeCount likeCount = new LikeCount(); likeCount.setKnowledgeId(knowledgeId); likeCount.setCount(count); return send(likeCount); } /** * * @param entity * @return * @throws ParseException */ @Post public Boundary escape(KnowledgesEntity entity) throws ParseException { super.setSendEscapeHtml(false); entity.setTitle(sanitize(entity.getTitle())); entity.setContent(sanitize(entity.getContent())); return super.send(entity); } /** * markdownHTML * @param entity * @return * @throws ParseException */ @Post public Boundary marked(KnowledgesEntity entity) throws ParseException { super.setSendEscapeHtml(false); entity.setTitle(sanitize(entity.getTitle())); MarkDown markDown = MarkdownLogic.get().markdownToHtml(entity.getContent()); entity.setContent(markDown.getHtml()); return super.send(entity); } /** * * @return */ @Get public Boundary search() { KeywordLogic keywordLogic = KeywordLogic.get(); LoginedUser loginedUser = super.getLoginedUser(); List<GroupsEntity> groupitems = new ArrayList<GroupsEntity>(); List<TagsEntity> tagitems = TagsDao.get().selectAll(); setAttribute("tagitems", tagitems); if (loginedUser != null) { if (loginedUser.isAdmin()) { groupitems = GroupsDao.get().selectAll(); } else { groupitems = loginedUser.getGroups(); } } setAttribute("groupitems", groupitems); setViewParam(); // groups:tags: String keyword = getParam("keyword"); setAttribute("searchKeyword", keywordLogic.parseKeyword(keyword)); setAttribute("tagNames", keywordLogic.parseQuery("tags", keyword)); if (loginedUser != null) { setAttribute("groupNames", keywordLogic.parseQuery("groups", keyword)); } return forward("search.jsp"); } /** * * @return * @throws InvalidParamException */ @Get public Boundary likes() throws InvalidParamException { setViewParam(); Long knowledgeId = super.getPathLong(Long.valueOf(-1)); setAttribute("knowledgeId", knowledgeId); // () TODO KnowledgeLogic knowledgeLogic = KnowledgeLogic.get(); KnowledgesEntity entity = knowledgeLogic.select(knowledgeId, getLoginedUser()); if (entity == null) { return sendError(HttpStatus.SC_404_NOT_FOUND, "NOT FOUND"); } Integer page = 0; String p = getParamWithDefault("page", ""); if (StringUtils.isInteger(p)) { page = Integer.parseInt(p); } LikesDao likesDao = LikesDao.get(); List<LikesEntity> likes = likesDao.selectOnKnowledge(knowledgeId, page * PAGE_LIMIT, PAGE_LIMIT); setAttribute("likes", likes); int previous = page -1; if (previous < 0) { previous = 0; } setAttribute("page", page); setAttribute("previous", previous); setAttribute("next", page + 1); return forward("likes.jsp"); } @Get public Boundary histories() throws InvalidParamException { setViewParam(); Long knowledgeId = super.getPathLong(Long.valueOf(-1)); setAttribute("knowledgeId", knowledgeId); KnowledgeLogic knowledgeLogic = KnowledgeLogic.get(); KnowledgesEntity entity = knowledgeLogic.select(knowledgeId, getLoginedUser()); if (entity == null) { return sendError(HttpStatus.SC_404_NOT_FOUND, "NOT FOUND"); } Integer page = 0; String p = getParamWithDefault("page", ""); if (StringUtils.isInteger(p)) { page = Integer.parseInt(p); } int previous = page -1; if (previous < 0) { previous = 0; } setAttribute("page", page); setAttribute("previous", previous); setAttribute("next", page + 1); KnowledgeHistoriesDao historiesDao = KnowledgeHistoriesDao.get(); List<KnowledgeHistoriesEntity> histories = historiesDao.selectOnKnowledge(knowledgeId, page * PAGE_LIMIT, PAGE_LIMIT); setAttribute("histories", histories); return forward("histories.jsp"); } @Get public Boundary history() throws InvalidParamException { setViewParam(); Long knowledgeId = super.getPathLong(Long.valueOf(-1)); setAttribute("knowledgeId", knowledgeId); KnowledgeLogic knowledgeLogic = KnowledgeLogic.get(); KnowledgesEntity entity = knowledgeLogic.select(knowledgeId, getLoginedUser()); if (entity == null) { return sendError(HttpStatus.SC_404_NOT_FOUND, "NOT FOUND"); } Integer page = 0; String p = getParamWithDefault("page", ""); if (StringUtils.isInteger(p)) { page = Integer.parseInt(p); } setAttribute("page", page); Integer historyNo = 0; String h = getParamWithDefault("history_no", ""); if (StringUtils.isInteger(h)) { historyNo = Integer.parseInt(h); } KnowledgeHistoriesDao historiesDao = KnowledgeHistoriesDao.get(); KnowledgeHistoriesEntity history = historiesDao.selectOnKeyWithName(historyNo, knowledgeId); setAttribute("history", history); setAttribute("now", entity); List<String> changes = DiffLogic.get().diff(history.getContent(), entity.getContent()); setAttribute("changes", changes); return forward("history.jsp"); } /** * * @return * @throws InvalidParamException */ @Get public Boundary template() throws InvalidParamException { Integer typeId = super.getParam("type_id", Integer.class); TemplateMastersEntity template = TemplateMastersDao.get().selectWithItems(typeId); if (template == null) { typeId = TemplateMastersDao.TYPE_ID_KNOWLEDGE; template = TemplateMastersDao.get().selectWithItems(typeId); } String knowledgeId = super.getParam("knowledge_id"); if (StringUtils.isNotEmpty(knowledgeId) && StringUtils.isLong(knowledgeId)) { KnowledgeLogic knowledgeLogic = KnowledgeLogic.get(); KnowledgesEntity entity = knowledgeLogic.select(new Long(knowledgeId), getLoginedUser()); if (entity == null) { return sendError(HttpStatus.SC_404_NOT_FOUND, "NOT FOUND"); } List<KnowledgeItemValuesEntity> values = KnowledgeItemValuesDao.get().selectOnKnowledgeId(entity.getKnowledgeId()); List<TemplateItemsEntity> items = template.getItems(); for (KnowledgeItemValuesEntity val : values) { for (TemplateItemsEntity item : items) { if (val.getItemNo().equals(item.getItemNo())) { item.setItemValue(val.getItemValue()); break; } } } } return send(template); } }
package joshua.decoder.ff.tm.packed; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.IntBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.logging.Logger; import joshua.corpus.Vocabulary; import joshua.decoder.JoshuaConfiguration; import joshua.decoder.ff.FeatureFunction; import joshua.decoder.ff.FeatureVector; import joshua.decoder.ff.tm.BasicRuleCollection; import joshua.decoder.ff.tm.BatchGrammar; import joshua.decoder.ff.tm.BilingualRule; import joshua.decoder.ff.tm.Rule; import joshua.decoder.ff.tm.RuleCollection; import joshua.decoder.ff.tm.Trie; import joshua.util.io.LineReader; import joshua.util.quantization.Quantizer; import joshua.util.quantization.QuantizerConfiguration; public class PackedGrammar extends BatchGrammar { private static final Logger logger = Logger.getLogger(PackedGrammar.class.getName()); private int spanLimit = -1; private int owner; private QuantizerConfiguration quantization; private HashMap<Integer, Integer> featureNameMap; private PackedRoot root; private ArrayList<PackedSlice> slices; private final float maxId; public PackedGrammar(String grammar_directory, int span_limit, String owner) throws FileNotFoundException, IOException { this.spanLimit = span_limit; // Read the vocabulary. logger.info("Reading vocabulary: " + grammar_directory + File.separator + "vocabulary"); Vocabulary.read(grammar_directory + File.separator + "vocabulary"); maxId = (float) Vocabulary.size(); // Read the quantizer setup. logger.info("Reading quantization configuration: " + grammar_directory + File.separator + "quantization"); quantization = new QuantizerConfiguration(); quantization.read(grammar_directory + File.separator + "quantization"); // Set phrase owner. this.owner = Vocabulary.id(owner); // Read the dense feature name map. if (JoshuaConfiguration.dense_features) loadFeatureNameMap(grammar_directory + File.separator + "dense_map"); String[] listing = new File(grammar_directory).list(); slices = new ArrayList<PackedSlice>(); for (int i = 0; i < listing.length; i++) { if (listing[i].startsWith("slice_") && listing[i].endsWith(".source")) slices .add(new PackedSlice(grammar_directory + File.separator + listing[i].substring(0, 11))); } root = new PackedRoot(this); } private void loadFeatureNameMap(String map_file_name) throws IOException { featureNameMap = new HashMap<Integer, Integer>(); LineReader reader = new LineReader(map_file_name); while (reader.hasNext()) { String line = reader.next().trim(); String[] fields = line.split("\\s+"); if (fields.length != 2) { logger.severe("Invalid feature map format: " + line); System.exit(0); } int feature_index = Integer.parseInt(fields[0]); int feature_id = Vocabulary.id(fields[1]); if (featureNameMap.values().contains(feature_index)) { logger.severe("Duplicate index in feature map: " + feature_index); System.exit(0); } featureNameMap.put(feature_id, feature_index); } reader.close(); // Run a sanity check. for (int feature_id : featureNameMap.keySet()) { int index = featureNameMap.get(feature_id); if (0 > index || index >= featureNameMap.size()) { logger.severe("Out of scope feature index in map: " + Vocabulary.word(feature_id) + " -> " + index); System.exit(0); } } } @Override public Trie getTrieRoot() { return root; } @Override public boolean hasRuleForSpan(int startIndex, int endIndex, int pathLength) { return (spanLimit == -1 || pathLength <= spanLimit); } @Override public int getNumRules() { int num_rules = 0; for (PackedSlice ps : slices) num_rules += ps.featureSize; return num_rules; } public Rule constructManualRule(int lhs, int[] src, int[] tgt, float[] scores, int arity) { return null; } public class PackedTrie implements Trie, RuleCollection { private final PackedSlice grammar; private final int position; private int[] src; private int arity; private PackedTrie(PackedSlice grammar, int position) { this.grammar = grammar; this.position = position; src = new int[0]; arity = 0; } public PackedTrie(PackedSlice grammar, int position, int[] parent_src, int parent_arity, int symbol) { this.grammar = grammar; this.position = position; src = new int[parent_src.length + 1]; System.arraycopy(parent_src, 0, src, 0, parent_src.length); src[src.length - 1] = symbol; arity = parent_arity; if (Vocabulary.nt(symbol)) arity++; } @Override public final Trie match(int token_id) { int num_children = grammar.source[position]; if (num_children == 0) return null; if (num_children == 1 && token_id == grammar.source[position + 1]) return new PackedTrie(grammar, grammar.source[position + 2], src, arity, token_id); int top = 0; int bottom = num_children - 1; while (true) { int candidate = (top + bottom) / 2; int candidate_position = position + 1 + 2 * candidate; int read_token = grammar.source[candidate_position]; if (read_token == token_id) { return new PackedTrie(grammar, grammar.source[candidate_position + 1], src, arity, token_id); } else if (top == bottom) { return null; } else if (read_token > token_id) { top = candidate + 1; } else { bottom = candidate - 1; } if (bottom < top) return null; } } // public final Trie match(final int token_id) { // final int num_children = grammar.source.get(position); // final int offset = position + 1; // if (num_children == 0) // return null; // if (num_children == 1 && token_id == grammar.source.get(position + 1)) // return new PackedTrie(grammar, grammar.source.get(position + 2), // src, arity, token_id); // int top = 0; // int bottom = num_children - 1; // int top_token, bottom_token; // int candidate, candidate_position, candidate_token; // while (true) { // top_token = grammar.source.get(offset + 2 * top); // bottom_token = grammar.source.get(offset + 2 * bottom); // candidate = (int) ((bottom_token - token_id) / (float) (top_token - bottom_token)) * (bottom // - top); // candidate_position = offset + 2 * candidate; // candidate_token = grammar.source.get(candidate_position); // logger.info("[" + top + " - " + candidate + " - " + bottom + "]"); // logger.info("{" + top_token + " - " + candidate_token + " - " + bottom_token + "}"); // if (candidate_token == token_id) { // return new PackedTrie(grammar, // grammar.source.get(candidate_position + 1), // src, arity, token_id); // } else if (top == bottom) { // return null; // } else if (candidate_token > token_id) { // top = candidate + 1; // } else { // bottom = candidate - 1; // if (bottom < top) // return null; @Override public HashMap<Integer, ? extends Trie> getChildren() { // TODO: implement this System.err.println("* WARNING: PackedTrie doesn't implement getChildren()"); return new HashMap<Integer, PackedTrie>(); } public boolean hasExtensions() { return (grammar.source[position] != 0); } public ArrayList<? extends Trie> getExtensions() { int num_children = grammar.source[position]; ArrayList<PackedTrie> tries = new ArrayList<PackedTrie>(num_children); for (int i = 0; i < num_children; i++) { int symbol = grammar.source[position + 1 + 2 * i]; int address = grammar.source[position + 2 + 2 * i]; tries.add(new PackedTrie(grammar, address, src, arity, symbol)); } return tries; } public boolean hasRules() { int num_children = grammar.source[position]; return (grammar.source[position + 1 + 2 * num_children] != 0); } public RuleCollection getRuleCollection() { return this; } public List<Rule> getRules() { int num_children = grammar.source[position]; int rule_position = position + 2 * (num_children + 1); int num_rules = grammar.source[rule_position - 1]; ArrayList<Rule> rules = new ArrayList<Rule>(num_rules); for (int i = 0; i < num_rules; i++) { rules.add(new PackedRule(this, rule_position + 3 * i)); } return rules; } /** * We determine if the Trie is sorted by checking if the estimated cost of the first rule in the * trie has been set. */ @Override public boolean isSorted() { int num_children = grammar.source[position]; int rule_position = position + 2 * (num_children + 1); int num_rules = grammar.source[rule_position - 1]; int block_id = grammar.source[rule_position + 2]; return (num_rules == 0 || grammar.estimated[block_id] != Float.NEGATIVE_INFINITY); } @Override public void sortRules(List<FeatureFunction> models) { int num_children = grammar.source[position]; int rule_position = position + 2 * (num_children + 1); int num_rules = grammar.source[rule_position - 1]; if (num_rules == 0) return; Integer[] rules = new Integer[num_rules]; int target_address; int block_id; for (int i = 0; i < num_rules; i++) { target_address = grammar.source[rule_position + 1 + 3 * i]; rules[i] = rule_position + 2 + 3 * i; block_id = grammar.source[rules[i]]; BilingualRule rule = new BilingualRule(grammar.source[rule_position + 3 * i], src, grammar.getTarget(target_address), grammar.getFeatures(block_id), arity, owner); grammar.estimated[block_id] = rule.estimateRuleCost(models); grammar.precomputable[block_id] = rule.getPrecomputableCost(); } Arrays.sort(rules, new Comparator<Integer>() { public int compare(Integer a, Integer b) { float a_cost = grammar.estimated[grammar.source[a]]; float b_cost = grammar.estimated[grammar.source[b]]; if (a_cost == b_cost) return 0; return (a_cost > b_cost ? 1 : -1); } }); int[] sorted = new int[3 * num_rules]; int j = 0; for (int i = 0; i < rules.length; i++) { int address = rules[i]; sorted[j++] = grammar.source[address - 2]; sorted[j++] = grammar.source[address - 1]; sorted[j++] = grammar.source[address]; } for (int i = 0; i < sorted.length; i++) grammar.source[rule_position + i] = sorted[i]; } @Override public List<Rule> getSortedRules() { return getRules(); } @Override public int[] getSourceSide() { return src; } @Override public int getArity() { return arity; } } public final class PackedRoot implements Trie { private HashMap<Integer, PackedSlice> lookup; public PackedRoot(PackedGrammar grammar) { lookup = new HashMap<Integer, PackedSlice>(); for (PackedSlice ps : grammar.slices) { int num_children = ps.source[0]; for (int i = 0; i < num_children; i++) lookup.put(ps.source[2 * i + 1], ps); } } @Override public Trie match(int word_id) { PackedSlice ps = lookup.get(word_id); if (ps != null) { PackedTrie trie = new PackedTrie(ps, 0); return trie.match(word_id); } return null; } @Override public boolean hasExtensions() { return !lookup.isEmpty(); } @Override public HashMap<Integer, ? extends Trie> getChildren() { // TODO: implement this System.err.println("* WARNING: PackedRoot doesn't implement getChildren()"); return new HashMap<Integer, PackedRoot>(); } @Override public ArrayList<? extends Trie> getExtensions() { ArrayList<Trie> tries = new ArrayList<Trie>(); for (int key : lookup.keySet()) { tries.add(match(key)); } return tries; } @Override public boolean hasRules() { return false; } @Override public RuleCollection getRuleCollection() { return new BasicRuleCollection(0, new int[0]); } } public final class PackedRule implements Rule { PackedTrie parent; int address; int[] tgt = null; FeatureVector features = null; public PackedRule(PackedTrie parent, int address) { this.parent = parent; this.address = address; } @Override public void setArity(int arity) { } @Override public int getArity() { return parent.getArity(); } @Override public void setOwner(int ow) { } @Override public int getOwner() { return owner; } @Override public void setLHS(int lhs) { } @Override public int getLHS() { return parent.grammar.source[address]; } @Override public void setEnglish(int[] eng) { } @Override public int[] getEnglish() { if (tgt == null) { tgt = parent.grammar.getTarget(parent.grammar.source[address + 1]); } return tgt; } @Override public void setFrench(int[] french) { } @Override public int[] getFrench() { return parent.src; } @Override public FeatureVector getFeatureVector() { if (features == null) { features = new FeatureVector( parent.grammar.getFeatures(parent.grammar.source[address + 2]), ""); features.times(-1); } return features; } @Override public void setEstimatedCost(float cost) { parent.grammar.estimated[parent.grammar.source[address + 2]] = cost; } @Override public float getEstimatedCost() { return parent.grammar.estimated[parent.grammar.source[address + 2]]; } @Override public void setPrecomputableCost(float cost) { parent.grammar.precomputable[parent.grammar.source[address + 2]] = cost; } @Override public float getPrecomputableCost() { return parent.grammar.precomputable[parent.grammar.source[address + 2]]; } @Override public float estimateRuleCost(List<FeatureFunction> models) { return parent.grammar.estimated[parent.grammar.source[address + 2]]; } } public final class PackedSlice { private final String name; private final int[] source; private final int[] target; private final int[] targetLookup; private MappedByteBuffer features; int featureSize; private int[] featureLookup; private float[] estimated; private float[] precomputable; public PackedSlice(String prefix) throws IOException { name = prefix; File source_file = new File(prefix + ".source"); File target_file = new File(prefix + ".target"); File target_lookup_file = new File(prefix + ".target.lookup"); File feature_file = new File(prefix + ".features"); // Get the channels etc. FileChannel source_channel = new FileInputStream(source_file).getChannel(); int source_size = (int) source_channel.size(); FileChannel target_channel = new FileInputStream(target_file).getChannel(); int target_size = (int) target_channel.size(); FileChannel feature_channel = new RandomAccessFile(feature_file, "r").getChannel(); int feature_size = (int) feature_channel.size(); IntBuffer source_buffer = source_channel.map(MapMode.READ_ONLY, 0, source_size).asIntBuffer(); source = new int[source_size / 4]; source_buffer.get(source); IntBuffer target_buffer = target_channel.map(MapMode.READ_ONLY, 0, target_size).asIntBuffer(); target = new int[target_size / 4]; target_buffer.get(target); features = feature_channel.map(MapMode.READ_ONLY, 0, feature_size); features.load(); int num_blocks = features.getInt(0); featureLookup = new int[num_blocks]; estimated = new float[num_blocks]; precomputable = new float[num_blocks]; featureSize = features.getInt(4); for (int i = 0; i < num_blocks; i++) { featureLookup[i] = features.getInt(8 + 4 * i); estimated[i] = Float.NEGATIVE_INFINITY; precomputable[i] = Float.NEGATIVE_INFINITY; } DataInputStream target_lookup_stream = new DataInputStream(new BufferedInputStream( new FileInputStream(target_lookup_file))); targetLookup = new int[target_lookup_stream.readInt()]; for (int i = 0; i < targetLookup.length; i++) targetLookup[i] = target_lookup_stream.readInt(); } final int[] makeArray(List<Integer> list) { int[] array = new int[list.size()]; int i = 0; for (int l : list) { array[i++] = l; } return array; } final int[] getTarget(int pointer) { // Figure out level. int tgt_length = 1; while (tgt_length < (targetLookup.length + 1) && targetLookup[tgt_length] <= pointer) tgt_length++; int[] tgt = new int[tgt_length]; int index = 0; int parent; do { parent = target[pointer]; if (parent != -1) tgt[index++] = target[pointer + 1]; pointer = parent; } while (pointer != -1); return tgt; } /** * NEW VERSION * * Returns a string version of the features associated with a rule (represented as a block ID). * These features are in the form "feature1=value feature2=value...". By default, unlabeled * features are named using the pattern * * tm_OWNER_INDEX * * where OWNER is the grammar's owner (Vocabulary.word(this.owner)) and INDEX is a 0-based index * of the feature found in the grammar. * * @param block_id * @return */ final String getFeatures(int block_id) { int feature_position = featureLookup[block_id]; /* The number of non-zero features stored with the rule. */ int num_features = features.getInt(feature_position); /* The vector will have to grow but it will be at least this size. */ feature_position += 4; StringBuilder sb = new StringBuilder(); for (int i = 0; i < num_features; i++) { int feature_id = features.getInt(feature_position); Quantizer quantizer = quantization.get(feature_id); int index = featureNameMap.get(feature_id); sb.append(String.format(" tm_%s_%d=%.5f", Vocabulary.word(owner), index, quantizer.read(features, feature_position))); feature_position += 4 + quantizer.size(); } // System.err.println("GETFEATURES() = " + sb.toString().trim()); return sb.toString().trim(); } public String toString() { return name; } } @Override public boolean isRegexpGrammar() { // TODO Auto-generated method stub return false; } }
package com.izforge.izpack.util.xml; import net.n3.nanoxml.XMLElement; /** * A Collection of convenient XML-Helper Methods and Constants * * @author marc.eppelmann&#064;gmx.de * @version $Revision: 1.1 $ */ public class XMLHelper { /** YES = "YES" */ public final static String YES = "YES"; /** NO = "NO" */ public final static String NO = "NO"; /** TRUE = "TRUE" */ public final static String TRUE = "TRUE"; /** FALSE = "FALSE" */ public final static String FALSE = "FALSE"; /** ON = "ON" */ public final static String ON = "ON"; /** OFF = "OFF" */ public final static String OFF = "OFF"; /** _1 = "1" */ public final static String _1 = "1"; /** _0 = "0" */ public final static String _0 = "0"; /** * Creates a new XMLHelper object. */ public XMLHelper( ) { super( ); } /** * Determines if the named attribute in true. True is represented by any of the * following strings and is not case sensitive. <br> * * <ul> * <li> * yes * </li> * <li> * 1 * </li> * <li> * true * </li> * <li> * on * </li> * </ul> * * <br> Every other string, including the empty string as well as the non-existence of * the attribute will cuase <code>false</code> to be returned. * * @param element the <code>XMLElement</code> to search for the attribute. * @param name the name of the attribute to test. * * @return <code>true</code> if the attribute value equals one of the pre-defined * strings, <code>false</code> otherwise. */ public static boolean attributeIsTrue( XMLElement element, String name ) { String value = element.getAttribute( name, "" ).toUpperCase( ); if( value.equals( YES ) ) { return ( true ); } else if( value.equals( TRUE ) ) { return ( true ); } else if( value.equals( ON ) ) { return ( true ); } else if( value.equals( _1 ) ) { return ( true ); } return ( false ); } /** * The Opposit of AttributeIsTrue() * * @param element the element to inspect * @param name the attribute to inspect * * @return returns true if name attribute of the given element contains &quot;false&quot; */ public static boolean attributeIsFalse( XMLElement element, String name ) { String value = element.getAttribute( name, "" ).toUpperCase( ); if( value.equals( "NO" ) ) { return ( true ); } else if( value.equals( "FALSE" ) ) { return ( true ); } else if( value.equals( "OFF" ) ) { return ( true ); } else if( value.equals( "0" ) ) { return ( true ); } return ( false ); } }
package org.videolan; import java.io.File; import java.io.InputStream; import java.io.InvalidObjectException; import java.util.Enumeration; import org.videolan.Logger; import org.bluray.net.BDLocator; import org.bluray.ti.TitleImpl; import org.davic.media.MediaLocator; import org.dvb.application.AppID; import org.dvb.application.AppsDatabase; import org.dvb.application.CurrentServiceFilter; import javax.media.Manager; import javax.tv.locator.Locator; import org.videolan.bdjo.AppEntry; import org.videolan.bdjo.Bdjo; import org.videolan.bdjo.GraphicsResolution; import org.videolan.bdjo.PlayListTable; import org.videolan.bdjo.TerminalInfo; import org.videolan.media.content.PlayerManager; public class BDJLoader { private static class FontCacheAction extends BDJAction { public FontCacheAction(InputStream is) { this.fontPath = null; this.is = is; } public FontCacheAction(String fontPath) { this.fontPath = fontPath; this.is = null; } protected void doAction() { try { if (this.is != null) { this.cacheFile = addFontImpl(is); } else { this.cacheFile = addFontImpl(fontPath); } } catch (RuntimeException e) { this.exception = e; } } public File execute() { BDJActionManager.getInstance().putCommand(this); waitEnd(); if (exception != null) { throw exception; } return cacheFile; } private final String fontPath; private final InputStream is; private File cacheFile = null; private RuntimeException exception = null; } /* called by org.dvb.ui.FontFactory */ public static File addFont(InputStream is) { if (BDJXletContext.getCurrentContext() == null) return addFontImpl(is); /* dispatch cache request to privileged thread */ return new FontCacheAction(is).execute(); } /* called by org.dvb.ui.FontFactory */ public static File addFont(String fontFile) { if (BDJXletContext.getCurrentContext() == null) return addFontImpl(fontFile); /* dispatch cache request to privileged thread */ return new FontCacheAction(fontFile).execute(); } private static File addFontImpl(InputStream is) { VFSCache localCache = vfsCache; if (localCache != null) { return localCache.addFont(is); } return null; } private static File addFontImpl(String fontFile) { VFSCache localCache = vfsCache; if (localCache != null) { return localCache.addFont(fontFile); } return null; } /* called by BDJSecurityManager */ protected static void accessFile(String file) { VFSCache localCache = vfsCache; if (localCache != null) { localCache.accessFile(file); } } public static String getCachedFile(String path) { VFSCache localCache = vfsCache; if (localCache != null) { return localCache.map(path); } return path; } public static boolean load(TitleImpl title, boolean restart, BDJLoaderCallback callback) { // This method should be called only from ServiceContextFactory if (title == null) return false; synchronized (BDJLoader.class) { if (queue == null) queue = BDJActionQueue.create("BDJLoader"); } queue.put(new BDJLoaderAction(title, restart, callback)); return true; } public static boolean unload(BDJLoaderCallback callback) { // This method should be called only from ServiceContextFactory synchronized (BDJLoader.class) { if (queue == null) queue = BDJActionQueue.create("BDJLoader"); } queue.put(new BDJLoaderAction(null, false, callback)); return true; } protected static void shutdown() { try { if (queue != null) { queue.shutdown(); } } catch (Throwable e) { logger.error("shutdown() failed: " + e + "\n" + Logger.dumpStack(e)); } queue = null; vfsCache = null; } private static boolean loadN(TitleImpl title, boolean restart) { if (vfsCache == null) { vfsCache = VFSCache.createInstance(); } TitleInfo ti = title.getTitleInfo(); if (!ti.isBdj()) { logger.info("Not BD-J title - requesting HDMV title start"); unloadN(); return Libbluray.selectHdmvTitle(title.getTitleNum()); } try { // load bdjo Bdjo bdjo = Libbluray.getBdjo(ti.getBdjoName()); if (bdjo == null) throw new InvalidObjectException("bdjo not loaded"); AppEntry[] appTable = bdjo.getAppTable(); // reuse appProxys BDJAppProxy[] proxys = new BDJAppProxy[appTable.length]; AppsDatabase db = AppsDatabase.getAppsDatabase(); Enumeration ids = db.getAppIDs(new CurrentServiceFilter()); while (ids.hasMoreElements()) { AppID id = (AppID)ids.nextElement(); BDJAppProxy proxy = (BDJAppProxy)db.getAppProxy(id); AppEntry entry = (AppEntry)db.getAppAttributes(id); if (proxy == null) { logger.error("AppsDatabase corrupted!"); continue; } if (entry == null) { logger.error("AppsDatabase corrupted!"); proxy.release(); continue; } for (int i = 0; i < appTable.length; i++) { if (id.equals(appTable[i].getIdentifier()) && entry.getInitialClass().equals(appTable[i].getInitialClass())) { if (restart && appTable[i].getIsServiceBound()) { logger.info("Stopping xlet " + appTable[i].getInitialClass() + " (for restart)"); proxy.stop(true); } else { logger.info("Keeping xlet " + appTable[i].getInitialClass()); proxys[i] = proxy; proxy = null; } break; } } if (proxy != null) { logger.info("Terminating xlet " + entry.getInitialClass()); proxy.release(); } } // start bdj window GUIManager gui = GUIManager.createInstance(); TerminalInfo terminfo = bdjo.getTerminalInfo(); GraphicsResolution res = terminfo.getResolution(); gui.setDefaultFont(terminfo.getDefaultFont()); gui.setResizable(true); gui.setSize(res.getWidth(), res.getHeight()); gui.setVisible(true); Libbluray.setUOMask(terminfo.getMenuCallMask(), terminfo.getTitleSearchMask()); Libbluray.setKeyInterest(bdjo.getKeyInterestTable()); // initialize AppCaches if (vfsCache != null) { vfsCache.add(bdjo.getAppCaches()); } // initialize appProxys for (int i = 0; i < appTable.length; i++) { if (proxys[i] == null) { proxys[i] = BDJAppProxy.newInstance( new BDJXletContext( appTable[i], bdjo.getAppCaches(), gui)); /* log startup class, startup parameters and jar file */ String[] params = appTable[i].getParams(); String p = ""; if (params != null && params.length > 0) { p = "(" + StrUtil.Join(params, ",") + ")"; } logger.info("Loaded class: " + appTable[i].getInitialClass() + p + " from " + appTable[i].getBasePath() + ".jar"); } else { proxys[i].getXletContext().update(appTable[i], bdjo.getAppCaches()); logger.info("Reused class: " + appTable[i].getInitialClass() + " from " + appTable[i].getBasePath() + ".jar"); } } // change psr Libbluray.writePSR(Libbluray.PSR_TITLE_NUMBER, title.getTitleNum()); // notify AppsDatabase ((BDJAppsDatabase)BDJAppsDatabase.getAppsDatabase()).newDatabase(bdjo, proxys); // auto start playlist try { PlayListTable plt = bdjo.getAccessiblePlaylists(); if ((plt != null) && (plt.isAutostartFirst())) { logger.info("Auto-starting playlist"); String[] pl = plt.getPlayLists(); if (pl.length > 0) Manager.createPlayer(new MediaLocator(new BDLocator("bd://PLAYLIST:" + pl[0]))).start(); } } catch (Exception e) { logger.error("loadN(): autoplaylist failed: " + e + "\n" + Logger.dumpStack(e)); } // now run all the xlets for (int i = 0; i < appTable.length; i++) { int code = appTable[i].getControlCode(); if (code == AppEntry.AUTOSTART) { logger.info("Autostart xlet " + i + ": " + appTable[i].getInitialClass()); proxys[i].start(); } else if (code == AppEntry.PRESENT) { logger.info("Init xlet " + i + ": " + appTable[i].getInitialClass()); proxys[i].init(); } else { logger.info("Unsupported xlet code (" +code+") xlet " + i + ": " + appTable[i].getInitialClass()); } } logger.info("Finished initializing and starting xlets."); return true; } catch (Throwable e) { logger.error("loadN() failed: " + e + "\n" + Logger.dumpStack(e)); unloadN(); return false; } } private static boolean unloadN() { try { try { GUIManager.getInstance().setVisible(false); } catch (Error e) { } AppsDatabase db = AppsDatabase.getAppsDatabase(); /* stop xlets first */ Enumeration ids = db.getAppIDs(new CurrentServiceFilter()); while (ids.hasMoreElements()) { AppID id = (AppID)ids.nextElement(); BDJAppProxy proxy = (BDJAppProxy)db.getAppProxy(id); if (proxy != null) { proxy.stop(true); } } ids = db.getAppIDs(new CurrentServiceFilter()); while (ids.hasMoreElements()) { AppID id = (AppID)ids.nextElement(); BDJAppProxy proxy = (BDJAppProxy)db.getAppProxy(id); if (proxy != null) { proxy.release(); } } ((BDJAppsDatabase)db).newDatabase(null, null); PlayerManager.getInstance().releaseAllPlayers(true); return true; } catch (Throwable e) { logger.error("unloadN() failed: " + e + "\n" + Logger.dumpStack(e)); return false; } } private static class BDJLoaderAction extends BDJAction { public BDJLoaderAction(TitleImpl title, boolean restart, BDJLoaderCallback callback) { this.title = title; this.restart = restart; this.callback = callback; } protected void doAction() { boolean succeed; if (title != null) succeed = loadN(title, restart); else succeed = unloadN(); if (callback != null) callback.loaderDone(succeed); } private TitleImpl title; private boolean restart; private BDJLoaderCallback callback; } private static final Logger logger = Logger.getLogger(BDJLoader.class.getName()); private static BDJActionQueue queue = null; private static VFSCache vfsCache = null; }
package net.meisen.general.server.http.listener.util; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLDecoder; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import org.apache.http.Consts; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpRequest; import org.apache.http.util.EntityUtils; /** * Utility class when working with <code>HttpRequest</code> instances. * * @author pmeisen * */ public class RequestHandlingUtilities { private static final String PARAMETER_SEPARATOR = "&"; private static final String NAME_VALUE_SEPARATOR = "="; /** * Get the header information from the request. * * @param request * the request to read the header from * * @return the read header values */ public static Map<String, String> parseHeaders(final HttpRequest request) { final Map<String, String> parameters = new HashMap<String, String>(); for (final Header header : request.getAllHeaders()) { parameters.put(header.getName(), header.getValue()); } return parameters; } /** * Get the parameters of a <code>HttpRequest</code>. * * @param request * the <code>HttpRequest</code> to parse for parameters * * @return the found parameters, can never be <code>null</code> */ public static Map<String, String> parseParameter(final HttpRequest request) { final Map<String, String> parameters = new HashMap<String, String>(); final String method = request.getRequestLine().getMethod(); // get parameters can always be there parameters.putAll(parseGetParameter(request)); // add post parameters if ("POST".equals(method)) { parameters.putAll(parsePostParameter(request)); } return parameters; } /** * Parse all the post parameters from the request. The request stream is * closed after reading. * * @param request * the {@code HttpRequest} to read from * * @return the read parameters */ public static Map<String, String> parsePostParameter( final HttpRequest request) { // check the request if (request == null) { return new HashMap<String, String>(); } // For some reason, just putting the incoming entity into // the response will not work. We have to buffer the message. byte[] data; if (request instanceof HttpEntityEnclosingRequest) { final HttpEntity entity = ((HttpEntityEnclosingRequest) request) .getEntity(); try { data = EntityUtils.toByteArray(entity); } catch (final IOException e) { data = new byte[0]; } } else { data = new byte[0]; } return scanRawForParameters(new String(data)); } /** * Parse all the get parameters from the request * * @param request * the {@code HttpRequest} to read from * * @return the read parameters */ public static Map<String, String> parseGetParameter( final HttpRequest request) { // check the request if (request == null) { return new HashMap<String, String>(); } // get the URI final URI uri; try { uri = new URI(request.getRequestLine().getUri()); } catch (URISyntaxException e) { throw new IllegalStateException("Unexpected exception thrown", e); } // check the uri and it's raw query final String rawQuery; if (uri == null || (rawQuery = uri.getRawQuery()) == null) { return new HashMap<String, String>(); } // work with the retrieved URI return scanRawForParameters(rawQuery); } /** * Scans the passed {@code raw} string for parameters. * * @param raw * the string to be parsed * * @return the read parameters */ protected static Map<String, String> scanRawForParameters(final String raw) { final Map<String, String> parameters = new HashMap<String, String>(); final Scanner scanner = new Scanner(raw); scanner.useDelimiter(PARAMETER_SEPARATOR); // parse the parameter while (scanner.hasNext()) { final String token = scanner.next(); // get the position of the separator final int position = token.indexOf(NAME_VALUE_SEPARATOR); // get the name and the value final String name; final String value; if (position != -1) { name = token.substring(0, position).trim(); value = token.substring(position + 1).trim(); } else { name = token.trim(); value = null; } // add the parameter parameters.put(decode(name), decode(value)); } return parameters; } /** * Decodes the passed <code>value</code> using the default * <code>URLDecoder</code>. * * @param value * the encoded string * * @return the decoded string * * @see URLDecoder */ public static String decode(final String value) { if (value == null) { return value; } else { try { return URLDecoder.decode(value, Consts.UTF_8.toString()); } catch (final UnsupportedEncodingException e) { throw new IllegalStateException("Unexpected exception thrown", e); } } } }
package protocolsupport.protocol.pipeline.version; import java.util.List; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import protocolsupport.api.Connection; import protocolsupport.protocol.legacyremapper.LegacyAnimatePacketReorderer; import protocolsupport.protocol.packet.middle.ServerBoundMiddlePacket; import protocolsupport.protocol.serializer.ReplayingProtocolSupportSupportPacketDataSerializer; import protocolsupport.protocol.storage.NetworkDataCache; import protocolsupport.utils.netty.ReplayingDecoderBuffer.EOFSignal; import protocolsupport.utils.nms.NetworkListenerState; public class AbstractLegacyPacketDecoder extends AbstractPacketDecoder { public AbstractLegacyPacketDecoder(Connection connection, NetworkDataCache storage) { super(connection, storage); } private final ByteBuf cumulation = Unpooled.buffer(); private final ReplayingProtocolSupportSupportPacketDataSerializer serializer = new ReplayingProtocolSupportSupportPacketDataSerializer(connection.getVersion()); { serializer.setBuf(cumulation); } private final LegacyAnimatePacketReorderer animateReorderer = new LegacyAnimatePacketReorderer(); private ServerBoundMiddlePacket packetTransformer = null; @Override public void decode(ChannelHandlerContext ctx, ByteBuf input, List<Object> list) throws InstantiationException, IllegalAccessException { if (!input.isReadable()) { return; } cumulation.writeBytes(input); while (serializer.isReadable()) { if (!decode0(ctx.channel(), list)) { break; } } cumulation.discardSomeReadBytes(); } private boolean decode0(Channel channel, List<Object> list) throws InstantiationException, IllegalAccessException { serializer.markReaderIndex(); try { if (packetTransformer == null) { packetTransformer = registry.getTransformer(NetworkListenerState.getFromChannel(channel), serializer.readUnsignedByte()); } packetTransformer.readFromClientData(serializer); addPackets(animateReorderer.orderPackets(packetTransformer.toNative()), list); packetTransformer = null; return true; } catch (EOFSignal ex) { serializer.resetReaderIndex(); return false; } } }
package com.dstsystems.hackathon.autotempo.tempo; import com.dstsystems.hackathon.autotempo.models.WorklogModel; import com.dstsystems.hackathon.autotempo.utils.DateTestUtils; import org.junit.Before; import org.junit.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONCompareMode; import java.util.TimeZone; public class TempoSubmitterTest { private TempoSubmitter tempoSubmitter; private TempoConfig tempoConfig; @Before public void setUp() throws Exception { // Set timezone for CI server TimeZone.setDefault(TimeZone.getTimeZone("Asia/Bangkok")); tempoConfig = new TempoConfig(); tempoConfig.setUrl("http://localhost/"); tempoConfig.setUsername("myjirauser"); tempoConfig.setPassword("myjirapassword"); tempoSubmitter = new TempoSubmitter(tempoConfig); } @Test public void testGetWorklogJsonInternal() throws Exception { WorklogModel worklogModel = new WorklogModel(); worklogModel.setComment("My comment"); worklogModel.setIssueKey("INT-1"); worklogModel.setTimeSpent(3600); worklogModel.setDate(DateTestUtils.buildDate("2015-11-01")); worklogModel.setAccountKey("ATT01"); String expectedJson = "{\n" + " \"dateStarted\": \"2015-10-31T17:00:00.000Z\",\n" + " \"timeSpentSeconds\": 3600,\n" + " \"comment\": \"My comment\",\n" + " \"author\": {\n" + " \"name\": \"myjirauser\"\n" + " },\n" + " \"issue\": {\n" + " \"key\": \"INT-1\",\n" + " \"remainingEstimateSeconds\": 0\n" + " },\n" + " \"worklogAttributes\": [\n" + " {\n" + " \"key\": \"_account_\",\n" + " \"value\": \"ATT01\"\n" + " }\n" + " ]\n" + "}\n"; String json = tempoSubmitter.getWorklogJson(worklogModel); JSONAssert.assertEquals(expectedJson, json, JSONCompareMode.STRICT); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.laytonsmith.aliasengine.functions; import com.laytonsmith.aliasengine.MScriptComplete; import com.laytonsmith.aliasengine.functions.exceptions.ConfigCompileException; import com.laytonsmith.aliasengine.functions.exceptions.ConfigRuntimeException; import com.sk89q.commandhelper.CommandHelperPlugin; import org.bukkit.Location; import org.junit.Test; import org.bukkit.entity.Player; import org.bukkit.Server; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import static org.mockito.Mockito.*; import static com.laytonsmith.testing.StaticTest.*; import static org.junit.Assert.*; /** * * @author Layton */ public class PlayerManangementTest { Server fakeServer; Player fakePlayer; public PlayerManangementTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { fakeServer = GetFakeServer(); fakePlayer = GetOp("wraithguard01", fakeServer); when(fakePlayer.getServer()).thenReturn(fakeServer); CommandHelperPlugin.myServer = fakeServer; when(fakeServer.getPlayer(fakePlayer.getName())).thenReturn(fakePlayer); } @After public void tearDown() { } @Test public void testPlayer() throws ConfigCompileException{ String script = "player()"; assertEquals(fakePlayer.getName(), SRun(script, fakePlayer)); assertEquals("null", SRun(script, null)); } @Test public void testPlayer2() throws ConfigCompileException{ String script = "msg(player())"; ConsoleCommandSender c = GetFakeConsoleCommandSender(); Run(script, c); verify(c).sendMessage("~console"); } @Test public void testPlayer3() throws ConfigCompileException{ CommandSender c = GetFakeConsoleCommandSender(); assertEquals("~console", SRun("player()", c)); } @Test public void testAllPlayers() throws ConfigCompileException{ String script = "all_players()"; String done = SRun(script, fakePlayer); //This output is too long to test with msg() assertEquals("{wraithguard01, wraithguard02, wraithguard03}", done); } @Test public void testPloc() throws ConfigCompileException{ String script = "ploc()"; World w = GetWorld("world"); when(fakePlayer.getLocation()).thenReturn(new Location(w, 0, 1, 0)); when(fakePlayer.getWorld()).thenReturn(w); final StringBuilder done = new StringBuilder(); Run(script, fakePlayer, new MScriptComplete() { public void done(String output) { done.append(output); } }); assertEquals("{0.0, 0.0, 0.0, world}", done.toString()); } @Test public void testSetPloc() throws ConfigCompileException{ World w = GetWorld("world"); CommandHelperPlugin.myServer = fakeServer; when(fakeServer.getPlayer(fakePlayer.getName())).thenReturn(fakePlayer); when(fakePlayer.getWorld()).thenReturn(w); when(fakePlayer.getLocation()).thenReturn(new Location(w, 0, 0, 0)); Run("set_ploc(1, 1, 1)", fakePlayer); verify(fakePlayer).teleport(new Location(w, 1, 2, 1, 0, 0)); Run("set_ploc(array(2, 2, 2))", fakePlayer); verify(fakePlayer).teleport(new Location(w, 2, 3, 2, 0, 0)); Run("set_ploc('" + fakePlayer.getName() + "', 3, 3, 3)", fakePlayer); verify(fakePlayer).teleport(new Location(w, 3, 4, 3, 0, 0)); Run("set_ploc('" + fakePlayer.getName() + "', array(4, 4, 4))", fakePlayer); verify(fakePlayer).teleport(new Location(w, 4, 5, 4, 0, 0)); } @Test public void testPcursor() throws ConfigCompileException{ Block b = mock(Block.class); CommandHelperPlugin.myServer = fakeServer; when(fakeServer.getPlayer(fakePlayer.getName())).thenReturn(fakePlayer); when(fakePlayer.getTargetBlock(null, 200)).thenReturn(b); World w = mock(World.class); when(b.getWorld()).thenReturn(w); Run("pcursor()", fakePlayer); Run("pcursor('" + fakePlayer.getName() + "')", fakePlayer); verify(fakePlayer, times(2)).getTargetBlock(null, 200); } @Test public void testKill() throws ConfigCompileException{ Run("kill()", fakePlayer); Run("kill('" + fakePlayer.getName() + "')", fakePlayer); verify(fakePlayer, times(2)).setHealth(0); } //@Test public void testPgroup() throws ConfigCompileException{ Run("", fakePlayer); Run("", fakePlayer); } //@Test public void testPinfo(){ } //@Test public void testPworld(){ } //@Test public void testKick(){ } //@Test public void testSetDisplayName(){ } //@Test public void testResetDisplayName(){ } //@Test public void testPFacing(){ } //@Test public void testPinv(){ } //@Test public void testSetPinv(){ } }
package BlueTurtle.parsers; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import BlueTurtle.finders.ProjectInfoFinder; import BlueTurtle.warnings.PMDWarning; import BlueTurtle.warnings.Warning; /** * This class can be used to parse a PMD XML output file. * * @author BlueTurtle. * */ public class PMDXMLParser extends XMLParser { /** * Parse a PMD report file. * * @param xmlFilePath * the location of the PMD report. * @return a list of PMD warnings. */ @Override public List<Warning> parseFile(String xmlFilePath) { // List to store the warnings. List<Warning> pmdWarnings = new LinkedList<Warning>(); try { // Instantiate things that are necessary for the parser. File inputFile = new File(xmlFilePath); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Parse the file. Document doc = dBuilder.parse(inputFile); // Normalize the elements of the document. doc.getDocumentElement().normalize(); // Get all list of files where there are warnings. NodeList nList = doc.getElementsByTagName("file"); for (int i = 0; i < nList.getLength(); i++) { // Get the file from the list. Node file = nList.item(i); if (file.getNodeType() == Node.ELEMENT_NODE) { // Convert the node to an element. Element fileElement = (Element) file; // Get the path of the file where the warning is from. String filePath = fileElement.getAttribute("name"); // Get the name of the file where the warning is from. String fileName = filePath.substring(filePath.lastIndexOf("src") + 3, filePath.length()); //System.out.println(fileName); // Get all the warnings. NodeList warningList = fileElement.getElementsByTagName("violation"); addWarnings(fileName, warningList, pmdWarnings); } } } catch (Exception e) { e.printStackTrace(); } return pmdWarnings; } /** * add individual warning to the warningList. * * @param filePathis the file path of the warning * @param fileName is the file name of the warning. * @param warningList is a list of warnings. * @param pmdWarnings is list of PMD warnings. */ public void addWarnings(String fileName, NodeList warningList, List<Warning> pmdWarnings) { for (int j = 0; j < warningList.getLength(); j++) { // Get the warning from the list of warnings. Node warning = warningList.item(j); if (warning.getNodeType() == Node.ELEMENT_NODE) { // Convert the node to an element. Element warningElement = (Element) warning; // packageName of warning String packageName = warningElement.getAttribute("package"); // ruleSet of warning String ruleSet = warningElement.getAttribute("ruleset"); // method of warning String method = warningElement.getAttribute("method"); // line number where the warning is located. int line = Integer.parseInt(warningElement.getAttribute("beginline")); // Get the category of the warning. String ruleName = warningElement.getAttribute("rule"); // PMD rule name is a special concatenation of rule set and rule name String pmdRN = ruleSet.replace(" ", "").toLowerCase() + ".xml/" + ruleName; // find the correct classification given the rule name and the rule set. String classification = classify(pmdRN); // get the classPaths list from ProjectInfoFinder. ArrayList<String> classPaths = ProjectInfoFinder.getClassPaths(); // debug info System.out.println(" System.out.println("fileName:" + fileName); System.out.println("size of the stream: " + classPaths.size()); System.out.println(" //for-loop in stream, find correct filePath. String filePath = classPaths.stream().filter(p -> p.endsWith(fileName)).findFirst().get(); String filePathtemp = filePath; // Get the name of the file where the warning is from. String finalFileName = filePathtemp.substring(filePathtemp.lastIndexOf(File.separatorChar) + 1, filePathtemp.length()); // Add warning to the list of warnings. pmdWarnings.add(new PMDWarning(filePath, finalFileName, line, packageName, ruleSet, method, ruleName, classification)); } } } }
package org.chocosolver.samples.todo.problems.nqueen; import org.chocosolver.samples.AbstractProblem; import org.chocosolver.solver.variables.IntVar; import org.kohsuke.args4j.Option; import static org.chocosolver.solver.search.strategy.SearchStrategyFactory.minDomLBSearch; /** * <br/> * * @author Charles Prud'homme * @since 31/03/11 */ public abstract class AbstractNQueen extends AbstractProblem { @Option(name = "-q", usage = "Number of queens.", required = false) int n = 4; IntVar[] vars; @Override public void configureSearch() { model.getSolver().set(minDomLBSearch(vars)); } @Override public void solve() { model.solve(); } }
package net.bytten.metazelda; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Set; public class DungeonGenerator { private Random random; protected Dungeon dungeon; public DungeonGenerator(long seed) { random = new Random(seed); } protected Random getRandom() { return random; } public Dungeon getDungeon() { return dungeon; } // The actual core algorithm from // The choose* methods below control the decisions the algorithm makes. // Try tweaking the probabilities to see if you can produce better dungeons. // 'depth' is a count of how many rooms in the current chain have been // generated without any keys or locks. Subclasses may use this count to // optimize dungeons. public Room addItemPath(Symbol item, int depth) { // Add a new room to the dungeon containing the given item. Conditions // to enter the room are randomly generated, and if requiring a new item // in the dungeon, will cause other rooms to be added, too. Condition cond = null; // Choose condition to enter the room if (chooseCreateNewItem()) { // create a new condition and item for it Symbol elem = dungeon.makeNewItem(); cond = new Condition(elem); addItemPath(elem, 0); } else if (chooseReuseItem()) { // make the condition one which we've used before Symbol elem = choosePlacedItem(); if (elem != null) { cond = new Condition(elem); depth = 0; } } // Choose where to place the new room Room locRoom = null; Integer locD = null; if (chooseCreatePaddingRoom(depth)) { // Add padding rooms (and potentially more conditions and branches // along the way) locRoom = addItemPath(null, depth+1); locD = chooseAdjacentSpace(locRoom); // addItemPath can create a room with no adjacent spaces, so // loc.second (the direction to add the new room in) might still be // null. } if (locRoom == null || locD == null) { // Choose an existing room with a free edge locRoom = chooseExistingRoom(); locD = chooseAdjacentSpace(locRoom); } // Compute the new room's preconditions // (NB. cond is the condition to enter the room along the ingoing edge, // while precond is the set of all symbols that the player must be // holding to have reached the room) Condition precond = locRoom.getPrecond(); if (cond != null) { precond = precond.and(dungeon.precondClosure(cond)); } // Finally create the new room and link it to the parent room Room room = new Room(locRoom.coords.nextInDirection(locD), item, precond); synchronized (dungeon) { dungeon.add(room); dungeon.link(locRoom, room, cond); } linkNeighbors(room); return room; } protected void linkNeighbors(Room room) { Condition precond = room.getPrecond(); // for each neighboring room: for (int d = 0; d < Direction.NUM_DIRS; ++d) { Room neighbor = dungeon.get(room.coords.nextInDirection(d)); if (neighbor == null || dungeon.roomsAreLinked(room, neighbor)) continue; if (precond.equals(neighbor.getPrecond())) { // these two rooms have equivalent preconditions -- linking both // ways will not break any puzzles synchronized (dungeon) { dungeon.link(room, neighbor); } } else if (precond.implies(neighbor.getPrecond())) { if (chooseLinkNeighborOneWay(room, neighbor)) { // link from the new room to the neighbor. A link that way // won't break any puzzles, but a link back the other way // would! synchronized (dungeon) { dungeon.linkOneWay(room, neighbor); } } } } } private static final int MAX_ELEMS = 26; protected boolean chooseCreateNewItem() { return dungeon.itemCount() < MAX_ELEMS && getRandom().nextFloat() < 0.2; } protected boolean chooseReuseItem() { return getRandom().nextFloat() < 0.3; } protected boolean chooseCreatePaddingRoom(int depth) { return dungeon.roomCount() < 20 && getRandom().nextFloat() < 0.7; } protected boolean chooseLinkNeighborOneWay(Room room, Room neighbor) { return getRandom().nextFloat() < 0.3; } protected Symbol choosePlacedItem() { Set<Symbol> placedItems = dungeon.getPlacedItems(); if (placedItems.size() == 0) return null; int i = getRandom().nextInt(placedItems.size()); return new ArrayList<Symbol>(placedItems).get(i); } protected Room chooseExistingRoom() { List<Room> rooms = dungeon.computeBoundaryRooms(); return rooms.get(getRandom().nextInt(rooms.size())); } protected boolean newRoomAllowedInSpace(Coords xy) { return dungeon.get(xy) == null; } protected Integer chooseAdjacentSpace(Room room) { // Return a random direction of travel from room to an adjacent empty // space, or null if there are no nearby spaces int d = getRandom().nextInt(Direction.NUM_DIRS), tries = 0; Coords xy = room.coords.nextInDirection(d); while (!newRoomAllowedInSpace(xy) && tries < Direction.NUM_DIRS) { d = (d+1) % Direction.NUM_DIRS; ++tries; xy = room.coords.nextInDirection(d); } if (newRoomAllowedInSpace(xy)) return d; return null; } public Dungeon generate() { dungeon = new Dungeon(); Room startRoom = new Room(0,0, null, new Condition()); startRoom.setItem(new Symbol(Symbol.START)); dungeon.add(startRoom); addItemPath(new Symbol(Symbol.GOAL), 0); return dungeon; } }
package org.openlmis.referencedata.serializer; import static org.junit.Assert.assertEquals; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.ObjectMapper; import org.joda.money.CurrencyUnit; import org.joda.money.Money; import org.junit.Before; import org.junit.Test; import org.springframework.test.util.ReflectionTestUtils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; public class MoneyDeserializerTest { private ObjectMapper mapper; private MoneyDeserializer moneyDeserializer; @Before public void setup() { mapper = new ObjectMapper(); moneyDeserializer = new MoneyDeserializer(); ReflectionTestUtils.setField(moneyDeserializer, "currencyCode", "USD"); } @Test(expected = NumberFormatException.class) public void shouldNotDeserializeMoneyWhenValueEmpty() throws IOException { String json = String.format("{\"value\":%s}", "\"\""); deserializeMoney(json); } @Test public void shouldDeserializeMoney() throws IOException { String json = String.format("{\"value\":%s}", "\"10\""); Money money = deserializeMoney(json); assertEquals(new BigDecimal("10.00"), money.getAmount()); assertEquals(CurrencyUnit.USD, money.getCurrencyUnit()); } private Money deserializeMoney(String json) throws IOException { InputStream stream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)); JsonParser parser = mapper.getFactory().createParser(stream); parser.nextValue(); parser.nextValue(); DeserializationContext ctxt = mapper.getDeserializationContext(); return moneyDeserializer.deserialize(parser, ctxt); } }
package at.ac.ait.ubicity.voodoo; import at.ac.ait.ubicity.commons.exceptions.ExceptionHandler; import at.ac.ait.ubicity.commons.protocol.Medium; import org.json.JSONObject; /** * * @author jan van oort * @param <M> this Framer's implementation target, e.g. Twitter */ public interface Framer< M extends Medium >{ public MediumEdge<M> attemptEdge( JSONObject o ); public MediumEdge<M> attemptEdge( JSONObject o, ExceptionHandler exceptionCallback ); public MediumVertex<M> attemptVertex( JSONObject o ); public MediumVertex<M> attemptVertex( JSONObject o, ExceptionHandler exceptionCallback ); public Class<M> getMedium(); }
package cc.nsg.bukkit.syncnbt; import org.bukkit.Bukkit; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; /** * This class listens for events from Bukkit. * @author Stefan Berggren * */ public class Listeners implements Listener { SyncNBT plugin = null; public Listeners(SyncNBT plugin) { this.plugin = plugin; } /** * A player leaves the server, note that this event is only triggered with * a clean normal quit. */ @EventHandler public void playerLogout(PlayerQuitEvent event) { plugin.db.openConnection(); Player player = event.getPlayer(); plugin.db.lockPlayer(player.getName()); if (plugin.db.getSetting(player.getName()) == 2) { plugin.getLogger().info("Player " + player.getName() + " logout, saving data with mode 2"); new PlayerTicker(plugin, player.getName()).stopPlayerTicker(true); } else { plugin.getLogger().info("Player " + player.getName() + " logout, saving data with mode 1"); plugin.nbt.saveInventory(player); } plugin.db.unlockPlayer(player.getName()); } /** * A player logs in to the server, race conditions! */ @EventHandler public void playerLogin(PlayerJoinEvent event) { final Player player = event.getPlayer(); /* * Spawn a async thread and wait for the lock to clear */ new BukkitRunnable() { @Override public void run() { while(plugin.db.isPlayerLocked(player.getName())) { player.sendMessage("Items still locked by another server..."); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } // Call a sync thread to modify the world Bukkit.getScheduler().runTask(plugin, new Runnable() { @Override public void run() { if (plugin.db.getSetting(player.getName()) == 2) { plugin.getLogger().info("Player " + player.getName() + " login, saving data with mode 2"); new PlayerTicker(plugin, player.getName()).startPlayerTicker(); } else { plugin.getLogger().info("Player " + player.getName() + " login, saving data with mode 1"); plugin.nbt.restoreInventory(player); player.sendMessage("Your items are restored! New storage mode set."); plugin.db.setSetting(player.getName(), 2); } } }); } }.runTaskLaterAsynchronously(plugin, 20L); } }
package net.smoofyuniverse.epi.api; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import net.smoofyuniverse.common.app.App; import net.smoofyuniverse.common.download.ConnectionConfiguration; import net.smoofyuniverse.common.util.DownloadUtil; import net.smoofyuniverse.epi.EpiStats; import net.smoofyuniverse.logger.core.Logger; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.time.Instant; import java.util.*; public class PlayerInfo { public static final UUID EMPTY_UUID = new UUID(0, 0); public static final URL URL_BASE; private static final Logger logger = App.getLogger("PlayerInfo"); public final Map<String, Map<String, Double>> stats; public final UUID id; public final String name, guild; public final Instant date; public PlayerInfo(String name, UUID id, Instant date) { this(null, id, name, null, date); } public PlayerInfo(Map<String, Map<String, Double>> stats, UUID id, String name, String guild, Instant date) { this.stats = stats; this.id = id; this.name = name; this.guild = guild; this.date = date; } public static Optional<PlayerInfo> get(String playerName, boolean stats) { try { return Optional.of(read(playerName, stats)); } catch (IOException e) { String msg = e.getMessage(); if (msg != null && msg.startsWith("Invalid response code")) logger.error("Failed to get json content for player '" + playerName + "' (" + msg + ")"); else logger.error("Failed to get json content for player '" + playerName + "'", e); return Optional.empty(); } } public static PlayerInfo read(String playerName, boolean stats) throws IOException { return read(DownloadUtil.appendUrlSuffix(URL_BASE, playerName + (stats ? ".json?with=stats" : ".json")), App.get().getConnectionConfig(), Instant.now(), stats); } public static PlayerInfo read(URL url, ConnectionConfiguration config, Instant date, boolean stats) throws IOException { HttpURLConnection co = config.openHttpConnection(url); co.connect(); int code = co.getResponseCode(); if (code / 100 == 2) { try (JsonParser json = EpiStats.JSON_FACTORY.createParser(co.getInputStream())) { return read(json, date, stats); } } else throw new IOException("Invalid response code: " + code); } public static PlayerInfo read(JsonParser json, Instant date, boolean stats) throws IOException { if (json.nextToken() != JsonToken.START_OBJECT) throw new IOException("Expected to start an new object"); Map<String, Map<String, Double>> statsMap = null; String name = null, guild = null; UUID id = null; while (json.nextToken() != JsonToken.END_OBJECT) { String field = json.getCurrentName(); if (field.equals("player_uuid")) { if (json.nextToken() != JsonToken.VALUE_STRING) throw new JsonParseException(json, "Field 'player_uuid' was expected to be a string"); id = idFromString(json.getValueAsString()); continue; } if (field.equals("player_name")) { if (json.nextToken() != JsonToken.VALUE_STRING) throw new JsonParseException(json, "Field 'player_name' was expected to be a string"); name = json.getValueAsString(); continue; } if (field.equals("guild")) { if (json.nextToken() == JsonToken.VALUE_NULL) { guild = null; continue; } if (json.currentToken() != JsonToken.START_OBJECT) throw new JsonParseException(json, "Field 'guild' was expected to be an object"); while (json.nextToken() != JsonToken.END_OBJECT) { String field2 = json.getCurrentName(); if (field2.equals("name")) { if (json.nextToken() != JsonToken.VALUE_STRING) throw new JsonParseException(json, "Field 'name' of the guild was expected to be a string"); guild = json.getValueAsString(); continue; } json.nextToken(); json.skipChildren(); } continue; } if (stats && field.equals("stats")) { if (json.nextToken() != JsonToken.START_OBJECT) throw new JsonParseException(json, "Field 'stats' was expected to be an object"); statsMap = new HashMap<>(); while (json.nextToken() != JsonToken.END_OBJECT) { Map<String, Double> map = new HashMap<>(); statsMap.put(json.getCurrentName(), Collections.unmodifiableMap(map)); if (json.nextToken() != JsonToken.START_OBJECT) throw new JsonParseException(json, "Subfield in 'stats' was expected to be an object"); while (json.nextToken() != JsonToken.END_OBJECT) { String field2 = json.getCurrentName(); json.nextToken(); map.put(field2, json.getDoubleValue()); } } continue; } json.nextToken(); json.skipChildren(); } if (stats && statsMap == null) throw new IllegalArgumentException("Field 'stats' is missing"); if (name == null) throw new IllegalArgumentException("Field 'name' is missing"); if (id == null) throw new IllegalArgumentException("Field 'player_uuid' is missing"); return new PlayerInfo(stats ? Collections.unmodifiableMap(statsMap) : null, id, name, guild, date); } public static UUID idFromString(String v) { return UUID.fromString(v.replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5")); } public static Optional<PlayerInfo> get(UUID playerId, boolean stats) { try { return Optional.of(read(playerId, stats)); } catch (IOException e) { String msg = e.getMessage(); if (msg != null && msg.startsWith("Invalid response code")) logger.error("Failed to get json content for player '" + playerId + "' (" + msg + ")"); else logger.error("Failed to get json content for player '" + playerId + "'", e); return Optional.empty(); } } public static PlayerInfo read(UUID playerId, boolean stats) throws IOException { return read(DownloadUtil.appendUrlSuffix(URL_BASE, idToString(playerId) + (stats ? ".json?with=stats" : ".json")), App.get().getConnectionConfig(), Instant.now(), stats); } public static String idToString(UUID id) { return id.toString().replace("-", ""); } static { try { URL_BASE = new URL("https://stats.epicube.fr/player/"); } catch (MalformedURLException e) { throw new RuntimeException(e); } } }
package com.akiban.cserver.store; import java.util.List; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.io.File; import java.io.FileOutputStream; import com.akiban.cserver.FieldDef; import com.akiban.cserver.RowData; import com.akiban.cserver.RowDef; import com.akiban.cserver.RowDefCache; import com.persistit.Exchange; import com.persistit.Key; import com.persistit.exception.PersistitException; import com.akiban.vstore.ColumnArray; import com.akiban.vstore.ColumnDescriptor; import com.akiban.vstore.VMeta; /** * @author percent * @author posulliv */ public class VStore implements Store { public void setHStore(Store hstore) { this.hstore = hstore; } public Store getHStore() { return hstore; } /** * @see com.akiban.cserver.store.Store#deleteRow(com.akiban.cserver.RowData) */ @Override public int deleteRow(RowData rowData) throws Exception { return hstore.deleteRow(rowData); } /** * @see com.akiban.cserver.store.Store#dropSchema(java.lang.String) */ @Override public int dropSchema(String schemaName) throws Exception { return hstore.dropSchema(schemaName); } /** * @see com.akiban.cserver.store.Store#dropTable(int) */ @Override public int dropTable(int rowDefId) throws Exception { return hstore.dropTable(rowDefId); } /** * @see com.akiban.cserver.store.Store#fetchRows(java.lang.String, * java.lang.String, java.lang.String, java.lang.Object, * java.lang.Object, java.lang.String) */ @Override public List<RowData> fetchRows(String schemaName, String tableName, String columnName, Object least, Object greatest, String leafTableName) throws Exception { return hstore.fetchRows(schemaName, tableName, columnName, least, greatest, leafTableName); } /** * @see com.akiban.cserver.store.Store#getAutoIncrementValue(int) */ @Override public long getAutoIncrementValue(int rowDefId) throws Exception { return hstore.getAutoIncrementValue(rowDefId); } /** * @see com.akiban.cserver.store.Store#getCurrentRowCollector(int) */ @Override public RowCollector getCurrentRowCollector(int tableId) { return hstore.getCurrentRowCollector(tableId); } /** * @see com.akiban.cserver.store.Store#getRowCount(boolean, * com.akiban.cserver.RowData, com.akiban.cserver.RowData, byte[]) */ @Override public long getRowCount(boolean exact, RowData start, RowData end, byte[] columnBitMap) throws Exception { return hstore.getRowCount(exact, start, end, columnBitMap); } /** * @see com.akiban.cserver.store.Store#getRowDefCache() */ @Override public RowDefCache getRowDefCache() { return hstore.getRowDefCache(); } /** * @see com.akiban.cserver.store.Store#getTableStatistics(int) */ @Override public TableStatistics getTableStatistics(int tableId) throws Exception { return hstore.getTableStatistics(tableId); } /** * @see com.akiban.cserver.store.Store#isVerbose() */ @Override public boolean isVerbose() { return hstore.isVerbose(); } /** * @see com.akiban.cserver.store.Store#newRowCollector(int, int, int, * com.akiban.cserver.RowData, com.akiban.cserver.RowData, byte[]) */ @Override public RowCollector newRowCollector(int rowDefId, int indexId, int scanFlags, RowData start, RowData end, byte[] columnBitMap) throws Exception { return hstore.newRowCollector(rowDefId, indexId, scanFlags, start, end, columnBitMap); } /** * @see com.akiban.cserver.store.Store#setOrdinals() */ @Override public void setOrdinals() throws Exception { hstore.setOrdinals(); } /** * @see com.akiban.cserver.store.Store#setVerbose(boolean) */ @Override public void setVerbose(boolean verbose) { } /** * @see com.akiban.cserver.store.Store#shutDown() */ @Override public void shutDown() throws Exception { } /** * @see com.akiban.cserver.store.Store#startUp() */ @Override public void startUp() throws Exception { } /** * @see com.akiban.cserver.store.Store#truncateTable(int) */ @Override public int truncateTable(int rowDefId) throws Exception { return hstore.truncateTable(rowDefId); } /** * @see com.akiban.cserver.store.Store#updateRow(com.akiban.cserver.RowData, * com.akiban.cserver.RowData) */ @Override public int updateRow(RowData oldRowData, RowData newRowData) throws Exception { return hstore.updateRow(oldRowData, newRowData); } /** * @see com.akiban.cserver.store.Store#writeRow(com.akiban.cserver.RowData) */ @Override public int writeRow(RowData rowData) throws Exception { return hstore.writeRow(rowData); } public void constructColumnDescriptors() throws Exception { columnArrays = new ArrayList<ColumnArray>(); columnDescriptors = new ArrayList<ColumnDescriptor>(); for (Map.Entry<String, String> entry : columnList.entrySet()) { try { File columnData = new File(entry.getValue()); ColumnArray colArr = new ColumnArray(columnData); columnArrays.add(colArr); ColumnInfo info = columnInfo.get(entry.getKey()); // XXX - schema name is required ColumnDescriptor descrip = new ColumnDescriptor(null, info.getTableName(), info.getColumnName(), info.getTableId(), info.getOrdinal(), info.getSize(), info.getCount()); columnDescriptors.add(descrip); } catch (Exception e) { e.printStackTrace(); } } /* hard-code metadata file name for now */ String metaFileName = datapath + "/vstoreMetaFile"; File metaFile = new File(metaFileName); VMeta vmeta = new VMeta(columnDescriptors); vmeta.write(metaFile); } public ArrayList<ColumnDescriptor> getColumnDescriptors() { return columnDescriptors; } public List<ColumnArray> getColumnArrays() { return columnArrays; } /** * @see com.akiban.cserver.store.Store#writeRowForBulkLoad(com.persistit.Exchange, * com.akiban.cserver.RowDef, com.akiban.cserver.RowData, int[], * com.akiban.cserver.FieldDef[][], java.lang.Object[][]) */ @Override public int writeRowForBulkLoad(final Exchange hEx, final RowDef rowDef, final RowData rowData, final int[] ordinals, FieldDef[][] fieldDefs, Object[][] hKeyValues) throws Exception { final Key hkey = constructHKey(rowDef, ordinals, fieldDefs, hKeyValues); String schemaName = rowDef.getSchemaName(); /* * First check if a directory exists for this table. If not, then create it. */ int tableId = rowDef.getRowDefId(); String tableName = rowDef.getTableName(); String tableDirectory = datapath + "/" + tableName; File tableData = new File(tableDirectory); if (! tableData.exists()) { boolean ret = tableData.mkdir(); if (! ret) { throw new Exception(); } } /* column for the hkey. */ String hkeyColumnPath = tableDirectory + "/hkeyColumn"; File hkeyColumn = new File(hkeyColumnPath); if (! hkeyColumn.exists()) { boolean ret = hkeyColumn.createNewFile(); if (! ret) { throw new Exception(); } FileOutputStream fout = new FileOutputStream(hkeyColumn, true); fout.write(hkey.getEncodedBytes()); /* write the key's bytes to disk */ } /* * Go through each column in this row and ensure that a file exists for that column. For * now, we have 1 file per column by default. If a file does not exist, then create it. * @todo: for now, the name used per file is the column name. Need to discuss if this needs * to be changed or not. */ for (int i = 0; i < fieldDefs.length; i++) { FieldDef[] tableFieldDefs = fieldDefs[i]; for (int j = 0; j < tableFieldDefs.length; j++) { FieldDef field = tableFieldDefs[j]; String columnName = field.getName(); String columnFileName = tableDirectory + "/" + columnName; File columnData = new File(columnFileName); if (! columnData.exists()) { boolean ret = columnData.createNewFile(); if (! ret) { throw new Exception(); } columnList.put(columnName, columnFileName); ColumnInfo info = new ColumnInfo(columnName, tableName, schemaName, tableId, i); columnInfo.put(columnName, info); } ColumnInfo info = columnInfo.get(columnName); /* @todo: temporary only */ /* insert the data */ final long locationAndSize = rowDef.fieldLocation(rowData, j); if (0 == locationAndSize) { /* NULL field. @todo: how do we handle NULL's in the V store? */ } int offset = (int) locationAndSize; int size = (int) (locationAndSize >>> 32); byte[] bytes = rowData.getBytes(); FileOutputStream fout = new FileOutputStream(columnData, true); fout.write(bytes, offset, size); info.incrementCount(); info.setSize(size); columnInfo.put(columnName, info); } } return 0; } private Key constructHKey(final RowDef rowDef, final int[] ordinals, final FieldDef[][] fieldDefs, final Object[][] hKeyValues) throws Exception { final Key hKey = new Key(((PersistitStore) hstore).getDb()); hKey.clear(); for (int i = 0; i < hKeyValues.length; i++) { hKey.append(ordinals[i]); Object[] tableHKeyValues = hKeyValues[i]; FieldDef[] tableFieldDefs = fieldDefs[i]; for (int j = 0; j < tableHKeyValues.length; j++) { tableFieldDefs[j].getEncoding().toKey(tableFieldDefs[j], tableHKeyValues[j], hKey); } } return hKey; } @Override public void updateTableStats(RowDef rowDef, long rowCount) throws PersistitException, StoreException { hstore.updateTableStats(rowDef, rowCount); } public static void setDataPath(final String path) { datapath = path; } /* * Temporary class only being used for testing purposes right now to carry metadata about * columns. Once the metadata for column is actually stored in some kind of header on disk, we * shouldn't need this class anymore. */ class ColumnInfo { public ColumnInfo(int columnSize) { this.columnSize = columnSize; this.count = 0; } public ColumnInfo(String columnName, String tableName, String schemaName, int tableId, int ordinal) { this.tableId = tableId; this.ordinal = ordinal; this.columnSize = 0; this.count = 0; this.columnName = columnName; this.tableName = tableName; this.schemaName = schemaName; } public ColumnInfo() { this.columnSize = 0; this.count = 0; } public void incrementCount() { count++; } public void setSize(int size) { if (0 == columnSize) { columnSize = size; } } public int getSize() { return columnSize; } public int getCount() { return count; } public int getTableId() { return tableId; } public int getOrdinal() { return ordinal; } public String getSchemaName() { return schemaName; } public String getTableName() { return tableName; } public String getColumnName() { return columnName; } private int tableId; private int ordinal; private int columnSize; private int count; private String schemaName; private String tableName; private String columnName; } private Store hstore; static String datapath = "/tmp/chunkserver_data"; private HashMap<String, String> columnList = new HashMap<String, String>(); private HashMap<String, ColumnInfo> columnInfo = new HashMap<String, ColumnInfo>(); private List<ColumnArray> columnArrays; private ArrayList<ColumnDescriptor> columnDescriptors; }
package controllers; import java.util.ArrayList; import views.grid.GridWorld; import exceptions.IllegalValueException; import models.Coordinate; import models.campaign.KarelCode; import models.campaign.Level; import models.campaign.World; import models.gridobjects.creatures.Creature; /** * An object to go through and execute the Karel code * */ public class Interpreter { /** * The karel code to parse through */ private ArrayList<String> karelCode; /** * The current position of the executing code */ private int activeCodeBlock; /** * The world that the code should be executed in */ private World world; /** * Constructor for the parser * * @param karelCode the Karel code to parse and execute * @param world the world where to execute the karel code */ public Interpreter(ArrayList<String> karelCode, World world){ this.karelCode = karelCode; this.world = world; GridWorld.getInstance().setWorld(this.world); } /** * Moves onto the next code block WITHOUT executing it */ public boolean next(){ this.activeCodeBlock++; return this.activeCodeBlock < this.karelCode.size(); } public boolean validPosition(){ return this.activeCodeBlock < this.karelCode.size(); } /** * Moves to the previous code block WITHOUT executing it */ public int previous(){ this.activeCodeBlock return this.activeCodeBlock; } /** * Executes the current code block and then moves to the next one */ public void executeOne(){ this.instruction(); } /** * Set the position of the active code block * * @param activeCodeBlock the new position for the active code block */ public int setPosition(int activeCodeBlock){ this.activeCodeBlock = activeCodeBlock; return this.activeCodeBlock; } /** * Resets the parser back to the first code block */ public void reset(){ this.activeCodeBlock = 0; } /** * Executes all the code */ public void executeAll(){ } /** * Changes the karelCode and resets the activeCodeBlock * * @param karelCode the new Karel Code to execute */ public void changeKarelCode(ArrayList<String> karelCode){ this.karelCode = karelCode; } public void start(){ instructions(); } public void instructions(){ System.out.println("Instructions: " + this.karelCode.get(this.activeCodeBlock)); instruction(); if(!validPosition()) return; if(this.karelCode.get(this.activeCodeBlock).equals(KarelCode.CLOSESTATEMENT)) return; if(this.karelCode.get(this.activeCodeBlock).equals(KarelCode.ENDIF)) return; if(this.karelCode.get(this.activeCodeBlock).equals(KarelCode.ENDELSE)) return; if(this.karelCode.get(this.activeCodeBlock).equals(KarelCode.ENDWHILE)) return; if(this.karelCode.get(this.activeCodeBlock).equals(KarelCode.ENDLOOP)) return; instructions(); } public void instruction(){ System.out.println("Instruction: " + this.karelCode.get(this.activeCodeBlock)); switch(this.karelCode.get(this.activeCodeBlock)){ //end statements case KarelCode.ENDIF: case KarelCode.ENDWHILE: case KarelCode.ENDELSE: case KarelCode.ENDLOOP: this.next(); return; //close statements case KarelCode.CLOSESTATEMENT: return; //repetitions case KarelCode.LOOPSTATEMENT: case KarelCode.WHILESTATEMENT: repetition(); this.next(); break; //conditionals case KarelCode.IFSTATEMENT: conditional(); this.next(); break; //operations case KarelCode.MOVE: case KarelCode.WAKEUP: case KarelCode.SLEEP: case KarelCode.TURNLEFT: case KarelCode.PICKBAMBOO: case KarelCode.PUTBAMBOO: operation(); this.next(); break; default: throw new IllegalValueException("Illegal Karel Code Segment: " + this.karelCode.get(this.activeCodeBlock)); } } public void repetition(){ System.out.println("Repetition: " + this.karelCode.get(this.activeCodeBlock)); switch(this.karelCode.get(this.activeCodeBlock)){ case KarelCode.WHILESTATEMENT: if(!this.next()) throw new IllegalValueException("Ill formed Karel Code"); int variableCode = this.activeCodeBlock; boolean result = variable(); while(result){ if(!this.next()) return; instructions(); this.activeCodeBlock = variableCode; result = variable(); } if(!result){ do{ if(!this.next()) throw new IllegalValueException("Ill formed Karel Code"); }while(!this.karelCode.get(this.activeCodeBlock).equals(KarelCode.ENDWHILE)); } break; case KarelCode.LOOPSTATEMENT: if(!this.next()) throw new IllegalValueException("Ill formed Karel Code"); int times = positiveNumbers(); int currentInstruction = this.activeCodeBlock; for(int counter = 0; counter < times; counter++){ this.activeCodeBlock = currentInstruction; instructions(); } break; default: throw new IllegalValueException("Ill formed Karel Code" + this.karelCode.get(this.activeCodeBlock)); } } public void conditional(){ //if statement System.out.println("Conditional: " + this.karelCode.get(this.activeCodeBlock)); System.out.println("Conditional: CURRENT LOCATION: " + this.world.getEve().getCoordinates()); if(!this.karelCode.get(this.activeCodeBlock).equals(KarelCode.IFSTATEMENT)) return; //error if(!this.next()) throw new IllegalValueException("Ill formed code"); if(!this.karelCode.get(this.activeCodeBlock).equals(KarelCode.CLOSESTATEMENT)) return; if(!this.next()) throw new IllegalValueException("Ill formed code"); System.out.println("Conditional (variable): " + this.karelCode.get(this.activeCodeBlock)); boolean result = variable(); if(result){ if(!this.next()) throw new IllegalValueException("Ill formed Karel Code"); instructions(); } else{ do{ this.next(); }while(!this.karelCode.get(this.activeCodeBlock).equals(KarelCode.ENDIF)); System.out.println("Conditional (variable false): " + this.karelCode.get(this.activeCodeBlock)); } if(!this.next()) return; System.out.println("Conditional (else check): " + this.karelCode.get(this.activeCodeBlock)); if(this.karelCode.get(this.activeCodeBlock).equals(KarelCode.ELSESTATEMENT) && !result){ if(!this.next()) throw new IllegalValueException("Ill formed Karel Code"); instructions(); } if(this.karelCode.get(this.activeCodeBlock).equals(KarelCode.ELSESTATEMENT)&& result){ do{ this.next(); }while(!this.karelCode.get(this.activeCodeBlock).equals(KarelCode.ENDIF)); } System.out.println("Conditional (end): " + this.karelCode.get(this.activeCodeBlock)); } public void operation(){ if(!this.world.getEve().isAwake()){ if(this.karelCode.get(this.activeCodeBlock).equals(KarelCode.WAKEUP)){ this.world.getEve().setAwake(true); } else{ return; } } System.out.println("OPERATION: CURRENT LOCATION: " + this.world.getEve().getCoordinates()); switch(this.karelCode.get(this.activeCodeBlock)){ case KarelCode.MOVE: this.world.moveEve(); return; case KarelCode.TURNLEFT: this.world.getEve().turnLeft(); return; case KarelCode.SLEEP: this.world.getEve().setAwake(false); return; case KarelCode.PUTBAMBOO: this.world.evePutBamboo(); return; case KarelCode.PICKBAMBOO: this.world.evePickBamboo(); return; default: throw new IllegalValueException("Ill forme Karel Code"); } } public boolean variable(){ System.out.println("VARIABLE: CURRENT DIRECTION: " + this.world.getEve().getDirection()); System.out.println("VARIABLE: CURRENT LOCATION: " + this.world.getEve().getCoordinates()); switch(this.karelCode.get(this.activeCodeBlock)){ case KarelCode.FRONTISCLEAR: return this.world.frontIsClear(); case KarelCode.BAGISEMPTY: return !this.world.getEve().hasBamboo(); case KarelCode.FACINGNORTH: return this.world.getEve().getDirection() == Coordinate.UP; case KarelCode.FACINGSOUTH: return this.world.getEve().getDirection() == Coordinate.DOWN; case KarelCode.FACINGEAST: return this.world.getEve().getDirection() == Coordinate.RIGHT; case KarelCode.FACINGWEST: return this.world.getEve().getDirection() == Coordinate.LEFT; default: throw new IllegalValueException("Ill formed Karel Code " + this.karelCode.get(this.activeCodeBlock)); } } public int positiveNumbers(){ String number = ""; do{ number += this.karelCode.get(this.activeCodeBlock); if(!this.next()) throw new IllegalValueException("Ill formed Karel Code"); }while(!this.karelCode.get(this.activeCodeBlock).equals(KarelCode.CLOSESTATEMENT)); return Integer.parseInt(number); } public static void main(String[] args){ World world = new World("test_world",5, 5); Level level = new Level(world, "testing the parser"); if(world.addCreature(new Creature("Eve", new Coordinate(0,0)))) System.out.println("added eve"); else System.out.println("unable to add eve"); level.addKarelCode(KarelCode.MOVE); Interpreter interpreter = new Interpreter(level.getKarelCode(), world); if(world.getEve() == null) return; world.printWorld(); interpreter.executeOne(); System.out.println("Active Code Block: " + interpreter.activeCodeBlock + "total size: " + level.getKarelCode().size()); world.printWorld(); } }
package app.hongs; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public abstract class CoreSerial implements Serializable { /** * * @param path * @param name * @param time * @throws app.hongs.HongsException */ public CoreSerial(String path, String name, long time) throws HongsException { this.init(path, name, time); } /** * * @param path * @param name * @param date * @throws app.hongs.HongsException */ public CoreSerial(String path, String name, Date date) throws HongsException { this.init(path, name, date); } /** * * @param name * @param time * @throws app.hongs.HongsException */ public CoreSerial(String name, long time) throws HongsException { this.init(name, time); } /** * * @param name * @param date * @throws app.hongs.HongsException */ public CoreSerial(String name, Date date) throws HongsException { this.init(name, date); } /** * * @param name * @throws app.hongs.HongsException */ public CoreSerial(String name) throws HongsException { this.init(name); } /** * (init) */ public CoreSerial() { // TODO: init } /** * * @throws app.hongs.HongsException */ abstract protected void imports() throws HongsException; /** * * @param time * @return true * @throws app.hongs.HongsException */ protected boolean expired(long time) throws HongsException { return time != 0 && time < System.currentTimeMillis(); } /** * () * @param path * @param name * @param time * @throws app.hongs.HongsException */ protected final void init(String path, String name, long time) throws HongsException { if (path == null) { path = Core.DATA_PATH + File.separator + "serial"; } File file = new File(path + File.separator + name + ".ser"); this.load(file, time + file.lastModified( )); } /** * () * @param path * @param name * @param date * @throws app.hongs.HongsException */ protected final void init(String path, String name, Date date) throws HongsException { if (path == null) { path = Core.DATA_PATH + File.separator + "serial"; } File file = new File(path + File.separator + name + ".ser"); this.load(file, date!=null?date.getTime():0); } protected final void init(String name, long time) throws HongsException { this.init(null, name, time); } protected final void init(String name, Date date) throws HongsException { this.init(null, name, date); } protected final void init(String name) throws HongsException { this.init(null, name, null); } /** * * @param file * @param time * @throws app.hongs.HongsException */ protected void load(File file, long time) throws HongsException { ReadWriteLock rwlock = lock(file.getAbsolutePath()); Lock lock; lock = rwlock. readLock(); lock.lock(); try { if (file.exists() && !expired(time)) { load(file); return; } } finally { lock.unlock( ); } lock = rwlock.writeLock(); lock.lock(); try { imports( ); save(file); } finally { lock.unlock( ); } } /** * * @param file * @throws app.hongs.HongsException */ protected final void load(File file) throws HongsException { try { FileInputStream fis = null; ObjectInputStream ois = null; try { fis = new FileInputStream(file); ois = new ObjectInputStream(fis ); Map map = (Map) ois.readObject( ); load( map ); } finally { if (ois != null) ois.close(); if (fis != null) fis.close(); } } catch (ClassNotFoundException ex) { throw new HongsException(0x10d8, ex); } catch (FileNotFoundException ex) { throw new HongsException(0x10d6, ex); } catch (IOException ex) { throw new HongsException(0x10d4, ex); } } /** * * @param file * @throws app.hongs.HongsException */ protected final void save(File file) throws HongsException { if (!file.exists()) { File dn = file.getParentFile( ); if (!dn.exists()) { dn.mkdirs(); } try { file.createNewFile( ); } catch (IOException e) { throw new HongsException(0x10d0,e); } } try { FileOutputStream fos = null; ObjectOutputStream oos = null; try { fos = new FileOutputStream(file); oos = new ObjectOutputStream(fos ); Map map = new HashMap(); save( map ); oos.writeObject ( map ); oos.flush(); } finally { if (oos != null) oos.close(); if (fos != null) fos.close(); } } catch (FileNotFoundException ex) { throw new HongsException(0x10d6, ex); } catch (IOException ex) { throw new HongsException(0x10d2, ex); } } /** * * @param map * @throws app.hongs.HongsException */ protected void load(Map<String, Object> map) throws HongsException { Field[] fields; Class clazz = getClass(); fields = clazz.getFields(); for (Field field : fields) { int ms = field.getModifiers(); if (Modifier.isTransient(ms ) || Modifier.isStatic(ms ) || Modifier.isFinal (ms)) { continue; } String name = field.getName(); try { field.set(this, map.get(name)); } catch (IllegalAccessException e) { throw new HongsException(0x10da, e); } catch (IllegalArgumentException e) { throw new HongsException(0x10da, e); } } fields = clazz.getDeclaredFields(); for (Field field : fields) { int ms = field.getModifiers(); if (Modifier.isTransient(ms ) || Modifier.isPublic(ms ) || Modifier.isStatic(ms ) || Modifier.isFinal (ms)) { continue; } String name = field.getName(); field.setAccessible ( true ); try { field.set(this, map.get(name)); } catch (IllegalAccessException e) { throw new HongsException(0x10da, e); } catch (IllegalArgumentException e) { throw new HongsException(0x10da, e); } } } /** * * @param map * @throws HongsException */ protected void save(Map<String, Object> map) throws HongsException { Field[] fields; Class clazz = getClass(); fields = clazz.getFields(); for (Field field : fields) { int ms = field.getModifiers(); if (Modifier.isTransient(ms ) || Modifier.isStatic(ms ) || Modifier.isFinal (ms)) { continue; } String name = field.getName(); try { map.put(name, field.get(this)); } catch (IllegalAccessException e) { throw new HongsException(0x10da, e); } catch (IllegalArgumentException e) { throw new HongsException(0x10da, e); } } fields = clazz.getDeclaredFields(); for (Field field : fields) { int ms = field.getModifiers(); if (Modifier.isTransient(ms ) || Modifier.isPublic(ms ) || Modifier.isStatic(ms ) || Modifier.isFinal (ms)) { continue; } String name = field.getName(); field.setAccessible ( true ); try { map.put(name, field.get(this)); } catch (IllegalAccessException e) { throw new HongsException(0x10da, e); } catch (IllegalArgumentException e) { throw new HongsException(0x10da, e); } } } private ReadWriteLock lock(String flag) { ReadWriteLock rwlock; Lock lock; lock = lockr. readLock(); lock.lock(); try { rwlock = locks.get(flag); if (rwlock != null) { return rwlock; } } finally { lock.unlock(); } lock = lockr.writeLock(); lock.lock(); try { rwlock = new ReentrantReadWriteLock(); locks.put(flag, rwlock); return rwlock; } finally { lock.unlock(); } } private static Map<String, ReadWriteLock> locks = new HashMap( ); private static ReadWriteLock lockr = new ReentrantReadWriteLock(); }
package org.bioconsensus.kbase; import com.thinkaurelius.titan.core.TitanGraph; import com.thinkaurelius.titan.core.TitanTransaction; import com.thinkaurelius.titan.core.TransactionBuilder; import com.thinkaurelius.titan.core.util.TitanCleanup; import org.junit.Test; import org.ms2ms.graph.Graphs; import org.ms2ms.graph.PropertyNode; import org.ms2ms.nosql.Titans; import org.ms2ms.test.TestAbstract; import java.util.Map; public class UniprotTest01 extends TestAbstract { @Test public void readUniprot() throws Exception { TitanGraph g = Titans.openHBaseGraph(); // TransactionBuilder tx = g.buildTransaction(); // tx.enableBatchLoading(); // TitanTransaction t = tx.start(); g.shutdown(); TitanCleanup.clear(g); // Graphs.clear(g); g = Titans.openHBaseGraph(); UniprotHandler uniprot = new UniprotHandler(g, "Homo sapiens"); // uniprot.parseDocument("/home/wyu/Projects/molgraph/data/up1k.xml"); uniprot.parseDocument("/media/data/import/bio4j/uniprot_sprot.xml"); g.shutdown(); } @Test public void readVertices() throws Exception { TitanGraph g = Titans.openHBaseGraph(); Map<String, PropertyNode> tag_node = Graphs.getVertices( g.buildTransaction().start(), "gene"); g.shutdown(); } }
package com.bladecoder.ink.runtime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.bladecoder.ink.runtime.SimpleJson.Writer; public class Flow { public String name; public CallStack callStack; public List<RTObject> outputStream; public List<Choice> currentChoices; public Flow(String name, Story story) { this.name = name; this.callStack = new CallStack(story); this.outputStream = new ArrayList<>(); this.currentChoices = new ArrayList<>(); } @SuppressWarnings("unchecked") public Flow(String name, Story story, HashMap<String, Object> jObject) throws Exception { this.name = name; this.callStack = new CallStack(story); this.callStack.setJsonToken((HashMap<String, Object>) jObject.get("callstack"), story); this.outputStream = Json.jArrayToRuntimeObjList((List<Object>) jObject.get("outputStream")); this.currentChoices = Json.jArrayToRuntimeObjList((List<Object>) jObject.get("currentChoices")); // choiceThreads is optional Object jChoiceThreadsObj; // This does not work in Android with SDK < 24 //jChoiceThreadsObj = jObject.getOrDefault("choiceThreads", null); if (jObject.containsKey("choiceThreads")) { jChoiceThreadsObj = jObject.get("choiceThreads"); } else { jChoiceThreadsObj = null; } loadFlowChoiceThreads((HashMap<String, Object>) jChoiceThreadsObj, story); } public void writeJson(SimpleJson.Writer writer) throws Exception { writer.writeObjectStart(); writer.writeProperty("callstack", new SimpleJson.InnerWriter() { @Override public void write(Writer w) throws Exception { callStack.writeJson(w); } }); writer.writeProperty("outputStream", new SimpleJson.InnerWriter() { @Override public void write(Writer w) throws Exception { Json.writeListRuntimeObjs(w, outputStream); } }); // choiceThreads: optional // Has to come BEFORE the choices themselves are written out // since the originalThreadIndex of each choice needs to be set boolean hasChoiceThreads = false; for (Choice c : currentChoices) { c.originalThreadIndex = c.getThreadAtGeneration().threadIndex; if (callStack.getThreadWithIndex(c.originalThreadIndex) == null) { if (!hasChoiceThreads) { hasChoiceThreads = true; writer.writePropertyStart("choiceThreads"); writer.writeObjectStart(); } writer.writePropertyStart(c.originalThreadIndex); c.getThreadAtGeneration().writeJson(writer); writer.writePropertyEnd(); } } if (hasChoiceThreads) { writer.writeObjectEnd(); writer.writePropertyEnd(); } writer.writeProperty("currentChoices", new SimpleJson.InnerWriter() { @Override public void write(Writer w) throws Exception { w.writeArrayStart(); for (Choice c : currentChoices) Json.writeChoice(w, c); w.writeArrayEnd(); } }); writer.writeObjectEnd(); } // Used both to load old format and current @SuppressWarnings("unchecked") public void loadFlowChoiceThreads(HashMap<String, Object> jChoiceThreads, Story story) throws Exception { for (Choice choice : currentChoices) { CallStack.Thread foundActiveThread = callStack.getThreadWithIndex(choice.originalThreadIndex); if (foundActiveThread != null) { choice.setThreadAtGeneration(foundActiveThread.copy()); } else { HashMap<String, Object> jSavedChoiceThread = (HashMap<String, Object>) jChoiceThreads .get(Integer.toString(choice.originalThreadIndex)); choice.setThreadAtGeneration(new CallStack.Thread(jSavedChoiceThread, story)); } } } }
package org.andengine.util.adt.list; import java.util.ArrayList; import org.andengine.util.IMatcher; import org.andengine.util.call.ParameterCallable; public class SmartList<T> extends ArrayList<T> { // Constants private static final long serialVersionUID = 8655669528273139819L; // Fields // Constructors public SmartList() { } public SmartList(final int pCapacity) { super(pCapacity); } // Getter & Setter // Methods for/from SuperClass/Interfaces /** * @param pItem the item to remove. * @param pParameterCallable to be called with the removed item, if it was removed. */ public boolean remove(final T pItem, final ParameterCallable<T> pParameterCallable) { final boolean removed = this.remove(pItem); if(removed) { pParameterCallable.call(pItem); } return removed; } public T remove(final IMatcher<T> pMatcher) { for(int i = 0; i < this.size(); i++) { if(pMatcher.matches(this.get(i))) { return this.remove(i); } } return null; } public T remove(final IMatcher<T> pMatcher, final ParameterCallable<T> pParameterCallable) { for(int i = this.size() - 1; i >= 0; i if(pMatcher.matches(this.get(i))) { final T removed = this.remove(i); pParameterCallable.call(removed); return removed; } } return null; } public boolean removeAll(final IMatcher<T> pMatcher) { boolean result = false; for(int i = this.size() - 1; i >= 0; i if(pMatcher.matches(this.get(i))) { this.remove(i); result = true; } } return result; } /** * @param pMatcher to find the items. * @param pParameterCallable to be called with each matched item after it was removed. */ public boolean removeAll(final IMatcher<T> pMatcher, final ParameterCallable<T> pParameterCallable) { boolean result = false; for(int i = this.size() - 1; i >= 0; i if(pMatcher.matches(this.get(i))) { final T removed = this.remove(i); pParameterCallable.call(removed); result = true; } } return result; } public void clear(final ParameterCallable<T> pParameterCallable) { for(int i = this.size() - 1; i >= 0; i final T removed = this.remove(i); pParameterCallable.call(removed); } } public T find(final IMatcher<T> pMatcher) { // TODO Could be indexOf and listIndexOf for(int i = this.size() - 1; i >= 0; i final T item = this.get(i); if(pMatcher.matches(item)) { return item; } } return null; } public void call(final ParameterCallable<T> pParameterCallable) { for(int i = this.size() - 1; i >= 0; i final T item = this.get(i); pParameterCallable.call(item); } } public void call(final IMatcher<T> pMatcher, final ParameterCallable<T> pParameterCallable) { for(int i = this.size() - 1; i >= 0; i final T item = this.get(i); if(pMatcher.matches(item)) { pParameterCallable.call(item); } } } // Methods // Inner and Anonymous Classes }
package org.javasimon.jdbc; import org.testng.annotations.Test; import org.testng.annotations.DataProvider; import org.testng.Assert; import java.util.Arrays; /** * Unit tests for SqlNormalizer class. * * @author Radovan Sninsky * @author <a href="mailto:virgo47@gmail.com">Richard "Virgo" Richter</a> * @version $Revision$ $Date$ * @created 25.8.2008 10:51:52 * @since 1.0 */ public class SqlNormalizerTest { @DataProvider(name = "dp1") public Object[][] createTestData() { return new Object[][] { {null, null, null}, {"select * from trn, subtrn where amount>=45.8 and date!=to_date('5.6.2008', 'dd.mm.yyyy') and type='Mark''s'", "select", "select * from trn, subtrn where amount >= ? and date != ? and type = ?"}, {"select name as 'Customer Name', sum(item_price) as sum from foo where dept = ? group by name", "select", "select name as 'Customer Name', sum(item_price) as sum from foo where dept = ? group by name"}, {"select name as employee, sum(dur)/8 hrs from foo where dept='sys' group by name order by name desc", "select", "select name as employee, sum(dur)/8 hrs from foo where dept = ? group by name order by name desc"}, {"select sysdate(), sysdate from sys.dual", "select", "select sysdate(), sysdate from sys.dual"}, {"update trn set amount=50.6,type='bubu' where id=4", "update", "update trn set amount = ?, type = ? where id = ?"}, {"update 'trn' set amount= 50.6,type='' where id in (4,5,6) or date in (to_date('6.6.2006','dd.mm.yyyy'), to_date('7.6.2006','dd.mm.yyyy'))", "update", "update 'trn' set amount = ?, type = ? where id in (?) or date in (?)"}, {" delete from trn where id in (select id from subtrn where trndesc not like '%SX')", "delete", "delete from trn where id in (select id from subtrn where trndesc not like ?)"}, {"delete from trn where date between to_date('6.6.2006','dd.mm.yyyy') and to_date('7.6.2006','dd.mm.yyyy') and id<=10000", "delete", "delete from trn where date between ? and ? and id <= ?"}, {" create table foo(a1 varchar2(30) not null, a2 numeric(12,4))", "create", "create table foo"}, {"insert into foo ('bufo', 4.47)", "insert", "insert into foo (?, ?)"}, {"insert into foo (a1) values ('bubu')", "insert", "insert into foo (a1) values (?)"}, {"{call foo_ins_proc(99999, 'This text is inserted from stored procedure')}", "call", "call foo_ins_proc(?, ?)"}, {"{?= call foo_ins_proc_with_ret(99999, 'Text', sysdate())}", "call", "call foo_ins_proc(?, ?)"}, {"begin foo_ins_proc_with_ret(99999, 'Text', sysdate()); end;", "call", "call foo_ins_proc(?, ?)"}, }; } @Test(dataProvider = "dp1") public void sqlNormalizerTest(String sql, String type, String normSql) { SqlNormalizer sn = new SqlNormalizer(sql); Assert.assertEquals(sn.getType(), type); Assert.assertEquals(sn.getNormalizedSql(), normSql); } @Test public void batchNormalizationTest() { SqlNormalizer sn = new SqlNormalizer(Arrays.asList("update trn set amount=50.6,type='bubu' where id=4", "insert into foo ('bufo', 4.47)")); Assert.assertEquals(sn.getType(), "batch"); Assert.assertEquals(sn.getSql(), "batch"); Assert.assertEquals(sn.getNormalizedSql(), "update trn set amount = ?, type = ? where id = ?; insert into foo (?, ?)"); } }
package com.carlosefonseca.common; import android.app.ActivityManager; import android.app.Application; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.os.Environment; import com.carlosefonseca.common.utils.CodeUtils; import com.carlosefonseca.common.utils.Log; import java.io.File; import static com.carlosefonseca.common.utils.CodeUtils.getTag; /** * Base Class for the Application class. * Does the context management and sets up the test device. * Utils also access this class for its context. */ public class CFApp extends Application { private static final String TAG = getTag(CFApp.class); public static final String VERSION_KEY = "VERSION"; public static Context context; public static boolean test; private static final boolean ALLOW_TEST_DEVICE = true; @Override public void onCreate() { super.onCreate(); context = this; setTestDevice(isTest()); final SharedPreferences sharedPreferences = getSharedPreferences(getPackageName(), MODE_PRIVATE); final int stored = sharedPreferences.getInt(VERSION_KEY, -1); final int current = CodeUtils.getAppVersionCode(); if (stored != current) { Log.put("App Update", "" + stored + " -> " + current); sharedPreferences.edit().putInt(VERSION_KEY, current).commit(); } init(current, stored); } protected void init(int currentVersion, int previousVersion) {} public static boolean testIfTestDevice() { return isEmulator() || checkForceLogFile(); } private static boolean isEmulator() {return Build.FINGERPRINT.startsWith("generic");} private static boolean checkForceLogFile() { return new File(Environment.getExternalStorageDirectory(), "logbw.txt").exists(); } public static Context getContext() { if (context == null) Log.w(TAG, "Please setup a CFApp subclass!"); return context; } /** * You should override this and return com.yourapp.BuildConfig.DEBUG */ protected boolean isTest() { return test; } public static boolean isTestDevice() { return test; } public static void setTestDevice(boolean testDevice) { CFApp.test = testDevice; Log.setConsoleLogging(testDevice || testIfTestDevice()); if (testDevice) Log.w(TAG, "TEST DEVICE!"); } /** * @return {@link android.app.ActivityManager.MemoryInfo#availMem} * @see android.app.ActivityManager#getMemoryInfo(android.app.ActivityManager.MemoryInfo) */ public static long availableMemory() { ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo(); ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE); activityManager.getMemoryInfo(mi); long availableMegs = mi.availMem / 1048576L; Log.i(TAG, "RAM \"Available\": " + availableMegs + " MB"); return mi.availMem; } @Override public void onTerminate() { context = null; super.onTerminate(); } public static SharedPreferences getUserPreferences() {return getUserPreferences("default");} public static SharedPreferences getUserPreferences(String name) { return context.getSharedPreferences(name, Context.MODE_PRIVATE); } }
package datafu.test.pig.util; import static org.testng.Assert.*; import java.util.List; import org.adrianwalker.multilinestring.Multiline; import org.apache.pig.data.Tuple; import org.apache.pig.pigunit.PigTest; import org.testng.Assert; import org.testng.annotations.Test; import datafu.test.pig.PigTests; public class AssertTests extends PigTests { /** register $JAR_PATH define ASSERT datafu.pig.util.Assert(); data = LOAD 'input' AS (val:INT); data2 = FILTER data BY ASSERT(val,'assertion appears to have failed, doh!'); STORE data2 INTO 'output'; */ @Multiline private static String assertWithMessage; @Test public void shouldAssertWithMessageOnZero() throws Exception { try { PigTest test = createPigTestFromString(assertWithMessage); this.writeLinesToFile("input", "0"); test.runScript(); this.getLinesForAlias(test, "data2"); fail("test should have failed, but it didn't"); } catch (Exception e) { } } @Test public void shouldNotAssertWithMessageOnOne() throws Exception { PigTest test = createPigTestFromString(assertWithMessage); this.writeLinesToFile("input", "1"); test.runScript(); List<Tuple> result = this.getLinesForAlias(test, "data2"); Assert.assertEquals(result.size(), 1); Assert.assertEquals(result.get(0).size(), 1); Assert.assertEquals(result.get(0).get(0), 1); } /** register $JAR_PATH define ASSERT datafu.pig.util.Assert(); data = LOAD 'input' AS (val:INT); data2 = FILTER data BY ASSERT(val); STORE data2 INTO 'output'; */ @Multiline private static String assertWithoutMessage; @Test public void shouldAssertWithoutMessageOnZero() throws Exception { try { PigTest test = createPigTestFromString(assertWithoutMessage); this.writeLinesToFile("input", "0"); test.runScript(); this.getLinesForAlias(test, "data2"); fail("test should have failed, but it didn't"); } catch (Exception e) { } } @Test public void shouldNotAssertWithoutMessageOnOne() throws Exception { PigTest test = createPigTestFromString(assertWithoutMessage); this.writeLinesToFile("input", "1"); test.runScript(); List<Tuple> result = this.getLinesForAlias(test, "data2"); Assert.assertEquals(result.size(), 1); Assert.assertEquals(result.get(0).size(), 1); Assert.assertEquals(result.get(0).get(0), 1); } }
package org.apache.fop.render.pdf; // FOP import org.apache.fop.render.PrintRenderer; import org.apache.fop.messaging.MessageHandler; import org.apache.fop.image.ImageArea; import org.apache.fop.image.FopImage; import org.apache.fop.apps.FOPException; import org.apache.fop.fo.properties.*; import org.apache.fop.layout.inline.*; import org.apache.fop.datatypes.*; import org.apache.fop.svg.*; import org.apache.fop.pdf.*; import org.apache.fop.layout.*; import org.apache.fop.image.*; import org.apache.fop.extensions.*; import org.apache.fop.datatypes.IDReferences; import org.apache.batik.bridge.*; import org.apache.batik.swing.svg.*; import org.apache.batik.swing.gvt.*; import org.apache.batik.gvt.*; import org.apache.batik.gvt.renderer.*; import org.apache.batik.gvt.filter.*; import org.apache.batik.gvt.event.*; import org.w3c.dom.*; import org.w3c.dom.svg.*; import org.w3c.dom.css.*; import org.w3c.dom.svg.SVGLength; // Java import java.io.IOException; import java.io.OutputStream; import java.util.Enumeration; import java.util.Vector; import java.util.Hashtable; import java.awt.geom.AffineTransform; import java.awt.geom.Dimension2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.font.FontRenderContext; import java.awt.Dimension; /** * Renderer that renders areas to PDF */ public class PDFRenderer extends PrintRenderer { /** the PDF Document being created */ protected PDFDocument pdfDoc; /** the /Resources object of the PDF document being created */ protected PDFResources pdfResources; /** the current stream to add PDF commands to */ PDFStream currentStream; /** the current annotation list to add annotations to */ PDFAnnotList currentAnnotList; /** the current page to add annotations to */ PDFPage currentPage; PDFColor currentColor; /** true if a TJ command is left to be written */ boolean textOpen = false; /** the previous Y coordinate of the last word written. Used to decide if we can draw the next word on the same line. */ int prevWordY = 0; /** the previous X coordinate of the last word written. used to calculate how much space between two words */ int prevWordX = 0; /** The width of the previous word. Used to calculate space between */ int prevWordWidth = 0; private PDFOutline rootOutline; /** reusable word area string buffer to reduce memory usage */ private StringBuffer _wordAreaPDF = new StringBuffer(); /** * create the PDF renderer */ public PDFRenderer() { this.pdfDoc = new PDFDocument(); } /** * set the PDF document's producer * * @param producer string indicating application producing PDF */ public void setProducer(String producer) { this.pdfDoc.setProducer(producer); } /** * render the areas into PDF * * @param areaTree the laid-out area tree * @param stream the OutputStream to write the PDF to */ public void render(AreaTree areaTree, OutputStream stream) throws IOException, FOPException { MessageHandler.logln("rendering areas to PDF"); idReferences = areaTree.getIDReferences(); this.pdfResources = this.pdfDoc.getResources(); this.pdfDoc.setIDReferences(idReferences); Enumeration e = areaTree.getPages().elements(); while (e.hasMoreElements()) { this.renderPage((Page) e.nextElement()); } if (!idReferences.isEveryIdValid()) { // throw new FOPException("The following id's were referenced but not found: "+idReferences.getInvalidIds()+"\n"); MessageHandler.errorln("WARNING: The following id's were referenced but not found: "+ idReferences.getInvalidIds() + "\n"); } renderRootExtensions(areaTree); FontSetup.addToResources(this.pdfDoc, fontInfo); MessageHandler.logln("writing out PDF"); this.pdfDoc.output(stream); } /** * add a line to the current stream * * @param x1 the start x location in millipoints * @param y1 the start y location in millipoints * @param x2 the end x location in millipoints * @param y2 the end y location in millipoints * @param th the thickness in millipoints * @param r the red component * @param g the green component * @param b the blue component */ protected void addLine(int x1, int y1, int x2, int y2, int th, PDFPathPaint stroke) { closeText(); currentStream.add("ET\nq\n" + stroke.getColorSpaceOut(false) + (x1 / 1000f) + " "+ (y1 / 1000f) + " m " + (x2 / 1000f) + " "+ (y2 / 1000f) + " l " + (th / 1000f) + " w S\n" + "Q\nBT\n"); } /** * add a line to the current stream * * @param x1 the start x location in millipoints * @param y1 the start y location in millipoints * @param x2 the end x location in millipoints * @param y2 the end y location in millipoints * @param th the thickness in millipoints * @param rs the rule style * @param r the red component * @param g the green component * @param b the blue component */ protected void addLine(int x1, int y1, int x2, int y2, int th, int rs, PDFPathPaint stroke) { closeText(); currentStream.add("ET\nq\n" + stroke.getColorSpaceOut(false) + setRuleStylePattern(rs) + (x1 / 1000f) + " "+ (y1 / 1000f) + " m " + (x2 / 1000f) + " "+ (y2 / 1000f) + " l " + (th / 1000f) + " w S\n" + "Q\nBT\n"); } /** * add a rectangle to the current stream * * @param x the x position of left edge in millipoints * @param y the y position of top edge in millipoints * @param w the width in millipoints * @param h the height in millipoints * @param stroke the stroke color/gradient */ protected void addRect(int x, int y, int w, int h, PDFPathPaint stroke) { closeText(); currentStream.add("ET\nq\n" + stroke.getColorSpaceOut(false) + (x / 1000f) + " " + (y / 1000f) + " " + (w / 1000f) + " " + (h / 1000f) + " re s\n" + "Q\nBT\n"); } /** * add a filled rectangle to the current stream * * @param x the x position of left edge in millipoints * @param y the y position of top edge in millipoints * @param w the width in millipoints * @param h the height in millipoints * @param fill the fill color/gradient * @param stroke the stroke color/gradient */ protected void addRect(int x, int y, int w, int h, PDFPathPaint stroke, PDFPathPaint fill) { closeText(); currentStream.add("ET\nq\n" + fill.getColorSpaceOut(true) + stroke.getColorSpaceOut(false) + (x / 1000f) + " " + (y / 1000f) + " " + (w / 1000f) + " " + (h / 1000f) + " re b\n" + "Q\nBT\n"); } /** * render image area to PDF * * @param area the image area to render */ public void renderImageArea(ImageArea area) { // adapted from contribution by BoBoGi int x = this.currentAreaContainerXPosition + area.getXOffset(); int y = this.currentYPosition; int w = area.getContentWidth(); int h = area.getHeight(); this.currentYPosition -= h; FopImage img = area.getImage(); if (img instanceof SVGImage) { try { closeText(); SVGSVGElement svg = ((SVGImage) img).getSVGDocument().getRootElement(); currentStream.add("ET\nq\n" + (((float) w) / 1000f) + " 0 0 " + (((float) h) / 1000f) + " " + (((float) x) / 1000f) + " " + (((float)(y - h)) / 1000f) + " cm\n"); // renderSVG(svg, (int) x, (int) y); currentStream.add("Q\nBT\n"); } catch (FopImageException e) { } } else { int xObjectNum = this.pdfDoc.addImage(img); closeText(); currentStream.add("ET\nq\n" + (((float) w) / 1000f) + " 0 0 " + (((float) h) / 1000f) + " " + (((float) x) / 1000f) + " " + (((float)(y - h)) / 1000f) + " cm\n" + "/Im" + xObjectNum + " Do\nQ\nBT\n"); } } /** render a foreign object area */ public void renderForeignObjectArea(ForeignObjectArea area) { // if necessary need to scale and align the content this.currentXPosition = this.currentXPosition + area.getXOffset(); this.currentYPosition = this.currentYPosition; switch (area.getAlign()) { case TextAlign.START: break; case TextAlign.END: break; case TextAlign.CENTER: case TextAlign.JUSTIFY: break; } switch (area.getVerticalAlign()) { case VerticalAlign.BASELINE: break; case VerticalAlign.MIDDLE: break; case VerticalAlign.SUB: break; case VerticalAlign.SUPER: break; case VerticalAlign.TEXT_TOP: break; case VerticalAlign.TEXT_BOTTOM: break; case VerticalAlign.TOP: break; case VerticalAlign.BOTTOM: break; } closeText(); // in general the content will not be text currentStream.add("ET\n"); // align and scale currentStream.add("q\n"); switch (area.scalingMethod()) { case Scaling.UNIFORM: break; case Scaling.NON_UNIFORM: break; } // if the overflow is auto (default), scroll or visible // then the contents should not be clipped, since this // is considered a printing medium. switch (area.getOverflow()) { case Overflow.VISIBLE: case Overflow.SCROLL: case Overflow.AUTO: break; case Overflow.HIDDEN: break; } area.getObject().render(this); currentStream.add("Q\n"); currentStream.add("BT\n"); this.currentXPosition += area.getEffectiveWidth(); // this.currentYPosition -= area.getEffectiveHeight(); } /** * render SVG area to PDF * * @param area the SVG area to render */ public void renderSVGArea(SVGArea area) { // place at the current instream offset int x = this.currentXPosition; int y = this.currentYPosition; SVGSVGElement svg = area.getSVGDocument().getRootElement(); int w = (int)(svg.getWidth().getBaseVal().getValue() * 1000); int h = (int)(svg.getHeight().getBaseVal().getValue() * 1000); float sx = 1, sy = -1; int xOffset = x, yOffset = y; /* * Clip to the svg area. * Note: To have the svg overlay (under) a text area then use * an fo:block-container */ currentStream.add("q\n"); if (w != 0 && h != 0) { currentStream.add(x / 1000f + " " + y / 1000f + " m\n"); currentStream.add((x + w) / 1000f + " " + y / 1000f + " l\n"); currentStream.add((x + w) / 1000f + " " + (y - h) / 1000f + " l\n"); currentStream.add(x / 1000f + " " + (y - h) / 1000f + " l\n"); currentStream.add("h\n"); currentStream.add("W\n"); currentStream.add("n\n"); } // transform so that the coordinates (0,0) is from the top left // and positive is down and to the right. (0,0) is where the // viewBox puts it. currentStream.add(sx + " 0 0 " + sy + " " + xOffset / 1000f + " " + yOffset / 1000f + " cm\n"); SVGDocument doc = area.getSVGDocument(); UserAgent userAgent = new MUserAgent(new AffineTransform()); GVTBuilder builder = new GVTBuilder(); GraphicsNodeRenderContext rc = getRenderContext(); BridgeContext ctx = new BridgeContext(userAgent, rc); GraphicsNode root; //System.out.println("creating PDFGraphics2D"); PDFGraphics2D graphics = new PDFGraphics2D(true, area.getFontState(), pdfDoc, currentFontName, currentFontSize, currentXPosition, currentYPosition); graphics.setGraphicContext( new org.apache.batik.ext.awt.g2d.GraphicContext()); graphics.setRenderingHints(rc.getRenderingHints()); try { root = builder.build(ctx, doc); root.paint(graphics, rc); currentStream.add(graphics.getString()); } catch (Exception e) { e.printStackTrace(); } currentStream.add("Q\n"); } public GraphicsNodeRenderContext getRenderContext() { GraphicsNodeRenderContext nodeRenderContext = null; if (nodeRenderContext == null) { RenderingHints hints = new RenderingHints(null); hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); hints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); FontRenderContext fontRenderContext = new FontRenderContext(new AffineTransform(), true, true); TextPainter textPainter = new StrokingTextPainter(); GraphicsNodeRableFactory gnrFactory = new ConcreteGraphicsNodeRableFactory(); nodeRenderContext = new GraphicsNodeRenderContext( new AffineTransform(), null, hints, fontRenderContext, textPainter, gnrFactory); nodeRenderContext.setTextPainter(textPainter); } return nodeRenderContext; } /** * render inline area to PDF * * @param area inline area to render */ public void renderWordArea(WordArea area) { synchronized (_wordAreaPDF) { StringBuffer pdf = _wordAreaPDF; pdf.setLength(0); Hashtable kerning = null; boolean kerningAvailable = false; kerning = area.getFontState().getKerning(); if (kerning != null && !kerning.isEmpty()) { kerningAvailable = true; } String name = area.getFontState().getFontName(); int size = area.getFontState().getFontSize(); // This assumes that *all* CIDFonts use a /ToUnicode mapping boolean useMultiByte = false; Font f = (Font) area.getFontState().getFontInfo().getFonts(). get(name); if (f instanceof CIDFont) useMultiByte = true; //String startText = useMultiByte ? "<FEFF" : "("; String startText = useMultiByte ? "<" : "("; String endText = useMultiByte ? "> " : ") "; if ((!name.equals(this.currentFontName)) || (size != this.currentFontSize)) { closeText(); this.currentFontName = name; this.currentFontSize = size; pdf = pdf.append("/" + name + " " + (size / 1000) + " Tf\n"); } PDFColor areaColor = null; if (this.currentFill instanceof PDFColor) { areaColor = (PDFColor) this.currentFill; } if (areaColor == null || areaColor.red() != (double) area.getRed() || areaColor.green() != (double) area.getGreen() || areaColor.blue() != (double) area.getBlue()) { areaColor = new PDFColor((double) area.getRed(), (double) area.getGreen(), (double) area.getBlue()); closeText(); this.currentFill = areaColor; pdf.append(this.currentFill.getColorSpaceOut(true)); } int rx = this.currentXPosition; int bl = this.currentYPosition; addWordLines(area, rx, bl, size, areaColor); if (!textOpen || bl != prevWordY) { closeText(); pdf.append("1 0 0 1 " +(rx / 1000f) + " " + (bl / 1000f) + " Tm [" + startText); prevWordY = bl; textOpen = true; } else { // express the space between words in thousandths of an em int space = prevWordX - rx + prevWordWidth; float emDiff = (float) space / (float) currentFontSize * 1000f; pdf.append(Float.toString(emDiff)); pdf.append(" "); pdf.append(startText); } prevWordWidth = area.getContentWidth(); prevWordX = rx; String s; if (area.getPageNumberID() != null) { // this text is a page number, so resolve it s = idReferences.getPageNumber(area.getPageNumberID()); if (s == null) { s = ""; } } else { s = area.getText(); } int l = s.length(); for (int i = 0; i < l; i++) { char ch = s.charAt(i); if (!useMultiByte) { if (ch > 127) { pdf.append("\\"); pdf.append(Integer.toOctalString((int) ch)); } else { switch (ch) { case '(': case ')': case '\\': pdf.append("\\"); break; } pdf.append(ch); } } else { pdf.append(getUnicodeString(ch)); } if (kerningAvailable && (i + 1) < l) { addKerning(pdf, (new Integer((int) ch)), (new Integer((int) s.charAt(i + 1))), kerning, startText, endText); } } pdf.append(endText); currentStream.add(pdf.toString()); this.currentXPosition += area.getContentWidth(); } } /** * Convert a char to a multibyte hex representation */ private String getUnicodeString(char c) { StringBuffer buf = new StringBuffer(4); byte[] uniBytes = null; try { char[] a = {c}; uniBytes = new String(a).getBytes("UnicodeBigUnmarked"); } catch (Exception e) { // This should never fail } for (int i = 0; i < uniBytes.length; i++) { int b = (uniBytes[i] < 0) ? (int)(256 + uniBytes[i]) : (int) uniBytes[i]; String hexString = Integer.toHexString(b); if (hexString.length() == 1) buf = buf.append("0"+hexString); else buf = buf.append(hexString); } return buf.toString(); } /** Checks to see if we have some text rendering commands open * still and writes out the TJ command to the stream if we do */ private void closeText() { if (textOpen) { currentStream.add("] TJ\n"); textOpen = false; prevWordX = 0; prevWordY = 0; } } private void addKerning(StringBuffer buf, Integer ch1, Integer ch2, Hashtable kerning, String startText, String endText) { Hashtable kernPair = (Hashtable) kerning.get(ch1); if (kernPair != null) { Integer width = (Integer) kernPair.get(ch2); if (width != null) { buf.append(endText).append(- (width.intValue())).append(' ').append(startText); } } } /** * render page into PDF * * @param page page to render */ public void renderPage(Page page) { BodyAreaContainer body; AreaContainer before, after, start, end; currentStream = this.pdfDoc.makeStream(); body = page.getBody(); before = page.getBefore(); after = page.getAfter(); start = page.getStart(); end = page.getEnd(); this.currentFontName = ""; this.currentFontSize = 0; currentStream.add("BT\n"); renderBodyAreaContainer(body); if (before != null) { renderAreaContainer(before); } if (after != null) { renderAreaContainer(after); } if (start != null) { renderAreaContainer(start); } if (end != null) { renderAreaContainer(end); } closeText(); currentStream.add("ET\n"); currentPage = this.pdfDoc.makePage(this.pdfResources, currentStream, page.getWidth() / 1000, page.getHeight() / 1000, page); if (page.hasLinks()) { currentAnnotList = this.pdfDoc.makeAnnotList(); currentPage.setAnnotList(currentAnnotList); Enumeration e = page.getLinkSets().elements(); while (e.hasMoreElements()) { LinkSet linkSet = (LinkSet) e.nextElement(); linkSet.align(); String dest = linkSet.getDest(); int linkType = linkSet.getLinkType(); Enumeration f = linkSet.getRects().elements(); while (f.hasMoreElements()) { LinkedRectangle lrect = (LinkedRectangle) f.nextElement(); currentAnnotList.addLink( this.pdfDoc.makeLink(lrect.getRectangle(), dest, linkType)); } } } else { // just to be on the safe side currentAnnotList = null; } // ensures that color is properly reset for blocks that carry over pages this.currentFill = null; } /** * defines a string containing dashArray and dashPhase for the rule style */ private String setRuleStylePattern (int style) { String rs = ""; switch (style) { case org.apache.fop.fo.properties.RuleStyle.SOLID: rs = "[] 0 d "; break; case org.apache.fop.fo.properties.RuleStyle.DASHED: rs = "[3 3] 0 d "; break; case org.apache.fop.fo.properties.RuleStyle.DOTTED: rs = "[1 3] 0 d "; break; case org.apache.fop.fo.properties.RuleStyle.DOUBLE: rs = "[] 0 d "; break; default: rs = "[] 0 d "; } return rs; } protected void renderRootExtensions(AreaTree areaTree) { Vector v = areaTree.getExtensions(); if (v != null) { Enumeration e = v.elements(); while (e.hasMoreElements()) { ExtensionObj ext = (ExtensionObj) e.nextElement(); if (ext instanceof Outline) { renderOutline((Outline) ext); } } } } private void renderOutline(Outline outline) { if (rootOutline == null) { rootOutline = this.pdfDoc.makeOutlineRoot(); } PDFOutline pdfOutline = null; Outline parent = outline.getParentOutline(); if (parent == null) { pdfOutline = this.pdfDoc.makeOutline(rootOutline, outline.getLabel().toString(), outline.getInternalDestination()); } else { PDFOutline pdfParentOutline = (PDFOutline) parent.getRendererObject(); if (pdfParentOutline == null) { MessageHandler.errorln("Error: pdfParentOutline is null"); } else { pdfOutline = this.pdfDoc.makeOutline(pdfParentOutline, outline.getLabel().toString(), outline.getInternalDestination()); } } outline.setRendererObject(pdfOutline); // handle sub outlines Vector v = outline.getOutlines(); Enumeration e = v.elements(); while (e.hasMoreElements()) { renderOutline((Outline) e.nextElement()); } } protected class MUserAgent implements UserAgent { AffineTransform currentTransform = null; /** * Creates a new SVGUserAgent. */ protected MUserAgent(AffineTransform at) { currentTransform = at; } /** * Displays an error message. */ public void displayError(String message) { System.err.println(message); } /** * Displays an error resulting from the specified Exception. */ public void displayError(Exception ex) { ex.printStackTrace(System.err); } /** * Displays a message in the User Agent interface. * The given message is typically displayed in a status bar. */ public void displayMessage(String message) { System.out.println(message); } /** * Returns a customized the pixel to mm factor. */ public float getPixelToMM() { return 0.264583333333333333333f; // 72 dpi } /** * Returns the language settings. */ public String getLanguages() { return "en";//userLanguages; } /** * Returns the user stylesheet uri. * @return null if no user style sheet was specified. */ public String getUserStyleSheetURI() { return null;//userStyleSheetURI; } /** * Returns the class name of the XML parser. */ public String getXMLParserClassName() { String parserClassName = System.getProperty("org.xml.sax.parser"); if (parserClassName == null) { parserClassName = "org.apache.xerces.parsers.SAXParser"; } return parserClassName;//application.getXMLParserClassName(); } /** * Opens a link in a new component. * @param doc The current document. * @param uri The document URI. */ public void openLink(SVGAElement elt) { //application.openLink(uri); } public Point getClientAreaLocationOnScreen() { return new Point(0, 0); } public void setSVGCursor(java.awt.Cursor cursor) { } public AffineTransform getTransform() { return currentTransform; } public Dimension2D getViewportSize() { return new Dimension(100, 100); } public EventDispatcher getEventDispatcher() { return null; } public boolean supportExtension(String str) { return false; } public boolean hasFeature(String str) { return false; } public void registerExtension(BridgeExtension be) { } } }
//@author A0111875E package com.epictodo.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; public class DateValidator { private Calendar _calendar = Calendar.getInstance(); private static DateValidator instance = null; private static final String DATE_PATTERN = "(\\d+)"; private static final String TIMEX_PATTERN = "((19|20)(\\d{2}))-([1-9]|0[1-9]|1[0-2])-(0[1-9]|[1-9]|[12][0-9]|3[01])-(\\S+)"; private static final String TIMEX_PATTERN_2 = "((19|20)(\\d{2}))-([1-9]|0[1-9]|1[0-2])-(0[1-9]|[1-9]|[12][0-9]|3[01])(\\S+)"; private static final String TIME_PATTERN = "((19|20)(\\d{2}))-([1-9]|0[1-9]|1[0-2])-(0[1-9]|[1-9]|[12][0-9]|3[01])-(\\S+T)(([01]?[0-9]|2[0-3]):[0-5][0-9])"; private static final String TIME_PATTERN_2 = "((19|20)(\\d{2}))-([1-9]|0[1-9]|1[0-2])-(0[1-9]|[1-9]|[12][0-9]|3[01])(T)(([01]?[0-9]|2[0-3]):[0-5][0-9])"; /** * This method ensures that there will only be one running instance * * @return */ public static DateValidator getInstance() { if (instance == null) { instance = new DateValidator(); } return instance; } /** * This method is the same as getDateInFormat except it's parsed format is different * FUTURE Date is parsed from exactDate() which will return exactly the format of yyyy-MM-dd * <p/> * Usage: * <p/> * getDateToCompare("2014-11-09"); > 2014-11-09 * getDateToCompare("2014-11-23T14:30"); > 2014-11-23 * getDateToCompare("2014-11-11-WXX-2"); > 2011-11-11 * getDateToCompare("2014-11-18-WXX-2T10:00"); > 2014-11-18 * * @param _date * @return _result * @throws ParseException */ public String getDateToCompare(String _date) throws ParseException { SimpleDateFormat date_format = new SimpleDateFormat("yyyy-MM-dd"); int num_days; String _result; String[] exact_date = extractDate(_date); Date today_date = date_format.parse(getTodayDate()); Date next_date = date_format.parse(exact_date[2] + "-" + exact_date[1] + "-" + exact_date[0]); num_days = calculateDays(today_date, next_date); if (next_date.after(today_date) || next_date.equals(today_date)) { if (num_days >= 0 && num_days <= 1) { _result = exact_date[2] + "-" + exact_date[1] + "-" + exact_date[0]; return _result; } } _result = exact_date[2] + "-" + exact_date[1] + "-" + exact_date[0]; return _result; } /** * This method validates the date and parse to the following format (yyyy-MM-dd) * This will return with the format of ddMMyy * <p/> * Issues: * 3 cases: * 1. yyyy-MM-dd * 2. yyyy-MM-dd-WXX-dT-hh:mm * 3. yyyy-MM-ddT-hh:mm * <p/> * Usage: * <p/> * getDateInFormat("2014-11-09"); > 091114 * getDateInFormat("2014-11-23T14:30"); > 231114 * getDateInFormat("2014-11-11-WXX-2"); > 111114 * getDateInFormat("2014-11-18-WXX-2T10:00"); > 181114 * * @param _date * @return _result */ public String getDateInFormat(String _date) throws ParseException { SimpleDateFormat date_format = new SimpleDateFormat("yyyy-MM-dd"); int num_days; String _result; String[] exact_date = extractDate(_date); Pattern date_pattern = Pattern.compile(TIMEX_PATTERN_2); Matcher date_matcher = date_pattern.matcher(_date); Date today_date = date_format.parse(getTodayDate()); Date next_date = date_format.parse(exact_date[2] + "-" + exact_date[1] + "-" + exact_date[0]); num_days = calculateDays(today_date, next_date); if (next_date.after(today_date) || next_date.equals(today_date)) { if (num_days >= 0 && num_days <= 1) { while (date_matcher.find()) { _result = date_matcher.group(5) + date_matcher.group(4) + date_matcher.group(3); return _result; } } } if (!date_matcher.matches()) { return null; } else { _result = date_matcher.group(5) + date_matcher.group(4) + date_matcher.group(3); } return _result; } /** * This method validates the time and parse to the following format (hh:mm) * This will return the time from the given string in the format of hh:mm * <p/> * Usage: * <p/> * getTimeInFormat("10:30"); > 10:30 * getTimeInFormat("2014-11-23T14:30"); > 14:30 * getTimeInFormat("2014-11-18-WXX-2T10:00"); > 10:00 * * @param _time * @return _result * @throws ParseException */ public String getTimeInFormat(String _time) throws ParseException { SimpleDateFormat date_format = new SimpleDateFormat("yyyy-MM-dd"); int num_days; String _result; Pattern date_pattern = Pattern.compile(TIME_PATTERN_2); Matcher date_matcher = date_pattern.matcher(_time); Date today_date = date_format.parse(getTodayDate()); Date next_date = date_format.parse(_time); num_days = calculateDays(today_date, next_date); if (next_date.after(today_date) || next_date.equals(today_date)) { if (num_days >= 0 && num_days <= 1) { while (date_matcher.find()) { _result = date_matcher.group(7); return _result; } } } if (!date_matcher.matches()) { return null; } else { _result = date_matcher.group(7); } return _result; } /** * This method validates the date and parse to the following format (ddMMyy) * This works for general cases where the day difference is more than 2 days. * This method is similar to getDateInFormat * <p/> * Usage: * validateDate("2014-11-18-WXX-2T10:00"); > 181114 * * @param _date * @return */ public String validateDate(String _date) { String _result; Pattern date_pattern = Pattern.compile(TIMEX_PATTERN); Matcher date_matcher = date_pattern.matcher(_date); if (!date_matcher.matches()) { return null; } _result = date_matcher.group(5) + date_matcher.group(4) + date_matcher.group(3); return _result; } /** * This method validates the token from NLP SUTIME Annotation based on our predefined regex expression * This method is parsed to get the time only * <p/> * Usage: * <p/> * validateTime("2014-11-18-WXX-2T10:00"); > 10:00 * validateTime("10:30"); > 10:30 * validateTime("2014-11-23T14:30"); > 14:30 * validateTime("2014-11-18-WXX-2T10:00"); > 10:00 * * @param _time * @return */ public String validateTime(String _time) { String _result; Pattern date_pattern = Pattern.compile(TIME_PATTERN); Matcher date_matcher = date_pattern.matcher(_time); if (!date_matcher.matches()) { return null; } _result = date_matcher.group(7); return _result; } /** * This method extracts the date based on the format of yyyy-MM-dd * This will return an Array of String results containing DAY, MONTH, YEAR * <p/> * Usage: * <p/> * extractDate("2014-11-09"); > [09, 11, 2014] * extractDate("2014-11-23T14:30"); > [23, 11, 2014] * extractDate("2014-11-11-WXX-2"); > [11, 11, 2014] * extractDate("2014-11-18-WXX-2T10:00"); > [18, 11, 2014] * * @param _date * @return _list * @throws ParseException */ public String[] extractDate(String _date) throws ParseException { SimpleDateFormat date_format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); String[] _list = new String[3]; _calendar.setTime(date_format.parse(_date)); int _year = _calendar.get(Calendar.YEAR); int _month = _calendar.get(Calendar.MONTH) + 1; int _day = _calendar.get(Calendar.DAY_OF_MONTH); _list[0] = String.valueOf(_day); _list[1] = String.valueOf(_month); _list[2] = String.valueOf(_year); return _list; } /** * This method determines the priority of a task based on natural processing * This artificial natural processing calculates the days difference * <p/> * The priority is determined by the number of weeks apart from today's date * The current rule of this determiner decreases the priority each week from today's date * The closer the date is to today's date holds the highest priority and decreases each week * <p/> * Assumptions: * 1. User can override the priority based on their preferred choice * 2. Priority is set based on this determiner algorithm, may not accurately reflect user's intentions * 3. Priority range from 1 - 9. 1 represents the least of priority, 9 represents the most urgent of priority * <p/> * The higher the priority the more urgent the task is * The default priority is set to '2' * <p/> * Usage: (example based on TODAY's Date = 2014-11-01) * <p/> * determinePriority("2014-11-08") > 9 * determinePriority("2014-11-20") > 8 * determinePriority("2014-11-23") > 7 * determinePriority("2014-12-07") > 5 * * @param _date * @return * @throws ParseException */ public String determinePriority(String _date) throws ParseException { SimpleDateFormat date_format = new SimpleDateFormat("yyyy-MM-dd"); int num_days; String[] exact_date = extractDate(_date); Date today_date = date_format.parse(getTodayDate()); Date next_date = date_format.parse(exact_date[2] + "-" + exact_date[1] + "-" + exact_date[0]); num_days = calculateDays(today_date, next_date); if (next_date.after(today_date)) { if (num_days >= 0 && num_days <= 7) { return "9"; } else if (num_days > 7 && num_days <= 14) { return "8"; } else if (num_days > 14 && num_days <= 21) { return "7"; } else if (num_days > 21 && num_days <= 28) { return "6"; } else if (num_days > 28 && num_days <= 35) { return "5"; } else if (num_days > 35 && num_days <= 42) { return "5"; } else if (num_days > 42 && num_days <= 49) { return "4"; } else if (num_days > 49 && num_days <= 56) { return "3"; } else if (num_days > 56) { return "2"; } } else if (next_date.before(today_date)) { return "Date is invalid!"; } return "2"; } /** * This method compares 2 dates, TODAY and FUTURE * This method enables flexiAdd() to determine the number of days between dates in order to process the result * <p/> * Usage: (example based on TODAY's Date = 2014-11-01) * <p/> * compareDate("2014-11-03") > 2 * compareDate("2014-11-20") > 19 * * @param _date * @return num_days * @throws ParseException */ public int compareDate(String _date) throws ParseException { SimpleDateFormat date_format = new SimpleDateFormat("yyyy-MM-dd"); int num_days; Date today_date = date_format.parse(getTodayDate()); Date next_date = date_format.parse(_date); num_days = calculateDays(today_date, next_date); return num_days; } /** * This method checks and validates if the integer passed is in the format of ddMMyy * * @param _date * @return boolean * @throws ParseException */ public boolean checkDateFormat(String _date) throws ParseException { Pattern date_pattern = Pattern.compile(DATE_PATTERN); Matcher date_matcher = date_pattern.matcher(_date); if (!date_matcher.matches()) { return false; } return true; } /** * This method returns today's date * * @return */ public String getTodayDate() { Date _date = new Date(); SimpleDateFormat date_format = new SimpleDateFormat("yyyy-MM-dd"); return date_format.format(_date); } /** * This method calculates the number of days difference from today's date * This method is the core algorithm of the day calculation which is used in determinePriority() method * <p/> * Usage: * <p/> * calculateDays(2014-11-01, 2014-11-05); > 4 * calculateDays(2014-11-01, 2014-11-10); > 9 * * @param today_date * @param next_date * @return */ private int calculateDays(Date today_date, Date next_date) { return (int) ((next_date.getTime() - today_date.getTime()) / (24 * 60 * 60 * 1000)); } }
package com.socialize.test; import com.google.android.testing.mocking.AndroidMock; import com.google.android.testing.mocking.UsesMocks; import com.socialize.Socialize; import com.socialize.SocializeService; import com.socialize.android.ioc.IOCContainer; import com.socialize.api.SocializeSession; import com.socialize.entity.Comment; import com.socialize.error.SocializeException; import com.socialize.listener.comment.CommentAddListener; /** * @author Jason Polites * */ @UsesMocks({IOCContainer.class, SocializeService.class, SocializeSession.class}) public class SocializeTest extends SocializeUnitTest { public void testSocializeInitDestroy() { IOCContainer container = AndroidMock.createMock(IOCContainer.class); SocializeService service = AndroidMock.createMock(SocializeService.class, getContext()); AndroidMock.expect(container.getBean("socializeService")).andReturn(service); container.destroy(); AndroidMock.replay(container); Socialize socialize = new Socialize(); socialize.init(getContext(), container); assertTrue(socialize.isInitialized()); socialize.destroy(); assertFalse(socialize.isInitialized()); AndroidMock.verify(container); } @UsesMocks ({CommentAddListener.class}) public void testAddCommentSuccess() { IOCContainer container = AndroidMock.createMock(IOCContainer.class); SocializeService service = AndroidMock.createMock(SocializeService.class, getContext()); CommentAddListener listener = AndroidMock.createMock(CommentAddListener.class); SocializeSession session = AndroidMock.createMock(SocializeSession.class); final String key = "foo", comment = "bar"; AndroidMock.expect(container.getBean("socializeService")).andReturn(service); service.addComment(session, key, comment, listener); AndroidMock.replay(container); AndroidMock.replay(service); Socialize socialize = new Socialize(); socialize.init(getContext(), container); assertTrue(socialize.isInitialized()); socialize.addComment(session, key, comment, listener); AndroidMock.verify(container); AndroidMock.verify(service); } public void testAddCommentFail() { SocializeSession session = AndroidMock.createMock(SocializeSession.class); final String key = "foo", comment = "bar"; CommentAddListener listener = new CommentAddListener() { @Override public void onError(SocializeException error) { addResult(error); } @Override public void onCreate(Comment entity) {} }; Socialize socialize = new Socialize(); assertFalse(socialize.isInitialized()); socialize.addComment(session, key, comment, listener); Exception error = getResult(); assertNotNull(error); assertTrue(error instanceof SocializeException); } }
package org.clapper.util.config; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import org.clapper.util.text.TextUtil; import org.clapper.util.text.UnixShellVariableSubstituter; import org.clapper.util.text.VariableDereferencer; import org.clapper.util.text.VariableNameChecker; import org.clapper.util.text.VariableSubstitutionException; import org.clapper.util.text.VariableSubstituter; import org.clapper.util.text.XStringBuffer; import org.clapper.util.io.FileUtil; public class Configuration implements VariableDereferencer, VariableNameChecker { private static final String COMMENT_CHARS = "#!"; private static final char SECTION_START = '['; private static final char SECTION_END = ']'; private static final String INCLUDE = "%include"; private static final int MAX_INCLUDE_NESTING_LEVEL = 50; private static final String SYSTEM_SECTION_NAME = "system"; private static final String PROGRAM_SECTION_NAME = "program"; /** * Contains one logical input line. */ class Line { static final int COMMENT = 0; static final int INCLUDE = 1; static final int SECTION = 2; static final int VARIABLE = 3; static final int BLANK = 4; int number = 0; int type = COMMENT; XStringBuffer buffer = new XStringBuffer(); Line() { } void newLine() { buffer.setLength (0); } } /** * Context for variable substitution */ private class SubstitutionContext { Variable currentVariable; int totalSubstitutions = 0; SubstitutionContext (Variable v) { currentVariable = v; } } /** * Container for data used only during parsing. */ private class ParseContext { /** * Current section. Only set during parsing. */ private Section currentSection = null; /** * Current variable name being processed. Used during the variable * substitution parsing phase. */ private Variable currentVariable = null; /** * Current include file nesting level. Used as a fail-safe during * parsing. */ private int includeFileNestingLevel = 0; /** * Table of files/URLs currently open. Used during include * processing. */ private Set openURLs = new HashSet(); ParseContext() { } } /** * The URL of the configuration file, if available */ private URL configURL = null; /** * List of sections, in order encountered. Each element is a reference to * a Section object. */ private List sectionsInOrder = new ArrayList(); /** * Sections by name. Each index is a string. Each value is a reference to * a Section object. */ private Map sectionsByName = new HashMap(); /** * Special section for System.properties */ private static Section systemSection; /** * Special section for program properties */ private Section programSection; /** * Section ID values. */ private int nextSectionID = 1; /** * Construct an empty <tt>Configuration</tt> object. The object may * later be filled with configuration data via one of the <tt>load()</tt> * methods, or by calls to {@link #addSection addSection()} and * {@link #setVariable setVariable()}. */ public Configuration() { } /** * Construct a <tt>Configuration</tt> object that parses data from * the specified file. * * @param f The <tt>File</tt> to open and parse * * @throws IOException can't open or read file * @throws ConfigurationException error in configuration data */ public Configuration (File f) throws IOException, ConfigurationException { load (f); } /** * Construct a <tt>Configuration</tt> object that parses data from * the specified file. * * @param path the path to the file to parse * * @throws FileNotFoundException specified file doesn't exist * @throws IOException can't open or read file * @throws ConfigurationException error in configuration data */ public Configuration (String path) throws FileNotFoundException, IOException, ConfigurationException { load (path); } /** * Construct a <tt>Configuration</tt> object that parses data from * the specified URL. * * @param url the URL to open and parse * * @throws IOException can't open or read URL * @throws ConfigurationException error in configuration data */ public Configuration (URL url) throws IOException, ConfigurationException { load (url); } /** * Construct a <tt>Configuration</tt> object that parses data from * the specified <tt>InputStream</tt>. * * @param iStream the <tt>InputStream</tt> * * @throws IOException can't read from <tt>InputStream</tt> * @throws ConfigurationException error in configuration data */ public Configuration (InputStream iStream) throws IOException, ConfigurationException { load (iStream); } /** * Add a new section to this configuration data. * * @param sectionName the name of the new section * * @throws SectionExistsException a section by that name already exists * * @see #containsSection * @see #getSectionNames * @see #setVariable */ public void addSection (String sectionName) throws SectionExistsException { if (sectionsByName.get (sectionName) != null) throw new SectionExistsException (sectionName); makeNewSection (sectionName); } /** * Clear this object of all configuration data. */ public void clear() { sectionsInOrder.clear(); sectionsByName.clear(); configURL = null; } /** * Determine whether this object contains a specified section. * * @param sectionName the section name * * @return <tt>true</tt> if the section exists in this configuration, * <tt>false</tt> if not. * * @see #getSectionNames * @see #addSection */ public boolean containsSection (String sectionName) { return (sectionsByName.get (sectionName) != null); } /** * Get the URL of the configuration file, if available. * * @return the URL of the configuration file, or null if the file * was parsed from an <tt>InputStream</tt> */ public URL getConfigurationFileURL() { return configURL; } /** * Get the names of the sections in this object, in the order they were * parsed and/or added. * * @param collection the <tt>Collection</tt> to which to add the section * names. The names are added in the order they were * parsed and/or added to this object; of course, the * <tt>Collection</tt> may reorder them. * * @return the <tt>collection</tt> parameter, for convenience * * @see #getVariableNames */ public Collection getSectionNames (Collection collection) { for (Iterator it = sectionsInOrder.iterator(); it.hasNext(); ) collection.add (((Section) it.next()).getName()); return collection; } /** * Get the names of the all the variables in a section, in the order * they were parsed and/or added. * * @param sectionName the name of the section to access * @param collection the <tt>Collection</tt> to which to add the variable * names. The names are added in the order they were * parsed and/or added to this object; of course, the * <tt>Collection</tt> may reorder them. * * @return the <tt>collection</tt> parameter, for convenience * * @throws NoSuchSectionException no such section * * @see #getSectionNames * @see #containsSection * @see #getVariableValue */ public Collection getVariableNames (String sectionName, Collection collection) throws NoSuchSectionException { Section section = (Section) sectionsByName.get (sectionName); if (section == null) throw new NoSuchSectionException (sectionName); collection.addAll (section.getVariableNames()); return collection; } /** * Get the value for a variable. * * @param sectionName the name of the section containing the variable * @param variableName the variable name * * @return the value for the variable (which may be the empty string) * * @throws NoSuchSectionException the named section does not exist * @throws NoSuchVariableException the section has no such variable */ public String getConfigurationValue (String sectionName, String variableName) throws NoSuchSectionException, NoSuchVariableException { Section section = (Section) sectionsByName.get (sectionName); if (section == null) throw new NoSuchSectionException (sectionName); Variable variable = null; try { variable = section.getVariable (variableName); } catch (ConfigurationException ex) { } if (variable == null) throw new NoSuchVariableException (sectionName, variableName); return variable.getCookedValue(); } /** * Convenience method to get and convert an optional integer parameter. * The default value applies if the variable is missing or is there but * has an empty value. * * @param sectionName section name * @param variableName variable name * @param defaultValue default value if not found * * @return the value, or the default value if not found * * @throws NoSuchSectionException no such section * @throws ConfigurationException bad numeric value */ public int getOptionalIntegerValue (String sectionName, String variableName, int defaultValue) throws NoSuchSectionException, ConfigurationException { try { return getRequiredIntegerValue (sectionName, variableName); } catch (NoSuchVariableException ex) { return defaultValue; } } /** * Convenience method to get and convert a required integer parameter. * * @param sectionName section name * @param variableName variable name * * @return the value * * @throws NoSuchSectionException no such section * @throws NoSuchVariableException no such variable * @throws ConfigurationException bad numeric value */ public int getRequiredIntegerValue (String sectionName, String variableName) throws NoSuchSectionException, NoSuchVariableException, ConfigurationException { String sNum = getConfigurationValue (sectionName, variableName); try { return Integer.parseInt (sNum); } catch (NumberFormatException ex) { throw new ConfigurationException (Package.BUNDLE_NAME, "Configuration.badNumericValue", "Bad numeric value \"{0}\" for " + "variable \"{1}\" in section " + "\"{2}\"", new Object[] { sNum, variableName, sectionName }); } } /** * Convenience method to get and convert an optional floating point * numeric parameter. The default value applies if the variable is * missing or is there but has an empty value. * * @param sectionName section name * @param variableName variable name * @param defaultValue default value if not found * * @return the value, or the default value if not found * * @throws NoSuchSectionException no such section * @throws ConfigurationException bad numeric value */ public double getOptionalDoubleValue (String sectionName, String variableName, double defaultValue) throws NoSuchSectionException, ConfigurationException { try { return getRequiredDoubleValue (sectionName, variableName); } catch (NoSuchVariableException ex) { return defaultValue; } } /** * Convenience method to get and convert a required floating point * numeric parameter. * * @param sectionName section name * @param variableName variable name * * @return the value * * @throws NoSuchSectionException no such section * @throws NoSuchVariableException no such variable * @throws ConfigurationException bad numeric value */ public double getRequiredDoubleValue (String sectionName, String variableName) throws NoSuchSectionException, NoSuchVariableException, ConfigurationException { String sNum = getConfigurationValue (sectionName, variableName); try { return Double.parseDouble (sNum); } catch (NumberFormatException ex) { throw new ConfigurationException (Package.BUNDLE_NAME, "Configuration.badFloatValue", "Bad floating point value " + "\"{0}\" for variable \"{1}\" " + "in section \"{2}\"", new Object[] { sNum, variableName, sectionName }); } } /** * Convenience method to get and convert an optional boolean parameter. * The default value applies if the variable is missing or is there * but has an empty value. * * @param sectionName section name * @param variableName variable name * @param defaultValue default value if not found * * @return the value, or the default value if not found * * @throws NoSuchSectionException no such section * @throws ConfigurationException bad numeric value */ public boolean getOptionalBooleanValue (String sectionName, String variableName, boolean defaultValue) throws NoSuchSectionException, ConfigurationException { boolean result = defaultValue; try { String s = getConfigurationValue (sectionName, variableName); if (s.trim().length() == 0) result = defaultValue; else result = TextUtil.booleanFromString (s); } catch (NoSuchVariableException ex) { result = defaultValue; } catch (IllegalArgumentException ex) { throw new ConfigurationException (ex.getMessage()); } return result; } /** * Convenience method to get and convert a required boolean parameter. * * @param sectionName section name * @param variableName variable name * * @return the value * * @throws NoSuchSectionException no such section * @throws NoSuchVariableException no such variable * @throws ConfigurationException bad numeric value */ public boolean getRequiredBooleanValue (String sectionName, String variableName) throws NoSuchSectionException, ConfigurationException, NoSuchVariableException { return Boolean.valueOf (getConfigurationValue (sectionName, variableName)) .booleanValue(); } /** * Convenience method to get an optional string value. The default * value applies if the variable is missing or is there but has an * empty value. * * @param sectionName section name * @param variableName variable name * @param defaultValue default value if not found * * @return the value, or the default value if not found * * @throws NoSuchSectionException no such section * @throws ConfigurationException bad numeric value */ public String getOptionalStringValue (String sectionName, String variableName, String defaultValue) throws NoSuchSectionException, ConfigurationException { String result; try { result = getConfigurationValue (sectionName, variableName); if (result.trim().length() == 0) result = defaultValue; } catch (NoSuchVariableException ex) { result = defaultValue; } return result; } /** * Get the value associated with a given variable. Required by the * {@link VariableDereferencer} interface, this method is used during * parsing to handle variable substitutions (but also potentially * useful by other applications). See this class's documentation for * details on variable references. * * @param varName The name of the variable for which the value is * desired. * @param context a context object, passed through from the caller * to the dereferencer, or null if there isn't one. * For this class, the context object is a * SubstitutionContext variable. * * @return The variable's value. If the variable has no value, this * method must return the empty string (""). It is important * <b>not</b> to return null. * * @throws VariableSubstitutionException variable references itself */ public String getVariableValue (String varName, Object context) throws VariableSubstitutionException { int i; Section section = null; String sectionName; String value = null; SubstitutionContext substContext = (SubstitutionContext) context; Section variableParentSection; Variable currentVariable; try { checkVariableName (varName); } catch (ConfigurationException ex) { throw new VariableSubstitutionException (ex); } currentVariable = substContext.currentVariable; if (currentVariable.getName().equals (varName)) { throw new VariableSubstitutionException (Package.BUNDLE_NAME, "Configuration.recursiveSubst", "Attempt to substitute value for variable " + "\"{0}\" within itself.", new Object[] {varName}); } variableParentSection = substContext.currentVariable.getSection(); i = varName.indexOf (':'); if (i == -1) { // No section in the variable reference. Use the variable's // context. section = variableParentSection; } else { sectionName = varName.substring (0, i); varName = varName.substring (i + 1); if (sectionName.equals (SYSTEM_SECTION_NAME)) section = systemSection; else if (sectionName.equals (PROGRAM_SECTION_NAME)) section = programSection; else section = (Section) sectionsByName.get (sectionName); } if (section != null) { if (variableParentSection.getID() < section.getID()) { String parentSectionName = variableParentSection.getName(); String thisSectionName = section.getName(); throw new VariableSubstitutionException (Package.BUNDLE_NAME, "Configuration.badSectionRef", "Variable \"{0}\" in section \"{1}\" cannot substitute " + "the value of variable \"{2}\" from section \"{3}\", " + "because section \"{3}\" appears after section \"{1}\" " + "in the configuration file.", new Object[] { substContext.currentVariable.getName(), parentSectionName, varName, thisSectionName, thisSectionName, parentSectionName }); } Variable varToSubst; try { varToSubst = section.getVariable (varName); } catch (ConfigurationException ex) { throw new VariableSubstitutionException (ex.getMessage()); } if (varToSubst != null) value = varToSubst.getCookedValue(); } substContext.totalSubstitutions++; return (value == null) ? "" : value; } public boolean legalVariableCharacter (char c) { return ! (UnixShellVariableSubstituter.isVariableMetacharacter (c)); } /** * Load configuration from a <tt>File</tt>. Any existing data is * discarded. * * @param file the file * * @throws IOException read error * @throws ConfigurationException parse error */ public void load (File file) throws IOException, ConfigurationException { clear(); URL url = file.toURL(); parse (new FileInputStream (file), url); this.configURL = url; } /** * Load configuration from a file specified as a pathname. Any existing * data is discarded. * * @param path the path * * @throws FileNotFoundException specified file doesn't exist * @throws IOException can't open or read file * @throws ConfigurationException error in configuration data */ public void load (String path) throws FileNotFoundException, IOException, ConfigurationException { clear(); URL url = new File (path).toURL(); parse (new FileInputStream (path), url); this.configURL = url; } /** * Load configuration from a URL. Any existing data is discarded. * * @param url the URL * * @throws IOException read error * @throws ConfigurationException parse error */ public void load (URL url) throws IOException, ConfigurationException { clear(); parse (url.openStream(), url); this.configURL = url; } /** * Load configuration from an <tt>InputStream</tt>. Any existing data * is discarded. * * @param iStream the <tt>InputStream</tt> * * @throws IOException can't open or read URL * @throws ConfigurationException error in configuration data */ public void load (InputStream iStream) throws IOException, ConfigurationException { clear(); parse (iStream, null); } /** * Set a variable's value. If the variable does not exist, it is created. * If it does exist, its current value is overwritten with the new one. * Metacharacters and variable references are not expanded unless the * <tt>expand</tt> parameter is <tt>true</tt>. An <tt>expand</tt> value * of <tt>false</tt> is useful when creating new configuration data to * be written later. * * @param sectionName name of existing section to contain the variable * @param variableName name of variable to set * @param value variable's value * @param expand <tt>true</tt> to expand metacharacters and variable * references in the value, <tt>false</tt> to leave * the value untouched. * * @throws NoSuchSectionException section does not exist * @throws VariableSubstitutionException variable substitution error */ public void setVariable (String sectionName, String variableName, String value, boolean expand) throws NoSuchSectionException, VariableSubstitutionException { Section section = (Section) sectionsByName.get (sectionName); if (section == null) throw new NoSuchSectionException (sectionName); Variable variable = null; try { variable = section.getVariable (variableName); } catch (ConfigurationException ex) { throw new VariableSubstitutionException (ex.getMessage()); } if (variable != null) variable.setValue (value); else variable = section.addVariable (variableName, value); if (expand) { try { substituteVariables (variable, new UnixShellVariableSubstituter(), true); } catch (ConfigurationException ex) { throw new VariableSubstitutionException (ex.getMessage()); } } } /** * Writes the configuration data to a <tt>PrintWriter</tt>. The sections * and variables within the sections are written in the order they were * originally read from the file. Non-printable characters (and a few * others) are encoded into metacharacter sequences. Comments and * variable references are not propagated, since they are not retained * when the data is parsed. * * @param out where to write the configuration data * * @throws ConfigurationException on error * * @see XStringBuffer#encodeMetacharacters() */ public void write (PrintWriter out) throws ConfigurationException { Iterator itSect; Iterator itVar; Section section; String varName; Variable var; XStringBuffer value = new XStringBuffer(); boolean firstSection = true; out.print (COMMENT_CHARS.charAt (0)); out.print (" Written by "); out.println (this.getClass().getName()); out.print (COMMENT_CHARS.charAt (0)); out.print (" on "); out.println (new Date().toString()); out.println(); for (itSect = sectionsInOrder.iterator(); itSect.hasNext(); ) { section = (Section) itSect.next(); if (! firstSection) out.println(); out.println (SECTION_START + section.getName() + SECTION_END); firstSection = false; for (itVar = section.getVariableNames().iterator(); itVar.hasNext(); ) { varName = (String) itVar.next(); var = section.getVariable (varName); value.setLength (0); value.append (var.getCookedValue()); value.encodeMetacharacters(); out.println (varName + ": " + value.toString()); } } } /** * Writes the configuration data to a <tt>PrintStream</tt>. The sections * and variables within the sections are written in the order they were * originally read from the file. Non-printable characters (and a few * others) are encoded into metacharacter sequences. Comments and * variable references are not propagated, since they are not retained * when the data is parsed. * * @param out where to write the configuration data * * @throws ConfigurationException on error * * @see XStringBuffer#encodeMetacharacters() */ public void write (PrintStream out) throws ConfigurationException { PrintWriter w = new PrintWriter (out); write (w); w.flush(); } /** * Parse configuration data from the specified stream. * * @param in the input stream * @param url the URL associated with the stream, or null if not known * * @throws ConfigurationException parse error */ private synchronized void parse (InputStream in, URL url) throws ConfigurationException { loadConfiguration (in, url, new ParseContext()); } /** * Load the configuration data into memory, without processing * metacharacters or variable substitution. Includes are processed, * though. * * @param in input stream * @param url URL associated with the stream, or null if not known * @param parseContext current parsing context * * @throws IOException read error * @throws ConfigurationException parse error */ private void loadConfiguration (InputStream in, URL url, ParseContext parseContext) throws ConfigurationException { BufferedReader r; Line line = new Line(); String sURL = url.toExternalForm(); // Now, create the phantom program and system sections. These MUST // be created first, or other sections won't be able to substitute // from them. (i.e., They must have the lowest IDs.) programSection = new ProgramSection (PROGRAM_SECTION_NAME, nextSectionID()); systemSection = new SystemSection (SYSTEM_SECTION_NAME, nextSectionID()); if (parseContext.openURLs.contains (sURL)) { throw new ConfigurationException (Package.BUNDLE_NAME, "Configuration.recursiveInclude", "{0}, line {1}: Attempt to include \"{2}\" " + "from itself, either directly or indirectly.", new Object[] { url.toExternalForm(), String.valueOf (line.number), sURL }); } parseContext.openURLs.add (sURL); // Parse the entire file into memory before doing variable // substitution and metacharacter expansion. r = new BufferedReader (new InputStreamReader (in)); while (readLogicalLine (r, line)) { try { switch (line.type) { case Line.COMMENT: case Line.BLANK: break; case Line.INCLUDE: handleInclude (line, url, parseContext); break; case Line.SECTION: parseContext.currentSection = handleNewSection (line, url); break; case Line.VARIABLE: if (parseContext.currentSection == null) { throw new ConfigurationException (Package.BUNDLE_NAME, "Configuration.varBeforeSection", "{0}, line {1}: Variable assignment " + "before first section.", new Object[] { url.toExternalForm(), String.valueOf (line.number) }); } handleVariable (line, url, parseContext); break; default: throw new IllegalStateException ("Bug: line.type=" + line.type); } } catch (IOException ex) { throw new ConfigurationException (getExceptionPrefix (line, url) + ex.toString()); } } parseContext.openURLs.remove (sURL); } /** * Handle a new section. * * @param line line buffer * @param url URL currently being processed, or null if unknown * * @return a new Section object, which has been stored in the appropriate * places * * @throws ConfigurationException configuration error */ private Section handleNewSection (Line line, URL url) throws ConfigurationException { String s = line.buffer.toString().trim(); if (s.charAt (0) != SECTION_START) { throw new ConfigurationException (Package.BUNDLE_NAME, "Configuration.badSectionBegin", "{0}, line {1}: Section does not begin with \"{2}\"", new Object[] { url.toExternalForm(), String.valueOf (line.number), String.valueOf (SECTION_START) }); } else if (s.charAt (s.length() - 1) != SECTION_END) { throw new ConfigurationException (Package.BUNDLE_NAME, "Configuration.badSectionEnd", "{0}, line {1}: Section does not end with \"{2}\"", new Object[] { url.toExternalForm(), String.valueOf (line.number), String.valueOf (SECTION_END) }); } return makeNewSection (s.substring (1, s.length() - 1)); } /** * Handle a new variable during parsing. * * @param line line buffer * @param url URL currently being processed, or null if unknown * @param parseContext current parsing context * * @throws ConfigurationException configuration error */ private void handleVariable (Line line, URL url, ParseContext parseContext) throws ConfigurationException { char[] s = line.buffer.toString().toCharArray(); int iSep; for (iSep = 0; iSep < s.length; iSep++) { if ((s[iSep] == ':') || (s[iSep] == '=')) break; } if (iSep == s.length) { throw new ConfigurationException (Package.BUNDLE_NAME, "Configuration.missingAssignOp", "{0}, line {1}: Missing \"=\" " + "or \":\" for variable " + "definition.", new Object[] { url.toExternalForm(), String.valueOf (line.number) }); } if (iSep == 0) { throw new ConfigurationException (Package.BUNDLE_NAME, "Configuration.noVariablName", "{0}, line {1}: Missing " + "variable name for variable " + "definition.", new Object[] { url.toExternalForm(), String.valueOf (line.number) }); } int i = 0; int j = iSep - 1; while (Character.isWhitespace (s[i])) i++; while (Character.isWhitespace (s[j])) j if (i > j) { throw new ConfigurationException (Package.BUNDLE_NAME, "Configuration.noVariablName", "{0}, line {1}: Missing " + "variable name for variable " + "definition.", new Object[] { url.toExternalForm(), String.valueOf (line.number) }); } String varName = new String (s, i, j - i + 1); if (varName.length() == 0) { throw new ConfigurationException (Package.BUNDLE_NAME, "Configuration.noVariablName", "{0}, line {1}: Missing " + "variable name for variable " + "definition.", new Object[] { url.toExternalForm(), String.valueOf (line.number) }); } checkVariableName (varName); i = skipWhitespace (s, iSep + 1); j = s.length - i; Section currentSection = parseContext.currentSection; String value = new String (s, i, j); Variable existing = currentSection.getVariable (varName); if (existing != null) { throw new ConfigurationException (Package.BUNDLE_NAME, "Configuration.duplicateVar", "{0}, line {1}: Section \"{2}\" has a " + "duplicate definition for variable " + "\"{3}\". The first instance was defined " + "on line {4}.", new Object[] { url.toExternalForm(), String.valueOf (line.number), currentSection.getName(), varName, String.valueOf (existing.lineWhereDefined()) }); } Variable newVar = currentSection.addVariable (varName, value, line.number); // Expand the metacharacters and variable references in the variable. try { newVar.segmentValue(); VariableSubstituter sub = new UnixShellVariableSubstituter(); substituteVariables (newVar, sub, false); decodeMetacharacters (newVar); newVar.reassembleCookedValueFromSegments(); } catch (VariableSubstitutionException ex) { throw new ConfigurationException (ex.getMessage()); } } private void checkVariableName (String varName) throws ConfigurationException { char[] ch = varName.toCharArray(); for (int i = 0; i < ch.length; i++) { if (! legalVariableCharacter (ch[i])) { throw new ConfigurationException (Package.BUNDLE_NAME, "Configuration.badVariableName", "\"{0}\" is an illegal variable name", new Object[] {varName}); } } } /** * Handle an include directive. * * @param line line buffer * @param url URL currently being processed, or null if unknown * @param parseContext current parsing context * * @throws IOException I/O error opening or reading include * @throws ConfigurationException configuration error */ private void handleInclude (Line line, URL url, ParseContext parseContext) throws IOException, ConfigurationException { if (parseContext.includeFileNestingLevel >= MAX_INCLUDE_NESTING_LEVEL) { throw new ConfigurationException (Package.BUNDLE_NAME, "Configuration.maxNestedIncludeExceeded", "{0}, line {1}: Exceeded maximum nested " + "include level of {2}.", new Object[] { url.toExternalForm(), String.valueOf (line.number), String.valueOf (MAX_INCLUDE_NESTING_LEVEL) }); } parseContext.includeFileNestingLevel++; String s = line.buffer.toString(); // Parse the file name. String includeTarget = s.substring (INCLUDE.length() + 1).trim(); int len = includeTarget.length(); // Make sure double quotes surround the file or URL. if ((len < 2) || (! includeTarget.startsWith ("\"")) || (! includeTarget.endsWith ("\""))) { throw new ConfigurationException (Package.BUNDLE_NAME, "Configuration.malformedDirective", "{0}, line {1}: Malformed \"{2}\" directive", new Object[] { url.toExternalForm(), String.valueOf (line.number), INCLUDE }); } // Extract the file. includeTarget = includeTarget.substring (1, len - 1); if (includeTarget.length() == 0) { throw new ConfigurationException (Package.BUNDLE_NAME, "Configuration.includeMissingFile", "{0}, line {1}: Missing file name or URL in " + "\"{2}\" directive", new Object[] { url.toExternalForm(), String.valueOf (line.number), INCLUDE }); } // Process the include try { loadInclude (new URL (includeTarget), parseContext); } catch (MalformedURLException ex) { // Not obviously a URL. First, determine whether it has // directory information or not. If not, try to use the // parent's directory information. if (FileUtil.isAbsolutePath (includeTarget)) { loadInclude (new URL (url.getProtocol(), url.getHost(), url.getPort(), includeTarget), parseContext); } else { // It's relative to the parent. If the parent URL is not // specified, then we can't do anything except try to load // the include as is. It'll probably fail... if (url == null) { loadInclude (new File (includeTarget).toURL(), parseContext); } else { String parent = new File (url.getFile()).getParent(); if (parent == null) parent = ""; loadInclude (new URL (url.getProtocol(), url.getHost(), url.getPort(), parent + "/" + includeTarget), parseContext); } } } parseContext.includeFileNestingLevel } /** * Actually attempts to load an include reference. This is basically just * a simplified front-end to loadConfiguration(). * * @param url the URL to be included * @param parseContext current parsing context * * @throws IOException I/O error * @throws ConfigurationException configuration error */ private void loadInclude (URL url, ParseContext parseContext) throws IOException, ConfigurationException { loadConfiguration (url.openStream(), url, parseContext); } /** * Read the next logical line of input from a config file. * * @param r the reader * @param line where to store the line. The line number in this * object is incremented, the "buffer" field is updated, * and the "type" field is set appropriately. * * @return <tt>true</tt> if a line was read, <tt>false</tt> for EOF. * * @throws ConfigurationException read error */ private boolean readLogicalLine (BufferedReader r, Line line) throws ConfigurationException { boolean continued = false; boolean gotSomething = false; line.newLine(); for (;;) { String s; try { s = r.readLine(); } catch (IOException ex) { throw new ConfigurationException (ex.toString()); } if (s == null) break; gotSomething = true; line.number++; // Strip leading white space on all lines. int i; char[] chars = s.toCharArray(); i = skipWhitespace (chars, 0); if (i < chars.length) s = s.substring (i); else s = ""; if (! continued) { // First line. Determine what it is. char firstChar; if (s.length() == 0) line.type = Line.BLANK; else if (COMMENT_CHARS.indexOf (s.charAt (0)) != -1) line.type = Line.COMMENT; else if (s.charAt (0) == SECTION_START) line.type = Line.SECTION; else if (new StringTokenizer (s).nextToken().equals (INCLUDE)) line.type = Line.INCLUDE; else line.type = Line.VARIABLE; } if ((line.type == Line.VARIABLE) && (hasContinuationMark (s))) { continued = true; line.buffer.append (s.substring (0, s.length() - 1)); } else { line.buffer.append (s); break; } } return gotSomething; } /** * Determine whether a line has a continuation mark or not. * * @param s the line * * @return true if there's a continuation mark, false if not */ private boolean hasContinuationMark (String s) { boolean has = false; if (s.length() > 0) { char[] chars = s.toCharArray(); if (chars[chars.length-1] == '\\') { // Possibly. See if there are an odd number of them. int total = 0; for (int i = chars.length - 1; i >= 0; i { if (chars[i] != '\\') break; total++; } has = ((total % 2) == 1); } } return has; } /** * Get an appropriate exception prefix (e.g., line number, etc.) * * @param line line buffer * @param url URL currently being processed, or null if unknown * * @return a suitable string */ private String getExceptionPrefix (Line line, URL url) { StringBuffer buf = new StringBuffer(); if (url != null) { buf.append (url.toExternalForm()); buf.append (", line "); } else { buf.append ("Line "); } buf.append (line.number); buf.append (": "); return buf.toString(); } /** * Handle metacharacter substitution for a variable value. * * @param var The current variable being processed * * @return the expanded result * * @throws VariableSubstitutionException variable substitution error * @throws ConfigurationException some other configuration error */ private void decodeMetacharacters (Variable var) throws VariableSubstitutionException, ConfigurationException { ValueSegment[] segments = var.getCookedSegments(); for (int i = 0; i < segments.length; i++) { ValueSegment segment = segments[i]; if (segment.isLiteral) continue; segment.segmentBuf.decodeMetacharacters(); } } /** * Handle variable substitution for a variable value. * * @param var The current variable being processed * @param substituter VariableSubstituter to use * @param concatSegments Re-concatenate the segments * * @return the expanded result * * @throws VariableSubstitutionException variable substitution error * @throws ConfigurationException some other configuration error */ private void substituteVariables (Variable var, VariableSubstituter substituter, boolean concatSegments) throws VariableSubstitutionException, ConfigurationException { ValueSegment[] segments = var.getCookedSegments(); SubstitutionContext context = new SubstitutionContext (var); for (int i = 0; i < segments.length; i++) { // Keep substituting the current variable's value until there // no more substitutions are performed. This handles the case // where a dereferenced variable value contains its own // variable references. ValueSegment segment = segments[i]; if (segment.isLiteral) continue; String s = segment.segmentBuf.toString(); do { context.totalSubstitutions = 0; s = substituter.substitute (s, this, this, context); } while (context.totalSubstitutions > 0); segment.segmentBuf.setLength (0); segment.segmentBuf.append (s); } if (concatSegments) var.reassembleCookedValueFromSegments(); } /** * Get index of first non-whitespace character. * * @param s string to check * @param start starting point * * @return index of first non-whitespace character past "start", or -1 */ private int skipWhitespace (String s, int start) { return skipWhitespace (s.toCharArray(), start); } /** * Get index of first non-whitespace character. * * @param chars character array to check * @param start starting point * * @return index of first non-whitespace character past "start", or -1 */ private int skipWhitespace (char[] chars, int start) { while (start < chars.length) { if (! Character.isWhitespace (chars[start])) break; start++; } return start; } /** * Create and save a new Section. * * @param sectionName the name * * @return the Section object, which has been saved. */ private Section makeNewSection (String sectionName) { int id = nextSectionID(); Section section = new Section (sectionName, id); sectionsInOrder.add (section); sectionsByName.put (sectionName, section); return section; } /** * Get the next section ID * * @return the ID */ private synchronized int nextSectionID() { return ++nextSectionID; } }
package com.belladati.sdk.impl; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; import org.apache.http.entity.StringEntity; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.belladati.sdk.exception.interval.InvalidAbsoluteIntervalException; import com.belladati.sdk.exception.interval.InvalidRelativeIntervalException; import com.belladati.sdk.exception.interval.NullIntervalException; import com.belladati.sdk.impl.ViewImpl.UnknownViewTypeException; import com.belladati.sdk.intervals.AbsoluteInterval; import com.belladati.sdk.intervals.DateUnit; import com.belladati.sdk.intervals.Interval; import com.belladati.sdk.intervals.IntervalUnit; import com.belladati.sdk.intervals.RelativeInterval; import com.belladati.sdk.intervals.TimeUnit; import com.belladati.sdk.test.TestRequestHandler; import com.belladati.sdk.view.View; import com.belladati.sdk.view.ViewType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.IntNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; @Test public class IntervalTest extends SDKTest { private final String viewId = "viewId"; private final String viewName = "name"; private final String viewsUri = String.format("/api/reports/views/%s/chart", viewId); private final Calendar start = new GregorianCalendar(2012, 1, 2, 3, 4, 5); private final Calendar end = new GregorianCalendar(2013, 7, 8, 9, 10, 11); private final ObjectMapper mapper = new ObjectMapper(); /** absolute time interval down to seconds */ public void absoluteSecondsToJson() { Interval<?> interval = new AbsoluteInterval<IntervalUnit>(TimeUnit.SECOND, start, end); ObjectNode from = mapper.createObjectNode().put("hour", start.get(Calendar.HOUR)) .put("minute", start.get(Calendar.MINUTE)).put("second", start.get(Calendar.SECOND)); ObjectNode to = mapper.createObjectNode().put("hour", end.get(Calendar.HOUR)).put("minute", end.get(Calendar.MINUTE)) .put("second", end.get(Calendar.SECOND)); JsonNode expectedJson = buildIntervalNode(TimeUnit.SECOND, from, to, "absolute"); assertEquals(interval.toJson(), expectedJson); assertEquals(interval.toString(), expectedJson.toString()); } /** absolute time interval down to minutes */ public void absoluteMinutesToJson() { Interval<?> interval = new AbsoluteInterval<IntervalUnit>(TimeUnit.MINUTE, start, end); ObjectNode from = mapper.createObjectNode().put("hour", start.get(Calendar.HOUR)) .put("minute", start.get(Calendar.MINUTE)); ObjectNode to = mapper.createObjectNode().put("hour", end.get(Calendar.HOUR)).put("minute", end.get(Calendar.MINUTE)); JsonNode expectedJson = buildIntervalNode(TimeUnit.MINUTE, from, to, "absolute"); assertEquals(interval.toJson(), expectedJson); assertEquals(interval.toString(), expectedJson.toString()); } /** absolute time interval down to hours */ public void absoluteHoursToJson() { Interval<?> interval = new AbsoluteInterval<IntervalUnit>(TimeUnit.HOUR, start, end); ObjectNode from = mapper.createObjectNode().put("hour", start.get(Calendar.HOUR)); ObjectNode to = mapper.createObjectNode().put("hour", end.get(Calendar.HOUR)); JsonNode expectedJson = buildIntervalNode(TimeUnit.HOUR, from, to, "absolute"); assertEquals(interval.toJson(), expectedJson); assertEquals(interval.toString(), expectedJson.toString()); } /** absolute date interval down to days */ public void absoluteDaysToJson() { Interval<?> interval = new AbsoluteInterval<IntervalUnit>(DateUnit.DAY, start, end); ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)) .put("month", start.get(Calendar.MONTH) + 1).put("day", start.get(Calendar.DAY_OF_MONTH)); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)).put("month", end.get(Calendar.MONTH) + 1) .put("day", end.get(Calendar.DAY_OF_MONTH)); JsonNode expectedJson = buildIntervalNode(DateUnit.DAY, from, to, "absolute"); assertEquals(interval.toJson(), expectedJson); assertEquals(interval.toString(), expectedJson.toString()); } /** absolute date interval down to weeks */ public void absoluteWeeksToJson() { Interval<?> interval = new AbsoluteInterval<IntervalUnit>(DateUnit.WEEK, start, end); ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)) .put("week", start.get(Calendar.WEEK_OF_YEAR)); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)).put("week", end.get(Calendar.WEEK_OF_YEAR)); JsonNode expectedJson = buildIntervalNode(DateUnit.WEEK, from, to, "absolute"); assertEquals(interval.toJson(), expectedJson); assertEquals(interval.toString(), expectedJson.toString()); } /** absolute date interval down to months */ public void absoluteMonthsToJson() { Interval<?> interval = new AbsoluteInterval<IntervalUnit>(DateUnit.MONTH, start, end); ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)) .put("month", start.get(Calendar.MONTH) + 1); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)).put("month", end.get(Calendar.MONTH) + 1); JsonNode expectedJson = buildIntervalNode(DateUnit.MONTH, from, to, "absolute"); assertEquals(interval.toJson(), expectedJson); assertEquals(interval.toString(), expectedJson.toString()); } /** absolute date interval down to quarters */ public void absoluteQuartersToJson() { Interval<?> interval = new AbsoluteInterval<IntervalUnit>(DateUnit.QUARTER, start, end); ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)) .put("quarter", start.get(Calendar.MONTH) / 3 + 1); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)) .put("quarter", end.get(Calendar.MONTH) / 3 + 1); JsonNode expectedJson = buildIntervalNode(DateUnit.QUARTER, from, to, "absolute"); assertEquals(interval.toJson(), expectedJson); assertEquals(interval.toString(), expectedJson.toString()); } /** absolute date interval down to years */ public void absoluteYearsToJson() { Interval<?> interval = new AbsoluteInterval<IntervalUnit>(DateUnit.YEAR, start, end); ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)); JsonNode expectedJson = buildIntervalNode(DateUnit.YEAR, from, to, "absolute"); assertEquals(interval.toJson(), expectedJson); assertEquals(interval.toString(), expectedJson.toString()); } /** relative intervals */ @Test(dataProvider = "intervalUnitProvider") public void relativeToJson(IntervalUnit unit) { Interval<?> interval = new RelativeInterval<IntervalUnit>(unit, -10, 10); JsonNode from = new IntNode(-10); JsonNode to = new IntNode(10); JsonNode expectedJson = buildIntervalNode(unit, from, to, "relative"); assertEquals(interval.toJson(), expectedJson); assertEquals(interval.toString(), expectedJson.toString()); } /** start and end may be equal in absolute intervals */ public void startEndEqualAbsolute() { Interval<?> interval = new AbsoluteInterval<IntervalUnit>(TimeUnit.HOUR, start, start); ObjectNode from = mapper.createObjectNode().put("hour", start.get(Calendar.HOUR)); ObjectNode to = mapper.createObjectNode().put("hour", start.get(Calendar.HOUR)); JsonNode expectedJson = buildIntervalNode(TimeUnit.HOUR, from, to, "absolute"); assertEquals(interval.toJson(), expectedJson); assertEquals(interval.toString(), expectedJson.toString()); } /** start and end may be equal in relative intervals */ public void startEndEqualRelative() { Interval<?> interval = new RelativeInterval<IntervalUnit>(DateUnit.DAY, 10, 10); JsonNode from = new IntNode(10); JsonNode to = new IntNode(10); JsonNode expectedJson = buildIntervalNode(DateUnit.DAY, from, to, "relative"); assertEquals(interval.toJson(), expectedJson); assertEquals(interval.toString(), expectedJson.toString()); } /** start may not be later than end in absolute intervals */ public void startAfterEndAbsolute() { try { new AbsoluteInterval<IntervalUnit>(TimeUnit.HOUR, end, start); fail("did not throw exception"); } catch (InvalidAbsoluteIntervalException e) { assertEquals(e.getIntervalUnit(), TimeUnit.HOUR); assertEquals(e.getStart(), end); assertEquals(e.getEnd(), start); } } /** start may not be greater than end in relative intervals */ public void startAfterEndRelative() { try { new RelativeInterval<IntervalUnit>(DateUnit.DAY, 10, -10); fail("did not throw exception"); } catch (InvalidRelativeIntervalException e) { assertEquals(e.getIntervalUnit(), DateUnit.DAY); assertEquals((int) e.getStart(), 10); assertEquals((int) e.getEnd(), -10); } } /** interval unit may not be null in absolute intervals */ @Test(expectedExceptions = NullIntervalException.class) public void unitNullAbsolute() { new AbsoluteInterval<IntervalUnit>(null, start, end); } /** interval unit may not be null in relative intervals */ @Test(expectedExceptions = NullIntervalException.class) public void unitNullRelative() { new RelativeInterval<IntervalUnit>(null, -1, 1); } /** interval start may not be null */ @Test(expectedExceptions = NullIntervalException.class) public void startNullAbsolute() { new AbsoluteInterval<IntervalUnit>(TimeUnit.HOUR, null, end); } /** interval end may not be null */ @Test(expectedExceptions = NullIntervalException.class) public void endNullAbsolute() { new AbsoluteInterval<IntervalUnit>(TimeUnit.HOUR, start, null); } /** Query parameters with time only are correct. */ public void queryStringTimeOnly() throws UnknownViewTypeException { final ObjectNode from = mapper.createObjectNode().put("hour", start.get(Calendar.HOUR)); final ObjectNode to = mapper.createObjectNode().put("hour", end.get(Calendar.HOUR)); server.register(viewsUri, new TestRequestHandler() { @Override protected void handle(HttpHolder holder) throws IOException { String intervalString = holder.getUrlParameters().get("dateTimeDefinition"); assertNotNull(intervalString); ObjectNode intervalNode = buildIntervalNode(TimeUnit.HOUR, from, to, "absolute"); assertEquals(mapper.readTree(intervalString), intervalNode); holder.response.setEntity(new StringEntity("{}")); } }); service.createViewLoader(viewId, ViewType.CHART) .setTimeInterval(new AbsoluteInterval<TimeUnit>(TimeUnit.HOUR, start, end)).loadContent(); server.assertRequestUris(viewsUri); } /** Query parameters with date only are correct. */ public void queryStringDateOnly() throws UnknownViewTypeException { final ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)); final ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)); server.register(viewsUri, new TestRequestHandler() { @Override protected void handle(HttpHolder holder) throws IOException { String intervalString = holder.getUrlParameters().get("dateTimeDefinition"); assertNotNull(intervalString); ObjectNode intervalNode = buildIntervalNode(DateUnit.YEAR, from, to, "absolute"); assertEquals(mapper.readTree(intervalString), intervalNode); holder.response.setEntity(new StringEntity("{}")); } }); service.createViewLoader(viewId, ViewType.CHART) .setDateInterval(new AbsoluteInterval<DateUnit>(DateUnit.YEAR, start, end)).loadContent(); server.assertRequestUris(viewsUri); } /** Query parameters with both intervals are correct. */ public void queryStringBoth() throws UnknownViewTypeException { final ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)); final ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)); server.register(viewsUri, new TestRequestHandler() { @Override protected void handle(HttpHolder holder) throws IOException { String intervalString = holder.getUrlParameters().get("dateTimeDefinition"); assertNotNull(intervalString); ObjectNode intervalNode = buildIntervalNode(DateUnit.YEAR, from, to, "absolute"); intervalNode.setAll(buildIntervalNode(TimeUnit.MINUTE, new IntNode(-10), new IntNode(10), "relative")); assertEquals(mapper.readTree(intervalString), intervalNode); holder.response.setEntity(new StringEntity("{}")); } }); service.createViewLoader(viewId, ViewType.CHART) .setDateInterval(new AbsoluteInterval<DateUnit>(DateUnit.YEAR, start, end)) .setTimeInterval(new RelativeInterval<TimeUnit>(TimeUnit.MINUTE, -10, 10)).loadContent(); server.assertRequestUris(viewsUri); } /** absolute time interval in seconds */ public void predefinedSecondInterval() throws UnknownViewTypeException { ObjectNode from = mapper.createObjectNode().put("hour", start.get(Calendar.HOUR)) .put("minute", start.get(Calendar.MINUTE)).put("second", start.get(Calendar.SECOND)); ObjectNode to = mapper.createObjectNode().put("hour", end.get(Calendar.HOUR)).put("minute", end.get(Calendar.MINUTE)) .put("second", end.get(Calendar.SECOND)); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(TimeUnit.SECOND, from, to, "absolute")); View view = ViewImpl.buildView(service, viewNode); Calendar expectedStart = new GregorianCalendar(0, 0, 0, start.get(Calendar.HOUR), start.get(Calendar.MINUTE), start.get(Calendar.SECOND)); Calendar expectedEnd = new GregorianCalendar(0, 0, 0, end.get(Calendar.HOUR), end.get(Calendar.MINUTE), end.get(Calendar.SECOND)); assertFalse(view.hasPredefinedDateInterval()); assertTrue(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); AbsoluteInterval<TimeUnit> interval = (AbsoluteInterval<TimeUnit>) view.getPredefinedTimeInterval(); assertEquals(interval.getIntervalUnit(), TimeUnit.SECOND); assertEquals(interval.getStart(), expectedStart); assertEquals(interval.getEnd(), expectedEnd); } /** absolute time interval in minutes */ public void predefinedMinuteInterval() throws UnknownViewTypeException { ObjectNode from = mapper.createObjectNode().put("hour", start.get(Calendar.HOUR)) .put("minute", start.get(Calendar.MINUTE)); ObjectNode to = mapper.createObjectNode().put("hour", end.get(Calendar.HOUR)).put("minute", end.get(Calendar.MINUTE)); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(TimeUnit.MINUTE, from, to, "absolute")); View view = ViewImpl.buildView(service, viewNode); Calendar expectedStart = new GregorianCalendar(0, 0, 0, start.get(Calendar.HOUR), start.get(Calendar.MINUTE), 0); Calendar expectedEnd = new GregorianCalendar(0, 0, 0, end.get(Calendar.HOUR), end.get(Calendar.MINUTE), 0); assertFalse(view.hasPredefinedDateInterval()); assertTrue(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); AbsoluteInterval<TimeUnit> interval = (AbsoluteInterval<TimeUnit>) view.getPredefinedTimeInterval(); assertEquals(interval.getIntervalUnit(), TimeUnit.MINUTE); assertEquals(interval.getStart(), expectedStart); assertEquals(interval.getEnd(), expectedEnd); } /** absolute time interval in hours */ public void predefinedHourInterval() throws UnknownViewTypeException { ObjectNode from = mapper.createObjectNode().put("hour", start.get(Calendar.HOUR)); ObjectNode to = mapper.createObjectNode().put("hour", end.get(Calendar.HOUR)); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(TimeUnit.HOUR, from, to, "absolute")); View view = ViewImpl.buildView(service, viewNode); Calendar expectedStart = new GregorianCalendar(0, 0, 0, start.get(Calendar.HOUR), 0, 0); Calendar expectedEnd = new GregorianCalendar(0, 0, 0, end.get(Calendar.HOUR), 0, 0); assertFalse(view.hasPredefinedDateInterval()); assertTrue(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); AbsoluteInterval<TimeUnit> interval = (AbsoluteInterval<TimeUnit>) view.getPredefinedTimeInterval(); assertEquals(interval.getIntervalUnit(), TimeUnit.HOUR); assertEquals(interval.getStart(), expectedStart); assertEquals(interval.getEnd(), expectedEnd); } /** absolute date interval in days */ public void predefinedDayInterval() throws UnknownViewTypeException { ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)) .put("month", start.get(Calendar.MONTH) + 1).put("day", start.get(Calendar.DAY_OF_MONTH)); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)).put("month", end.get(Calendar.MONTH) + 1) .put("day", end.get(Calendar.DAY_OF_MONTH)); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(DateUnit.DAY, from, to, "absolute")); View view = ViewImpl.buildView(service, viewNode); Calendar expectedStart = new GregorianCalendar(start.get(Calendar.YEAR), start.get(Calendar.MONTH), start.get(Calendar.DAY_OF_MONTH)); Calendar expectedEnd = new GregorianCalendar(end.get(Calendar.YEAR), end.get(Calendar.MONTH), end.get(Calendar.DAY_OF_MONTH)); assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); AbsoluteInterval<DateUnit> interval = (AbsoluteInterval<DateUnit>) view.getPredefinedDateInterval(); assertEquals(interval.getIntervalUnit(), DateUnit.DAY); assertEquals(interval.getStart(), expectedStart); assertEquals(interval.getEnd(), expectedEnd); assertNull(view.getPredefinedTimeInterval()); } /** absolute week interval in weeks */ public void predefinedWeekInterval() throws UnknownViewTypeException { ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)) .put("week", start.get(Calendar.WEEK_OF_YEAR)); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)).put("week", end.get(Calendar.WEEK_OF_YEAR)); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(DateUnit.WEEK, from, to, "absolute")); View view = ViewImpl.buildView(service, viewNode); Calendar expectedStart = new GregorianCalendar(start.get(Calendar.YEAR), 0, 1); expectedStart.set(Calendar.WEEK_OF_YEAR, start.get(Calendar.WEEK_OF_YEAR)); Calendar expectedEnd = new GregorianCalendar(end.get(Calendar.YEAR), 0, 1); expectedEnd.set(Calendar.WEEK_OF_YEAR, end.get(Calendar.WEEK_OF_YEAR)); assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); AbsoluteInterval<DateUnit> interval = (AbsoluteInterval<DateUnit>) view.getPredefinedDateInterval(); assertEquals(interval.getIntervalUnit(), DateUnit.WEEK); assertEquals(interval.getStart(), expectedStart); assertEquals(interval.getEnd(), expectedEnd); assertNull(view.getPredefinedTimeInterval()); } /** absolute date interval in months */ public void predefinedMonthInterval() throws UnknownViewTypeException { ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)) .put("month", start.get(Calendar.MONTH) + 1); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)).put("month", end.get(Calendar.MONTH) + 1); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(DateUnit.MONTH, from, to, "absolute")); View view = ViewImpl.buildView(service, viewNode); Calendar expectedStart = new GregorianCalendar(start.get(Calendar.YEAR), start.get(Calendar.MONTH), 1); Calendar expectedEnd = new GregorianCalendar(end.get(Calendar.YEAR), end.get(Calendar.MONTH), 1); assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); AbsoluteInterval<DateUnit> interval = (AbsoluteInterval<DateUnit>) view.getPredefinedDateInterval(); assertEquals(interval.getIntervalUnit(), DateUnit.MONTH); assertEquals(interval.getStart(), expectedStart); assertEquals(interval.getEnd(), expectedEnd); assertNull(view.getPredefinedTimeInterval()); } /** absolute date interval in quarters */ public void predefinedQuarterInterval() throws UnknownViewTypeException { ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)) .put("quarter", start.get(Calendar.MONTH) / 3 + 1); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)) .put("quarter", end.get(Calendar.MONTH) / 3 + 1); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(DateUnit.QUARTER, from, to, "absolute")); View view = ViewImpl.buildView(service, viewNode); Calendar expectedStart = new GregorianCalendar(start.get(Calendar.YEAR), (start.get(Calendar.MONTH) / 3) * 3, 1); Calendar expectedEnd = new GregorianCalendar(end.get(Calendar.YEAR), (end.get(Calendar.MONTH) / 3) * 3, 1); assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); AbsoluteInterval<DateUnit> interval = (AbsoluteInterval<DateUnit>) view.getPredefinedDateInterval(); assertEquals(interval.getIntervalUnit(), DateUnit.QUARTER); assertEquals(interval.getStart(), expectedStart); assertEquals(interval.getEnd(), expectedEnd); assertNull(view.getPredefinedTimeInterval()); } /** absolute date interval in years */ public void predefinedYearInterval() throws UnknownViewTypeException { ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(DateUnit.YEAR, from, to, "absolute")); View view = ViewImpl.buildView(service, viewNode); Calendar expectedStart = new GregorianCalendar(start.get(Calendar.YEAR), 0, 1); Calendar expectedEnd = new GregorianCalendar(end.get(Calendar.YEAR), 0, 1); assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); AbsoluteInterval<DateUnit> interval = (AbsoluteInterval<DateUnit>) view.getPredefinedDateInterval(); assertEquals(interval.getIntervalUnit(), DateUnit.YEAR); assertEquals(interval.getStart(), expectedStart); assertEquals(interval.getEnd(), expectedEnd); assertNull(view.getPredefinedTimeInterval()); } /** predefined relative intervals */ @Test(dataProvider = "intervalUnitProvider") public void predefinedRelativeInterval(IntervalUnit unit) throws UnknownViewTypeException { ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(unit, new IntNode(-3), new IntNode(3), "rElAtIvE")); View view = ViewImpl.buildView(service, viewNode); if (unit instanceof DateUnit) { assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); RelativeInterval<DateUnit> interval = (RelativeInterval<DateUnit>) view.getPredefinedDateInterval(); assertEquals(interval.getIntervalUnit(), unit); assertEquals(interval.getStart(), -3); assertEquals(interval.getEnd(), 3); assertNull(view.getPredefinedTimeInterval()); } else { assertFalse(view.hasPredefinedDateInterval()); assertTrue(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); RelativeInterval<TimeUnit> interval = (RelativeInterval<TimeUnit>) view.getPredefinedTimeInterval(); assertEquals(interval.getIntervalUnit(), unit); assertEquals(interval.getStart(), -3); assertEquals(interval.getEnd(), 3); } } /** an interval that's not absolute or relative */ @Test(dataProvider = "intervalUnitProvider") public void predefinedNotAbsoluteOrRelativeInterval(IntervalUnit unit) throws UnknownViewTypeException { ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(unit, new IntNode(-3), new IntNode(3), "something else")); View view = ViewImpl.buildView(service, viewNode); assertFalse(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); assertNull(view.getPredefinedTimeInterval()); } /** invalid relative intervals are ignored */ @Test(dataProvider = "intervalUnitProvider") public void invalidRelativeInterval(IntervalUnit unit) throws UnknownViewTypeException { ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(unit, new TextNode("abc"), new IntNode(3), "relative")); View view = ViewImpl.buildView(service, viewNode); assertFalse(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); assertNull(view.getPredefinedTimeInterval()); } /** invalid absolute intervals are ignored */ public void invalidAbsoluteInterval() throws UnknownViewTypeException { ObjectNode from = mapper.createObjectNode().put("year", "abc"); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(DateUnit.YEAR, from, to, "absolute")); View view = ViewImpl.buildView(service, viewNode); assertFalse(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); assertNull(view.getPredefinedTimeInterval()); } /** intervals with numeric strings instead of numbers are allowed */ @Test(dataProvider = "intervalUnitProvider") public void stringRelativeInterval(IntervalUnit unit) throws UnknownViewTypeException { ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(unit, new TextNode("-3"), new IntNode(3), "relative")); View view = ViewImpl.buildView(service, viewNode); if (unit instanceof DateUnit) { assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); RelativeInterval<DateUnit> interval = (RelativeInterval<DateUnit>) view.getPredefinedDateInterval(); assertEquals(interval.getIntervalUnit(), unit); assertEquals(interval.getStart(), -3); assertEquals(interval.getEnd(), 3); assertNull(view.getPredefinedTimeInterval()); } else { assertFalse(view.hasPredefinedDateInterval()); assertTrue(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); RelativeInterval<TimeUnit> interval = (RelativeInterval<TimeUnit>) view.getPredefinedTimeInterval(); assertEquals(interval.getIntervalUnit(), unit); assertEquals(interval.getStart(), -3); assertEquals(interval.getEnd(), 3); } } /** intervals with numeric strings instead of numbers are allowed */ public void stringAbsoluteInterval() throws UnknownViewTypeException { ObjectNode from = mapper.createObjectNode().put("year", "" + start.get(Calendar.YEAR)); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(DateUnit.YEAR, from, to, "absolute")); View view = ViewImpl.buildView(service, viewNode); assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); AbsoluteInterval<DateUnit> interval = (AbsoluteInterval<DateUnit>) view.getPredefinedDateInterval(); assertEquals(interval.getIntervalUnit(), DateUnit.YEAR); assertEquals(interval.getStart(), new GregorianCalendar(start.get(Calendar.YEAR), 0, 1)); assertEquals(interval.getEnd(), new GregorianCalendar(end.get(Calendar.YEAR), 0, 1)); assertNull(view.getPredefinedTimeInterval()); } /** intervals with numeric fraction strings instead of numbers are allowed */ @Test(dataProvider = "intervalUnitProvider") public void fractionRelativeInterval(IntervalUnit unit) throws UnknownViewTypeException { ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(unit, new TextNode("-3.0"), new IntNode(3), "relative")); View view = ViewImpl.buildView(service, viewNode); if (unit instanceof DateUnit) { assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); RelativeInterval<DateUnit> interval = (RelativeInterval<DateUnit>) view.getPredefinedDateInterval(); assertEquals(interval.getIntervalUnit(), unit); assertEquals(interval.getStart(), -3); assertEquals(interval.getEnd(), 3); assertNull(view.getPredefinedTimeInterval()); } else { assertFalse(view.hasPredefinedDateInterval()); assertTrue(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); RelativeInterval<TimeUnit> interval = (RelativeInterval<TimeUnit>) view.getPredefinedTimeInterval(); assertEquals(interval.getIntervalUnit(), unit); assertEquals(interval.getStart(), -3); assertEquals(interval.getEnd(), 3); } } /** intervals with numeric fraction strings instead of numbers are allowed */ public void fractionAbsoluteInterval() throws UnknownViewTypeException { ObjectNode from = mapper.createObjectNode().put("year", "" + start.get(Calendar.YEAR) + ".0"); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(DateUnit.YEAR, from, to, "absolute")); View view = ViewImpl.buildView(service, viewNode); assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); AbsoluteInterval<DateUnit> interval = (AbsoluteInterval<DateUnit>) view.getPredefinedDateInterval(); assertEquals(interval.getIntervalUnit(), DateUnit.YEAR); assertEquals(interval.getStart(), new GregorianCalendar(start.get(Calendar.YEAR), 0, 1)); assertEquals(interval.getEnd(), new GregorianCalendar(end.get(Calendar.YEAR), 0, 1)); assertNull(view.getPredefinedTimeInterval()); } /** intervals with invalid units are ignored */ public void invalidUnits() throws UnknownViewTypeException { ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); ObjectNode definitionNode = buildIntervalNode(DateUnit.DAY, new TextNode("-3"), new IntNode(3), "relative"); definitionNode.setAll(buildIntervalNode(TimeUnit.HOUR, new TextNode("-3"), new IntNode(3), "relative")); ((ObjectNode) definitionNode.get("dateInterval")).put("aggregationType", "not a date unit"); ((ObjectNode) definitionNode.get("timeInterval")).put("aggregationType", "not a time unit"); viewNode.put("dateTimeDefinition", definitionNode); View view = ViewImpl.buildView(service, viewNode); assertFalse(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); assertNull(view.getPredefinedTimeInterval()); } /** intervals with null units are ignored */ public void noUnits() throws UnknownViewTypeException { ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); ObjectNode definitionNode = buildIntervalNode(DateUnit.DAY, new TextNode("-3"), new IntNode(3), "relative"); definitionNode.setAll(buildIntervalNode(TimeUnit.HOUR, new TextNode("-3"), new IntNode(3), "relative")); ((ObjectNode) definitionNode.get("dateInterval")).remove("aggregationType"); ((ObjectNode) definitionNode.get("timeInterval")).remove("aggregationType"); viewNode.put("dateTimeDefinition", definitionNode); View view = ViewImpl.buildView(service, viewNode); assertFalse(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); assertNull(view.getPredefinedTimeInterval()); } /** intervals with start after end are ignored */ public void startAfterEnd() throws UnknownViewTypeException { ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); ObjectNode definitionNode = buildIntervalNode(DateUnit.DAY, new IntNode(3), new IntNode(-3), "relative"); definitionNode.setAll(buildIntervalNode(TimeUnit.HOUR, new IntNode(3), new IntNode(-3), "relative")); viewNode.put("dateTimeDefinition", definitionNode); View view = ViewImpl.buildView(service, viewNode); assertFalse(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); assertNull(view.getPredefinedTimeInterval()); } /** interval units are not case-sensitive */ public void unitCaseInsensitive() throws UnknownViewTypeException { ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); ObjectNode definitionNode = buildIntervalNode(DateUnit.DAY, new TextNode("-3"), new IntNode(3), "relative"); definitionNode.setAll(buildIntervalNode(TimeUnit.HOUR, new TextNode("-3"), new IntNode(3), "relative")); ((ObjectNode) definitionNode.get("dateInterval")).put("aggregationType", "dAy"); ((ObjectNode) definitionNode.get("timeInterval")).put("aggregationType", "hOuR"); viewNode.put("dateTimeDefinition", definitionNode); View view = ViewImpl.buildView(service, viewNode); assertTrue(view.hasPredefinedDateInterval()); assertTrue(view.hasPredefinedTimeInterval()); } /** two intervals with same parameters are equal */ public void intervalEquals() { assertEquals(new RelativeInterval<IntervalUnit>(DateUnit.DAY, -1, 1), new RelativeInterval<IntervalUnit>(DateUnit.DAY, -1, 1)); assertEquals(new AbsoluteInterval<IntervalUnit>(DateUnit.DAY, start, end), new AbsoluteInterval<IntervalUnit>( DateUnit.DAY, start, end)); assertEquals(new AbsoluteInterval<IntervalUnit>(DateUnit.DAY, Calendar.getInstance(), Calendar.getInstance()), new AbsoluteInterval<IntervalUnit>(DateUnit.DAY, Calendar.getInstance(), Calendar.getInstance())); assertNotEquals(new RelativeInterval<IntervalUnit>(DateUnit.DAY, -1, 1), new RelativeInterval<IntervalUnit>(DateUnit.DAY, -1, -1)); assertNotEquals(new AbsoluteInterval<IntervalUnit>(DateUnit.DAY, start, end), new AbsoluteInterval<IntervalUnit>( DateUnit.DAY, start, start)); assertNotEquals(new RelativeInterval<IntervalUnit>(DateUnit.DAY, -1, 1), new RelativeInterval<IntervalUnit>( DateUnit.MONTH, -1, 1)); assertNotEquals(new AbsoluteInterval<IntervalUnit>(DateUnit.DAY, start, end), new AbsoluteInterval<IntervalUnit>( DateUnit.MONTH, start, end)); } /** system locale doesn't affect upper/lowercase conversion */ @Test(dataProvider = "intervalUnitProvider", groups = "locale") public void localeCaseConversion(IntervalUnit unit) throws UnknownViewTypeException { Locale.setDefault(new Locale("tr")); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); ObjectNode intervalNode = buildIntervalNode(unit, new TextNode("-3.0"), new IntNode(3), "relative"); // set the aggregation type to lower case in English conversion // when converted back using Turkish, i will not become I String unitType = unit instanceof DateUnit ? "dateInterval" : "timeInterval"; ObjectNode typeNode = (ObjectNode) intervalNode.get(unitType); typeNode.put("aggregationType", typeNode.get("aggregationType").asText().toLowerCase(Locale.ENGLISH)); viewNode.put("dateTimeDefinition", intervalNode); View view = ViewImpl.buildView(service, viewNode); if (unit instanceof DateUnit) { assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); } else { assertFalse(view.hasPredefinedDateInterval()); assertTrue(view.hasPredefinedTimeInterval()); } } @DataProvider(name = "intervalUnitProvider") protected Object[][] provideIntervalUnits() { List<IntervalUnit[]> unitList = new ArrayList<IntervalUnit[]>(); for (IntervalUnit unit : DateUnit.values()) { unitList.add(new IntervalUnit[] { unit }); } for (IntervalUnit unit : TimeUnit.values()) { unitList.add(new IntervalUnit[] { unit }); } return unitList.toArray(new IntervalUnit[0][0]); } private ObjectNode buildIntervalNode(IntervalUnit intervalUnit, JsonNode from, JsonNode to, String type) { ObjectNode expectedJson = mapper.createObjectNode(); ObjectNode timeInterval = mapper.createObjectNode(); ObjectNode intervalNode = mapper.createObjectNode(); String unitType = intervalUnit instanceof DateUnit ? "dateInterval" : "timeInterval"; expectedJson.put(unitType, timeInterval); timeInterval.put("interval", intervalNode); timeInterval.put("aggregationType", intervalUnit.name()); intervalNode.put("from", from); intervalNode.put("to", to); intervalNode.put("type", type); return expectedJson; } }
package com.fishercoder.solutions; public class _1020 { public static class Solution1 { public void walk(int[][] A, boolean[][] visited, int x, int y) { if (x >= A.length || x < 0 || y >= A[0].length || y < 0) { return; } if (visited[x][y]) { return; } if (A[x][y] == 0) { return; } visited[x][y] = true; walk(A, visited, x - 1, y); walk(A, visited, x, y - 1); walk(A, visited, x, y + 1); walk(A, visited, x + 1, y); } public int numEnclaves(int[][] A) { int n = A.length; int m = A[0].length; boolean[][] visited = new boolean[n][m]; for (int i = 0; i < n; ++i) { walk(A, visited, i, 0); walk(A, visited, i, m - 1); } for (int j = 0; j < m; ++j) { walk(A, visited, 0, j); walk(A, visited, n - 1, j); } int unreachables = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (A[i][j] == 1 && !visited[i][j]) { ++unreachables; } } } return unreachables; } } }
// associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // furnished to do so, subject to the following conditions: // substantial portions of the Software. // NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // To compile: javac -cp MalmoJavaJar.jar JavaExamples_run_mission.java // To run: java -cp MalmoJavaJar.jar:. JavaExamples_run_mission (on Linux) // java -cp MalmoJavaJar.jar;. JavaExamples_run_mission (on Windows) // To run from the jar file without compiling: java -cp MalmoJavaJar.jar:JavaExamples_run_mission.jar -Djava.library.path=. JavaExamples_run_mission (on Linux) // java -cp MalmoJavaJar.jar;JavaExamples_run_mission.jar -Djava.library.path=. JavaExamples_run_mission (on Windows) import com.microsoft.msr.malmo.*; public class JavaExamples_run_mission { static { System.loadLibrary("MalmoJava"); // attempts to load MalmoJava.dll (on Windows) or libMalmoJava.so (on Linux) } public static void main(String argv[]) { AgentHost agent_host = new AgentHost(); try { StringVector args = new StringVector(); args.add("JavaExamples_run_mission"); for( String arg : argv ) args.add( arg ); agent_host.parse( args ); } catch( Exception e ) { System.out.println( "ERROR: " + e.getMessage() ); System.out.println( agent_host.getUsage() ); System.exit(1); } if( agent_host.receivedArgument("help") ) { System.out.println( agent_host.getUsage() ); System.exit(0); } MissionSpec my_mission = new MissionSpec(); my_mission.timeLimitInSeconds(10); my_mission.requestVideo( 320, 240 ); my_mission.rewardForReachingPosition(19.5f,0.0f,19.5f,100.0f,1.1f); MissionRecordSpec my_mission_record = new MissionRecordSpec("./saved_data.tgz"); my_mission_record.recordCommands(); my_mission_record.recordMP4(20, 400000); my_mission_record.recordRewards(); my_mission_record.recordObservations(); try { agent_host.startMission( my_mission, my_mission_record ); } catch (Exception e) { System.out.println( "Error starting mission: " + e.getMessage() ); System.exit(1); } WorldState world_state; System.out.print( "Waiting for the mission to start" ); do { System.out.print( "." ); try { Thread.sleep(100); } catch(InterruptedException ex) { System.out.println( "User interrupted while waiting for mission to start." ); return; } world_state = agent_host.getWorldState(); for( int i = 0; i < world_state.getErrors().size(); i++ ) System.out.println( "Error: " + world_state.getErrors().get(i).getText() ); } while( !world_state.getIsMissionRunning() ); System.out.println( "" ); // main loop: do { agent_host.sendCommand( "move 1" ); agent_host.sendCommand( "turn " + Math.random() ); try { Thread.sleep(500); } catch(InterruptedException ex) { System.out.println( "User interrupted while mission was running." ); return; } world_state = agent_host.getWorldState(); System.out.print( "video,observations,rewards received: " ); System.out.print( world_state.getNumberOfVideoFramesSinceLastState() + "," ); System.out.print( world_state.getNumberOfObservationsSinceLastState() + "," ); System.out.println( world_state.getNumberOfRewardsSinceLastState() ); for( int i = 0; i < world_state.getRewards().size(); i++ ) { TimestampedReward reward = world_state.getRewards().get(i); System.out.println( "Summed reward: " + reward.getValue() ); } for( int i = 0; i < world_state.getErrors().size(); i++ ) { TimestampedString error = world_state.getErrors().get(i); System.out.println( "Error: " + error.getText() ); } } while( world_state.getIsMissionRunning() ); System.out.println( "Mission has stopped." ); } }
package com.belladati.sdk.impl; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; import org.apache.http.entity.StringEntity; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.belladati.sdk.exception.interval.InvalidAbsoluteIntervalException; import com.belladati.sdk.exception.interval.InvalidRelativeIntervalException; import com.belladati.sdk.exception.interval.NullIntervalException; import com.belladati.sdk.impl.ViewImpl.UnknownViewTypeException; import com.belladati.sdk.intervals.AbsoluteInterval; import com.belladati.sdk.intervals.DateUnit; import com.belladati.sdk.intervals.Interval; import com.belladati.sdk.intervals.IntervalUnit; import com.belladati.sdk.intervals.RelativeInterval; import com.belladati.sdk.intervals.TimeUnit; import com.belladati.sdk.test.TestRequestHandler; import com.belladati.sdk.view.View; import com.belladati.sdk.view.ViewType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.IntNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; @Test public class IntervalTest extends SDKTest { private final String viewId = "viewId"; private final String viewName = "name"; private final String viewsUri = String.format("/api/reports/views/%s/chart", viewId); private final Calendar start = new GregorianCalendar(2012, 1, 2, 3, 4, 5); private final Calendar end = new GregorianCalendar(2013, 7, 8, 9, 10, 11); private final ObjectMapper mapper = new ObjectMapper(); /** absolute time interval down to seconds */ public void absoluteSecondsToJson() { Interval<?> interval = new AbsoluteInterval<IntervalUnit>(TimeUnit.SECOND, start, end); ObjectNode from = mapper.createObjectNode().put("hour", start.get(Calendar.HOUR)) .put("minute", start.get(Calendar.MINUTE)).put("second", start.get(Calendar.SECOND)); ObjectNode to = mapper.createObjectNode().put("hour", end.get(Calendar.HOUR)).put("minute", end.get(Calendar.MINUTE)) .put("second", end.get(Calendar.SECOND)); JsonNode expectedJson = buildIntervalNode(TimeUnit.SECOND, from, to, "absolute"); assertEquals(interval.toJson(), expectedJson); assertEquals(interval.toString(), expectedJson.toString()); } /** absolute time interval down to minutes */ public void absoluteMinutesToJson() { Interval<?> interval = new AbsoluteInterval<IntervalUnit>(TimeUnit.MINUTE, start, end); ObjectNode from = mapper.createObjectNode().put("hour", start.get(Calendar.HOUR)) .put("minute", start.get(Calendar.MINUTE)); ObjectNode to = mapper.createObjectNode().put("hour", end.get(Calendar.HOUR)).put("minute", end.get(Calendar.MINUTE)); JsonNode expectedJson = buildIntervalNode(TimeUnit.MINUTE, from, to, "absolute"); assertEquals(interval.toJson(), expectedJson); assertEquals(interval.toString(), expectedJson.toString()); } /** absolute time interval down to hours */ public void absoluteHoursToJson() { Interval<?> interval = new AbsoluteInterval<IntervalUnit>(TimeUnit.HOUR, start, end); ObjectNode from = mapper.createObjectNode().put("hour", start.get(Calendar.HOUR)); ObjectNode to = mapper.createObjectNode().put("hour", end.get(Calendar.HOUR)); JsonNode expectedJson = buildIntervalNode(TimeUnit.HOUR, from, to, "absolute"); assertEquals(interval.toJson(), expectedJson); assertEquals(interval.toString(), expectedJson.toString()); } /** absolute date interval down to days */ public void absoluteDaysToJson() { Interval<?> interval = new AbsoluteInterval<IntervalUnit>(DateUnit.DAY, start, end); ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)) .put("month", start.get(Calendar.MONTH) + 1).put("day", start.get(Calendar.DAY_OF_MONTH)); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)).put("month", end.get(Calendar.MONTH) + 1) .put("day", end.get(Calendar.DAY_OF_MONTH)); JsonNode expectedJson = buildIntervalNode(DateUnit.DAY, from, to, "absolute"); assertEquals(interval.toJson(), expectedJson); assertEquals(interval.toString(), expectedJson.toString()); } /** absolute date interval down to weeks */ public void absoluteWeeksToJson() { Interval<?> interval = new AbsoluteInterval<IntervalUnit>(DateUnit.WEEK, start, end); ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)) .put("week", start.get(Calendar.WEEK_OF_YEAR)); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)).put("week", end.get(Calendar.WEEK_OF_YEAR)); JsonNode expectedJson = buildIntervalNode(DateUnit.WEEK, from, to, "absolute"); assertEquals(interval.toJson(), expectedJson); assertEquals(interval.toString(), expectedJson.toString()); } /** absolute date interval down to months */ public void absoluteMonthsToJson() { Interval<?> interval = new AbsoluteInterval<IntervalUnit>(DateUnit.MONTH, start, end); ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)) .put("month", start.get(Calendar.MONTH) + 1); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)).put("month", end.get(Calendar.MONTH) + 1); JsonNode expectedJson = buildIntervalNode(DateUnit.MONTH, from, to, "absolute"); assertEquals(interval.toJson(), expectedJson); assertEquals(interval.toString(), expectedJson.toString()); } /** absolute date interval down to quarters */ public void absoluteQuartersToJson() { Interval<?> interval = new AbsoluteInterval<IntervalUnit>(DateUnit.QUARTER, start, end); ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)) .put("quarter", start.get(Calendar.MONTH) / 3 + 1); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)) .put("quarter", end.get(Calendar.MONTH) / 3 + 1); JsonNode expectedJson = buildIntervalNode(DateUnit.QUARTER, from, to, "absolute"); assertEquals(interval.toJson(), expectedJson); assertEquals(interval.toString(), expectedJson.toString()); } /** absolute date interval down to years */ public void absoluteYearsToJson() { Interval<?> interval = new AbsoluteInterval<IntervalUnit>(DateUnit.YEAR, start, end); ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)); JsonNode expectedJson = buildIntervalNode(DateUnit.YEAR, from, to, "absolute"); assertEquals(interval.toJson(), expectedJson); assertEquals(interval.toString(), expectedJson.toString()); } /** relative intervals */ @Test(dataProvider = "intervalUnitProvider") public void relativeToJson(IntervalUnit unit) { Interval<?> interval = new RelativeInterval<IntervalUnit>(unit, -10, 10); JsonNode from = new IntNode(-10); JsonNode to = new IntNode(10); JsonNode expectedJson = buildIntervalNode(unit, from, to, "relative"); assertEquals(interval.toJson(), expectedJson); assertEquals(interval.toString(), expectedJson.toString()); } /** start and end may be equal in absolute intervals */ public void startEndEqualAbsolute() { Interval<?> interval = new AbsoluteInterval<IntervalUnit>(TimeUnit.HOUR, start, start); ObjectNode from = mapper.createObjectNode().put("hour", start.get(Calendar.HOUR)); ObjectNode to = mapper.createObjectNode().put("hour", start.get(Calendar.HOUR)); JsonNode expectedJson = buildIntervalNode(TimeUnit.HOUR, from, to, "absolute"); assertEquals(interval.toJson(), expectedJson); assertEquals(interval.toString(), expectedJson.toString()); } /** start and end may be equal in relative intervals */ public void startEndEqualRelative() { Interval<?> interval = new RelativeInterval<IntervalUnit>(DateUnit.DAY, 10, 10); JsonNode from = new IntNode(10); JsonNode to = new IntNode(10); JsonNode expectedJson = buildIntervalNode(DateUnit.DAY, from, to, "relative"); assertEquals(interval.toJson(), expectedJson); assertEquals(interval.toString(), expectedJson.toString()); } /** start may not be later than end in absolute intervals */ public void startAfterEndAbsolute() { try { new AbsoluteInterval<IntervalUnit>(TimeUnit.HOUR, end, start); fail("did not throw exception"); } catch (InvalidAbsoluteIntervalException e) { assertEquals(e.getIntervalUnit(), TimeUnit.HOUR); assertEquals(e.getStart(), end); assertEquals(e.getEnd(), start); } } /** start may not be greater than end in relative intervals */ public void startAfterEndRelative() { try { new RelativeInterval<IntervalUnit>(DateUnit.DAY, 10, -10); fail("did not throw exception"); } catch (InvalidRelativeIntervalException e) { assertEquals(e.getIntervalUnit(), DateUnit.DAY); assertEquals((int) e.getStart(), 10); assertEquals((int) e.getEnd(), -10); } } /** interval unit may not be null in absolute intervals */ @Test(expectedExceptions = NullIntervalException.class) public void unitNullAbsolute() { new AbsoluteInterval<IntervalUnit>(null, start, end); } /** interval unit may not be null in relative intervals */ @Test(expectedExceptions = NullIntervalException.class) public void unitNullRelative() { new RelativeInterval<IntervalUnit>(null, -1, 1); } /** interval start may not be null */ @Test(expectedExceptions = NullIntervalException.class) public void startNullAbsolute() { new AbsoluteInterval<IntervalUnit>(TimeUnit.HOUR, null, end); } /** interval end may not be null */ @Test(expectedExceptions = NullIntervalException.class) public void endNullAbsolute() { new AbsoluteInterval<IntervalUnit>(TimeUnit.HOUR, start, null); } /** Query parameters with time only are correct. */ public void queryStringTimeOnly() throws UnknownViewTypeException { final ObjectNode from = mapper.createObjectNode().put("hour", start.get(Calendar.HOUR)); final ObjectNode to = mapper.createObjectNode().put("hour", end.get(Calendar.HOUR)); server.register(viewsUri, new TestRequestHandler() { @Override protected void handle(HttpHolder holder) throws IOException { String intervalString = holder.getUrlParameters().get("dateTimeDefinition"); assertNotNull(intervalString); ObjectNode intervalNode = buildIntervalNode(TimeUnit.HOUR, from, to, "absolute"); assertEquals(mapper.readTree(intervalString), intervalNode); holder.response.setEntity(new StringEntity("{}")); } }); service.createViewLoader(viewId, ViewType.CHART) .setTimeInterval(new AbsoluteInterval<TimeUnit>(TimeUnit.HOUR, start, end)).loadContent(); server.assertRequestUris(viewsUri); } /** Query parameters with date only are correct. */ public void queryStringDateOnly() throws UnknownViewTypeException { final ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)); final ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)); server.register(viewsUri, new TestRequestHandler() { @Override protected void handle(HttpHolder holder) throws IOException { String intervalString = holder.getUrlParameters().get("dateTimeDefinition"); assertNotNull(intervalString); ObjectNode intervalNode = buildIntervalNode(DateUnit.YEAR, from, to, "absolute"); assertEquals(mapper.readTree(intervalString), intervalNode); holder.response.setEntity(new StringEntity("{}")); } }); service.createViewLoader(viewId, ViewType.CHART) .setDateInterval(new AbsoluteInterval<DateUnit>(DateUnit.YEAR, start, end)).loadContent(); server.assertRequestUris(viewsUri); } /** Query parameters with both intervals are correct. */ public void queryStringBoth() throws UnknownViewTypeException { final ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)); final ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)); server.register(viewsUri, new TestRequestHandler() { @Override protected void handle(HttpHolder holder) throws IOException { String intervalString = holder.getUrlParameters().get("dateTimeDefinition"); assertNotNull(intervalString); ObjectNode intervalNode = buildIntervalNode(DateUnit.YEAR, from, to, "absolute"); intervalNode.setAll(buildIntervalNode(TimeUnit.MINUTE, new IntNode(-10), new IntNode(10), "relative")); assertEquals(mapper.readTree(intervalString), intervalNode); holder.response.setEntity(new StringEntity("{}")); } }); service.createViewLoader(viewId, ViewType.CHART) .setDateInterval(new AbsoluteInterval<DateUnit>(DateUnit.YEAR, start, end)) .setTimeInterval(new RelativeInterval<TimeUnit>(TimeUnit.MINUTE, -10, 10)).loadContent(); server.assertRequestUris(viewsUri); } /** absolute time interval in seconds */ public void predefinedSecondInterval() throws UnknownViewTypeException { ObjectNode from = mapper.createObjectNode().put("hour", start.get(Calendar.HOUR)) .put("minute", start.get(Calendar.MINUTE)).put("second", start.get(Calendar.SECOND)); ObjectNode to = mapper.createObjectNode().put("hour", end.get(Calendar.HOUR)).put("minute", end.get(Calendar.MINUTE)) .put("second", end.get(Calendar.SECOND)); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(TimeUnit.SECOND, from, to, "absolute")); View view = ViewImpl.buildView(service, viewNode); Calendar expectedStart = new GregorianCalendar(0, 0, 0, start.get(Calendar.HOUR), start.get(Calendar.MINUTE), start.get(Calendar.SECOND)); Calendar expectedEnd = new GregorianCalendar(0, 0, 0, end.get(Calendar.HOUR), end.get(Calendar.MINUTE), end.get(Calendar.SECOND)); assertFalse(view.hasPredefinedDateInterval()); assertTrue(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); AbsoluteInterval<TimeUnit> interval = (AbsoluteInterval<TimeUnit>) view.getPredefinedTimeInterval(); assertEquals(interval.getIntervalUnit(), TimeUnit.SECOND); assertEquals(interval.getStart(), expectedStart); assertEquals(interval.getEnd(), expectedEnd); } /** absolute time interval in minutes */ public void predefinedMinuteInterval() throws UnknownViewTypeException { ObjectNode from = mapper.createObjectNode().put("hour", start.get(Calendar.HOUR)) .put("minute", start.get(Calendar.MINUTE)); ObjectNode to = mapper.createObjectNode().put("hour", end.get(Calendar.HOUR)).put("minute", end.get(Calendar.MINUTE)); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(TimeUnit.MINUTE, from, to, "absolute")); View view = ViewImpl.buildView(service, viewNode); Calendar expectedStart = new GregorianCalendar(0, 0, 0, start.get(Calendar.HOUR), start.get(Calendar.MINUTE), 0); Calendar expectedEnd = new GregorianCalendar(0, 0, 0, end.get(Calendar.HOUR), end.get(Calendar.MINUTE), 0); assertFalse(view.hasPredefinedDateInterval()); assertTrue(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); AbsoluteInterval<TimeUnit> interval = (AbsoluteInterval<TimeUnit>) view.getPredefinedTimeInterval(); assertEquals(interval.getIntervalUnit(), TimeUnit.MINUTE); assertEquals(interval.getStart(), expectedStart); assertEquals(interval.getEnd(), expectedEnd); } /** absolute time interval in hours */ public void predefinedHourInterval() throws UnknownViewTypeException { ObjectNode from = mapper.createObjectNode().put("hour", start.get(Calendar.HOUR)); ObjectNode to = mapper.createObjectNode().put("hour", end.get(Calendar.HOUR)); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(TimeUnit.HOUR, from, to, "absolute")); View view = ViewImpl.buildView(service, viewNode); Calendar expectedStart = new GregorianCalendar(0, 0, 0, start.get(Calendar.HOUR), 0, 0); Calendar expectedEnd = new GregorianCalendar(0, 0, 0, end.get(Calendar.HOUR), 0, 0); assertFalse(view.hasPredefinedDateInterval()); assertTrue(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); AbsoluteInterval<TimeUnit> interval = (AbsoluteInterval<TimeUnit>) view.getPredefinedTimeInterval(); assertEquals(interval.getIntervalUnit(), TimeUnit.HOUR); assertEquals(interval.getStart(), expectedStart); assertEquals(interval.getEnd(), expectedEnd); } /** absolute date interval in days */ public void predefinedDayInterval() throws UnknownViewTypeException { ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)) .put("month", start.get(Calendar.MONTH) + 1).put("day", start.get(Calendar.DAY_OF_MONTH)); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)).put("month", end.get(Calendar.MONTH) + 1) .put("day", end.get(Calendar.DAY_OF_MONTH)); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(DateUnit.DAY, from, to, "absolute")); View view = ViewImpl.buildView(service, viewNode); Calendar expectedStart = new GregorianCalendar(start.get(Calendar.YEAR), start.get(Calendar.MONTH), start.get(Calendar.DAY_OF_MONTH)); Calendar expectedEnd = new GregorianCalendar(end.get(Calendar.YEAR), end.get(Calendar.MONTH), end.get(Calendar.DAY_OF_MONTH)); assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); AbsoluteInterval<DateUnit> interval = (AbsoluteInterval<DateUnit>) view.getPredefinedDateInterval(); assertEquals(interval.getIntervalUnit(), DateUnit.DAY); assertEquals(interval.getStart(), expectedStart); assertEquals(interval.getEnd(), expectedEnd); assertNull(view.getPredefinedTimeInterval()); } /** absolute week interval in weeks */ public void predefinedWeekInterval() throws UnknownViewTypeException { ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)) .put("week", start.get(Calendar.WEEK_OF_YEAR)); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)).put("week", end.get(Calendar.WEEK_OF_YEAR)); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(DateUnit.WEEK, from, to, "absolute")); View view = ViewImpl.buildView(service, viewNode); Calendar expectedStart = new GregorianCalendar(start.get(Calendar.YEAR), 0, 0); expectedStart.set(Calendar.WEEK_OF_YEAR, start.get(Calendar.WEEK_OF_YEAR)); Calendar expectedEnd = new GregorianCalendar(end.get(Calendar.YEAR), 0, 0); expectedEnd.set(Calendar.WEEK_OF_YEAR, end.get(Calendar.WEEK_OF_YEAR)); assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); AbsoluteInterval<DateUnit> interval = (AbsoluteInterval<DateUnit>) view.getPredefinedDateInterval(); assertEquals(interval.getIntervalUnit(), DateUnit.WEEK); assertEquals(interval.getStart(), expectedStart); assertEquals(interval.getEnd(), expectedEnd); assertNull(view.getPredefinedTimeInterval()); } /** absolute date interval in months */ public void predefinedMonthInterval() throws UnknownViewTypeException { ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)) .put("month", start.get(Calendar.MONTH) + 1); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)).put("month", end.get(Calendar.MONTH) + 1); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(DateUnit.MONTH, from, to, "absolute")); View view = ViewImpl.buildView(service, viewNode); Calendar expectedStart = new GregorianCalendar(start.get(Calendar.YEAR), start.get(Calendar.MONTH), 0); Calendar expectedEnd = new GregorianCalendar(end.get(Calendar.YEAR), end.get(Calendar.MONTH), 0); assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); AbsoluteInterval<DateUnit> interval = (AbsoluteInterval<DateUnit>) view.getPredefinedDateInterval(); assertEquals(interval.getIntervalUnit(), DateUnit.MONTH); assertEquals(interval.getStart(), expectedStart); assertEquals(interval.getEnd(), expectedEnd); assertNull(view.getPredefinedTimeInterval()); } /** absolute date interval in quarters */ public void predefinedQuarterInterval() throws UnknownViewTypeException { ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)) .put("quarter", start.get(Calendar.MONTH) / 3); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)).put("quarter", end.get(Calendar.MONTH) / 3); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(DateUnit.QUARTER, from, to, "absolute")); View view = ViewImpl.buildView(service, viewNode); Calendar expectedStart = new GregorianCalendar(start.get(Calendar.YEAR), (start.get(Calendar.MONTH) / 3) * 3, 0); Calendar expectedEnd = new GregorianCalendar(end.get(Calendar.YEAR), (end.get(Calendar.MONTH) / 3) * 3, 0); assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); AbsoluteInterval<DateUnit> interval = (AbsoluteInterval<DateUnit>) view.getPredefinedDateInterval(); assertEquals(interval.getIntervalUnit(), DateUnit.QUARTER); assertEquals(interval.getStart(), expectedStart); assertEquals(interval.getEnd(), expectedEnd); assertNull(view.getPredefinedTimeInterval()); } /** absolute date interval in years */ public void predefinedYearInterval() throws UnknownViewTypeException { ObjectNode from = mapper.createObjectNode().put("year", start.get(Calendar.YEAR)); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(DateUnit.YEAR, from, to, "absolute")); View view = ViewImpl.buildView(service, viewNode); Calendar expectedStart = new GregorianCalendar(start.get(Calendar.YEAR), 0, 0); Calendar expectedEnd = new GregorianCalendar(end.get(Calendar.YEAR), 0, 0); assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); AbsoluteInterval<DateUnit> interval = (AbsoluteInterval<DateUnit>) view.getPredefinedDateInterval(); assertEquals(interval.getIntervalUnit(), DateUnit.YEAR); assertEquals(interval.getStart(), expectedStart); assertEquals(interval.getEnd(), expectedEnd); assertNull(view.getPredefinedTimeInterval()); } /** predefined relative intervals */ @Test(dataProvider = "intervalUnitProvider") public void predefinedRelativeInterval(IntervalUnit unit) throws UnknownViewTypeException { ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(unit, new IntNode(-3), new IntNode(3), "rElAtIvE")); View view = ViewImpl.buildView(service, viewNode); if (unit instanceof DateUnit) { assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); RelativeInterval<DateUnit> interval = (RelativeInterval<DateUnit>) view.getPredefinedDateInterval(); assertEquals(interval.getIntervalUnit(), unit); assertEquals(interval.getStart(), -3); assertEquals(interval.getEnd(), 3); assertNull(view.getPredefinedTimeInterval()); } else { assertFalse(view.hasPredefinedDateInterval()); assertTrue(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); RelativeInterval<TimeUnit> interval = (RelativeInterval<TimeUnit>) view.getPredefinedTimeInterval(); assertEquals(interval.getIntervalUnit(), unit); assertEquals(interval.getStart(), -3); assertEquals(interval.getEnd(), 3); } } /** an interval that's not absolute or relative */ @Test(dataProvider = "intervalUnitProvider") public void predefinedNotAbsoluteOrRelativeInterval(IntervalUnit unit) throws UnknownViewTypeException { ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(unit, new IntNode(-3), new IntNode(3), "something else")); View view = ViewImpl.buildView(service, viewNode); assertFalse(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); assertNull(view.getPredefinedTimeInterval()); } /** invalid relative intervals are ignored */ @Test(dataProvider = "intervalUnitProvider") public void invalidRelativeInterval(IntervalUnit unit) throws UnknownViewTypeException { ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(unit, new TextNode("abc"), new IntNode(3), "relative")); View view = ViewImpl.buildView(service, viewNode); assertFalse(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); assertNull(view.getPredefinedTimeInterval()); } /** invalid absolute intervals are ignored */ public void invalidAbsoluteInterval() throws UnknownViewTypeException { ObjectNode from = mapper.createObjectNode().put("year", "abc"); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(DateUnit.YEAR, from, to, "absolute")); View view = ViewImpl.buildView(service, viewNode); assertFalse(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); assertNull(view.getPredefinedTimeInterval()); } /** intervals with numeric strings instead of numbers are allowed */ @Test(dataProvider = "intervalUnitProvider") public void stringRelativeInterval(IntervalUnit unit) throws UnknownViewTypeException { ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(unit, new TextNode("-3"), new IntNode(3), "relative")); View view = ViewImpl.buildView(service, viewNode); if (unit instanceof DateUnit) { assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); RelativeInterval<DateUnit> interval = (RelativeInterval<DateUnit>) view.getPredefinedDateInterval(); assertEquals(interval.getIntervalUnit(), unit); assertEquals(interval.getStart(), -3); assertEquals(interval.getEnd(), 3); assertNull(view.getPredefinedTimeInterval()); } else { assertFalse(view.hasPredefinedDateInterval()); assertTrue(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); RelativeInterval<TimeUnit> interval = (RelativeInterval<TimeUnit>) view.getPredefinedTimeInterval(); assertEquals(interval.getIntervalUnit(), unit); assertEquals(interval.getStart(), -3); assertEquals(interval.getEnd(), 3); } } /** intervals with numeric strings instead of numbers are allowed */ public void stringAbsoluteInterval() throws UnknownViewTypeException { ObjectNode from = mapper.createObjectNode().put("year", "" + start.get(Calendar.YEAR)); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(DateUnit.YEAR, from, to, "absolute")); View view = ViewImpl.buildView(service, viewNode); assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); AbsoluteInterval<DateUnit> interval = (AbsoluteInterval<DateUnit>) view.getPredefinedDateInterval(); assertEquals(interval.getIntervalUnit(), DateUnit.YEAR); assertEquals(interval.getStart(), new GregorianCalendar(start.get(Calendar.YEAR), 0, 0)); assertEquals(interval.getEnd(), new GregorianCalendar(end.get(Calendar.YEAR), 0, 0)); assertNull(view.getPredefinedTimeInterval()); } /** intervals with numeric fraction strings instead of numbers are allowed */ @Test(dataProvider = "intervalUnitProvider") public void fractionRelativeInterval(IntervalUnit unit) throws UnknownViewTypeException { ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(unit, new TextNode("-3.0"), new IntNode(3), "relative")); View view = ViewImpl.buildView(service, viewNode); if (unit instanceof DateUnit) { assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); RelativeInterval<DateUnit> interval = (RelativeInterval<DateUnit>) view.getPredefinedDateInterval(); assertEquals(interval.getIntervalUnit(), unit); assertEquals(interval.getStart(), -3); assertEquals(interval.getEnd(), 3); assertNull(view.getPredefinedTimeInterval()); } else { assertFalse(view.hasPredefinedDateInterval()); assertTrue(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); RelativeInterval<TimeUnit> interval = (RelativeInterval<TimeUnit>) view.getPredefinedTimeInterval(); assertEquals(interval.getIntervalUnit(), unit); assertEquals(interval.getStart(), -3); assertEquals(interval.getEnd(), 3); } } /** intervals with numeric fraction strings instead of numbers are allowed */ public void fractionAbsoluteInterval() throws UnknownViewTypeException { ObjectNode from = mapper.createObjectNode().put("year", "" + start.get(Calendar.YEAR) + ".0"); ObjectNode to = mapper.createObjectNode().put("year", end.get(Calendar.YEAR)); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); viewNode.put("dateTimeDefinition", buildIntervalNode(DateUnit.YEAR, from, to, "absolute")); View view = ViewImpl.buildView(service, viewNode); assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); AbsoluteInterval<DateUnit> interval = (AbsoluteInterval<DateUnit>) view.getPredefinedDateInterval(); assertEquals(interval.getIntervalUnit(), DateUnit.YEAR); assertEquals(interval.getStart(), new GregorianCalendar(start.get(Calendar.YEAR), 0, 0)); assertEquals(interval.getEnd(), new GregorianCalendar(end.get(Calendar.YEAR), 0, 0)); assertNull(view.getPredefinedTimeInterval()); } /** intervals with invalid units are ignored */ public void invalidUnits() throws UnknownViewTypeException { ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); ObjectNode definitionNode = buildIntervalNode(DateUnit.DAY, new TextNode("-3"), new IntNode(3), "relative"); definitionNode.setAll(buildIntervalNode(TimeUnit.HOUR, new TextNode("-3"), new IntNode(3), "relative")); ((ObjectNode) definitionNode.get("dateInterval")).put("aggregationType", "not a date unit"); ((ObjectNode) definitionNode.get("timeInterval")).put("aggregationType", "not a time unit"); viewNode.put("dateTimeDefinition", definitionNode); View view = ViewImpl.buildView(service, viewNode); assertFalse(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); assertNull(view.getPredefinedTimeInterval()); } /** intervals with null units are ignored */ public void noUnits() throws UnknownViewTypeException { ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); ObjectNode definitionNode = buildIntervalNode(DateUnit.DAY, new TextNode("-3"), new IntNode(3), "relative"); definitionNode.setAll(buildIntervalNode(TimeUnit.HOUR, new TextNode("-3"), new IntNode(3), "relative")); ((ObjectNode) definitionNode.get("dateInterval")).remove("aggregationType"); ((ObjectNode) definitionNode.get("timeInterval")).remove("aggregationType"); viewNode.put("dateTimeDefinition", definitionNode); View view = ViewImpl.buildView(service, viewNode); assertFalse(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); assertNull(view.getPredefinedTimeInterval()); } /** intervals with start after end are ignored */ public void startAfterEnd() throws UnknownViewTypeException { ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); ObjectNode definitionNode = buildIntervalNode(DateUnit.DAY, new IntNode(3), new IntNode(-3), "relative"); definitionNode.setAll(buildIntervalNode(TimeUnit.HOUR, new IntNode(3), new IntNode(-3), "relative")); viewNode.put("dateTimeDefinition", definitionNode); View view = ViewImpl.buildView(service, viewNode); assertFalse(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); assertNull(view.getPredefinedDateInterval()); assertNull(view.getPredefinedTimeInterval()); } /** interval units are not case-sensitive */ public void unitCaseInsensitive() throws UnknownViewTypeException { ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); ObjectNode definitionNode = buildIntervalNode(DateUnit.DAY, new TextNode("-3"), new IntNode(3), "relative"); definitionNode.setAll(buildIntervalNode(TimeUnit.HOUR, new TextNode("-3"), new IntNode(3), "relative")); ((ObjectNode) definitionNode.get("dateInterval")).put("aggregationType", "dAy"); ((ObjectNode) definitionNode.get("timeInterval")).put("aggregationType", "hOuR"); viewNode.put("dateTimeDefinition", definitionNode); View view = ViewImpl.buildView(service, viewNode); assertTrue(view.hasPredefinedDateInterval()); assertTrue(view.hasPredefinedTimeInterval()); } /** two intervals with same parameters are equal */ public void intervalEquals() { assertEquals(new RelativeInterval<IntervalUnit>(DateUnit.DAY, -1, 1), new RelativeInterval<IntervalUnit>(DateUnit.DAY, -1, 1)); assertEquals(new AbsoluteInterval<IntervalUnit>(DateUnit.DAY, start, end), new AbsoluteInterval<IntervalUnit>( DateUnit.DAY, start, end)); assertEquals(new AbsoluteInterval<IntervalUnit>(DateUnit.DAY, Calendar.getInstance(), Calendar.getInstance()), new AbsoluteInterval<IntervalUnit>(DateUnit.DAY, Calendar.getInstance(), Calendar.getInstance())); assertNotEquals(new RelativeInterval<IntervalUnit>(DateUnit.DAY, -1, 1), new RelativeInterval<IntervalUnit>(DateUnit.DAY, -1, -1)); assertNotEquals(new AbsoluteInterval<IntervalUnit>(DateUnit.DAY, start, end), new AbsoluteInterval<IntervalUnit>( DateUnit.DAY, start, start)); assertNotEquals(new RelativeInterval<IntervalUnit>(DateUnit.DAY, -1, 1), new RelativeInterval<IntervalUnit>( DateUnit.MONTH, -1, 1)); assertNotEquals(new AbsoluteInterval<IntervalUnit>(DateUnit.DAY, start, end), new AbsoluteInterval<IntervalUnit>( DateUnit.MONTH, start, end)); } /** system locale doesn't affect upper/lowercase conversion */ @Test(dataProvider = "intervalUnitProvider", groups = "locale") public void localeCaseConversion(IntervalUnit unit) throws UnknownViewTypeException { Locale.setDefault(new Locale("tr")); ObjectNode viewNode = builder.buildViewNode(viewId, viewName, "chart"); ObjectNode intervalNode = buildIntervalNode(unit, new TextNode("-3.0"), new IntNode(3), "relative"); // set the aggregation type to lower case in English conversion // when converted back using Turkish, i will not become I String unitType = unit instanceof DateUnit ? "dateInterval" : "timeInterval"; ObjectNode typeNode = (ObjectNode) intervalNode.get(unitType); typeNode.put("aggregationType", typeNode.get("aggregationType").asText().toLowerCase(Locale.ENGLISH)); viewNode.put("dateTimeDefinition", intervalNode); View view = ViewImpl.buildView(service, viewNode); if (unit instanceof DateUnit) { assertTrue(view.hasPredefinedDateInterval()); assertFalse(view.hasPredefinedTimeInterval()); } else { assertFalse(view.hasPredefinedDateInterval()); assertTrue(view.hasPredefinedTimeInterval()); } } @DataProvider(name = "intervalUnitProvider") protected Object[][] provideIntervalUnits() { List<IntervalUnit[]> unitList = new ArrayList<IntervalUnit[]>(); for (IntervalUnit unit : DateUnit.values()) { unitList.add(new IntervalUnit[] { unit }); } for (IntervalUnit unit : TimeUnit.values()) { unitList.add(new IntervalUnit[] { unit }); } return unitList.toArray(new IntervalUnit[0][0]); } private ObjectNode buildIntervalNode(IntervalUnit intervalUnit, JsonNode from, JsonNode to, String type) { ObjectNode expectedJson = mapper.createObjectNode(); ObjectNode timeInterval = mapper.createObjectNode(); ObjectNode intervalNode = mapper.createObjectNode(); String unitType = intervalUnit instanceof DateUnit ? "dateInterval" : "timeInterval"; expectedJson.put(unitType, timeInterval); timeInterval.put("interval", intervalNode); timeInterval.put("aggregationType", intervalUnit.name()); intervalNode.put("from", from); intervalNode.put("to", to); intervalNode.put("type", type); return expectedJson; } }
package com.fishercoder.solutions; public class _1175 { public static class Solution1 { public int numPrimeArrangements(int n) { //TODO: implement it return -1; } } }
package org.exist.util.serializer; import java.io.IOException; import java.io.Writer; import javax.xml.transform.TransformerException; import org.exist.Namespaces; import org.exist.dom.QName; import org.exist.util.hashtable.ObjectHashSet; /** * @author wolf * */ public class XHTMLWriter extends IndentingXMLWriter { private final static ObjectHashSet<String> emptyTags = new ObjectHashSet<String>(31); static { emptyTags.add("area"); emptyTags.add("base"); emptyTags.add("br"); emptyTags.add("col"); emptyTags.add("hr"); emptyTags.add("img"); emptyTags.add("input"); emptyTags.add("link"); emptyTags.add("meta"); emptyTags.add("basefont"); emptyTags.add("frame"); emptyTags.add("isindex"); emptyTags.add("param"); } private static boolean isEmptyTag(String tag) { return emptyTags.contains(tag); } private String currentTag; public XHTMLWriter() { super(); } /** * @param writer */ public XHTMLWriter(Writer writer) { super(writer); } boolean haveCollapsedXhtmlPrefix = false; @Override public void startElement(QName qname) throws TransformerException { final QName xhtmlQName = removeXhtmlPrefix(qname); super.startElement(xhtmlQName); currentTag = xhtmlQName.getStringValue(); } @Override public void endElement(QName qname) throws TransformerException { final QName xhtmlQName = removeXhtmlPrefix(qname); super.endElement(xhtmlQName); haveCollapsedXhtmlPrefix = false; } private QName removeXhtmlPrefix(QName qname) { String prefix = qname.getPrefix(); String namespaceURI = qname.getNamespaceURI(); if(prefix != null && prefix.length() > 0 && namespaceURI != null && namespaceURI.equals(Namespaces.XHTML_NS)) { haveCollapsedXhtmlPrefix = true; return new QName(qname.getLocalName(), namespaceURI); } return qname; } @Override public void startElement(String namespaceURI, String localName, String qname) throws TransformerException { final String xhtmlQName = removeXhtmlPrefix(namespaceURI, qname); super.startElement(namespaceURI, localName, xhtmlQName); currentTag = xhtmlQName; } @Override public void endElement(String namespaceURI, String localName, String qname) throws TransformerException { final String xhtmlQName = removeXhtmlPrefix(namespaceURI, qname); super.endElement(namespaceURI, localName, xhtmlQName); haveCollapsedXhtmlPrefix = false; } private String removeXhtmlPrefix(String namespaceURI, String qname) { int pos = qname.indexOf(':'); if(pos > 0 && namespaceURI != null && namespaceURI.equals(Namespaces.XHTML_NS)) { haveCollapsedXhtmlPrefix = true; return qname.substring(pos+1); } return qname; } @Override public void namespace(String prefix, String nsURI) throws TransformerException { if(haveCollapsedXhtmlPrefix && prefix != null && prefix.length() > 0 && nsURI.equals(Namespaces.XHTML_NS)) { return; //dont output the xmlns:prefix for the collapsed nodes prefix } super.namespace(prefix, nsURI); } @Override protected void closeStartTag(boolean isEmpty) throws TransformerException { try { if (tagIsOpen) { if (isEmpty) { if (isEmptyTag(currentTag)) writer.write(" />"); else { writer.write('>'); writer.write("</"); writer.write(currentTag); writer.write('>'); } } else writer.write('>'); tagIsOpen = false; } } catch (IOException e) { throw new TransformerException(e.getMessage(), e); } } }
package com.fxhelper.loader; import com.mister.app.Main; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import java.io.IOException; public class SceneLoader { public static Scene load(String viewName) { String viewPath = String.format("/views/%s.fxml", viewName); try { FXMLLoader loader = new FXMLLoader(Main.class.getResource(viewPath)); Parent root = (Parent) loader.load(); return new Scene(root); } catch (IOException e) { System.err.println(String.format("Scene %s not found on %s", viewName, viewPath)); e.printStackTrace(); System.exit(1); return null; } } }
package com.asafge.newsblurplus; import java.util.ArrayList; import java.util.List; import android.text.TextUtils; /* * A data structure for holding N objects in a list, discarding the last one when it fills up. * Elements should allow serialization to/from Strings. */ public class RotateQueue<E> { public List<E> Elements; public int Capacity; @SuppressWarnings("unchecked") public RotateQueue(int capacity, String serialized) { Elements = new ArrayList<E>(capacity); Capacity = capacity; if (!TextUtils.isEmpty(serialized)) { String[] values = serialized.split(",", capacity); for (String v : values) if (!TextUtils.isEmpty(v)) this.AddElement((E)v); } } public synchronized void AddElement(E value) { if (Capacity == Elements.size()) { int deleteFrom = (int)Math.ceil(Capacity * 0.05); Elements = Elements.subList(deleteFrom, Capacity); } if (!this.SearchElement(value)) { Elements.add(value); } } public synchronized boolean SearchElement(E value) { return Elements.contains(value); } @Override public synchronized String toString() { StringBuilder sb = new StringBuilder(); for (E element : Elements) sb.append(element.toString()).append(","); return sb.toString(); } }
package org.ice4j.stack; import java.io.*; import java.util.logging.*; import org.ice4j.*; import org.ice4j.message.*; /** * The ClientTransaction class retransmits (what a surprise) requests as * specified by rfc 3489. * * Once formulated and sent, the client sends the Binding Request. Reliability * is accomplished through request retransmissions. The ClientTransaction * retransmits the request starting with an interval of 100ms, doubling * every retransmit until the interval reaches 1.6s. Retransmissions * continue with intervals of 1.6s until a response is received, or a * total of 9 requests have been sent. If no response is received by 1.6 * seconds after the last request has been sent, the client SHOULD * consider the transaction to have failed. In other words, requests * would be sent at times 0ms, 100ms, 300ms, 700ms, 1500ms, 3100ms, * 4700ms, 6300ms, and 7900ms. At 9500ms, the client considers the * transaction to have failed if no response has been received. * * * @author Emil Ivov. * @author Pascal Mogeri (contributed configuration of client transactions). */ class StunClientTransaction implements Runnable { /** * Our class logger. */ private static final Logger logger = Logger.getLogger(StunClientTransaction.class.getName()); /** * The number of times to retransmit a request if no explicit value has been * specified by org.ice4j.MAX_RETRANSMISSIONS. */ public static final int DEFAULT_MAX_RETRANSMISSIONS = 6; /** * Maximum number of retransmissions. Once this number is reached and if no * response is received after MAX_WAIT_INTERVAL milliseconds the request is * considered unanswered. */ public int maxRetransmissions = DEFAULT_MAX_RETRANSMISSIONS; /** * The number of milliseconds a client should wait before retransmitting, * after it has sent a request for the first time. */ public static final int DEFAULT_ORIGINAL_WAIT_INTERVAL = 100; /** * The number of milliseconds to wait before the first retransmission of the * request. */ public int originalWaitInterval = DEFAULT_ORIGINAL_WAIT_INTERVAL; /** * The maximum number of milliseconds a client should wait between * consecutive retransmissions, after it has sent a request for the first * time. */ public static final int DEFAULT_MAX_WAIT_INTERVAL = 1600; /** * The maximum wait interval. Once this interval is reached we should stop * doubling its value. */ public int maxWaitInterval = DEFAULT_MAX_WAIT_INTERVAL; /** * Indicates how many times we have retransmitted so fat. */ private int retransmissionCounter = 0; /** * How much did we wait after our last retransmission. */ private int nextWaitInterval = originalWaitInterval; /** * The <tt>StunStack</tt> that created us. */ private final StunStack stackCallback; /** * The request that we are retransmitting. */ private final Request request; /** * The destination of the request. */ private final TransportAddress requestDestination; /** * The id of the transaction. */ private final TransactionID transactionID; /** * The <tt>TransportAddress</tt> through which the original request was sent * and that we are supposed to be retransmitting through. */ private final TransportAddress localAddress; /** * The instance to notify when a response has been received in the current * transaction or when it has timed out. */ private final ResponseCollector responseCollector; /** * Determines whether the transaction is active or not. */ private boolean cancelled = false; /** * The thread that this transaction runs in. */ private Thread retransmissionsThread = null; /** * Creates a client transaction. * * @param stackCallback the stack that created us. * @param request the request that we are living for. * @param requestDestination the destination of the request. * @param localAddress the local <tt>TransportAddress</tt> this transaction * will be communication through. * @param responseCollector the instance that should receive this request's * response retransmit. */ public StunClientTransaction(StunStack stackCallback, Request request, TransportAddress requestDestination, TransportAddress localAddress, ResponseCollector responseCollector) { this(stackCallback, request, requestDestination, localAddress, responseCollector, TransactionID.createNewTransactionID()); } /** * Creates a client transaction. * * @param stackCallback the stack that created us. * @param request the request that we are living for. * @param requestDestination the destination of the request. * @param localAddress the local <tt>TransportAddress</tt> this transaction * will be communication through. * @param responseCollector the instance that should receive this request's * response retransmit. * @param transactionID the ID that we'd like the new transaction to have * in case the application created it in order to use it for application * data correlation. */ public StunClientTransaction(StunStack stackCallback, Request request, TransportAddress requestDestination, TransportAddress localAddress, ResponseCollector responseCollector, TransactionID transactionID) { this.stackCallback = stackCallback; this.request = request; this.localAddress = localAddress; this.responseCollector = responseCollector; this.requestDestination = requestDestination; initTransactionConfiguration(); this.transactionID = transactionID; try { request.setTransactionID(transactionID.getBytes()); } catch (StunException ex) { //Shouldn't happen so lets just through a runtime exception in //case anything is real messed up throw new IllegalArgumentException("The TransactionID class " +"generated an invalid transaction ID"); } retransmissionsThread = new Thread(this, "StunClientTransaction@"+hashCode()); retransmissionsThread.setDaemon(true); } /** * Implements the retransmissions algorithm. Retransmits the request * starting with an interval of 100ms, doubling every retransmit until the * interval reaches 1.6s. Retransmissions continue with intervals of 1.6s * until a response is received, or a total of 7 requests have been sent. * If no response is received by 1.6 seconds after the last request has been * sent, we consider the transaction to have failed. */ public void run() { retransmissionsThread.setName("ice4j.ClientTransaction"); nextWaitInterval = originalWaitInterval; synchronized(this) { for (retransmissionCounter = 0; retransmissionCounter < maxRetransmissions; retransmissionCounter ++) { waitFor(nextWaitInterval); //did someone tell us to get lost? if(cancelled) return; int curWaitInterval = nextWaitInterval; if(nextWaitInterval < maxWaitInterval) nextWaitInterval *= 2; try { logger.fine("retrying STUN " + " tid " + transactionID + " from " + localAddress + " to " + requestDestination + " waited " + curWaitInterval + " ms retrans " + (retransmissionCounter+1) + " of " + maxRetransmissions); sendRequest0(); } catch (Exception ex) { //I wonder whether we should notify anyone that a //retransmission has failed logger.log(Level.INFO, "A client tran retransmission failed", ex); } } //before stating that a transaction has timeout-ed we should first //wait for a reception of the response if(nextWaitInterval < maxWaitInterval) nextWaitInterval *= 2; waitFor(nextWaitInterval); if(cancelled) return; stackCallback.removeClientTransaction(this); responseCollector.processTimeout( new StunTimeoutEvent( stackCallback, this.request, getLocalAddress(), transactionID)); } } void sendRequest() throws IllegalArgumentException, IOException { logger.fine("sending STUN " + " tid " + transactionID + " from " + localAddress + " to " + requestDestination); sendRequest0(); retransmissionsThread.start(); } private void sendRequest0() throws IllegalArgumentException, IOException { if(cancelled) { logger.finer("Trying to resend a cancelled transaction."); return; } stackCallback.getNetAccessManager().sendMessage( this.request, localAddress, requestDestination); } /** * Returns the request that was the reason for creating this transaction. * @return the request that was the reason for creating this transaction. */ Request getRequest() { return this.request; } /** * Waits until next retransmission is due or until the transaction is * cancelled (whichever comes first). * * @param millis the number of milliseconds to wait for. */ void waitFor(long millis) { try { wait(millis); } catch (InterruptedException ex) { throw new RuntimeException(ex); } } /** * Cancels the transaction. Once this method is called the transaction is * considered terminated and will stop retransmissions. * * @param waitForResponse indicates whether we should wait for the current * RTO to expire before ending the transaction or immediately terminate. */ synchronized void cancel(boolean waitForResponse) { this.cancelled = true; if(!waitForResponse) notifyAll(); } /** * Cancels the transaction. Once this method is called the transaction is * considered terminated and will stop retransmissions. */ synchronized void cancel() { cancel(false); } /** * Dispatches the response then cancels itself and notifies the StunStack * for its termination. * * @param evt the event that contains the newly received message */ synchronized void handleResponse(StunMessageEvent evt) { logger.log(Level.FINE, "handleResponse tid " + getTransactionID()); if( !Boolean.getBoolean(StackProperties.KEEP_CRANS_AFTER_A_RESPONSE) ) this.cancel(); this.responseCollector.processResponse( new StunResponseEvent( stackCallback, evt.getRawMessage(), (Response) evt.getMessage(), this.request, getTransactionID())); } /** * Returns the ID of the current transaction. * * @return the ID of the transaction. */ TransactionID getTransactionID() { return this.transactionID; } /** * Init transaction duration/retransmission parameters. * (Mostly, contributed by Pascal Maugeri). */ private void initTransactionConfiguration() { //Max Retransmissions String maxRetransmissionsStr = System.getProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS); if(maxRetransmissionsStr != null && maxRetransmissionsStr.trim().length() > 0){ try { maxRetransmissions = Integer.parseInt(maxRetransmissionsStr); } catch (NumberFormatException e) { logger.log(Level.FINE, "Failed to parse MAX_RETRANSMISSIONS", e); maxRetransmissions = DEFAULT_MAX_RETRANSMISSIONS; } } //Original Wait Interval String originalWaitIntervalStr = System.getProperty(StackProperties.FIRST_CTRAN_RETRANS_AFTER); if(originalWaitIntervalStr != null && originalWaitIntervalStr.trim().length() > 0){ try { originalWaitInterval = Integer.parseInt(originalWaitIntervalStr); } catch (NumberFormatException e) { logger.log(Level.FINE, "Failed to parse ORIGINAL_WAIT_INTERVAL", e); originalWaitInterval = DEFAULT_ORIGINAL_WAIT_INTERVAL; } } //Max Wait Interval String maxWaitIntervalStr = System.getProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER); if(maxWaitIntervalStr != null && maxWaitIntervalStr.trim().length() > 0){ try { maxWaitInterval = Integer.parseInt(maxWaitIntervalStr); } catch (NumberFormatException e) { logger.log(Level.FINE, "Failed to parse MAX_WAIT_INTERVAL", e); maxWaitInterval = DEFAULT_MAX_WAIT_INTERVAL; } } } /** * Returns the local <tt>TransportAddress</tt> that this transaction is * sending requests from. * * @return the local <tt>TransportAddress</tt> that this transaction is * sending requests from. */ public TransportAddress getLocalAddress() { return localAddress; } /** * Returns the remote <tt>TransportAddress</tt> that this transaction is * sending requests to. * * @return the remote <tt>TransportAddress</tt> that this transaction is * sending requests to. */ public TransportAddress getRemoteAddress() { return requestDestination; } }
package com.imap4j.hbase; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Scanner; import org.apache.hadoop.hbase.io.BatchUpdate; import org.apache.hadoop.hbase.io.RowResult; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class HBaseConnector { final static String tablename = "blogposts"; public static void insertPost(String val) throws IOException { BatchUpdate upd = new BatchUpdate(val); upd.put("post:title", ("This is a title " + val).getBytes()); upd.put("post:author", ("This is a author " + val).getBytes()); upd.put("post:body", ("This is a body " + val).getBytes()); upd.put("image:header", ("This is a header " + val).getBytes()); upd.put("image:bodyimage", ("This is a image " + val).getBytes()); final HTable table = new HTable(new HBaseConfiguration(), tablename); table.commit(upd); } public static Map<String, String> retrievePost(String postId) throws IOException { final HTable table = new HTable(new HBaseConfiguration(), tablename); final Map<String, String> post = new HashMap<String, String>(); final RowResult result = table.getRow(postId); for (byte[] column : result.keySet()) { String str = new String(column); String val = new String(result.get(column).getValue()); post.put(str, val); } return post; } public static void main(String[] args) throws IOException { //for (int i = 2; i < 5; i++) // insertPost("post" + i); /* for (int j = 1; j < 5; j++) { String key = "post" + j; Map<String, String> blogpost = HBaseConnector.retrievePost(key); for (String col : blogpost.keySet()) System.out.println(key + ": " + blogpost.get(col) + " - " + blogpost.get(col)); } */ HBaseAdmin admin = new HBaseAdmin(new HBaseConfiguration()); HTableDescriptor desc = admin.getTableDescriptor(tablename); for (HColumnDescriptor col : desc.getFamilies()) System.out.println("Family: " + col.getNameAsString()); final HTable table = new HTable(new HBaseConfiguration(), tablename); byte[][] start = table.getStartKeys(); byte[][] end = table.getEndKeys(); String s1 = new String(start[0]); String s2 = new String(end[0]); int g = 9; Scanner scanner = table.getScanner(new String[]{"post:"}); for (RowResult res : scanner) { System.out.println(res); System.out.println("Key: " + new String(res.getRow())); for (byte[] b : res.keySet()) System.out.println(new String(b)); } } }
package com.jaamsim.events; import java.util.ArrayList; /** * The EventManager is responsible for scheduling future events, controlling * conditional event evaluation, and advancing the simulation time. Events are * scheduled in based on: * <ul> * <li>1 - The execution time scheduled for the event * <li>2 - The priority of the event (if scheduled to occur at the same time) * <li>3 - If both 1) and 2) are equal, the user specified FIFO or LIFO order * </ul> * <p> * The event time is scheduled using a backing long value. Double valued time is * taken in by the scheduleWait function and scaled to the nearest long value * using the simTimeFactor. * <p> * Most EventManager functionality is available through static methods that rely * on being in a running model context which will access the eventmanager that is * currently running, think of it like a thread-local variable for all model threads. */ public final class EventManager { public final String name; private final Object lockObject; // Object used as global lock for synchronization private final EventTree eventTree; private volatile boolean executeEvents; private boolean processRunning; private final ArrayList<ConditionalEvent> condEvents; private long currentTick; // Master simulation time (long) private long nextTick; // The next tick to execute events at private long targetTick; // the largest time we will execute events for (run to time) private double ticksPerSecond; // The number of discrete ticks per simulated second private double secsPerTick; // The length of time in seconds each tick represents // Real time execution state private long realTimeTick; // the simulation tick corresponding to the wall-clock millis value private long realTimeMillis; // the wall-clock time in millis private volatile boolean executeRealTime; // TRUE if the simulation is to be executed in Real Time mode private volatile boolean rebaseRealTime; // TRUE if the time keeping for Real Time model needs re-basing private volatile int realTimeFactor; // target ratio of elapsed simulation time to elapsed wall clock time private EventTimeListener timelistener; private EventErrorListener errListener; private EventTraceListener trcListener; /** * Allocates a new EventManager with the given parent and name * * @param parent the connection point for this EventManager in the tree * @param name the name this EventManager should use */ public EventManager(String name) { // Basic initialization this.name = name; lockObject = new Object(); // Initialize and event lists and timekeeping variables currentTick = 0; nextTick = 0; setTickLength(1e-6d); eventTree = new EventTree(); condEvents = new ArrayList<>(); executeEvents = false; processRunning = false; executeRealTime = false; realTimeFactor = 1; rebaseRealTime = true; setTimeListener(null); setErrorListener(null); } public final void setTimeListener(EventTimeListener l) { synchronized (lockObject) { if (l != null) timelistener = l; else timelistener = new NoopListener(); timelistener.tickUpdate(currentTick); } } public final void setErrorListener(EventErrorListener l) { synchronized (lockObject) { if (l != null) errListener = l; else errListener = new NoopListener(); } } public final void setTraceListener(EventTraceListener l) { synchronized (lockObject) { trcListener = l; } } public void clear() { synchronized (lockObject) { currentTick = 0; nextTick = 0; targetTick = Long.MAX_VALUE; timelistener.tickUpdate(currentTick); rebaseRealTime = true; eventTree.runOnAllNodes(new KillAllEvents()); eventTree.reset(); clearFreeList(); for (int i = 0; i < condEvents.size(); i++) { condEvents.get(i).target.kill(); if (condEvents.get(i).handle != null) { condEvents.get(i).handle.event = null; } } condEvents.clear(); } } private static class KillAllEvents implements EventNode.Runner { @Override public void runOnNode(EventNode node) { Event each = node.head; while (each != null) { if (each.handle != null) { each.handle.event = null; each.handle = null; } each.target.kill(); each = each.next; } } } private boolean executeTarget(Process cur, ProcessTarget t) { try { // If the event has a captured process, pass control to it Process p = t.getProcess(); if (p != null) { p.setNextProcess(cur); p.wake(); threadWait(cur); return true; } // Execute the method t.process(); // Notify the event manager that the process has been completed if (trcListener != null) trcListener.traceProcessEnd(this, currentTick); return !cur.wakeNextProcess(); } catch (Throwable e) { // This is how kill() is implemented for sleeping processes. if (e instanceof ThreadKilledException) return false; // Tear down any threads waiting for this to finish Process next = cur.forceKillNext(); while (next != null) { next = next.forceKillNext(); } executeEvents = false; processRunning = false; errListener.handleError(this, e, currentTick); return false; } } /** * Main event execution method the eventManager, this is the only entrypoint * for Process objects taken out of the pool. */ final void execute(Process cur, ProcessTarget t) { synchronized (lockObject) { // This occurs in the startProcess or interrupt case where we start // a process with a target already assigned if (t != null) { executeTarget(cur, t); return; } if (processRunning) return; processRunning = true; timelistener.timeRunning(true); // Loop continuously while (true) { EventNode nextNode = eventTree.getNextNode(); if (nextNode == null || currentTick >= targetTick) { executeEvents = false; } if (!executeEvents) { processRunning = false; timelistener.timeRunning(false); return; } // If the next event is at the current tick, execute it if (nextNode.schedTick == currentTick) { // Remove the event from the future events Event nextEvent = nextNode.head; ProcessTarget nextTarget = nextEvent.target; if (trcListener != null) trcListener.traceEvent(this, currentTick, nextNode.schedTick, nextNode.priority, nextTarget); removeEvent(nextEvent); // the return from execute target informs whether or not this // thread should grab an new Event, or return to the pool if (executeTarget(cur, nextTarget)) continue; else return; } // If the next event would require us to advance the time, check the // conditonal events if (eventTree.getNextNode().schedTick > nextTick) { if (condEvents.size() > 0) { evaluateConditions(cur); if (!executeEvents) continue; } // If a conditional event was satisfied, we will have a new event at the // beginning of the eventStack for the current tick, go back to the // beginning, otherwise fall through to the time-advance nextTick = eventTree.getNextNode().schedTick; if (nextTick == currentTick) continue; } // Advance to the next event time if (executeRealTime) { // Loop until the next event time is reached long realTick = this.calcRealTimeTick(); if (realTick < nextTick && realTick < targetTick) { // Update the displayed simulation time currentTick = realTick; timelistener.tickUpdate(currentTick); //Halt the thread for 20ms and then reevaluate the loop try { lockObject.wait(20); } catch( InterruptedException e ) {} continue; } } // advance time if (targetTick < nextTick) currentTick = targetTick; else currentTick = nextTick; timelistener.tickUpdate(currentTick); } } } private void evaluateConditions(Process cur) { cur.begCondWait(); try { for (int i = 0; i < condEvents.size();) { ConditionalEvent c = condEvents.get(i); if (c.c.evaluate()) { condEvents.remove(i); EventNode node = getEventNode(currentTick, 0); Event evt = getEvent(); evt.node = node; evt.target = c.target; evt.handle = c.handle; if (evt.handle != null) { // no need to check the handle.isScheduled as we just unscheduled it above // and we immediately switch it to this event evt.handle.event = evt; } if (trcListener != null) trcListener.traceWaitUntilEnded(this, currentTick, c.target); node.addEvent(evt, true); continue; } i++; } } catch (Throwable e) { executeEvents = false; processRunning = false; errListener.handleError(this, e, currentTick); } cur.endCondWait(); } /** * Return the simulation time corresponding the given wall clock time * @param simTime = the current simulation time used when setting a real-time basis * @return simulation time in seconds */ private long calcRealTimeTick() { long curMS = System.currentTimeMillis(); if (rebaseRealTime) { realTimeTick = currentTick; realTimeMillis = curMS; rebaseRealTime = false; } double simElapsedsec = ((curMS - realTimeMillis) * realTimeFactor) / 1000.0d; long simElapsedTicks = secondsToNearestTick(simElapsedsec); return realTimeTick + simElapsedTicks; } /** // Pause the current active thread and restart the next thread on the // active thread list. For this case, a future event or conditional event // has been created for the current thread. Called by // eventManager.scheduleWait() and related methods, and by // eventManager.waitUntil(). // restorePreviousActiveThread() * Must hold the lockObject when calling this method. */ private void captureProcess(Process cur) { // if we don't wake a new process, take one from the pool if (!cur.wakeNextProcess()) { processRunning = false; Process.processEvents(this); } threadWait(cur); cur.setActive(); } /** * Calculate the time for an event taking into account numeric overflow. * Must hold the lockObject when calling this method */ private long calculateEventTime(long waitLength) { // Test for negative duration schedule wait length if(waitLength < 0) throw new ProcessError("Negative duration wait is invalid, waitLength = " + waitLength); // Check for numeric overflow of internal time long nextEventTime = currentTick + waitLength; if (nextEventTime < 0) nextEventTime = Long.MAX_VALUE; return nextEventTime; } public static final void waitTicks(long ticks, int priority, boolean fifo, EventHandle handle) { Process cur = Process.current(); cur.evt().waitTicks(cur, ticks, priority, fifo, handle); } public static final void waitSeconds(double secs, int priority, boolean fifo, EventHandle handle) { Process cur = Process.current(); long ticks = cur.evt().secondsToNearestTick(secs); cur.evt().waitTicks(cur, ticks, priority, fifo, handle); } /** * Schedules a future event to occur with a given priority. Lower priority * events will be executed preferentially over higher priority. This is * by lower priority events being placed higher on the event stack. * @param ticks the number of discrete ticks from now to schedule the event. * @param priority the priority of the scheduled event: 1 is the highest priority (default is priority 5) */ private void waitTicks(Process cur, long ticks, int priority, boolean fifo, EventHandle handle) { synchronized (lockObject) { cur.checkCondWait(); long nextEventTime = calculateEventTime(ticks); WaitTarget t = new WaitTarget(cur); EventNode node = getEventNode(nextEventTime, priority); Event evt = getEvent(); evt.node = node; evt.target = t; evt.handle = handle; if (handle != null) { if (handle.isScheduled()) throw new ProcessError("Tried to schedule using an EventHandle already in use"); handle.event = evt; } if (trcListener != null) trcListener.traceWait(this, currentTick, nextEventTime, priority, t); node.addEvent(evt, fifo); captureProcess(cur); } } /** * Find an eventNode in the list, if a node is not found, create one and * insert it. */ private EventNode getEventNode(long tick, int prio) { return eventTree.createOrFindNode(tick, prio); } private Event freeEvents = null; private Event getEvent() { if (freeEvents != null) { Event evt = freeEvents; freeEvents = evt.next; return evt; } return new Event(); } private void clearFreeList() { freeEvents = null; } public static final void waitUntil(Conditional cond, EventHandle handle) { Process cur = Process.current(); cur.evt().waitUntil(cur, cond, handle); } /** * Used to achieve conditional waits in the simulation. Adds the calling * thread to the conditional stack, then wakes the next waiting thread on * the thread stack. */ private void waitUntil(Process cur, Conditional cond, EventHandle handle) { synchronized (lockObject) { cur.checkCondWait(); WaitTarget t = new WaitTarget(cur); ConditionalEvent evt = new ConditionalEvent(cond, t, handle); if (handle != null) { if (handle.isScheduled()) throw new ProcessError("Tried to waitUntil using a handle already in use"); handle.event = evt; } condEvents.add(evt); if (trcListener != null) trcListener.traceWaitUntil(this, currentTick); captureProcess(cur); } } public static final void scheduleUntil(ProcessTarget t, Conditional cond, EventHandle handle) { Process cur = Process.current(); cur.evt().schedUntil(cur, t, cond, handle); } private void schedUntil(Process cur, ProcessTarget t, Conditional cond, EventHandle handle) { synchronized (lockObject) { cur.checkCondWait(); ConditionalEvent evt = new ConditionalEvent(cond, t, handle); if (handle != null) { if (handle.isScheduled()) throw new ProcessError("Tried to scheduleUntil using a handle already in use"); handle.event = evt; } condEvents.add(evt); if (trcListener != null) trcListener.traceWaitUntil(this, currentTick); } } public static final void startProcess(ProcessTarget t) { Process cur = Process.current(); cur.evt().start(cur, t); } private void start(Process cur, ProcessTarget t) { Process newProcess = Process.allocate(this, cur, t); // Notify the eventManager that a new process has been started synchronized (lockObject) { cur.checkCondWait(); if (trcListener != null) trcListener.traceProcessStart(this, t, currentTick); // Transfer control to the new process newProcess.wake(); threadWait(cur); } } /** * Remove an event from the eventList, must hold the lockObject. * @param idx * @return */ private void removeEvent(Event evt) { EventNode node = evt.node; node.removeEvent(evt); if (node.head == null) { if (!eventTree.removeNode(node.schedTick, node.priority)) throw new ProcessError("Tried to remove an eventnode that could not be found"); } // Clear the event to reuse it evt.node = null; evt.target = null; if (evt.handle != null) { evt.handle.event = null; evt.handle = null; } evt.next = freeEvents; freeEvents = evt; } private ProcessTarget rem(EventHandle handle) { ProcessTarget t = handle.event.target; BaseEvent base = handle.event; if (base instanceof Event) { removeEvent((Event)base); } else { handle.event = null; base.handle = null; condEvents.remove(base); } return t; } /** * Removes the event held in the EventHandle and disposes of it, the ProcessTarget is not run. * If the handle does not currently hold a scheduled event, this method simply returns. * @throws ProcessError if called outside of a Process context */ public static final void killEvent(EventHandle handle) { Process cur = Process.current(); cur.evt().killEvent(cur, handle); } /** * Removes an event from the pending list without executing it. */ private void killEvent(Process cur, EventHandle handle) { synchronized (lockObject) { cur.checkCondWait(); // Handle was not scheduled, nothing to do if (handle.event == null) return; if (trcListener != null) trcKill(handle.event); ProcessTarget t = rem(handle); t.kill(); } } private void trcKill(BaseEvent event) { if (event instanceof Event) { EventNode node = ((Event)event).node; trcListener.traceKill(this, currentTick, node.schedTick, node.priority, event.target); } else { trcListener.traceKill(this, currentTick, -1, -1, event.target); } } /** * Interrupts the event held in the EventHandle and immediately runs the ProcessTarget. * If the handle does not currently hold a scheduled event, this method simply returns. * @throws ProcessError if called outside of a Process context */ public static final void interruptEvent(EventHandle handle) { Process cur = Process.current(); cur.evt().interruptEvent(cur, handle); } /** * Removes an event from the pending list and executes it. */ private void interruptEvent(Process cur, EventHandle handle) { synchronized (lockObject) { cur.checkCondWait(); // Handle was not scheduled, nothing to do if (handle.event == null) return; if (trcListener != null) trcInterrupt(handle.event); ProcessTarget t = rem(handle); Process proc = t.getProcess(); if (proc == null) proc = Process.allocate(this, cur, t); proc.setNextProcess(cur); proc.wake(); threadWait(cur); } } private void trcInterrupt(BaseEvent event) { if (event instanceof Event) { EventNode node = ((Event)event).node; trcListener.traceInterrupt(this, currentTick, node.schedTick, node.priority, event.target); } else { trcListener.traceInterrupt(this, currentTick, -1, -1, event.target); } } public void setExecuteRealTime(boolean useRealTime, int factor) { executeRealTime = useRealTime; realTimeFactor = factor; if (useRealTime) rebaseRealTime = true; } /** * Locks the calling thread in an inactive state to the global lock. * When a new thread is created, and the current thread has been pushed * onto the inactive thread stack it must be put to sleep to preserve * program ordering. * <p> * The function takes no parameters, it puts the calling thread to sleep. * This method is NOT static as it requires the use of wait() which cannot * be called from a static context * <p> * There is a synchronized block of code that will acquire the global lock * and then wait() the current thread. */ private void threadWait(Process cur) { // Ensure that the thread owns the global thread lock try { /* * Halt the thread and only wake up by being interrupted. * * The infinite loop is _absolutely_ necessary to prevent * spurious wakeups from waking us early....which causes the * model to get into an inconsistent state causing crashes. */ while (true) { lockObject.wait(); } } // Catch the exception when the thread is interrupted catch( InterruptedException e ) {} if (cur.shouldDie()) throw new ThreadKilledException("Thread killed"); } public static final long secondsToTicks(double secs) { Process cur = Process.current(); return cur.evt().secondsToNearestTick(secs); } public static final double calcSimTime(double secs) { EventManager evt = Process.current().evt(); long ticks = evt.secondsToNearestTick(secs) + evt.currentTick; if (ticks < 0) ticks = Long.MAX_VALUE; return evt.ticksToSeconds(ticks); } public static final long calcSimTicks(double secs) { EventManager evt = Process.current().evt(); long ticks = evt.secondsToNearestTick(secs) + evt.currentTick; if (ticks < 0) ticks = Long.MAX_VALUE; return ticks; } public void scheduleProcessExternal(long waitLength, int eventPriority, boolean fifo, ProcessTarget t, EventHandle handle) { synchronized (lockObject) { long schedTick = calculateEventTime(waitLength); EventNode node = getEventNode(schedTick, eventPriority); Event evt = getEvent(); evt.node = node; evt.target = t; evt.handle = handle; if (handle != null) { if (handle.isScheduled()) throw new ProcessError("Tried to schedule using an EventHandle already in use"); handle.event = evt; } if (trcListener != null) trcListener.traceSchedProcess(this, currentTick, schedTick, eventPriority, t); node.addEvent(evt, fifo); } } /** * Schedule a future event in the controlling EventManager for the current Process, * if called outside of a Process context, returns null. * @throws ProcessError if called outside of a Process context * * @param waitLength the number of ticks in the future to schedule this event * @param eventPriority the priority of the scheduled event * @param fifo break ties with previously scheduled events using FIFO/LIFO ordering * @param t the process target to run when the event is executed * @param handle an optional handle to hold onto the scheduled event */ public static final void scheduleTicks(long waitLength, int eventPriority, boolean fifo, ProcessTarget t, EventHandle handle) { Process cur = Process.current(); cur.evt().scheduleTicks(cur, waitLength, eventPriority, fifo, t, handle); } /** * Schedule a future event in the controlling EventManager for the current Process, * if called outside of a Process context, returns null. * @throws ProcessError if called outside of a Process context * * @param secs the number of seconds in the future to schedule this event * @param eventPriority the priority of the scheduled event * @param fifo break ties with previously scheduled events using FIFO/LIFO ordering * @param t the process target to run when the event is executed * @param handle an optional handle to hold onto the scheduled event */ public static final void scheduleSeconds(double secs, int eventPriority, boolean fifo, ProcessTarget t, EventHandle handle) { Process cur = Process.current(); long ticks = cur.evt().secondsToNearestTick(secs); cur.evt().scheduleTicks(cur, ticks, eventPriority, fifo, t, handle); } private void scheduleTicks(Process cur, long waitLength, int eventPriority, boolean fifo, ProcessTarget t, EventHandle handle) { cur.checkCondWait(); long schedTick = calculateEventTime(waitLength); EventNode node = getEventNode(schedTick, eventPriority); Event evt = getEvent(); evt.node = node; evt.target = t; evt.handle = handle; if (handle != null) { if (handle.isScheduled()) throw new ProcessError("Tried to schedule using an EventHandle already in use"); handle.event = evt; } if (trcListener != null) trcListener.traceSchedProcess(this, currentTick, schedTick, eventPriority, t); node.addEvent(evt, fifo); } /** * Sets the value that is tested in the doProcess loop to determine if the * next event should be executed. If set to false, the eventManager will * execute a threadWait() and wait until an interrupt is generated. It is * guaranteed in this state that there is an empty thread stack and the * thread referenced in activeThread is the eventManager thread. */ public void pause() { executeEvents = false; } /** * Sets the value that is tested in the doProcess loop to determine if the * next event should be executed. Generates an interrupt of activeThread * in case the eventManager thread has already been paused and needs to * resume the event execution loop. This prevents the model being resumed * from an inconsistent state. */ public void resume(long targetTicks) { synchronized (lockObject) { targetTick = targetTicks; rebaseRealTime = true; if (executeEvents) return; executeEvents = true; Process.processEvents(this); } } @Override public String toString() { return name; } /** * Returns whether or not we are currently running in a Process context * that has a controlling EventManager. * @return true if we are in a Process context, false otherwise */ public static final boolean hasCurrent() { return (Thread.currentThread() instanceof Process); } /** * Returns the controlling EventManager for the current Process. * @throws ProcessError if called outside of a Process context */ public static final EventManager current() { return Process.current().evt(); } /** * Returns the current simulation tick for the current Process. * @throws ProcessError if called outside of a Process context */ public static final long simTicks() { return Process.current().evt().currentTick; } /** * Returns the current simulation time in seconds for the current Process. * @throws ProcessError if called outside of a Process context */ public static final double simSeconds() { return Process.current().evt()._simSeconds(); } private double _simSeconds() { return currentTick * secsPerTick; } public final void setTickLength(double tickLength) { secsPerTick = tickLength; ticksPerSecond = Math.round(1e9d / secsPerTick) / 1e9d; } /** * Convert the number of seconds rounded to the nearest tick. */ public final long secondsToNearestTick(double seconds) { return Math.round(seconds * ticksPerSecond); } /** * Convert the number of ticks into a value in seconds. */ public final double ticksToSeconds(long ticks) { return ticks * secsPerTick; } }
package com.laxture.lib.util; import java.text.DecimalFormat; public class NumberUtil { public static String format(Integer num, String pattern) { if (num == null) return ""; return new DecimalFormat(pattern).format(num); } public static String format(Long num, String pattern) { if (num == null) return ""; return new DecimalFormat(pattern).format(num); } public static String format(Double num, String pattern) { if (num == null) return ""; return new DecimalFormat(pattern).format(num); } public static String format(float num, String pattern) { return new DecimalFormat(pattern).format(num); } public static int parseInt(String text) { try { if (text.contains(".")) return (int) parseDouble(text); return Integer.parseInt(text); } catch (Exception ignored) {} return 0; } public static long parseLong(String text) { try { if (text.contains(".")) return (long) parseDouble(text); return Long.parseLong(text); } catch (Exception ignored) {} return 0; } public static short parseShort(String text) { try { return Short.parseShort(text); } catch (Exception ignored) {} return 0; } public static byte parseByte(String text) { try { return Byte.parseByte(text); } catch (Exception ignored) {} return 0; } public static float parseFloat(String text) { try { return Float.parseFloat(text); } catch (Exception ignored) {} return 0; } public static double parseDouble(String text) { try { return Double.parseDouble(text); } catch (Exception ignored) {} return 0; } public static boolean isSameDouble(Double a, Double b) { if (a == null && b == null) return true; if (a == null || b == null) return false; return Math.abs(a - b) < 1.0E-6; } }
package com.maestrano.net; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import javax.xml.bind.DatatypeConverter; import com.maestrano.Maestrano; public class MnoHttpClient { private String defaultUserAgent; private String basicAuthHash; public MnoHttpClient() { this.defaultUserAgent = "maestrano-java/" + System.getProperty("java.version"); } /** * Return a client with basic auth setup */ public static MnoHttpClient getAuthenticatedClient() { MnoHttpClient client = new MnoHttpClient(); String authStr = Maestrano.apiService().getId() + ":" + Maestrano.apiService().getKey(); client.basicAuthHash = "Basic " + DatatypeConverter.printBase64Binary(authStr.getBytes()); return client; } /** * Perform a GET request on the specified endpoint * @param url * @return response body * @throws IOException */ public String get(String url) throws IOException { return performRequest(url,"GET",null,null,null); } /** * Perform a GET request on the specified endpoint * @param url * @return response body * @throws IOException */ public String get(String url, Map<String,String> params) throws IOException { return performRequest(url,"GET",params, null,null); } /** * Perform a GET request on the specified endpoint * @param url * @return response body * @throws IOException */ public String get(String url, Map<String,String> params, Map<String,String> header) throws IOException { return performRequest(url,"GET",params, header,null); } /** * Perform a POST request on the specified endpoint * @param url * @param header * @param payload * @return response body * @throws IOException */ public String post(String url, Map<String,String> header, String payload) throws IOException { return performRequest(url,"POST",null,header,payload); } /** * Perform a PUT request on the specified endpoint * @param url * @param header * @param payload * @return response body * @throws IOException */ public String put(String url, Map<String,String> header, String payload) throws IOException { return performRequest(url,"PUT",null,header,payload); } /** * Perform a PUT request on the specified endpoint * @param url * @param header * @param payload * @return response body * @throws IOException */ public String delete(String url, Map<String,String> header, String payload) throws IOException { return performRequest(url,"DELETE",null,header,payload); } /** * Perform a request to the remote endpoint * @param url the remote endpoint to contact * @param method such as 'GET', 'PUT', 'POST' or 'DELETE' * @param header values * @param payload data to send * @return response body * @throws IOException */ protected String performRequest(String url, String method, Map<String,String> params, Map<String,String> header, String payload) throws IOException { // Prepare header if (header == null) { header = new HashMap<String,String>(); } // Set method header.put("method",method.toUpperCase()); // Set user agent if (header.get("User-Agent") == null || header.get("User-Agent").isEmpty()) { header.put("User-Agent",defaultUserAgent); } // Set authorization if (this.basicAuthHash != null && ! this.basicAuthHash.isEmpty()) { if(header.get("Authorization") == null || header.get("Authorization").isEmpty()) { header.put("Authorization",basicAuthHash); } } // Prepare url String realUrl = url; if (params != null && !params.isEmpty()) { realUrl += "?"; for (Map.Entry<String, String> param : params.entrySet()) { String key = URLEncoder.encode(param.getKey(),"UTF-8"); String val = URLEncoder.encode(param.getValue(), "UTF-8"); realUrl += "&" + key + "=" + val; } } // Get connection HttpURLConnection conn = openConnection(realUrl,header); // Send Data if PUT/POST if (payload != null) { if (method.equalsIgnoreCase("PUT") || method.equalsIgnoreCase("POST")) { OutputStream output = null; try { output = conn.getOutputStream(); output.write(payload.getBytes()); } finally { if (output != null) { output.close(); } } } } // Parse response BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuffer html = new StringBuffer(); while ((inputLine = in.readLine()) != null) { html.append(inputLine); } in.close(); return html.toString(); } /** * Open a connection and follow the redirect * @param String url * @param header contain * @return HttpURLConnection connection * @throws IOException */ protected HttpURLConnection openConnection(String url, Map<String,String> header) throws IOException { // Initialize connection URL urlObj = null; HttpURLConnection conn = null; int redirectCount = 0; boolean redirect = true; while (redirect) { if (redirectCount > 10) { throw new ProtocolException("Too many redirects: " + redirectCount); } if (conn == null) { urlObj = new URL(url); } else { // get redirect url from "location" header field urlObj = new URL(conn.getHeaderField("Location")); } // open the new connection again conn = (HttpURLConnection) urlObj.openConnection(); conn.setRequestMethod(header.get("method")); conn.addRequestProperty("User-Agent", header.get("User-Agent")); conn.setInstanceFollowRedirects(true); // Check if redirect redirect = false; int status = conn.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; redirectCount ++; } } return conn; } }
package org.opencms.workplace; import org.opencms.i18n.CmsEncoder; import org.opencms.jsp.CmsJspActionElement; import org.opencms.main.CmsLog; import org.opencms.main.I_CmsThrowable; import org.opencms.main.OpenCms; import org.opencms.util.CmsRequestUtil; import org.opencms.util.CmsStringUtil; import org.opencms.widgets.A_CmsWidget; import org.opencms.widgets.CmsDisplayWidget; import org.opencms.widgets.I_CmsWidget; import org.opencms.widgets.I_CmsWidgetDialog; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import org.apache.commons.logging.Log; /** * Base class for dialogs that use the OpenCms widgets without XML content.<p> * * @since 6.0.0 */ public abstract class CmsWidgetDialog extends CmsDialog implements I_CmsWidgetDialog { /** Action for optional element creation. */ public static final int ACTION_ELEMENT_ADD = 152; /** Action for optional element removal. */ public static final int ACTION_ELEMENT_REMOVE = 153; /** Value for the action: error in the form validation. */ public static final int ACTION_ERROR = 303; /** Value for the action: save the dialog. */ public static final int ACTION_SAVE = 300; /** Request parameter value for the action: save the dialog. */ public static final String DIALOG_SAVE = "save"; /** Indicates an optional element should be created. */ public static final String EDITOR_ACTION_ELEMENT_ADD = "addelement"; /** Indicates an optional element should be removed. */ public static final String EDITOR_ACTION_ELEMENT_REMOVE = "removeelement"; /** Prefix for "hidden" parameters, required since these must be unescaped later. */ public static final String HIDDEN_PARAM_PREFIX = "hidden."; /** The log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsWidgetDialog.class); /** The errors thrown by commit actions. */ protected List<Throwable> m_commitErrors; /** The object edited with this widget dialog. */ protected Object m_dialogObject; /** The allowed pages for this dialog in a List. */ protected List<String> m_pages; /** Controls which page is currently displayed in the dialog. */ protected String m_paramPage; /** The validation errors for the input form. */ protected List<Throwable> m_validationErrorList; /** Contains all parameter value of this dialog. */ protected Map<String, List<CmsWidgetDialogParameter>> m_widgetParamValues; /** The list of widgets used on the dialog. */ protected List<CmsWidgetDialogParameter> m_widgets; /** The set of help message ids that have already been used. */ private Set<String> m_helpMessageIds; /** * Parameter stores the index of the element to add or remove.<p> * * This must not be <code>null</code>, because it must be available * when calling <code>{@link org.opencms.workplace.CmsWorkplace#paramsAsHidden()}</code>.<p> */ private String m_paramElementIndex = "0"; /** * Parameter stores the name of the element to add or remove.<p> * * This must not be <code>null</code>, because it must be available * when calling <code>{@link org.opencms.workplace.CmsWorkplace#paramsAsHidden()}</code>.<p> */ private String m_paramElementName = "undefined"; /** Optional localized key prefix identificator. */ private String m_prefix; /** * Public constructor with JSP action element.<p> * * @param jsp an initialized JSP action element */ public CmsWidgetDialog(CmsJspActionElement jsp) { super(jsp); } /** * Public constructor with JSP variables.<p> * * @param context the JSP page context * @param req the JSP request * @param res the JSP response */ public CmsWidgetDialog(PageContext context, HttpServletRequest req, HttpServletResponse res) { this(new CmsJspActionElement(context, req, res)); } /** * Deletes the edited dialog object from the session.<p> */ public void actionCancel() { clearDialogObject(); } /** * Commits the edited object after pressing the "OK" button.<p> * * @throws IOException in case of errors forwarding to the required result page * @throws ServletException in case of errors forwarding to the required result page */ public abstract void actionCommit() throws IOException, ServletException; /** * Adds or removes an optional element.<p> * * Depends on the value stored in the <code>{@link CmsDialog#getAction()}</code> method.<p> */ public void actionToggleElement() { // get the necessary parameters to add/remove the element int index = 0; try { index = Integer.parseInt(getParamElementIndex()); } catch (Exception e) { // ignore, should not happen } String name = getParamElementName(); // get the base parameter definition CmsWidgetDialogParameter base = getParameterDefinition(name); if (base != null) { // the requested parameter is valid for this dialog List<CmsWidgetDialogParameter> params = getParameters().get(name); if (getAction() == ACTION_ELEMENT_REMOVE) { // remove the value params.remove(index); } else { List<CmsWidgetDialogParameter> sequence = getParameters().get(base.getName()); if (sequence.size() > 0) { // add the new value after the clicked element index = index + 1; } CmsWidgetDialogParameter newParam = new CmsWidgetDialogParameter(base, index); params.add(index, newParam); } // reset all index value in the parameter list for (int i = 0; i < params.size(); i++) { CmsWidgetDialogParameter param = params.get(i); param.setindex(i); } } } /** * Returns the html for a button to add an optional element.<p> * * @param elementName name of the element * @param insertAfter the index of the element after which the new element should be created * @param enabled if true, the button to add an element is shown, otherwise a spacer is returned * @return the html for a button to add an optional element */ public String buildAddElement(String elementName, int insertAfter, boolean enabled) { if (enabled) { StringBuffer href = new StringBuffer(4); href.append("javascript:addElement('"); href.append(elementName); href.append("', "); href.append(insertAfter); href.append(");"); return button(href.toString(), null, "new.png", Messages.GUI_DIALOG_BUTTON_ADDNEW_0, 0); } else { return ""; } } /** * Builds the HTML for the dialog form.<p> * * @return the HTML for the dialog form */ public String buildDialogForm() { // create the dialog HTML return createDialogHtml(getParamPage()); } /** * Returns the html for a button to remove an optional element.<p> * * @param elementName name of the element * @param index the element index of the element to remove * @param enabled if true, the button to remove an element is shown, otherwise a spacer is returned * @return the html for a button to remove an optional element */ public String buildRemoveElement(String elementName, int index, boolean enabled) { if (enabled) { StringBuffer href = new StringBuffer(4); href.append("javascript:removeElement('"); href.append(elementName); href.append("', "); href.append(index); href.append(");"); return button(href.toString(), null, "deletecontent.png", Messages.GUI_DIALOG_BUTTON_DELETE_0, 0); } else { return ""; } } /** * Clears the "dialog object" for this widget dialog by removing it from the current users session.<p> */ public void clearDialogObject() { setDialogObject(null); } /** * Builds the end HTML for a block with 3D border in the dialog content area.<p> * * @return 3D block start / end segment */ @Override public String dialogBlockEnd() { StringBuffer result = new StringBuffer(8); result.append(super.dialogBlockEnd()); result.append(dialogSpacer()); result.append("</td></tr>\n"); return result.toString(); } /** * Builds the start HTML for a block with 3D border and optional subheadline in the dialog content area.<p> * * @param headline the headline String for the block * @return 3D block start / end segment */ @Override public String dialogBlockStart(String headline) { StringBuffer result = new StringBuffer(8); result.append("<tr><td colspan=\"5\">\n"); result.append(super.dialogBlockStart(headline)); return result.toString(); } /** * Creates the HTML for the buttons on the dialog.<p> * * @return the HTML for the buttons on the dialog.<p> */ public String dialogButtonsCustom() { if (getPages().size() > 1) { // this is a multi page dialog, create buttons according to current page int pageIndex = getPages().indexOf(getParamPage()); if (pageIndex == (getPages().size() - 1)) { // this is the last dialog page return dialogButtons(new int[] {BUTTON_OK, BUTTON_BACK, BUTTON_CANCEL}, new String[3]); } else if (pageIndex > 0) { // this is a dialog page between first and last page return dialogButtons(new int[] {BUTTON_BACK, BUTTON_CONTINUE, BUTTON_CANCEL}, new String[3]); } else { // this is the first dialog page return dialogButtons(new int[] {BUTTON_CONTINUE, BUTTON_CANCEL}, new String[2]); } } boolean onlyDisplay = true; Iterator<CmsWidgetDialogParameter> it = getWidgets().iterator(); while (it.hasNext()) { CmsWidgetDialogParameter wdp = it.next(); if (!(wdp.getWidget() instanceof CmsDisplayWidget)) { onlyDisplay = false; break; } } if (!onlyDisplay) { // this is a single page dialog, create common buttons return dialogButtons(new int[] {BUTTON_OK, BUTTON_CANCEL}, new String[2]); } // this is a display only dialog return ""; } /** * Performs the dialog actions depending on the initialized action and displays the dialog form.<p> * * @throws JspException if dialog actions fail * @throws IOException if writing to the JSP out fails, or in case of errors forwarding to the required result page * @throws ServletException in case of errors forwarding to the required result page */ public void displayDialog() throws JspException, IOException, ServletException { displayDialog(false); } /** * Performs the dialog actions depending on the initialized action and displays the dialog form if needed.<p> * * @param writeLater if <code>true</code> no output is written, * you have to call manually the <code>{@link #defaultActionHtml()}</code> method. * * @throws JspException if dialog actions fail * @throws IOException if writing to the JSP out fails, or in case of errors forwarding to the required result page * @throws ServletException in case of errors forwarding to the required result page */ public void displayDialog(boolean writeLater) throws JspException, IOException, ServletException { if (isForwarded()) { return; } switch (getAction()) { case ACTION_CANCEL: // ACTION: cancel button pressed actionCancel(); actionCloseDialog(); break; case ACTION_ERROR: // ACTION: an error occurred (display nothing) break; case ACTION_SAVE: // ACTION: save edited values setParamAction(DIALOG_OK); actionCommit(); if (closeDialogOnCommit()) { setAction(ACTION_CANCEL); actionCloseDialog(); break; } setAction(ACTION_DEFAULT); //$FALL-THROUGH$ case ACTION_DEFAULT: default: // ACTION: show dialog (default) if (!writeLater) { writeDialog(); } } } /** * @see org.opencms.widgets.I_CmsWidgetDialog#getButtonStyle() */ public int getButtonStyle() { return getSettings().getUserSettings().getEditorButtonStyle(); } /** * Returns the errors that are thrown by save actions or form generation.<p> * * @return the errors that are thrown by save actions or form generation */ public List<Throwable> getCommitErrors() { return m_commitErrors; } /** * Returns the dialog object for this widget dialog, or <code>null</code> * if no dialog object has been set.<p> * * @return the dialog object for this widget dialog, or <code>null</code> */ public Object getDialogObject() { if (m_dialogObject == null) { m_dialogObject = getDialogObjectMap().get(getClass().getName()); } return m_dialogObject; } /** * @see org.opencms.widgets.I_CmsWidgetDialog#getHelpMessageIds() */ public Set<String> getHelpMessageIds() { if (m_helpMessageIds == null) { m_helpMessageIds = new HashSet<String>(); } return m_helpMessageIds; } /** * Returns the index of the element to add or remove.<p> * * @return the index of the element to add or remove */ public String getParamElementIndex() { return m_paramElementIndex; } /** * Returns the name of the element to add or remove.<p> * * @return the name of the element to add or remove */ public String getParamElementName() { return m_paramElementName; } /** * Returns the page parameter.<p> * * @return the page parameter */ public String getParamPage() { return m_paramPage; } /** * Returns the value of the widget parameter with the given name, or <code>null</code> * if no such widget parameter is available.<p> * * @param name the widget parameter name to get the value for * * @return the value of the widget parameter with the given name */ public String getParamValue(String name) { return getParamValue(name, 0); } /** * Returns the value of the widget parameter with the given name and index, or <code>null</code> * if no such widget parameter is available.<p> * * @param name the widget parameter name to get the value for * @param index the widget parameter index * * @return the value of the widget parameter with the given name and index */ public String getParamValue(String name, int index) { List<CmsWidgetDialogParameter> params = m_widgetParamValues.get(name); if (params != null) { if ((index >= 0) && (index < params.size())) { CmsWidgetDialogParameter param = params.get(index); if (param.getId().equals(CmsWidgetDialogParameter.createId(name, index))) { return param.getStringValue(getCms()); } } } return null; } /** * @see org.opencms.widgets.I_CmsWidgetDialog#getUserAgent() */ public String getUserAgent() { return getJsp().getRequest().getHeader(CmsRequestUtil.HEADER_USER_AGENT); } /** * Generates the HTML for the end of the widget dialog.<p> * * This HTML includes additional components, for example the &lt;div&gt; * tags containing the help texts.<p> * * @return the HTML for the end of the widget dialog */ public String getWidgetHtmlEnd() { StringBuffer result = new StringBuffer(32); // iterate over unique widgets from collector Iterator<CmsWidgetDialogParameter> i = getWidgets().iterator(); while (i.hasNext()) { CmsWidgetDialogParameter param = i.next(); result.append(param.getWidget().getDialogHtmlEnd(getCms(), this, param)); } return result.toString(); } /** * Generates the HTML include tags for external JavaScripts files of the used widgets.<p> * * @return the HTML include tags for external JavaScripts files of the used widgets * * @throws JspException if an error occurs during JavaScript generation */ public String getWidgetIncludes() throws JspException { StringBuffer result = new StringBuffer(32); try { // iterate over unique widgets from collector Iterator<CmsWidgetDialogParameter> i = getWidgets().iterator(); Set<I_CmsWidget> set = new HashSet<I_CmsWidget>(); while (i.hasNext()) { I_CmsWidget widget = i.next().getWidget(); if (!set.contains(widget)) { result.append(widget.getDialogIncludes(getCms(), this)); result.append('\n'); set.add(widget); } } } catch (Throwable e) { includeErrorpage(this, e); } return result.toString(); } /** * Generates the JavaScript init calls for the used widgets.<p> * * @return the JavaScript init calls for the used widgets * * @throws JspException the JavaScript init calls for the used widgets */ public String getWidgetInitCalls() throws JspException { StringBuffer result = new StringBuffer(32); try { // iterate over unique widgets from collector Iterator<CmsWidgetDialogParameter> i = getWidgets().iterator(); Set<I_CmsWidget> set = new HashSet<I_CmsWidget>(); while (i.hasNext()) { I_CmsWidget widget = i.next().getWidget(); if (!set.contains(widget)) { result.append(widget.getDialogInitCall(getCms(), this)); set.add(widget); } } } catch (Throwable e) { includeErrorpage(this, e); } return result.toString(); } /** * Generates the JavaScript initialization methods for the used widgets.<p> * * @return the JavaScript initialization methods for the used widgets * * @throws JspException if an error occurs during JavaScript generation */ public String getWidgetInitMethods() throws JspException { StringBuffer result = new StringBuffer(32); try { // iterate over unique widgets from collector Iterator<CmsWidgetDialogParameter> i = getWidgets().iterator(); Set<I_CmsWidget> set = new HashSet<I_CmsWidget>(); while (i.hasNext()) { I_CmsWidget widget = i.next().getWidget(); if (!set.contains(widget)) { result.append(widget.getDialogInitMethod(getCms(), this)); set.add(widget); } } } catch (Throwable e) { includeErrorpage(this, e); } return result.toString(); } /** * @see org.opencms.workplace.CmsWorkplace#paramsAsHidden() */ @Override public String paramsAsHidden() { if (getAction() != ACTION_ERROR) { return super.paramsAsHidden(); } // on an error page, also output the widget parameters StringBuffer result = new StringBuffer(); result.append(super.paramsAsHidden()); result.append('\n'); result.append(widgetParamsAsHidden()); return result.toString(); } /** * Stores the given object as "dialog object" for this widget dialog in the current users session.<p> * * @param dialogObject the object to store */ public void setDialogObject(Object dialogObject) { m_dialogObject = dialogObject; if (dialogObject == null) { // null object: remove the entry from the map getDialogObjectMap().remove(getClass().getName()); } else { getDialogObjectMap().put(getClass().getName(), dialogObject); } } /** * Sets the index of the element to add or remove.<p> * * @param elementIndex the index of the element to add or remove */ public void setParamElementIndex(String elementIndex) { m_paramElementIndex = elementIndex; } /** * Sets the name of the element to add or remove.<p> * * @param elementName the name of the element to add or remove */ public void setParamElementName(String elementName) { m_paramElementName = elementName; } /** * Sets the page parameter.<p> * * @param paramPage the page parameter to set */ public void setParamPage(String paramPage) { m_paramPage = paramPage; } /** * Returns the values of all widget parameters of this dialog as HTML hidden fields.<p> * * @return the values of all widget parameters of this dialog as HTML hidden fields * * @see org.opencms.workplace.CmsWorkplace#paramsAsHidden() */ public String widgetParamsAsHidden() { return widgetParamsAsHidden(null); } /** * Returns the values of all widget parameters of this dialog as HTML hidden fields, * excluding the widget values that are on the given dialog page.<p> * * This can be used to create multi-page dialogs where the values are passed from * one page to another before everything is submitted. If a widget A is used on page X, * there should be no "hidden" HTML field for A since otherwise A would have 2 values when * submitting the dialog page: The one from the widget itself and the one from the hidden * field. This may lead to undefined results when processing the submitted values.<p> * * @param excludeDialogPage the dialog page to exclude the values for * * @return the values of all widget parameters of this dialog as HTML hidden fields, * excluding the widget values that are on the given dialog page * * @see org.opencms.workplace.CmsWorkplace#paramsAsHidden() */ public String widgetParamsAsHidden(String excludeDialogPage) { StringBuffer result = new StringBuffer(); Iterator<String> i = m_widgetParamValues.keySet().iterator(); while (i.hasNext()) { List<CmsWidgetDialogParameter> params = m_widgetParamValues.get(i.next()); Iterator<CmsWidgetDialogParameter> j = params.iterator(); while (j.hasNext()) { CmsWidgetDialogParameter param = j.next(); String value = param.getStringValue(getCms()); if (CmsStringUtil.isNotEmpty(value) && ((excludeDialogPage == null) || (!param.getDialogPage().equals(excludeDialogPage)))) { result.append("<input type=\"hidden\" name=\""); result.append(HIDDEN_PARAM_PREFIX); result.append(param.getId()); result.append("\" value=\""); String encoded = CmsEncoder.encode(value, getCms().getRequestContext().getEncoding()); result.append(encoded); result.append("\">\n"); } } } return result.toString(); } /** * Writes the dialog html code, only if the <code>{@link #ACTION_DEFAULT}</code> is set.<p> * * @throws JspException if dialog actions fail * @throws IOException if writing to the JSP out fails, or in case of errors forwarding to the required result page */ public void writeDialog() throws IOException, JspException { if (isForwarded()) { return; } switch (getAction()) { case ACTION_CANCEL: case ACTION_ERROR: case ACTION_SAVE: break; case ACTION_DEFAULT: default: // ACTION: show dialog (default) setParamAction(DIALOG_SAVE); JspWriter out = getJsp().getJspContext().getOut(); out.print(defaultActionHtml()); } } /** * Adds the given error to the list of errors that are thrown by save actions or form generation.<p> * * If the error list has not been initialized yet, this is done automatically.<p> * * @param error the errors to add */ protected void addCommitError(Exception error) { if (m_commitErrors == null) { m_commitErrors = new ArrayList<Throwable>(); } m_commitErrors.add(error); } /** * Adds a new widget parameter definition to the list of all widgets of this dialog.<p> * * @param param the widget parameter definition to add */ protected void addWidget(CmsWidgetDialogParameter param) { if (m_widgets == null) { m_widgets = new ArrayList<CmsWidgetDialogParameter>(); } param.setKeyPrefix(m_prefix); m_widgets.add(param); } /** * Returns <code>true</code> if the dialog should be closed after the values have been committed.<p> * * The default implementation returns <code>true</code> in case there are no * commit errors.<p> * * @return <code>true</code> if the dialog should be closed after the values have been committed */ protected boolean closeDialogOnCommit() { return !hasCommitErrors(); } /** * Commits all values on the dialog.<p> * * @return a List of all Exceptions that occurred when comitting the dialog.<p> */ protected List<Throwable> commitWidgetValues() { return commitWidgetValues(null); } /** * Commits all values on the given dialog page.<p> * * @param dialogPage the dialog (page) to commit * * @return a List of all Exceptions that occurred when committing the dialog page.<p> */ protected List<Throwable> commitWidgetValues(String dialogPage) { List<Throwable> result = new ArrayList<Throwable>(); Iterator<CmsWidgetDialogParameter> i = getWidgets().iterator(); while (i.hasNext()) { // check for all widget parameters CmsWidgetDialogParameter base = i.next(); if ((dialogPage == null) || (base.getDialogPage() == null) || dialogPage.equals(base.getDialogPage())) { // the parameter is located on the requested dialog base.prepareCommit(); List<CmsWidgetDialogParameter> params = m_widgetParamValues.get(base.getName()); Iterator<CmsWidgetDialogParameter> j = params.iterator(); while (j.hasNext()) { CmsWidgetDialogParameter param = j.next(); try { param.commitValue(this); } catch (Exception e) { result.add(e); } } } } setValidationErrorList(result); return result; } /** * Creates the dialog HTML for all defined widgets of this dialog.<p> * * @return the dialog HTML for all defined widgets of this dialog */ protected String createDialogHtml() { return createDialogHtml(null); } /** * Creates the dialog HTML for all defined widgets of the named dialog (page).<p> * * To get a more complex layout variation, you have to overwrite this method in your dialog class.<p> * * @param dialog the dialog (page) to get the HTML for * @return the dialog HTML for all defined widgets of the named dialog (page) */ protected String createDialogHtml(String dialog) { StringBuffer result = new StringBuffer(1024); // create table result.append(createWidgetTableStart()); // show error header once if there were validation errors result.append(createWidgetErrorHeader()); Iterator<CmsWidgetDialogParameter> i = getWidgets().iterator(); // iterate the type sequence while (i.hasNext()) { // get the current widget base definition CmsWidgetDialogParameter base = i.next(); // check if the element is on the requested dialog page if ((dialog == null) || dialog.equals(base.getDialogPage())) { // add the HTML for the dialog element result.append(createDialogRowHtml(base)); } } // close table result.append(createWidgetTableEnd()); return result.toString(); } /** * Creates the dialog HTML for all occurrences of one widget parameter.<p> * * @param base the widget parameter base * @return the dialog HTML for one widget parameter */ protected String createDialogRowHtml(CmsWidgetDialogParameter base) { StringBuffer result = new StringBuffer(256); List<CmsWidgetDialogParameter> sequence = getParameters().get(base.getName()); int count = sequence.size(); // check if value is optional or multiple boolean addValue = false; if (count < base.getMaxOccurs()) { addValue = true; } boolean removeValue = false; if (count > base.getMinOccurs()) { removeValue = true; } // check if value is present boolean disabledElement = false; if (count < 1) { // no parameter with the value present, but also not optional: use base as parameter sequence = new ArrayList<CmsWidgetDialogParameter>(); sequence.add(base); count = 1; if (base.getMinOccurs() == 0) { disabledElement = true; } } // loop through multiple elements for (int j = 0; j < count; j++) { // get the parameter and the widget CmsWidgetDialogParameter p = sequence.get(j); I_CmsWidget widget = p.getWidget(); // check for an error in this row if (p.hasError()) { // show error message result.append("<tr><td></td><td><img src=\""); result.append(getSkinUri()).append("editors/xmlcontent/"); result.append("error.png"); result.append("\" border=\"0\" alt=\"\"></td><td class=\"xmlTdError\">"); Throwable t = p.getError(); while (t != null) { if (t instanceof I_CmsThrowable) { result.append(CmsEncoder.escapeXml(((I_CmsThrowable)t).getLocalizedMessage(getLocale()))); } else { result.append(CmsEncoder.escapeXml(t.getLocalizedMessage())); } t = t.getCause(); if (t != null) { result.append("<br>"); } } result.append("</td><td colspan=\"2\"></td></tr>\n"); } // create label and help bubble cells result.append("<tr>"); result.append("<td class=\"xmlLabel"); if (disabledElement) { // element is disabled, mark it with css result.append("Disabled"); } result.append("\">"); result.append(keyDefault(A_CmsWidget.getLabelKey(p), p.getName())); if (count > 1) { result.append(" [").append(p.getIndex() + 1).append("]"); } result.append(": </td>"); if (p.getIndex() == 0) { // show help bubble only on first element of each content definition result.append(p.getWidget().getHelpBubble(getCms(), this, p)); } else { // create empty cell for all following elements result.append(dialogHorizontalSpacer(16)); } // append individual widget html cell if element is enabled if (!disabledElement) { // this is a simple type, display widget result.append(widget.getDialogWidget(getCms(), this, p)); } else { // disabled element, show message for optional element result.append("<td class=\"xmlTdDisabled maxwidth\">"); result.append(key(Messages.GUI_EDITOR_WIDGET_OPTIONALELEMENT_0)); result.append("</td>"); } // append add and remove element buttons if required result.append(dialogHorizontalSpacer(5)); result.append("<td>"); if (addValue || removeValue) { result.append("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>"); if (!addValue) { result.append(dialogHorizontalSpacer(25)); } else { result.append("<td><table class=\"editorbuttonbackground\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>"); result.append(buildAddElement(base.getName(), p.getIndex(), addValue)); } if (removeValue) { if (!addValue) { result.append("<td><table class=\"editorbuttonbackground\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>"); } result.append(buildRemoveElement(base.getName(), p.getIndex(), removeValue)); } result.append("</tr></table></td>"); result.append("</tr></table>"); } result.append("</td>"); // close row result.append("</tr>\n"); } return result.toString(); } /** * Creates the dialog widget rows HTML for the specified widget indices.<p> * * @param startIndex the widget index to start with * @param endIndex the widget index to stop at * * @return the dialog widget rows HTML for the specified widget indices */ protected String createDialogRowsHtml(int startIndex, int endIndex) { StringBuffer result = new StringBuffer((endIndex - startIndex) * 8); for (int i = startIndex; i <= endIndex; i++) { CmsWidgetDialogParameter base = getWidgets().get(i); result.append(createDialogRowHtml(base)); } return result.toString(); } /** * Creates the complete widget dialog end block HTML that finishes a widget block.<p> * * @return the complete widget dialog end block HTML that finishes a widget block */ protected String createWidgetBlockEnd() { StringBuffer result = new StringBuffer(8); result.append(createWidgetTableEnd()); result.append(dialogBlockEnd()); return result.toString(); } /** * Create the complete widget dialog start block HTML that begins a widget block with optional headline.<p> * * @param headline the headline String for the block * * @return the complete widget dialog start block HTML that begins a widget block with optional headline */ protected String createWidgetBlockStart(String headline) { StringBuffer result = new StringBuffer(16); result.append(dialogBlockStart(headline)); result.append(createWidgetTableStart()); return result.toString(); } /** * Creates the HTML for the error message if validation errors were found.<p> * * @return the HTML for the error message if validation errors were found */ protected String createWidgetErrorHeader() { StringBuffer result = new StringBuffer(8); if (hasValidationErrors() || hasCommitErrors()) { result.append("<tr><td colspan=\"5\">&nbsp;</td></tr>\n"); result.append("<tr><td colspan=\"2\">&nbsp;</td>"); result.append("<td class=\"xmlTdErrorHeader\">"); result.append(key(Messages.GUI_EDITOR_WIDGET_VALIDATION_ERROR_TITLE_0)); result.append("</td><td colspan=\"2\">&nbsp;"); result.append("</td></tr>\n"); result.append("<tr><td colspan=\"5\">&nbsp;</td></tr>\n"); if (hasCommitErrors()) { result.append(dialogBlockStart("")); result.append(createWidgetTableStart()); Iterator<Throwable> i = getCommitErrors().iterator(); while (i.hasNext()) { Throwable t = i.next(); result.append("<tr><td><img src=\""); result.append(getSkinUri()).append("editors/xmlcontent/"); result.append("error.png"); result.append("\" border=\"0\" alt=\"\"></td><td class=\"xmlTdError maxwidth\">"); while (t != null) { String message = ""; if (t instanceof I_CmsThrowable) { message = ((I_CmsThrowable)t).getLocalizedMessage(getLocale()); } else { message = t.getLocalizedMessage(); } if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(message)) { result.append(CmsStringUtil.escapeHtml(message)); } t = t.getCause(); if (t != null) { result.append("<br/>"); } } result.append("</td></tr>\n"); } result.append(createWidgetTableEnd()); result.append(dialogBlockEnd()); } if (hasValidationErrors()) { result.append(dialogBlockStart("")); result.append(createWidgetTableStart()); Iterator<Throwable> i = getValidationErrorList().iterator(); while (i.hasNext()) { Throwable t = i.next(); result.append("<tr><td><img src=\""); result.append(getSkinUri()).append("editors/xmlcontent/"); result.append("error.png"); result.append("\" border=\"0\" alt=\"\"></td><td class=\"xmlTdError maxwidth\">"); while (t != null) { String message = ""; if (t instanceof I_CmsThrowable) { message = ((I_CmsThrowable)t).getLocalizedMessage(getLocale()); } else { message = t.getLocalizedMessage(); } result.append(CmsStringUtil.escapeHtml(message)); t = t.getCause(); if (t != null) { result.append("<br>"); } } result.append("</td></tr>\n"); } result.append(createWidgetTableEnd()); result.append(dialogBlockEnd()); } } return result.toString(); } /** * Creates the HTML for the table around the dialog widgets.<p> * * @return the HTML for the table around the dialog widgets */ protected String createWidgetTableEnd() { return "</table>\n"; } /** * Creates the HTML to close the table around the dialog widgets.<p> * * @return the HTML to close the table around the dialog widgets */ protected String createWidgetTableStart() { return "<table cellspacing='0' cellpadding='0' class='xmlTable'>\n"; } /** * Generates the dialog starting html code.<p> * * @return html code * * @throws JspException if something goes wrong */ protected String defaultActionHtml() throws JspException { StringBuffer result = new StringBuffer(2048); result.append(defaultActionHtmlStart()); result.append(defaultActionHtmlContent()); result.append(defaultActionHtmlEnd()); return result.toString(); } /** * Returns the html code for the default action content.<p> * * @return html code */ protected String defaultActionHtmlContent() { StringBuffer result = new StringBuffer(2048); result.append("<form name=\"EDITOR\" id=\"EDITOR\" method=\"post\" action=\"").append(getDialogRealUri()); result.append("\" class=\"nomargin\" onsubmit=\"return submitAction('").append(DIALOG_OK).append( "', null, 'EDITOR');\">\n"); result.append(dialogContentStart(getDialogTitle())); result.append(buildDialogForm()); result.append(dialogContentEnd()); result.append(dialogButtonsCustom()); result.append(paramsAsHidden()); if (getParamFramename() == null) { result.append("\n<input type=\"hidden\" name=\"").append(PARAM_FRAMENAME).append("\" value=\"\">\n"); } result.append("</form>\n"); result.append(getWidgetHtmlEnd()); return result.toString(); } /** * Generates the dialog ending html code.<p> * * @return html code */ protected String defaultActionHtmlEnd() { StringBuffer result = new StringBuffer(2048); result.append(dialogEnd()); result.append(bodyEnd()); result.append(htmlEnd()); return result.toString(); } /** * Generates the dialog starting html code.<p> * * @return html code * * @throws JspException if something goes wrong */ protected String defaultActionHtmlStart() throws JspException { StringBuffer result = new StringBuffer(2048); result.append(htmlStart("administration/index.html")); result.append("<script type=\"text/javascript\" src=\"").append(getResourceUri()).append( "editors/xmlcontent/edit.js\"></script>\n"); result.append("<script type=\"text/javascript\" src=\"").append(getResourceUri()).append( "editors/xmlcontent/help.js\"></script>\n"); result.append(getWidgetIncludes()); result.append("<script type=\"text/javascript\">\n<! result.append("// flag indicating if form initialization is finished\n"); result.append("var initialized = false;\n"); result.append("// the OpenCms context path\n"); result.append("var contextPath = \"").append(OpenCms.getSystemInfo().getOpenCmsContext()).append("\";\n\n"); result.append("// action parameters of the form\n"); result.append("var actionAddElement = \"").append(EDITOR_ACTION_ELEMENT_ADD).append("\";\n"); result.append("var actionRemoveElement = \"").append(EDITOR_ACTION_ELEMENT_REMOVE).append("\";\n"); result.append("function init() {\n"); result.append(getWidgetInitCalls()); result.append("\tsetTimeout(\"scrollForm();\", 200);\n"); result.append("\tinitialized = true;\n"); result.append("\twindow.onbeforeunload=exitEditor;\n"); result.append("}\n\n"); result.append("window.exitEditorCalled = false;\n"); result.append("function exitEditor() {\n"); result.append("\tif (window.exitEditorCalled) return;\n"); result.append("\twindow.exitEditorCalled = true; \n"); result.append("\ttry {\n"); result.append("\t\t// close file selector popup if present\n"); result.append("\t\tcloseTreeWin();\n"); result.append("\t} catch (e) {}\n"); result.append("}\n"); result.append(getWidgetInitMethods()); result.append("\n// -->\n</script>\n"); result.append(bodyStart(null, "onload='init();' onunload='exitEditor();'")); result.append(dialogStart()); return result.toString(); } /** * Defines the list of parameters for this dialog.<p> */ protected abstract void defineWidgets(); /** * Fills all widgets of this widget dialog with the values from the request parameters.<p> * * @param request the current HTTP servlet request */ protected void fillWidgetValues(HttpServletRequest request) { Map<?, ?> parameters = request.getParameterMap(); Map<String, String[]> processedParameters = new HashMap<String, String[]>(); Iterator<?> p = parameters.entrySet().iterator(); // make sure all "hidden" widget parameters are decoded while (p.hasNext()) { Map.Entry<?, ?> entry = (Map.Entry<?, ?>)p.next(); String key = (String)entry.getKey(); String[] values = (String[])entry.getValue(); if (key.startsWith(HIDDEN_PARAM_PREFIX)) { // this is an encoded hidden parameter key = key.substring(HIDDEN_PARAM_PREFIX.length()); String[] newValues = new String[values.length]; for (int l = 0; l < values.length; l++) { newValues[l] = CmsEncoder.decode(values[l], getCms().getRequestContext().getEncoding()); } values = newValues; } processedParameters.put(key, values); } // now process the parameters m_widgetParamValues = new HashMap<String, List<CmsWidgetDialogParameter>>(); Iterator<CmsWidgetDialogParameter> i = getWidgets().iterator(); while (i.hasNext()) { // check for all widget base parameters CmsWidgetDialogParameter base = i.next(); List<CmsWidgetDialogParameter> params = new ArrayList<CmsWidgetDialogParameter>(); int maxOccurs = base.getMaxOccurs(); boolean onPage = false; if (base.isCollectionBase()) { // for a collection base, check if we are on the page where the collection base is shown if (CmsStringUtil.isNotEmpty(getParamAction()) && !DIALOG_INITIAL.equals(getParamAction())) { // if no action set (usually for first display of dialog) make sure all values are shown // DIALOG_INITIAL is a special value for the first display and must be handled the same way String page = getParamPage(); // keep in mind that since the paramPage will be set AFTER the widget values are filled, // so the first time this page is called from another page the following will result to "false", // but for every "submit" on the page this will be "true" onPage = CmsStringUtil.isEmpty(page) || CmsStringUtil.isEmpty(base.getDialogPage()) || base.getDialogPage().equals(page); } } for (int j = 0; j < maxOccurs; j++) { // check for all possible values in the request parameters String id = CmsWidgetDialogParameter.createId(base.getName(), j); boolean required = (params.size() < base.getMinOccurs()) || (processedParameters.get(id) != null) || (!onPage && base.hasValue(j)); if (required) { CmsWidgetDialogParameter param = new CmsWidgetDialogParameter(base, params.size(), j); param.setKeyPrefix(m_prefix); base.getWidget().setEditorValue(getCms(), processedParameters, this, param); params.add(param); } } m_widgetParamValues.put(base.getName(), params); } } /** * Returns the title for this Dialog.<p> * * In the default implementation this method returns <code>null</code>. * Override this if needed.<p> * * @return the title for this Dialog, or <code>null</code> if this dialog has no title */ protected String getDialogTitle() { return null; } /** * Returns the allowed pages for this dialog.<p> * * @return the allowed pages for this dialog */ protected abstract String[] getPageArray(); /** * Returns the allowed pages for this dialog.<p> * * @return the allowed pages for this dialog */ protected List<String> getPages() { if (m_pages == null) { m_pages = Arrays.asList(getPageArray()); } return m_pages; } /** * Returns the parameter widget definition for the given parameter name.<p> * * @param name the parameter name to get the definition for * * @return the parameter widget definition for the given parameter name */ protected CmsWidgetDialogParameter getParameterDefinition(String name) { Iterator<CmsWidgetDialogParameter> i = getWidgets().iterator(); while (i.hasNext()) { // check for all widget parameters CmsWidgetDialogParameter base = i.next(); if (base.getName().equals(name)) { return base; } } return null; } /** * Returns the map with the widget parameter values.<p> * * @return the map with the widget parameter values */ protected Map<String, List<CmsWidgetDialogParameter>> getParameters() { return m_widgetParamValues; } /** * Returns the validation errors for the dialog.<p> * * The method (@link CmsWidgetDialog#commitWidgetValues(String)) has to set this list.<p> * * @return the validation errors for the dialog */ protected List<Throwable> getValidationErrorList() { return m_validationErrorList; } /** * Returns the widget HTML code for the given parameter.<p> * * @param param the name (id) of the parameter to get the widget HTML for * * @return the widget HTML code for the given parameter */ protected String getWidget(CmsWidgetDialogParameter param) { if (param != null) { return param.getWidget().getDialogWidget(getCms(), this, param); } return null; } /** * Returns the list of all widgets used on this widget dialog, the * List must contain Objects of type <code>{@link CmsWidgetDialogParameter}</code>.<p> * * @return the list of all widgets used on this widget dialog */ protected List<CmsWidgetDialogParameter> getWidgets() { if (m_widgets == null) { m_widgets = new ArrayList<CmsWidgetDialogParameter>(); } return m_widgets; } /** * Returns <code>true</code> if the current dialog (page) has commit errors.<p> * * @return <code>true</code> if the current dialog (page) has commit errors */ protected boolean hasCommitErrors() { return (m_commitErrors != null) && (m_commitErrors.size() > 0); } /** * Returns <code>true</code> if the current dialog (page) has validation errors.<p> * * @return <code>true</code> if the current dialog (page) has validation errors */ protected boolean hasValidationErrors() { return (m_validationErrorList != null) && (m_validationErrorList.size() > 0); } /** * @see org.opencms.workplace.CmsWorkplace#initWorkplaceRequestValues(org.opencms.workplace.CmsWorkplaceSettings, javax.servlet.http.HttpServletRequest) */ @Override protected void initWorkplaceRequestValues(CmsWorkplaceSettings settings, HttpServletRequest request) { // set the dialog type setParamDialogtype(getClass().getName()); // fill the parameter values in the get/set methods fillParamValues(request); if (CmsStringUtil.isEmptyOrWhitespaceOnly(getParamPage()) || !getPages().contains(getParamPage())) { // ensure a valid page is set setParamPage(getPages().get(0)); } // test the needed parameters try { validateParamaters(); } catch (Exception e) { if (LOG.isInfoEnabled()) { LOG.info(Messages.get().container(Messages.ERR_WORKPLACE_DIALOG_PARAMS_1, getCurrentToolPath()), e); } // close if parameters not available setAction(ACTION_CANCEL); try { actionCloseDialog(); } catch (JspException e1) { // ignore } return; } // fill the widget map defineWidgets(); fillWidgetValues(request); // set the action for the JSP switch if (DIALOG_SAVE.equals(getParamAction())) { // ok button pressed, save List<Throwable> errors = commitWidgetValues(null); if (errors.size() > 0) { setAction(ACTION_DEFAULT); // found validation errors, redisplay page return; } setAction(ACTION_SAVE); } else if (DIALOG_OK.equals(getParamAction())) { // ok button pressed setAction(ACTION_CANCEL); } else if (DIALOG_CANCEL.equals(getParamAction())) { // cancel button pressed setAction(ACTION_CANCEL); } else if (EDITOR_ACTION_ELEMENT_ADD.equals(getParamAction())) { // add optional input element setAction(ACTION_ELEMENT_ADD); actionToggleElement(); setAction(ACTION_DEFAULT); } else if (EDITOR_ACTION_ELEMENT_REMOVE.equals(getParamAction())) { // remove optional input element setAction(ACTION_ELEMENT_REMOVE); actionToggleElement(); setAction(ACTION_DEFAULT); } else if (DIALOG_BACK.equals(getParamAction())) { // go back one page setAction(ACTION_DEFAULT); List<Throwable> errors = commitWidgetValues(getParamPage()); if (errors.size() > 0) { // found validation errors, redisplay page return; } int pageIndex = getPages().indexOf(getParamPage()) - 1; setParamPage(getPages().get(pageIndex)); } else if (DIALOG_CONTINUE.equals(getParamAction())) { // go to next page setAction(ACTION_DEFAULT); List<Throwable> errors = commitWidgetValues(getParamPage()); if (errors.size() > 0) { // found validation errors, redisplay page return; } int pageIndex = getPages().indexOf(getParamPage()) + 1; setParamPage(getPages().get(pageIndex)); } else { // first dialog call, set the default action setAction(ACTION_DEFAULT); } } /** * Sets the errors that are thrown by save actions or form generation.<p> * * @param errors the errors that are thrown by save actions or form generation */ protected void setCommitErrors(List<Throwable> errors) { m_commitErrors = errors; } /** * Sets an optional localized key prefix identificator for all widgets.<p> * * @param prefix the optional localized key prefix identificator for all widgets * * @see org.opencms.widgets.I_CmsWidgetParameter#setKeyPrefix(java.lang.String) */ protected void setKeyPrefix(String prefix) { m_prefix = prefix; } /** * Sets the allowed pages for this dialog.<p> * * @param pages the allowed pages for this dialog */ protected void setPages(List<String> pages) { m_pages = pages; } /** * Sets the validation errors for the dialog.<p> * * Use this in the method (@link CmsWidgetDialog#commitWidgetValues(String)) to set the list.<p> * * @param errors the validation errors */ protected void setValidationErrorList(List<Throwable> errors) { m_validationErrorList = errors; } /** * Should be overridden for parameter validation.<p> * * The exception is never seen by the user, so it can be just a <code>new {@link Exception}()</code>.<p> * * @throws Exception if the parameters are not valid */ protected void validateParamaters() throws Exception { // valid by default } /** * Returns the (internal use only) map of dialog objects.<p> * * @return the (internal use only) map of dialog objects */ private Map<String, Object> getDialogObjectMap() { @SuppressWarnings("unchecked") Map<String, Object> objects = (Map<String, Object>)getSettings().getDialogObject(); if (objects == null) { // using hash table as most efficient version of a synchronized map objects = new Hashtable<String, Object>(); getSettings().setDialogObject(objects); } return objects; } }
package com.matt.forgehax.mods; import com.matt.forgehax.util.command.Setting; import com.matt.forgehax.util.entity.EntityUtils; import com.matt.forgehax.util.entity.LocalPlayerUtils; import com.matt.forgehax.util.math.VectorUtils; import com.matt.forgehax.util.mod.Category; import com.matt.forgehax.util.mod.ToggleMod; import com.matt.forgehax.util.mod.loader.RegisterMod; import net.minecraft.client.gui.Gui; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.texture.DynamicTexture; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.Vec3d; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.client.event.RenderPlayerEvent; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.net.URL; @RegisterMod public class WaifuESP extends ToggleMod { public WaifuESP() { super (Category.RENDER, "WaifuESP", false, "overlay cute animes over players"); } public final Setting<Boolean> noRenderPlayers = getCommandStub().builders().<Boolean>newSettingBuilder() .name("noRenderPlayers") .description("render other players") .defaultTo(false) .build(); //private ResourceLocation waifu = new ResourceLocation("textures/forgehax/waifu1.png"); private ResourceLocation waifu; private final String waifuUrl = "https://raw.githubusercontent.com/fr1kin/ForgeHax/master/src/main/resources/assets/minecraft/textures/forgehax/waifu1.png"; private BufferedImage getImageFromUrl(String link) { BufferedImage image = null; try { URL url = new URL(link); image = ImageIO.read(url); } catch (Exception e) { e.printStackTrace(); } return image; } private boolean shouldDraw(EntityLivingBase entity) { return LocalPlayerUtils.isTargetEntity(entity) || ( !entity.equals(MC.player) && EntityUtils.isAlive(entity) && EntityUtils.isValidEntity(entity) && ( EntityUtils.isPlayer(entity)) ); } @SubscribeEvent(priority = EventPriority.LOWEST) public void onRenderGameOverlayEvent (RenderGameOverlayEvent.Text event) { if (waifu == null) return; for (Entity entity : MC.world.loadedEntityList) { if (EntityUtils.isLiving(entity) && shouldDraw((EntityLivingBase) entity)) { EntityLivingBase living = (EntityLivingBase) (entity); Vec3d bottomVec = EntityUtils.getInterpolatedPos(living, event.getPartialTicks()); Vec3d topVec = bottomVec.add(new Vec3d(0, (entity.getRenderBoundingBox().maxY - entity.posY), 0)); VectorUtils.ScreenPos top = VectorUtils._toScreen(topVec.x, topVec.y, topVec.z); VectorUtils.ScreenPos bot = VectorUtils._toScreen(bottomVec.x, bottomVec.y, bottomVec.z); if (top.isVisible || bot.isVisible) { int height = (bot.y - top.y); int width = height; int x = (int)(top.x - (width / 1.8)); // normally 2.0 but lowering it shifts it to the left int y = top.y; // draw waifu MC.renderEngine.bindTexture(waifu); GlStateManager.color(255,255,255); Gui.drawScaledCustomSizeModalRect(x, y, 0, 0, width, height, width, height, width, height); } } } } @SubscribeEvent public void onRenderPlayer(RenderPlayerEvent.Pre event) { if(noRenderPlayers.getAsBoolean() && !event.getEntity().equals(MC.player)) { event.setCanceled(true); } } @Override public void onLoad() { MC.addScheduledTask(() -> { try { BufferedImage image = getImageFromUrl(waifuUrl); if (image == null) { LOGGER.warn("Failed to download waifu image"); return; } DynamicTexture dynamicTexture = new DynamicTexture(image); dynamicTexture.loadTexture(MC.getResourceManager()); waifu = MC.getTextureManager().getDynamicTextureLocation("WAIFU", dynamicTexture); } catch (Exception e) { e.printStackTrace(); } }); } }
package org.sosy_lab.solver.api; /** * Instances of this interface provide access to an SMT solver. * A single SolverContext should be used only from a single thread. * * <p>If you wish to use multiple contexts (even for the same solver), * create one SolverContext per each. * Formulas can be transferred between different contexts using * {@link FormulaManager#translate(BooleanFormula, SolverContext)}. */ public interface SolverContext extends AutoCloseable { /** * Get the formula manager, which is used for formula manipulation. */ FormulaManager getFormulaManager(); /** * Options for the prover environment. */ enum ProverOptions { /** * Whether the solver should generate models (i.e., satisfying assignments) * for satisfiable formulas. */ GENERATE_MODELS, /** * Whether the solver should generate an unsat core * for unsatisfiable formulas. */ GENERATE_UNSAT_CORE } /** * Create a fresh new {@link ProverEnvironment} which encapsulates an assertion stack * and can be used to check formulas for unsatisfiability. * * @param options Options specified for the prover environment. * All of the options specified in {@link ProverOptions} * are turned off by default. */ ProverEnvironment newProverEnvironment(ProverOptions... options); /** * Create a fresh new {@link InterpolatingProverEnvironment} which encapsulates an assertion stack * and allows to generate and retrieve interpolants for unsatisfiable formulas. * If the SMT solver is able to handle satisfiability tests with assumptions please consider * implementing the {@link InterpolatingProverEnvironmentWithAssumptions} interface, and return * an Object of this type here. */ InterpolatingProverEnvironmentWithAssumptions<?> newProverEnvironmentWithInterpolation(); /** * Create a fresh new {@link OptimizationProverEnvironment} which encapsulates an assertion stack * and allows to solve optimization queries. */ OptimizationProverEnvironment newOptimizationProverEnvironment(); /** * Get version information out of the solver. */ String getVersion(); /** * Close the solver context. * Necessary for solvers implemented in native code, frees the associated * memory. */ @Override void close(); }
package com.rultor.agents.ecs; import com.amazonaws.services.ecs.model.Container; import com.jcabi.aspects.Immutable; import com.jcabi.log.Logger; import com.jcabi.xml.XML; import com.rultor.agents.AbstractAgent; import java.io.IOException; import lombok.EqualsAndHashCode; import lombok.ToString; import org.xembly.Directive; import org.xembly.Directives; @Immutable @ToString @EqualsAndHashCode(callSuper = false, of = { "amazon" }) public final class StartsECS extends AbstractAgent { /** * AmazonECS client provider. */ private final transient Amazon amazon; /** * Ctor. * @param amaz Amazon */ public StartsECS(final Amazon amaz) { super("/talk[daemon and not(shell)]"); this.amazon = amaz; } @Override //@todo #629 Add Instance params to Directive, for example publicIpAddress public Iterable<Directive> process(final XML xml) throws IOException { final Container container = this.amazon.runOnDemand(); Logger.info( this, "ECS instance %s created", container ); return new Directives().xpath("/talk") .add("ec2") .attr("id", container.getContainerArn()); } }
package org.springframework.jndi; import java.util.Properties; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Helper class that simplifies JNDI operations. It provides methods to lookup * and bind objects, and allows implementations of the ContextCallback interface * to perform any operation they like with a JNDI naming context provided. * * <p>This is the central class in this package. It is analogous to the * JdbcTemplate class. This class performs all JNDI context handling. * * @author Rod Johnson * @author Juergen Hoeller * @see ContextCallback * @see org.springframework.jdbc.core.JdbcTemplate * @version $Id: JndiTemplate.java,v 1.4 2004-02-09 10:46:09 jhoeller Exp $ */ public class JndiTemplate { protected final Log logger = LogFactory.getLog(getClass()); private Properties environment; /** * Create a new JndiTemplate instance. */ public JndiTemplate() { } /** * Create a new JndiTemplate instance, using the given environment. */ public JndiTemplate(Properties environment) { this.environment = environment; } /** * Set the environment for the JNDI InitialContext. */ public void setEnvironment(Properties environment) { this.environment = environment; } /** * Return the environment for the JNDI InitialContext. */ public Properties getEnvironment() { return environment; } /** * Execute the given JNDI context callback implementation. * @param contextCallback ContextCallback implementation * @return a result object returned by the callback, or null * @throws NamingException thrown by the callback implementation * @see #createInitialContext */ public Object execute(ContextCallback contextCallback) throws NamingException { Context ctx = createInitialContext(); try { return contextCallback.doInContext(ctx); } finally { try { ctx.close(); } catch (NamingException ex) { logger.warn("Could not close JNDI InitialContext", ex); } } } /** * Create a new JNDI initial context. Invoked by execute. * The default implementation use this template's environment settings. * Can be subclassed for custom contexts, e.g. for testing. * @return the initial Context instance * @throws NamingException in case of initialization errors */ protected Context createInitialContext() throws NamingException { return new InitialContext(getEnvironment()); } /** * Lookup the object with the given name in the current JNDI context. * @param name the JNDI name of the object * @return object found (cannot be null; if a not so well-behaved * JNDI implementations returns null, a NamingException gets thrown) * @throws NamingException if there is no object with the given * name bound to JNDI */ public Object lookup(final String name) throws NamingException { return execute(new ContextCallback() { public Object doInContext(Context ctx) throws NamingException { logger.debug("Looking up JNDI object with name '" + name + "'"); Object located = ctx.lookup(name); if (located == null) { throw new NamingException("JNDI object not found: JNDI implementation returned null"); } return located; } }); } /** * Bind the given object to the current JNDI context, using the given name. * @param name the JNDI name of the object * @param object the object to bind * @throws NamingException thrown by JNDI, mostly name already bound */ public void bind(final String name, final Object object) throws NamingException { execute(new ContextCallback() { public Object doInContext(Context ctx) throws NamingException { logger.info("Binding JNDI object with name '" + name + "'"); ctx.bind(name, object); return null; } }); } /** * Remove the binding for the given name from the current JNDI context. * @param name the JNDI name of the object * @throws NamingException thrown by JNDI, mostly name not found */ public void unbind(final String name) throws NamingException { execute(new ContextCallback() { public Object doInContext(Context ctx) throws NamingException { logger.info("Unbinding JNDI object with name '" + name + "'"); ctx.unbind(name); return null; } }); } }
package com.ts.timeseries.grid; import com.google.common.collect.ImmutableBiMap; import com.ts.timeseries.util.Preconditions; import java.util.concurrent.TimeUnit; final class Duration { @SuppressWarnings({"WeakerAccess"}) private static final ImmutableBiMap<String, TimeUnit> identifiers = ImmutableBiMap.of( "ms", TimeUnit.MILLISECONDS , "s", TimeUnit.SECONDS , "min", TimeUnit.MINUTES , "h", TimeUnit.HOURS , "d", TimeUnit.DAYS ); private final TimeUnit timeUnit; private final long value; Duration(String serialized) { TimeUnit unit = null; long val = 0; for (String identifier : identifiers.keySet()) { if (serialized.endsWith(identifier)) { unit = identifiers.get(identifier); val = Long.valueOf(serialized.substring(0, serialized.length() - identifier.length())); break; } } Preconditions.checkNotNull(unit, "Wrong format, should be number + any of " + identifiers.keySet()); timeUnit = unit; value = val; } /** * Duration in Milliseconds * * @return Length of Duration in Milliseconds */ long getDurationInMs() { return timeUnit.toMillis(value); } }
package com.yahoo.memory; import java.nio.ByteBuffer; import java.nio.ByteOrder; /** * Provides read and write, positional primitive and primitive array access to any of the four * resources mentioned at the package level. * * @author Roman Leventov * @author Lee Rhodes */ public abstract class WritableBuffer extends Buffer { //Pass-through ctor for all parameters WritableBuffer( final Object unsafeObj, final long nativeBaseOffset, final long regionOffset, final long capacityBytes, final boolean readOnly, final ByteOrder byteOrder, final ByteBuffer byteBuf, final StepBoolean valid) { super(unsafeObj, nativeBaseOffset, regionOffset, capacityBytes, readOnly, byteOrder, byteBuf, valid); } //BYTE BUFFER XXX /** * Accesses the given ByteBuffer for write operations. The returned WritableBuffer object has * the same byte order, as the given ByteBuffer, unless the capacity of the given ByteBuffer is * zero, then byte order of the returned WritableBuffer object, as well as backing storage and * read-only status are unspecified. * @param byteBuf the given ByteBuffer, must not be null. * @return a new WritableBuffer for write operations on the given ByteBuffer. */ public static WritableBuffer wrap(final ByteBuffer byteBuf) { return wrap(byteBuf, byteBuf.order()); } /** * Accesses the given ByteBuffer for write operations. The returned WritableBuffer object has * the given byte order, ignoring the byte order of the given ByteBuffer. If the capacity of * the given ByteBuffer is zero the byte order of the returned WritableBuffer object * (as well as backing storage) is unspecified. * @param byteBuf the given ByteBuffer, must not be null * @param byteOrder the byte order to be used, which may be independent of the byte order * state of the given ByteBuffer * @return a new WritableBuffer for write operations on the given ByteBuffer. */ public static WritableBuffer wrap(final ByteBuffer byteBuf, final ByteOrder byteOrder) { final BaseWritableMemoryImpl wmem = BaseWritableMemoryImpl.wrapByteBuffer(byteBuf, false, byteOrder); final WritableBuffer wbuf = wmem.asWritableBufferImpl(false, byteOrder); wbuf.setStartPositionEnd(0, byteBuf.position(), byteBuf.limit()); return wbuf; } //MAP XXX //Use WritableMemory for mapping files and then asWritableBuffer() //ALLOCATE DIRECT XXX //Use WritableMemory to allocate direct memory and then asWritableBuffer(). //DUPLICATES XXX /** * Returns a duplicate writable view of this Buffer with the same but independent values of * <i>start</i>, <i>position</i> and <i>end</i>. * If this object's capacity is zero, the returned object is effectively immutable and * the backing storage and byte order are unspecified. * @return a duplicate writable view of this Buffer with the same but independent values of * <i>start</i>, <i>position</i> and <i>end</i>. */ public abstract WritableBuffer writableDuplicate(); //REGIONS XXX /** * A writable region is a writable view of the backing store of this object. * This returns a new <i>WritableBuffer</i> representing the defined writable region. * <ul> * <li>Returned object's origin = this object's <i>position</i></li> * <li>Returned object's <i>start</i> = 0</li> * <li>Returned object's <i>position</i> = 0</li> * <li>Returned object's <i>end</i> = this object's (<i>end</i> - <i>position</i>)</li> * <li>Returned object's <i>capacity</i> = this object's (<i>end</i> - <i>position</i>)</li> * <li>Returned object's <i>start</i>, <i>position</i> and <i>end</i> are mutable and * independent of this object's <i>start</i>, <i>position</i> and <i>end</i></li> * </ul> * If this object's capacity is zero, the returned object is effectively immutable and * the backing storage and byte order are unspecified. * @return a new <i>WritableBuffer</i> representing the defined writable region. */ public abstract WritableBuffer writableRegion(); /** * A writable region is a writable view of the backing store of this object. * This returns a new <i>WritableBuffer</i> representing the defined writable region * with the given offsetBytes, capacityBytes and byte order. * <ul> * <li>Returned object's origin = this objects' origin + <i>offsetBytes</i></li> * <li>Returned object's <i>start</i> = 0</li> * <li>Returned object's <i>position</i> = 0</li> * <li>Returned object's <i>end</i> = <i>capacityBytes</i></li> * <li>Returned object's <i>capacity</i> = <i>capacityBytes</i></li> * <li>Returned object's <i>start</i>, <i>position</i> and <i>end</i> are mutable and * independent of this object's <i>start</i>, <i>position</i> and <i>end</i></li> * <li>Returned object's byte order = <i>byteOrder</i></li> * </ul> * If this object's capacity is zero, the returned object is effectively immutable and * the backing storage and byte order are unspecified. * * <p><b>Note: </b><i>asWritableMemory()</i> and <i>asMemory()</i> * will return the originating <i>Memory</i> byte order.</p> * @param offsetBytes the starting offset with respect to the origin of this <i>WritableBuffer</i> * @param capacityBytes the <i>capacity</i> of the returned region in bytes * @param byteOrder the given byte order * @return a new <i>WritableBuffer</i> representing the defined writable region. */ public abstract WritableBuffer writableRegion(long offsetBytes, long capacityBytes, ByteOrder byteOrder); //AS MEMORY XXX /** * Convert this WritableBuffer to a WritableMemory. * If this object's capacity is zero, the returned object is effectively immutable and * the backing storage and byte order are unspecified. * @return WritableMemory */ public abstract WritableMemory asWritableMemory(); //ACCESS PRIMITIVE HEAP ARRAYS for write XXX //use WritableMemory and then asWritableBuffer(). //END OF CONSTRUCTOR-TYPE METHODS //PRIMITIVE putXXX() and putXXXArray() XXX /** * Puts the boolean value at the current position. * Increments the position by 1. * @param value the value to put */ public abstract void putBoolean(boolean value); /** * Puts the boolean value at the given offset. * This does not change the position. * @param offsetBytes offset bytes relative to this <i>WritableMemory</i> start. * @param value the value to put */ public abstract void putBoolean(long offsetBytes, boolean value); /** * Puts the boolean array at the current position. * Increments the position by <i>lengthBooleans - srcOffsetBooleans</i>. * @param srcArray The source array. * @param srcOffsetBooleans offset in array units * @param lengthBooleans number of array units to transfer */ public abstract void putBooleanArray(boolean[] srcArray, int srcOffsetBooleans, int lengthBooleans); /** * Puts the byte value at the current position. * Increments the position by <i>Byte.BYTES</i>. * @param value the value to put */ public abstract void putByte(byte value); /** * Puts the byte value at the given offset. * This does not change the position. * @param offsetBytes offset bytes relative to this <i>WritableMemory</i> start * @param value the value to put */ public abstract void putByte(long offsetBytes, byte value); /** * Puts the byte array at the current position. * Increments the position by <i>Byte.BYTES * (lengthBytes - srcOffsetBytes)</i>. * @param srcArray The source array. * @param srcOffsetBytes offset in array units * @param lengthBytes number of array units to transfer */ public abstract void putByteArray(byte[] srcArray, int srcOffsetBytes, int lengthBytes); /** * Puts the char value at the current position. * Increments the position by <i>Character.BYTES</i>. * @param value the value to put */ public abstract void putChar(char value); /** * Puts the char value at the given offset. * This does not change the position. * @param offsetBytes offset bytes relative to this <i>WritableMemory</i> start * @param value the value to put */ public abstract void putChar(long offsetBytes, char value); /** * Puts the char array at the current position. * Increments the position by <i>Character.BYTES * (lengthChars - srcOffsetChars)</i>. * @param srcArray The source array. * @param srcOffsetChars offset in array units * @param lengthChars number of array units to transfer */ public abstract void putCharArray(char[] srcArray, int srcOffsetChars, int lengthChars); /** * Puts the double value at the current position. * Increments the position by <i>Double.BYTES</i>. * @param value the value to put */ public abstract void putDouble(double value); /** * Puts the double value at the given offset. * This does not change the position. * @param offsetBytes offset bytes relative to this <i>WritableMemory</i> start * @param value the value to put */ public abstract void putDouble(long offsetBytes, double value); /** * Puts the double array at the current position. * Increments the position by <i>Double.BYTES * (lengthDoubles - srcOffsetDoubles)</i>. * @param srcArray The source array. * @param srcOffsetDoubles offset in array units * @param lengthDoubles number of array units to transfer */ public abstract void putDoubleArray(double[] srcArray, int srcOffsetDoubles, int lengthDoubles); /** * Puts the float value at the current position. * Increments the position by <i>Float.BYTES</i>. * @param value the value to put */ public abstract void putFloat(float value); /** * Puts the float value at the given offset. * This does not change the position. * @param offsetBytes offset bytes relative to this <i>WritableMemory</i> start * @param value the value to put */ public abstract void putFloat(long offsetBytes, float value); /** * Puts the float array at the current position. * Increments the position by <i>Float.BYTES * (lengthFloats - srcOffsetFloats)</i>. * @param srcArray The source array. * @param srcOffsetFloats offset in array units * @param lengthFloats number of array units to transfer */ public abstract void putFloatArray(float[] srcArray, int srcOffsetFloats, int lengthFloats); /** * Puts the int value at the current position. * Increments the position by <i>Integer.BYTES</i>. * @param value the value to put */ public abstract void putInt(int value); /** * Puts the int value at the given offset. * This does not change the position. * @param offsetBytes offset bytes relative to this <i>WritableMemory</i> start * @param value the value to put */ public abstract void putInt(long offsetBytes, int value); /** * Puts the int array at the current position. * Increments the position by <i>Integer.BYTES * (lengthInts - srcOffsetInts)</i>. * @param srcArray The source array. * @param srcOffsetInts offset in array units * @param lengthInts number of array units to transfer */ public abstract void putIntArray(int[] srcArray, int srcOffsetInts, int lengthInts); /** * Puts the long value at the current position. * Increments the position by <i>Long.BYTES</i>. * @param value the value to put */ public abstract void putLong(long value); /** * Puts the long value at the given offset. * This does not change the position. * @param offsetBytes offset bytes relative to this <i>WritableMemory</i> start * @param value the value to put */ public abstract void putLong(long offsetBytes, long value); /** * Puts the long array at the current position. * Increments the position by <i>Long.BYTES * (lengthLongs - srcOffsetLongs)</i>. * @param srcArray The source array. * @param srcOffsetLongs offset in array units * @param lengthLongs number of array units to transfer */ public abstract void putLongArray(long[] srcArray, int srcOffsetLongs, int lengthLongs); /** * Puts the short value at the current position. * Increments the position by <i>Short.BYTES</i>. * @param value the value to put */ public abstract void putShort(short value); /** * Puts the short value at the given offset. * This does not change the position. * @param offsetBytes offset bytes relative to this <i>WritableMemory</i> start * @param value the value to put */ public abstract void putShort(long offsetBytes, short value); /** * Puts the short array at the current position. * Increments the position by <i>Short.BYTES * (lengthShorts - srcOffsetShorts)</i>. * @param srcArray The source array. * @param srcOffsetShorts offset in array units * @param lengthShorts number of array units to transfer */ public abstract void putShortArray(short[] srcArray, int srcOffsetShorts, int lengthShorts); //OTHER WRITE METHODS XXX /** * Returns the primitive backing array, otherwise null. * @return the primitive backing array, otherwise null. */ public abstract Object getArray(); /** * Clears all bytes of this Buffer from position to end to zero. The position will be set to end. */ public abstract void clear(); /** * Fills this Buffer from position to end with the given byte value. * The position will be set to <i>end</i>. * @param value the given byte value */ public abstract void fill(byte value); //OTHER XXX /** * Returns the offset of the start of this WritableBuffer from the backing resource, * but not including any Java object header. * * @return the offset of the start of this WritableBuffer from the backing resource. */ public abstract long getRegionOffset(); /** * Returns the offset of the start of this WritableBuffer from the backing resource plus * the given offsetBytes, but not including any Java object header. * * @param offsetBytes the given offset bytes * @return the offset of the start of this WritableBuffer from the backing resource. */ public abstract long getRegionOffset(long offsetBytes); }
package de.dhbw.humbuch.util; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import au.com.bytecode.opencsv.CSVReader; import de.dhbw.humbuch.model.SubjectHandler; import de.dhbw.humbuch.model.entity.Grade; import de.dhbw.humbuch.model.entity.Parent; import de.dhbw.humbuch.model.entity.Student; import de.dhbw.humbuch.model.entity.Subject; public final class CSVHandler { /** * Reads a csv file and creates student objects of it's records. * * @param path * a path to the csv which contains information about students * @return an ArrayList that contains student objects * @exception throws an UnsupportedOperationException if an error occurred * @see ArrayList */ public static ArrayList<Student> createStudentObjectsFromCSV(CSVReader csvReaderParam) throws UnsupportedOperationException { ArrayList<Student> studentArrayList = new ArrayList<Student>(); try { //csvReader - separator is ';'; CSVReader csvReader = csvReaderParam; Properties csvHeaderProperties = readCSVConfigurationFile(); Map<String, String> csvHeaderPropertyStrings = new LinkedHashMap<>(); for (Object property : csvHeaderProperties.keySet()) { csvHeaderPropertyStrings.put(((String) property).replaceAll("\\p{C}", ""), csvHeaderProperties.getProperty((String) property)); } List<String[]> allRecords = csvReader.readAll(); Iterator<String[]> allRecordsIterator = allRecords.iterator(); HashMap<String, Integer> headerIndexMap = new HashMap<String, Integer>(); if (allRecordsIterator.hasNext()) { String[] headerRecord = allRecordsIterator.next(); for (int i = 0; i < headerRecord.length; i++) { // removes all non-printable characters headerIndexMap.put(headerRecord[i].replaceAll("\\p{C}", ""), i); } } int index = 0; while (allRecordsIterator.hasNext()) { String[] record = allRecordsIterator.next(); index++; Student student = createStudentObject(record, csvHeaderPropertyStrings, headerIndexMap, index); if (student != null) { studentArrayList.add(student); } else { throw new UnsupportedOperationException("Mindestens ein Studenten-Datensatz war korrumpiert"); } } csvReader.close(); } catch (IOException e) { throw new UnsupportedOperationException("Die Studentendaten konnten nicht eingelesen werden"); } return studentArrayList; } private static Properties readCSVConfigurationFile() { Properties csvHeaderProperties = new Properties(); try { csvHeaderProperties.load(new InputStreamReader(new ResourceLoader("csvConfiguration.properties").getStream())); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return csvHeaderProperties; } /** * Creates a student object with the information in the record. * * @param record * is one line of the loaded csv-file * @param dataSetIndex * @return Student */ private static Student createStudentObject(String[] record, Map<String, String> properties, HashMap<String, Integer> index, int dataSetIndex) throws UnsupportedOperationException { String foreignLanguage1, foreignLanguage2, foreignLanguage3, gradeString, firstName, lastName, gender, birthDay, religion; String parentTitle, parentLastName, parentFirstName, parentStreet, parentPlace; int id; int parentPostalcode; try { foreignLanguage1 = record[getAttributeNameToHeaderIndex(properties, index, "foreignLanguage1")]; foreignLanguage2 = record[getAttributeNameToHeaderIndex(properties, index, "foreignLanguage2")]; foreignLanguage3 = record[getAttributeNameToHeaderIndex(properties, index, "foreignLanguage3")]; gradeString = record[getAttributeNameToHeaderIndex(properties, index, "grade")]; firstName = record[getAttributeNameToHeaderIndex(properties, index, "firstName")]; lastName = record[getAttributeNameToHeaderIndex(properties, index, "lastName")]; gender = record[getAttributeNameToHeaderIndex(properties, index, "gender")]; birthDay = record[getAttributeNameToHeaderIndex(properties, index, "birthDay")]; id = Integer.parseInt(record[getAttributeNameToHeaderIndex(properties, index, "id")]); religion = record[getAttributeNameToHeaderIndex(properties, index, "religion")]; } catch (ArrayIndexOutOfBoundsException a) { throw new UnsupportedOperationException("Ein Wert im Studentendatensatz konnte nicht gelesen werden. Fehler in Datensatz: " + dataSetIndex); } catch (NumberFormatException e) { throw new UnsupportedOperationException("Mindestens eine Postleitzahl ist keine gültige Nummer. Fehler in Datensatz: " + dataSetIndex); } Parent parent = null; try { parentTitle = record[getAttributeNameToHeaderIndex(properties, index, "parentTitle")]; parentLastName = record[getAttributeNameToHeaderIndex(properties, index, "parentLastName")]; parentFirstName = record[getAttributeNameToHeaderIndex(properties, index, "parentFirstName")]; parentStreet = record[getAttributeNameToHeaderIndex(properties, index, "parentStreet")]; parentPostalcode = Integer.parseInt(record[getAttributeNameToHeaderIndex(properties, index, "parentPostalcode")]); parentPlace = record[getAttributeNameToHeaderIndex(properties, index, "parentPlace")]; parent = new Parent.Builder(parentFirstName, parentLastName).title(parentTitle) .street(parentStreet).postcode(parentPostalcode).city(parentPlace).build(); } catch (NullPointerException e) { throw new UnsupportedOperationException("Die Elterndaten enthalten an mindestens einer Stelle einen Fehler. Fehler in Datensatz: " + dataSetIndex); } catch (ArrayIndexOutOfBoundsException e) { throw new UnsupportedOperationException("Mindestens ein Datensatz enthält keine Eltern-Informationen. Fehler in Datensatz: " + dataSetIndex); } catch (NumberFormatException e) { throw new UnsupportedOperationException("Mindestens eine Postleitzahl ist keine gültige Nummer.Fehler in Datensatz: " + dataSetIndex); } Map<String, Boolean> checkValidityMap = new LinkedHashMap<>(); checkValidityMap.put(foreignLanguage1, true); checkValidityMap.put(foreignLanguage2, true); checkValidityMap.put(foreignLanguage3, true); checkValidityMap.put(gradeString, false); checkValidityMap.put(firstName, false); checkValidityMap.put(lastName, false); checkValidityMap.put(gender, false); checkValidityMap.put(birthDay, false); checkValidityMap.put("" + id, false); checkValidityMap.put(religion, false); checkValidityMap.put(parentTitle, false); checkValidityMap.put(parentLastName, false); checkValidityMap.put(parentFirstName, false); checkValidityMap.put(parentStreet, false); checkValidityMap.put("" + parentPostalcode, false); checkValidityMap.put(parentPlace, false); String check = checkForValidityOfAttributes(checkValidityMap); if (!check.equals("okay")) { if(check.equals("error")){ throw new UnsupportedOperationException("Mindestens ein Studenten-Datensatz war korrumpiert. Fehler in Datensatz: " + dataSetIndex); } else if(check.equals("empty")){ throw new UnsupportedOperationException("Ein Datensatz ist nicht vollständig gefüllt. Fehler in Datensatz: " + dataSetIndex); } } Date date = null; try { date = new SimpleDateFormat("dd.mm.yyyy", Locale.GERMAN).parse(birthDay); } catch (ParseException e) { System.err.println("Could not format date " + e.getStackTrace()); return null; } Grade grade = new Grade.Builder(gradeString).build(); String[] foreignLanguage = new String[3]; foreignLanguage[0] = foreignLanguage1; foreignLanguage[1] = foreignLanguage2; foreignLanguage[2] = foreignLanguage3; Set<Subject> subjectSet = SubjectHandler.createProfile(foreignLanguage, religion); return new Student.Builder(id, firstName, lastName, date, grade).profile(subjectSet).gender(gender).parent(parent).leavingSchool(false).build(); } private static int getAttributeNameToHeaderIndex(Map<String, String> properties, HashMap<String, Integer> indexMap, String attributeName) throws UnsupportedOperationException { String headerValue = (String) properties.get(attributeName); if (headerValue != null) { int indexHeader = -1; if (indexMap.get(headerValue) != null) { indexHeader = indexMap.get(headerValue); } else { throw new UnsupportedOperationException("Ein CSV-Spaltenname konnte nicht zugeordnet werden. " + "Bitte die Einstellungsdatei mit der CSV-Datei abgleichen. Spaltenname: " + headerValue); } return indexHeader; } return -1; } /** * If one string of the map is -1 an error occurred previously and the * method will return false. If one string is empty that is not to allowed to * be empty (indicated by 'false' in the map) the method will return false. * If this method returns false, an exception will be thrown that the CSV lacks important data. * If this method returns true, the data set of the CSV is correct. * * @param attributes * @return boolean that indicates whether the data set of the CSV is correct or not. */ private static String checkForValidityOfAttributes(Map<String, Boolean> attributes) { for (String str : attributes.keySet()) { if (str.equals("-1")) { return "error"; } if (!attributes.get(str)) { if (str.equals("")) { return "empty"; } } } return "okay"; } }
package utils; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.Callable; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.hibernate.Session; import org.webdsl.WebDSLEntity; import org.webdsl.lang.Environment; import org.webdsl.logging.Logger; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; public abstract class AbstractPageServlet{ protected abstract void renderDebugJsVar(PrintWriter sout); protected abstract boolean logSqlCheckAccess(); protected abstract void initTemplateClass(); protected abstract void redirectHttpHttps(); protected abstract boolean isActionSubmit(); protected abstract String[] getUsedSessionEntityJoins(); protected TemplateServlet templateservlet = null; protected abstract org.webdsl.WebDSLEntity getRequestLogEntry(); protected abstract void addPrincipalToRequestLog(org.webdsl.WebDSLEntity rle); protected abstract void addLogSqlToSessionMessages(); public Session hibernateSession = null; protected static Pattern isMarkupLangMimeType= Pattern.compile("html|xml$"); protected static Pattern baseURLPattern= Pattern.compile("(^\\w{0,6})(: protected AbstractPageServlet commandingPage = this; public boolean isReadOnly = false; public boolean isWebService(){ return false; } public String placeholderId = "1"; static{ common_css_link_tag_suffix = "/stylesheets/" + CachedResourceFileNameHelper.getNameWithHash("stylesheets", "common_.css") + "\" rel=\"stylesheet\" type=\"text/css\" />"; fav_ico_link_tag_suffix = "/" + CachedResourceFileNameHelper.getNameWithHash("", "favicon.ico") + "\" rel=\"shortcut icon\" type=\"image/x-icon\" />"; ajax_js_include_name = "ajax.js"; } public void serve(HttpServletRequest request, HttpServletResponse httpServletResponse, Map<String, String> parammap, Map<String, List<String>> parammapvalues, Map<String,List<utils.File>> fileUploads) throws Exception { initTemplateClass(); this.startTime = System.currentTimeMillis(); ThreadLocalPage.set(this); this.request=request; this.httpServletResponse = httpServletResponse; this.response = new ResponseWrapper(httpServletResponse); this.parammap = parammap; this.parammapvalues = parammapvalues; this.fileUploads=fileUploads; redirectHttpHttps(); String ajaxParam = parammap.get( "__ajax_runtime_request__" ); if( ajaxParam != null ){ this.setAjaxRuntimeRequest( true ); if( ajaxParam != "1" ){ placeholderId = ajaxParam; } } org.webdsl.WebDSLEntity rle = getRequestLogEntry(); org.apache.log4j.MDC.put("request", rle.getId().toString()); org.apache.log4j.MDC.put("template", "/" + getPageName()); utils.RequestAppender reqAppender = null; if(parammap.get("disableopt") != null){ this.isOptimizationEnabled = false; } if(parammap.get("logsql") != null){ this.isLogSqlEnabled = true; this.isPageCacheDisabled = true; reqAppender = utils.RequestAppender.getInstance(); } if(reqAppender != null){ reqAppender.addRequest(rle.getId().toString()); } if(parammap.get("nocache") != null){ this.isPageCacheDisabled = true; } initRequestVars(); hibernateSession = utils.HibernateUtil.getCurrentSession(); hibernateSession.beginTransaction(); if(isReadOnly){ hibernateSession.setFlushMode(org.hibernate.FlushMode.MANUAL); } else{ hibernateSession.setFlushMode(org.hibernate.FlushMode.COMMIT); } try { StringWriter s = new StringWriter(); PrintWriter out = new PrintWriter(s); ThreadLocalOut.push(out); ThreadLocalServlet.get().loadSessionManager(hibernateSession, getUsedSessionEntityJoins()); ThreadLocalServlet.get().retrieveIncomingMessagesFromHttpSession(); initVarsAndArgs(); enterPlaceholderIdContext(); if(isActionSubmit()) { if(parammap.get("__action__link__") != null) { this.setActionLinkUsed(true); } templateservlet.storeInputs(null, args, new Environment(envGlobalAndSession), null); clearTemplateContext(); //storeinputs also finds which action is executed, since validation might be ignored using [ignore-validation] on the submit boolean ignoreValidation = actionToBeExecutedHasDisabledValidation; if (!ignoreValidation){ templateservlet.validateInputs (null, args, new Environment(envGlobalAndSession), null); clearTemplateContext(); } if(validated){ templateservlet.handleActions(null, args, new Environment(envGlobalAndSession), null); clearTemplateContext(); } } if(isNotValid()){ // mark transaction so it will be aborted at the end // entered form data can be used to update the form on the client with ajax, taking into account if's and other control flow template elements // this also means that data in vars/args and hibernate session should not be cleared until form is rendered abortTransaction(); } String outstream = s.toString(); if(download != null) { //File.download() excecuted in action download(); } else { boolean isAjaxResponse = true; // regular render, or failed action render if( hasNotExecutedAction() || isNotValid() ){ // ajax replace performed during validation, assuming that handles all validation // all inputajax templates use rollback() to prevent making actual changes -> check for isRollback() if(isAjaxRuntimeRequest() && outstream.length() > 0 && isRollback()){ response.getWriter().write("["); response.getWriter().write(outstream); if(this.isLogSqlEnabled()){ // Cannot use (parammap.get("logsql") != null) here, because the parammap is cleared by actions if(logSqlCheckAccess()){ response.getWriter().write("{action: \"logsql\", value: \"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(utils.HibernateLog.printHibernateLog(this, "ajax")) + "\"}"); } else{ response.getWriter().write("{action: \"logsql\", value: \"Access to SQL logs was denied.\"}"); } response.getWriter().write(","); } response.getWriter().write("{}]"); } // action called but no action found else if( !isWebService() && isValid() && isActionSubmit() ){ org.webdsl.logging.Logger.error("Error: server received POST request but was unable to dispatch to a proper action (" + getRequestURL() + ")" ); httpServletResponse.setStatus( 404 ); response.getWriter().write("404 \n Error: server received POST request but was unable to dispatch to a proper action"); } // action inside ajax template called and failed else if( isAjaxTemplateRequest() && isActionSubmit() ){ StringWriter s1 = renderPageOrTemplateContents(); response.getWriter().write("[{action:\"replace\", id:{type:'enclosing-placeholder'}, value:\"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(s1.toString()) + "\"}]"); } //actionLink or ajax action used (request came through js runtime), and action failed else if( isActionLinkUsed() || isAjaxRuntimeRequest() ){ validationFormRerender = true; renderPageOrTemplateContents(); if(submittedFormId != null){ response.getWriter().write("[{action:\"replace\", id:\"" + submittedFormId + "\", value:\"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript( submittedFormContent ) + "\"}]"); } else{ response.getWriter().write("[{action:\"replace\", id:{submitid:'" + submittedSubmitId + "'}, value:\"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript( submittedFormContent ) + "\"}]"); } } // 1 regular render without any action being executed // 2 regular action submit, and action failed // 3 redirect in page init // 4 download in page init else{ isAjaxResponse = false; renderOrInitAction(); } } // successful action, always redirect, no render else { // actionLink or ajax action used and replace(placeholder) invoked if( isReRenderPlaceholders() ){ response.getWriter().write( "[" ); templateservlet.validateInputs (null, args, new Environment(envGlobalAndSession), null); clearTemplateContext(); renderDynamicFormWithOnlyDirtyData = true; renderPageOrTemplateContents(); // content of placeholders is collected in reRenderPlaceholdersContent map StringWriter replacements = new StringWriter(); boolean addComma = false; for(String ph : reRenderPlaceholders){ if(addComma){ replacements.write(","); } else { addComma = true; } replacements.write("{action:\"replace\", id:\""+ph+"\", value:\"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(reRenderPlaceholdersContent.get(ph)) + "\"}"); } response.getWriter().write( replacements.toString() ); if( outstream.length() > 0 ){ response.getWriter().write( "," + outstream.substring(0, outstream.length() - 1) + "]" ); // Other ajax updates, such as clear(ph). Done after ph rerendering to allow customization. } else{ response.getWriter().write( "]" ); } } //hasExecutedAction() && isValid() else if( isAjaxRuntimeRequest() ){ response.getWriter().write("["); response.getWriter().write(outstream); if(this.isLogSqlEnabled()){ // Cannot use (parammap.get("logsql") != null) here, because the parammap is cleared by actions if(logSqlCheckAccess()){ response.getWriter().write("{action: \"logsql\", value: \"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(utils.HibernateLog.printHibernateLog(this, "ajax")) + "\"}"); } else{ response.getWriter().write("{action: \"logsql\", value: \"Access to SQL logs was denied.\"}"); } response.getWriter().write(","); } response.getWriter().write("{}]"); } else if( isActionLinkUsed() ){ //action link also uses ajax when ajax is not enabled //, send only redirect location, so the client can simply set // window.location = req.responseText; response.getWriter().write("[{action:\"relocate\", value:\""+this.getRedirectUrl() + "\"}]"); } else { isAjaxResponse = false; } if(!isAjaxRuntimeRequest()) { addLogSqlToSessionMessages(); } //else: action successful + no validation error + regular submit // -> always results in a redirect, no further action necessary here } if(isAjaxResponse){ response.setContentType("application/json"); } } updatePageRequestStatistics(); hibernateSession = utils.HibernateUtil.getCurrentSession(); if( isTransactionAborted() || isRollback() ){ try{ hibernateSession.getTransaction().rollback(); response.sendContent(); } catch (org.hibernate.SessionException e){ if(!e.getMessage().equals("Session is closed!")){ // closed session is not an issue when rolling back throw e; } } } else { ThreadLocalServlet.get().storeOutgoingMessagesInHttpSession( !isRedirected() || isPostRequest() ); addPrincipalToRequestLog(rle); if(!this.isAjaxRuntimeRequest()){ ThreadLocalServlet.get().setEndTimeAndStoreRequestLog(utils.HibernateUtil.getCurrentSession()); } ThreadLocalServlet.get().setCookie(hibernateSession); if(isReadOnly || !hasWrites){ // either page has read-only modifier, or no writes have been detected hibernateSession.getTransaction().rollback(); } else{ hibernateSession.flush(); validateEntities(); hibernateSession.getTransaction().commit(); invalidatePageCacheIfNeeded(); } if(exceptionInHibernateInterceptor != null){ throw exceptionInHibernateInterceptor; } response.sendContent(); } ThreadLocalOut.popChecked(out); } catch(utils.MultipleValidationExceptions mve){ String url = getRequestURL(); org.webdsl.logging.Logger.error("Validation exceptions occurred while handling request URL [ " + url + " ]. Transaction is rolled back."); for(utils.ValidationException vex : mve.getValidationExceptions()){ org.webdsl.logging.Logger.error( "Validation error: " + vex.getErrorMessage() , vex ); } hibernateSession.getTransaction().rollback(); setValidated(false); throw mve; } catch(utils.EntityNotFoundException enfe) { org.webdsl.logging.Logger.error( enfe.getMessage() + ". Transaction is rolled back." ); if(hibernateSession.isOpen()){ hibernateSession.getTransaction().rollback(); } throw enfe; } catch (Exception e) { String url = getRequestURL(); org.webdsl.logging.Logger.error("exception occurred while handling request URL [ " + url + " ]. Transaction is rolled back."); org.webdsl.logging.Logger.error("exception message: "+e.getMessage(), e); if(hibernateSession.isOpen()){ hibernateSession.getTransaction().rollback(); } throw e; } finally{ cleanupThreadLocals(); org.apache.log4j.MDC.remove("request"); org.apache.log4j.MDC.remove("template"); if(reqAppender != null) reqAppender.removeRequest(rle.getId().toString()); } } // LoadingCache is thread-safe public static boolean pageCacheEnabled = utils.BuildProperties.getNumCachedPages() > 0; public static Cache<String, CacheResult> cacheAnonymousPages = CacheBuilder.newBuilder() .maximumSize(utils.BuildProperties.getNumCachedPages()).build(); public boolean invalidateAllPageCache = false; protected boolean shouldTryCleanPageCaches = false; public String invalidateAllPageCacheMessage; public void invalidateAllPageCache(String entityname){ commandingPage.invalidateAllPageCacheInternal(entityname); } private void invalidateAllPageCacheInternal(String entityname){ invalidateAllPageCache = true; invalidateAllPageCacheMessage = entityname; } public void shouldTryCleanPageCaches(){ commandingPage.shouldTryCleanPageCachesInternal(); } private void shouldTryCleanPageCachesInternal(){ shouldTryCleanPageCaches = true; } public static Cache<String, CacheResult> cacheUserSpecificPages = CacheBuilder.newBuilder() .maximumSize(utils.BuildProperties.getNumCachedPages()).build(); public boolean invalidateUserSpecificPageCache = false; public String invalidateUserSpecificPageCacheMessage; public void invalidateUserSpecificPageCache(String entityname){ commandingPage.invalidateUserSpecificPageCacheInternal(entityname); } private void invalidateUserSpecificPageCacheInternal(String entityname){ invalidateUserSpecificPageCache = true; String propertySetterTrace = Warning.getStackTraceLineAtIndex(4); invalidateUserSpecificPageCacheMessage = entityname + " - " + propertySetterTrace; } public boolean pageCacheWasUsed = false; public void invalidatePageCacheIfNeeded(){ if(pageCacheEnabled && shouldTryCleanPageCaches){ if(invalidateAllPageCache){ Logger.info("All page caches invalidated, triggered by change in: "+invalidateAllPageCacheMessage); cacheAnonymousPages.invalidateAll(); cacheUserSpecificPages.invalidateAll(); } else if(invalidateUserSpecificPageCache){ Logger.info("user-specific page cache invalidated, triggered by change in: "+invalidateUserSpecificPageCacheMessage); cacheUserSpecificPages.invalidateAll(); } } } public void renderOrInitAction() throws IOException{ String key = getRequestURL(); String s = ""; Cache<String, CacheResult> cache = null; AbstractDispatchServletHelper servlet = ThreadLocalServlet.get(); if( // not using page cache if: this.isPageCacheDisabled // ?nocache added to URL || this.isPostRequest() // post parameters are not included in cache key || isNotValid() // data validation errors need to be rendered || !servlet.getIncomingSuccessMessages().isEmpty() // success messages need to be rendered ){ StringWriter renderedContent = renderPageOrTemplateContents(); if(!mimetypeChanged){ s = renderResponse(renderedContent); } else{ s = renderedContent.toString(); } } else{ // using page cache if( // use user-specific page cache if: servlet.sessionHasChanges() // not necessarily login, any session data changes can be included in a rendered page || webdsl.generated.functions.loggedIn_.loggedIn_() // user might have old session from before application start, this check is needed to avoid those logged in pages ending up in the anonymous page cache ){ key = key + servlet.getSessionManager().getId(); cache = cacheUserSpecificPages; } else{ cache = cacheAnonymousPages; } try{ pageCacheWasUsed = true; CacheResult result = cache.get(key, new Callable<CacheResult>(){ public CacheResult call(){ // System.out.println("key not found"); pageCacheWasUsed = false; StringWriter renderedContent = renderPageOrTemplateContents(); CacheResult result = new CacheResult(); if(!mimetypeChanged){ result.body = renderResponse(renderedContent); } else{ result.body = renderedContent.toString(); } result.mimetype = getMimetype(); return result; } }); s = result.body; setMimetype(result.mimetype); } catch(java.util.concurrent.ExecutionException e){ e.printStackTrace(); } } // redirect in init action can be triggered with GET request, the render call in the line above will execute such inits if( !isPostRequest() && isRedirected() ){ redirect(); if(cache != null){ cache.invalidate(key); } } else if( download != null ){ //File.download() executed in page/template init block download(); if(cache != null){ cache.invalidate(key); } // don't cache binary file response in this page response cache, can be cached on client with expires header } else{ response.setContentType(getMimetype()); PrintWriter sout = response.getWriter(); //reponse.getWriter() must be called after file download checks sout.write(s); } } public boolean renderDynamicFormWithOnlyDirtyData = false; public StringWriter renderPageOrTemplateContents(){ if(isTemplate() && !ThreadLocalServlet.get().isPostRequest){ throw new utils.AjaxWithGetRequestException(); } StringWriter s = new StringWriter(); PrintWriter out = new PrintWriter(s); if(getParammap().get("dynamicform") == null){ // regular pages and forms if(isNotValid()){ clearHibernateCache(); } ThreadLocalOut.push(out); templateservlet.render(null, args, new Environment(envGlobalAndSession), null); ThreadLocalOut.popChecked(out); } else{ // dynamicform uses submitted variable data to process form content // render form with newly entered data, rest with the current persisted data if(isNotValid() && !renderDynamicFormWithOnlyDirtyData){ StringWriter theform = new StringWriter(); PrintWriter pwform = new PrintWriter(theform); ThreadLocalOut.push(pwform); // render, when encountering submitted form save in abstractpage validationFormRerender = true; templateservlet.render(null, args, new Environment(envGlobalAndSession), null); ThreadLocalOut.popChecked(pwform); clearHibernateCache(); } ThreadLocalOut.push(out); // render, when isNotValid and encountering submitted form render old templateservlet.render(null, args, new Environment(envGlobalAndSession), null); ThreadLocalOut.popChecked(out); } return s; } public StringWriter renderPageOrTemplateContentsSingle(){ if(isTemplate() && !ThreadLocalServlet.get().isPostRequest){ throw new utils.AjaxWithGetRequestException(); } StringWriter s = new StringWriter(); PrintWriter out = new PrintWriter(s); ThreadLocalOut.push(out); templateservlet.render(null, args, new Environment(envGlobalAndSession), null); ThreadLocalOut.popChecked(out); return s; } private boolean validationFormRerender = false; public boolean isValidationFormRerender(){ return validationFormRerender; } public String submittedFormContent = null; public String submittedFormId = null; public String submittedSubmitId = null; // helper methods that enable a submit without enclosing form to be ajax-refreshed when validation error occurs protected StringWriter submitWrapSW; protected PrintWriter submitWrapOut; public void submitWrapOpenHelper(String submitId){ if( ! inSubmittedForm && validationFormRerender && request != null && getParammap().get(submitId) != null ){ submittedSubmitId = submitId; submitWrapSW = new java.io.StringWriter(); submitWrapOut = new java.io.PrintWriter(submitWrapSW); ThreadLocalOut.push(submitWrapOut); ThreadLocalOut.peek().print("<span submitid=" + submitId + ">"); } } public void submitWrapCloseHelper(){ if( ! inSubmittedForm && validationFormRerender && submitWrapSW != null ){ ThreadLocalOut.peek().print("</span>"); ThreadLocalOut.pop(); submittedFormContent = submitWrapSW.toString(); submitWrapSW = null; } } private static String common_css_link_tag_suffix; private static String fav_ico_link_tag_suffix; private static String ajax_js_include_name; public String renderResponse(StringWriter s) { StringWriter sw = new StringWriter(); PrintWriter sout = new PrintWriter(sw); ThreadLocalOut.push(sout); addJavascriptInclude( utils.IncludePaths.jQueryJS() ); addJavascriptInclude( ajax_js_include_name ); sout.println("<!DOCTYPE html>"); sout.println("<html>"); sout.println("<head>"); sout.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"); sout.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">"); sout.println("<title>"+getPageTitle().replaceAll("<[^>]*>","")+"</title>"); sout.println("<link href=\""+ThreadLocalPage.get().getAbsoluteLocation()+fav_ico_link_tag_suffix); sout.println("<link href=\""+ThreadLocalPage.get().getAbsoluteLocation()+common_css_link_tag_suffix); renderDebugJsVar(sout); sout.println("<script type=\"text/javascript\">var contextpath=\""+ThreadLocalPage.get().getAbsoluteLocation()+"\";</script>"); for(String sheet : this.stylesheets) { if(sheet.startsWith(" sout.print("<link rel=\"stylesheet\" href=\""+ sheet + "\" type=\"text/css\" />"); } else{ String hashedName = CachedResourceFileNameHelper.getNameWithHash("stylesheets", sheet); sout.print("<link rel=\"stylesheet\" href=\""+ThreadLocalPage.get().getAbsoluteLocation()+"/stylesheets/"+hashedName+"\" type=\"text/css\" />"); } } for(String script : this.javascripts) { if(script.startsWith(" sout.println("<script type=\"text/javascript\" src=\"" + script + "\"></script>"); } else{ String hashedName = CachedResourceFileNameHelper.getNameWithHash("javascript", script); sout.println("<script type=\"text/javascript\" src=\""+ThreadLocalPage.get().getAbsoluteLocation()+"/javascript/"+hashedName+"\"></script>"); } } for(Map.Entry<String,String> headEntry : customHeadNoDuplicates.entrySet()) { // sout.println("<!-- " + headEntry.getKey() + " -->"); sout.println(headEntry.getValue()); } for(String headEntry : customHeads) { sout.println(headEntry); } sout.println("</head>"); sout.print("<body id=\""+this.getPageName()+"\""); for(String attribute : this.bodyAttributes) { sout.print(attribute); } sout.print(">"); renderLogSqlMessage(); renderIncomingSuccessMessages(); s.flush(); sout.write(s.toString()); if(this.isLogSqlEnabled()){ if(logSqlCheckAccess()){ sout.print("<hr/><div class=\"logsql\">"); utils.HibernateLog.printHibernateLog(sout, this, null); sout.print("</div>"); } else{ sout.print("<hr/><div class=\"logsql\">Access to SQL logs was denied.</div>"); } } sout.print("</body>"); sout.println("</html>"); ThreadLocalOut.popChecked(sout); return sw.toString(); } //ajax/js runtime request related protected abstract void initializeBasics(AbstractPageServlet ps, Object[] args); public boolean isServingAsAjaxResponse = false; public void serveAsAjaxResponse(Object[] args, TemplateCall templateArg, String placeholderId) { AbstractPageServlet ps = ThreadLocalPage.get(); TemplateServlet ts = ThreadLocalTemplate.get(); //inherit commandingPage commandingPage = ps.commandingPage; //use passed PageServlet ps here, since this is the context for this type of response initializeBasics(ps, args); ThreadLocalPage.set(this); //outputstream threadlocal is already set, see to-java-servlet/ajax/ajax.str this.isServingAsAjaxResponse = true; this.placeholderId = placeholderId; enterPlaceholderIdContext(); templateservlet.render(null, args, Environment.createNewLocalEnvironment(envGlobalAndSession), null); // new clean environment with only the global templates, and global/session vars ThreadLocalTemplate.set(ts); ThreadLocalPage.set(ps); } protected boolean isTemplate() { return false; } public static AbstractPageServlet getRequestedPage(){ return ThreadLocalPage.get(); } private boolean passedThroughAjaxTemplate = false; public boolean passedThroughAjaxTemplate(){ return passedThroughAjaxTemplate; } public void setPassedThroughAjaxTemplate(boolean b){ passedThroughAjaxTemplate = b; } protected boolean isLogSqlEnabled = false; public boolean isLogSqlEnabled() { return isLogSqlEnabled; } public boolean isPageCacheDisabled = false; protected boolean isOptimizationEnabled = true; public boolean isOptimizationEnabled() { return isOptimizationEnabled; } public String getExtraQueryArguments(String firstChar) { // firstChar is expected to be ? or &, depending on whether there are more query arguments HttpServletRequest req = getRequest(); return (req != null) ? (firstChar + req.getQueryString()) : ""; } public abstract String getPageName(); public abstract String getUniqueName(); protected MessageDigest messageDigest = null; public MessageDigest getMessageDigest(){ if(messageDigest == null){ try{ messageDigest = MessageDigest.getInstance("MD5"); } catch(NoSuchAlgorithmException ae) { org.webdsl.logging.Logger.error("MD5 not available: "+ae.getMessage()); return null; } } return messageDigest; } public boolean actionToBeExecutedHasDisabledValidation = false; public boolean actionHasAjaxPageUpdates = false; //TODO merge getActionTarget and getPageUrlWithParams public String getActionTarget() { if (isServingAsAjaxResponse){ return this.getUniqueName(); } return getPageName(); } //TODO merge getActionTarget and getPageUrlWithParams public String getPageUrlWithParams(){ //used for action field in forms if(isServingAsAjaxResponse){ return ThreadLocalPage.get().getAbsoluteLocation()+"/"+ThreadLocalPage.get().getActionTarget(); } else{ //this doesn't work with ajax template render from action, since an ajax template needs to submit to a different page than the original request return getRequestURL(); } } protected abstract void renderIncomingSuccessMessages(); protected abstract void renderLogSqlMessage(); public boolean isPostRequest(){ return ThreadLocalServlet.get().isPostRequest; } public boolean isNotPostRequest(){ return !ThreadLocalServlet.get().isPostRequest; } public boolean isAjaxTemplateRequest(){ return ThreadLocalServlet.get().getPages().get(ThreadLocalServlet.get().getRequestedPage()).isAjaxTemplate(); } public abstract String getHiddenParams(); public abstract String getUrlQueryParams(); public abstract String getHiddenPostParamsJson(); //public javax.servlet.http.HttpSession session; public static void cleanupThreadLocals(){ ThreadLocalEmailContext.set(null); ThreadLocalPage.set(null); ThreadLocalTemplate.setNull(); } //templates scope public static Environment staticEnv = Environment.createSharedEnvironment(); public Environment envGlobalAndSession = Environment.createLocalEnvironment(); //emails protected static Map<String, Class<?>> emails = new HashMap<String, Class<?>>(); public static Map<String, Class<?>> getEmails() { return emails; } public boolean sendEmail(String name, Object[] emailargs, Environment emailenv){ EmailServlet temp = renderEmail(name,emailargs,emailenv); return temp.send(); } public EmailServlet renderEmail(String name, Object[] emailargs, Environment emailenv){ EmailServlet temp = null; try { temp = ((EmailServlet)getEmails().get(name).newInstance()); } catch(IllegalAccessException iae) { org.webdsl.logging.Logger.error("Problem in email template lookup: " + iae.getMessage()); } catch(InstantiationException ie) { org.webdsl.logging.Logger.error("Problem in email template lookup: " + ie.getMessage()); } temp.render(emailargs, emailenv); return temp; } //rendertemplate function public String renderTemplate(String name, Object[] args, Environment env){ return executeTemplatePhase(RENDER_PHASE, name, args, env); } //validatetemplate function public String validateTemplate(String name, Object[] args, Environment env){ return executeTemplatePhase(VALIDATE_PHASE, name, args, env); } public static final int DATABIND_PHASE = 1; public static final int VALIDATE_PHASE = 2; public static final int ACTION_PHASE = 3; public static final int RENDER_PHASE = 4; public String executeTemplatePhase(int phase, String name, Object[] args, Environment env){ StringWriter s = new StringWriter(); PrintWriter out = new PrintWriter(s); ThreadLocalOut.push(out); TemplateServlet enclosingTemplateObject = ThreadLocalTemplate.get(); try{ TemplateServlet temp = ((TemplateServlet)env.getTemplate(name).newInstance()); switch(phase){ case VALIDATE_PHASE: temp.validateInputs(name, args, env, null); break; case RENDER_PHASE: temp.render(name, args, env, null); break; } } catch(Exception oe){ try { TemplateCall tcall = env.getWithcall(name); //'elements' or requires arg TemplateServlet temp = ((TemplateServlet)env.getTemplate(tcall.name).newInstance()); String parent = env.getWithcall(name)==null?null:env.getWithcall(name).parentName; switch(phase){ case VALIDATE_PHASE: temp.validateInputs(parent, tcall.args, env, null); break; case RENDER_PHASE: temp.render(parent, tcall.args, env, null); break; } } catch(Exception ie){ org.webdsl.logging.Logger.error("EXCEPTION",oe); org.webdsl.logging.Logger.error("EXCEPTION",ie); } } ThreadLocalTemplate.set(enclosingTemplateObject); ThreadLocalOut.popChecked(out); return s.toString(); } //ref arg protected static Map<String, Class<?>> refargclasses = new HashMap<String, Class<?>>(); public static Map<String, Class<?>> getRefArgClasses() { return refargclasses; } public abstract String getAbsoluteLocation(); public String getXForwardedProto() { if (request == null) { return null; } else { return request.getHeader("x-forwarded-proto"); } } protected TemplateContext templateContext = new TemplateContext(); public String getTemplateContextString() { return templateContext.getTemplateContextString(); } public void enterPlaceholderIdContext() { if( ! "1".equals( placeholderId ) ){ templateContext.enterTemplateContext( placeholderId ); } } public void enterTemplateContext(String s) { templateContext.enterTemplateContext(s); } public void leaveTemplateContext() { templateContext.leaveTemplateContext(); } public void leaveTemplateContextChecked(String s) { templateContext.leaveTemplateContextChecked(s); } public void clearTemplateContext(){ templateContext.clearTemplateContext(); enterPlaceholderIdContext(); } public void setTemplateContext(TemplateContext tc){ templateContext = tc; } public TemplateContext getTemplateContext(){ return templateContext; } // objects scheduled to be checked after action completes, filled by hibernate event listener in hibernate util class ArrayList<WebDSLEntity> entitiesToBeValidated = new ArrayList<WebDSLEntity>(); boolean allowAddingEntitiesForValidation = true; public void clearEntitiesToBeValidated(){ entitiesToBeValidated = new ArrayList<WebDSLEntity>(); allowAddingEntitiesForValidation = true; } public void addEntityToBeValidated(WebDSLEntity w){ if(allowAddingEntitiesForValidation){ entitiesToBeValidated.add(w); } } public void validateEntities(){ allowAddingEntitiesForValidation = false; //adding entities must be disabled when checking is performed, new entities may be loaded for checks, but do not have to be checked themselves java.util.Set<WebDSLEntity> set = new java.util.HashSet<WebDSLEntity>(entitiesToBeValidated); java.util.List<utils.ValidationException> exceptions = new java.util.LinkedList<utils.ValidationException>(); for(WebDSLEntity w : set){ if(w.isChanged()){ try { // System.out.println("validating: "+ w.get_WebDslEntityType() + ":" + w.getName()); w.validateSave(); //System.out.println("done validating"); } catch(utils.ValidationException ve){ exceptions.add(ve); } catch(utils.MultipleValidationExceptions ve) { for(utils.ValidationException vex : ve.getValidationExceptions()){ exceptions.add(vex); } } } } if(exceptions.size() > 0){ throw new utils.MultipleValidationExceptions(exceptions); } clearEntitiesToBeValidated(); } protected List<utils.ValidationException> validationExceptions = new java.util.LinkedList<utils.ValidationException>(); public List<utils.ValidationException> getValidationExceptions() { return validationExceptions; } public void addValidationException(String name, String message){ validationExceptions.add(new ValidationException(name,message)); } public List<utils.ValidationException> getValidationExceptionsByName(String name) { List<utils.ValidationException> list = new java.util.LinkedList<utils.ValidationException>(); for(utils.ValidationException v : validationExceptions){ if(v.getName().equals(name)){ list.add(v); } } return list; } public List<String> getValidationErrorsByName(String name) { List<String> list = new java.util.ArrayList<String>(); for(utils.ValidationException v : validationExceptions){ if(v.getName().equals(name)){ list.add(v.getErrorMessage()); } } return list; } public boolean hasExecutedAction = false; public boolean hasExecutedAction(){ return hasExecutedAction; } public boolean hasNotExecutedAction(){ return !hasExecutedAction; } protected boolean abortTransaction = false; public boolean isTransactionAborted(){ return abortTransaction; } public void abortTransaction(){ abortTransaction = true; } public java.util.List<String> ignoreset= new java.util.ArrayList<String>(); public boolean hibernateCacheCleared = false; protected java.util.List<String> javascripts = new java.util.ArrayList<String>(); protected java.util.List<String> stylesheets = new java.util.ArrayList<String>(); protected java.util.List<String> customHeads = new java.util.ArrayList<String>(); protected java.util.List<String> bodyAttributes = new java.util.ArrayList<String>(); protected java.util.Map<String,String> customHeadNoDuplicates = new java.util.HashMap<String,String>(); public void addJavascriptInclude(String filename) { commandingPage.addJavascriptIncludeInternal( filename ); } public void addJavascriptIncludeInternal(String filename) { if(!javascripts.contains(filename)) javascripts.add(filename); } public void addStylesheetInclude(String filename) { commandingPage.addStylesheetIncludeInternal( filename ); } public void addStylesheetIncludeInternal(String filename) { if(!stylesheets.contains(filename)){ stylesheets.add(filename); } } public void addStylesheetInclude(String filename, String media) { commandingPage.addStylesheetIncludeInternal( filename, media ); } public void addStylesheetIncludeInternal(String filename, String media) { String combined = media != null && !media.isEmpty() ? filename + "\" media=\""+ media : filename; if(!stylesheets.contains(combined)){ stylesheets.add(combined); } } public void addCustomHead(String header) { commandingPage.addCustomHeadInternal(header, header); } public void addCustomHead(String key, String header) { commandingPage.addCustomHeadInternal(key, header); } public void addCustomHeadInternal(String key, String header) { customHeadNoDuplicates.put(key, header); } public void addBodyAttribute(String key, String value) { commandingPage.addBodyAttributeInternal(key, value); } public void addBodyAttributeInternal(String key, String value) { bodyAttributes.add(" "+key+"=\""+value+"\""); } protected abstract void initialize(); protected abstract void conversion(); protected abstract void loadArguments(); public abstract void initVarsAndArgs(); public void clearHibernateCache() { // used to be only ' hibSession.clear(); ' but that doesn't revert already flushed changes. // since flushing now happens automatically when querying, this could produce wrong results. // e.g. output in page with validation errors shows changes that were not persisted to the db. // see regression test in test/succeed-web/validate-false-and-flush.app utils.HibernateUtil.getCurrentSession().getTransaction().rollback(); openNewTransactionThroughGetCurrentSession(); ThreadLocalServlet.get().reloadSessionManager(hibernateSession); initVarsAndArgs(); hibernateCacheCleared = true; } protected org.hibernate.Session openNewTransactionThroughGetCurrentSession(){ hibernateSession = utils.HibernateUtil.getCurrentSession(); hibernateSession.beginTransaction(); return hibernateSession; } protected HttpServletRequest request; protected ResponseWrapper response; protected HttpServletResponse httpServletResponse; protected Object[] args; // public void setHibSession(Session s) { // hibSession = s; // public Session getHibSession() { // return hibSession; public HttpServletRequest getRequest() { return request; } private String requestURLCached = null; private String requestURICached = null; public String getRequestURL(){ if(requestURLCached == null) { requestURLCached = AbstractDispatchServletHelper.get().getRequestURL(); } return requestURLCached; } public String getRequestURI(){ if(requestURICached == null) { requestURICached = AbstractDispatchServletHelper.get().getRequestURI(); } return requestURICached; } public ResponseWrapper getResponse() { return response; } protected boolean validated=true; /* * when this is true, it can mean: * 1 no validation has been performed yet * 2 some validation has been performed without errors * 3 all validation has been performed without errors */ public boolean isValid() { return validated; } public boolean isNotValid() { return !validated; } public void setValidated(boolean validated) { this.validated = validated; } /* * complete action regularly but rollback hibernate session * skips validation of entities at end of action, if validation messages are necessary * use cancel() instead of rollback() * can be used to replace templates with ajax without saving, e.g. for validation */ protected boolean rollback = false; public boolean isRollback() { return rollback; } public void setRollback() { //by setting validated true, the action will succeed this.setValidated(true); //the session will be rolled back, to cancel persisting any changes this.rollback = true; } public List<String> failedCaptchaResponses = new ArrayList<String>(); protected boolean inSubmittedForm = false; public boolean inSubmittedForm() { return inSubmittedForm; } public void setInSubmittedForm(boolean b) { this.inSubmittedForm = b; } // used for runtime check to detect nested forms protected String inForm = null; public boolean isInForm() { return inForm != null; } public void enterForm(String t) { inForm = t; } public String getEnclosingForm() { return inForm; } public void leaveForm() { inForm = null; } public void clearParammaps(){ parammap.clear(); parammapvalues.clear(); fileUploads.clear(); } protected java.util.Map<String, String> parammap; public java.util.Map<String, String> getParammap() { return parammap; } protected Map<String,List<utils.File>> fileUploads; public Map<String, List<utils.File>> getFileUploads() { return fileUploads; } public List<utils.File> getFileUploads(String key) { return fileUploads.get(key); } protected Map<String, List<String>> parammapvalues; public Map<String, List<String>> getParammapvalues() { return parammapvalues; } protected String pageTitle = ""; public String getPageTitle() { return pageTitle; } public void setPageTitle(String pageTitle) { this.pageTitle = pageTitle; } protected String formIdent = ""; public String getFormIdent() { return formIdent; } public void setFormIdent(String fi) { this.formIdent = fi; } protected boolean actionLinkUsed = false; public boolean isActionLinkUsed() { return actionLinkUsed; } public void setActionLinkUsed(boolean a) { this.actionLinkUsed = a; } protected boolean ajaxRuntimeRequest = false; public boolean isAjaxRuntimeRequest() { return ajaxRuntimeRequest; } public void setAjaxRuntimeRequest(boolean a) { ajaxRuntimeRequest = a; } protected String redirectUrl = ""; public boolean isRedirected(){ return !"".equals(redirectUrl); } public String getRedirectUrl() { return redirectUrl; } public void setRedirectUrl(String a) { this.redirectUrl = a; } // perform the actual redirect public void redirect(){ try { response.sendRedirect(this.getRedirectUrl()); } catch (IOException ioe) { org.webdsl.logging.Logger.error("redirect failed", ioe); } } protected String mimetype = "text/html; charset=UTF-8"; protected boolean mimetypeChanged = false; public String getMimetype() { return mimetype; } public void setMimetype(String mimetype) { this.mimetype = mimetype; mimetypeChanged = true; if(!isMarkupLangMimeType.matcher(mimetype).find()){ enableRawoutput(); } disableTemplateSpans(); } protected boolean downloadInline = false; public boolean getDownloadInline() { return downloadInline; } public void enableDownloadInline() { this.downloadInline = true; } protected boolean ajaxActionExecuted = false; public boolean isAjaxActionExecuted() { return ajaxActionExecuted; } public void enableAjaxActionExecuted() { ajaxActionExecuted = true; } protected boolean rawoutput = false; public boolean isRawoutput() { return rawoutput; } public void enableRawoutput() { rawoutput = true; } public void disableRawoutput() { rawoutput = false; } protected String[] pageArguments = null; public void setPageArguments(String[] pa) { pageArguments = pa; } public String[] getPageArguments() { return pageArguments; } protected String httpMethod = null; public void setHttpMethod(String httpMethod) { this.httpMethod = httpMethod; } public String getHttpMethod() { return httpMethod; } protected boolean templateSpans = true; public boolean templateSpans() { return templateSpans; } public void disableTemplateSpans() { templateSpans = false; } protected List<String> reRenderPlaceholders = null; protected Map<String,String> reRenderPlaceholdersContent = null; public boolean isReRenderPlaceholders() { return reRenderPlaceholders != null; } public void addReRenderPlaceholders(String placeholder) { if(reRenderPlaceholders == null){ reRenderPlaceholders = new ArrayList<String>(); reRenderPlaceholdersContent = new HashMap<String,String>(); } reRenderPlaceholders.add(placeholder); } public void addReRenderPlaceholdersContent(String placeholder, String content) { if(reRenderPlaceholders != null && reRenderPlaceholders.contains(placeholder)){ reRenderPlaceholdersContent.put(placeholder,content); } } protected utils.File download = null; public void setDownload(utils.File file){ this.download = file; } public boolean isDownloadSet(){ return this.download != null; } protected void download() { /* Long id = download.getId(); org.hibernate.Session hibSession = HibernateUtilConfigured.getSessionFactory().openSession(); hibSession.beginTransaction(); hibSession.setFlushMode(org.hibernate.FlushMode.MANUAL); utils.File download = (utils.File)hibSession.load(utils.File.class,id); */ try { javax.servlet.ServletOutputStream outstream; outstream = response.getOutputStream(); java.sql.Blob blob = download.getContent(); java.io.InputStream in; in = blob.getBinaryStream(); response.setContentType(download.getContentType()); if(!downloadInline) { response.setHeader("Content-Disposition", "attachment; filename=\"" + download.getFileNameForDownload() + "\""); } java.io.BufferedOutputStream bufout = new java.io.BufferedOutputStream(outstream); byte bytes[] = new byte[32768]; int index = in.read(bytes, 0, 32768); while(index != -1) { bufout.write(bytes, 0, index); index = in.read(bytes, 0, 32768); } bufout.flush(); } catch(java.sql.SQLException ex) { org.webdsl.logging.Logger.error("exception in download serve"); org.webdsl.logging.Logger.error("EXCEPTION",ex); } catch (IOException ex) { org.webdsl.logging.Logger.error("exception in download serve"); org.webdsl.logging.Logger.error("EXCEPTION",ex); } /* hibSession.flush(); hibSession.getTransaction().commit(); */ } //data validation public java.util.LinkedList<String> validationContext = new java.util.LinkedList<String>(); public String getValidationContext() { //System.out.println("using" + validationContext.peek()); return validationContext.peek(); } public void enterValidationContext(String ident) { validationContext.add(ident); //System.out.println("entering" + ident); } public void leaveValidationContext() { /*String s = */ validationContext.removeLast(); //System.out.println("leaving" +s); } public boolean inValidationContext() { return validationContext.size() != 0; } //form public boolean formRequiresMultipartEnc = false; //formGroup public String formGroupLeftSize = "150"; //public java.util.Stack<utils.FormGroupContext> formGroupContexts = new java.util.Stack<utils.FormGroupContext>(); public utils.FormGroupContext getFormGroupContext() { return (utils.FormGroupContext) tableContexts.peek(); } public void enterFormGroupContext() { tableContexts.push(new utils.FormGroupContext()); } public void leaveFormGroupContext() { tableContexts.pop(); } public boolean inFormGroupContext() { return !tableContexts.empty() && tableContexts.peek() instanceof utils.FormGroupContext; } public java.util.Stack<String> formGroupContextClosingTags = new java.util.Stack<String>(); public void formGroupContextsCheckEnter(PrintWriter out) { if(inFormGroupContext()){ utils.FormGroupContext temp = getFormGroupContext(); if(!temp.isInDoubleColumnContext()){ // ignore defaults when in scope of a double column if(!temp.isInColumnContext()){ //don't nest left and right temp.enterColumnContext(); if(temp.isInLeftContext()) { out.print("<div style=\"clear:left; float:left; width: " + formGroupLeftSize + "px\">"); formGroupContextClosingTags.push("left"); temp.toRightContext(); } else { out.print("<div style=\"float: left;\">"); formGroupContextClosingTags.push("right"); temp.toLeftContext(); } } else{ formGroupContextClosingTags.push("none"); } } } } public void formGroupContextsCheckLeave(PrintWriter out) { if(inFormGroupContext()){ utils.FormGroupContext temp = getFormGroupContext(); if(!temp.isInDoubleColumnContext()) { String tags = formGroupContextClosingTags.pop(); if(tags.equals("left")){ //temp.toRightContext(); temp.leaveColumnContext(); out.print("</div>"); } else if(tags.equals("right")){ //temp.toLeftContext(); temp.leaveColumnContext(); out.print("</div>"); } } } } public void formGroupContextsDisplayLeftEnter(PrintWriter out) { if(inFormGroupContext()){ utils.FormGroupContext temp = getFormGroupContext(); if(!temp.isInColumnContext()){ temp.enterColumnContext(); out.print("<div style=\"clear:left; float:left; width: " + formGroupLeftSize + "px\">"); formGroupContextClosingTags.push("left"); temp.toRightContext(); } else{ formGroupContextClosingTags.push("none"); } } } public void formGroupContextsDisplayRightEnter(PrintWriter out) { if(inFormGroupContext()){ utils.FormGroupContext temp = getFormGroupContext(); if(!temp.isInColumnContext()){ temp.enterColumnContext(); out.print("<div style=\"float: left;\">"); formGroupContextClosingTags.push("right"); temp.toLeftContext(); } else{ formGroupContextClosingTags.push("none"); } } } //label public String getLabelString() { return getLabelStringForTemplateContext(ThreadLocalTemplate.get().getUniqueId()); } public java.util.Stack<String> labelStrings = new java.util.Stack<String>(); public java.util.Set<String> usedPageElementIds = new java.util.HashSet<String>(); public static java.util.Random rand = new java.util.Random(); //avoid duplicate ids; if multiple inputs are in a label, only the first is connected to the label public String getLabelStringOnce() { String s = labelStrings.peek(); if(usedPageElementIds.contains(s)){ do{ s += rand.nextInt(); } while(usedPageElementIds.contains(s)); } usedPageElementIds.add(s); return s; } public java.util.Map<String,String> usedPageElementIdsTemplateContext = new java.util.HashMap<String,String>(); //subsequent calls from the same defined template (e.g. in different phases) should produce the same id public String getLabelStringForTemplateContext(String context) { String labelid = usedPageElementIdsTemplateContext.get(context); if(labelid == null){ labelid = getLabelStringOnce(); usedPageElementIdsTemplateContext.put(context, labelid); } return labelid; } public void enterLabelContext(String ident) { labelStrings.push(ident); } public void leaveLabelContext() { labelStrings.pop(); } public boolean inLabelContext() { return !labelStrings.empty(); } //section public int sectionDepth = 0; public int getSectionDepth() { return sectionDepth; } public void enterSectionContext() { sectionDepth++; } public void leaveSectionContext() { sectionDepth } public boolean inSectionContext() { return sectionDepth > 0; } //table public java.util.Stack<Object> tableContexts = new java.util.Stack<Object>(); public utils.TableContext getTableContext() { return (utils.TableContext) tableContexts.peek(); } public void enterTableContext() { tableContexts.push(new utils.TableContext()); } public void leaveTableContext() { tableContexts.pop(); } public boolean inTableContext() { return !tableContexts.empty() && tableContexts.peek() instanceof utils.TableContext; } public java.util.Stack<String> tableContextClosingTags = new java.util.Stack<String>(); //separate row and column checks, used by label public void rowContextsCheckEnter(PrintWriter out) { if(inTableContext()){ utils.TableContext x_temp = getTableContext(); if(!x_temp.isInRowContext()) { out.print("<tr>"); x_temp.enterRowContext(); tableContextClosingTags.push("</tr>"); } else{ tableContextClosingTags.push(""); } } } public void rowContextsCheckLeave(PrintWriter out) { if(inTableContext()){ utils.TableContext x_temp = getTableContext(); String tags = tableContextClosingTags.pop(); if(tags.equals("</tr>")){ x_temp.leaveRowContext(); out.print(tags); } } } public void columnContextsCheckEnter(PrintWriter out) { if(inTableContext()){ utils.TableContext x_temp = getTableContext(); if(x_temp.isInRowContext() && !x_temp.isInColumnContext()) { out.print("<td>"); x_temp.enterColumnContext(); tableContextClosingTags.push("</td>"); } else{ tableContextClosingTags.push(""); } } } public void columnContextsCheckLeave(PrintWriter out) { if(inTableContext()){ utils.TableContext x_temp = getTableContext(); String tags = tableContextClosingTags.pop(); if(tags.equals("</td>")){ x_temp.leaveColumnContext(); out.print(tags); } } } //session manager public void reloadSessionManagerFromExistingSessionId(UUID sessionId){ ThreadLocalServlet.get().reloadSessionManagerFromExistingSessionId(hibernateSession, sessionId); initialize(); //reload session variables } //request vars public HashMap<String, Object> requestScopedVariables = new HashMap<String, Object>(); public void initRequestVars(){ initRequestVars(null); } public abstract void initRequestVars(PrintWriter out); protected long startTime = 0L; public long getStartTime() { return startTime; } public long getElapsedTime() { return System.currentTimeMillis() - startTime; } public Object getRequestScopedVar(String key){ return commandingPage.requestScopedVariables.get(key); } public void addRequestScopedVar(String key, Object val){ if(val != null){ commandingPage.requestScopedVariables.put(key, val); } } public void addRequestScopedVar(String key, WebDSLEntity val){ if(val != null){ val.setRequestVar(); commandingPage.requestScopedVariables.put(key, val); } } // statistics to be shown in log protected abstract void increaseStatReadOnly(); protected abstract void increaseStatReadOnlyFromCache(); protected abstract void increaseStatUpdate(); protected abstract void increaseStatActionFail(); protected abstract void increaseStatActionReadOnly(); protected abstract void increaseStatActionUpdate(); // register whether entity changes were made, see isChanged property of entities protected boolean hasWrites = false; public void setHasWrites(boolean b){ commandingPage.hasWrites = b; } protected void updatePageRequestStatistics(){ if(hasNotExecutedAction()){ if(!hasWrites || isRollback()){ if(pageCacheWasUsed){ increaseStatReadOnlyFromCache(); } else{ increaseStatReadOnly(); } } else{ increaseStatUpdate(); } } else{ if(isNotValid()){ increaseStatActionFail(); } else{ if(!hasWrites || isRollback()){ increaseStatActionReadOnly(); } else{ increaseStatActionUpdate(); } } } } // Hibernate interceptor hooks (such as beforeTransactionCompletion) catch Throwable but then only log the error, e.g. when db transaction conflict occurs // this causes the problem that a page might be rendered with data that was not actually committed // workaround: store the exception in this variable and explicitly rethrow before sending page content to output stream public Exception exceptionInHibernateInterceptor = null; public static Environment loadTemplateMap(Class<?> clazz) { return loadTemplateMap(clazz, null, staticEnv); } public static Environment loadTemplateMap(Class<?> clazz, String keyOverwrite, Environment env) { reflectionLoadClassesHelper(clazz, "loadTemplateMap", new Object[] { keyOverwrite, env }); return env; } public static Object[] loadEmailAndTemplateMapArgs = new Object[] { staticEnv, emails }; public static void loadEmailAndTemplateMap(Class<?> clazz) { reflectionLoadClassesHelper(clazz, "loadEmailAndTemplateMap", loadEmailAndTemplateMapArgs); } public static Object[] loadLiftedTemplateMapArgs = new Object[] { staticEnv }; public static void loadLiftedTemplateMap(Class<?> clazz) { reflectionLoadClassesHelper(clazz, "loadLiftedTemplateMap", loadLiftedTemplateMapArgs); } public static Object[] loadRefArgClassesArgs = new Object[] { refargclasses }; public static void loadRefArgClasses(Class<?> clazz) { reflectionLoadClassesHelper(clazz, "loadRefArgClasses", loadRefArgClassesArgs); } public static void reflectionLoadClassesHelper(Class<?> clazz, String method, Object[] args) { for (java.lang.reflect.Method m : clazz.getMethods()) { if (method.equals(m.getName())) { // will just skip if not defined, so the code generator does not need to generate empty methods try { m.invoke(null, args); } catch (IllegalAccessException | IllegalArgumentException | java.lang.reflect.InvocationTargetException e) { e.printStackTrace(); } break; } } } }
package edu.berkeley.bid.comm; import java.util.List; import java.util.LinkedList; import edu.berkeley.bid.UTILS; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class AllReduce { public class Machine { /* Machine Configuration Variables */ int N; // Number of features int D; // Depth of the network int M; // Number of Machines int imachine; // My identity int [] allks; // k values Layer [] layers; // All the layers int [][] sendbuf; // buffers, one for each destination in a group int [][] recbuf; IVec finalMap; // Map to down from down --> up at layer D-1 LinkedList<Msg> [][] messages; // Message queue for the simulation boolean doSim = true; ExecutorService executor; boolean trace = true; public Machine(int N0, int [] allks0, int imachine0, int M0, int bufsize, boolean doSim0) { N = N0; M = M0; imachine = imachine0; allks = allks0; D = allks.length; doSim = doSim0; layers = new Layer[D]; int left = 0; int right = N; int cumk = 1; int maxk = 1; for (int i = 0; i < D; i++) { int k = allks[i]; layers[i] = new Layer(k, cumk, left, right, imachine, i); int pimg = layers[i].posInMyGroup; left = layers[i].left; if (pimg > 0) left = layers[i].partBoundaries.data[pimg-1]; right = layers[i].partBoundaries.data[pimg]; cumk *= k; maxk = Math.max(maxk, k); } executor = Executors.newFixedThreadPool(2*maxk); sendbuf = new int[maxk][]; recbuf = new int[maxk][]; for (int i = 0; i < maxk; i++) { sendbuf[i] = new int[bufsize]; recbuf[i] = new int[bufsize]; } if (doSim) { messages = new LinkedList[M][]; for (int i = 0; i < M; i++) { messages[i] = new LinkedList[3*D]; for (int j = 0; j < 3*D; j++) { messages[i][j] = new LinkedList<Msg>(); } } } } public void config(IVec downi, IVec upi) { IVec [] outputs = new IVec[2]; for (int i = 0; i < D; i++) { layers[i].config(downi, upi, outputs); downi = outputs[0]; upi = outputs[1]; } finalMap = IVec.mapInds(upi, downi); } public Vec reduce(Vec downv) { for (int d = 0; d < D; d++) { downv = layers[d].reduceDown(downv); } Vec upv = downv.mapFrom(finalMap); for (int d = D-1; d >= 0; d upv = layers[d].reduceUp(upv); } return upv; } class Layer { /* Layer Configuration Variables */ int k; // Size of this group int left; // Left boundary of its indices int right; // Right boundary of its indices int depth; int posInMyGroup; // Position in this machines group int [] outNbr; // Machines we talk to int [] inNbr; // Machines we listen to IVec partBoundaries; // Partition boundaries IVec [] downMaps; // Maps to indices below for down indices IVec [] upMaps; // Maps to indices below for up indices int downn; // Size of the down master list int upn; // Size of the up vector int [] dPartInds; int [] uPartInds; public Layer(int k0, int cumk, int left0, int right0, int imachine, int depth0) { k = k0; int i; left = left0; right = right0; depth = depth0; partBoundaries = new IVec(k); inNbr = new int [k]; outNbr = new int [k]; dPartInds = new int[k+1]; uPartInds = new int[k+1]; int ckk = cumk * k; int ioff = imachine % cumk; int ibase = (imachine/ckk)*ckk; posInMyGroup = (imachine - ibase) / cumk; for (i = 0; i < k; i++) { partBoundaries.data[i] = left + (int)(((long)(right - left)) * (i+1) / k); outNbr[i] = ibase + (ioff + i * cumk); inNbr[i] = outNbr[i]; // inNbr[i] = ibase + (ioff + (k - i) * cumk) % (cumk * k); } downMaps = new IVec[k]; upMaps = new IVec[k]; } class ConfigThread implements Runnable { IVec [] downp; IVec [] upp; IVec [] newdownp; IVec [] newupp; IVec [] dtree; IVec [] utree; int i; CountDownLatch latch; public ConfigThread(IVec [] downp0, IVec [] upp0, IVec [] newdownp0, IVec [] newupp0, IVec [] dtree0, IVec [] utree0, int i0, CountDownLatch latch0) { downp = downp0; upp = upp0; newdownp = newdownp0; newupp = newupp0; dtree = dtree0; utree = utree0; i = i0; latch = latch0; } public void run() { int [] segments = new int[2]; int [] sbuf = sendbuf[i]; int [] rbuf = recbuf[i]; System.arraycopy(downp[i].data, 0, sbuf, 2, downp[i].size()); segments[0] = downp[i].size(); System.arraycopy(upp[i].data, 0, sbuf, segments[0]+2, upp[i].size()); segments[1] = segments[0] + upp[i].size(); sbuf[0] = segments[0]; sbuf[1] = segments[1]; if (trace) System.out.format("config layer %d machine %d sent msg to %d, from %d, sizes %d %d\n", depth, imachine, outNbr[i], inNbr[i], sbuf[0], sbuf[1]); sendrecv(sbuf, segments[1]+2, outNbr[i], rbuf, rbuf.length, inNbr[i], depth*3); if (trace) System.out.format("config layer %d machine %d got msg from %d, sizes %d %d\n", depth, imachine, inNbr[i], rbuf[0], rbuf[1]); IVec downout = new IVec(rbuf[0]); IVec upout = new IVec(rbuf[1]-rbuf[0]); System.arraycopy(rbuf, 2, downout.data, 0, rbuf[0]); System.arraycopy(rbuf, 2 + rbuf[0], upout.data, 0, rbuf[1]-rbuf[0]); IVec.checkTree(dtree, downout, i, k); IVec.checkTree(utree, upout, i, k); newdownp[i] = downout; newupp[i] = upout; latch.countDown(); } } public void config(IVec downi, IVec upi, IVec [] outputs) { IVec [] downp = IVec.partition(downi, partBoundaries); IVec [] upp = IVec.partition(upi, partBoundaries); IVec [] newdownp = new IVec[downp.length]; IVec [] newupp = new IVec[upp.length]; IVec [] dtree = new IVec[2*k-1]; IVec [] utree = new IVec[2*k-1]; // System.out.format("machine %d layer %d, dparts %d %d\n", imachine, depth, downp[0].size(), downp[1].size()); if (trace) System.out.format("machine %d layer %d, uparts %d %d %d, bounds %d %d\n", imachine, depth, upp[0].size(), upp[1].size(), upi.size(), partBoundaries.data[0], partBoundaries.data[partBoundaries.size()-1]); dPartInds[0] = 0; uPartInds[0] = 0; CountDownLatch latch = new CountDownLatch(k); for (int i = 0; i < k; i++) { dPartInds[i+1] = dPartInds[i] + downp[i].size(); uPartInds[i+1] = uPartInds[i] + upp[i].size(); executor.execute(new ConfigThread(downp, upp, newdownp, newupp, dtree, utree, i, latch)); } try { latch.await(); } catch (InterruptedException e) {} IVec dmaster = dtree[0]; downn = dmaster.size(); IVec umaster = utree[0]; upn = upi.size(); for (int i = 0; i < k; i++) { downMaps[i] = IVec.mapInds(newdownp[i], dmaster); upMaps[i] = IVec.mapInds(newupp[i], umaster); // System.out.format("machine %d dmap(%d) size %d\n", imachine, i, downMaps[i].size()); if (trace) System.out.format("machine %d umap(%d) size %d\n", imachine, i, upMaps[i].size()); } outputs[0] = dmaster; outputs[1] = umaster; } public class ReduceDownThread implements Runnable { Vec newv; Vec downv; int i; CountDownLatch latch; public ReduceDownThread(Vec newv0, Vec downv0, int i0, CountDownLatch latch0) { newv = newv0; downv = downv0; i = i0; latch = latch0; } public void run() { int [] sbuf = sendbuf[i]; int [] rbuf = recbuf[i]; int msize = dPartInds[i+1] - dPartInds[i]; sbuf[0] = msize; UTILS.memcpyfi(msize, downv.data, dPartInds[i], sbuf, 1); if (trace) System.out.format("reduce layer %d machine %d sent msg to %d, from %d, size %d\n", depth, imachine, outNbr[i], inNbr[i], sbuf[0]); sendrecv(sbuf, msize+1, outNbr[i], rbuf, rbuf.length, inNbr[i], depth*3+1); if (trace) System.out.format("reduce layer %d machine %d got msg from %d, size %d\n", depth, imachine, inNbr[i], rbuf[0]); Vec res = new Vec(rbuf[0]); UTILS.memcpyif(rbuf[0], rbuf, 1, res.data, 0); res.addTo(newv, downMaps[i]); latch.countDown(); } } public Vec reduceDown(Vec downv) { Vec newv = new Vec(downn); CountDownLatch latch = new CountDownLatch(k); for (int i = 0; i < k; i++) { executor.execute(new ReduceDownThread(newv, downv, i, latch)); } try { latch.await(); } catch (InterruptedException e) {} System.out.format("layer %d machine %d reduce down finished\n", depth, imachine); return newv; } public class ReduceUpThread implements Runnable { Vec newv; Vec upv; int i; CountDownLatch latch; public ReduceUpThread(Vec newv0, Vec upv0, int i0, CountDownLatch latch0) { newv = newv0; upv = upv0; i = i0; latch = latch0; } public void run () { int [] sbuf = sendbuf[i]; int [] rbuf = recbuf[i]; Vec up = upv.mapFrom(upMaps[i]); sbuf[0] = up.size(); UTILS.memcpyfi(up.size(), up.data, 0, sbuf, 1); if (trace) System.out.format("reduce up layer %d machine %d sent msg to %d, from %d, size %d\n", depth, imachine, outNbr[i], inNbr[i], sbuf[0]); sendrecv(sbuf, up.size()+1, inNbr[i], rbuf, rbuf.length, outNbr[i], depth*3+2); if (trace) System.out.format("reduce up layer %d machine %d got msg from %d, size %d\n", depth, imachine, inNbr[i], rbuf[0]); int msize = uPartInds[i+1] - uPartInds[i]; if (uPartInds[i+1] > newv.size()) throw new RuntimeException("ReduceUp index out of range "+uPartInds[i+1]+" "+newv.size()); UTILS.memcpyif(msize, rbuf, 1, newv.data, uPartInds[i]); latch.countDown(); } } public Vec reduceUp(Vec upv) { Vec newv = new Vec(upn); CountDownLatch latch = new CountDownLatch(k); for (int i = 0; i < k; i++) { executor.execute(new ReduceUpThread(newv, upv, i, latch)); } try { latch.await(); } catch (InterruptedException e) {} System.out.format("layer %d machine %d reduce up finished\n", depth, imachine); return newv; } } public boolean sendrecv(int [] sbuf, int sendn, int outi, int [] rbuf, int recn, int ini, int tag) { if (imachine == outi) { System.arraycopy(sbuf, 0, rbuf, 0, sendn); return true; } else { if (doSim) { synchronized (simNetwork[outi].messages[imachine][tag]) { // if (trace) System.out.format("Message sent %d %d %d\n", imachine, sendn, outi); simNetwork[outi].messages[imachine][tag].add(new Msg(sbuf, sendn, imachine, outi)); simNetwork[outi].messages[imachine][tag].notify(); } synchronized (messages[ini][tag]) { while (messages[ini][tag].size() == 0) { try { messages[ini][tag].wait(); } catch (InterruptedException e) {} } Msg msg = messages[ini][tag].removeFirst(); // if (trace) System.out.format("Message recv %d %d %d\n", imachine, msg.sender, msg.receiver, msg.size); System.arraycopy(msg.buf, 0, rbuf, 0, msg.size); } return true; } else { /* MPI.COMM_WORLD.Sendrecv(sbuf, 0, sendn, MPI.INT, outi, tag, rbuf, 0, recn, MPI.INT, ini, tag); Request sreq = MPI.COMM_WORLD.ISend(sbuf, 0, sendn, MPI.INT, outi, tag) Request rreq = MPI.COMM_WORLD.IRecv(rbuf, 0, recn, MPI.INT, ini, tag) Status rdone = null; Status sdone = null; long timeout = 1000; // Wait this many msecs long then = System.currentTimeMillis(); while ((sdone == null || rdone == null) && System.currentTimeMillis() - then < timeout) { if (rdone == null) rdone = rreq.Test(); if (sdone == null) sdone = sreq.Test(); sleep(1); } if (rdone == null) rreq.Cancel(); if (sdone == null) sreq.Cancel(); if (rdone == null || sdone == null) { return false; } else { return true; } */ return true; } } } } public class Msg { int [] buf; int size; int sender; int receiver; public Msg(int [] inbuf0, int size0, int sender0, int receiver0) { buf = new int[size0]; System.arraycopy(inbuf0, 0, buf, 0, size0); size = size0; sender = sender0; receiver = receiver0; } } public Machine [] simNetwork; public AllReduce(int M) { simNetwork = new Machine[M]; } }
package edu.gslis.eval; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import edu.gslis.searchhits.SearchHit; import edu.gslis.searchhits.SearchHits; public class FilterEvaluation { private SearchHits results; private Qrels qrels; private Map<String,List<Double>> aggregateStats; public FilterEvaluation(Qrels qrels) { this.qrels = qrels; aggregateStats = new HashMap<String,List<Double>>(); } public void setResults(SearchHits results) { this.results = results; } public double precision(String queryName) { double numRelRet = this.numRelRet(queryName); if(numRelRet==0.0) { return 0.0; } double numRet = (double)results.size(); double p = numRelRet / numRet; return p; } public double recall(String queryName) { double numRelRet = this.numRelRet(queryName); if(numRelRet==0.0) { return 0.0; } double numRel = qrels.numRel(queryName); return numRelRet / numRel; } public double numRelRet(String queryName) { double relRet = 0.0; if(results == null) return 0.0; Iterator<SearchHit> resultIterator = results.iterator(); while(resultIterator.hasNext()) { SearchHit result = resultIterator.next(); if(qrels.isRel(queryName, result.getDocno())) { relRet += 1.0; } } return (double)relRet; } public double numRet(String queryName) { if(results == null) return 0.0; return (double)results.size(); } /** * calculate F1 for a particular query * @param queryName the TREC-assigned query ID * @return F1 * @throws Exception */ public double f1Query(String queryName) { double precision = this.precision(queryName); double recall = this.recall(queryName); double f = 2 * (precision * recall) / (precision + recall); //System.err.println("EVAL: " + results.size() + " " + f); if(Double.isNaN(f)) { return 0.0; } return f; } /** * calculate Fbeta for a particular query * @param queryName the TREC-assigned query ID * @param beta Beta for weighting precision. beta=1 yields F1 equivalence. * @return Fbeta * @throws Exception */ public double f1Query(String queryName, double beta) throws Exception { beta *= beta; double precision = this.precision(queryName); double recall = this.recall(queryName); double f = (1 + beta) * (precision * recall) / (beta * precision + recall); if(Double.isNaN(f)) { return 0.0; } return f; } public double t11su(String queryName) { if(results == null) return 0.0; double t = 0.0; double minU = 0.5; double truePos = this.numRelRet(queryName); double falsePos = (double)results.size() - truePos; t = (2.0 * truePos - falsePos) / qrels.numRel(queryName); if(Double.isNaN(t)) t = 0.0; t = (Math.max(t, minU) - minU) / (1.0 - minU); return t; } public double utility(String queryName, double truePosWeight) { if(results == null) return 0.0; double truePos = this.numRelRet(queryName); double falsePos = (double)results.size() - truePos; return Math.max(-100, truePosWeight * truePos - falsePos); } public void addStat(String statName, double value) { List<Double> stats = null; if(aggregateStats.containsKey(statName)) { stats = aggregateStats.get(statName); } else { stats = new LinkedList<Double>(); } stats.add(value); aggregateStats.put(statName, stats); } public double avg(String statName) { if(! aggregateStats.containsKey(statName)) { return -1.0; } double mean = 0.0; Iterator<Double> statIterator = aggregateStats.get(statName).iterator(); while(statIterator.hasNext()) { mean += statIterator.next(); } mean /= (double)aggregateStats.get(statName).size(); return mean; } }
package ee.pardiralli.db; import ee.pardiralli.domain.Duck; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import java.util.Date; import java.util.List; public interface DuckRepository extends CrudRepository<Duck, Integer> { @Query("SELECT d FROM Duck d WHERE d.serialNumber = :serial AND d.race.beginning = :date") Duck findBySerialNumber(@Param("serial") Integer serialNumber, @Param("date") Date date); /** * Search item by parameters, parameters can be empty string. */ @Query("SELECT d FROM Duck d WHERE " + "LOWER(d.duckOwner.firstName) LIKE LOWER(CONCAT(:ownerFirstName,'%')) AND " + "LOWER(d.duckOwner.lastName) LIKE LOWER(CONCAT(:ownerLastName,'%')) AND " + "LOWER(d.duckBuyer.email) LIKE LOWER(CONCAT(:email,'%')) AND " + " (d.race.beginning) = :date AND " + "LOWER(d.duckOwner.phoneNumber) LIKE LOWER(CONCAT(:phone,'%'))") List<Duck> findDuck(@Param("ownerFirstName") String ownerFirstName, @Param("ownerLastName") String ownerLastName, @Param("email") String email, @Param("phone") String phone, @Param("date") Date date, Pageable pageable); @Query("SELECT d FROM Duck d WHERE " + "LOWER(d.duckOwner.firstName) LIKE LOWER(CONCAT(:ownerFirstName,'%')) AND " + "LOWER(d.duckOwner.lastName) LIKE LOWER(CONCAT(:ownerLastName,'%')) AND " + "LOWER(d.duckBuyer.email) LIKE LOWER(CONCAT(:email,'%')) AND " + " (d.race.beginning) = :date AND " + "LOWER(d.duckOwner.phoneNumber) LIKE LOWER(CONCAT(:phone,'%'))") List<Duck> findDuck(@Param("ownerFirstName") String ownerFirstName, @Param("ownerLastName") String ownerLastName, @Param("email") String email, @Param("phone") String phone, @Param("date") Date date); }
package exnihilocreatio.tiles; import com.google.common.base.Objects; import exnihilocreatio.ModEnchantments; import exnihilocreatio.blocks.BlockSieve; import exnihilocreatio.config.ModConfig; import exnihilocreatio.registries.manager.ExNihiloRegistryManager; import exnihilocreatio.registries.types.Siftable; import exnihilocreatio.util.BlockInfo; import exnihilocreatio.util.Util; import lombok.Getter; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Enchantments; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.Style; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.UUID; public class TileSieve extends BaseTileEntity { private static final Random rand = new Random(); public TileAutoSifter autoSifter = null; @Getter private BlockInfo currentStack; @Getter private byte progress = 0; @Getter private ItemStack meshStack = ItemStack.EMPTY; @Getter private BlockSieve.MeshType meshType = BlockSieve.MeshType.NONE; private long lastSieveAction = 0; private UUID lastPlayer; /** * Sets the mesh type in the sieve. * * @param newMesh The mesh to set * @return true if setting is successful. */ public boolean setMesh(ItemStack newMesh) { return setMesh(newMesh, false); } public boolean setMesh(ItemStack newMesh, boolean simulate) { if (progress != 0 || currentStack != null) return false; if (meshStack.isEmpty()) { if (!simulate) { meshStack = newMesh.copy(); meshType = BlockSieve.MeshType.getMeshTypeByID(newMesh.getMetadata()); this.markDirtyClient(); } return true; } if (!meshStack.isEmpty() && newMesh.isEmpty()) { //Removing if (!simulate) { meshStack = ItemStack.EMPTY; meshType = BlockSieve.MeshType.NONE; this.markDirtyClient(); } return true; } return false; } public boolean addBlock(ItemStack stack) { if (currentStack == null && ExNihiloRegistryManager.SIEVE_REGISTRY.canBeSifted(stack)) { if (meshStack.isEmpty()) return false; int meshLevel = meshStack.getItemDamage(); for (Siftable siftable : ExNihiloRegistryManager.SIEVE_REGISTRY.getDrops(stack)) { if (siftable.getMeshLevel() == meshLevel) { currentStack = new BlockInfo(stack); markDirtyClient(); return true; } } } return false; } public void doSieving(EntityPlayer player, boolean automatedSieving) { if (!world.isRemote) { if (currentStack == null) { return; } // 4 ticks is the same period of holding down right click if (getWorld().getTotalWorldTime() - lastSieveAction < 4 && !automatedSieving) { return; } // Really good chance that they're using a macro if (!automatedSieving && player != null && getWorld().getTotalWorldTime() - lastSieveAction == 0 && lastPlayer.equals(player.getUniqueID())) { if (ModConfig.sieve.setFireToMacroUsers) { player.setFire(1); } player.sendMessage(new TextComponentString("Bad").setStyle(new Style().setColor(TextFormatting.RED).setBold(true))); } lastSieveAction = getWorld().getTotalWorldTime(); if (player != null) { lastPlayer = player.getUniqueID(); } int efficiency = EnchantmentHelper.getEnchantmentLevel(ModEnchantments.EFFICIENCY, meshStack); efficiency += EnchantmentHelper.getEnchantmentLevel(Enchantments.EFFICIENCY, meshStack); int fortune = EnchantmentHelper.getEnchantmentLevel(ModEnchantments.FORTUNE, meshStack); fortune += EnchantmentHelper.getEnchantmentLevel(Enchantments.FORTUNE, meshStack); if (player != null) { fortune += player.getLuck(); } int luckOfTheSea = EnchantmentHelper.getEnchantmentLevel(ModEnchantments.LUCK_OF_THE_SEA, meshStack); luckOfTheSea += EnchantmentHelper.getEnchantmentLevel(Enchantments.LUCK_OF_THE_SEA, meshStack); if (luckOfTheSea > 0 && player != null) { luckOfTheSea += player.getLuck(); } progress += 10 + 5 * efficiency; markDirtyClient(); if (progress >= 100) { List<ItemStack> drops = ExNihiloRegistryManager.SIEVE_REGISTRY.getRewardDrops(rand, currentStack.getBlockState(), meshStack.getMetadata(), fortune); if (drops == null) { drops = new ArrayList<>(); } // Fancy math to make the average fish dropped ~ luckOfTheSea / 2 fish, which is what it was before int fishToDrop = (int) Math.round(rand.nextGaussian() + (luckOfTheSea / 2.0)); fishToDrop = Math.min(fishToDrop, 0); fishToDrop = Math.max(fishToDrop, luckOfTheSea); for (int i = 0; i < fishToDrop; i++) { /* * Gives fish following chances: * Normal: 43% (3/7) * Salmon: 29% (2/7) * Clown: 14% (1/7) * Puffer: 14% (1/7) */ int fishMeta = 0; switch (rand.nextInt(7)) { case 3: case 4: fishMeta = 1; break; case 5: fishMeta = 2; break; case 6: fishMeta = 3; break; default: break; } drops.add(new ItemStack(Items.FISH, 1, fishMeta)); } drops.forEach(stack -> Util.dropItemInWorld(this, player, stack, 1)); resetSieve(); markDirtyClient(); } } } public boolean isSieveSimilar(TileSieve sieve) { return sieve != null && !meshStack.isEmpty() && !sieve.getMeshStack().isEmpty() && meshStack.getItemDamage() == sieve.getMeshStack().getItemDamage() && progress == sieve.getProgress() && /*TODO*/ currentStack != null && currentStack.equals(sieve.getCurrentStack()); } public boolean isSieveSimilarToInput(TileSieve sieve) { return !meshStack.isEmpty() && !sieve.getMeshStack().isEmpty() && meshStack.getItemDamage() == sieve.getMeshStack().getItemDamage() && progress == sieve.getProgress() && sieve.getCurrentStack() == null; } private void resetSieve() { progress = 0; currentStack = null; markDirtyClient(); } public void validateAutoSieve() { if (autoSifter == null || autoSifter.isInvalid() || !(world.getTileEntity(autoSifter.getPos()) instanceof TileAutoSifter || autoSifter.toSift == null)) { autoSifter = null; } } @SideOnly(Side.CLIENT) public TextureAtlasSprite getTexture() { if (currentStack != null) { return Util.getTextureFromBlockState(currentStack.getBlockState()); } return null; } @Override public boolean shouldRefresh(World world, BlockPos pos, @Nonnull IBlockState oldState, @Nonnull IBlockState newState) { return oldState.getBlock() != newState.getBlock(); } @Override @Nonnull public NBTTagCompound writeToNBT(NBTTagCompound tag) { if (currentStack != null) { NBTTagCompound stackTag = currentStack.writeToNBT(new NBTTagCompound()); tag.setTag("stack", stackTag); } if (!meshStack.isEmpty()) { NBTTagCompound meshTag = meshStack.writeToNBT(new NBTTagCompound()); tag.setTag("mesh", meshTag); } tag.setByte("progress", progress); return super.writeToNBT(tag); } @Override public void readFromNBT(NBTTagCompound tag) { if (tag.hasKey("stack")) currentStack = BlockInfo.readFromNBT(tag.getCompoundTag("stack")); else currentStack = null; if (tag.hasKey("mesh")) { meshStack = new ItemStack(tag.getCompoundTag("mesh")); meshType = BlockSieve.MeshType.getMeshTypeByID(meshStack.getMetadata()); } else { meshStack = ItemStack.EMPTY; meshType = BlockSieve.MeshType.NONE; } progress = tag.getByte("progress"); super.readFromNBT(tag); } @Override public int hashCode() { return Objects.hashCode(pos.getX(), pos.getY(), pos.getZ()); } }
package fr.notfound; import java.net.URI; public class BattleDayParameters { public static final URI TestArenaUri = URI.create( "http://ec2-54-200-12-98.us-west-2.compute.amazonaws.com/csnbattlearena/webservices/test/"); // FIXME: Enable and correct on battle day public static final URI ArenaUri = URI.create("http://192.168.2.2:8080/csnbattlearena/webservices/battle"); public static final String TeamName = "404"; public static final String Password = ""; public static final int NumberOfOpponentTeams = 5; public static final int RetryDelay = 100; }
package hudson.plugins.git; import hudson.MarkupText; import hudson.model.Hudson; import hudson.model.User; import hudson.plugins.git.GitSCM.DescriptorImpl; import hudson.scm.ChangeLogAnnotator; import hudson.scm.ChangeLogSet; import hudson.scm.ChangeLogSet.AffectedFile; import hudson.scm.EditType; import org.apache.commons.lang.math.NumberUtils; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import javax.annotation.CheckForNull; import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.TimeZone; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import static hudson.Util.fixEmpty; import org.joda.time.DateTime; import org.joda.time.DateTimeFieldType; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.DateTimeFormatterBuilder; import org.joda.time.format.ISODateTimeFormat; /** * Represents a change set. * @author Nigel Magnay */ public class GitChangeSet extends ChangeLogSet.Entry { private static final String PREFIX_AUTHOR = "author "; private static final String PREFIX_COMMITTER = "committer "; private static final String IDENTITY = "([^<]*)<(.*)> (.*)"; private static final Pattern FILE_LOG_ENTRY = Pattern.compile("^:[0-9]{6} [0-9]{6} ([0-9a-f]{40}) ([0-9a-f]{40}) ([ACDMRTUX])(?>[0-9]+)?\t(.*)$"); private static final Pattern AUTHOR_ENTRY = Pattern.compile("^" + PREFIX_AUTHOR + IDENTITY + "$"); private static final Pattern COMMITTER_ENTRY = Pattern.compile("^" + PREFIX_COMMITTER + IDENTITY + "$"); private static final Pattern RENAME_SPLIT = Pattern.compile("^(.*?)\t(.*)$"); private static final String NULL_HASH = "0000000000000000000000000000000000000000"; private static final String ISO_8601 = "yyyy-MM-dd'T'HH:mm:ss"; private static final String ISO_8601_WITH_TZ = "yyyy-MM-dd'T'HH:mm:ssX"; private final DateTimeFormatter [] dateFormatters; public static final Logger LOGGER = Logger.getLogger(GitChangeSet.class.getName()); /** * This is broken as a part of the 1.5 refactoring. * * <p> * When we build a commit that multiple branches point to, Git plugin historically recorded * changelogs "revOfBranchInPreviousBuild...revToBuild" for each branch separately. This * however fails to take full generality of Git commit graph into account, as such rev-lists * can share common commits, which then get reported multiple times. * * <p> * In Git, a commit doesn't belong to a branch, in the sense that you cannot look at the object graph * and re-construct exactly how branch has evolved. In that sense, trying to attribute commits to * branches is a somewhat futile exercise. * * <p> * On the other hand, if this is still deemed important, the right thing to do is to traverse * the commit graph and see if a commit can be only reachable from the "revOfBranchInPreviousBuild" of * just one branch, in which case it's safe to attribute the commit to that branch. */ private String committer; private String committerEmail; private String committerTime; private String author; private String authorEmail; private String authorTime; private String comment; private String title; private String id; private String parentCommit; private Collection<Path> paths = new HashSet<>(); private boolean authorOrCommitter; /** * Create Git change set using information in given lines * * @param lines change set lines read to construct change set * @param authorOrCommitter if true, use author information (name, time), otherwise use committer information */ public GitChangeSet(List<String> lines, boolean authorOrCommitter) { this.authorOrCommitter = authorOrCommitter; if (lines.size() > 0) { parseCommit(lines); } // Nearly ISO dates generated by git whatchanged --format=+ci // Look like '2015-09-30 08:21:24 -0600' // ISO is '2015-09-30T08:21:24-06:00' // Uses Builder rather than format pattern for more reliable parsing DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder(); builder.appendFixedDecimal(DateTimeFieldType.year(), 4); builder.appendLiteral('-'); builder.appendFixedDecimal(DateTimeFieldType.monthOfYear(), 2); builder.appendLiteral('-'); builder.appendFixedDecimal(DateTimeFieldType.dayOfMonth(), 2); builder.appendLiteral(' '); builder.appendFixedDecimal(DateTimeFieldType.hourOfDay(), 2); builder.appendLiteral(':'); builder.appendFixedDecimal(DateTimeFieldType.minuteOfHour(), 2); builder.appendLiteral(':'); builder.appendFixedDecimal(DateTimeFieldType.secondOfMinute(), 2); builder.appendLiteral(' '); builder.appendTimeZoneOffset(null, false, 2, 2); DateTimeFormatter gitDateFormatter = builder.toFormatter(); // DateTimeFormat.forPattern("yyyy-MM-DDTHH:mm:ssZ"); // 2013-03-21T15:16:44+0100 // Uses Builder rather than format pattern for more reliable parsing builder = new DateTimeFormatterBuilder(); builder.appendFixedDecimal(DateTimeFieldType.year(), 4); builder.appendLiteral('-'); builder.appendFixedDecimal(DateTimeFieldType.monthOfYear(), 2); builder.appendLiteral('-'); builder.appendFixedDecimal(DateTimeFieldType.dayOfMonth(), 2); builder.appendLiteral('T'); builder.appendFixedDecimal(DateTimeFieldType.hourOfDay(), 2); builder.appendLiteral(':'); builder.appendFixedDecimal(DateTimeFieldType.minuteOfHour(), 2); builder.appendLiteral(':'); builder.appendFixedDecimal(DateTimeFieldType.secondOfMinute(), 2); builder.appendTimeZoneOffset(null, false, 2, 2); DateTimeFormatter nearlyISOFormatter = builder.toFormatter(); DateTimeFormatter isoDateFormat = ISODateTimeFormat.basicDateTimeNoMillis(); dateFormatters = new DateTimeFormatter[3]; dateFormatters[0] = gitDateFormatter; // First priority +%cI format dateFormatters[1] = nearlyISOFormatter; // Second priority seen in git-plugin dateFormatters[2] = isoDateFormat; // Third priority, ISO 8601 format } private void parseCommit(List<String> lines) { StringBuilder message = new StringBuilder(); for (String line : lines) { if( line.length() < 1) continue; if (line.startsWith("commit ")) { String[] split = line.split(" "); if (split.length > 1) this.id = split[1]; else throw new IllegalArgumentException("Commit has no ID" + lines); } else if (line.startsWith("tree ")) { } else if (line.startsWith("parent ")) { String[] split = line.split(" "); // parent may be null for initial commit or changelog computed from a shallow clone if (split.length > 1) this.parentCommit = split[1]; } else if (line.startsWith(PREFIX_COMMITTER)) { Matcher committerMatcher = COMMITTER_ENTRY.matcher(line); if (committerMatcher.matches() && committerMatcher.groupCount() >= 3) { this.committer = committerMatcher.group(1).trim(); this.committerEmail = committerMatcher.group(2); this.committerTime = isoDateFormat(committerMatcher.group(3)); } } else if (line.startsWith(PREFIX_AUTHOR)) { Matcher authorMatcher = AUTHOR_ENTRY.matcher(line); if (authorMatcher.matches() && authorMatcher.groupCount() >= 3) { this.author = authorMatcher.group(1).trim(); this.authorEmail = authorMatcher.group(2); this.authorTime = isoDateFormat(authorMatcher.group(3)); } } else if (line.startsWith(" ")) { message.append(line.substring(4)).append('\n'); } else if (':' == line.charAt(0)) { Matcher fileMatcher = FILE_LOG_ENTRY.matcher(line); if (fileMatcher.matches() && fileMatcher.groupCount() >= 4) { String mode = fileMatcher.group(3); if (mode.length() == 1) { String src = null; String dst = null; String path = fileMatcher.group(4); char editMode = mode.charAt(0); if (editMode == 'M' || editMode == 'A' || editMode == 'D' || editMode == 'R' || editMode == 'C') { src = parseHash(fileMatcher.group(1)); dst = parseHash(fileMatcher.group(2)); } // Handle rename as two operations - a delete and an add if (editMode == 'R') { Matcher renameSplitMatcher = RENAME_SPLIT.matcher(path); if (renameSplitMatcher.matches() && renameSplitMatcher.groupCount() >= 2) { String oldPath = renameSplitMatcher.group(1); String newPath = renameSplitMatcher.group(2); this.paths.add(new Path(src, dst, 'D', oldPath, this)); this.paths.add(new Path(src, dst, 'A', newPath, this)); } } // Handle copy as an add else if (editMode == 'C') { Matcher copySplitMatcher = RENAME_SPLIT.matcher(path); if (copySplitMatcher.matches() && copySplitMatcher.groupCount() >= 2) { String newPath = copySplitMatcher.group(2); this.paths.add(new Path(src, dst, 'A', newPath, this)); } } else { this.paths.add(new Path(src, dst, editMode, path, this)); } } } } } this.comment = message.toString(); int endOfFirstLine = this.comment.indexOf('\n'); if (endOfFirstLine == -1) { this.title = this.comment; } else { this.title = this.comment.substring(0, endOfFirstLine); } } /** Convert to iso date format if required */ private String isoDateFormat(String s) { String date = s; String timezone = "Z"; int spaceIndex = s.indexOf(' '); if (spaceIndex > 0) { date = s.substring(0, spaceIndex); timezone = s.substring(spaceIndex+1); } if (NumberUtils.isDigits(date)) { // legacy mode long time = Long.parseLong(date); DateFormat formatter = new SimpleDateFormat(ISO_8601); formatter.setTimeZone(TimeZone.getTimeZone("GMT")); return formatter.format(new Date(time * 1000)) + timezone; } else { // already in ISO format return s; } } private String parseHash(String hash) { return NULL_HASH.equals(hash) ? null : hash; } @Exported public String getDate() { return authorOrCommitter ? authorTime : committerTime; } @Exported public String getAuthorEmail() { return authorOrCommitter ? authorEmail : committerEmail; } @Override public long getTimestamp() { String date = getDate(); if (date == null) { LOGGER.log(Level.WARNING, "Failed to parse null date"); return -1; } if (date.isEmpty()) { LOGGER.log(Level.WARNING, "Failed to parse empty date"); return -1; } for (DateTimeFormatter dateFormatter : dateFormatters) { try { DateTime dateTime = DateTime.parse(date, dateFormatter); return dateTime.getMillis(); } catch (IllegalArgumentException ia) { } } try { return new SimpleDateFormat(ISO_8601_WITH_TZ).parse(date).getTime(); } catch (ParseException e) { return -1; } catch (IllegalArgumentException ia) { final String java6FormatDef = ISO_8601_WITH_TZ.replace("X", "Z"); final String java6Date = getDate().replaceAll(":(\\d\\d)$", "$1"); try { return new SimpleDateFormat(java6FormatDef).parse(java6Date).getTime(); } catch (ParseException e) { return -1; } } } @Override public String getCommitId() { return id; } @Override public void setParent(ChangeLogSet parent) { super.setParent(parent); } public @CheckForNull String getParentCommit() { return parentCommit; } @Override public Collection<String> getAffectedPaths() { Collection<String> affectedPaths = new HashSet<>(this.paths.size()); for (Path file : this.paths) { affectedPaths.add(file.getPath()); } return affectedPaths; } /** * Gets the files that are changed in this commit. * @return * can be empty but never null. */ @Exported public Collection<Path> getPaths() { return paths; } @Override public Collection<Path> getAffectedFiles() { return this.paths; } /** * Returns user of the change set. * * @param csAuthor user name. * @param csAuthorEmail user email. * @param createAccountBasedOnEmail true if create new user based on committer's email. * @return {@link User} */ public User findOrCreateUser(String csAuthor, String csAuthorEmail, boolean createAccountBasedOnEmail) { User user; if (csAuthor == null) { return User.getUnknown(); } if (createAccountBasedOnEmail) { user = User.get(csAuthorEmail, false); if (user == null) { try { user = User.get(csAuthorEmail, true); user.setFullName(csAuthor); if (hasHudsonTasksMailer()) setMail(user, csAuthorEmail); user.save(); } catch (IOException e) { // add logging statement? } } } else { user = User.get(csAuthor, false); if (user == null) { // Ensure that malformed email addresses (in this case, just '@') // don't mess us up. String[] emailParts = csAuthorEmail.split("@"); if (emailParts.length > 0) { user = User.get(emailParts[0], true); } else { return User.getUnknown(); } } } // set email address for user if none is already available if (fixEmpty(csAuthorEmail) != null && hasHudsonTasksMailer() && !hasMail(user)) { try { setMail(user, csAuthorEmail); } catch (IOException e) { // ignore } } return user; } private void setMail(User user, String csAuthorEmail) throws IOException { user.addProperty(new hudson.tasks.Mailer.UserProperty(csAuthorEmail)); } private boolean hasMail(User user) { hudson.tasks.Mailer.UserProperty property = user.getProperty(hudson.tasks.Mailer.UserProperty.class); return property != null && property.hasExplicitlyConfiguredAddress(); } private boolean hasHudsonTasksMailer() { // TODO convert to checking for mailer plugin as plugin migrates to 1.509+ try { Class.forName("hudson.tasks.Mailer"); return true; } catch (ClassNotFoundException e) { return false; } } private boolean isCreateAccountBasedOnEmail() { Hudson hudson = Hudson.getInstance(); if (hudson == null) { return false; } DescriptorImpl descriptor = (DescriptorImpl) hudson.getDescriptor(GitSCM.class); if (descriptor == null) { return false; } return descriptor.isCreateAccountBasedOnEmail(); } @Override @Exported public User getAuthor() { String csAuthor; String csAuthorEmail; // If true, use the author field from git log rather than the committer. if (authorOrCommitter) { csAuthor = this.author; csAuthorEmail = this.authorEmail; } else { csAuthor = this.committer; csAuthorEmail = this.committerEmail; } return findOrCreateUser(csAuthor, csAuthorEmail, isCreateAccountBasedOnEmail()); } /** * Gets the author name for this changeset - note that this is mainly here * so that we can test authorOrCommitter without needing a fully instantiated * Hudson (which is needed for User.get in getAuthor()). * * @return author name */ public String getAuthorName() { // If true, use the author field from git log rather than the committer. String csAuthor = authorOrCommitter ? author : committer; return csAuthor; } @Override @Exported public String getMsg() { return this.title; } @Exported public String getId() { return this.id; } public String getRevision() { return this.id; } @Exported public String getComment() { return this.comment; } /** * Gets {@linkplain #getComment() the comment} fully marked up by {@link ChangeLogAnnotator}. @return annotated comment */ public String getCommentAnnotated() { MarkupText markup = new MarkupText(getComment()); for (ChangeLogAnnotator a : ChangeLogAnnotator.all()) a.annotate(getParent().getRun(), this, markup); return markup.toString(false); } public String getBranch() { return null; } @ExportedBean(defaultVisibility=999) public static class Path implements AffectedFile { private String src; private String dst; private char action; private String path; private GitChangeSet changeSet; private Path(String source, String destination, char action, String filePath, GitChangeSet changeSet) { this.src = source; this.dst = destination; this.action = action; this.path = filePath; this.changeSet = changeSet; } public String getSrc() { return src; } public String getDst() { return dst; } @Exported(name="file") public String getPath() { return path; } public GitChangeSet getChangeSet() { return changeSet; } @Exported public EditType getEditType() { switch (action) { case 'A': return EditType.ADD; case 'D': return EditType.DELETE; default: return EditType.EDIT; } } } public int hashCode() { return id != null ? id.hashCode() : super.hashCode(); } public boolean equals(Object obj) { if (obj == this) return true; if (obj instanceof GitChangeSet) return id != null && id.equals(((GitChangeSet) obj).id); return false; } }
package io.sniffy.servlet; import io.sniffy.Constants; import io.sniffy.util.LruCache; import javax.servlet.*; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.MalformedURLException; import java.util.Collections; import java.util.Map; import java.util.regex.Pattern; * <url-pattern>/*</url-pattern> * </filter-mapping> * } * </pre> * * @since 2.3.0 */ public class SnifferFilter implements Filter { public static final String HEADER_NUMBER_OF_QUERIES = "X-Sql-Queries"; public static final String HEADER_REQUEST_DETAILS = "X-Request-Details"; public static final String SNIFFER_URI_PREFIX = "/sniffy/" + Constants.MAJOR_VERSION + "." + Constants.MINOR_VERSION + "." + Constants.PATCH_VERSION; public static final String JAVASCRIPT_URI = SNIFFER_URI_PREFIX + "/sniffy.min.js"; public static final String REQUEST_URI_PREFIX = SNIFFER_URI_PREFIX + "/request/"; public static final String SNIFFY = "sniffy"; protected boolean injectHtml = false; protected boolean enabled = true; protected Pattern excludePattern = null; // TODO: consider replacing with some concurrent collection instead protected final Map<String, RequestStats> cache = Collections.synchronizedMap(new LruCache<String, RequestStats>(10000)); protected SnifferServlet snifferServlet; protected ServletContext servletContext; protected String contextPath; public void init(FilterConfig filterConfig) throws ServletException { String injectHtml = filterConfig.getInitParameter("inject-html"); if (null != injectHtml) { this.injectHtml = Boolean.parseBoolean(injectHtml); } String enabled = filterConfig.getInitParameter("enabled"); if (null != enabled) { this.enabled = Boolean.parseBoolean(enabled); } String excludePattern = filterConfig.getInitParameter("exclude-pattern"); if (null != excludePattern) { this.excludePattern = Pattern.compile(excludePattern); } snifferServlet = new SnifferServlet(cache); snifferServlet.init(new FilterServletConfigAdapter(filterConfig, "sniffy")); servletContext = filterConfig.getServletContext(); contextPath = servletContext.getContextPath(); } public void doFilter(final ServletRequest request, ServletResponse response, final FilterChain chain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; Boolean sniffyEnabled = enabled; // override by request parameter/cookie value if provided String sniffyEnabledParam = request.getParameter(SNIFFY); if (null != sniffyEnabledParam) { sniffyEnabled = Boolean.parseBoolean(sniffyEnabledParam); setSessionCookie(httpServletResponse, SNIFFY, String.valueOf(sniffyEnabled)); } else { sniffyEnabledParam = readCookie(httpServletRequest, SNIFFY); if (null != sniffyEnabledParam) { sniffyEnabled = Boolean.parseBoolean(sniffyEnabledParam); } } // if disabled, run chain and return if (!sniffyEnabled) { chain.doFilter(request, response); return; } // process Sniffy REST calls if (injectHtml) { try { snifferServlet.service(request, response); if (response.isCommitted()) return; } catch (Exception e) { servletContext.log("Exception in SniffyServlet; calling original chain", e); chain.doFilter(request, response); return; } } // create request decorator SniffyRequestProcessor sniffyRequestProcessor; try { sniffyRequestProcessor = new SniffyRequestProcessor(this, request, response); } catch (Exception e) { servletContext.log("Exception in SniffyRequestProcessor initialization; calling original chain", e); chain.doFilter(request, response); return; } sniffyRequestProcessor.process(chain); } private void setSessionCookie(HttpServletResponse httpServletResponse, String name, String value) throws MalformedURLException { Cookie cookie = new Cookie(name, value); cookie.setPath("/"); httpServletResponse.addCookie(cookie); } private String readCookie(HttpServletRequest httpServletRequest, String name) { for (Cookie cookie : httpServletRequest.getCookies()) { if (name.equals(cookie.getName())) { return cookie.getValue(); } } return null; } public void destroy() { } public boolean isInjectHtml() { return injectHtml; } public void setInjectHtml(boolean injectHtml) { this.injectHtml = injectHtml; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } }
package is.ru.coolpeople.tictactoe; import java.util.Objects; import java.util.Queue; public class Game { private Board board; private Queue<Player> players; // The current player is always first in the Queue private final int minWinCondition = 3; private final int minCustomGameWinCondition = 4; private int winCondition = minWinCondition; private int lastValidMove; private String lastSymbol; public Game(Queue<Player> playersQueue) { board = new Board(); players = playersQueue; } public Game(Queue<Player> playersQueue, int bW, int bH) { board = new Board(bW, bH); players = playersQueue; } // Returns false if the cell has already been marked, otherwise, markes the cell public TurnResult doTurn(int index) { if (board.getSymbolAtIndex(index) != null) { return TurnResult.invalid; } lastValidMove = index; lastSymbol = players.peek().getSymbol(); board.placeSymbol(lastSymbol, index); players.add(players.poll()); //changes the current player return isGameOver() ? TurnResult.gameOver : TurnResult.valid; } public Board getBoard() { return board; } public int getLastValidMove() { return lastValidMove; } public String getLastSymbol() { return lastSymbol; } public String currentPlayerName() { return (players.peek()).getName(); } public int getWinCondition(){ return winCondition; } public void setWinCondition(int wC){ if(wC < minWinCondition){ throw new IllegalArgumentException("Win condition must be at least 3"); } winCondition = wC; } public boolean isGameOver() { //checks if game is won by horizontal lines for (int i = 0; i < 7; i += 3) { if (board.getSymbolAtIndex(i) != null) { if (Objects.equals(board.getSymbolAtIndex(i), board.getSymbolAtIndex(i + 1)) && Objects.equals(board.getSymbolAtIndex(i), board.getSymbolAtIndex(i + 2))) { return true; } } } //check if game is won by vertical lines for (int i = 0; i < 3; i++) { if (board.getSymbolAtIndex(i) != null) { if (Objects.equals(board.getSymbolAtIndex(i), board.getSymbolAtIndex(i + 3)) && Objects.equals(board.getSymbolAtIndex(i), board.getSymbolAtIndex(i + 6))) { return true; } } } //check if game is won by corner-to-corner lines if (board.getSymbolAtIndex(4) != null) { if (Objects.equals(board.getSymbolAtIndex(0), board.getSymbolAtIndex(4)) && Objects.equals(board.getSymbolAtIndex(4), board.getSymbolAtIndex(8))) { return true; } if (Objects.equals(board.getSymbolAtIndex(6), board.getSymbolAtIndex(4)) && Objects.equals(board.getSymbolAtIndex(4), board.getSymbolAtIndex(2))) { return true; } } return false; } }
package mil.dds.anet.database; import com.codahale.metrics.MetricRegistry; import com.google.common.collect.ObjectArrays; import java.lang.invoke.MethodHandles; import java.lang.reflect.InvocationTargetException; import java.net.URISyntaxException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.CompletableFuture; import javax.cache.Cache; import javax.cache.Cache.Entry; import javax.cache.CacheManager; import javax.cache.Caching; import javax.cache.spi.CachingProvider; import mil.dds.anet.AnetObjectEngine; import mil.dds.anet.beans.Person; import mil.dds.anet.beans.Person.PersonStatus; import mil.dds.anet.beans.PersonPositionHistory; import mil.dds.anet.beans.Position; import mil.dds.anet.beans.lists.AnetBeanList; import mil.dds.anet.beans.search.PersonSearchQuery; import mil.dds.anet.database.mappers.PersonMapper; import mil.dds.anet.database.mappers.PersonPositionHistoryMapper; import mil.dds.anet.utils.AnetAuditLogger; import mil.dds.anet.utils.DaoUtils; import mil.dds.anet.utils.FkDataLoaderKey; import mil.dds.anet.utils.Utils; import mil.dds.anet.views.ForeignKeyFetcher; import org.apache.commons.beanutils.PropertyUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.vyarus.guicey.jdbi3.tx.InTransaction; public class PersonDao extends AnetBaseDao<Person, PersonSearchQuery> { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); // Must always retrieve these e.g. for ORDER BY public static String[] minimalFields = {"uuid", "name", "rank", "createdAt"}; public static String[] additionalFields = {"status", "role", "emailAddress", "phoneNumber", "biography", "country", "gender", "endOfTourDate", "domainUsername", "pendingVerification", "code", "updatedAt", "customFields"}; // "avatar" has its own batcher public static String[] avatarFields = {"uuid", "avatar"}; public static final String[] allFields = ObjectArrays.concat(minimalFields, additionalFields, String.class); public static String TABLE_NAME = "people"; public static String PERSON_FIELDS = DaoUtils.buildFieldAliases(TABLE_NAME, allFields, true); public static String PERSON_AVATAR_FIELDS = DaoUtils.buildFieldAliases(TABLE_NAME, avatarFields, true); public static String PERSON_FIELDS_NOAS = DaoUtils.buildFieldAliases(TABLE_NAME, allFields, false); private static final String EHCACHE_CONFIG = "/ehcache-config.xml"; private static final String DOMAIN_USERS_CACHE = "domainUsersCache"; private Cache<String, Person> domainUsersCache; private MetricRegistry metricRegistry; public PersonDao() { try { final CachingProvider cachingProvider = Caching.getCachingProvider(); final CacheManager manager = cachingProvider.getCacheManager( PersonDao.class.getResource(EHCACHE_CONFIG).toURI(), PersonDao.class.getClassLoader()); domainUsersCache = manager.getCache(DOMAIN_USERS_CACHE, String.class, Person.class); if (domainUsersCache == null) { logger.warn("Caching config for {} not found in {}, proceeding without caching", DOMAIN_USERS_CACHE, EHCACHE_CONFIG); } } catch (URISyntaxException | NullPointerException e) { logger.warn("Caching config {} not found, proceeding without caching", EHCACHE_CONFIG); } } public MetricRegistry getMetricRegistry() { return metricRegistry; } public void setMetricRegistry(MetricRegistry metricRegistry) { this.metricRegistry = metricRegistry; } @Override public Person getByUuid(String uuid) { return getByIds(Arrays.asList(uuid)).get(0); } static class SelfIdBatcher extends IdBatcher<Person> { private static final String sql = "/* batch.getPeopleByUuids */ SELECT " + PERSON_FIELDS + " FROM people WHERE uuid IN ( <uuids> )"; public SelfIdBatcher() { super(sql, "uuids", new PersonMapper()); } } static class AvatarBatcher extends IdBatcher<Person> { private static final String sql = "/* batch.getPeopleAvatars */ SELECT " + PERSON_AVATAR_FIELDS + " FROM people WHERE uuid IN ( <uuids> )"; public AvatarBatcher() { super(sql, "uuids", new PersonMapper()); } } @Override public List<Person> getByIds(List<String> uuids) { final IdBatcher<Person> idBatcher = AnetObjectEngine.getInstance().getInjector().getInstance(SelfIdBatcher.class); return idBatcher.getByIds(uuids); } public Person getAvatar(String uuid) { return getAvatars(Arrays.asList(uuid)).get(0); } public List<Person> getAvatars(List<String> uuids) { final IdBatcher<Person> avatarBatcher = AnetObjectEngine.getInstance().getInjector().getInstance(AvatarBatcher.class); return avatarBatcher.getByIds(uuids); } static class PersonPositionHistoryBatcher extends ForeignKeyBatcher<PersonPositionHistory> { private static final String sql = "/* batch.getPersonPositionHistory */ SELECT * FROM \"peoplePositions\" " + "WHERE \"personUuid\" IN ( <foreignKeys> ) ORDER BY \"createdAt\" ASC"; public PersonPositionHistoryBatcher() { super(sql, "foreignKeys", new PersonPositionHistoryMapper(), "personUuid"); } } public List<List<PersonPositionHistory>> getPersonPositionHistory(List<String> foreignKeys) { final ForeignKeyBatcher<PersonPositionHistory> personPositionHistoryBatcher = AnetObjectEngine .getInstance().getInjector().getInstance(PersonPositionHistoryBatcher.class); return personPositionHistoryBatcher.getByForeignKeys(foreignKeys); } @Override public Person insertInternal(Person p) { StringBuilder sql = new StringBuilder(); sql.append("/* personInsert */ INSERT INTO people " + "(uuid, name, status, role, \"emailAddress\", \"phoneNumber\", rank, \"pendingVerification\", " + "gender, country, avatar, code, \"endOfTourDate\", biography, \"domainUsername\", \"createdAt\", \"updatedAt\", \"customFields\") " + "VALUES (:uuid, :name, :status, :role, :emailAddress, :phoneNumber, :rank, :pendingVerification, " + ":gender, :country, :avatar, :code, "); if (DaoUtils.isMsSql()) { // MsSql requires an explicit CAST when datetime2 might be NULL. sql.append("CAST(:endOfTourDate AS datetime2), "); } else { sql.append(":endOfTourDate, "); } sql.append(":biography, :domainUsername, :createdAt, :updatedAt, :customFields);"); getDbHandle().createUpdate(sql.toString()).bindBean(p) .bind("createdAt", DaoUtils.asLocalDateTime(p.getCreatedAt())) .bind("updatedAt", DaoUtils.asLocalDateTime(p.getUpdatedAt())) .bind("endOfTourDate", DaoUtils.asLocalDateTime(p.getEndOfTourDate())) .bind("status", DaoUtils.getEnumId(p.getStatus())) .bind("role", DaoUtils.getEnumId(p.getRole())).execute(); evictFromCache(p); return p; } @Override public int updateInternal(Person p) { StringBuilder sql = new StringBuilder("/* personUpdate */ UPDATE people " + "SET name = :name, status = :status, role = :role, " + "gender = :gender, country = :country, \"emailAddress\" = :emailAddress, " + "\"avatar\" = :avatar, code = :code, " + "\"phoneNumber\" = :phoneNumber, rank = :rank, biography = :biography, " + "\"pendingVerification\" = :pendingVerification, \"domainUsername\" = :domainUsername, " + "\"updatedAt\" = :updatedAt, \"customFields\" = :customFields, "); if (DaoUtils.isMsSql()) { // MsSql requires an explicit CAST when datetime2 might be NULL. sql.append("\"endOfTourDate\" = CAST(:endOfTourDate AS datetime2) "); } else { sql.append("\"endOfTourDate\" = :endOfTourDate "); } sql.append("WHERE uuid = :uuid"); final int nr = getDbHandle().createUpdate(sql.toString()).bindBean(p) .bind("updatedAt", DaoUtils.asLocalDateTime(p.getUpdatedAt())) .bind("endOfTourDate", DaoUtils.asLocalDateTime(p.getEndOfTourDate())) .bind("status", DaoUtils.getEnumId(p.getStatus())) .bind("role", DaoUtils.getEnumId(p.getRole())).execute(); evictFromCache(p); // The domainUsername may have changed, evict original person as well evictFromCache(findInCache(p)); return nr; } @Override public AnetBeanList<Person> search(PersonSearchQuery query) { return search(null, query); } public AnetBeanList<Person> search(Set<String> subFields, PersonSearchQuery query) { return AnetObjectEngine.getInstance().getSearcher().getPersonSearcher().runSearch(subFields, query); } @InTransaction public List<Person> findByDomainUsername(String domainUsername) { final Person person = getFromCache(domainUsername); if (person != null) { return Collections.singletonList(person); } final List<Person> people = getDbHandle() .createQuery("/* findByDomainUsername */ SELECT " + PERSON_FIELDS + "," + PositionDao.POSITIONS_FIELDS + "FROM people LEFT JOIN positions ON people.uuid = positions.\"currentPersonUuid\" " + "WHERE people.\"domainUsername\" = :domainUsername " + "AND people.status != :inactiveStatus") .bind("domainUsername", domainUsername) .bind("inactiveStatus", DaoUtils.getEnumId(PersonStatus.INACTIVE)).map(new PersonMapper()) .list(); // There should at most one match people.stream().forEach(p -> putInCache(p)); return people; } /** * Evict the person from the cache. * * @param personUuid the uuid of the person to be evicted from the cache */ public void evictFromCacheByPersonUuid(String personUuid) { evictFromCache(findInCacheByPersonUuid(personUuid)); } /** * Evict the person holding the position from the cache. * * @param positionUuid the uuid of the position for the person to be evicted from the cache */ public void evictFromCacheByPositionUuid(String positionUuid) { evictFromCache(findInCacheByPositionUuid(positionUuid)); } private Person getFromCache(String domainUsername) { if (domainUsersCache == null || domainUsername == null) { return null; } final Person person = domainUsersCache.get(domainUsername); if (metricRegistry != null) { metricRegistry.counter(MetricRegistry.name(DOMAIN_USERS_CACHE, "LoadCount")).inc(); if (person == null) { metricRegistry.counter(MetricRegistry.name(DOMAIN_USERS_CACHE, "CacheMissCount")).inc(); } else { metricRegistry.counter(MetricRegistry.name(DOMAIN_USERS_CACHE, "CacheHitCount")).inc(); } } // defensively copy the person we return from the cache return copyPerson(person); } private void putInCache(Person person) { if (domainUsersCache != null && person != null && person.getDomainUsername() != null) { // defensively copy the person we will be caching final Person copy = copyPerson(person); if (copy != null) { domainUsersCache.put(person.getDomainUsername(), copy); } } } /** * Just to be on the safe side, we only cache objects retrieved inside * {@link #findByDomainUsername(String)}. * * @param person the person to be evicted from the domain users cache */ private void evictFromCache(Person person) { if (domainUsersCache != null && person != null && person.getDomainUsername() != null) { domainUsersCache.remove(person.getDomainUsername()); } } private Person findInCache(Person person) { return findInCacheByPersonUuid(DaoUtils.getUuid(person)); } private Person findInCacheByPersonUuid(String personUuid) { if (domainUsersCache != null && personUuid != null) { for (final Entry<String, Person> entry : domainUsersCache) { if (entry != null && Objects.equals(DaoUtils.getUuid(entry.getValue()), personUuid)) { return entry.getValue(); } } } return null; } private Person findInCacheByPositionUuid(String positionUuid) { if (domainUsersCache != null && positionUuid != null) { for (final Entry<String, Person> entry : domainUsersCache) { if (entry != null && Objects.equals(DaoUtils.getUuid(entry.getValue().getPosition()), positionUuid)) { return entry.getValue(); } } } return null; } // Make a defensive copy of a person and their position private Person copyPerson(Person person) { if (person != null) { try { final Person personCopy = new Person(); for (final String prop : allFields) { PropertyUtils.setSimpleProperty(personCopy, prop, PropertyUtils.getSimpleProperty(person, prop)); } final Position position = person.getPosition(); if (position != null) { final Position positionCopy = new Position(); for (final String prop : PositionDao.fields) { PropertyUtils.setSimpleProperty(positionCopy, prop, PropertyUtils.getSimpleProperty(position, prop)); } personCopy.setPosition(positionCopy); } return personCopy; } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { logger.warn("Could not copy person", e); } } return null; } @InTransaction public int mergePeople(Person winner, Person loser) { // delete duplicates where other is primary, or where neither is primary getDbHandle().createUpdate("DELETE FROM \"reportPeople\" WHERE (" + "\"personUuid\" = :loserUuid AND \"reportUuid\" IN (" + "SELECT \"reportUuid\" FROM \"reportPeople\" WHERE \"personUuid\" = :winnerUuid AND \"isPrimary\" = :isPrimary" + ")) OR (\"personUuid\" = :winnerUuid AND \"reportUuid\" IN (" + "SELECT \"reportUuid\" FROM \"reportPeople\" WHERE \"personUuid\" = :loserUuid AND \"isPrimary\" = :isPrimary" + ")) OR (" + "\"personUuid\" = :loserUuid AND \"isPrimary\" != :isPrimary AND \"reportUuid\" IN (" + "SELECT \"reportUuid\" FROM \"reportPeople\" WHERE \"personUuid\" = :winnerUuid AND \"isPrimary\" != :isPrimary" + "))").bind("winnerUuid", winner.getUuid()).bind("loserUuid", loser.getUuid()) .bind("isPrimary", true).execute(); // update report attendance, should now be unique getDbHandle().createUpdate( "UPDATE \"reportPeople\" SET \"personUuid\" = :winnerUuid WHERE \"personUuid\" = :loserUuid") .bind("winnerUuid", winner.getUuid()).bind("loserUuid", loser.getUuid()).execute(); // update approvals this person might have done getDbHandle().createUpdate( "UPDATE \"reportActions\" SET \"personUuid\" = :winnerUuid WHERE \"personUuid\" = :loserUuid") .bind("winnerUuid", winner.getUuid()).bind("loserUuid", loser.getUuid()).execute(); // report author update getDbHandle() .createUpdate( "UPDATE reports SET \"authorUuid\" = :winnerUuid WHERE \"authorUuid\" = :loserUuid") .bind("winnerUuid", winner.getUuid()).bind("loserUuid", loser.getUuid()).execute(); // comment author update getDbHandle() .createUpdate( "UPDATE comments SET \"authorUuid\" = :winnerUuid WHERE \"authorUuid\" = :loserUuid") .bind("winnerUuid", winner.getUuid()).bind("loserUuid", loser.getUuid()).execute(); // update position history getDbHandle().createUpdate( "UPDATE \"peoplePositions\" SET \"personUuid\" = :winnerUuid WHERE \"personUuid\" = :loserUuid") .bind("winnerUuid", winner.getUuid()).bind("loserUuid", loser.getUuid()).execute(); // update note authors getDbHandle() .createUpdate( "UPDATE \"notes\" SET \"authorUuid\" = :winnerUuid WHERE \"authorUuid\" = :loserUuid") .bind("winnerUuid", winner.getUuid()).bind("loserUuid", loser.getUuid()).execute(); // update note related objects where we don't already have the same note for the winnerUuid getDbHandle().createUpdate( "UPDATE \"noteRelatedObjects\" SET \"relatedObjectUuid\" = :winnerUuid WHERE \"relatedObjectUuid\" = :loserUuid" + " AND \"noteUuid\" NOT IN (" + "SELECT \"noteUuid\" FROM \"noteRelatedObjects\" WHERE \"relatedObjectUuid\" = :winnerUuid" + ")") .bind("winnerUuid", winner.getUuid()).bind("loserUuid", loser.getUuid()).execute(); // now delete obsolete note related objects getDbHandle() .createUpdate("DELETE FROM \"noteRelatedObjects\" WHERE \"relatedObjectUuid\" = :loserUuid") .bind("loserUuid", loser.getUuid()).execute(); // delete the person! final int nr = getDbHandle().createUpdate("DELETE FROM people WHERE uuid = :loserUuid") .bind("loserUuid", loser.getUuid()).execute(); // E.g. positions may have been updated, so evict from the cache evictFromCache(winner); evictFromCache(loser); return nr; } public CompletableFuture<List<PersonPositionHistory>> getPositionHistory( Map<String, Object> context, String personUuid) { return new ForeignKeyFetcher<PersonPositionHistory>() .load(context, FkDataLoaderKey.PERSON_PERSON_POSITION_HISTORY, personUuid) .thenApply(l -> PersonPositionHistory.getDerivedHistory(l)); } @InTransaction public void clearEmptyBiographies() { // Search all people with a not null biography field final PersonSearchQuery query = new PersonSearchQuery(); query.setPageSize(0); query.setHasBiography(true); final List<Person> persons = search(query).getList(); // For each person with an empty html biography, set this one to null for (final Person p : persons) { if (Utils.isEmptyHtml(p.getBiography())) { getDbHandle() .createUpdate( "/* updatePersonBiography */ UPDATE people SET biography = NULL WHERE uuid = :uuid") .bind("uuid", p.getUuid()).execute(); AnetAuditLogger.log("Person {} has an empty html biography, set it to null", p); } } } }
package mx.nic.rdap.sql; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; import mx.nic.rdap.db.exception.InitializationException; import mx.nic.rdap.db.service.DataAccessService; /** * Manage the Datasource used in the database connection */ public class DatabaseSession { private static final Logger logger = Logger.getLogger(DataAccessService.class.getName()); /** From the migrator's perspective, this is the "destination" database. */ private static DataSource rdapDataSource; /** From the migrator's perspective, this is the "source" database. */ private static DataSource originDataSource; private static void testDatabase(BasicDataSource ds, String testQuery) throws SQLException { try (Connection connection = ds.getConnection(); Statement statement = connection.createStatement();) { logger.log(Level.INFO, "Executing QUERY: " + testQuery); ResultSet resultSet = statement.executeQuery(testQuery); if (!resultSet.next()) { throw new SQLException("'" + testQuery + "' returned no rows."); } int result = resultSet.getInt(1); if (result != 1) { throw new SQLException("'" + testQuery + "' returned " + result); } } } public static Connection getRdapConnection() throws SQLException { return rdapDataSource.getConnection(); } public static Connection getMigrationConnection() throws SQLException { return originDataSource.getConnection(); } public static void initRdapConnection(Properties config) throws InitializationException { /* * This code is rather awkward, I admit. * * The problem is, at compile time, the application does not know the * data access implementation, and the data access implementation does * not know the application. * * So we don't know for sure where the data source can be found, and the * application cannot tell us. There is no interface for the application * to provide us with a data source, because the data source is OUR * problem. From the app's perspective, it might not even exist. * * So what we're going to do is probe the candidate locations and stick * with what works. */ rdapDataSource = findRdapDataSource(config); if (rdapDataSource != null) { logger.info("Data source found."); return; } logger.info("I could not find the RDAP data source in the context. " + "This won't be a problem if I can find it in the configuration. Attempting that now... "); rdapDataSource = loadDataSourceFromProperties(config); } private static DataSource findRdapDataSource(Properties config) { Context context; try { context = new InitialContext(); } catch (NamingException e) { logger.log(Level.INFO, "I could not instance an initial context. " + "I will not be able to find the data source by JDNI name.", e); return null; } String jdniName = config.getProperty("db_resource_name"); if (jdniName != null) { return findRdapDataSource(context, jdniName); } // Try the default string. // In some server containers (such as Wildfly), the default string is "java:/comp/env/jdbc/rdap". // In other server containers (such as Payara), the string is "java:comp/env/jdbc/rdap". // In other server containers (such as Tomcat), it doesn't matter. DataSource result = findRdapDataSource(context, "java:/comp/env/jdbc/rdap"); if (result != null) { return result; } return findRdapDataSource(context, "java:comp/env/jdbc/rdap"); } private static DataSource findRdapDataSource(Context context, String jdniName) { logger.info("Attempting to find data source '" + jdniName + "'..."); try { return (DataSource) context.lookup(jdniName); } catch (NamingException e) { logger.info("Data source not found. Attempting something else..."); return null; } } public static void initOriginConnection(Properties config) throws InitializationException { originDataSource = loadDataSourceFromProperties(config); } private static DataSource loadDataSourceFromProperties(Properties config) throws InitializationException { String driverClassName = config.getProperty("driverClassName"); String url = config.getProperty("url"); if (driverClassName == null || url == null) { throw new InitializationException("I can't find a data source in the configuration."); } BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(driverClassName); dataSource.setUrl(url); dataSource.setUsername(config.getProperty("userName")); dataSource.setPassword(config.getProperty("password")); dataSource.setDefaultAutoCommit(false); String testQuery = config.getProperty("testQuery", "select 1"); try { testDatabase(dataSource, testQuery); } catch (SQLException e) { throw new InitializationException("The database connection test yielded failure.", e); } return dataSource; } public static void closeRdapDataSource() throws SQLException { if (rdapDataSource instanceof BasicDataSource) { ((BasicDataSource) rdapDataSource).close(); } } public static void closeOriginDataSource() throws SQLException { if (originDataSource instanceof BasicDataSource) { ((BasicDataSource) originDataSource).close(); } } }
package people; import java.math.BigInteger; import java.security.MessageDigest; import java.util.List; import javax.persistence.Entity; import javax.persistence.Id; import serverLogic.DatabaseUtil; import attendance.Absence; import attendance.AttendanceReport; import attendance.EarlyCheckOut; import attendance.Event; import attendance.Tardy; @Entity public class User { @Id private Long id; // Field to tell what they are private String type; // Student, Director, or TA // common fields private String netID; private String firstName; private String lastName; private String univID; private String hashedPassword; // student fields private String major; private String section; private int year; private String rank; private double grade; public String toHTML() { String ret = ""; ret += "<p>Name: " + firstName + " " + lastName + "</p>\n"; ret += "<p>NetID: " + netID + "</p>\n"; return ret; } public User(String netID, String password, String firstName, String lastName, String univID, String type, String major, String section, int year) { this.netID = netID; this.hashedPassword = password; this.firstName = firstName; this.lastName = lastName; this.univID = univID; this.type = type; this.id = (long) netID.hashCode(); this.major = major; this.section = section; this.year = year; this.rank = "|"; this.grade = 100.00; } public String toString() { return netID + " " + firstName + " " + lastName + " " + univID + " " + major + " " + section + " " + year + " " + rank + " " + grade; } public String toStringTA() { return "TA" + " " + netID + " " + firstName + " " + lastName + " " + hashedPassword + " " + rank; } public void addTardy(Tardy newTardy) { // get student's attendance report, add the tardy, and re-store it in // the database AttendanceReport report = getAttendanceReport(); report.addTardy(newTardy); DatabaseUtil.addAttendanceReport(report); } public void addAbsence(Absence newAbsence) { // get student's attendance report, add the absence, and re-store it in // the database AttendanceReport report = getAttendanceReport(); report.addAbsence(newAbsence); DatabaseUtil.addAttendanceReport(report); } public AttendanceReport getAttendanceReport() { return DatabaseUtil.getAttendanceReport(netID); } public List<Absence> getAbsences() { return getAttendanceReport().getAbsences(); } public List<Tardy> getTardies() { return getAttendanceReport().getTardies(); } public List<EarlyCheckOut> getEarlyCheckOuts() { return getAttendanceReport().getEarlyCheckOuts(); } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } public String getSection() { return section; } public void setSection(String section) { this.section = section; } public String getRank() { return rank; } public void setRank(String rank) { this.rank = rank; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getNetID() { return netID; } public void setNetID(String netID) { this.netID = netID; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getUnivID() { return univID; } public void setUnivID(String univID) { this.univID = univID; } public String getHashedPassword() { return hashedPassword; } public void setHashedPassword(String hashedPassword) { this.hashedPassword = hashedPassword; } public void setGrade(double grade) { this.grade = grade; } public double getGrade() { return grade; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public String getLetterGrade() { String letterGrade; if (grade >= 90.00) letterGrade = "A"; else if (grade >= 80.00) letterGrade = "B"; else if (grade >= 70.00) letterGrade = "C"; else if (grade >= 60.00) letterGrade = "D"; else letterGrade = "F"; if (grade % 10 > (20.0 / 3.0) && grade < 90.00) letterGrade += "+"; else if (grade % 10 < (10.0 / 3.0) && grade < 100.00) letterGrade += "-"; return letterGrade; } public void calculateGrade() { // big crazy function to calculate grade based off absences, tardies, // and excuses. } /** * Returns a string with the status of this user for the given event * * @author Curtis Ullerich * @date 4/9/12 * @return */ public String eventStatus(Event event) { List<Tardy> tardies = this.getTardies(); List<EarlyCheckOut> ecos = this.getEarlyCheckOuts(); List<Absence> absences = this.getAbsences(); String status = "present"; for (Absence a : absences) { if (a.isDuringEvent(event)) { status = a.getStatus() + " " + "absent"; break; } } for (EarlyCheckOut e : ecos) { if (e.isDuringEvent(event)) { status = e.getStatus() + " " + "early checkout"; break; } } for (Tardy t : tardies) { if (t.isDuringEvent(event)) { status = t.getStatus() + " " + "tardy"; break; } } return status; } // public long hash(String netID) { // try { // MessageDigest cript = MessageDigest.getInstance("SHA-1"); // cript.reset(); // cript.update(netID.getBytes("utf8")); // BigInteger bigot = new BigInteger(cript.digest()); // // Something about things // return bigot.longValue(); // } catch (Exception e) { // e.printStackTrace(); // return 0; @Override public boolean equals(Object other) { if (other == null) return false; if (other.getClass() != this.getClass()) return false; User o = (User) other; return o.getNetID().equalsIgnoreCase(this.netID); } @Override public int hashCode() { return netID.hashCode(); } public String getAttendanceHtml() { // TODO // loop through all events and print the information in the format below return "<tr><td>8/21</td><td> </td><td> </td><td> </td><td> </td><td><button onClick=\"sendMeToMyMessages();\">Messages</button></tr>"; } }
package net.darkhax.bookshelf; import java.util.Random; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import net.darkhax.bookshelf.command.ArgumentTypeLootTable; import net.darkhax.bookshelf.command.ArgumentTypeMod; import net.darkhax.bookshelf.crafting.block.BlockIngredient; import net.darkhax.bookshelf.crafting.block.BlockIngredientAny; import net.darkhax.bookshelf.crafting.block.BlockIngredientCheckBlock; import net.darkhax.bookshelf.crafting.block.BlockIngredientCheckState; import net.darkhax.bookshelf.crafting.block.BlockIngredientCheckTag; import net.darkhax.bookshelf.crafting.item.IngredientEnchantmentType; import net.darkhax.bookshelf.crafting.item.IngredientModid; import net.darkhax.bookshelf.crafting.item.IngredientPotion; import net.darkhax.bookshelf.crafting.item.IngredientToolType; import net.darkhax.bookshelf.crafting.predicate.ItemPredicateIngredient; import net.darkhax.bookshelf.crafting.predicate.ItemPredicateModid; import net.darkhax.bookshelf.crafting.recipes.ShapedRecipeDamaging; import net.darkhax.bookshelf.crafting.recipes.ShapelessRecipeDamage; import net.darkhax.bookshelf.crafting.recipes.smithing.SmithingRecipeEnchantment; import net.darkhax.bookshelf.crafting.recipes.smithing.SmithingRecipeFont; import net.darkhax.bookshelf.crafting.recipes.smithing.SmithingRecipeRepairCost; import net.darkhax.bookshelf.internal.command.ArgumentTypeHandOutput; import net.darkhax.bookshelf.internal.command.BookshelfCommands; import net.darkhax.bookshelf.loot.condition.CheckBiomeTag; import net.darkhax.bookshelf.loot.condition.CheckDimensionId; import net.darkhax.bookshelf.loot.condition.CheckEnchantability; import net.darkhax.bookshelf.loot.condition.CheckEnergy; import net.darkhax.bookshelf.loot.condition.CheckHarvestLevel; import net.darkhax.bookshelf.loot.condition.CheckItem; import net.darkhax.bookshelf.loot.condition.CheckPower; import net.darkhax.bookshelf.loot.condition.CheckRaid; import net.darkhax.bookshelf.loot.condition.CheckRarity; import net.darkhax.bookshelf.loot.condition.CheckSlimeChunk; import net.darkhax.bookshelf.loot.condition.CheckStructure; import net.darkhax.bookshelf.loot.condition.CheckVillage; import net.darkhax.bookshelf.loot.condition.EntityIsMob; import net.darkhax.bookshelf.loot.modifier.ModifierAddItem; import net.darkhax.bookshelf.loot.modifier.ModifierClear; import net.darkhax.bookshelf.loot.modifier.ModifierConvert; import net.darkhax.bookshelf.loot.modifier.ModifierRecipe; import net.darkhax.bookshelf.loot.modifier.ModifierSilkTouch; import net.darkhax.bookshelf.registry.RegistryHelper; import net.minecraft.advancements.criterion.ItemPredicate; import net.minecraft.command.arguments.ArgumentSerializer; import net.minecraft.enchantment.EnchantmentType; import net.minecraft.item.AxeItem; import net.minecraft.item.HoeItem; import net.minecraft.item.PickaxeItem; import net.minecraft.item.ShearsItem; import net.minecraft.item.ShovelItem; import net.minecraft.item.SwordItem; import net.minecraft.loot.LootConditionType; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.ToolType; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; @Mod(Bookshelf.MOD_ID) public final class Bookshelf { public static Bookshelf instance; // System Constants public static final Random RANDOM = new Random(); public static final String NEW_LINE = System.getProperty("line.separator"); // Mod Constants public static final String MOD_ID = "bookshelf"; public static final String MOD_NAME = "Bookshelf"; public static final Logger LOG = LogManager.getLogger(MOD_NAME); private final RegistryHelper registry = new RegistryHelper(MOD_ID, LOG); public final LootConditionType conditionIsMob; public final LootConditionType conditionCheckVillage; public final LootConditionType conditionCheckStructure; public final LootConditionType conditionCheckSlimeChunk; public final LootConditionType conditionCheckRarity; public final LootConditionType conditionCheckRaid; public final LootConditionType conditionCheckPower; public final LootConditionType conditionCheckItem; public final LootConditionType conditionCheckHarvestLevel; public final LootConditionType conditionCheckEnergy; public final LootConditionType conditionCheckEnchantability; public final LootConditionType conditionCheckBiomeTag; public final LootConditionType conditionCheckDimension; public Bookshelf() { // Commands new BookshelfCommands(this.registry); // Command arguments this.registry.commands.registerCommandArgument("enum", ArgumentTypeHandOutput.class, new ArgumentTypeHandOutput.Serialzier()); this.registry.commands.registerCommandArgument("mod", ArgumentTypeMod.class, new ArgumentSerializer<>( () -> ArgumentTypeMod.INSTACE)); this.registry.commands.registerCommandArgument("loot", ArgumentTypeLootTable.class, new ArgumentSerializer<>( () -> ArgumentTypeLootTable.INSTACE)); // Loot Modifier this.registry.lootModifiers.register(ModifierClear.SERIALIZER, "clear"); this.registry.lootModifiers.register(ModifierSilkTouch.SERIALIZER, "silk_touch"); this.registry.lootModifiers.register(ModifierConvert.SERIALIZER, "convert"); this.registry.lootModifiers.register(ModifierRecipe.CRAFTING, "crafting"); this.registry.lootModifiers.register(ModifierRecipe.SMELTING, "smelting"); this.registry.lootModifiers.register(ModifierRecipe.BLASTING, "blasting"); this.registry.lootModifiers.register(ModifierRecipe.SMOKING, "smoking"); this.registry.lootModifiers.register(ModifierRecipe.CAMPFIRE, "campfire_cooking"); this.registry.lootModifiers.register(ModifierRecipe.STONECUT, "stonecutting"); this.registry.lootModifiers.register(ModifierRecipe.SMITHING, "smithing"); this.registry.lootModifiers.register(ModifierAddItem.SERIALIZER, "add_item"); // Loot Conditions this.conditionIsMob = this.registry.lootConditions.register(EntityIsMob.SERIALIZER, "is_mob"); this.conditionCheckVillage = this.registry.lootConditions.register(CheckVillage.SERIALIZER, "check_village"); this.conditionCheckStructure = this.registry.lootConditions.register(CheckStructure.SERIALIZER, "check_structure"); this.conditionCheckSlimeChunk = this.registry.lootConditions.register(CheckSlimeChunk.SERIALIZER, "slime_chunk"); this.conditionCheckRarity = this.registry.lootConditions.register(CheckRarity.SERIALIZER, "check_rarity"); this.conditionCheckRaid = this.registry.lootConditions.register(CheckRaid.SERIALIZER, "check_raid"); this.conditionCheckPower = this.registry.lootConditions.register(CheckPower.SERIALIZER, "check_power"); this.conditionCheckItem = this.registry.lootConditions.register(CheckItem.SERIALIZER, "check_item"); this.conditionCheckHarvestLevel = this.registry.lootConditions.register(CheckHarvestLevel.SERIALIZER, "check_harvest_level"); this.conditionCheckEnergy = this.registry.lootConditions.register(CheckEnergy.SERIALIZER, "check_forge_energy"); this.conditionCheckEnchantability = this.registry.lootConditions.register(CheckEnchantability.SERIALIZER, "check_enchantability"); this.conditionCheckBiomeTag = this.registry.lootConditions.register(CheckBiomeTag.SERIALIZER, "check_biome_tag"); this.conditionCheckDimension = this.registry.lootConditions.register(CheckDimensionId.SERIALIZER, "check_dimension"); // Item Predicates ItemPredicate.register(new ResourceLocation("bookshelf", "modid"), ItemPredicateModid::fromJson); ItemPredicate.register(new ResourceLocation("bookshelf", "ingredient"), ItemPredicateIngredient::fromJson); // Recipe Serializers this.registry.recipeSerializers.register(ShapedRecipeDamaging.SERIALIZER, "crafting_shaped_with_damage"); this.registry.recipeSerializers.register(ShapelessRecipeDamage.SERIALIZER, "crafting_shapeless_with_damage"); this.registry.recipeSerializers.register(SmithingRecipeFont.SERIALIZER, "smithing_font"); this.registry.recipeSerializers.register(SmithingRecipeRepairCost.SERIALIZER, "smithing_repair_cost"); this.registry.recipeSerializers.register(SmithingRecipeEnchantment.SERIALIZER, "smithing_enchant"); // Ingredients this.registry.ingredients.register("potion", IngredientPotion.SERIALIZER); this.registry.ingredients.register("modid", IngredientModid.SERIALIZER); this.registry.ingredients.register("any_axe", IngredientToolType.create(i -> i instanceof AxeItem, ToolType.AXE)); this.registry.ingredients.register("any_hoe", IngredientToolType.create(i -> i instanceof HoeItem, ToolType.HOE)); this.registry.ingredients.register("any_pickaxe", IngredientToolType.create(i -> i instanceof PickaxeItem, ToolType.PICKAXE)); this.registry.ingredients.register("any_shovel", IngredientToolType.create(i -> i instanceof ShovelItem, ToolType.SHOVEL)); this.registry.ingredients.register("any_sword", IngredientToolType.create(i -> i instanceof SwordItem, null)); this.registry.ingredients.register("any_shear", IngredientToolType.create(i -> i instanceof ShearsItem, null)); this.registry.ingredients.register("enchant_armor", IngredientEnchantmentType.create(EnchantmentType.ARMOR)); this.registry.ingredients.register("enchant_armor_feet", IngredientEnchantmentType.create(EnchantmentType.ARMOR_FEET)); this.registry.ingredients.register("enchant_armor_legs", IngredientEnchantmentType.create(EnchantmentType.ARMOR_LEGS)); this.registry.ingredients.register("enchant_armor_chest", IngredientEnchantmentType.create(EnchantmentType.ARMOR_CHEST)); this.registry.ingredients.register("enchant_armor_head", IngredientEnchantmentType.create(EnchantmentType.ARMOR_HEAD)); this.registry.ingredients.register("enchant_weapon", IngredientEnchantmentType.create(EnchantmentType.WEAPON)); this.registry.ingredients.register("enchant_digger", IngredientEnchantmentType.create(EnchantmentType.DIGGER)); this.registry.ingredients.register("enchant_fishing_rod", IngredientEnchantmentType.create(EnchantmentType.FISHING_ROD)); this.registry.ingredients.register("enchant_trident", IngredientEnchantmentType.create(EnchantmentType.TRIDENT)); this.registry.ingredients.register("enchant_breakable", IngredientEnchantmentType.create(EnchantmentType.BREAKABLE)); this.registry.ingredients.register("enchant_bow", IngredientEnchantmentType.create(EnchantmentType.BOW)); this.registry.ingredients.register("enchant_wearable", IngredientEnchantmentType.create(EnchantmentType.WEARABLE)); this.registry.ingredients.register("enchant_crossbow", IngredientEnchantmentType.create(EnchantmentType.CROSSBOW)); this.registry.ingredients.register("enchant_vanishable", IngredientEnchantmentType.create(EnchantmentType.VANISHABLE)); // Block Ingredients BlockIngredient.register(BlockIngredientAny.SERIALIZER, BlockIngredientAny.ID); BlockIngredient.register(BlockIngredientCheckState.SERIALIZER, BlockIngredientCheckState.ID); BlockIngredient.register(BlockIngredientCheckBlock.SERIALIZER, BlockIngredientCheckBlock.ID); BlockIngredient.register(BlockIngredientCheckTag.SERIALIZER, BlockIngredientCheckTag.ID); this.registry.initialize(FMLJavaModLoadingContext.get().getModEventBus()); } }
package net.ilexiconn.magister; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import net.ilexiconn.magister.adapter.ProfileAdapter; import net.ilexiconn.magister.adapter.StudyAdapter; import net.ilexiconn.magister.container.*; import net.ilexiconn.magister.container.sub.Privilege; import net.ilexiconn.magister.exeption.PrivilegeException; import net.ilexiconn.magister.handler.*; import net.ilexiconn.magister.util.AndroidUtil; import net.ilexiconn.magister.util.HttpUtil; import net.ilexiconn.magister.util.LogUtil; import net.ilexiconn.magister.util.android.ImageContainer; import javax.net.ssl.HttpsURLConnection; import java.io.IOException; import java.net.URL; import java.security.InvalidParameterException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * The main API class. You can get a new instance by running {@link Magister#login(School, String, String)}. * * @author iLexiconn * @since 0.1.0 */ public class Magister { public static final String VERSION = "0.1.0-SNAPSHOT"; public Gson gson = new GsonBuilder() .registerTypeAdapter(Profile.class, new ProfileAdapter()) .registerTypeAdapter(Study[].class, new StudyAdapter()) .create(); public School school; public User user; public Version version; public Session session; public Profile profile; public Study[] studies; public Study currentStudy; private List<IHandler> handlerList = new ArrayList<IHandler>(); protected Magister() { handlerList.add(new GradeHandler(this)); handlerList.add(new PresenceHandler(this)); handlerList.add(new ContactHandler(this)); handlerList.add(new MessageHandler(this)); handlerList.add(new AppointmentHandler(this)); handlerList.add(new ELOHandler(this)); } /** * Create a new {@link Magister} instance by logging in. Will return null if login fails. * * @param school the {@link School} instance. Can't be null. * @param username the username of the profile. Can't be null. * @param password the password of the profile. Can't be null. * @return the new {@link Magister} instance, null if login fails. * @throws IOException if there is no active internet connection. * @throws ParseException if parsing the date fails. * @throws InvalidParameterException if one of the arguments is null. */ public static Magister login(School school, String username, String password) throws IOException, ParseException, InvalidParameterException { if (school == null || username == null || username.isEmpty() || password == null || password.isEmpty()) { throw new InvalidParameterException("Parameters can't be null or empty!"); } Magister magister = new Magister(); AndroidUtil.checkAndroid(); magister.school = school; magister.version = magister.gson.fromJson(HttpUtil.httpGet(school.url + "/api/versie"), Version.class); magister.user = new User(username, password, true); magister.logout(); Map<String, String> nameValuePairMap = magister.gson.fromJson(magister.gson.toJson(magister.user), new TypeToken<Map<String, String>>() { }.getType()); magister.session = magister.gson.fromJson(HttpUtil.httpPost(school.url + "/api/sessies/huidige", nameValuePairMap), Session.class); if (!magister.session.state.equals("active")) { LogUtil.printError("Invalid credentials", new InvalidParameterException()); return null; } magister.profile = magister.gson.fromJson(HttpUtil.httpGet(school.url + "/api/account"), Profile.class); magister.studies = magister.gson.fromJson(HttpUtil.httpGet(school.url + "/api/personen/" + magister.profile.id + "/aanmeldingen"), Study[].class); DateFormat format = new SimpleDateFormat("y-m-d", Locale.ENGLISH); Date now = new Date(); for (Study study : magister.studies) { if (format.parse(study.endDate.substring(0, 10)).after(now)) { magister.currentStudy = study; } } return magister; } /** * Refresh the session of this magister instance by logging in again. * * @return the current session. * @throws IOException if there is no active internet connection. */ public Session login() throws IOException { logout(); Map<String, String> nameValuePairMap = gson.fromJson(gson.toJson(user), new TypeToken<Map<String, String>>() { }.getType()); session = gson.fromJson(HttpUtil.httpPost(school.url + "/api/sessies/huidige", nameValuePairMap), Session.class); return session; } /** * Logout the current session. You have to wait a few seconds before logging in again. * * @throws IOException if there is no active internet connection. */ public void logout() throws IOException { HttpUtil.httpDelete(school.url + "/api/sessies/huidige"); } /** * Get the current session of this magister instance. Use this to check if the user is still logged in. * * @return the current session. * @throws IOException if there is no active internet connection. */ public Session getCurrentSession() throws IOException { return gson.fromJson(HttpUtil.httpGet(school.url + "/api/sessies/huidige"), Session.class); } /** * Check if this user has the following privilege. * * @param privilege the privilege name. * @return true if the profile has the privilege. */ public boolean hasPrivilege(String privilege) { for (Privilege p : profile.privileges) { if (p.name.equals(privilege)) { return true; } } return false; } /** * Get the current profile picture in the default size. * * @return the current profile picture in the default size. * @throws IOException if there is no active internet connection. */ public ImageContainer getImage() throws IOException { return getImage(42, 64, false); } /** * Get the current profile picture. * * @param width the width. * @param height the height. * @param crop true if not in default ratio. * @return the current profile picture. * @throws IOException if there is no active internet connection. */ public ImageContainer getImage(int width, int height, boolean crop) throws IOException { String url = school.url + "/api/personen/" + profile.id + "/foto" + (width != 42 || height != 64 || crop ? "?width=" + width + "&height=" + height + "&crop=" + crop : ""); HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Cookie", HttpUtil.getCurrentCookies()); connection.connect(); try { return new ImageContainer(connection.getInputStream()); } catch (ClassNotFoundException e) { LogUtil.printError("Unable to load image class.", e); return null; } } /** * Change the password of the current profile. * * @param oldPassword the current password. * @param newPassword the new password. * @param newPassword2 the new password. * @return a String with the response. 'Successful' if the password changed successfully. * @throws IOException if there is no active internet connection. * @throws InvalidParameterException if one of the parameters is null or empty, or when the two new passwords aren't * the same. * @throws PrivilegeException if the profile doesn't have the privilege to perform this action. */ public String changePassword(String oldPassword, String newPassword, String newPassword2) throws IOException, InvalidParameterException, PrivilegeException { if (!hasPrivilege("WachtwoordWijzigen")) { throw new PrivilegeException(); } if (oldPassword == null || oldPassword.isEmpty() || newPassword == null || newPassword.isEmpty() || newPassword2 == null || newPassword2.isEmpty()) { throw new InvalidParameterException("Parameters can't be null or empty!"); } else if (!newPassword.equals(newPassword2)) { throw new InvalidParameterException("New passwords don't match!"); } Map<String, String> nameValuePairMap = new HashMap<String, String>(); nameValuePairMap.put("HuidigWachtwoord", oldPassword); nameValuePairMap.put("NieuwWachtwoord", newPassword); nameValuePairMap.put("PersoonId", profile.id + ""); nameValuePairMap.put("WachtwoordBevestigen", newPassword2); Response response = gson.fromJson(HttpUtil.httpPost(school.url + "/api/personen/account/wachtwoordwijzigen?persoonId=" + profile.id, nameValuePairMap), Response.class); if (response == null) { user.password = newPassword; return "Successful"; } else { LogUtil.printError(response.message, new InvalidParameterException()); return response.message; } } /** * Get a handler instance from this magister instance. * * @param type the class of the handler. * @return the {@link IHandler} instance, null if it can't be found. * @throws PrivilegeException if the profile doesn't have the privilege to perform this action. */ public <T extends IHandler> T getHandler(Class<T> type) throws PrivilegeException { for (IHandler handler : handlerList) { if (handler.getClass() == type) { if (!hasPrivilege(handler.getPrivilege())) { throw new PrivilegeException(); } return type.cast(handler); } } return null; } }
package net.pixelcop.sewer; import java.util.HashMap; import java.util.Map; import net.pixelcop.sewer.sink.DfsSink; import net.pixelcop.sewer.sink.SequenceFileSink; import net.pixelcop.sewer.sink.TcpWriteableEventSink; import net.pixelcop.sewer.sink.debug.ConsoleSink; import net.pixelcop.sewer.sink.debug.DelayedOpenSink; import net.pixelcop.sewer.sink.debug.NullSink; import net.pixelcop.sewer.sink.durable.ReliableSequenceFileSink; import net.pixelcop.sewer.sink.durable.ReliableSink; import net.pixelcop.sewer.sink.durable.RollSink; @SuppressWarnings("rawtypes") public class SinkRegistry { private static final Map<String, Class> registry = new HashMap<String, Class>(); static { // endpoints register("dfs", DfsSink.class); register("seqfile", SequenceFileSink.class); register("reliableseq", ReliableSequenceFileSink.class); register("tcpwrite", TcpWriteableEventSink.class); // decorators register("reliable", ReliableSink.class); register("roll", RollSink.class); register("delayed_open", DelayedOpenSink.class); // debug register("null", NullSink.class); register("console", ConsoleSink.class); register("stdout", ConsoleSink.class); } public static final void register(String name, Class clazz) { registry.put(name.toLowerCase(), clazz); } public static Map<String, Class> getRegistry() { return registry; } }
/* * @(#) TemplateProcessor.java */ package net.pwall.xml; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import javax.xml.parsers.ParserConfigurationException; import net.pwall.el.Expression; import net.pwall.el.Functions; import net.pwall.el.SimpleVariable; import net.pwall.html.HTMLFormatter; import net.pwall.util.UserError; import org.w3c.dom.Attr; import org.w3c.dom.CDATASection; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.SAXException; import org.xml.sax.ext.DefaultHandler2; import org.xml.sax.helpers.AttributesImpl; /** * XML Template Processor for Java * * @author Peter Wall */ public class TemplateProcessor { // TODO list: // 1. Reconsider use of exceptions - make TemplateException a subclass of UserError? // 2. Implement <include> // 3. Consider <set> with contents - allocate element itself to a variable to allow access // to elements contained within it? // 4. In Expression - allow JavaScript object syntax? // e.g. <xt:set name="array" value="['a','b','c']"> // 5. Consider passing context object on each call - avoids potential error in unwinding // 6. Update namespace version number to 1.0 (or greater?) // 7. Consider a "for" attribute (or "while") to go with "if" // 8. Block use of <set> to modify an existing variable? // 9. Is <macro> the best name for this functionality? public static final String defaultNamespace = "http://pwall.net/xml/xt/0.1"; private static final String templateElementName = "template"; private static final String macroElementName = "macro"; private static final String errorElementName = "error"; private static final String doctypeElementName = "doctype"; private static final String includeElementName = "include"; private static final String setElementName = "set"; private static final String ifElementName = "if"; private static final String switchElementName = "switch"; private static final String caseElementName = "case"; private static final String forElementName = "for"; private static final String callElementName = "call"; private static final String paramElementName = "param"; private static final String commentElementName = "comment"; private static final String copyElementName = "copy"; private static final String interceptElementName = "intercept"; private static final String whitespaceAttrName = "whitespace"; private static final String outputAttrName = "output"; private static final String outputXML = "xml"; private static final String outputHTML = "html"; private static final String prefixAttrName = "prefix"; private static final String textAttrName = "text"; private static final String systemAttrName = "system"; private static final String publicAttrName = "public"; private static final String nameAttrName = "name"; private static final String documentAttrName = "document"; private static final String valueAttrName = "value"; private static final String testAttrName = "test"; private static final String collectionAttrName = "collection"; private static final String fromAttrName = "from"; private static final String toAttrName = "to"; private static final String byAttrName = "by"; private static final String elementAttrName = "element"; private static final String optionAttrName = "option"; private static final String idAttrName = "id"; private static final String ifAttrName = "if"; private static final String prefixYes = "yes"; private static final String prefixNo = "no"; private static final String whitespaceNone = "none"; private static final String whitespaceAll = "all"; private static final String whitespaceIndent = "indent"; private static final String optionInclude = "include"; private Document dom; private Expression.Parser parser; private TemplateContext context; private String namespace; private String whitespace; private boolean prefixXML; public TemplateProcessor(Document dom) { this.dom = Objects.requireNonNull(dom); parser = new Expression.Parser(); parser.setConditionalAllowed(true); context = new TemplateContext(null, dom.getDocumentElement()); namespace = defaultNamespace; whitespace = null; prefixXML = false; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public String getWhitespace() { return whitespace; } public void setWhitespace(String whitespace) throws TemplateException { if (!(whitespaceNone.equalsIgnoreCase(whitespace) || whitespaceAll.equalsIgnoreCase(whitespace) || whitespaceIndent.equalsIgnoreCase(whitespace))) throw new TemplateException("Illegal whitespace option - " + whitespace); this.whitespace = whitespace; } public boolean isPrefixXML() { return prefixXML; } public void setPrefixXML(boolean prefixXML) { this.prefixXML = prefixXML; } public void setPrefixXML(String prefixXML) throws TemplateException { if (!(prefixYes.equalsIgnoreCase(prefixXML) || prefixNo.equalsIgnoreCase(prefixXML))) throw new TemplateException("Illegal prefix option - " + prefixXML); setPrefixXML(prefixYes.equalsIgnoreCase(prefixXML)); } public void setVariable(String identifier, Object object) { context.setVariable(identifier, object); } public void addNamespace(String uri, String namespace) { context.addNamespace(uri, namespace); } public void process(OutputStream os) throws Expression.ExpressionException { Element documentElement = dom.getDocumentElement(); if (XML.matchNS(documentElement, templateElementName, namespace)) { String whitespaceOption = substAttr(documentElement, whitespaceAttrName); if (!isEmpty(whitespaceOption)) setWhitespace(whitespaceOption); String outputAttr = substAttr(documentElement, outputAttrName); if (!isEmpty(outputAttr)) { if (outputAttr.equalsIgnoreCase(outputXML)) { String prefixAttr = substAttr(documentElement, prefixAttrName); if (!isEmpty(prefixAttr)) setPrefixXML(prefixAttr); processXML(os); } else if (outputAttr.equalsIgnoreCase(outputHTML)) processHTML(os); else throw new TemplateException(documentElement, "Illegal " + outputAttrName + ": " + outputAttr); } else processXML(os); } else processXML(os); } public void processXML(OutputStream os) throws Expression.ExpressionException { try (XMLFormatter formatter = new XMLFormatter(os)) { if (whitespaceNone.equalsIgnoreCase(whitespace)) formatter.setWhitespace(XMLFormatter.Whitespace.NONE); else if (whitespaceAll.equalsIgnoreCase(whitespace)) formatter.setWhitespace(XMLFormatter.Whitespace.ALL); else if (whitespaceIndent.equalsIgnoreCase(whitespace)) formatter.setWhitespace(XMLFormatter.Whitespace.INDENT); if (prefixXML) formatter.prefix(); formatter.startDocument(); Element documentElement = dom.getDocumentElement(); if (XML.matchNS(documentElement, templateElementName, namespace)) processElementContents(documentElement, formatter, false); else processElement(documentElement, formatter); formatter.endDocument(); } catch (IOException ioe) { throw new RuntimeException("Unexpected I/O exception", ioe); } catch (SAXException saxe) { throw new RuntimeException("Unexpected SAX exception", saxe); } } public void processHTML(OutputStream os) throws Expression.ExpressionException { try (HTMLFormatter formatter = new HTMLFormatter(os)) { if (whitespaceNone.equalsIgnoreCase(whitespace)) formatter.setWhitespace(HTMLFormatter.Whitespace.NONE); else if (whitespaceAll.equalsIgnoreCase(whitespace)) formatter.setWhitespace(HTMLFormatter.Whitespace.ALL); else if (whitespaceIndent.equalsIgnoreCase(whitespace)) formatter.setWhitespace(HTMLFormatter.Whitespace.INDENT); formatter.startDocument(); Element documentElement = dom.getDocumentElement(); if (XML.matchNS(documentElement, templateElementName, namespace)) processElementContents(documentElement, formatter, false); else processElement(documentElement, formatter); formatter.endDocument(); } catch (IOException ioe) { throw new RuntimeException("Unexpected I/O exception", ioe); } catch (SAXException saxe) { throw new RuntimeException("Unexpected SAX exception", saxe); } } private void processElement(Element element, DefaultHandler2 formatter) throws Expression.ExpressionException { String test = element.getAttributeNS(namespace, ifAttrName); String substTest = subst(test); if (!isEmpty(substTest)) { try { if (!parser.parseExpression(substTest, context).asBoolean()) return; } catch (Exception e) { throw new TemplateException("Error in \"if\" attribute - " + test + '\n' + e.getMessage()); } } if (XML.matchNS(element, errorElementName, namespace)) processError(element, formatter); else if (XML.matchNS(element, doctypeElementName, namespace)) processDoctype(element, formatter); else if (XML.matchNS(element, includeElementName, namespace)) processInclude(element, formatter); else if (XML.matchNS(element, setElementName, namespace)) processSet(element, formatter); else if (XML.matchNS(element, ifElementName, namespace)) processIf(element, formatter); else if (XML.matchNS(element, switchElementName, namespace)) processSwitch(element, formatter); else if (XML.matchNS(element, forElementName, namespace)) processFor(element, formatter); else if (XML.matchNS(element, callElementName, namespace)) processCall(element, formatter); else if (XML.matchNS(element, commentElementName, namespace)) processComment(element, formatter); else if (XML.matchNS(element, copyElementName, namespace)) processCopy(element, formatter); else outputElement(element, formatter); } private void processElementContents(Element element, DefaultHandler2 formatter, boolean trim) throws Expression.ExpressionException { NodeList childNodes = element.getChildNodes(); int start = 0; int end = childNodes.getLength(); if (trim) { while (start < end && isCommentOrEmpty(childNodes.item(start))) start++; while (start < end && isCommentOrEmpty(childNodes.item(end - 1))) end } for (int i = start, n = end; i < n; i++) { Node childNode = childNodes.item(i); if (childNode.getNodeType() == Node.ELEMENT_NODE && XML.matchNS((Element)childNode, macroElementName, namespace)) context.addMacro((Element)childNode); } for (int i = start, n = end; i < n; i++) { Node childNode = childNodes.item(i); if (childNode.getNodeType() == Node.ELEMENT_NODE) { if (!XML.matchNS((Element)childNode, macroElementName, namespace)) processElement((Element)childNode, formatter); } else if (childNode.getNodeType() == Node.TEXT_NODE) { String data = ((Text)childNode).getData(); if (trim) { if (i == start) data = trimLeading(data); if (i == n - 1) data = trimTrailing(data); } outputText(data, formatter); } } } private void processElementContentsNewContext(Element element, DefaultHandler2 formatter, boolean trim) throws Expression.ExpressionException { context = new TemplateContext(context, element); processElementContents(element, formatter, trim); context = context.getParent(); } private void processError(Element element, @SuppressWarnings("unused") DefaultHandler2 formatter) throws Expression.ExpressionException { // TODO check - is this how we want to handle this? String text = substAttr(element, textAttrName); throw new TemplateException(element, !isEmpty(text) ? text : "Error directive"); } private void processDoctype(Element element, DefaultHandler2 formatter) throws Expression.ExpressionException { String name = substAttr(element, nameAttrName); if (isEmpty(name)) throw new TemplateException(element, "Name missing"); String systemAttr = substAttr(element, systemAttrName); String publicAttr = substAttr(element, publicAttrName); try { formatter.startDTD(name, isEmpty(publicAttr) ? null : publicAttr, isEmpty(systemAttr) ? null : systemAttr); // TODO implement doctype internal subset? Otherwise check element empty? formatter.endDTD(); } catch (SAXException e) { throw new TemplateException(element, "Error processing document type"); } } private void processInclude(Element element, @SuppressWarnings("unused") DefaultHandler2 formatter) throws Expression.ExpressionException { // TODO implement <include> throw new TemplateException(element, "Can't handle <include>"); } private void processSet(Element element, @SuppressWarnings("unused") DefaultHandler2 formatter) throws Expression.ExpressionException { String name = substAttr(element, nameAttrName); if (!isValidName(name)) throw new TemplateException(element, "Name missing or invalid"); if (!isEmpty(element.getAttribute(documentAttrName))) throw new TemplateException(element, "Can't handle <set document= >"); // TODO should be able to do this in Java String value = substAttr(element, valueAttrName); try { Expression exp = parser.parseExpression(value, context); context.setVariable(name, exp.evaluate()); } catch (Expression.ExpressionException e) { throw new TemplateException(element, "Error in value - " + value + '\n' + e.getMessage()); } if (!isElementEmpty(element)) throw new TemplateException(element, "Illegal content"); // TODO allow content - if it contains elements, store as an ElementWrapper; // otherwise parse as JSON } private void processIf(Element element, DefaultHandler2 formatter) throws Expression.ExpressionException { String test = substAttr(element, testAttrName); if (isEmpty(test)) throw new TemplateException(element, "Test must be specified"); boolean testResult; try { testResult = parser.parseExpression(test, context).asBoolean(); } catch (Expression.ExpressionException e) { throw new TemplateException(element, "Error in test - " + test + '\n' + e.getMessage()); } if (testResult) processElementContentsNewContext(element, formatter, true); } private void processSwitch(Element element, DefaultHandler2 formatter) throws Expression.ExpressionException { NodeList childNodes = element.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node node = childNodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element childElement = (Element) node; if (XML.matchNS(childElement, caseElementName, namespace)) { String test = substAttr(childElement, testAttrName); boolean testResult = true; if (!isEmpty(test)) { try { testResult = parser.parseExpression(test, context).asBoolean(); } catch (Expression.ExpressionException e) { throw new TemplateException(childElement, "Error in test - " + test + '\n' + e.getMessage()); } } if (testResult) { processElementContentsNewContext(childElement, formatter, true); break; // note - doesn't check switch contents following successful case } } else throw new TemplateException(childElement, "Illegal element within <switch>"); } else if (!isCommentOrEmpty(node)) throw new TemplateException(element, "Illegal content within <switch>"); } } private void processFor(Element element, DefaultHandler2 formatter) throws Expression.ExpressionException { // TODO document not yet handled String name = substAttr(element, nameAttrName); String coll = substAttr(element, collectionAttrName); String from = substAttr(element, fromAttrName); String to = substAttr(element, toAttrName); String by = substAttr(element, byAttrName); if (!isEmpty(coll)) { if (!isEmpty(from) || !isEmpty(to) || !isEmpty(by)) throw new TemplateException(element, "<for> has illegal combination of attributes"); processForCollection(element, formatter, name, coll); } else if (!isEmpty(from) || !isEmpty(to) || !isEmpty(by)) { Object fromObject = isEmpty(from) ? null : parser.parseExpression(from, context).evaluate(); Object toObject = isEmpty(to) ? null : parser.parseExpression(to, context).evaluate(); Object byObject = isEmpty(by) ? null : parser.parseExpression(by, context).evaluate(); if (isFloating(fromObject) || isFloating(toObject) || isFloating(byObject)) processForSequenceFloat(element, formatter, name, fromObject, toObject, byObject); else processForSequenceInt(element, formatter, name, fromObject, toObject, byObject); } else throw new TemplateException(element, "<for> must specify iteration type"); } private void processForSequenceInt(Element element, DefaultHandler2 formatter, String name, Object from, Object to, Object by) throws Expression.ExpressionException { // note - "to" value is exclusive; from="0" to="4" will perform 0,1,2,3 int fromValue = from == null ? 0 : intValue(from, element, "<for> from value invalid"); int toValue = to == null ? 0 : intValue(to, element, "<for> to value invalid"); int byValue = by == null ? 1 : intValue(by, element, "<for> by value invalid"); if (byValue <= 0) throw new TemplateException(element, "<for> by value invalid"); if (fromValue != toValue) { context = new TemplateContext(context, element); if (fromValue < toValue) { do { if (!isEmpty(name)) context.setVariable(name, new Integer(fromValue)); processElementContents(element, formatter, true); fromValue += byValue; } while (fromValue < toValue); } else { do { if (!isEmpty(name)) context.setVariable(name, new Integer(fromValue)); processElementContents(element, formatter, true); fromValue -= byValue; } while (fromValue > toValue); } context = context.getParent(); } } private int intValue(Object obj, Element element, String msg) throws TemplateException { try { return Expression.asInt(obj); } catch (Expression.IntCoercionException e) { throw new TemplateException(element, msg); } } private void processForSequenceFloat(Element element, DefaultHandler2 formatter, String name, Object from, Object to, Object by) throws Expression.ExpressionException { // note - "to" value is exclusive; from="0" to="4" will perform 0,1,2,3 double fromValue = from == null ? 0.0 : doubleValue(from, element, "<for> from value invalid"); double toValue = to == null ? 0.0 : doubleValue(to, element, "<for> to value invalid"); double byValue = by == null ? 1.0 : doubleValue(by, element, "<for> by value invalid"); if (byValue <= 0.0) throw new TemplateException(element, "<for> by value invalid"); if (fromValue != toValue) { context = new TemplateContext(context, element); if (fromValue < toValue) { do { if (!isEmpty(name)) context.setVariable(name, new Double(fromValue)); processElementContents(element, formatter, true); fromValue += byValue; } while (fromValue < toValue); } else { do { if (!isEmpty(name)) context.setVariable(name, new Double(fromValue)); processElementContents(element, formatter, true); fromValue -= byValue; } while (fromValue > toValue); } context = context.getParent(); } } private double doubleValue(Object obj, Element element, String msg) throws TemplateException { try { return Expression.asDouble(obj); } catch (Expression.DoubleCoercionException e) { throw new TemplateException(element, msg); } } private void processForCollection(Element element, DefaultHandler2 formatter, String name, String coll) throws Expression.ExpressionException { Object collObject = parser.parseExpression(coll, context).evaluate(); if (collObject != null) { context = new TemplateContext(context, element); if (collObject instanceof Map<?, ?>) { for (Object obj : ((Map<?, ?>)collObject).values()) { if (!isEmpty(name)) context.setVariable(name, obj); processElementContents(element, formatter, true); } } else if (collObject instanceof Iterable<?>) { for (Object obj : (Iterable<?>)collObject) { if (!isEmpty(name)) context.setVariable(name, obj); processElementContents(element, formatter, true); } } else if (collObject instanceof Object[]) { Object[] array = (Object[])collObject; for (int i = 0, n = array.length; i < n; i++) { Object obj = array[i]; if (!isEmpty(name)) context.setVariable(name, obj); processElementContents(element, formatter, true); } } else if (collObject.getClass().isArray()) { for (int i = 0, n = Array.getLength(collObject); i < n; i++) { Object obj = Array.get(collObject, i); if (!isEmpty(name)) context.setVariable(name, obj); processElementContents(element, formatter, true); } } else throw new TemplateException(element, "<for> collection must be capable of iteration"); context = context.getParent(); } } private void processCall(Element element, DefaultHandler2 formatter) throws Expression.ExpressionException { String name = substAttr(element, nameAttrName); Element macro = context.getMacro(name); if (macro == null) throw new TemplateException(element, "macro name incorrect - " + name); context = new TemplateContext(context, element); NodeList childNodes = element.getChildNodes(); for (int i = 0, n = childNodes.getLength(); i < n; i++) { Node childNode = childNodes.item(i); if (childNode.getNodeType() == Node.ELEMENT_NODE) { Element childElement = (Element)childNode; if (XML.matchNS(childElement, paramElementName, namespace)) { name = substAttr(childElement, nameAttrName); if (!isValidName(name)) throw new TemplateException(childElement, "Name missing or invalid"); String value = substAttr(childElement, valueAttrName); if (isEmpty(value)) throw new TemplateException(childElement, "Value missing"); try { context.setVariable(name, // must be outer context parser.parseExpression(value, context).evaluate()); } catch (Expression.ExpressionException e) { throw new TemplateException(childElement, "Error in value - " + value + '\n' + e.getMessage()); } } else throw new TemplateException(childElement, "Illegal element within <call>"); } else if (!isCommentOrEmpty(childNode)) throw new TemplateException(element, "Illegal content within <call>"); } processElementContents(macro, formatter, true); context = context.getParent(); } private void processComment(@SuppressWarnings("unused") Element element, @SuppressWarnings("unused") DefaultHandler2 formatter) { // TODO complete this } private void processCopy(Element element, DefaultHandler2 formatter) throws Expression.ExpressionException { String elementName = substAttr(element, elementAttrName); if (isEmpty(elementName)) throw new TemplateException(element, "<copy> element missing"); // TODO if element not specified, process contents of <copy> (skipping <intercept>s)?? context = new TemplateContext(context, element); Element elementToCopy = null; try { Object obj = parser.parseExpression(elementName, context).evaluate(); if (!(obj instanceof ElementWrapper)) throw new TemplateException(element, "<copy> must specify element"); elementToCopy = ((ElementWrapper)obj).getElement(); } catch (TemplateException te) { throw te; } catch (Expression.ExpressionException ee) { throw new TemplateException(element, "Error in element specification"); } boolean include = false; String opt = substAttr(element, optionAttrName); if (!isEmpty(opt)) { if (optionInclude.equals(opt)) include = true; else throw new TemplateException(element, "<copy> option not recognised - " + opt); } List<Intercept> intercepts = new ArrayList<>(); NodeList childNodes = element.getChildNodes(); for (int i = 0, n = childNodes.getLength(); i < n; i++) { Node childNode = childNodes.item(i); if (childNode instanceof Element) { Element childElement = (Element)childNode; context = new TemplateContext(context, element); if (XML.matchNS(childElement, interceptElementName, namespace)) { elementName = substAttr(childElement, elementAttrName); if (isEmpty(elementName)) throw new TemplateException(element, "<intercept> element missing"); String name = substAttr(childElement, nameAttrName); intercepts.add(new Intercept(elementName, childElement, name)); } else throw new TemplateException(element, "Illegal element within <copy>"); context = context.getParent(); } else if (!isCommentOrEmpty(childNode)) throw new TemplateException(element, "Illegal content within <copy>"); } if (include) copyElement(elementToCopy, intercepts, formatter); else copyElementContents(elementToCopy, intercepts, formatter); context = context.getParent(); } private void copyElement(Element element, List<Intercept> intercepts, DefaultHandler2 formatter) throws Expression.ExpressionException { for (Intercept intercept : intercepts) { if (element.getTagName().equals(intercept.getTagName())) { Element replacement = intercept.getReplacement(); context = new TemplateContext(context, replacement); String name = intercept.getName(); if (!isEmpty(name)) context.setVariable(name, new ElementWrapper(element)); processElementContents(replacement, formatter, true); context = context.getParent(); return; } } AttributesImpl attrs = new AttributesImpl(); NamedNodeMap attributes = element.getAttributes(); for (int i = 0, n = attributes.getLength(); i < n; i++) { Attr attr = (Attr)attributes.item(i); attrs.addAttribute(attr.getNamespaceURI(), attr.getLocalName(), attr.getNodeName(), "CDATA", attr.getValue()); } try { formatter.startElement(element.getNamespaceURI(), element.getLocalName(), element.getNodeName(), attrs); copyElementContents(element, intercepts, formatter); formatter.endElement(element.getNamespaceURI(), element.getLocalName(), element.getNodeName()); } catch (SAXException e) { throw new TemplateException(element, "Error writing element"); } } private void copyElementContents(Element element, List<Intercept> intercepts, DefaultHandler2 formatter) throws Expression.ExpressionException { context = new TemplateContext(context, element); NodeList childNodes = element.getChildNodes(); for (int i = 0, n = childNodes.getLength(); i < n; i++) { Node childNode = childNodes.item(i); if (childNode instanceof Element) copyElement((Element)childNode, intercepts, formatter); else if (childNode instanceof Text) outputText(((Text)childNode).getData(), formatter); else if (childNode instanceof CDATASection) { try { formatter.startCDATA(); outputText(((Text)childNode).getData(), formatter); formatter.endCDATA(); } catch (SAXException e) { throw new RuntimeException("Unexpected SAXException", e); } } } context = context.getParent(); } private void outputElement(Element element, DefaultHandler2 formatter) throws Expression.ExpressionException { AttributesImpl attrs = new AttributesImpl(); NamedNodeMap attributes = element.getAttributes(); for (int i = 0, n = attributes.getLength(); i < n; i++) { Attr attr = (Attr)attributes.item(i); if (!namespace.equals(attr.getNamespaceURI())) { String value = subst(attr.getValue()); if (!isEmpty(value)) attrs.addAttribute(attr.getNamespaceURI(), attr.getLocalName(), attr.getNodeName(), "CDATA", value); } } try { formatter.startElement(element.getNamespaceURI(), element.getLocalName(), element.getNodeName(), attrs); processElementContents(element, formatter, false); formatter.endElement(element.getNamespaceURI(), element.getLocalName(), element.getNodeName()); } catch (SAXException e) { throw new TemplateException(element, "Error writing element"); } } private void outputText(String data, DefaultHandler2 formatter) throws Expression.ExpressionException { try { String data1 = subst(data); formatter.characters(data1.toCharArray(), 0, data1.length()); } catch (SAXException e) { throw new TemplateException("Error writing text node"); } } private String substAttr(Element element, String attrName) throws Expression.ExpressionException { return subst(element.getAttribute(attrName)); } private String subst(String str) throws Expression.ExpressionException { return str == null ? null : parser.substitute(str, context); } private static boolean isEmpty(String str) { return str == null || str.length() == 0; } private static boolean isElementEmpty(Element element) { NodeList childNodes = element.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { if (!isCommentOrEmpty(childNodes.item(i))) return false; } return true; } private static boolean isCommentOrEmpty(Node node) { return node.getNodeType() == Node.COMMENT_NODE || node.getNodeType() == Node.TEXT_NODE && XML.isAllWhiteSpace(((Text)node).getData()); } public static boolean isValidName(String name) { if (isEmpty(name) || !isValidNameStart(name.charAt(0))) return false; for (int i = 1; i < name.length(); i++) if (!isValidNameContinuation(name.charAt(i))) return false; return true; } public static boolean isValidNameStart(char ch) { return ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' || ch == '_' || ch == '$'; } public static boolean isValidNameContinuation(char ch) { return isValidNameStart(ch) || ch >= '0' && ch <= '9'; } public static String trimLeading(String str) { int i = 0; int n = str.length(); while (i < n && XML.isWhiteSpace(str.charAt(i))) i++; return i > 0 ? str.substring(i) : str; } public static String trimTrailing(String str) { int i = 0; int n = str.length(); while (i < n && XML.isWhiteSpace(str.charAt(n - 1))) n return n < str.length() ? str.substring(0, n) : str; } public static boolean isFloating(Object obj) { return obj instanceof Double || obj instanceof Float; } public static String getXPath(Element element) { StringBuilder sb = new StringBuilder(); for (;;) { sb.insert(0, getXPathElement(element)); sb.insert(0, '/'); Node parent = element.getParentNode(); if (parent == null || !(parent instanceof Element)) break; element = (Element)parent; } return sb.toString(); } public static String getXPathElement(Element element) { StringBuilder sb = new StringBuilder(element.getTagName()); String id = element.getAttribute(idAttrName); if (!isEmpty(id)) sb.append('#').append(id); else { Node parent = element.getParentNode(); if (parent != null) { String tagName = element.getTagName(); int count = 0; int thisIndex = 0; NodeList siblings = parent.getChildNodes(); for (int i = 0, n = siblings.getLength(); i < n; i++) { Node sibling = siblings.item(i); if (sibling == element) thisIndex = count; else if (sibling instanceof Element && ((Element)sibling).getTagName().equals(tagName)) count++; } if (count > 0) sb.append('[').append(thisIndex + 1).append(']'); } } return sb.toString(); } public static void main(String[] args) { try { File template = null; File in = null; File out = null; for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.equals("-template")) { if (++i >= args.length || args[i].startsWith("-")) throw new UserError("-template with no pathname"); if (template != null) throw new UserError("Duplicate -template"); template = new File(args[i]); if (!template.exists() || !template.isFile()) throw new UserError("-template file does not exist - " + args[i]); } else if (arg.equals("-in")) { if (++i >= args.length || args[i].startsWith("-")) throw new UserError("-in with no pathname"); if (in != null) throw new UserError("Duplicate -in"); in = new File(args[i]); if (!in.exists() || !in.isFile()) throw new UserError("-in file does not exist - " + args[i]); } else if (arg.equals("-out")) { if (++i >= args.length || args[i].startsWith("-")) throw new UserError("-out with no pathname"); if (out != null) throw new UserError("Duplicate -out"); out = new File(args[i]); } else throw new UserError("Unrecognised argument - " + arg); } if (out != null) { try (OutputStream os = new FileOutputStream(out)) { run(os, in, template); } catch (IOException ioe) { throw new RuntimeException("Error writing output file", ioe); } } else run(System.out, in, template); } catch (TemplateException te) { System.err.println(); Element element = te.getElement(); if (element != null) System.err.println("XPath: " + getXPath(element)); System.err.println(te.getMessage()); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private static void run(OutputStream os, File in, File template) throws ParserConfigurationException, SAXException, IOException, Expression.ExpressionException { Document templateDOM = XML.getDocumentBuilderNS().parse(Objects.requireNonNull(template)); TemplateProcessor processor = new TemplateProcessor(templateDOM); processor.addNamespace("http://java.sun.com/jsp/jstl/functions", Functions.class.getName()); // should the above be variable? command-line args? if (in != null) { Document inputDOM = XML.parse(in); processor.setVariable("page", new ElementWrapper(inputDOM.getDocumentElement())); } processor.process(os); } public static class TemplateException extends Expression.ExpressionException { private static final long serialVersionUID = 7462874004583859973L; private Element element; public TemplateException(Element element, String message) { super(message); this.element = element; } public TemplateException(String message) { this(null, message); } public Element getElement() { return element; } } /** * Template Context - includes Name Resolver for Expression Language. */ public static class TemplateContext implements Expression.ExtendedResolver { private TemplateContext parent; private Element element; private Map<String, Expression> map; private Map<String, Element> macros; private Map<String, String> namespaces; /** * Construct the <code>TemplateResolver</code> * * @param parent the parent context */ public TemplateContext(TemplateContext parent, Element element) { this.parent = parent; this.element = element; map = new HashMap<>(); macros = new HashMap<>(); namespaces = new HashMap<>(); } /** * Get the parent context. * * @return the parent context */ public TemplateContext getParent() { return parent; } /** * Create a variable, or modify an existing one. * * @param identifier the identifier of the variable * @param object the value of the variable */ public void setVariable(String identifier, Object object) { map.put(identifier, new SimpleVariable(identifier, object)); } public void setConstant(String identifier, Object object) { map.put(identifier, new Expression.Constant(object)); } /** * Resolve an identifier to an expression. * * @param identifier the identifier to be resolved * @return a variable, or null if the name can not be resolved * @see Expression.Resolver#resolve(String) */ @Override public Expression resolve(String identifier) { for (TemplateContext context = this; context != null; context = context.parent) { Expression e = context.map.get(identifier); if (e != null) return e; } return null; } /** * Add a macro to the current context. * * @param element the macro element * @throws TemplateException if the macro does not have a valid name, or is a duplicate */ public void addMacro(Element element) throws TemplateException { String name = element.getAttribute(nameAttrName); if (!isValidName(name)) throw new TemplateException(element, "Macro name missing or invalid"); if (macros.containsKey(name)) throw new TemplateException(element, "Duplicate macro - " + name); macros.put(name, element); } /** * Get a macro. * * @param name the macro name * @return the macro element */ public Element getMacro(String name) { for (TemplateContext context = this; context != null; context = context.parent) { Element macro = context.macros.get(name); if (macro != null) return macro; } return null; } public void addNamespace(String uri, String namespace) { namespaces.put(uri, namespace); } @Override public String resolvePrefix(String prefix) { String xmlnsAttrName = "xmlns:" + Objects.requireNonNull(prefix); Element element = this.element; for (;;) { String uri = element.getAttribute(xmlnsAttrName); if (!isEmpty(uri)) return uri; Node parent = element.getParentNode(); if (!(parent instanceof Element)) break; element = (Element)parent; } return null; } @Override public String resolveNamespace(String uri) { for (TemplateContext context = this; context != null; context = context.parent) { String classname = context.namespaces.get(uri); if (classname != null) return classname; } return null; } } public static class ElementWrapper { private Element element; private List<ElementWrapper> elems; private Map<String, Object> attrs; private String text; public ElementWrapper(Element element) { this.element = element; elems = null; attrs = null; text = null; } public Element getElement() { return element; } public String getTagName() { return element.getTagName(); } public List<ElementWrapper> getElems() { if (elems == null) { elems = new ArrayList<>(); NodeList children = element.getChildNodes(); for (int i = 0, n = children.getLength(); i < n; i++) { Node child = children.item(i); if (child instanceof Element) elems.add(new ElementWrapper((Element)child)); } } return elems; } public Map<String, Object> getAttrs() { if (attrs == null) { attrs = new HashMap<>(); NamedNodeMap attributes = element.getAttributes(); for (int i = 0, n = attributes.getLength(); i < n; i++) { Attr attr = (Attr)attributes.item(i); attrs.put(attr.getName(), attr.getValue()); } } return attrs; } public String getText() { if (text == null) { StringBuilder sb = new StringBuilder(); appendData(sb, element); text = sb.toString(); } return text; } private void appendData(StringBuilder sb, Node node) { if (node instanceof Text) sb.append(((Text)node).getData()); else if (node instanceof Element) { NodeList children = ((Element)node).getChildNodes(); for (int i = 0, n = children.getLength(); i < n; i++) appendData(sb, children.item(i)); } } } public static class Intercept { private String tagName; private Element replacement; private String name; public Intercept(String tagName, Element replacement, String name) { this.tagName = tagName; this.replacement = replacement; this.name = name; } public String getTagName() { return tagName; } public Element getReplacement() { return replacement; } public String getName() { return name; } } }
package org.keycloak.testutils; import io.undertow.Undertow; import io.undertow.Undertow.Builder; import io.undertow.server.handlers.resource.Resource; import io.undertow.server.handlers.resource.ResourceManager; import io.undertow.server.handlers.resource.URLResource; import io.undertow.servlet.Servlets; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.FilterInfo; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import javax.servlet.DispatcherType; import org.jboss.resteasy.jwt.JsonSerialization; import org.jboss.resteasy.logging.Logger; import org.jboss.resteasy.plugins.server.undertow.UndertowJaxrsServer; import org.jboss.resteasy.spi.ResteasyDeployment; import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSessionFactory; import org.keycloak.models.RealmModel; import org.keycloak.models.RoleModel; import org.keycloak.models.UserModel; import org.keycloak.representations.idm.CredentialRepresentation; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.services.filters.KeycloakSessionServletFilter; import org.keycloak.services.managers.RealmManager; import org.keycloak.services.resources.KeycloakApplication; import org.keycloak.services.resources.SaasService; /** * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a> */ public class KeycloakServer { private static final Logger log = Logger.getLogger(KeycloakServer.class); private boolean sysout = false; public static class KeycloakServerConfig { private String host = "localhost"; private int port = 8081; public String getHost() { return host; } public int getPort() { return port; } public void setHost(String host) { this.host = host; } public void setPort(int port) { this.port = port; } } private static <T> T loadJson(InputStream is, Class<T> type) { try { ByteArrayOutputStream os = new ByteArrayOutputStream(); int c; while ((c = is.read()) != -1) { os.write(c); } byte[] bytes = os.toByteArray(); return JsonSerialization.fromBytes(type, bytes); } catch (IOException e) { throw new RuntimeException("Failed to parse json", e); } } public static void main(String[] args) throws Throwable { KeycloakServerConfig config = new KeycloakServerConfig(); for (int i = 0; i < args.length; i++) { if (args[i].equals("-b")) { config.setHost(args[++i]); } if (args[i].equals("-p")) { config.setPort(Integer.valueOf(args[++i])); } } final KeycloakServer keycloak = new KeycloakServer(config); keycloak.sysout = true; keycloak.start(); for (int i = 0; i < args.length; i++) { if (args[i].equals("-import")) { keycloak.importRealm(new FileInputStream(args[++i])); } } Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { keycloak.stop(); } }); } private KeycloakServerConfig config; private KeycloakSessionFactory factory; private UndertowJaxrsServer server; public KeycloakServer() { this(new KeycloakServerConfig()); } public KeycloakServer(KeycloakServerConfig config) { this.config = config; } public KeycloakSessionFactory getKeycloakSessionFactory() { return factory; } public UndertowJaxrsServer getServer() { return server; } public void importRealm(InputStream realm) { RealmRepresentation rep = loadJson(realm, RealmRepresentation.class); importRealm(rep); } public void importRealm(RealmRepresentation rep) { KeycloakSession session = factory.createSession(); session.getTransaction().begin(); try { RealmManager manager = new RealmManager(session); if (rep.getId() == null) { throw new RuntimeException("Realm id not specified"); } if (manager.getRealm(rep.getId()) != null) { info("Not importing realm " + rep.getRealm() + " realm already exists"); return; } RealmModel realm = manager.createRealm(rep.getId(), rep.getRealm()); manager.importRealm(rep, realm); info("Imported realm " + realm.getName()); session.getTransaction().commit(); } finally { session.close(); } } protected void setupDefaultRealm() { KeycloakSession session = factory.createSession(); session.getTransaction().begin(); try { RealmManager manager = new RealmManager(session); if (manager.getRealm(RealmModel.DEFAULT_REALM) != null) { return; } RealmModel defaultRealm = manager.createRealm(RealmModel.DEFAULT_REALM, RealmModel.DEFAULT_REALM); defaultRealm.setName(RealmModel.DEFAULT_REALM); defaultRealm.setEnabled(true); defaultRealm.setTokenLifespan(300); defaultRealm.setAccessCodeLifespan(60); defaultRealm.setAccessCodeLifespanUserAction(600); defaultRealm.setSslNotRequired(true); defaultRealm.setCookieLoginAllowed(true); defaultRealm.setRegistrationAllowed(true); manager.generateRealmKeys(defaultRealm); defaultRealm.addRequiredCredential(CredentialRepresentation.PASSWORD); defaultRealm.addRole(SaasService.REALM_CREATOR_ROLE); defaultRealm.addDefaultRole(SaasService.REALM_CREATOR_ROLE); session.getTransaction().commit(); } finally { session.close(); } } public void start() throws Throwable { long start = System.currentTimeMillis(); ResteasyDeployment deployment = new ResteasyDeployment(); deployment.setApplicationClass(KeycloakApplication.class.getName()); Builder builder = Undertow.builder().addListener(config.getPort(), config.getHost()); server = new UndertowJaxrsServer().start(builder); DeploymentInfo di = server.undertowDeployment(deployment, "rest"); di.setClassLoader(getClass().getClassLoader()); di.setContextPath("/auth-server"); di.setDeploymentName("Keycloak"); di.setResourceManager(new KeycloakResourceManager()); FilterInfo filter = Servlets.filter("SessionFilter", KeycloakSessionServletFilter.class); di.addFilter(filter);
package openeye.config; import com.google.common.base.Preconditions; import com.google.common.collect.Table; import com.google.common.collect.TreeBasedTable; import java.io.File; import java.util.Collection; import java.util.List; import openeye.Log; public class ConfigProcessing { public static final IConfigProcessingEngine GSON = new GsonConfigProcessingEngine(); private static Table<String, String, IConfigPropertyHolder> categorizeProperties(Collection<IConfigPropertyHolder> properties) { Table<String, String, IConfigPropertyHolder> result = TreeBasedTable.create(); for (IConfigPropertyHolder property : properties) { IConfigPropertyHolder prev = result.put(property.category(), property.name(), property); Preconditions.checkState(prev == null, "Duplicated property %s:%s", property.category(), property.name()); } return result; } private static void loadAndDump(File configFile, IConfigProcessingEngine engine, final List<IConfigPropertyHolder> holders) { final Table<String, String, IConfigPropertyHolder> properties = categorizeProperties(holders); final boolean modified = engine.loadConfig(configFile, properties); if (modified) { Log.info("Detected missing/malformed fields in file %s, updating", configFile); engine.dumpConfig(configFile, properties); } } public static void processConfig(File configFile, Class<?> cls, IConfigProcessingEngine engine) { final List<IConfigPropertyHolder> holders = ConfigPropertyCollector.collectFromClass(cls); loadAndDump(configFile, engine, holders); } public static void processConfig(File configFile, Object target, boolean excludeStatic, IConfigProcessingEngine engine) { Preconditions.checkNotNull(target); final List<IConfigPropertyHolder> holders = ConfigPropertyCollector.collectFromInstance(target, excludeStatic); loadAndDump(configFile, engine, holders); } }
package org.sakaiproject.evaluation.tool.producers; import java.text.DateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.sakaiproject.evaluation.logic.EvalEvaluationsLogic; import org.sakaiproject.evaluation.logic.EvalExternalLogic; import org.sakaiproject.evaluation.logic.EvalItemsLogic; import org.sakaiproject.evaluation.logic.EvalSettings; import org.sakaiproject.evaluation.logic.externals.ExternalHierarchyLogic; import org.sakaiproject.evaluation.logic.model.EvalGroup; import org.sakaiproject.evaluation.logic.model.EvalHierarchyNode; import org.sakaiproject.evaluation.logic.utils.EvalUtils; import org.sakaiproject.evaluation.logic.utils.TemplateItemUtils; import org.sakaiproject.evaluation.model.EvalAnswer; import org.sakaiproject.evaluation.model.EvalAssignGroup; import org.sakaiproject.evaluation.model.EvalEvaluation; import org.sakaiproject.evaluation.model.EvalTemplateItem; import org.sakaiproject.evaluation.model.constant.EvalConstants; import org.sakaiproject.evaluation.tool.LocalResponsesLogic; import org.sakaiproject.evaluation.tool.renderers.ItemRenderer; import org.sakaiproject.evaluation.tool.viewparams.EvalCategoryViewParameters; import org.sakaiproject.evaluation.tool.viewparams.EvalTakeViewParameters; import uk.org.ponder.rsf.components.ELReference; import uk.org.ponder.rsf.components.UIBranchContainer; import uk.org.ponder.rsf.components.UICommand; import uk.org.ponder.rsf.components.UIContainer; import uk.org.ponder.rsf.components.UIELBinding; import uk.org.ponder.rsf.components.UIForm; import uk.org.ponder.rsf.components.UIInternalLink; import uk.org.ponder.rsf.components.UIMessage; import uk.org.ponder.rsf.components.UIOutput; import uk.org.ponder.rsf.components.UISelect; import uk.org.ponder.rsf.components.UIVerbatim; import uk.org.ponder.rsf.components.decorators.DecoratorList; import uk.org.ponder.rsf.components.decorators.UIStyleDecorator; import uk.org.ponder.rsf.flow.ARIResult; import uk.org.ponder.rsf.flow.ActionResultInterceptor; import uk.org.ponder.rsf.flow.jsfnav.NavigationCase; import uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter; import uk.org.ponder.rsf.view.ComponentChecker; import uk.org.ponder.rsf.view.ViewComponentProducer; import uk.org.ponder.rsf.viewstate.SimpleViewParameters; import uk.org.ponder.rsf.viewstate.ViewParameters; import uk.org.ponder.rsf.viewstate.ViewParamsReporter; public class TakeEvalProducer implements ViewComponentProducer, ViewParamsReporter, NavigationCaseReporter, ActionResultInterceptor { // removed original authors for writing code that does not even work -AZ public static final String VIEW_ID = "take_eval"; public String getViewID() { return VIEW_ID; } private EvalExternalLogic external; public void setExternal(EvalExternalLogic external) { this.external = external; } private EvalEvaluationsLogic evalsLogic; public void setEvalsLogic(EvalEvaluationsLogic evalsLogic) { this.evalsLogic = evalsLogic; } private EvalItemsLogic itemsLogic; public void setItemsLogic(EvalItemsLogic itemsLogic) { this.itemsLogic = itemsLogic; } ItemRenderer itemRenderer; public void setItemRenderer(ItemRenderer itemRenderer) { this.itemRenderer = itemRenderer; } private LocalResponsesLogic localResponsesLogic; public void setLocalResponsesLogic(LocalResponsesLogic localResponsesLogic) { this.localResponsesLogic = localResponsesLogic; } private EvalSettings evalSettings; public void setEvalSettings(EvalSettings evalSettings) { this.evalSettings = evalSettings; } private Locale locale; public void setLocale(Locale locale) { this.locale = locale; } private ExternalHierarchyLogic hierarchyLogic; public void setExternalHierarchyLogic(ExternalHierarchyLogic logic) { this.hierarchyLogic = logic; } String responseOTPBinding = "responseBeanLocator"; String responseOTP = responseOTPBinding + "."; String newResponseOTPBinding = responseOTP + "new"; String newResponseOTP = newResponseOTPBinding + "."; String responseAnswersOTPBinding = "responseAnswersBeanLocator"; String responseAnswersOTP = responseAnswersOTPBinding + "."; String newResponseAnswersOTPBinding = responseAnswersOTP + "new"; String newResponseAnswersOTP = newResponseAnswersOTPBinding + "."; String evalOTPBinding = "evaluationBeanLocator"; String evalOTP = evalOTPBinding+"."; Long responseId; Long evaluationId; String evalGroupId; int displayNumber=1; int renderedItemCount=0; List<EvalTemplateItem> allItems; // should be set to a list of all evaluation items Map<String, EvalAnswer> answerMap = new HashMap<String, EvalAnswer>(); /* (non-Javadoc) * @see uk.org.ponder.rsf.view.ComponentProducer#fillComponents(uk.org.ponder.rsf.components.UIContainer, uk.org.ponder.rsf.viewstate.ViewParameters, uk.org.ponder.rsf.view.ComponentChecker) */ public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) { boolean canAccess = false; boolean userCanAccess = false; String currentUserId = external.getCurrentUserId(); // use a date which is related to the current users locale DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale); UIMessage.make(tofill, "page-title", "takeeval.page.title"); UIInternalLink.make(tofill, "summary-toplink", UIMessage.make("summary.page.title"), new SimpleViewParameters(SummaryProducer.VIEW_ID)); // get passed in get params EvalTakeViewParameters evalTakeViewParams = (EvalTakeViewParameters) viewparams; evaluationId = evalTakeViewParams.evaluationId; evalGroupId = evalTakeViewParams.evalGroupId; responseId = evalTakeViewParams.responseId; // get the evaluation based on the passed in VPs EvalEvaluation eval = evalsLogic.getEvaluationById(evaluationId); if (eval == null) { throw new IllegalArgumentException("Invalid evaluationId ("+evaluationId+"), cannot load evaluation"); } UIMessage.make(tofill, "eval-title-header", "takeeval.eval.title.header"); UIOutput.make(tofill, "evalTitle", eval.getTitle()); // check the states of the evaluation first to give the user a tip that this eval is not takeable, String evalStatus = evalsLogic.updateEvaluationState(evaluationId); // make sure state is up to date if (EvalConstants.EVALUATION_STATE_INQUEUE.equals(evalStatus)) { UIMessage.make(tofill, "eval-cannot-take-message", "takeeval.eval.not.open", new String[] {df.format(eval.getStartDate()), df.format(eval.getDueDate())} ); } else if (EvalConstants.EVALUATION_STATE_CLOSED.equals(evalStatus) || EvalConstants.EVALUATION_STATE_VIEWABLE.equals(evalStatus)) { UIMessage.make(tofill, "eval-cannot-take-message", "takeeval.eval.closed", new String[] {df.format(eval.getDueDate())} ); } else { // eval state is possible to take eval canAccess = true; } if (canAccess) { // eval is accessible so check user can take it if (evalGroupId != null) { // there was an eval group passed in so make sure things are ok if (evalsLogic.canTakeEvaluation(currentUserId, evaluationId, evalGroupId)) { userCanAccess = true; } } else { // select the first eval group the current user can take evaluation in, // also store the total number so we can give the user a list to choose from if there are more than one Map<Long, List<EvalAssignGroup>> m = evalsLogic.getEvaluationAssignGroups(new Long[] {evaluationId}, true); List<EvalGroup> validGroups = new ArrayList<EvalGroup>(); // stores EvalGroup objects if ( external.isUserAdmin(currentUserId) ) { // special case, the super admin can always access userCanAccess = true; List<EvalAssignGroup> assignGroups = m.get(evaluationId); for (int i = 0; i < assignGroups.size(); i++) { EvalAssignGroup assignGroup = assignGroups.get(i); if (evalGroupId == null) { // set the evalGroupId to the first valid group if unset evalGroupId = assignGroup.getEvalGroupId(); } validGroups.add( external.makeEvalGroupObject( assignGroup.getEvalGroupId() )); } } else { EvalGroup[] evalGroups; if ( EvalConstants.EVALUATION_AUTHCONTROL_NONE.equals(eval.getAuthControl()) ) { // anonymous eval allows any group to be evaluated List<EvalAssignGroup> assignGroups = m.get(evaluationId); evalGroups = new EvalGroup[assignGroups.size()]; for (int i = 0; i < assignGroups.size(); i++) { EvalAssignGroup assignGroup = (EvalAssignGroup) assignGroups.get(i); evalGroups[i] = external.makeEvalGroupObject( assignGroup.getEvalGroupId() ); } } else { evalGroups = EvalUtils.getGroupsInCommon( external.getEvalGroupsForUser(currentUserId, EvalConstants.PERM_TAKE_EVALUATION), m.get(evaluationId) ); } for (int i = 0; i < evalGroups.length; i++) { EvalGroup group = evalGroups[i]; if (evalsLogic.canTakeEvaluation(currentUserId, evaluationId, group.evalGroupId)) { if (evalGroupId == null) { // set the evalGroupId to the first valid group if unset evalGroupId = group.evalGroupId; userCanAccess = true; } validGroups.add( external.makeEvalGroupObject(group.evalGroupId) ); } } } // generate the get form to allow the user to choose a group if more than one is available if (validGroups.size() > 1) { String[] values = new String[validGroups.size()]; String[] labels = new String[validGroups.size()]; for (int i=0; i<validGroups.size(); i++) { EvalGroup group = (EvalGroup) validGroups.get(i); values[i] = group.evalGroupId; labels[i] = group.title; } // show the switch group selection and form UIBranchContainer showSwitchGroup = UIBranchContainer.make(tofill, "show-switch-group:"); UIMessage.make(showSwitchGroup, "switch-group-header", "takeeval.switch.group.header"); UIForm chooseGroupForm = UIForm.make(showSwitchGroup, "switch-group-form", new EvalTakeViewParameters(TakeEvalProducer.VIEW_ID, evaluationId, evalGroupId, responseId)); UISelect.make(chooseGroupForm, "switch-group-list", values, labels, "#{evalGroupId}"); UIMessage.make(chooseGroupForm, "switch-group-button", "takeeval.switch.group.button"); } } } if (userCanAccess) { // fill in group title UIBranchContainer groupTitle = UIBranchContainer.make(tofill, "show-group-title:"); UIMessage.make(groupTitle, "group-title-header", "takeeval.group.title.header"); UIOutput.make(groupTitle, "group-title", external.getDisplayTitle(evalGroupId) ); // show instructions if not null if (eval.getInstructions() != null) { UIBranchContainer instructions = UIBranchContainer.make(tofill, "show-eval-instructions:"); UIMessage.make(instructions, "eval-instructions-header", "takeeval.instructions.header"); UIVerbatim.make(instructions, "eval-instructions", eval.getInstructions()); } Boolean studentAllowedLeaveUnanswered = ((Boolean)evalSettings.get(EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED)); if (studentAllowedLeaveUnanswered == null) { studentAllowedLeaveUnanswered = eval.getBlankResponsesAllowed(); if (studentAllowedLeaveUnanswered == null) { studentAllowedLeaveUnanswered = false; } } // show a warning to the user if all items must be filled in if ( studentAllowedLeaveUnanswered == false ) { UIBranchContainer note = UIBranchContainer.make(tofill, "show-eval-note:"); UIMessage.make(note, "eval-note-header", "general.note"); UIMessage.make(note, "eval-note-text", "takeeval.user.must.answer.all"); } UIBranchContainer formBranch = UIBranchContainer.make(tofill, "form-branch:"); UIForm form = UIForm.make(formBranch, "evaluationForm"); // bind the evaluation and evalGroup to the ones in the take eval bean form.parameters.add( new UIELBinding("#{takeEvalBean.eval}", new ELReference(evalOTP + eval.getId())) ); form.parameters.add( new UIELBinding("#{takeEvalBean.evalGroupId}", evalGroupId) ); // now we begin the complex task of rendering the evaluation items // get the instructors for this evaluation Set<String> instructors = external.getUserIdsForEvalGroup(evalGroupId, EvalConstants.PERM_BE_EVALUATED); // Get the Hierarchy NodeIDs for the current Group List<EvalHierarchyNode> evalHierNodes = hierarchyLogic.getNodesAboveEvalGroup(evalGroupId); String[] evalHierNodeIDs = new String[evalHierNodes.size()]; for (int nodecnt = 0; nodecnt < evalHierNodes.size(); nodecnt++) { evalHierNodeIDs[nodecnt] = evalHierNodes.get(nodecnt).id; } // get all items for this evaluation allItems = itemsLogic.getTemplateItemsForEvaluation(evaluationId, evalHierNodeIDs, instructors.toArray(new String[instructors.size()]), new String[] {evalGroupId}); // filter out the block child items, to get a list non-child items List<EvalTemplateItem> ncItemsList = TemplateItemUtils.getNonChildItems(allItems); // load up the previous responses for this user if (responseId != null) { answerMap = localResponsesLogic.getAnswersMapByTempItemAndAssociated(responseId); } if (TemplateItemUtils.checkTemplateItemsCategoryExists(EvalConstants.ITEM_CATEGORY_COURSE, ncItemsList)) { // for all course items, go through render process UIBranchContainer courseSection = UIBranchContainer.make(form, "courseSection:"); UIMessage.make(courseSection, "course-questions-header", "takeeval.group.questions.header"); // for each non-child item in this evaluation UIMessage.make(courseSection, "course-questions-header", "takeeval.group.questions.header"); handleCategoryRender(TemplateItemUtils.getCategoryTemplateItems(EvalConstants.ITEM_CATEGORY_COURSE, ncItemsList), form, courseSection, evalHierNodes); } if (TemplateItemUtils.checkTemplateItemsCategoryExists(EvalConstants.ITEM_CATEGORY_INSTRUCTOR, ncItemsList)) { // for each instructor, make a branch containing all instructor questions for (String instructor : instructors) { UIBranchContainer instructorSection = UIBranchContainer.make(form, "instructorSection:", "inst"+displayNumber); UIMessage.make(instructorSection, "instructor-questions-header", "takeeval.instructor.questions.header", new Object[] { external.getUserDisplayName(instructor) }); // for each non-child item in this evaluation handleCategoryRender(TemplateItemUtils.getCategoryTemplateItems(EvalConstants.ITEM_CATEGORY_INSTRUCTOR, ncItemsList), form, instructorSection, evalHierNodes); } } UICommand.make(form, "submitEvaluation", UIMessage.make("takeeval.submit.button"), "#{takeEvalBean.submitEvaluation}"); } else { // user cannot access eval so give them a sad message UIMessage.make(tofill, "eval-cannot-take-message", "takeeval.user.cannot.take"); } } /** * Handles the rendering of a set of items in a category/section of the view * @param ncItemsList the list of items to render in this section * @param form the form the controls for this set of items are attached to * @param section the parent branch container that holds all the UI elements in this section */ private void handleCategoryRender(List<EvalTemplateItem> itemsList, UIForm form, UIBranchContainer section, List<EvalHierarchyNode> evalHierNodes) { /* We need to render things by section. For now we'll just loop through each evalHierNode to start, and * see if there are items of it. If there are we'll go ahead and render them with a group header. We * have to take care of the special toplevel hierarchy type first. * * I don't suppose this is terribly efficient, just looping through the nodes and items over and over again. * However, I don't any survey is going to have enough questions for it to ever matter. */ List<EvalTemplateItem> togo = new ArrayList<EvalTemplateItem>(); for (EvalTemplateItem item: itemsList) { if (item.getHierarchyLevel().equals(EvalConstants.HIERARCHY_LEVEL_TOP)) { togo.add(item); } } if (togo.size() > 0) { handleCategoryHierarchyNodeRender(togo, form, section, null); } for (EvalHierarchyNode evalNode: evalHierNodes) { togo = new ArrayList<EvalTemplateItem>(); for (EvalTemplateItem item: itemsList) { if (item.getHierarchyLevel().equals(EvalConstants.HIERARCHY_LEVEL_NODE) && item.getHierarchyNodeId().equals(evalNode.id)) { togo.add(item); } } if (togo.size() > 0) { handleCategoryHierarchyNodeRender(togo, form, section, evalNode.title); } } } /* * This method is most likely to be invoked from handleCategoryRender. Basically it handles the grouping by node for each category. * So say in the Group/Courses category, you may have questions for "General", "Biology Department", and "Botany 101". You would call * this method once for each node group, passing in the items for that node, and the title (ie. "Biology Department") that you want rendered. * If you pass in a null or empty sectiontitle, it will assume that it is for the general top level node level. */ private void handleCategoryHierarchyNodeRender(List<EvalTemplateItem> itemsInNode, UIForm form, UIContainer tofill, String sectiontitle) { /* * Showing the section title is configurable via the admin screen. */ Boolean showHierSectionTitle = (Boolean) evalSettings.get(EvalSettings.DISPLAY_HIERARCHY_HEADERS); if (showHierSectionTitle != null && showHierSectionTitle.booleanValue() == true) { if (sectiontitle != null && !sectiontitle.equals("")) { UIBranchContainer labelrow = UIBranchContainer.make(tofill, "itemrow:hier-node-section"); UIOutput.make(labelrow, "hier-node-title", sectiontitle); } } for (int i = 0; i <itemsInNode.size(); i++) { EvalTemplateItem templateItem = itemsInNode.get(i); UIBranchContainer radiobranch = UIBranchContainer.make(tofill, "itemrow:first", i+""); if (i % 2 == 1) { radiobranch.decorators = new DecoratorList( new UIStyleDecorator("itemsListOddLine") ); // must match the existing CSS class } renderItemPrep(radiobranch, form, templateItem, "null", "null"); } } /** * Prep for rendering an item I assume (no comments by original authors) -AZ * * @param radiobranch * @param form * @param templateItem * @param answerMap * @param itemCategory * @param associatedId */ private void renderItemPrep(UIBranchContainer radiobranch, UIForm form, EvalTemplateItem templateItem, String itemCategory, String associatedId) { // holds array of bindings for child block items String[] caOTP = null; if (templateItem.getBlockParent() != null && templateItem.getBlockParent().booleanValue() == true) { // block item being rendered // get the child items of tempItem1 List<EvalTemplateItem> childList = TemplateItemUtils.getChildItems(allItems, templateItem.getId()); caOTP = new String[childList.size()]; // for each child item, construct a binding for (int j = 0; j < childList.size(); j++) { EvalTemplateItem currChildItem = (EvalTemplateItem) childList.get(j); // set up OTP paths if (responseId == null) { caOTP[j] = newResponseAnswersOTP + "new" + (renderedItemCount) + "."; } else { // if the user has answered this question before, point at their response EvalAnswer currAnswer = (EvalAnswer) answerMap.get(currChildItem.getId() + itemCategory + associatedId); // there is an existing response, but there is no answer if (currAnswer == null) { caOTP[j] = responseAnswersOTP + responseId + "." + "new" + (renderedItemCount) + "."; } else { caOTP[j] = responseAnswersOTP + responseId + "." + currAnswer.getId() + "."; } } // bind the current EvalTemplateItem's EvalItem to the current EvalAnswer's EvalItem form.parameters.add(new UIELBinding(caOTP[j] + "templateItem", new ELReference("templateItemWBL." + currChildItem.getId()))); if (EvalConstants.ITEM_CATEGORY_INSTRUCTOR.equals(itemCategory) || EvalConstants.ITEM_CATEGORY_ENVIRONMENT.equals(itemCategory)) { // bind the current instructor id to the current EvalAnswer.associated form.parameters.add(new UIELBinding(caOTP[j] + "associatedId", associatedId)); } // set up binding for UISelect caOTP[j] += "numeric"; renderedItemCount++; } } else if ( EvalConstants.ITEM_TYPE_SCALED.equals(templateItem.getItem().getClassification()) || EvalConstants.ITEM_TYPE_TEXT.equals(templateItem.getItem().getClassification()) ) { // single item being rendered // set up OTP paths for scaled/text type items String currAnswerOTP; if (responseId == null) { currAnswerOTP = newResponseAnswersOTP + "new" + renderedItemCount + "."; } else { // if the user has answered this question before, point at their response EvalAnswer currAnswer = (EvalAnswer) answerMap.get(templateItem.getId() + "null" + "null"); if (currAnswer == null) { currAnswerOTP = responseAnswersOTP + responseId + "." + "new" + (renderedItemCount) + "."; } else { currAnswerOTP = responseAnswersOTP + responseId + "." + currAnswer.getId() + "."; } } // bind the current EvalTemplateItem's EvalItem to the current EvalAnswer's EvalItem form.parameters.add( new UIELBinding(currAnswerOTP + "templateItem", new ELReference("templateItemWBL." + templateItem.getId())) ); if (EvalConstants.ITEM_CATEGORY_INSTRUCTOR.equals(itemCategory) || EvalConstants.ITEM_CATEGORY_ENVIRONMENT.equals(itemCategory)) { // bind the current instructor id to the current EvalAnswer.associated form.parameters.add(new UIELBinding(currAnswerOTP + "associatedId", associatedId)); } // update curranswerOTP for binding the UI input element (UIInput, UISelect, etc.) if ( EvalConstants.ITEM_TYPE_SCALED.equals(templateItem.getItem().getClassification()) ) { caOTP = new String[] { currAnswerOTP + "numeric" }; } else if ( EvalConstants.ITEM_TYPE_TEXT.equals(templateItem.getItem().getClassification()) ) { caOTP = new String[] { currAnswerOTP + "text" }; } } // render the item itemRenderer.renderItem(radiobranch, "rendered-item:", caOTP, templateItem, displayNumber, false); // increment the item counters, if we displayed 1 item, increment by 1, // if we displayed a block, renderedItem has been incremented, increment displayNumber by the number of blockChildren, // this happens to coincide with the number of current answer OTP strings exactly -AZ if (caOTP != null) displayNumber += caOTP.length; renderedItemCount++; } /* (non-Javadoc) * @see uk.org.ponder.rsf.viewstate.ViewParamsReporter#getViewParameters() */ public ViewParameters getViewParameters() { return new EvalTakeViewParameters(); } /* * (non-Javadoc) * @see uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter#reportNavigationCases() */ @SuppressWarnings("unchecked") public List reportNavigationCases() { List i = new ArrayList(); i.add(new NavigationCase("success", new SimpleViewParameters(SummaryProducer.VIEW_ID))); return i; } public void interceptActionResult(ARIResult result, ViewParameters incoming, Object actionReturn) { EvalTakeViewParameters etvp = (EvalTakeViewParameters) incoming; if (etvp.evalCategory != null) { result.resultingView = new EvalCategoryViewParameters(ShowEvalCategoryProducer.VIEW_ID, etvp.evalCategory); } } }
package com.allforfunmc.easyoreapi; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; @Mod (modid="oreapi", name="AllForFun's EasyOreAPI", version="Dev") public class EasyOreApi { @Instance (value="GenericModID") public static EasyOreApi instance; @SidedProxy(clientSide="com.allforfunmc.easyoreapi.ClientProxy",serverSide="com.allforfunmc.easyoreapi.CommonProxy") public static CommonProxy proxy; @EventHandler() public void load(FMLInitializationEvent event) { proxy.registerRenderers(); } @EventHandler() public void Init(FMLInitializationEvent event) { } @EventHandler() public void postInit(FMLInitializationEvent event){ } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv.sam; import org.apache.log4j.Logger; import org.broad.igv.Globals; import org.broad.igv.data.CoverageDataSource; import org.broad.igv.feature.FeatureUtils; import org.broad.igv.feature.LocusScore; import org.broad.igv.feature.genome.Genome; import org.broad.igv.goby.GobyCountArchiveDataSource; import org.broad.igv.prefs.IGVPreferences; import org.broad.igv.prefs.PreferencesManager; import org.broad.igv.renderer.*; import org.broad.igv.tdf.TDFDataSource; import org.broad.igv.tdf.TDFReader; import org.broad.igv.track.*; import org.broad.igv.ui.DataRangeDialog; import org.broad.igv.ui.IGV; import org.broad.igv.ui.color.ColorUtilities; import org.broad.igv.ui.panel.FrameManager; import org.broad.igv.ui.panel.IGVPopupMenu; import org.broad.igv.ui.panel.ReferenceFrame; import org.broad.igv.ui.util.FileDialogUtils; import org.broad.igv.ui.util.MessageUtils; import org.broad.igv.ui.util.UIUtilities; import org.broad.igv.util.ResourceLocator; import org.broad.igv.util.StringUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static org.broad.igv.prefs.Constants.*; /** * @author jrobinso */ public class CoverageTrack extends AbstractTrack implements ScalableTrack { private static Logger log = Logger.getLogger(CoverageTrack.class); public static final int TEN_MB = 10000000; static DecimalFormat locationFormatter = new DecimalFormat(); char[] nucleotides = {'a', 'c', 'g', 't', 'n'}; public static Color lightBlue = new Color(0, 0, 150); private static Color coverageGrey = new Color(175, 175, 175); public static final Color negStrandColor = new Color(140, 140, 160); public static final Color posStrandColor = new Color(160, 140, 140); public static final boolean DEFAULT_AUTOSCALE = true; public static final boolean DEFAULT_SHOW_REFERENCE = false; private float snpThreshold; private AlignmentTrack alignmentTrack; private AlignmentDataManager dataManager; private CoverageDataSource dataSource; private DataRenderer dataSourceRenderer; private IntervalRenderer intervalRenderer; private IGVPreferences prefs; private JMenuItem dataRangeItem; private Genome genome; private boolean removed = false; /** * Whether to autoscale across all ReferenceFrames * Default is true because we usually do, SashimiPlot does not */ private boolean globalAutoScale = true; /** * Copy constructor. Used for Sashimi plot. * * @param track */ public CoverageTrack(CoverageTrack track) { this(track.getResourceLocator(), track.getName(), track.alignmentTrack, track.genome); if (track.dataManager != null) this.setDataManager(track.dataManager); if (track.dataSource != null) this.setDataSource(track.dataSource); this.snpThreshold = track.snpThreshold; this.prefs = track.prefs; } public CoverageTrack(ResourceLocator locator, String name, AlignmentTrack alignmentTrack, Genome genome) { super(locator, locator.getPath() + "_coverage", name); super.setDataRange(new DataRange(0, 0, 60)); this.alignmentTrack = alignmentTrack; this.genome = genome; intervalRenderer = new IntervalRenderer(); setMaximumHeight(40); setColor(coverageGrey); prefs = PreferencesManager.getPreferences(); snpThreshold = prefs.getAsFloat(SAM_ALLELE_THRESHOLD); autoScale = DEFAULT_AUTOSCALE; } public CoverageTrack() { } @Override public String getSample() { if (sampleId != null) { return sampleId; // Explicitly set sample ID (e.g. from server load XML) } return alignmentTrack.getSample(); } @Override public boolean isNumeric() { return true; } public void setDataManager(AlignmentDataManager dataManager) { this.dataManager = dataManager; this.dataManager.subscribe(this); } public void setDataSource(CoverageDataSource dataSource) { this.dataSource = dataSource; dataSourceRenderer = new BarChartRenderer(); setDataRange(new DataRange(0, 0, 1.5f * (float) dataSource.getDataMax())); } @Override public boolean isReadyToPaint(ReferenceFrame frame) { int viewWindowSize = frame.getCurrentRange().getLength(); if (frame.getChrName().equals(Globals.CHR_ALL) || viewWindowSize < dataManager.getVisibilityWindow()) { return true; // Nothing to paint } else { return dataManager.isLoaded(frame); } } @Override public void load(ReferenceFrame referenceFrame) { dataManager.load(referenceFrame, alignmentTrack.renderOptions, true); } public void setSnpThreshold(float snpThreshold) { this.snpThreshold = snpThreshold; } public float getSnpThreshold() { return snpThreshold; } public boolean isRemoved() { return removed; } @Override public void dispose() { super.dispose(); removed = true; if (dataManager != null) { dataManager.unsubscribe(this); } dataManager = null; dataSource = null; alignmentTrack = null; setVisible(false); } public void render(RenderContext context, Rectangle rect) { int viewWindowSize = context.getReferenceFrame().getCurrentRange().getLength(); if (viewWindowSize > dataManager.getVisibilityWindow() && dataSource == null) { Rectangle visibleRect = context.getVisibleRect().intersection(rect); Graphics2D g = context.getGraphic2DForColor(Color.gray); GraphicUtils.drawCenteredText("Zoom in to see coverage.", visibleRect, g); return; } drawData(context, rect); drawBorder(context, rect); if (dataSourceRenderer != null) { dataSourceRenderer.renderBorder(this, context, rect); dataSourceRenderer.renderAxis(this, context, rect); } else { DataRenderer.drawScale(this.getDataRange(), context, rect); } } public void drawData(RenderContext context, Rectangle rect) { int viewWindowSize = context.getReferenceFrame().getCurrentRange().getLength(); if (viewWindowSize < dataManager.getVisibilityWindow() && !context.getChr().equals(Globals.CHR_ALL)) { //Show coverage calculated from intervals if zoomed in enough AlignmentInterval interval = null; if (dataManager != null) { dataManager.load(context.getReferenceFrame(), alignmentTrack.renderOptions, true); interval = dataManager.getLoadedInterval(context.getReferenceFrame()); } if (interval != null) { if (interval.contains(context.getChr(), (int) context.getOrigin(), (int) context.getEndLocation())) { //if (autoScale) rescale(context.getReferenceFrame()); intervalRenderer.paint(context, rect, interval.getCounts()); return; } } } //Not rendered yet. Use precomputed scores, if available List<LocusScore> scores = getInViewScores(context.getReferenceFrame()); if (scores != null) { dataSourceRenderer.renderScores(this, scores, context, rect); } } private List<LocusScore> getInViewScores(ReferenceFrame frame) { List<LocusScore> inViewScores = null; if (dataSource != null) { String chr = frame.getChrName(); int start = (int) frame.getOrigin(); int end = (int) frame.getEnd(); int zoom = frame.getZoom(); inViewScores = dataSource.getSummaryScoresForRange(chr, start, end, zoom); // Trim // Trim scores int startIdx = Math.max(0, FeatureUtils.getIndexBefore(start, inViewScores)); int endIdx = inViewScores.size() - 1; // Starting guess int tmp = Math.max(0, FeatureUtils.getIndexBefore(end, inViewScores)); for (int i = tmp; i < inViewScores.size(); i++) { if (inViewScores.get(i).getStart() > end) { endIdx = i - 1; break; } } endIdx = Math.max(startIdx + 1, endIdx); if (inViewScores.size() > 1) { return startIdx == 0 && endIdx == inViewScores.size() - 1 ? inViewScores : inViewScores.subList(startIdx, endIdx); } else { return inViewScores; } } return inViewScores; } @Override public Range getInViewRange(ReferenceFrame frame) { int viewWindowSize = frame.getCurrentRange().getLength(); if (dataManager == null || viewWindowSize > dataManager.getVisibilityWindow()) { List<LocusScore> scores = getInViewScores(frame); if (scores != null && scores.size() > 0) { float min = scores.get(0).getScore(); float max = min; for (int i = 1; i < scores.size(); i++) { LocusScore score = scores.get(i); float value = score.getScore(); min = Math.min(value, min); max = Math.max(value, max); } return new Range(min, max); } else { return null; } } else { dataManager.load(frame, alignmentTrack.renderOptions, true); AlignmentInterval interval = dataManager.getLoadedInterval(frame); if (interval == null) return null; int origin = (int) frame.getOrigin(); int end = (int) frame.getEnd() + 1; int intervalMax = interval.getMaxCount(origin, end); return new Range(0, Math.max(10, intervalMax)); } } /** * Draw border and scale * * @param context * @param rect */ private void drawBorder(RenderContext context, Rectangle rect) { context.getGraphic2DForColor(Color.gray).drawLine( rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height); } public void drawScale(RenderContext context, Rectangle rect) { DataRenderer.drawScale(getDataRange(), context, rect); } public boolean isLogNormalized() { return false; } public String getValueStringAt(String chr, double position, int mouseX, int mouseY, ReferenceFrame frame) { float maxRange = PreferencesManager.getPreferences().getAsFloat(SAM_MAX_VISIBLE_RANGE); float minVisibleScale = (maxRange * 1000) / 700; StringBuffer buf = new StringBuffer(); if (!chr.equals("All")) { String posString = chr + ":" + locationFormatter.format(Math.floor(position + 1)); buf.append(posString + "<br>"); buf.append("<hr>"); } if (frame.getScale() < minVisibleScale) { AlignmentInterval interval = dataManager.getLoadedInterval(frame); if (interval != null && interval.contains(chr, (int) position, (int) position)) { AlignmentCounts counts = interval.getCounts(); if (counts != null) { buf.append(counts.getValueStringAt((int) position)); } } } else { buf.append(getPrecomputedValueString(chr, position, frame)); } return buf.toString(); } public AlignmentCounts getCounts(String chr, double position, ReferenceFrame frame) { AlignmentInterval interval = dataManager.getLoadedInterval(frame); if (interval != null && interval.contains(chr, (int) position, (int) position)) { return interval.getCounts(); } else { return null; } } private String getPrecomputedValueString(String chr, double position, ReferenceFrame frame) { if (dataSource == null) { return ""; } int zoom = Math.max(0, frame.getZoom()); List<LocusScore> scores = dataSource.getSummaryScoresForRange(chr, (int) position - 10, (int) position + 10, zoom); // give a 2 pixel window, otherwise very narrow features will be missed. double bpPerPixel = frame.getScale(); double minWidth = 2 * bpPerPixel; if (scores == null) { return ""; } else { LocusScore score = (LocusScore) FeatureUtils.getFeatureAt(position, 0, scores); return score == null ? "" : "Mean count: " + score.getScore(); } } public float getRegionScore(String chr, int start, int end, int zoom, RegionScoreType type, String frameName) { return 0; } public void rescale(ReferenceFrame iframe) { List<ReferenceFrame> frameList = new ArrayList<ReferenceFrame>(); if (iframe != null) frameList.add(iframe); if (globalAutoScale) { frameList.addAll(FrameManager.getFrames()); } if (autoScale && dataManager != null) { int max = 10; for (ReferenceFrame frame : frameList) { AlignmentInterval interval = dataManager.getLoadedInterval(frame); if (interval == null) continue; int origin = (int) frame.getOrigin(); int end = (int) frame.getEnd() + 1; int intervalMax = interval.getMaxCount(origin, end); max = intervalMax > max ? intervalMax : max; } DataRange newRange = new DataRange(0, max); newRange.setType(getDataRange().getType()); super.setDataRange(newRange); } } /** * Class to render coverage track, including mismatches. * <p/> * NOTE: This class has been extensively optimized with the aid of a profiler, attempts to "clean up" this code * should be done with frequent profiling, or it will likely have detrimental performance impacts. */ class IntervalRenderer { private void paint(RenderContext context, Rectangle rect, AlignmentCounts alignmentCounts) { Color color = getColor(); Graphics2D graphics = context.getGraphic2DForColor(color); DataRange range = getDataRange(); double maxRange = range.isLog() ? Math.log10(range.getMaximum() + 1) : range.getMaximum(); final double rectX = rect.getX(); final double rectMaxX = rect.getMaxX(); final double rectY = rect.getY(); final double rectMaxY = rect.getMaxY(); final double rectHeight = rect.getHeight(); final double origin = context.getOrigin(); final double colorScaleMax = getColorScale().getMaximum(); final double scale = context.getScale(); boolean bisulfiteMode = alignmentTrack.renderOptions.getColorOption() == AlignmentTrack.ColorOption.BISULFITE; // First pass, coverage int lastpX = -1; int start = alignmentCounts.getStart(); int step = alignmentCounts.getBucketSize(); int nPoints = alignmentCounts.getNumberOfPoints(); boolean isSparse = alignmentCounts instanceof SparseAlignmentCounts; for (int idx = 0; idx < nPoints; idx++) { int pos = isSparse ? ((SparseAlignmentCounts) alignmentCounts).getPosition(idx) : start + idx * step; int pX = (int) (rectX + (pos - origin) / scale); if (pX > rectMaxX) { break; // We're done, data is position sorted so we're beyond the right-side of the view } int dX = (int) (rectX + (pos + step - origin) / scale) - pX; dX = dX < 1 ? 1 : dX; // if (pX + dX > lastpX) { int pY = (int) rectMaxY - 1; int totalCount = alignmentCounts.getTotalCount(pos); double tmp = range.isLog() ? Math.log10(totalCount + 1) / maxRange : totalCount / maxRange; int height = (int) (tmp * rectHeight); height = Math.min(height, rect.height - 1); int topY = (pY - height); if (dX > 3) { dX--; // Create a little space between bars when there is room. } if (height > 0) { graphics.fillRect(pX, topY, dX, height); } lastpX = pX + dX; } // Second pass - mark mismatches if (alignmentCounts.hasBaseCounts()) { lastpX = -1; BisulfiteCounts bisulfiteCounts = alignmentCounts.getBisulfiteCounts(); final int intervalEnd = alignmentCounts.getEnd(); final int intervalStart = alignmentCounts.getStart(); byte[] refBases = null; // Dont try to compute mismatches for intervals > 10 MB if ((intervalEnd - intervalStart) < TEN_MB) { refBases = genome.getSequence(context.getChr(), intervalStart, intervalEnd); } start = alignmentCounts.getStart(); nPoints = alignmentCounts.getNumberOfPoints(); isSparse = alignmentCounts instanceof SparseAlignmentCounts; for (int idx = 0; idx < nPoints; idx++) { int pos = isSparse ? ((SparseAlignmentCounts) alignmentCounts).getPosition(idx) : start + idx; BisulfiteCounts.Count bc = null; if (bisulfiteMode && bisulfiteCounts != null) { bc = bisulfiteCounts.getCount(pos); } int pX = (int) (rectX + (pos - origin) / scale); if (pX > rectMaxX) { break; // We're done, data is position sorted so we're beyond the right-side of the view } int dX = (int) (rectX + (pos + 1 - origin) / scale) - pX; dX = dX < 1 ? 1 : dX; if (pX + dX > lastpX) { // Test to see if any single nucleotide mismatch (nucleotide other than the reference) // has a quality weight > 20% of the total boolean mismatch = false; if (refBases != null) { int refIdx = pos - intervalStart; if (refIdx >= 0 && refIdx < refBases.length) { if (bisulfiteMode) { mismatch = (bc != null && (bc.methylatedCount + bc.unmethylatedCount) > 0); } else { byte ref = refBases[refIdx]; mismatch = alignmentCounts.isConsensusMismatch(pos, ref, context.getChr(), snpThreshold); } } } if (!mismatch) { continue; } int pY = (int) rectMaxY - 1; int totalCount = alignmentCounts.getTotalCount(pos); double tmp = range.isLog() ? Math.log10(totalCount + 1) / maxRange : totalCount / maxRange; int height = (int) (tmp * rectHeight); height = Math.min(height, rect.height - 1); if (dX > 3) { dX--; // Create a little space between bars when there is room. } if (height > 0) { if (bisulfiteMode) { if (bc != null) { drawBarBisulfite(context, pos, rect, totalCount, maxRange, pY, pX, dX, bc, range.isLog()); } } else { drawBar(context, pos, rect, totalCount, maxRange, pY, pX, dX, alignmentCounts, range.isLog()); } } lastpX = pX + dX; } } } } } /** * Draw a colored bar to represent a mismatch to the reference. The height is proportional to the % of * reads with respect to the total. If "showAllSnps == true" the bar is shaded by avg read quality. * * @param context * @param pos * @param rect * @param max * @param pY * @param pX * @param dX * @param interval * @return */ int drawBar(RenderContext context, int pos, Rectangle rect, double totalCount, double max, int pY, int pX, int dX, AlignmentCounts interval, boolean isLog) { for (char nucleotide : nucleotides) { int count = interval.getCount(pos, (byte) nucleotide); Color c = SequenceRenderer.nucleotideColors.get(nucleotide); Graphics2D tGraphics = context.getGraphic2DForColor(c); double tmp = isLog ? (count / totalCount) * Math.log10(totalCount + 1) / max : count / max; int height = (int) (tmp * rect.getHeight()); height = Math.min(pY - rect.y, height); int baseY = pY - height; if (height > 0) { tGraphics.fillRect(pX, baseY, dX, height); } pY = baseY; } return pX + dX; } int drawBarBisulfite(RenderContext context, int pos, Rectangle rect, double totalCount, double maxRange, int pY, int pX0, int dX, BisulfiteCounts.Count count, boolean isLog) { // If bisulfite mode, we expand the rectangle to make it more visible. This code is copied from // AlignmentRenderer int pX = pX0; if (dX < 3) { int expansion = dX; pX -= expansion; dX += (2 * expansion); } double nMethylated = count.methylatedCount; double unMethylated = count.unmethylatedCount; Color c = Color.red; Graphics2D tGraphics = context.getGraphic2DForColor(c); //Not all reads at a position are informative, color by % of informative reads // double totalInformative = count.methylatedCount + count.unmethylatedCount; // double mult = totalCount / totalInformative; // nMethylated *= mult; // unMethylated *= mult; double tmp = isLog ? (nMethylated / totalCount) * Math.log10(totalCount + 1) / maxRange : nMethylated / maxRange; int height = (int) (tmp * rect.getHeight()); height = Math.min(pY - rect.y, height); int baseY = pY - height; if (height > 0) { tGraphics.fillRect(pX, baseY, dX, height); } pY = baseY; c = Color.blue; tGraphics = context.getGraphic2DForColor(c); tmp = isLog ? (unMethylated / totalCount) * Math.log10(totalCount + 1) / maxRange : unMethylated / maxRange; height = (int) (tmp * rect.getHeight()); height = Math.min(pY - rect.y, height); baseY = pY - height; if (height > 0) { tGraphics.fillRect(pX, baseY, dX, height); } return pX + dX; } /** * Strand-specific * * @param context * @param pos * @param rect * @param maxCount * @param pY * @param pX * @param dX * @param isPositive * @param interval * @return */ void drawStrandBar(RenderContext context, int pos, Rectangle rect, double maxCount, int pY, int pX, int dX, boolean isPositive, AlignmentCounts interval) { for (char nucleotide : nucleotides) { Color c = SequenceRenderer.nucleotideColors.get(nucleotide); Graphics2D tGraphics = context.getGraphic2DForColor(c); int count = isPositive ? interval.getPosCount(pos, (byte) nucleotide) : interval.getNegCount(pos, (byte) nucleotide); int height = (int) Math.round(count * rect.getHeight() / maxCount); height = isPositive ? Math.min(pY - rect.y, height) : Math.min(rect.y + rect.height - pY, height); int baseY = (int) (isPositive ? (pY - height) : pY); if (height > 0) { tGraphics.fillRect(pX, baseY, dX, height); } pY = isPositive ? baseY : baseY + height; } } static float[] colorComps = new float[3]; private Color getShadedColor(int qual, Color backgroundColor, Color color) { float alpha = 0; int minQ = prefs.getAsInt(SAM_BASE_QUALITY_MIN); ColorUtilities.getRGBColorComponents(color); if (qual < minQ) { alpha = 0.1f; } else { int maxQ = prefs.getAsInt(SAM_BASE_QUALITY_MAX); alpha = Math.max(0.1f, Math.min(1.0f, 0.1f + 0.9f * (qual - minQ) / (maxQ - minQ))); } // Round alpha to nearest 0.1, for effeciency; alpha = ((int) (alpha * 10 + 0.5f)) / 10.0f; if (alpha >= 1) { return color; } else { return ColorUtilities.getCompositeColor(backgroundColor, color, alpha); } } /** * Override to return a specialized popup menu * * @return */ @Override public IGVPopupMenu getPopupMenu(TrackClickEvent te) { Collection<Track> tmp = new ArrayList<Track>(); tmp.add(this); IGVPopupMenu popupMenu = TrackMenuUtils.getPopupMenu(tmp, getName(), te); popupMenu.addSeparator(); this.addSnpTresholdItem(popupMenu); popupMenu.addSeparator(); addLoadCoverageDataItem(popupMenu); popupMenu.addSeparator(); addCopyDetailsItem(popupMenu, te); popupMenu.addSeparator(); addShowItems(popupMenu); return popupMenu; } private void addCopyDetailsItem(IGVPopupMenu popupMenu, TrackClickEvent te) { JMenuItem copyDetails = new JMenuItem("Copy Details to Clipboard"); copyDetails.setEnabled(false); if (te.getFrame() != null) { final String details = getValueStringAt(te.getFrame().getChrName(), te.getChromosomePosition(), te.getMouseEvent().getX(), te.getMouseEvent().getY(), te.getFrame()); copyDetails.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (details != null) { String deets = details.replace("<br>", System.getProperty("line.separator")); StringUtils.copyTextToClipboard(deets); } } }); copyDetails.setEnabled(details != null); } popupMenu.add(copyDetails); } public static JMenuItem addDataRangeItem(final Frame parentFrame, JPopupMenu menu, final Collection<? extends Track> selectedTracks) { JMenuItem maxValItem = new JMenuItem("Set Data Range"); maxValItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (selectedTracks.size() > 0) { DataRange prevAxisDefinition = selectedTracks.iterator().next().getDataRange(); DataRangeDialog dlg = new DataRangeDialog(parentFrame, prevAxisDefinition); dlg.setHideMid(true); dlg.setVisible(true); if (!dlg.isCanceled()) { float min = Math.min(dlg.getMin(), dlg.getMax()); float max = Math.max(dlg.getMin(), dlg.getMax()); float mid = dlg.getBase(); if (mid < min) mid = min; else if (mid > max) mid = max; DataRange dataRange = new DataRange(min, mid, max); dataRange.setType(dlg.getDataRangeType()); for (Track track : selectedTracks) { track.setDataRange(dataRange); track.setAutoScale(false); } parentFrame.repaint(); } } } }); if (menu != null) menu.add(maxValItem); return maxValItem; } public JMenuItem addSnpTresholdItem(JPopupMenu menu) { JMenuItem maxValItem = new JMenuItem("Set allele frequency threshold..."); maxValItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String value = JOptionPane.showInputDialog("Allele frequency threshold: ", Float.valueOf(snpThreshold)); if (value == null) { return; } try { float tmp = Float.parseFloat(value); snpThreshold = tmp; IGV.getInstance().revalidateTrackPanels(); } catch (Exception exc) { //log } } }); menu.add(maxValItem); return maxValItem; } public void addShowItems(JPopupMenu menu) { if (alignmentTrack != null) { final JMenuItem alignmentItem = new JCheckBoxMenuItem("Show Alignment Track"); alignmentItem.setSelected(alignmentTrack.isVisible()); alignmentItem.setEnabled(!alignmentTrack.isRemoved()); alignmentItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { alignmentTrack.setVisible(alignmentItem.isSelected()); } }); menu.add(alignmentItem); final SpliceJunctionTrack spliceJunctionTrack = alignmentTrack.getSpliceJunctionTrack(); if (spliceJunctionTrack != null) { final JMenuItem junctionItem = new JCheckBoxMenuItem("Show Splice Junction Track"); junctionItem.setSelected(spliceJunctionTrack.isVisible()); junctionItem.setEnabled(!spliceJunctionTrack.isRemoved()); junctionItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { spliceJunctionTrack.setVisible(junctionItem.isSelected()); } }); menu.add(junctionItem); } final JMenuItem coverageItem = new JMenuItem("Hide Coverage Track"); coverageItem.setEnabled(!isRemoved()); coverageItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { UIUtilities.invokeOnEventThread(new Runnable() { public void run() { setVisible(false); if (IGV.hasInstance()) IGV.getInstance().getMainPanel().revalidate(); } }); } }); menu.add(coverageItem); } } public void addLoadCoverageDataItem(JPopupMenu menu) { // Change track height by attribute final JMenuItem item = new JCheckBoxMenuItem("Load pre-computed coverage data..."); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { final IGVPreferences prefs = PreferencesManager.getPreferences(); File initDirectory = prefs.getLastTrackDirectory(); File file = FileDialogUtils.chooseFile("Select coverage file", initDirectory, FileDialog.LOAD); if (file != null) { prefs.setLastTrackDirectory(file.getParentFile()); String path = file.getAbsolutePath(); if (path.endsWith(".tdf") || path.endsWith(".tdf")) { TDFReader reader = TDFReader.getReader(file.getAbsolutePath()); TDFDataSource ds = new TDFDataSource(reader, 0, getName() + " coverage", genome); setDataSource(ds); IGV.getInstance().revalidateTrackPanels(); } else if (path.endsWith(".counts")) { CoverageDataSource ds = new GobyCountArchiveDataSource(file); setDataSource(ds); IGV.getInstance().revalidateTrackPanels(); } else { MessageUtils.showMessage("Coverage data must be in .tdf format"); } } } }); item.setEnabled(dataSource == null); menu.add(item); } public void setGlobalAutoScale(boolean globalAutoScale) { this.globalAutoScale = globalAutoScale; } @Override public void marshalXML(Document document, Element element) { super.marshalXML(document, element); element.setAttribute("snpThreshold", String.valueOf(snpThreshold)); } @Override public void unmarshalXML(Element element, Integer version) { super.unmarshalXML(element, version); if (element.hasAttribute("snpThreshold")) { snpThreshold = Float.parseFloat(element.getAttribute("snpThreshold")); } } }
package com.google.copybara; import com.google.common.collect.ImmutableList; import com.google.common.truth.Truth; import com.google.copybara.config.Config; import com.google.copybara.git.GitOptions; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nullable; @RunWith(JUnit4.class) public class CopybaraTest { private final static class RecordsProcessCallDestination implements Destination.Yaml { List<Long> processTimestamps = new ArrayList<>(); @Override public Destination withOptions(Options options) { return new Destination() { @Override public void process(Path workdir, String originRef, long timestamp, String changesSummary) { processTimestamps.add(timestamp); } @Nullable @Override public String getPreviousRef() { return null; } }; } } private class DummyReference implements Origin.Reference<DummyOrigin> { String reference; @Override public Long readTimestamp() { return referenceToTimestamp.get(reference); } @Override public void checkout(Path workdir) throws RepoException { try { Files.createDirectories(workdir); Files.write(workdir.resolve("file.txt"), reference.getBytes()); } catch (IOException e) { throw new RepoException("Unexpected error", e); } } @Override public String asString() { return reference; } } private class DummyOrigin implements Origin<DummyOrigin> { @Override public Reference<DummyOrigin> resolve(@Nullable final String reference) { DummyReference wrappedReference = new DummyReference(); wrappedReference.reference = reference; return wrappedReference; } @Override public ImmutableList<Change<DummyOrigin>> changes(Reference<DummyOrigin> oldRef, @Nullable Reference<DummyOrigin> newRef) throws RepoException { throw new CannotComputeChangesException("not supported"); } } private Map<String, Long> referenceToTimestamp; private RecordsProcessCallDestination destination; private Config.Yaml yaml; private Path workdir; @Before public void setup() throws Exception { referenceToTimestamp = new HashMap<>(); destination = new RecordsProcessCallDestination(); yaml = new Config.Yaml(); yaml.setName("name"); yaml.setOrigin(new Origin.Yaml<DummyOrigin>() { @Override public DummyOrigin withOptions(Options options) { return new DummyOrigin(); } }); yaml.setDestination(destination); workdir = Files.createTempDirectory("workdir"); } private Options options() { return new Options( ImmutableList.of(new GitOptions(), new GeneralOptions(workdir, /*verbose=*/true))); } @Test public void processIsCalledWithCurrentTimeIfTimestampNotInOrigin() throws Exception { long beginTime = System.currentTimeMillis() / 1000; new Copybara(workdir).runForSourceRef(yaml.withOptions(options()), "some_sha1"); long timestamp = destination.processTimestamps.get(0); Truth.assertThat(timestamp).isAtLeast(beginTime); Truth.assertThat(timestamp).isAtMost(System.currentTimeMillis() / 1000); } @Test public void processIsCalledWithCorrectWorkdir() throws Exception { new Copybara(workdir).runForSourceRef(yaml.withOptions(options()), "some_sha1"); Truth.assertThat(Files.readAllLines(workdir.resolve("file.txt"), StandardCharsets.UTF_8)) .contains("some_sha1"); } @Test public void sendsOriginTimestampToDest() throws Exception { referenceToTimestamp.put("refname", (long) 42918273); new Copybara(workdir).runForSourceRef(yaml.withOptions(options()), "refname"); Truth.assertThat(destination.processTimestamps.get(0)) .isEqualTo(42918273); } }
package org.cobbzilla.util.daemon; import lombok.extern.slf4j.Slf4j; import org.cobbzilla.util.time.ClockProvider; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import static org.cobbzilla.util.daemon.ZillaRuntime.*; import static org.cobbzilla.util.system.Sleep.sleep; @Slf4j public class Await { public static final long DEFAULT_AWAIT_GET_SLEEP = 10; public static final long DEFAULT_AWAIT_RETRY_SLEEP = 100; public static final long DEFAULT_AWAIT_ALL_SLEEP = 200; public static <E> E awaitFirst(Collection<Future<E>> futures, long timeout) throws TimeoutException { return awaitFirst(futures, timeout, DEFAULT_AWAIT_RETRY_SLEEP); } public static <E> E awaitFirst(Collection<Future<E>> futures, long timeout, long retrySleep) throws TimeoutException { return awaitFirst(futures, timeout, retrySleep, DEFAULT_AWAIT_GET_SLEEP); } public static <E> E awaitFirst(Collection<Future<E>> futures, long timeout, long retrySleep, long getSleep) throws TimeoutException { long start = now(); while (!futures.isEmpty() && now() - start < timeout) { for (Iterator<Future<E>> iter = futures.iterator(); iter.hasNext(); ) { Future<E> future = iter.next(); try { final E value = future.get(getSleep, TimeUnit.MILLISECONDS); if (value != null) return value; iter.remove(); if (futures.isEmpty()) break; } catch (InterruptedException e) { die("await: interrupted: " + e); } catch (ExecutionException e) { die("await: execution error: " + e); } catch (TimeoutException e) { // noop } sleep(retrySleep); } } if (now() - start > timeout) throw new TimeoutException("await: timed out"); return null; // all futures had a null result } public static List awaitAndCollect(Collection<Future<List>> futures, int maxResults, long timeout) throws TimeoutException { return awaitAndCollect(futures, maxResults, timeout, DEFAULT_AWAIT_RETRY_SLEEP); } public static List awaitAndCollect(Collection<Future<List>> futures, int maxResults, long timeout, long retrySleep) throws TimeoutException { return awaitAndCollect(futures, maxResults, timeout, retrySleep, DEFAULT_AWAIT_GET_SLEEP); } public static List awaitAndCollect(Collection<Future<List>> futures, int maxResults, long timeout, long retrySleep, long getSleep) throws TimeoutException { return awaitAndCollect(futures, maxResults, timeout, retrySleep, getSleep, new ArrayList()); } public static List awaitAndCollect(List<Future<List>> futures, int maxQueryResults, long timeout, List results) throws TimeoutException { return awaitAndCollect(futures, maxQueryResults, timeout, DEFAULT_AWAIT_RETRY_SLEEP, DEFAULT_AWAIT_GET_SLEEP, results); } public static List awaitAndCollect(Collection<Future<List>> futures, int maxResults, long timeout, long retrySleep, long getSleep, List results) throws TimeoutException { long start = now(); int size = futures.size(); while (!futures.isEmpty() && now() - start < timeout) { for (Iterator<Future<List>> iter = futures.iterator(); iter.hasNext(); ) { Future future = iter.next(); try { results.addAll((List) future.get(getSleep, TimeUnit.MILLISECONDS)); iter.remove(); if (--size <= 0 || results.size() >= maxResults) return results; break; } catch (InterruptedException e) { die("await: interrupted: " + e); } catch (ExecutionException e) { die("await: execution error: " + e); } catch (TimeoutException e) { // noop } sleep(retrySleep); } } if (now() - start > timeout) throw new TimeoutException("await: timed out"); return results; } public static Set awaitAndCollectSet(Collection<Future<List>> futures, int maxResults, long timeout) throws TimeoutException { return awaitAndCollectSet(futures, maxResults, timeout, DEFAULT_AWAIT_RETRY_SLEEP); } public static Set awaitAndCollectSet(Collection<Future<List>> futures, int maxResults, long timeout, long retrySleep) throws TimeoutException { return awaitAndCollectSet(futures, maxResults, timeout, retrySleep, DEFAULT_AWAIT_GET_SLEEP); } public static Set awaitAndCollectSet(Collection<Future<List>> futures, int maxResults, long timeout, long retrySleep, long getSleep) throws TimeoutException { return awaitAndCollectSet(futures, maxResults, timeout, retrySleep, getSleep, new HashSet()); } public static Set awaitAndCollectSet(List<Future<List>> futures, int maxQueryResults, long timeout, Set results) throws TimeoutException { return awaitAndCollectSet(futures, maxQueryResults, timeout, DEFAULT_AWAIT_RETRY_SLEEP, DEFAULT_AWAIT_GET_SLEEP, results); } public static Set awaitAndCollectSet(Collection<Future<List>> futures, int maxResults, long timeout, long retrySleep, long getSleep, Set results) throws TimeoutException { long start = now(); int size = futures.size(); while (!futures.isEmpty() && now() - start < timeout) { for (Iterator<Future<List>> iter = futures.iterator(); iter.hasNext(); ) { Future future = iter.next(); try { results.addAll((Collection) future.get(getSleep, TimeUnit.MILLISECONDS)); iter.remove(); if (--size <= 0 || results.size() >= maxResults) return results; break; } catch (InterruptedException e) { die("await: interrupted: " + e); } catch (ExecutionException e) { die("await: execution error: " + e); } catch (TimeoutException e) { // noop } sleep(retrySleep); } } if (now() - start > timeout) throw new TimeoutException("await: timed out"); return results; } public static <T> AwaitResult<T> awaitAll(Collection<Future<?>> futures, long timeout) { return awaitAll(futures, timeout, ClockProvider.SYSTEM, DEFAULT_AWAIT_ALL_SLEEP, null); } public static <T> AwaitResult<T> awaitAll(Collection<Future<?>> futures, long timeout, ClockProvider clock) { return awaitAll(futures, timeout, clock, DEFAULT_AWAIT_ALL_SLEEP, null); } public static <T> AwaitResult<T> awaitAll(Collection<Future<?>> futures, long timeout, Runnable sleepCallback) { return awaitAll(futures, timeout, ClockProvider.SYSTEM, DEFAULT_AWAIT_ALL_SLEEP, sleepCallback); } public static <T> AwaitResult<T> awaitAll(Collection<Future<?>> futures, long timeout, long sleepTime, Runnable sleepCallback) { return awaitAll(futures, timeout, ClockProvider.SYSTEM, sleepTime, sleepCallback); } public static <T> AwaitResult<T> awaitAll(Collection<Future<?>> futures, long timeout, ClockProvider clock, Runnable sleepCallback) { return awaitAll(futures, timeout, clock, DEFAULT_AWAIT_ALL_SLEEP, sleepCallback); } public static <T> AwaitResult<T> awaitAll(Collection<Future<?>> futures, long timeout, ClockProvider clock, long sleepTime, Runnable sleepCallback) { long start = clock.now(); final AwaitResult<T> result = new AwaitResult<>(); final Collection<Future<?>> awaiting = new ArrayList<>(futures); while (true) { for (Iterator iter = awaiting.iterator(); iter.hasNext(); ) { final Future f = (Future) iter.next(); if (f.isDone()) { iter.remove(); try { final T r = (T) f.get(); if (r != null) log.info("awaitAll: "+ r); result.success(f, r); } catch (Exception e) { log.warn("awaitAll: "+e, e); result.fail(f, e); } } } if (awaiting.isEmpty()) break; if (sleepCallback != null) { try { sleepCallback.run(); } catch (Exception e) { log.warn("awaitAll: exception in sleepCallback: "+shortError(e)); } } if (clock.now() - start > timeout) break; if (sleepTime > 0) sleep(sleepTime, "awaitAll: awaiting tasks: "+awaiting.size()+"/"+futures.size()); } result.timeout(awaiting); return result; } }